What is the difference between "login" and "attempt" method in Auth - laravel

I'm learning Laravel 5.4 and customizing and making my original Auth functionalities.
The below is my "authenticate" method.
public function authenticate(Request $request)
{
$remember_me = (Input::has('remember')) ? true : false;
Auth::guard('web');
$this->validateLogin($request);
$credentials = array(
'username' => trim($request->input('username')),
'password' => trim($request->input('password'))
);
if(Auth::attempt($credentials, $remember_me)){
$user = Auth::guard('web')->user();
Auth::guard('web')->login($user, $remember_me);
return redirect()->route('mypage');
}
return redirect()->back();
}
I have a question about the part of $remember_me argument about both attempt and login methods noted above.
What is the difference between them?
When I saw the documentation, it said similar to, if you want to make "remember me" token, you can set the second boolean argument about both of them.

attempt($credentials, $remember_me) will attempt to log the user in if the login credentials are correct. If they are not, then the user is not logged in. This method returns a boolean so you can check success.
login($user_id, $remember_me) will log the user in, without checking any credentials.
The remember me specifys if the user login should persist across browser sessions without needing to re-auth.
In your example I see your calling login(...) within your attempt(...). This shouldn't be needed. You can remove the login(...) line.
Example:
if(Auth::attempt($credentials, $remember_me)){
return redirect()->route('mypage');
}

Related

Create session on consuming login with api on laravel

I have an api that has a method to start and I am calling it from a frontend project.
In the front end project I use Guzzle to make the call via post to the api and login, from which I get back a json with the user data and a jwt token.
But when I receive the token as I manage the session, I must create a session and save the token, since the laravel to authenticate I need a model user and have a database, which of course I do not have in this backend because I call the api to log in, which brings a token and user data, then as I manage it from the backend, I'm a little lost there.
$api = new Api();
$response = $api->loginapi(['user'=>'wings#test.com','password'=>'123']);
Because here I could not do Auth::login($user) to generate the session.
Because I don't have here the database because the login is done from the api.
There I call the api, of which the answer is the token, but how do I manage it from here, creating a session? saving the token?
thanks for your help.
With api, you don't usually manage a session. usually, you'd call something like
Auth::attempt([
'email' => 'me#example.com',
'password' => 'myPassword'
]);
If the credentials are correct, laravel will include a Set-Cookie header in response, and, that is how you authenticate with api. Via an auth cookie. You don't need to do anything else.
Let's show you how:
//AuthController.php
public function login(Request $request) {
$validatedData = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if(Auth::attempt($validatedData)){
return ['success' => 'true'];
}
else{
return ['success' => false, 'message' => 'Email or password Invalid'];
}
}
public function currentUser (){
return Auth::user();
}
Now, the APi file
Route::post('/login', ['App\Http\Controllers\AuthController', 'login']);
Route::get('/current_user', ['App\Http\Controllers\AuthController', 'currentUser']);
Now if you make a call to /api/current_user initially, you'll get null response since you're not currently logged in. But once you make request to /api/login and you get a successful response, you are now logged in. Now if you go to /api/current_user, you should see that you're already logged in.
Important ::
If you are using fetch, you need to include credentials if you're using something other than fetch, check out how to use credentials with that library or api
You want to use the API to authenticate and then use the SessionGuard to create session including the remember_me handling.
This is the default login controller endpoint for logging in. You don't want to change this, as it makes sure that user's do not have endless login attempts (protects for brut-force attacks) and redirects to your current location.
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if (method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
if ($request->hasSession()) {
$request->session()->put('auth.password_confirmed_at', time());
}
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
The core happens when we try to "attemptLogin" at
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->boolean('remember')
);
}
When using the SessioGurad (which is default) the method attemptLogin fires a couple of events, checks if the user has valid credentials (by hashing the password and matching it with db) and then logs the user in, including the remember me functionality.
Now, if you don't care about events, you can just check from your API if the credentials match and then use the login method from the guard. This will also handle the remember me functionality. Something like this:
protected function attemptLogin(Request $request)
{
$username = $request->input($this->username());
$password = $request->input('password');
$result = \Illuminate\Support\Facades\Http::post(env('YOUR_API_DOMAIN') . '/api/v0/login' , [
'username' => $username,
'password' => $password
])->json();
if(empty($result['success'])){
return false;
}
// Maybe you need to create the user here if the login is for the first time?
$user = User::where('username', '=', $username)->first();
$this->guard()->login(
$user, $request->boolean('remember')
);
return true;
}

Custom login property Laravel 8

