public static function boot() { parent::boot(); static::saved(function (Role $role) { if (!$role->is_active) { JWTUtilities::invalidateTokenByRoleId($role->id); } \Cache::forget('role:' . $role->id); }); static::deleted(function (Role $role) { JWTUtilities::invalidateTokenByRoleId($role->id); \Cache::forget('role:' . $role->id); }); }
/** * Updates user profile. * * @return array * @throws NotFoundException * @throws \Exception */ protected function handlePOST() { $payload = $this->getPayloadData(); $data = ['first_name' => ArrayUtils::get($payload, 'first_name'), 'last_name' => ArrayUtils::get($payload, 'last_name'), 'name' => ArrayUtils::get($payload, 'name'), 'email' => ArrayUtils::get($payload, 'email'), 'phone' => ArrayUtils::get($payload, 'phone'), 'security_question' => ArrayUtils::get($payload, 'security_question'), 'security_answer' => ArrayUtils::get($payload, 'security_answer'), 'default_app_id' => ArrayUtils::get($payload, 'default_app_id')]; ArrayUtils::removeNull($data); $user = Session::user(); if (empty($user)) { throw new NotFoundException('No user session found.'); } $oldToken = Session::getSessionToken(); $email = $user->email; $user->update($data); if (!empty($oldToken) && $email !== ArrayUtils::get($data, 'email', $email)) { // Email change invalidates token. Need to create a new token. $forever = JWTUtilities::isForever($oldToken); Session::setUserInfoWithJWT($user, $forever); $newToken = Session::getSessionToken(); return ['success' => true, 'session_token' => $newToken]; } return ['success' => true]; }
public function testApiKeyUserRole() { $user = ['name' => 'John Doe', 'first_name' => 'John', 'last_name' => 'Doe', 'email' => '*****@*****.**', 'password' => 'test1234', 'security_question' => 'Make of your first car?', 'security_answer' => 'mazda', 'is_active' => true]; $role = ['name' => 'test_role', 'is_active' => true, 'role_service_access_by_role_id' => [['service_id' => 1, 'component' => 'config', 'verb_mask' => 1, 'requestor_mask' => 1]]]; $this->service = ServiceHandler::getService('system'); $rs = $this->makeRequest(Verbs::POST, 'user', [], [$user]); $data = $rs->getContent(); $userId = Arr::get($data, static::$wrapper . '.0.id'); $this->service = ServiceHandler::getService('system'); $rs = $this->makeRequest(Verbs::POST, 'role', [], [$role]); $data = $rs->getContent(); $roleId = Arr::get($data, static::$wrapper . '.0.id'); \DreamFactory\Core\Models\UserAppRole::create(['user_id' => $userId, 'app_id' => 1, 'role_id' => $roleId]); $app = App::find(1); $apiKey = $app->api_key; $myUser = User::find($userId); $token = JWTUtilities::makeJWTByUser($myUser->id, $myUser->email); $this->call(Verbs::GET, '/api/v2/system', [], [], [], ['HTTP_X_DREAMFACTORY_API_KEY' => $apiKey, 'HTTP_X_DREAMFACTORY_SESSION_TOKEN' => $token]); $this->assertFalse(Session::isSysAdmin()); $this->assertEquals($roleId, Session::get('role.id')); $rsa = Session::get('role.services'); $this->assertTrue(!empty($rsa)); }
/** * Sets basic info of the user in session with JWT when authenticated. * * @param array|User $user * @param bool $forever * @param integer $appId * * @return bool */ public static function setUserInfoWithJWT($user, $forever = false, $appId = null) { $userInfo = null; if ($user instanceof User) { $userInfo = $user->toArray(); ArrayUtils::set($userInfo, 'is_sys_admin', $user->is_sys_admin); } if (!empty($userInfo)) { $id = ArrayUtils::get($userInfo, 'id'); $email = ArrayUtils::get($userInfo, 'email'); $token = JWTUtilities::makeJWTByUser($id, $email, $forever); static::setSessionToken($token); if (!empty($appId) && !$user->is_sys_admin) { static::setSessionData($appId, $id); return true; } else { return static::setUserInfo($userInfo); } } return false; }
/** * Refreshes current JWT. * * @return array * @throws \DreamFactory\Core\Exceptions\UnauthorizedException */ protected function handlePUT() { JWTUtilities::refreshToken(); return Session::getPublicInfo(); }
public static function boot() { parent::boot(); static::saved(function (User $user) { if (!$user->is_active) { JWTUtilities::invalidateTokenByUserId($user->id); } \Cache::forget('user:'******'user:' . $user->id); }); }
public static function boot() { static::saved(function (App $app) { if (!$app->is_active) { JWTUtilities::invalidateTokenByAppId($app->id); } \Cache::forget('app:' . $app->id); }); static::deleted(function (App $app) { JWTUtilities::invalidateTokenByAppId($app->id); \Cache::forget('app:' . $app->id); }); }
/** * @param Request $request * @param Closure $next * * @return array|mixed|string */ public function handle($request, Closure $next) { try { static::setExceptions(); //Get the api key. $apiKey = static::getApiKey($request); Session::setApiKey($apiKey); $appId = App::getAppIdByApiKey($apiKey); //Get the JWT. $token = static::getJwt($request); Session::setSessionToken($token); //Get the Console API Key $consoleApiKey = static::getConsoleApiKey($request); //Check for basic auth attempt. $basicAuthUser = $request->getUser(); $basicAuthPassword = $request->getPassword(); if (config('df.managed') && !empty($consoleApiKey) && $consoleApiKey === Managed::getConsoleKey()) { //DFE Console request return $next($request); } elseif (!empty($basicAuthUser) && !empty($basicAuthPassword)) { //Attempting to login using basic auth. Auth::onceBasic(); /** @var User $authenticatedUser */ $authenticatedUser = Auth::user(); if (!empty($authenticatedUser)) { $userId = $authenticatedUser->id; Session::setSessionData($appId, $userId); } else { throw new UnauthorizedException('Unauthorized. User credentials did not match.'); } } elseif (!empty($token)) { //JWT supplied meaning an authenticated user session/token. try { JWTAuth::setToken($token); /** @type Payload $payload */ $payload = JWTAuth::getPayload(); JWTUtilities::verifyUser($payload); $userId = $payload->get('user_id'); Session::setSessionData($appId, $userId); } catch (TokenExpiredException $e) { JWTUtilities::clearAllExpiredTokenMaps(); if (!static::isException($request)) { throw new UnauthorizedException($e->getMessage()); } } catch (TokenBlacklistedException $e) { throw new ForbiddenException($e->getMessage()); } catch (TokenInvalidException $e) { throw new BadRequestException('Invalid token: ' . $e->getMessage(), 401); } } elseif (!empty($apiKey)) { //Just Api Key is supplied. No authenticated session Session::setSessionData($appId); } elseif (static::isException($request)) { //Path exception. return $next($request); } else { throw new BadRequestException('Bad request. No token or api key provided.'); } if (static::isAccessAllowed()) { return $next($request); } elseif (static::isException($request)) { //API key and/or (non-admin) user logged in, but if access is still not allowed then check for exception case. return $next($request); } else { if (!Session::isAuthenticated()) { throw new UnauthorizedException('Unauthorized.'); } else { throw new ForbiddenException('Access Forbidden.'); } } } catch (\Exception $e) { return ResponseFactory::getException($e, $request); } }
/** * @param Request $request * @param \Closure $next * * @return array|mixed|string */ public function handle(Request $request, \Closure $next) { if (!in_array($route = $request->getPathInfo(), ['/setup', '/setup_db'])) { try { $apiKey = static::getApiKey($request); Session::setApiKey($apiKey); $appId = App::getAppIdByApiKey($apiKey); //Get the JWT. $token = static::getJwt($request); Session::setSessionToken($token); //Check for basic auth attempt. $basicAuthUser = $request->getUser(); $basicAuthPassword = $request->getPassword(); if (!empty($basicAuthUser) && !empty($basicAuthPassword)) { //Attempting to login using basic auth. Auth::onceBasic(); /** @var User $authenticatedUser */ $authenticatedUser = Auth::user(); if (!empty($authenticatedUser)) { $userId = $authenticatedUser->id; Session::setSessionData($appId, $userId); } else { throw new UnauthorizedException('Unauthorized. User credentials did not match.'); } } elseif (!empty($token)) { //JWT supplied meaning an authenticated user session/token. /** * Note: All caught exception from JWT are stored in session variables. * These are later checked and handled appropriately in the AccessCheck middleware. * * This is to allow processing API calls that do not require any valid * authenticated session. For example POST user/session to login, * PUT user/session to refresh old JWT, GET system/environment etc. * * This also allows for auditing API calls that are called by not permitted/processed. * It also allows counting unauthorized API calls against Enterprise Console limits. */ try { JWTAuth::setToken($token); /** @type Payload $payload */ $payload = JWTAuth::getPayload(); JWTUtilities::verifyUser($payload); $userId = $payload->get('user_id'); Session::setSessionData($appId, $userId); } catch (TokenExpiredException $e) { JWTUtilities::clearAllExpiredTokenMaps(); Session::set('token_expired', true); Session::set('token_expired_msg', $e->getMessage()); } catch (TokenBlacklistedException $e) { Session::set('token_blacklisted', true); Session::set('token_blacklisted_msg', $e->getMessage()); } catch (TokenInvalidException $e) { Session::set('token_invalid', true); Session::set('token_invalid_msg', 'Invalid token: ' . $e->getMessage()); } } elseif (!empty($apiKey)) { //Just Api Key is supplied. No authenticated session Session::setSessionData($appId); } return $next($request); } catch (\Exception $e) { return ResponseFactory::getException($e, $request); } } return $next($request); }
/** * @param Request $request * @param \Closure $next * * @return array|mixed|string */ public function handle(Request $request, \Closure $next) { if (!in_array($route = $request->getPathInfo(), ['/setup', '/setup_db'])) { try { $apiKey = static::getApiKey($request); Session::setApiKey($apiKey); $appId = App::getAppIdByApiKey($apiKey); //Get the JWT. $token = static::getJwt($request); Session::setSessionToken($token); //Check for basic auth attempt. $basicAuthUser = $request->getUser(); $basicAuthPassword = $request->getPassword(); if (!empty($basicAuthUser) && !empty($basicAuthPassword)) { //Attempting to login using basic auth. Auth::onceBasic(); /** @var User $authenticatedUser */ $authenticatedUser = Auth::user(); if (!empty($authenticatedUser)) { $userId = $authenticatedUser->id; Session::setSessionData($appId, $userId); } else { throw new UnauthorizedException('Unauthorized. User credentials did not match.'); } } elseif (!empty($token)) { //JWT supplied meaning an authenticated user session/token. try { JWTAuth::setToken($token); /** @type Payload $payload */ $payload = JWTAuth::getPayload(); JWTUtilities::verifyUser($payload); $userId = $payload->get('user_id'); Session::setSessionData($appId, $userId); } catch (TokenExpiredException $e) { JWTUtilities::clearAllExpiredTokenMaps(); Session::set('token_expired', true); Session::set('token_expired_msg', $e->getMessage()); } catch (TokenBlacklistedException $e) { throw new ForbiddenException($e->getMessage()); } catch (TokenInvalidException $e) { throw new BadRequestException('Invalid token: ' . $e->getMessage(), 401); } } elseif (!empty($apiKey)) { //Just Api Key is supplied. No authenticated session Session::setSessionData($appId); } return $next($request); } catch (\Exception $e) { return ResponseFactory::getException($e, $request); } } return $next($request); }