Example #1
0
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  */
 protected function setUp()
 {
     $this->object = new JWT();
     //NOTE, in order testAuthenticateSuccess to work all users must
     //have this password
     self::$users = [['id' => 1, 'email' => '*****@*****.**', 'password' => password_hash('123456', PASSWORD_BCRYPT), 'user_type' => 'user'], ['id' => 2, 'email' => '*****@*****.**', 'password' => password_hash('123456', PASSWORD_BCRYPT), 'user_type' => 'moderator']];
     $settings = ['jwt' => ['secret' => 'aabsLgq31/K+zXcyAqpdaabszyaabsoatAmnuwaH0Pgx4lzqjHtBmQ==', 'algorithm' => 'HS256', 'server' => 'test']];
     //Initliaze Phramework, to set settings
     $phramework = new Phramework($settings, new \Phramework\URIStrategy\URITemplate([]));
     //Set authentication class
     \Phramework\Authentication\Manager::register(JWT::class);
     //Set method to fetch user object, including password attribute
     \Phramework\Authentication\Manager::setUserGetByEmailMethod([JWTTest::class, 'getByEmailWithPassword']);
     \Phramework\Authentication\Manager::setAttributes(['user_type', 'email']);
     \Phramework\Authentication\Manager::setOnCheckCallback(function ($params) {
         //var_dump($params);
     });
     \Phramework\Authentication\Manager::setOnAuthenticateCallback(function ($params) {
         //var_dump($params);
     });
 }
Example #2
0
 /**
  * Authenticate a user using JWT authentication method
  * @param  array  $params  Request parameters
  * @param  string $method  Request method
  * @param  array  $headers  Request headers
  * @return false|array  Returns false on failure
  */
 public function authenticate($params, $method, $headers)
 {
     //Require email and password set in params
     $validationModel = new \Phramework\Validate\ObjectValidator(['email' => new \Phramework\Validate\EmailValidator(3, 100), 'password' => new \Phramework\Validate\StringValidator(3, 128, null, true)], ['email', 'password']);
     $parsed = $validationModel->parse($params);
     $email = $parsed->email;
     $password = $parsed->password;
     //Get user object
     $user = call_user_func(Manager::getUserGetByEmailMethod(), $email);
     if (!$user) {
         return false;
     }
     // Verify user's password (password is stored as hash)
     if (!password_verify($password, $user['password'])) {
         return false;
     }
     $secret = Phramework::getSetting('jwt', 'secret');
     $algorithm = Phramework::getSetting('jwt', 'algorithm');
     $serverName = Phramework::getSetting('jwt', 'server');
     $tokenId = base64_encode(\mcrypt_create_iv(32));
     $issuedAt = time();
     $notBefore = $issuedAt + Phramework::getSetting('jwt', 'nbf', 0);
     $expire = $notBefore + Phramework::getSetting('jwt', 'exp', 3600);
     /*
      * Create the token as an array
      */
     $data = ['iat' => $issuedAt, 'jti' => $tokenId, 'iss' => $serverName, 'nbf' => $notBefore, 'exp' => $expire, 'data' => ['id' => $user['id']]];
     //copy user attributes to jwt's data
     foreach (Manager::getAttributes() as $attribute) {
         if (!isset($user[$attribute])) {
             throw new \Phramework\Exceptions\ServerException(sprintf('Attribute "%s" is not set in user object', $attribute));
         }
         $data['data'][$attribute] = $user[$attribute];
     }
     $jwt = \Firebase\JWT\JWT::encode($data, $secret, $algorithm);
     //Call onAuthenticate callback if set
     if (($callback = Manager::getOnAuthenticateCallback()) !== null) {
         call_user_func($callback, (object) $data['data'], $jwt);
     }
     return [(object) $data['data'], $jwt];
 }
 /**
  * Authenticate a user using JWT authentication method
  * @param  array  $params  Request parameters
  * @param  string $method  Request method
  * @param  array  $headers  Request headers
  * @return false|array  Returns false on failure
  */
 public function authenticate($params, $method, $headers)
 {
     $email = \Phramework\Validate\EmailValidator::parseStatic($params['email']);
     $password = $params['password'];
     $user = call_user_func(Manager::getUserGetByEmailMethod(), $email);
     if (!$user) {
         return false;
     }
     if (!password_verify($password, $user['password'])) {
         return false;
     }
     /*
      * Create the token as an array
      */
     $data = ['id' => $user['id']];
     //copy user attributes to jwt's data
     foreach (Manager::getAttributes() as $attribute) {
         if (!isset($user[$attribute])) {
             throw new \Phramework\Exceptions\ServerException(sprintf('Attribute "%s" is not set in user object', $attribute));
         }
         $data[$attribute] = $user[$attribute];
     }
     //Convert to object
     $data = (object) $data;
     //Call onAuthenticate callback if set
     if (($callback = Manager::getOnAuthenticateCallback()) !== null) {
         call_user_func($callback, $data);
     }
     return [$data];
 }
 /**
  * @covers Phramework\Authentication\BasicAuthentication\BasicAuthentication::check
  */
 public function testCheckSuccess()
 {
     $index = 0;
     $user = \Phramework\Authentication\Manager::check([], Phramework::METHOD_GET, ['Authorization' => 'Basic ' . base64_encode(self::$users[$index]['email'] . ':' . '123456')]);
     $this->assertInternalType('object', $user, 'Expect an object');
     $this->assertObjectHasAttribute('id', $user);
     $this->assertObjectHasAttribute('email', $user);
     $this->assertObjectHasAttribute('user_type', $user);
     $this->assertObjectNotHasAttribute('password', $user);
     $this->assertSame(self::$users[$index]['id'], $user->id);
     $this->assertSame(self::$users[$index]['email'], $user->email);
     $this->assertSame(self::$users[$index]['user_type'], $user->user_type);
 }
