LoginController.class.php 1.67 KB
Newer Older
quentin.vrel's avatar
quentin.vrel committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
<?php
include_once __ROOT_DIR . '/libs/php-jwt/src/BeforeValidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/ExpiredException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/SignatureInvalidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/JWT.php';
use \Firebase\JWT\JWT;

class LoginController extends Controller {

   public function __construct($name, $request) {
      parent::__construct($name, $request);
   }

    public function processRequest() {
      if($this->request->getHttpMethod() !== 'POST')
         return Response::errorResponse('{ "message" : "Unsupported endpoint" }' );

      $json = $this->request->getData();
      if(!isset($json['login']) || !isset($json['login'])) {
         $r = new Response(422,"login and pwd fields are mandatory");
            $r->send();
      }

      $user = User::tryLogin($json['login']);
      if(empty($user) || !hash_equals($json['pwd'],$user->password())) {
            $r = new Response(422,"wrong credentials");
            $r->send();
      }

      // generate json web token
      $issued_at = time();
      $expiration_time = $issued_at + (60 * 60); // valid for 1 hour

      $token = array(
         "iat" => $issued_at,
         "exp" => $expiration_time,
         "iss" => JWT_ISSUER,
         "data" => array(
            "id" => $user->id(),
            "firstname" => $user->firstname(),
            "lastname" => $user->lastname(),
            "email" => $user->email()
         )
      );

      $jwt = JWT::encode( $token, JWT_BACKEND_KEY );
      $jsonResult = json_encode(
            array(
               "jwt_token" => $jwt
            )
      );

        return Response::okResponse($jsonResult);
    }
}