I have this custom function for atempting to login in Laravel 8
protected function attemptLogin(Request $request)
{
$credentials = $this->credentials($request);
$credentials['estado']=1;
return $this->guard()->attempt(
$credentials, $request->filled('remember')
);
}
How I can make to accept the login atempt when $credentials['estado'] also has 2 as value.
Don't know how to make it accept multiple values.
I managed to make the custom function accept the value of 1 but dunno how to make it accept multiple $credentials['estado'] values.
You don't need to change anything in attemptLogin() method, instead you can customize the crededentials() method in LoginController like this:
// login, if user have like a following described data in array
protected function credentials(Request $request)
{
$username = $this->username();
return [
$username => $request->get($username),
'password' => $request->get('password'),
'estado' => [ 1, 2 ], // OR condition
];
}
Answer for comments:
Honestly in my experience I didn't have that case, but if you want to redirect to the another view on failed login (for specific field 'estado'), you can customize the "sendFailedLoginResponse" method, and add some additional if-condition for checking the 'estado'.
As the "sendFailedLoginResponse" method will be called only for getting failed login response instance, then you can check: is that fail comes from 'estado' field actually. Something like this:
protected function sendFailedLoginResponse(Request $request)
{
// custom case, when login failed and estado is 2
if ($request->get('estado') == 2) {
return view('some.specific.view');
}
// laravel by default implementation
else {
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
}
Remember, in this case (when we're redirecting the user to some page) we actually not redirecting as for always, but instead we're just returning a view. We do that because I think you don't want to let the users to open that specific view page anytime their want, as you need to let them see that page only for specific case. But when you'll do the actual redirect, then you will let the users to visit that page with some static URL.
Of course, you can do some additional stuff (add something in DB or the Session, and check is the request comes actually from 'estado' fails, but not from any user), but this could be a headeche for you, and in my opinion that will not be a real laravel-specific code.
Anyway, this is the strategy. I don't think, that this is mandatory, but this can be do your work easy and secure.
Note: I've got this deafault implementations from "AuthenticatesUsers" trait (use use Illuminate\Foundation\Auth\AuthenticatesUsers;). In any time you can get some available methods from there and override them in your LoginController, as the LoginController used that as a trait.

Unwanted validation rule being applied on password reset

I'm trying to use the password reset ability of Laravel's authentication. After running make:auth command, inside my ResetPasswordController, I have overridden rules function of Illuminate\Foundation\Auth\ResetsPasswords trait as the following:
protected function rules()
{
return [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:4',
];
}
So, I am trying to change the minimum length value to 4. But when I try to reset my password, a rule of minimum of 8 characters is still being applied instead of 4.
Here is the reset function of laravel in the same file:
public function reset(Request $request)
{
$request->validate($this->rules(), $this->validationErrorMessages());
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($request, $response)
: $this->sendResetFailedResponse($request, $response);
}
And the $response being returned is Illuminate\Support\Facades\Password::INVALID_PASSWORD. I don't understand where this rule is coming from.
Actually the validation behavior is like this: When I enter less than 4 characters, my own rule is applied (correctly). However, entering 4 to less than 8 characters is also an error by some other rule.
The reason that you're getting the error back is because the PasswordBroker expects a password with a minimum length of 8 characters so even though your form validation is passing, the validation in the PasswordBroker isn't.
One way to get around this would be to override the broker() method in your ResetPasswordController and pass your own validator to it:
public function broker()
{
$broker = Password::broker();
$broker->validator(function ($credentials) {
return $credentials['password'] === $credentials['password_confirmation'];
});
return $broker;
}
The above is essentially the same as what's going on in the PasswordBroker itself, just without the string length check as well.
Don't forget to import the Password facade into your controller:
use Illuminate\Support\Facades\Password;
This isn't essential, but for good measure I would then suggest updating the password error message in your resources/lang/en/passwords.php file as well.

Laravel 5.4 show activation pending message on login form

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());
}

Laravel auth loses session after redirect

Due to laravel's default auth system not working for my current project I used their manual authentication system. The authenticating works but after I redirect the authentication gets destroyed or it simply isn't getting stored properly.
My authController:
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
class manualAuthController extends Controller {
public function authenticate(){
if (Auth::attempt(['email' => $_POST['email'], 'password' => $_POST['password']])) {
// Authentication passed...
$user = Auth::user();
//return '$user';
return redirect("test2");
}
return 'Auth failed!';
}
}
My route to test if the authenticated user is still stored:
Route::get('test2', function(){
echo 'test2<br>';
$user = Auth::user();
echo $user;
return '.';
});
If I uncomment "return '$user';" then the authenticated user gets returned properly.
I know that this question has been asked before but I couldn't find anybody with a working/ reliable solution to this problem so can someone here please help me with this problem(or finding the exact problem)?
Side note: I previously used the Socialite system which we had to switch for the laravel auth due to hosting problems. After this switch it worked in development for a while with my current session and db settings. Due to some other bugs I switched to manual authentication.

Resources