Beispiel #1
14
 public function authorize(HeaderInterface $authHeader)
 {
     list($jwt) = sscanf($authHeader->toString(), 'Authorization: Bearer %s');
     if ($jwt) {
         try {
             /*
              * decode the jwt using the key from config
              */
             $secretKey = base64_decode($this->config->get('jwt')->get('key'));
             $this->token = JWT::decode($jwt, $secretKey, [$this->config->get('jwt')->get('algorithm')]);
             $this->isAuthorized = true;
             $this->response = Response::createMessage("10");
         } catch (Exception $e) {
             /*
              * the token was not able to be decoded.
              * this is likely because the signature was not able to be verified (tampered token)
              */
             $this->isAuthorized = false;
             $this->response = Response::createMessage("03");
             $this->response["data"] = $jwt;
         }
     } else {
         /*
          * No token was able to be extracted from the authorization header
          */
         $this->isAuthorized = false;
         $this->response = Response::createMessage("01");
     }
 }
 /**
  * Execute the job.
  *
  * @param JWT $jwt
  * @param Carbon $carbon
  * @return String
  */
 public function handle(JWT $jwt, Carbon $carbon)
 {
     $token = $jwt->decode($this->token, env('APP_KEY'), ['HS256']);
     $date = $carbon->createFromTimestamp($token->timestamp);
     $today = $carbon->now();
     /**
      * if the difference is grater than 30 days, then request login again
      */
     return $date->diffInDays($today) > 30;
 }
 /**
  * Execute the job.
  *
  * @param JWT $jwt
  * @param Carbon $carbon
  * @return String
  */
 public function handle(JWT $jwt, Carbon $carbon)
 {
     $timestamp = $carbon->now()->timestamp;
     $data = collect($this->user->toArray())->only('id')->merge(compact('timestamp'));
     $token = $jwt->encode($data, env('APP_KEY'));
     /**
      * Save token on the user model
      */
     if ($this->saveToken) {
         $this->user->setAttribute('api_token', $token);
         $this->user->save();
     }
     return $token;
 }
 public function registerAction()
 {
     $email = $this->post_data['email'];
     $password = $this->post_data['password'];
     if ($email == NULL || $password == NULL) {
         return $this->fail('Email and password not empty', Response::HTTP_BAD_REQUEST);
     }
     $user = User::where('email', '=', $email)->first();
     if ($user) {
         return $this->fail('Email already exists ', Response::HTTP_BAD_REQUEST);
     } else {
         $user = new User();
         $user->username = $this->post_data['username'];
         $user->password = md5($this->post_data['password']);
         $user->email = $this->post_data['email'];
         $user->status = 1;
         $user->save();
         if ($user->password == md5($password) && $user->status == 1) {
             $secret = $this->app['config.app.secret'];
             $token = array('user_id' => $user->id);
             $encoded_token = JWT::encode($token, $secret, 'HS256');
             return $this->json(['mess' => 'Thành công', 'user_id' => $user->id, 'token' => $encoded_token]);
         } else {
             return $this->fail('Database error', Response::HTTP_BAD_REQUEST);
         }
     }
 }
 public function showAction(Request $request, $token)
 {
     try {
         $token = JWT::decode($token, $this->keyStorage, $this->allowedAlgorithms);
     } catch (\UnexpectedValueException $exception) {
         throw new NotFoundHttpException('Resource not found', $exception);
     } catch (\Exception $exception) {
         throw new BadRequestHttpException('Invalid token', $exception);
     }
     if (!isset($token->sdef) || !is_array($token->sdef) || count($token->sdef) !== 3) {
         throw new BadRequestHttpException('sdef should be a sub-definition identifier.');
     }
     list($sbas_id, $record_id, $subdef) = $token->sdef;
     try {
         $databox = $this->findDataboxById($sbas_id);
         $record = $databox->get_record($record_id);
         $subDefinition = $record->get_subdef($subdef);
         $permalink = $subDefinition->get_permalink();
     } catch (\Exception $exception) {
         throw new NotFoundHttpException('Media was not found', $exception);
     }
     $subRequest = Request::create((string) $permalink->get_url(), 'GET', [], $request->cookies->all(), [], $request->server->all());
     if ($request->query->has('download')) {
         $subRequest->query->set('download', $request->query->get('download'));
     }
     $response = $this->app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
     // Remove Caption link header as it contains permalink token.
     $response->headers->remove('link');
     return $response;
 }
 protected function buildToken(array $values = array(), $secretKey = 'ilios.jwt.key.secret')
 {
     $now = new DateTime();
     $default = array('iss' => 'ilios', 'aud' => 'ilios', 'iat' => $now->format('U'), 'exp' => $now->modify('+1 year')->format('U'), 'user_id' => 42);
     $merged = array_merge($default, $values);
     return JWT::encode($merged, $secretKey);
 }
