/** * Authenticates that the user is allowed to make call to the route. * * @param ServerRequestInterface ServerRequestInterface $request PSR-7 standard for receiving client request * @param ResponseInterface ResponseInterface $response PSR-& standard for sending server response * @param function $next callback function for calling next method * * @return ResponseInterface HTTP response of client request */ public function authorize(ServerRequestInterface $request, $response, $next) { if (empty($request->getHeader('Authorization'))) { $response = $response->withStatus(400); $response->getBody()->write(json_encode(['message' => 'Token not found'])); return $response; } //Get token for accessing this route $token = $request->getHeader('Authorization')[0]; try { //Decode token to get object of data $decodedToken = Auth::decodeToken($token); //Extract the user id from decoded token $uid = $decodedToken->data->uid; $user = User::find($uid); //Check if user exist with the user id if ($user != null) { if ($user->isTokenValid($decodedToken)) { $response = $next($request, $response); } } else { $response = $response->withStatus(401); $response->getBody()->write(json_encode(['message' => 'User does not exist'])); } } catch (TokenExpirationException $ex) { $response = $response->withStatus(401); $response->getBody()->write(json_encode(['message' => $ex->getMessage()])); } catch (\Exception $ex) { $response = $response->withStatus(400); $response->getBody()->write(json_encode(['message' => $ex->getMessage()])); } return $response; }
/** * Index route for getting all Emojis. * * @param ServerRequestInterface ServerRequestInterface $request PSR-7 standard for receiving client request * @param ResponseInterface ResponseInterface $response PSR-& standard for sending server response * * @return ResponseInterface HTTP response of client request */ public function create(ServerRequestInterface $request, ResponseInterface $response) { //Get Emoji data from request $data = $request->getParsedBody(); //Extract keywords from data $keywords = $data['keywords']; //Decode token to get object of data $decodedToken = Auth::decodeToken($request->getHeader('Authorization')[0], $request); //Check if user exist with the user id $user = User::find($decodedToken->data->uid); //Generate emoji data to return $emoji = ['name' => $data['name'], 'char' => $data['char'], 'category' => $data['category']]; DB::transaction(function () use($user, $emoji, $keywords) { //Insert Emoji data into emojis table $emoji = $user->emojis()->create($emoji); $keywordsObj = []; //create emoji keyword objects foreach ($keywords as $keyword) { $obj = new EmojiKeyword(); $obj->name = $keyword; $keywordsObj[] = $obj; } //Save all keywords objects $emoji->keywords()->saveMany($keywordsObj); }); $response->getBody()->write(json_encode(['message' => 'Emoji created'])); return $response; }