Example #5
0
 /**
  * Execute the API
  * @throws \Phramework\Exceptions\PermissionException
  * @throws \Phramework\Exceptions\NotFoundException
  * @throws \Phramework\Exceptions\IncorrectParametersException
  * @throws \Phramework\Exceptions\RequestException
  * @todo change default timezone
  * @todo change default language
  * @todo initialize database if set
  * @todo @security deny access to any else referals
  */
 public function invoke()
 {
     $params = new \stdClass();
     $method = self::METHOD_GET;
     $headers = [];
     try {
         date_default_timezone_set('Europe/Athens');
         if (self::getSetting('debug')) {
             error_reporting(E_ALL);
             ini_set('display_errors', '1');
         }
         if (self::getSetting('errorlog_path')) {
             ini_set('error_log', self::getSetting('errorlog_path'));
         }
         //Check if callback is set (JSONP)
         if (isset($_GET['callback'])) {
             if (!\Phramework\Validate\Validate::isValidJsonpCallback($_GET['callback'])) {
                 throw new \Phramework\Exceptions\IncorrectParametersException(['callback']);
             }
             self::$callback = $_GET['callback'];
             unset($_GET['callback']);
         }
         /*
         //Initialize Database connection if required or db set
         if (self::getSetting('require_db') || self::getSetting('db')) {
             \Phramework\Models\Database::requireDatabase(self::getSetting('db'));
         }
         
         //Unset from memory Database connection information
         unset(self::$settings['db']);
         */
         //Get method from the request (HTTP) method
         $method = self::$method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : self::METHOD_GET;
         //Check if the requested HTTP method method is allowed
         // @todo check error code
         if (!in_array($method, self::$methodWhitelist)) {
             throw new \Phramework\Exceptions\RequestException('Method not allowed');
         }
         //Default value of response's header origin
         $origin = '*';
         //Get request headers
         $headers = Models\Request::headers();
         //Check origin header
         if (isset($headers['Origin'])) {
             $originHost = parse_url($headers['Origin'], PHP_URL_HOST);
             //Check if origin host is allowed
             if ($originHost && self::getSetting('allowed_referer') && in_array($originHost, self::getSetting('allowed_referer'))) {
                 $origin = $headers['Origin'];
             }
             //@TODO @security else deny access
         } elseif (isset($_SERVER['HTTP_HOST']) && isset($_SERVER['REQUEST_URI'])) {
             $origin = '*';
             //TODO Exctract origin from request url
         }
         //Send access control headers
         if (!headers_sent()) {
             header('Access-Control-Allow-Credentials: true');
             header('Access-Control-Allow-Origin: ' . $origin);
             header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, HEAD, DELETE, OPTIONS');
             header('Access-Control-Allow-Headers: ' . 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Content-Encoding');
         }
         //Catch OPTIONS request and kill it
         if ($method == self::METHOD_OPTIONS) {
             header('HTTP/1.1 200 OK');
             exit;
         }
         //Merge all REQUEST parameters into $params array
         $params = (object) array_merge($_GET, $_POST, $_FILES);
         //TODO $_FILES only if POST OR PUT
         //Parse request body
         //@Todo add allowed content-types
         if (in_array($method, [self::METHOD_POST, self::METHOD_PATCH, self::METHOD_PUT, self::METHOD_DELETE])) {
             $CONTENT_TYPE = null;
             if (isset($headers[Request::HEADER_CONTENT_TYPE])) {
                 $CONTENT_TYPE = explode(';', $headers[Request::HEADER_CONTENT_TYPE]);
                 $CONTENT_TYPE = $CONTENT_TYPE[0];
             }
             if ($CONTENT_TYPE === 'application/x-www-form-urlencoded') {
                 //Decode and merge params
                 parse_str(file_get_contents('php://input'), $input);
                 if ($input && !empty($input)) {
                     $params = (object) array_merge((array) $params, (array) $input);
                 }
             } elseif (in_array($CONTENT_TYPE, ['application/json', 'application/vnd.api+json'], true)) {
                 $input = trim(file_get_contents('php://input'));
                 if (!empty($input)) {
                     //note if input length is >0 and decode returns null then its bad data
                     //json_last_error()
                     $inputObject = json_decode($input);
                     if (json_last_error() !== JSON_ERROR_NONE) {
                         throw new \Phramework\Exceptions\RequestException('JSON parse error: ' . json_last_error_msg());
                     }
                     if ($inputObject && !empty($inputObject)) {
                         $params = (object) array_merge((array) $params, (array) $inputObject);
                     }
                 }
             }
         }
         //STEP_AFTER_AUTHENTICATION_CHECK
         self::$stepCallback->call(StepCallback::STEP_BEFORE_AUTHENTICATION_CHECK, $params, $method, $headers);
         //Authenticate request (check authentication)
         self::$user = \Phramework\Authentication\Manager::check($params, $method, $headers);
         //In case of array returned force type to be object
         if (is_array(self::$user)) {
             self::$user = (object) self::$user;
         }
         //STEP_AFTER_AUTHENTICATION_CHECK
         self::$stepCallback->call(StepCallback::STEP_AFTER_AUTHENTICATION_CHECK, $params, $method, $headers, [self::$user]);
         //Default language value
         $language = self::getSetting('language');
         //Select request's language
         if (isset($_GET['this_language']) && self::getSetting('languages') && in_array($_GET['this_language'], self::getSetting('languages'))) {
             //Force requested language
             if ($_GET['this_language'] != $language) {
                 $language = $_GET['this_language'];
             }
             unset($_GET['this_language']);
         } elseif (self::$user && property_exists(self::$user, 'language_code')) {
             // Use user's langugae
             $language = self::$user->language_code;
         } elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && self::getSetting('languages')) {
             // Use Accept languge if provided
             $a = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
             if (in_array($a, self::getSetting('languages'))) {
                 $language = $a;
             }
         }
         //Set language variable
         self::$language = $language;
         //self::$translation->setLanguageCode($language);
         //STEP_BEFORE_CALL_URISTRATEGY
         self::$stepCallback->call(StepCallback::STEP_BEFORE_CALL_URISTRATEGY, $params, $method, $headers);
         //Call controller's method
         list($invokedController, $invokedMethod) = self::$URIStrategy->invoke($params, $method, $headers, self::$user);
         self::$stepCallback->call(StepCallback::STEP_AFTER_CALL_URISTRATEGY, $params, $method, $headers, [$invokedController, $invokedMethod]);
         //STEP_BEFORE_CLOSE
         self::$stepCallback->call(StepCallback::STEP_BEFORE_CLOSE, $params, $method, $headers);
     } catch (\Phramework\Exceptions\NotFoundException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\RequestException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\PermissionException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\UnauthorizedException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\MissingParametersException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'meta' => ['missing' => $exception->getParameters()], 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\IncorrectParametersException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'meta' => ['incorrect' => $exception->getParameters()], 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\MethodNotAllowedException $exception) {
         //Write allow header if AllowedMethods is set
         if (!headers_sent() && $exception->getAllowedMethods()) {
             header('Allow: ' . implode(', ', $exception->getAllowedMethods()));
         }
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'meta' => ['allow' => $exception->getAllowedMethods()], 'title' => $exception->getMessage()]], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Phramework\Exceptions\RequestException $exception) {
         self::errorView([(object) ['status' => $exception->getCode(), 'detail' => $exception->getMessage(), 'title' => 'Request Error']], $exception->getCode(), $params, $method, $headers, $exception);
     } catch (\Exception $exception) {
         self::errorView([(object) ['status' => 400, 'detail' => $exception->getMessage(), 'title' => 'Error']], 400, $params, $method, $headers, $exception);
     } finally {
         self::$stepCallback->call(StepCallback::STEP_FINALLY, $params, $method, $headers);
         //Unset all
         unset($params);
         //Try to close the databse
         \Phramework\Database\Database::close();
     }
 }