Beispiel #7
1
 public function login()
 {
     require plugin_dir_path(__FILE__) . '../../lib/php-jwt/JWT.php';
     require plugin_dir_path(__FILE__) . '../../lib/php-jwt/BeforeValidException.php';
     require plugin_dir_path(__FILE__) . '../../lib/php-jwt/ExpiredException.php';
     require plugin_dir_path(__FILE__) . '../../lib/php-jwt/SignatureInvalidException.php';
     $decoded = '';
     if (isset($_GET['jwt'])) {
         try {
             $decoded = \Firebase\JWT\JWT::decode($_GET['jwt'], $this->options['secret_token'], ['HS256']);
             $first_name = isset($decoded->first_name) ? $decoded->first_name : '';
             $last_name = isset($decoded->last_name) ? $decoded->last_name : '';
             $display_name = isset($decoded->display_name) ? $decoded->display_name : $first_name . ' ' . $last_name;
             $nicename = isset($decoded->nicename) ? $decoded->nicename : $display_name;
             $role = isset($decoded->role) ? $decoded->role : 'subscriber';
             $nickname = isset($decoded->nickname) ? $decoded->nickname : $username;
             $attrs = ['email' => $decoded->email, 'username' => $decoded->username, 'website' => isset($decoded->website) ? $decoded->website : '', 'nicename' => $nicename, 'display_name' => $display_name, 'first_name' => $first_name, 'last_name' => $last_name, 'role' => $role, 'nickname' => $nickname, 'description' => isset($decoded->description) ? $decoded->description : ''];
             parent::login($attrs);
         } catch (\Exception $e) {
             //var_dump($e);
             wp_redirect('/ssopress/error/');
             exit;
         }
     }
 }
Beispiel #8
1
 /**
  * @param stdClass $payload
  * @param null $expires - can be +1 day, or +1 week, etc
  *
  * @return String
  */
 public function encode(stdClass $payload, $expires = null) : string
 {
     if (!empty($expires)) {
         $payload->exp = is_numeric($expires) ? time() + $expires : strtotime($expires);
     }
     return JWT::encode($payload, $this->key, 'HS256');
 }
Beispiel #9
1
 protected function get_cookie_data($authCookie = null)
 {
     if ($authCookie) {
         /*
          * Extract the jwt from the Bearer
          */
         list($jwt) = sscanf($authCookie, 'Bearer %s');
         if ($jwt) {
             try {
                 /*
                  * decode the jwt using the key from config
                  */
                 $secretKey = base64_decode(ForumSettings::get('jwt_token'));
                 $token = JWT::decode($jwt, $secretKey, [ForumSettings::get('jwt_algorithm')]);
                 return $token;
             } catch (\Firebase\JWT\ExpiredException $e) {
                 // TODO: (Optionnal) add flash message to say token has expired
                 return false;
             } catch (\Firebase\JWT\SignatureInvalidException $e) {
                 // If token secret has changed (config.php file removed then regenerated)
                 return false;
             }
         } else {
             // Token is not present (or invalid) in cookie
             return false;
         }
     } else {
         // Auth cookie is not present in headers
         return false;
     }
 }
