/** * @param Request $request * @param Closure $next * * @return array|mixed|string */ public function handle($request, Closure $next) { // Allow console requests through if (env('DF_IS_VALID_CONSOLE_REQUEST', false)) { return $next($request); } try { static::setExceptions(); 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 { $apiKey = Session::getApiKey(); $token = Session::getSessionToken(); if (empty($apiKey) && empty($token)) { throw new BadRequestException('Bad request. No token or api key provided.'); } elseif (true === Session::get('token_expired')) { throw new UnauthorizedException(Session::get('token_expired_msg')); } elseif (!Session::isAuthenticated()) { throw new UnauthorizedException('Unauthorized.'); } else { throw new ForbiddenException('Access Forbidden.'); } } } catch (\Exception $e) { return ResponseFactory::getException($e, $request); } }
protected static function getApps() { if (SessionUtilities::isAuthenticated()) { $user = SessionUtilities::user(); $defaultAppId = $user->default_app_id; if (SessionUtilities::isSysAdmin()) { $appGroups = AppGroupModel::with(['app_by_app_to_app_group' => function ($q) { $q->whereIsActive(1)->whereNotIn('type', [AppTypes::NONE]); }])->get(); $apps = AppModel::whereIsActive(1)->whereNotIn('type', [AppTypes::NONE])->get(); } else { $userId = $user->id; $userAppRoles = UserAppRole::whereUserId($userId)->whereNotNull('role_id')->get(['app_id']); $appIds = []; foreach ($userAppRoles as $uar) { $appIds[] = $uar->app_id; } $appIdsString = implode(',', $appIds); $appIdsString = empty($appIdsString) ? '-1' : $appIdsString; $typeString = implode(',', [AppTypes::NONE]); $typeString = empty($typeString) ? '-1' : $typeString; $appGroups = AppGroupModel::with(['app_by_app_to_app_group' => function ($q) use($appIdsString, $typeString) { $q->whereRaw("(app.id IN ({$appIdsString}) OR role_id > 0) AND is_active = 1 AND type NOT IN ({$typeString})"); }])->get(); $apps = AppModel::whereRaw("(app.id IN ({$appIdsString}) OR role_id > 0) AND is_active = 1 AND type NOT IN ({$typeString})")->get(); } } else { $appGroups = AppGroupModel::with(['app_by_app_to_app_group' => function ($q) { $q->where('role_id', '>', 0)->whereIsActive(1)->whereNotIn('type', [AppTypes::NONE]); }])->get(); $apps = AppModel::whereIsActive(1)->where('role_id', '>', 0)->whereNotIn('type', [AppTypes::NONE])->get(); } if (empty($defaultAppId)) { $systemConfig = SystemConfig::first(['default_app_id']); $defaultAppId = !empty($systemConfig) ? $systemConfig->default_app_id : null; } $inGroups = []; $groupedApps = []; $noGroupedApps = []; foreach ($appGroups as $appGroup) { $appArray = $appGroup->getRelation('app_by_app_to_app_group')->toArray(); if (!empty($appArray)) { $appInfo = []; foreach ($appArray as $app) { $inGroups[] = $app['id']; $appInfo[] = static::makeAppInfo($app, $defaultAppId); } $groupedApps[] = ['id' => $appGroup->id, 'name' => $appGroup->name, 'description' => $appGroup->description, 'app' => $appInfo]; } } /** @type AppModel $app */ foreach ($apps as $app) { if (!in_array($app->id, $inGroups)) { $noGroupedApps[] = static::makeAppInfo($app->toArray(), $defaultAppId); } } return [$groupedApps, $noGroupedApps]; }
/** * {@inheritdoc} */ protected function handleGET() { if (!SessionUtility::isAuthenticated()) { throw new NotFoundException('No user session found.'); } if (!SessionUtility::isSysAdmin()) { throw new UnauthorizedException('You are not authorized to perform this action.'); } return parent::handleGET(); }
/** * Resets user password. * * @return array|bool * @throws BadRequestException * @throws \Exception */ protected function handlePOST() { $oldPassword = $this->getPayloadData('old_password'); $newPassword = $this->getPayloadData('new_password'); if (!empty($oldPassword) && Session::isAuthenticated()) { $user = Session::user(); return static::changePassword($user, $oldPassword, $newPassword); } $login = $this->request->getParameterAsBool('login'); $email = $this->getPayloadData('email'); $code = $this->getPayloadData('code'); $answer = $this->getPayloadData('security_answer'); if ($this->request->getParameterAsBool('reset')) { return static::passwordReset($email); } if (!empty($code)) { return static::changePasswordByCode($email, $code, $newPassword, $login); } if (!empty($answer)) { return static::changePasswordBySecurityAnswer($email, $answer, $newPassword, $login); } return false; }
/** * @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); } }
public function testPasswordResetUsingConfirmationCode() { Arr::set($this->user2, 'email', '*****@*****.**'); $user = $this->createUser(2); Config::set('mail.pretend', true); $rs = $this->makeRequest(Verbs::POST, static::RESOURCE . '/password', ['reset' => 'true'], ['email' => $user['email']]); $content = $rs->getContent(); $this->assertTrue($content['success']); /** @var User $userModel */ $userModel = User::find($user['id']); $code = $userModel->confirm_code; $rs = $this->makeRequest(Verbs::POST, static::RESOURCE . '/password', ['login' => 'true'], ['email' => $user['email'], 'code' => $code, 'new_password' => '778877']); $content = $rs->getContent(); $this->assertTrue($content['success']); $this->assertTrue(\DreamFactory\Core\Utility\Session::isAuthenticated()); $userModel = User::find($user['id']); $this->assertEquals('y', $userModel->confirm_code); $rs = $this->makeRequest(Verbs::POST, static::RESOURCE . '/session', [], ['email' => $user['email'], 'password' => '778877']); $content = $rs->getContent(); $token = $content['session_token']; $tokenMap = DB::table('token_map')->where('token', $token)->get(); $this->assertTrue(!empty($token)); $this->assertTrue(!empty($tokenMap)); }
public function testPasswordResetUsingConfirmationCode() { if (!$this->serviceExists('mymail')) { $emailService = \DreamFactory\Core\Models\Service::create(["name" => "mymail", "label" => "Test mail service", "description" => "Test mail service", "is_active" => true, "type" => "local_email", "mutable" => true, "deletable" => true, "config" => ["driver" => "sendmail", "command" => "/usr/sbin/sendmail -bs"]]); $userConfig = \DreamFactory\Core\User\Models\UserConfig::find(4); $userConfig->password_email_service_id = $emailService->id; $userConfig->save(); } if (!\DreamFactory\Core\Models\EmailTemplate::whereName('mytemplate')->exists()) { $template = \DreamFactory\Core\Models\EmailTemplate::create(['name' => 'mytemplate', 'description' => 'test', 'to' => $this->user2['email'], 'subject' => 'rest password test', 'body_text' => 'link {link}']); $userConfig = \DreamFactory\Core\User\Models\UserConfig::find(4); $userConfig->password_email_template_id = $template->id; $userConfig->save(); } Arr::set($this->user2, 'email', '*****@*****.**'); $user = $this->createUser(2); Config::set('mail.pretend', true); $rs = $this->makeRequest(Verbs::POST, static::RESOURCE, ['reset' => 'true'], ['email' => $user['email']]); $content = $rs->getContent(); $this->assertTrue($content['success']); /** @var User $userModel */ $userModel = User::find($user['id']); $code = $userModel->confirm_code; $rs = $this->makeRequest(Verbs::POST, static::RESOURCE, ['login' => 'true'], ['email' => $user['email'], 'code' => $code, 'new_password' => '778877']); $content = $rs->getContent(); $this->assertTrue($content['success']); $this->assertTrue(Session::isAuthenticated()); $userModel = User::find($user['id']); $this->assertEquals('y', $userModel->confirm_code); $this->service = ServiceHandler::getService($this->serviceId); $rs = $this->makeRequest(Verbs::POST, 'session', [], ['email' => $user['email'], 'password' => '778877']); $content = $rs->getContent(); $this->assertTrue(!empty($content['session_id'])); }