public function login() { try { $user = Sentry::getUserProvider()->findByLogin(Input::json('email')); $throttle = Sentry::getThrottleProvider()->findByUserId($user->id); $throttle->setSuspensionTime(10); $throttle->setAttemptLimit(3); $throttle->check(); $credentials = ['email' => Input::json('email'), 'password' => Input::json('password')]; $user = Sentry::authenticate($credentials, false); } catch (Cartalyst\Sentry\Users\WrongPasswordException $e) { return Response::json(array('flash' => 'Invalid username or password'), 500); } catch (Cartalyst\Sentry\Users\LoginRequiredException $e) { return Response::json(array('flash' => 'Login field is required'), 500); } catch (Cartalyst\Sentry\Users\PasswordRequiredException $e) { return Response::json(array('flash' => 'Password field is required'), 500); } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) { return Response::json(array('flash' => 'Invalid username or password'), 500); } catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) { return Response::json(array('flash' => 'This account is inactive'), 500); } catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e) { $time = $throttle->getSuspensionTime(); return Response::json(array('flash' => 'This account is suspended for ' . $time . ' minutes'), 500); } catch (Cartalyst\Sentry\Throttling\UserBannedException $e) { return Response::json(array('flash' => 'This account has been banned'), 500); } $user_details = User::join('users_groups', 'users.id', '=', 'users_groups.user_id')->join('groups', 'users_groups.group_id', '=', 'groups.id')->where('users.id', '=', $user->id)->select('users.id', 'users.email', 'users.first_name', 'users.last_name', 'groups.name as role', 'users.activated_at', 'users.last_login', 'users.created_at', 'users.updated_at')->get(); return Response::json($user_details[0], 200); }
public function testUnbanUser() { // Find the user we are going to suspend $user = Sentry::findUserByLogin('*****@*****.**'); // Prepare the Throttle Provider $throttleProvider = Sentry::getThrottleProvider(); // Ban the user $this->repo->ban($user->id); // This is the code we are testing $result = $this->repo->unban($user->id); // Ask the Throttle Provider to gather information for this user $throttle = $throttleProvider->findByUserId($user->id); // Check the throttle status. This should do nothing. $throttle->check(); // Assertions $this->assertTrue($result->isSuccessful()); }
}); HTML::macro('loggedUserEmail', function () { $user = AuthMgr::getLoggedUser(); return $user['email']; }); HTML::macro('loggedUserGravatarImage', function ($alt = null, $attributes = []) { $logged_user = AuthMgr::getLoggedUser(); if (empty($logged_user)) { return null; } return Gravatar::image($logged_user->email, $alt, $attributes); }); /* |-------------------------------------------------------------------------- | Helper Functions |-------------------------------------------------------------------------- | | Include helper functions file | */ require_once 'helper_functions.php'; /* |-------------------------------------------------------------------------- | Enable Sentry Throttling |-------------------------------------------------------------------------- | | Enable throttling invalid login attempts | */ Sentry::getThrottleProvider()->enable();
public function actionLogin() { // instantitate the login tracker $userLogin = new Synergixe\Services\SSO\UserLoginSignOn(); // get the control point of Sentry 2 throttling functionality (Providers) $t_provider = Sentry::getThrottleProvider(); // enable login throttling... // a228b23ad9afe0151ca82dd721b77032c9983c37 $t_provider->enable(); // default results for validation $vld_result = FALSE; // placeholder for error reason {string} $vld_error = ""; // status of user login process.. $userLoginSuccess = FALSE; // sanitize form input values... $credentials = array('email' => Synergixe\StrRoutines::sanitize_input(Input::get('email'), Synergixe\StrRoutines::FILTER_AS_EMAIL), 'password' => Synergixe\StrRoutines::sanitize_input(Input::get('password'), Synergixe\StrRoutines::FILTER_SPECIAL_STR)); // santize 'remember_me' as boolean $remember = Synergixe\StrRoutines::sanitize_input(Input::has('remember_me'), Synergixe\StrRoutines::FILTER_AS_BOOLEAN); // setup validation rules... Synergixe\Services\Validation\PostDataValidator::resetRules(array('email' => 'required|email|min:5', 'password' => 'required|min:6')); // validate form input values... $validator = new Synergixe\Services\Validation\PostDataValidator($credentials); try { $validator->setValidationType('POSTDATA'); $vld_result = $validator->passes(); } catch (Exception $ex) { $vld_error = $ex->getMessage(); Log::error('Validator Internal Error: ' . $vld_error); // for debugging purposes... } if (!$vld_result) { // if we have validation errors... // we can't proceed beyond this point (however, report these back to the client) $userLogin->problemMessages["validation.problems"] = empty($validator->errors) ? array('auth.validation-error' => $vld_error) : $validator->errors; } else { // we don't have validation errors, so // setup throttling settings... (@chris, it would be nice if you found out ) $throttle = $t_provider->findByUserLogin($credentials['email'], Request::ip()); // Synergixe\App\Models\Throttle::with('user')->where('user_id', '=', $user->id); $throttle->setAttemptLimit(4); // 4 counts $throttle->setSuspensionTime(5); // 5 minutes try { // authenticate the user $user = Sentry::authenticate($credentials, $remember); // get the organization the user belongs to // --- This isn't important as this point! --- $org = Organization::where('id', '=', $user->organization_id)->firstOrFail(); // setup argument data for 'UserLoginSignOn' $specialData = array("backend_url" => Input::get('redirect_piece'), "secret_key" => Request::header('X-Authorize-Key')); if (is_object($user)) { $userLoginSuccess = $userLogin->trackLoginOnRequest($user, $specialData); } } catch (Exception $e) { $exception_class_name = get_class($e); // get the class name!! switch ($exception_class_name) { case "Cartalyst\\Sentry\\Users\\LoginRequiredException": case "Cartalyst\\Sentry\\Users\\PasswordRequiredException": case "Cartalyst\\Sentry\\Users\\WrongPasswordException": case "Cartalyst\\Sentry\\Users\\UserNotFoundException": case "Cartalyst\\Sentry\\Users\\UserNotActivatedException": case "Cartalyst\\Sentry\\Throttling\\UserSuspendedException": $userLogin->problemMessages["auth.problems"] = $e->getMessage(); break; default: $userLogin->problemMessages["auth.problems"] = 'Unknown Login Problem'; break; } $userLogin->recordThrottle($throttle); } } if ($userLogin->hasProblem) { Event::fire('synlogin.failure', $userLogin); // fire failure event and send details to server side logging point } else { Event::fire('synlogin.success', $userLogin); // fire success event and send details to server side logging point } $response = Response::make(json_encode($userLogin->toArray()), $userLogin->getTrackingCode()); $response->header('Content-Type', 'application/json'); if ($userLoginSuccess) { $response->header('X-Authorize-Value', $userLogin->getAuthorizeValue()); /*if($userLogin->isSigningSet()){ $response->withCookie($userLogin->getTrackingCookie()); }*/ } return $response; /*if (!Sentry::check()){ //checks if a user is logged in. $user_details= array('email'=>Input::get('email'), 'password'=>Input::get('password')); $remember_me= Input::has('remember_me'); if ($user_details) { try{ $userauth= Sentry::authenticate($user_details,$remember_me); $token= hash('sha256',Str::random(10),false); $userauth->api_token= $token; $userauth->save(); return Response::json(array('token'=>$token, 'userauth'=>$userauth->toArray())); } catch (Cartalyst\Sentry\Users\LoginRequiredException $e) { return Response::json(array('errorMessage'=>'Login Required!')); } catch(Cartalyst\Sentry\Users\UserNotFoundException $e) { return Response::json(array('errorMessage'=>'User Not Found!')); } catch(Cartalyst\Sentry\Users\UserNotActivatedException $e) { return Response::json(array('errorMessage'=>'User Not Activated!')); } }else{ return Response::json(array('errorMessage'=>'User Already Logged in!')); } }*/ }
public function __construct() { $throttleProvider = \Sentry::getThrottleProvider(); $throttleProvider->disable(); }
<?php /* |-------------------------------------------------------------------------- | Application & Route Filters |-------------------------------------------------------------------------- | | Below you will find the "before" and "after" events for the application | which may be used to do any work before or after a request into your | application. Here you may also register your custom route filters. | */ App::before(function () { $throttleProvider = Sentry::getThrottleProvider(); $throttleProvider->enable(); }); App::after(function () { if (Config::get('larapress.settings.log')) { Helpers::logPerformance(); } }); /* |-------------------------------------------------------------------------- | Special larapress Filters |-------------------------------------------------------------------------- | | The following filters are developed for larapress but may be also useful | for your website. You can apply them to any route you'd like. | */ Route::filter('force.human', 'Larapress\\Filters\\Special\\ForceHumanFilter');
public function createOAuthProfile($userProfile) { if (isset($userProfile->username)) { $username = strlen($userProfile->username) > 0 ? $userProfile->username : ""; } if (isset($userProfile->screen_name)) { $username = strlen($userProfile->screen_name) > 0 ? $userProfile->screen_name : ""; } if (isset($userProfile->displayName)) { $username = strlen($userProfile->displayName) > 0 ? $userProfile->displayName : ""; } $email = strlen($userProfile->email) > 0 ? $userProfile->email : ""; $email = strlen($userProfile->emailVerified) > 0 ? $userProfile->emailVerified : ""; $password = $this->generatePassword(); if (Profile::where('email', $email)->count() <= 0) { $user = Sentry::register(array('email' => $email, 'password' => $password), true); try { $user_group = Sentry::findGroupById(1); } catch (Cartalyst\Sentry\Groups\GroupNotFoundException $e) { $this->createGroup('users'); $this->createGroup('admin'); $user_group = Sentry::findGroupById(1); } $user->addGroup($user_group); $profile = new Profile(); $profile->user_id = $user->getId(); $profile->email = $email; $profile->username = $username; $profile->save(); } //Login user //Try to authenticate user try { $user = Sentry::findUserByLogin($email); $throttle = Sentry::getThrottleProvider()->findByUserId($user->id); $throttle->check(); //Authenticate user $credentials = array('email' => $email, 'password' => Input::get('password')); Sentry::login($user, false); //At this point we may get many exceptions lets handle all user management and throttle exceptions } catch (Cartalyst\Sentry\Users\LoginRequiredException $e) { Session::flash('error_msg', 'Login field is required.'); return Redirect::to('/login'); } catch (Cartalyst\Sentry\Users\PasswordRequiredException $e) { Session::flash('error_msg', 'Password field is required.'); return Redirect::to('/login'); } catch (Cartalyst\Sentry\Users\WrongPasswordException $e) { Session::flash('error_msg', 'Wrong password, try again.'); return Redirect::to('/login'); } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) { Session::flash('error_msg', 'User was not found.'); return Redirect::to('/login'); } catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) { Session::flash('error_msg', 'User is not activated.'); return Redirect::to('/login'); } catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e) { Session::flash('error_msg', 'User is suspended '); return Redirect::to('/login'); } catch (Cartalyst\Sentry\Throttling\UserBannedException $e) { Session::flash('error_msg', 'User is banned.'); return Redirect::to('/login'); } }
public function postSuspend($id) { // Gather Sanitized Input $input = array('suspendTime' => Input::get('suspendTime')); // Set Validation Rules $rules = array('suspendTime' => 'required|numeric'); //Run input validation $v = Validator::make($input, $rules); if ($v->fails()) { // Validation has failed return Redirect::to('users/suspend/' . $id)->withErrors($v)->withInput(); } else { try { //Prep for suspension $throttle = Sentry::getThrottleProvider()->findByUserId($id); //Set suspension time $throttle->setSuspensionTime($input['suspendTime']); // Suspend the user $throttle->suspend(); //Done. Return to users page. Session::flash('success', "User has been suspended for " . $input['suspendTime'] . " minutes."); return Redirect::to('users'); } catch (Cartalyst\Sentry\UserNotFoundException $e) { Session::flash('error', 'There was a problem accessing that user\\s account.'); return Redirect::to('/users'); } } }
public function throttle() { return Sentry::getThrottleProvider(); }
public function storeLogin() { $inputs = array('identity' => Input::get('identity'), 'password' => Input::get('password')); //Since user can enter username,email we cannot have email validator $rules = array('identity' => 'required|min:4|max:32', 'password' => 'required|min:6'); //Find is that username or password and change identity validation rules //Lets use regular expressions if (filter_var(Input::get('identity'), FILTER_VALIDATE_EMAIL)) { //It is email $rules['identity'] = 'required|min:4|max:32|email'; } else { //It is username . Check if username exist in profile table if (Profile::where('username', Input::get('identity'))->count() > 0) { //User exist so get email address $user = Profile::where('username', Input::get('identity'))->first(); $inputs['identity'] = $user->email; } else { Session::flash('error_msg', 'User does not exist'); return Redirect::to('/login')->withInput(Input::except('password')); } } $v = Validator::make($inputs, $rules); if ($v->fails()) { return Redirect::to('/login')->withErrors($v)->withInput(Input::except('password')); } else { try { //Try to authenticate user $user = Sentry::getUserProvider()->findByLogin(Input::get('identity')); $throttle = Sentry::getThrottleProvider()->findByUserId($user->id); $throttle->check(); //Authenticate user $credentials = array('email' => Input::get('identity'), 'password' => Input::get('password')); //For now auto activate users $user = Sentry::authenticate($credentials, false); //At this point we may get many exceptions lets handle all user management and throttle exceptions } catch (Cartalyst\Sentry\Users\LoginRequiredException $e) { Session::flash('error_msg', 'Login field is required.'); return Redirect::to('/login'); } catch (Cartalyst\Sentry\Users\PasswordRequiredException $e) { Session::flash('error_msg', 'Password field is required.'); return Redirect::to('/login'); } catch (Cartalyst\Sentry\Users\WrongPasswordException $e) { Session::flash('error_msg', 'Wrong password, try again.'); return Redirect::to('/login'); } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) { Session::flash('error_msg', 'User was not found.'); return Redirect::to('/login'); } catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) { Session::flash('error_msg', 'User is not activated.'); return Redirect::to('/login'); } catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e) { Session::flash('error_msg', 'User is suspended '); return Redirect::to('/login'); } catch (Cartalyst\Sentry\Throttling\UserBannedException $e) { Session::flash('error_msg', 'User is banned.'); return Redirect::to('/login'); } Session::flash('success_msg', 'Loggedin Successfully'); return Redirect::to('/'); } }
#app/config/administrator/users.php /** * Users model config */ return array('title' => 'Usuarios', 'single' => 'Usuario', 'model' => 'User', 'columns' => array('email' => array('title' => 'Email'), 'first_name' => array('title' => 'First Name'), 'last_name' => array('title' => 'Last Name'), 'banned' => array('title' => 'Banned', 'relationship' => 'throttle', 'select' => "IF((:table).banned = 1, 'yes', 'no')")), 'edit_fields' => array('activated' => array('title' => 'Activo?', 'type' => 'bool'), 'first_name' => array('title' => 'Nombre', 'type' => 'text'), 'last_name' => array('title' => 'Apellido', 'type' => 'text'), 'email' => array('title' => 'Dirección de Email', 'type' => 'text'), 'password' => array('title' => 'Password', 'type' => 'password')), 'permission' => function () { $user = Sentry::getUser(); return $user->hasAnyAccess(array('user.delete', 'user.view', 'user.update')); }, 'action_permissions' => array('create' => function ($model) { $user = Sentry::getUser(); return $user->hasAccess('user.create'); }, 'delete' => function ($model) { $user = Sentry::getUser(); return $user->hasAccess('user.delete'); }, 'update' => function ($model) { $user = Sentry::getUser(); return $user->hasAccess('user.update'); }), 'actions' => array('ban' => array('title' => 'Ban / Unban', 'messages' => array('active' => '...', 'success' => 'Done!', 'error' => 'There was an error'), 'permission' => function ($model) { $user = Sentry::getUser(); return $user->hasAccess('user.update'); }, 'action' => function ($model) { // Find the user using the user id $throttle = Sentry::getThrottleProvider()->findByUserId($model->id); if ($throttle->isBanned()) { // Unban the user $throttle->unBan(); } else { // Ban the user $throttle->ban(); } return true; })));
public function __construct() { // Get the Throttle Provider and Enable $throttleProvider = Sentry::getThrottleProvider(); $throttleProvider->enable(); }
public function action_login_complete($view = array('throttle' => '')) { if ($this->request->post() != null) { $view = array('throttle' => ''); try { $throttle_provider = Sentry::getThrottleProvider(); //if the login throttler is enabled set it up if (Kohana::$config->load('sentry.throttle') == true) { $throttle_provider->enable(); $throttle = $throttle_provider->findByUserLogin($this->request->post('email')); //set the limit of consecutive failed login attempts $throttle->setAttemptLimit(Kohana::$config->load('sentry.throttle_attempts')); //set the suspension time in minutes $throttle->setSuspensionTime(Kohana::$config->load('sentry.throttle_suspension_time')); } else { $throttle_provider->disable(); } $user = Sentry::getUserProvider()->findByCredentials(array('email' => $this->request->post('email'), 'password' => $this->request->post('password'))); // Log the user in if ($this->request->post('remember', false)) { Sentry::loginAndRemember($user); } else { Sentry::login($user, false); } //if the login throttler is enabled clear failed login attempts if ($throttle_provider->isEnabled()) { $throttle->clearLoginAttempts(); } Hint::set(Hint::SUCCESS, 'Welcome back!'); //everything went successful, send the user somewhere else $this->redirect(Route::url('S4K.users.login', null, true)); //@todo you'll probably rather send your user to a welcome page than back to the login } catch (Cartalyst\Sentry\Users\WrongPasswordException $e) { Hint::set(Hint::ERROR, 'You seem to have have provided an incorrect password.'); //if throttles are enabled add an attempt and show how many attempts are left if ($throttle_provider->isEnabled()) { $throttle->addLoginAttempt(); $view['throttle'] = $throttle->getLoginAttempts() . '/' . $throttle->getAttemptLimit() . ' attempts left.'; } } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) { Hint::set(Hint::ERROR, 'There\'s no user with that login.'); } catch (Cartalyst\Sentry\Users\LoginRequiredException $e) { Hint::set(Hint::ERROR, 'We need to know who\'s logging in.'); } catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) { Hint::set(Hint::ERROR, 'Your account hasn\'t been activated yet.'); } catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e) { $time = $throttle->getSuspensionTime(); Hint::set(Hint::ERROR, 'You have tried logging in too much, wait ' . $time . ' minutes before trying again.'); } catch (Cartalyst\Sentry\Throttling\UserBannedException $e) { Hint::set(Hint::ERROR, 'You are banned.'); } //No success signing in, show the form again with the errors $this->_tpl->hints = Hint::render(null, true, 's4k/hint'); $this->action_login($view); } else { // no post request made, send back $this->redirect(Route::url('S4K.users.login', null, true)); } }