Beispiel #10
1
 /**
  * Decodes the token into an Object.
  *
  * @param string $token Raw token to decode
  *
  * @return object decoded token
  */
 public static function decodeToken($token)
 {
     $token = trim($token);
     //Check to ensure token is not empty or invalid
     if ($token === '' || $token === null || empty($token)) {
         throw new JWTException('Invalid Token');
     }
     //Remove Bearer if present
     $token = trim(str_replace('Bearer ', '', $token));
     //Decode token
     try {
         $token = JWT::decode($token, getenv('SECRET_KEY'), ['HS256']);
     } catch (\Exception $e) {
         throw new JWTException('Invalid Token');
     }
     //Ensure JIT is present
     if ($token->jit == null || $token->jit == '') {
         throw new JWTException('Invalid Token');
     }
     //Ensure User Id is present
     if ($token->data->uid == null || $token->data->uid == '') {
         throw new JWTException('Invalid Token');
     }
     return $token;
 }
Beispiel #11
1
 /**
  * Decode un token et le retourne sous forme d'objet.
  * Retourne FALSE si le token est invalide (expiré par exemple)
  * @param bool $jwt
  * @return bool|object
  */
 private static function Decode($jwt = false)
 {
     if ($jwt) {
         try {
             /*
              * decode the jwt using the key from config
              */
             $secretKey = self::$config['token_secret'];
             $token = JWT::decode($jwt, $secretKey, array('HS512'));
             if ($token->exp < time()) {
                 return false;
             } else {
                 return $token;
             }
         } catch (Exception $e) {
             /*
              * the token was not able to be decoded.
              * this is likely because the signature was not able to be verified (tampered token)
              */
             //die($e->getMessage());
             return false;
         }
     } else {
         /*
          * No token was able to be extracted from the authorization header
          */
         return false;
     }
 }
 /**
  * @inheritdoc
  */
 public function decode($jwt)
 {
     $payload = JWT::decode($jwt, $this->getSigningKey(), [self::SIGNING_ALGORITHM]);
     $userId = isset($payload->{self::CLAIM_USER_ID}) === true ? $payload->{self::CLAIM_USER_ID} : null;
     $user = $userId !== null ? User::find($userId) : null;
     return $user;
 }
Beispiel #13
1
 public function connect(Application $app)
 {
     $books = $app['controllers_factory'];
     $books->before(function (Request $request) use($app) {
         // Strip out the bearer
         $rawHeader = $request->headers->get('Authorization');
         if ($rawHeader) {
             if (strpos($rawHeader, 'Bearer ') === false) {
                 return new JsonResponse(array('message' => 'Unauthorized'), 401);
             }
             $jwt = str_replace('Bearer ', '', $rawHeader);
             $secretKey = base64_decode($app['secret']);
             try {
                 $token = JWT::decode($jwt, $secretKey, [$app['algorithm']]);
             } catch (Exception $e) {
                 return new JsonResponse(array('message' => 'Unauthorized'), 401);
             }
         } else {
             return new JsonResponse(array('message' => 'Bad Request'), 400);
         }
     });
     $books->get('/', 'MyApp\\Controller\\BookController::index');
     $books->post('/', 'MyApp\\Controller\\BookController::store');
     $books->get('/{id}', 'MyApp\\Controller\\BookController::show');
     $books->get('/edit/{id}', 'MyApp\\Controller\\BookController::edit');
     $books->put('/{id}', 'MyApp\\Controller\\BookController::update');
     $books->delete('/{id}', 'MyApp\\Controller\\BookController::destroy');
     return $books;
 }
Beispiel #14
1
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     $jwt = $request->header('x-auth-jwt');
     $key = 'fad';
     //env('JWT_KEY');
     $decoded = JWT::decode($jwt, $key, array('HS256'));
     /*
     	
     /*
      		NOTE: This will now be an object instead of an associative array. To get
      		an associative array, you will need to cast it as such:
     */
     //$decoded_array = (array) $jwt;
     /**
      * You can add a leeway to account for when there is a clock skew times between
      * the signing and verifying servers. It is recommended that this leeway should
      * not be bigger than a few minutes.
      *
      * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
      */
     //JWT::$leeway = 60; // $leeway in seconds
     //$decoded = JWT::decode($jwt, $key, array('HS256'));
     return $next($request);
     //$res = $next($request);
     //echo "after http request!";
     //return $res;
 }
