LoginController.class.php 1.72 KB
Newer Older
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
<?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->jsonContent();

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

      $user = User::tryLogin($json->login);
26 27 28 29 30
      // print_r($user);
      // exit;
      if(empty($user) || !hash_equals($json->pwd,$user->USER_PASSWORD)) {
         $r = new Response(422,"wrong credentials");
         $r->send();
31 32 33 34 35 36 37 38 39 40 41
      }

      // 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(
42 43 44 45
            "id" => $user->USER_ID,
            "firstname" => $user->USER_FIRSTNAME,
            "lastname" => $user->USER_LASTNAME,
            "email" => $user->USER_EMAIL
46 47 48 49 50 51 52 53 54 55 56 57 58
         )
      );

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

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