I am using laravel 4 auth component in my application. I want to know is there a way to activate and deactivate user with auth inbuilt function . I have an application in codeigniter here user is activates as :
if ($this->ion_auth->is_admin()) {
$activation=$this->ion_auth->activate($userId);
}
Please tell me if laravel auth provides similar inbuilt activate function or not . And also what would be the best way to do this usng auth .
I have a field 'active' in my user table .
By default, Laravel Auth do not have any function to activate an user. However, you can do it manually:
For example:
$user = User::find($userId);
$user->activate = 1;
$user->save();
or if you have only email:
$user = User::where('email', $email)->first();
$user->activate = 1;
$user->save();
Authenticating A User With Conditions: Authenticate user if activated.
if (Auth::attempt(array('email' => $email, 'password' => $password, 'active' => 1)))
{
// The user is active, not suspended, and exists.
}
Third party package:
if you want full authenticating features, you can use Sentry.
https://cartalyst.com/manual/sentry/introduction
Activate user using Sentry:
https://cartalyst.com/manual/sentry/users/activate
Related
I'm developing a module with Laravel 5 inside an external system, the external system has its own login and data in another DB, then I had to implement permissions into my Laravel module, so I had to configure a Middleware in the routes, and now i get 2 login screens, I just need to log into Laravel using the external system, i created the same credentials in laravel's user table, so i want to check external username against laravel username, get the password and auto-login into laravel.
where to do this is the main problem i face.
I need this screen to autologin
Routes middleware:
Route::group(['middleware' => ['role:admin,access_backend']], function(){
Route::get('dashboard', 'dashboardController#dashboard');
.....
.....
I Get username from external system using guzzle
$client = new Client(); //GuzzleHttp\Client
$result = $client->get($url);
$body = (string)$result->getBody();
this is what i'm trying in role middleware:(guess it fails with the password hash , i always get the login screen)
$resp = User::select('username','password')->where('username',trim($body))->first();
$password = (bcrypt($resp->password));
if (Auth::attempt(['username' =>$resp->username, 'password' => $password])){
dd('Hello world');
return redirect()->intended('dashboard');
/* ->route('admin/dashboard')
->with('Welcome! Your account has been successfully created!'); */
}
if (Auth::guest()) {
return redirect(url(config('backpack.base.route_prefix').'/login'));
}
I am working on Laravel 5.4 project. I love the login provided by Laravel and it works fine with both login or register.
I add below code to Auth/LoginController.php. It allows only activated users (status=1) to successfully login, but not pending users or blocked users (status =0 or something else).
protected function credentials(\Illuminate\Http\Request $request)
{
return ['email' => $request->{$this->username()}, 'password' => $request->password, 'status' => 1];
}
Anyway, to protect spam I would like to allow only activated users to login. For those whose account are not activated, I would like to show the pending message on the login form. Also, I would like to do the same thing for blocked users.
Could you please advise me how to achieve this?
This way Laravel would only pick only users by the credentials you specify, if you want to check status the user has and what view to show you can overwrite the authenticated() method of the login controller. It will have access to the already logged in user so note that you have to logout it the status is invalid.
protected function authenticated(Request $request, $user)
{
if ( $user->status == 0 ) {
auth()->logout();
return back()->withErrors(['email' => 'You are blocked or not activated.']);
}
return redirect()->intended($this->redirectPath());
}
I am using Laravel and Stormpath for User Management. I am able to register and login user successfully using AJAX.
After successful login only the url is returned to AJAX, but after login when I go to User specific pages I am not able to fetch User Data.
Registration and Login happens in RegisterController
User Pages are rendered using UserController
I've tried to get User data using
$user = app('stormpath.user');
in UserController, but when I do dd($user) null is returned.
How to persist or get User Data after successful login or sign-up in other Controllers?
Any help appreciated! Thanks in advance!
For the Stormpath Laravel integration, when you run AJAX calls, we do not set any cookies. We provide you with the JWT in the header response that you will need to look at and then store them youself. The JWT will then need to be attached to all other requests as a Bearer token which will allow you to use the `$user = app('stormpath.user') method to get the user information out of the JWT.
I finally got everything working. Thank you #bretterer
// Stormpath user account creation
\Stormpath\Client::$apiKeyProperties = "apiKey.id="
.env('STORMPATH_CLIENT_APIKEY_ID').
"\napiKey.secret=".env('STORMPATH_CLIENT_APIKEY_SECRET');
$client = \Stormpath\Client::getInstance();
$apps = $client->tenant->applications;
$apps->search = array('name' => 'My Application');
$application = $apps->getIterator()->current();
$account = \Stormpath\Resource\Account::instantiate(
[
'givenName' => $request->input('username'),
'middleName' => '',
'surname' => 'StromTrooper',
'username' => $request->input('username'),
'email' => $request->input('user_mail'),
'password' => $request->input('user_pass'),
'confirmPassword' => $request->input('user_pass')
]
);
// Create User Account and Log-in the User
try
{
$response = $application->createAccount($account);
$passwordGrant = new \Stormpath\Oauth\PasswordGrantRequest(
$request->input('user_mail'),
$request->input('user_pass')
);
$auth = new \Stormpath\Oauth\PasswordGrantAuthenticator($application);
$result = $auth->authenticate($passwordGrant);
$atoken = cookie("access_token",
$result->getAccessTokenString(),
$result->getExpiresIn()
);
$rtoken = cookie("refresh_token",
$result->getRefreshTokenString(),
$result->getExpiresIn()
);
$response_bag['success'] = url('userprofile');
}
catch (\Stormpath\Resource\ResourceError $re)
{
$response_bag['error'] = $re->getMessage();
$atoken = 'null';
$rtoken = 'null';
}
return response()
->json($response_bag)
->withCookie($atoken)
->withCookie($rtoken);
and in the User controller I am able to access the user details using app('stormpath.user');
and since I was using Laravel 5.1
I had to comment out $token = $request->bearerToken(); from vendor/stormpath/laravel/src/Http/Middleware/Authenticate.php from function public function isAuthenticated(Request $request)
I have a Laravel app that currently uses the built-in authentication system to determine who is logged in or not logged in. The built-in authentication uses a session based system. I am transitioning to a custom authentication system that uses random tokens stored either in local storage or cookies to determine user identity.
I am currently using the following:
public function auth{
$user = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'active' => 1
);
if(Auth::attempt($user, true)){
$userId = Auth::id();
$salt = $customGenerator->generateSalt();
$userToken = $customGenerator->generateTokenAndSaveInDB($userId, $salt);
// Can I also sent $userToken to index.welcome to store in localStorage?
return Redirect::route('index.welcome');
}
else{
return Redirect::route('index.failed');
}
}
The above will redirect the user to a specific page if their credentials were valid. I would also like to have $userToken be sent to this new page so I can store it in the client's local storage.
Is this possible with Laravel?
can you try
return Redirect::route('index.welcome', array('userToken' => $userToken));
Laravel Forum
It is possible to create user from Admin panel, by administrator without password? I imagine follow procedure:
Administrator create user without password
User get email with instruction for entering password and activation account
User can register with email and his password
I don't think so. That's why when I create my users I generate a random password.
$user->password = str_shuffle("Random_Password"); // generate random initial password
I have done this before by hacking the 'forgotten password' functionality of Laravel (rather that reinventing the wheel). I can't say how well this fits into Sentry but it was pretty trivial to do it in plain old Laravel:
Create user with blank password
Add an entry into the password reminders table (manually, don't use Auth::remind or whatever it is as it'll send an email, but do use the code from the class to generate the token)
Send welcome email to user with link to /user/confirm (or whatever, the point is that it doesn't have to be /user/forgotten-password) and hook that route up in the normal way for forgotten password with an added check for $user->password == '' if you wanna make sure only unconfirmed people can go to that page (not that it really matters).
You may also wish to extend the timeout on the forgotten passwords or, as I did (proper hacky I know), when the user's in the /user/confirm version of the forgotten password functionality, just refresh the timeout in the table before passing through to Laravel's auth system for checking.
Our code is something like this:
On register:
// however you register the user:
$user = new User;
$user->email = Input::get('email');
$user->password = '';
$user->save();
// create a reminder entry for the user
$reminderRepo = App::make('auth.reminder.repository');
$reminderRepo->create($user);
Mail::send(
'emails.registered',
[
'token' => $reminder->token,
],
function ($message) use ($user) {
$message->to($user->email)->setSubject(Lang::get('account.email.registered.subject', ['name' => $user->name]));
}
);
Now the confirm link:
class AccountController extends Controller
{
public function confirm($token)
{
$reminder = DB::table('password_reminders')->whereToken($token)->first();
if (! $reminder) {
App::abort(404);
}
// reset reminder date to now to keep it fresh
DB::table('password_reminders')->whereToken($token)->update(['created_at' => Carbon\Carbon::now()]);
// send token to view but also email so they don't have to type it in (with password reminders it's is a good thing to make users type it, but with confirm account it feels weird)
return View::make('account.confirm-account')->withToken($token)->withEmail($reminder->email);
}
public function postConfirm($token)
{
$credentials = Input::only('email', 'password', 'password_confirmation', 'token');
$response = Password::reset($credentials, function ($user, $password) {
$user->password = $password;
$user->save();
});
switch ($response) {
case Password::INVALID_PASSWORD:
case Password::INVALID_TOKEN:
case Password::INVALID_USER:
return Redirect::back()->withInput()->with('message-error', Lang::get($response));
case Password::PASSWORD_RESET:
Auth::login(User::whereEmail(Input::get('email'))->first());
return Redirect::route('account.home')->with('message-info', Lang::get('messages.confirm_account.succeeded'));
}
}