Beispiel #15
1
 function ValidateToken()
 {
     try {
         $headers = getallheaders();
         if (!isset($headers['Authorization'])) {
             return;
         }
         $tokenObject = explode(' ', $headers['Authorization']);
         if (count($tokenObject) != 2) {
             return;
         }
         $tokenValue = $tokenObject[1];
         if ($tokenValue == NULL || $tokenValue == '') {
             return;
         }
         JWT::$leeway = 60 * 60 * 24;
         //24 hours
         $decoded = JWT::decode($tokenValue, "JWT_KEY", array('HS256'));
         if (empty($decoded)) {
             return;
         }
         $decoded_array = (array) $decoded;
         if (empty($decoded_array)) {
             return;
         }
         self::$token = $tokenValue;
         self::$userId = $decoded_array['uid'];
         self::$isAuthorized = TRUE;
     } catch (UnexpectedValueException $e) {
         return;
     } catch (Exception $e) {
         return;
     }
 }
 /**
  * Logs in a user with the given username and password POSTed. Though true
  * REST doesn't believe in sessions, it is often desirable for an AJAX server.
  *
  * @url POST /auth
  */
 public function auth()
 {
     $username = $_POST['username'];
     $password = $_POST['password'];
     //ToDo: handle login and generate authtoken return it
     return JWT::encode('abc', 'my_key');
 }
Beispiel #17
1
 /**
  * @Route("/login")
  * @Method({"PUT"})
  */
 public function login(Request $request)
 {
     $email = $request->request->get('email');
     $password = $request->request->get('password');
     $customer = $this->getCustomerManager()->getRepo()->findOneByEmail($email);
     if (!$customer) {
         return $this->fail();
     }
     $em = $this->getDoctrine()->getManager();
     if ($customer->verifyPassword($password)) {
         $expire = new \DateTime('now');
         $expire->modify('+20 minute');
         $token = new Token($expire);
         if ($customer->getToken()) {
             $em->remove($customer->getToken());
         }
         $customer->setToken($token);
         $em->persist($token);
         $em->persist($customer);
         $em->flush();
         $key = $this->container->getParameter('jwt_key');
         $payload = array('type' => 'customer', 'user_id' => $customer->getId(), 'token_id' => $token->getId(), 'expires' => $token->getExpires());
         return $this->respondJson(array('jwt' => JWT::encode($payload, $key)));
     }
     return $this->fail();
 }
 public function login()
 {
     $response = $this->app->response();
     $response->header("Content-Type", "application/json");
     $username = $this->app->request()->params('username');
     $password = $this->app->request()->params('password');
     if (!isset($username)) {
         return Auth::deny_access("Username is null");
     }
     if (!isset($password)) {
         return Auth::deny_access("Password is null");
     }
     $username = htmlentities(trim($username));
     $password = htmlentities(trim($password));
     $database_user = User::where('username', $username);
     $database_user = json_decode($database_user, true);
     if (empty($database_user)) {
         return ['status' => 400, 'message' => 'username doesn\'t'];
     }
     $database_user = $database_user[0];
     if ($database_user['password'] == md5($password)) {
         $key = $this->config->jwt_key();
         $token = ["iss" => $this->config->jwt_issuer(), "iat" => $this->config->jwt_issuer_at(), "nbf" => $this->config->jwt_not_before(), "exp" => $this->config->jwt_expiration_time(), "data" => ["username" => $database_user['username']]];
         $encode_jwt = JWT::encode($token, $key, 'HS512');
         $responseArray = ["token" => $encode_jwt, "status" => 200];
         $response->status(200);
         $response->body(json_encode($responseArray));
         return $response;
     } else {
         return Auth::deny_access("Incorrect Authentication Details");
     }
 }
 public function authenticate(Application $app, Request $request)
 {
     $username = $request->get('user');
     $password = $request->get('pass');
     if ($username && $password) {
         $sql = "SELECT * FROM user WHERE username = ? AND password = ?";
         $user = $app['db']->fetchAssoc($sql, array($username, md5($password)));
         if ($user) {
             $tokenId = base64_encode(mcrypt_create_iv(32));
             $issuedAt = time();
             $notBefore = $issuedAt;
             //Adding 10 seconds
             $expire = $notBefore + 604800;
             // Adding 1 week
             $serverName = $app['serverName'];
             // Retrieve the server name from config file
             $id = 1;
             //TODO: da cambiare
             $data = ['iat' => $issuedAt, 'jti' => $tokenId, 'iss' => $serverName, 'nbf' => $notBefore, 'exp' => $expire, 'data' => ['userId' => $user['id'], 'userName' => $user['username']]];
             // Get the secret key for signing the JWT from an environment variable
             $secretKey = base64_decode($app['secret']);
             $algorithm = $app['algorithm'];
             // Sign the JWT with the secret key
             $jwt = JWT::encode($data, $secretKey, $algorithm);
             return new JsonResponse(array('token' => $jwt), 200);
         } else {
             return new JsonResponse(array('message' => 'Failed to Authenticate'), 403);
         }
     } else {
         return new JsonResponse(array('message' => 'Failed to Authenticate'), 403);
     }
 }
