Ejemplo n.º 1
0
 /**
  * This function authenticates users before they can be granted access to protected endpoints.
  * @param  Slim   $app
  */
 public static function authenticate(Slim $app)
 {
     $app->response->headers->set('Content-Type', 'application/json');
     $token = $app->request->headers->get('Authorization');
     if (is_null($token)) {
         OutputFormatter::formatOutput($app, 401, "You're not authorized to perform this action. Please login.");
     }
     try {
         Configuration::load();
         $secretKey = getenv('JWT_KEY');
         $jwt = JWT::decode($token, $secretKey, ['HS256']);
         return json_encode($jwt->data);
     } catch (ExpiredException $e) {
         OutputFormatter::formatOutput($app, 400, "Your token has expired. Please login again.");
     } catch (Exception $e) {
         OutputFormatter::formatOutput($app, 400, 'Exception: ' . $e->getMessage());
     }
 }
 /**
  *  This function logs in users by checking their login credentials against the database
  *  and generates a json web token (JWT) for valid users
  *  @param  Slim   $app [description]
  */
 public static function login(Slim $app)
 {
     $app->response->headers->set('Content-Type', 'application/json');
     $username = $app->request->params('username');
     $password = $app->request->params('password');
     $conn = User::getConnection();
     $sql = "SELECT * FROM users WHERE username='******'";
     $stmt = $conn->query($sql);
     $result = $stmt->fetch(PDO::FETCH_ASSOC);
     if (password_verify($password, $result['password'])) {
         $token = ['iat' => time(), 'exp' => time() + 3600, 'data' => ['userID' => $result['user_id'], 'username' => $username]];
         Configuration::load();
         $secretKey = getenv('JWT_KEY');
         $jwt = JWT::encode($token, $secretKey);
         $responseMessage = ['Status' => '200', 'Message' => 'Login successful', 'Token' => $jwt];
         return json_encode($responseMessage);
     } else {
         OutputFormatter::formatOutput($app, 401, 'Login failed. Username or password is invalid.');
     }
 }