/** * @return string * @throws \DreamFactory\Core\Exceptions\UnauthorizedException */ public static function refreshToken() { $token = Session::getSessionToken(); try { $newToken = \JWTAuth::refresh($token); $payload = \JWTAuth::getPayload($newToken); $userId = $payload->get('user_id'); $user = User::find($userId); $userInfo = $user->toArray(); ArrayUtils::set($userInfo, 'is_sys_admin', $user->is_sys_admin); Session::setSessionToken($newToken); Session::setUserInfo($userInfo); static::setTokenMap($payload, $newToken); } catch (TokenExpiredException $e) { $payloadArray = \JWTAuth::manager()->getJWTProvider()->decode($token); $forever = boolval(ArrayUtils::get($payloadArray, 'forever')); if ($forever) { $userId = ArrayUtils::get($payloadArray, 'user_id'); $user = User::find($userId); Session::setUserInfoWithJWT($user, $forever); } else { throw new UnauthorizedException($e->getMessage()); } } return Session::getSessionToken(); }
public function createFirstUser() { $request = \Request::instance(); $method = $request->method(); if (Verbs::GET === $method) { if (!User::adminExists()) { $data = ['version' => \Config::get('df.api_version'), 'email' => '', 'name' => '', 'first_name' => '', 'last_name' => '']; return view('firstUser', $data); } else { return redirect()->to('/'); } } else { if (Verbs::POST === $method) { $data = $request->all(); $registrar = new Registrar(); $validator = $registrar->validator($data); if ($validator->fails()) { $errors = $validator->getMessageBag()->all(); $data = array_merge($data, ['errors' => $errors, 'version' => \Config::get('df.api_version')]); return view('firstUser', $data); } else { $registrar->create($data); return redirect()->to('/'); } } } }
/** * Run the database seeds. * * @return void */ public function run() { Model::unguard(); // Add default admin user if (!User::exists()) { User::create(['name' => 'DF Admin', 'email' => 'dfadmin@' . gethostname() . '.com', 'password' => 'Dream123!', 'is_sys_admin' => true, 'is_active' => true]); $this->command->info('Admin user seeded!'); } }
public function testSysAdmin() { $user = \DreamFactory\Core\Models\User::find(1); Session::setUserInfoWithJWT($user); $permission = Session::getServicePermissions('system', '*'); $this->assertEquals($permission, VerbsMask::NONE_MASK | VerbsMask::GET_MASK | VerbsMask::POST_MASK | VerbsMask::PUT_MASK | VerbsMask::PATCH_MASK | VerbsMask::DELETE_MASK); $nonAdminUser = \DreamFactory\Core\Models\User::create(['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]); Session::setUserInfoWithJWT($nonAdminUser); $permission = Session::getServicePermissions('system', '*'); $this->assertEquals(VerbsMask::NONE_MASK, $permission); }
protected function adminCheck($records) { if (isset($records[static::$wrapper])) { $records = $records[static::$wrapper]; } foreach ($records as $user) { /** @type \DreamFactory\Core\Models\User $userModel */ $userModel = \DreamFactory\Core\Models\User::find($user['id']); if ($userModel->is_sys_admin) { return false; } } return true; }
public function index() { $uri = static::getURI($_SERVER); $dist = env('DF_INSTALL', ''); if (empty($dist) && false !== stripos(env('DB_DATABASE', ''), 'bitnami')) { $dist = 'Bitnami'; } $appCount = App::all()->count(); $adminCount = User::whereIsSysAdmin(1)->count(); $userCount = User::whereIsSysAdmin(0)->count(); $serviceCount = Service::all()->count(); $roleCount = Role::all()->count(); $status = ["uri" => $uri, "managed" => env('DF_MANAGED', false), "dist" => $dist, "demo" => Environment::isDemoApplication(), "version" => \Config::get('df.version'), "host_os" => PHP_OS, "resources" => ["app" => $appCount, "admin" => $adminCount, "user" => $userCount, "service" => $serviceCount, "role" => $roleCount]]; return ResponseFactory::sendResponse(ResponseFactory::create($status)); }
public function testPOSTRegister() { $u = $this->user1; $password = Arr::get($u, 'password'); $payload = ['first_name' => Arr::get($u, 'first_name'), 'last_name' => Arr::get($u, 'last_name'), 'name' => Arr::get($u, 'name'), 'email' => Arr::get($u, 'email'), 'phone' => Arr::get($u, 'phone'), 'security_question' => Arr::get($u, 'security_question'), 'security_answer' => Arr::get($u, 'security_answer'), 'password' => $password, 'password_confirmation' => Arr::get($u, 'password_confirmation', $password)]; Session::setUserInfoWithJWT(User::find(1)); $r = $this->makeRequest(Verbs::POST, static::RESOURCE, [], $payload); $c = $r->getContent(); $this->assertTrue(Arr::get($c, 'success')); Session::set('role.name', 'test'); Session::set('role.id', 1); $this->service = ServiceHandler::getService('user'); $r = $this->makeRequest(Verbs::POST, 'session', [], ['email' => Arr::get($u, 'email'), 'password' => Arr::get($u, 'password')]); $c = $r->getContent(); $this->assertTrue(!empty(Arr::get($c, 'session_id'))); }
/** * Run the setup process. * * @throws \DreamFactory\Core\Exceptions\BadRequestException */ protected function runSetup() { $force = $this->option('force'); if ($this->isConfigRequired()) { $this->runConfig(); return; } $this->info('**********************************************************************************************************************'); $this->info('* Welcome to DreamFactory setup wizard.'); $this->info('**********************************************************************************************************************'); $this->info('Running Migrations...'); $this->call('migrate', ['--force' => $force]); $this->info('Migration completed successfully.'); $this->info('**********************************************************************************************************************'); $this->info('**********************************************************************************************************************'); $this->info('Running Seeder...'); $this->call('db:seed', ['--force' => $force]); $this->info('All tables were seeded successfully.'); $this->info('**********************************************************************************************************************'); $this->info('**********************************************************************************************************************'); $this->info('Creating the first admin user...'); $user = false; while (!$user) { $firstName = $this->ask('Enter your first name'); $lastName = $this->ask('Enter your last name'); $displayName = $this->ask('Enter display name'); $displayName = empty($displayName) ? $firstName . ' ' . $lastName : $displayName; $email = $this->ask('Enter your email address?'); $password = $this->secret('Choose a password'); $passwordConfirm = $this->secret('Re-enter password'); $data = ['first_name' => $firstName, 'last_name' => $lastName, 'email' => $email, 'password' => $password, 'password_confirmation' => $passwordConfirm, 'name' => $displayName]; $user = User::createFirstAdmin($data); if (!$user) { $this->error('Failed to create user.' . print_r($data['errors'], true)); $this->info('Please try again...'); } } $this->info('Successfully created first admin user.'); $this->info('**********************************************************************************************************************'); $this->dirWarn(); $this->info('*********************************************** Setup Successful! ****************************************************'); $this->info('* Setup is complete! Your instance is ready. Please launch your instance using a browser.'); $this->info('* You can run "php artisan serve" to try out your instance without setting up a web server.'); $this->info('**********************************************************************************************************************'); }
/** * @param Request $request * @param \Closure $next * * @return \Illuminate\Http\RedirectResponse * @throws \Exception */ public function handle($request, Closure $next) { if (!in_array($route = $request->getPathInfo(), ['/setup', '/setup_db'])) { try { if (!User::adminExists()) { return redirect()->to('/setup'); } } catch (QueryException $e) { try { //base table or view not found. \Cache::put('setup_db', true, config('df.default_cache_ttl')); return redirect()->to('/setup_db'); } catch (\Exception $ex) { throw $ex; } } } return $next($request); }
public function createFirstUser() { if (!User::adminExists()) { $request = \Request::instance(); $method = $request->method(); if (Verbs::GET === $method) { $data = ['version' => \Config::get('df.version'), 'email' => '', 'name' => '', 'first_name' => '', 'last_name' => '']; return view('firstUser', $data); } else { if (Verbs::POST === $method) { $data = $request->all(); $user = User::createFirstAdmin($data); if (!$user) { return view('firstUser', $data); } } } } return redirect()->to('/'); }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * * @return mixed */ public function handle($request, Closure $next) { $route = $request->getPathInfo(); if ('/setup' !== $route && '/setup_db' !== $route) { try { if (!User::adminExists()) { return redirect()->to('/setup'); } } catch (QueryException $e) { $code = $e->getCode(); if ($code === '42S02') { //Mysql base table or view not found. \Cache::put('setup_db', true, config('df.default_cache_ttl')); return redirect()->to('/setup_db'); } else { throw $e; } } } return $next($request); }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * * @return mixed */ public function handle($request, Closure $next) { $route = $request->getPathInfo(); if ('/setup' !== $route) { try { if (!User::adminExists()) { return redirect()->to('/setup'); } } catch (QueryException $e) { $code = $e->getCode(); if ($code === '42S02') { //Mysql base table or view not found. \Artisan::call('migrate'); \Artisan::call('db:seed'); return redirect()->to('/setup'); } else { throw $e; } } } return $next($request); }
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)); }
/** * Creates a non-admin user. * * @param array $data * * @return \DreamFactory\Core\Models\User * @throws \DreamFactory\Core\Exceptions\ForbiddenException * @throws \DreamFactory\Core\Exceptions\InternalServerErrorException * @throws \Exception */ public function create(array $data) { $userService = Service::getCachedByName('user'); if (!$userService['config']['allow_open_registration']) { throw new ForbiddenException('Open Registration is not enabled.'); } $openRegEmailSvcId = $userService['config']['open_reg_email_service_id']; $openRegEmailTplId = $userService['config']['open_reg_email_template_id']; $openRegRoleId = $userService['config']['open_reg_role_id']; /** @type User $user */ $user = User::create($data); if (!empty($openRegEmailSvcId)) { $this->sendConfirmation($user, $openRegEmailSvcId, $openRegEmailTplId); } else { if (!empty($data['password'])) { $user->password = $data['password']; $user->save(); } } if (!empty($openRegRoleId)) { User::applyDefaultUserAppRole($user, $openRegRoleId); } return $user; }
/** * @param $userId * @param bool|false $deleteOnError * * @throws \DreamFactory\Core\Exceptions\BadRequestException * @throws \DreamFactory\Core\Exceptions\InternalServerErrorException * @throws \DreamFactory\Core\Exceptions\NotFoundException * @throws \Exception */ protected static function sendInvite($userId, $deleteOnError = false) { /** @type BaseSystemModel $user */ $user = \DreamFactory\Core\Models\User::find($userId); if (empty($user)) { throw new NotFoundException('User not found with id ' . $userId . '.'); } if ('y' === strtolower($user->confirm_code)) { throw new BadRequestException('User with this identifier has already confirmed this account.'); } try { $userService = Service::getCachedByName('user'); $config = $userService['config']; if (empty($config)) { throw new InternalServerErrorException('Unable to load system configuration.'); } $emailServiceId = $config['invite_email_service_id']; $emailTemplateId = $config['invite_email_template_id']; if (empty($emailServiceId)) { throw new InternalServerErrorException('No email service configured for user invite.'); } if (empty($emailTemplateId)) { throw new InternalServerErrorException("No default email template for user invite."); } /** @var EmailService $emailService */ $emailService = ServiceHandler::getServiceById($emailServiceId); $emailTemplate = EmailTemplate::find($emailTemplateId); if (empty($emailTemplate)) { throw new InternalServerErrorException("No data found in default email template for user invite."); } try { $email = $user->email; $code = \Hash::make($email); $user->confirm_code = base64_encode($code); $user->save(); $templateData = $emailTemplate->toArray(); $data = array_merge($templateData, ['to' => $email, 'confirm_code' => $user->confirm_code, 'link' => url(\Config::get('df.confirm_invite_url')) . '?code=' . $user->confirm_code, 'first_name' => $user->first_name, 'last_name' => $user->last_name, 'name' => $user->name, 'email' => $user->email, 'phone' => $user->phone, 'content_header' => ArrayUtils::get($templateData, 'subject', 'You are invited to try DreamFactory.'), 'instance_name' => \Config::get('df.instance_name')]); } catch (\Exception $e) { throw new InternalServerErrorException("Error creating user invite. {$e->getMessage()}", $e->getCode()); } $emailService->sendEmail($data, $emailTemplate->body_text, $emailTemplate->body_html); } catch (\Exception $e) { if ($deleteOnError) { $user->delete(); } throw new InternalServerErrorException("Error processing user invite. {$e->getMessage()}", $e->getCode()); } }
/** * Changes password by security answer. * * @param $email * @param $answer * @param $newPassword * @param bool $login * * @return array * @throws BadRequestException * @throws InternalServerErrorException * @throws NotFoundException */ protected static function changePasswordBySecurityAnswer($email, $answer, $newPassword, $login = true) { if (empty($email)) { throw new BadRequestException("Missing required email for password reset confirmation."); } if (empty($newPassword)) { throw new BadRequestException("Missing new password for reset."); } if (empty($answer)) { throw new BadRequestException("Missing security answer."); } /** @var User $user */ $user = User::whereEmail($email)->first(); if (null === $user) { // bad code throw new NotFoundException("The supplied email and confirmation code were not found in the system."); } static::isAllowed($user); try { // validate answer $isValid = \Hash::check($answer, $user->security_answer); } catch (\Exception $ex) { throw new InternalServerErrorException("Error validating security answer.\n{$ex->getMessage()}"); } if (!$isValid) { throw new BadRequestException("The answer supplied does not match."); } try { $user->password = $newPassword; $user->save(); } catch (\Exception $ex) { throw new InternalServerErrorException("Error processing password change.\n{$ex->getMessage()}"); } if ($login) { static::userLogin($email, $newPassword); return ['success' => true, 'session_token' => Session::getSessionToken()]; } return ['success' => true]; }
/** * If does not exists, creates a shadow LDap user using user info provided * by the Ldap service provider and assigns default role to this user * for all apps in the system. If user already exists then updates user's * role for all apps and returns it. * * @param LdapUserContract $ldapUser * * @return User * @throws \Exception */ public function createShadowADLdapUser(LdapUserContract $ldapUser) { $email = $ldapUser->getEmail(); $serviceName = $this->getName(); if (empty($email)) { $uid = $ldapUser->getUid(); if (empty($uid)) { $uid = str_replace(' ', '', $ldapUser->getName()); } $domain = $ldapUser->getDomain(); $email = $uid . '+' . $serviceName . '@' . $domain; } else { list($emailId, $domain) = explode('@', $email); $email = $emailId . '+' . $serviceName . '@' . $domain; } $user = User::whereEmail($email)->first(); if (empty($user)) { $data = ['name' => $ldapUser->getName(), 'first_name' => $ldapUser->getFirstName(), 'last_name' => $ldapUser->getLastName(), 'email' => $email, 'is_active' => true, 'adldap' => $this->getProviderName(), 'password' => $ldapUser->getPassword()]; $user = User::create($data); } $defaultRole = $this->getDefaultRole(); User::applyDefaultUserAppRole($user, $defaultRole); return $user; }
protected function deleteUser($num) { $user = $this->{'user' . $num}; $email = Arr::get($user, 'email'); User::whereEmail($email)->delete(); }
/** * If does not exists, creates a shadow OAuth user using user info provided * by the OAuth service provider and assigns default role to this user * for all apps in the system. If user already exists then updates user's * role for all apps and returns it. * * @param OAuthUserContract $OAuthUser * * @return User * @throws \Exception */ public function createShadowOAuthUser(OAuthUserContract $OAuthUser) { $fullName = $OAuthUser->getName(); @(list($firstName, $lastName) = explode(' ', $fullName)); $email = $OAuthUser->getEmail(); $serviceName = $this->getName(); $providerName = $this->getProviderName(); $accessToken = $OAuthUser->token; if (empty($email)) { $email = $OAuthUser->getId() . '+' . $serviceName . '@' . $serviceName . '.com'; } else { list($emailId, $domain) = explode('@', $email); $email = $emailId . '+' . $serviceName . '@' . $domain; } $user = User::whereEmail($email)->first(); if (empty($user)) { $data = ['name' => $fullName, 'first_name' => $firstName, 'last_name' => $lastName, 'email' => $email, 'is_active' => true, 'oauth_provider' => $providerName, 'password' => $accessToken]; $user = User::create($data); } $defaultRole = $this->getDefaultRole(); User::applyDefaultUserAppRole($user, $defaultRole); return $user; }
/** * This method is used for staging the overall * test environment. Which usually covers things like * running database migrations and seeders. * * In order to override and run this method on a child * class, you must set the static::$staged property to * false in the respective child class. */ public function stage() { Artisan::call('migrate'); Artisan::call('db:seed'); Model::unguard(); // Add default admin user if (!User::exists()) { User::create(['name' => 'DF Admin', 'email' => '*****@*****.**', 'password' => 'Dream123!', 'is_sys_admin' => true, 'is_active' => true]); } }
/** * @return User|null */ public static function user() { if (static::isAuthenticated()) { return User::find(static::getCurrentUserId()); } return null; }
protected function deleteUser($num) { $user = $this->{'user' . $num}; $email = Arr::get($user, 'email'); \DreamFactory\Core\Models\User::whereEmail($email)->delete(); }
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)); }