Beispiel #20
1
 protected function login($user)
 {
     $key = Config::get('custom.JWTkey');
     $token = array("sub" => $user->id, "iss" => "http://leo.app", "iat" => 1356999524, "name" => $user->name);
     $jwt = JWT::encode($token, $key);
     return $jwt;
 }
Beispiel #21
1
 /**
  * Generate JWT authorization header
  * @return string
  */
 public function generateAuthHeader()
 {
     $time = time();
     $iss = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'cli';
     $signatureData = ['sub' => $this->config['public_key'], 'iat' => $time, 'exp' => $time + $this->config['leeway'], 'iss' => $iss, 'nbf' => $time - $this->config['leeway'], 'jti' => md5($this->config['public_key'] . $time)];
     return JWT::encode($signatureData, $this->config['private_key']);
 }
 public function testGetToken()
 {
     $mockPlugin = new MockPlugin();
     $mockPlugin->addResponse(new Response(200, array(), json_encode(array('data' => array('access_token' => 'hi', 'expires_in' => 1, 'refresh_token' => 'refresh')))));
     $client = new Client();
     $client->addSubscriber($mockPlugin);
     $flow = new ClientCredentials(array('client_id' => 'clientid', 'client_secret' => 'clientsecret', 'shared_secret' => 'sharedsecret'), $client);
     $token = $flow->getToken();
     $request = $mockPlugin->getReceivedRequests()[0];
     $postFields = $request->getPostFields();
     $jwt = JWT::decode($postFields['client_assertion'], 'sharedsecret', array('HS512'));
     $this->assertEquals('POST', $request->getMethod());
     $this->assertEquals('clientid', $postFields['client_id']);
     $this->assertEquals('clientsecret', $postFields['client_secret']);
     $this->assertEquals('client_credentials', $postFields['grant_type']);
     $this->assertEquals('urn:params:oauth:client-assertion-type:jwt-bearer', $postFields['client_assertion_type']);
     $this->assertEquals('clientid', $jwt->iss);
     $this->assertEquals('clientid', $jwt->sub);
     $this->assertEquals('https://api.careerbuilder.com/oauth/token', $jwt->aud);
     $this->assertEquals(time() + 180, $jwt->exp);
     $this->assertEquals('hi', "{$token}");
     $this->assertEquals(true, $token->getRefreshToken());
     // TODO
     $this->assertEquals(time() + 1, $token->getExpiresAt());
 }
Beispiel #23
1
 private function get_profile_hmac($account)
 {
     $key = $this->apiSecret;
     $payload = array("account" => $account, "apiUniqueId" => $this->apiKey, "created" => date("DATE_W3C"));
     $jwt = JWT::encode($payload, $key);
     return $jwt;
 }
 public function validateMerchantOtp(request $request)
 {
     $apiKey = $request->only('api_key');
     $validator = Validator::make($apiKey, ['api_key' => 'required']);
     if ($validator->fails()) {
         $response = response()->json(['response_code' => 'ERR_IAK', 'messages' => 'Invalid Api Key'], 403);
         return $response;
     }
     $role = Role::find(2);
     $key = Config::get('custom.JWTkey');
     $decoded = JWT::decode($apiKey['api_key'], $key, array('HS256'));
     if ($decoded->type != 'merchant') {
         return $response = response()->json(['response_code' => 'ERR_IAK', 'messages' => 'Invalid Api Key'], 403);
     }
     $user = User::find($decoded->sub);
     // check the current user
     if (empty($user) || !$user->hasRole(['merchant']) || !$user->status) {
         return $response = response()->json(['response_code' => 'ERR_IAK', 'messages' => 'Invalid Api Key'], 403);
     }
     $user_id = $user->id;
     $input = $request->only('otp');
     $matchThese = ['user_id' => $user_id, 'code' => $input['otp']];
     $sms = UserSmsCode::where($matchThese)->first();
     if ($sms == '' || empty($sms)) {
         return response()->json(['response_code' => 'RES_IOG', 'messages' => 'Invalid OTP Given'], 422);
     }
     $sms->status = true;
     $sms->save();
     $user->is_mobile_verified = true;
     $user->save();
     return response()->json(['response_code' => 'RES_MV', 'messages' => 'Mobile Verified']);
 }
