/**
  * Assigns a new authentication token
  *
  * This route will assign the user a new
  * authentication token, if they provide
  * valid credentials.
  *
  * this token can be used on further
  * requests to authenticate the user.
  *
  **/
 public function login($app)
 {
     $username = $app->request->post('username');
     $password = $app->request->post('password');
     if ($username === null || $password === null) {
         $app->response->setStatus(403);
         $app->response->write('username and password required');
         return $app->response->finalize();
     }
     $users = UserModel::findWhere(['username' => $username]);
     if (count($users) == 0) {
         $app->response->setStatus(401);
         $app->response->write('invalid credentials');
         return $app->response->finalize();
     }
     $user = $users[0];
     if ($user->checkPassword($password)) {
         $previous_token = $app->getCookie(self::TOKEN_COOKIE);
         if ($previous_token != null) {
             TokenModel::invalidate($previous_token);
         }
         $key = TokenModel::makeKey();
         $token = TokenModel::generate($user, $key);
         $token->save();
         $app->setCookie(self::TOKEN_COOKIE, $key);
         $app->response->write("logged in");
         return $app->response->finalize();
     } else {
         $app->response->setStatus(403);
         $app->response->write('invalid credentials');
         return $app->response->finalize();
     }
 }
 /**
  * a token can be found by it's key
  **/
 public function testFindToken()
 {
     $user = new UserModel();
     $user->username = '******';
     $user->password = '******';
     $user->save();
     $key = TokenModel::makeKey();
     $token = TokenModel::generate($user, $key);
     $token->save();
     $token2 = TokenModel::findToken($key);
     $this->assertNotNull($token2);
 }
 /**
  * authorize users with a valid token
  *
  * users without a valid token are
  * forbidden(code: 401) from proceeding.
  **/
 public function handle(\Slim\Slim $app)
 {
     $token_cookie = $app->getCookie(AuthController::TOKEN_COOKIE);
     if (empty($token_cookie)) {
         $app->response->setStatus(401);
         $app->response->finalize();
         return $app->response->finalize();
     }
     $token = TokenModel::findToken($token_cookie);
     if ($token == null) {
         $app->response->setStatus(401);
         $app->response->finalize();
         return $app->response->finalize();
     }
 }