/** * Auth/Login route for logging a user in. * * @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 login(ServerRequestInterface $request, ResponseInterface $response) { $data = $request->getParsedBody(); //Check to make sure user sends username and password if (isset($data['username'], $data['password'])) { //Authenticate that username and password are correct $user = User::auth($data['username'], $data['password']); //Check if username exits if ((bool) $user) { //Ensures user is not logged out from other device $user->jit = $user->jit == null ? rand(1000, 999999999) : $user->jit; //Generate token $token = $this->buildToken($user->jit, $user->id, $user->username); $user->save(); $message = ['token' => $token]; } else { //Message when username or password is incorrect $response = $response->withStatus(401); $message = ['message' => 'username or password incorrect']; } } else { $response = $response->withStatus(400); $message = ['message' => 'Username or password not set']; } $response->getBody()->write(json_encode($message)); return $response; }