Beispiel #25
0
 public static function generate_jwt($user)
 {
     $issuedAt = time();
     $tokenId = base64_encode(Random::key(32));
     $serverName = Config::get('serverName');
     /*
      * Create the token as an array
      */
     $data = ['iat' => $issuedAt, 'jti' => $tokenId, 'iss' => $serverName, 'exp' => $issuedAt + 1800, 'data' => ['userId' => $user->id, 'userName' => $user->username]];
     /*
      * Extract the key, which is coming from the config file.
      *
      * Generated with base64_encode(openssl_random_pseudo_bytes(64));
      */
     $secretKey = base64_decode(Config::get('jwt')['key']);
     /*
      * Extract the algorithm from the config file too
      */
     $algorithm = Config::get('jwt')['algorithm'];
     /*
      * Encode the array to a JWT string.
      * Second parameter is the key to encode the token.
      *
      * The output string can be validated at http://jwt.io/
      */
     $jwt = JWT::encode($data, $secretKey, $algorithm);
     return $jwt;
 }
Beispiel #26
0
 public function getJwt()
 {
     $return = [];
     $key = "352352345623463246trswrgsdfgsdfgsdfgsert";
     $token = array("iss" => "http://example.org", "aud" => "http://example.com", "iat" => time(), "nbf" => time() - 4123123);
     /**
      * IMPORTANT:
      * You must specify supported algorithms for your application. See
      * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
      * for a list of spec-compliant algorithms.
      */
     $jwt = JWT::encode($token, $key);
     $return[] = $jwt;
     $decoded = JWT::decode($jwt, $key, array('HS256'));
     $return[] = $decoded;
     /*
      NOTE: This will now be an object instead of an associative array. To get
      an associative array, you will need to cast it as such:
     */
     $decoded_array = (array) $decoded;
     $return[] = $decoded_array;
     /**
      * You can add a leeway to account for when there is a clock skew times between
      * the signing and verifying servers. It is recommended that this leeway should
      * not be bigger than a few minutes.
      *
      * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
      */
     JWT::$leeway = 60;
     // $leeway in seconds
     $decoded = JWT::decode($jwt, $key, array('HS256'));
     $return[] = $decoded;
     return $return;
 }
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
 {
     $match = $this->router->match($request->getPathInfo());
     $route = substr($request->getPathInfo(), strlen(rtrim($this->config['baseDir'], '/')));
     if ($match) {
         $tokenValid = false;
         $jwtCookie = $this->config['jwt']['cookieName'];
         $jwtKey = $this->config['jwt']['key'];
         // check token from cookie
         if ($request->cookies->has($jwtCookie)) {
             $jwt = $request->cookies->get($jwtCookie);
             try {
                 $decoded = JWT::decode($jwt, $jwtKey, ['HS256']);
                 if ($decoded->e > time()) {
                     $tokenValid = true;
                     $this->auth->init($decoded->uid);
                 }
             } catch (\Exception $e) {
                 $tokenValid = false;
                 if (!$catch) {
                     throw $e;
                 }
                 $response = $this->dispatcher->dispatch('Home#error', ['message' => '[' . $e->getCode() . '] ' . $e->getMessage() . '<pre>' . $e->getTraceAsString() . '</pre>']);
                 $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
                 return $response;
             }
         }
         $allowed = false;
         $isPublic = false;
         foreach ($this->config['publicArea'] as $publicRoute) {
             if (preg_match('/^' . addcslashes($publicRoute, '/') . '/', $route)) {
                 $isPublic = true;
                 break;
             }
         }
         if ($match['name'] == 'home') {
             $isPublic = true;
         }
         if ($isPublic) {
             if ($route == '/login' && $tokenValid) {
                 return new RedirectResponse($this->router->generate('dashboard'));
             }
             $allowed = true;
         } else {
             $allowed = $tokenValid;
         }
         if ($allowed) {
             $this->app->setRouteMatch($match);
             return $this->app->handle($request, $type, $catch);
         } else {
             $this->flash->warning('Sesi Anda telah habis atau Anda tidak berhak mengakses halaman ini, silakan login terlebih dahulu!');
             $response = $this->dispatcher->dispatch('User#login', []);
             $response->setStatusCode(Response::HTTP_UNAUTHORIZED);
             return $response;
         }
     }
     $response = $this->dispatcher->dispatch('Home#error', ['message' => 'Halaman tidak ditemukan: ' . $route]);
     $response->setStatusCode(Response::HTTP_NOT_FOUND);
     return $response;
 }
 /**
  * @inheritdoc
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $jwt = $input->getArgument('jwt');
     $secret = $input->getArgument('start');
     $timeout = $input->getArgument('timeout');
     $found = false;
     $start = microtime(true);
     $step = 100000;
     while (microtime(true) - $start < $timeout) {
         for ($i = 0; $i < $step; $i++) {
             try {
                 JWT::decode($jwt, $secret, ['HS256']);
                 $found = true;
                 break 2;
             } catch (\Exception $e) {
                 $secret = $this->findNext($secret);
             }
         }
         $output->write(sprintf('%s, ', $secret));
     }
     $took = number_format(microtime(true) - $start, 2);
     $memoryUsed = number_format(memory_get_peak_usage() / (1024 * 1024), 2) . ' MB';
     if ($found) {
         $output->writeln(sprintf('<info>Secret found:</info> %s (took: %s, memory: %s)', $secret, $took, $memoryUsed));
     } else {
         $output->writeln(sprintf('<error>Secret not found:</error> finished on %s (took: %s, memory: %s)', $secret, $took, $memoryUsed));
     }
 }
Beispiel #29
0
 function login_post()
 {
     $email = '';
     $password = '';
     try {
         $entityBody = file_get_contents('php://input');
         $arrayObject = (array) json_decode($entityBody);
         if (!isset($arrayObject['email']) || !isset($arrayObject['password'])) {
             throw new Exception();
         }
         $email = $arrayObject['email'];
         $password = $arrayObject['password'];
         if ($email == '') {
             throw new Exception();
         }
         if ($password == '') {
             throw new Exception();
         }
     } catch (Exception $e) {
         $this->response(array('message' => 'Invalid request data'), self::HTTP_BAD_REQUEST);
     }
     $this->load->model('Model_users');
     $user = $this->Model_users->get_by(array('email' => $email, 'password' => sha1($password)));
     if ($user == NULL) {
         $this->response(array('message' => 'User not found'), self::HTTP_BAD_REQUEST);
     }
     $unixTime = new DateTime();
     $unixTime = $unixTime->getTimestamp();
     $token = array("uid" => $user->id, "name" => $user->name, "email" => $user->email, "iat" => $unixTime);
     $jwt = JWT::encode($token, "JWT_KEY");
     $this->response(array('id' => (int) $user->id, 'name' => $user->name, 'token' => $jwt), self::HTTP_OK);
 }
 /**
  * @vcr configuration_openid
  */
 public function testCreateAutologinJwt()
 {
     $authorization = $this->getValidAuthorization();
     $tokenSet = new \P7\SSO\TokenSet(['access_token' => 'ACCESS_TOKEN', 'id_token' => 'ID_TOKEN_TOKEN', 'expires_in' => 1234, 'received_at' => 5678]);
     $loginToken = JWT::decode($authorization->createAutologinJwt($tokenSet), $authorization->getConfig()->client_secret, ['HS256']);
     $this->assertEquals((object) ['access_token' => 'ACCESS_TOKEN', 'id_token' => 'ID_TOKEN_TOKEN', 'remember_me' => false], $loginToken);
 }