Always remember users in Laravel - laravel

How could I make it so that in my laravel sign in controller, users are always remembered?
I tried making $remember_me = 1
but that doesn't seem to work.
Controller:
public function postSignin(Request $request, AppMailer $mailer) {
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
$username = $request->get('email');
$password = $request->get('password');
$field = filter_var($username,FILTER_VALIDATE_EMAIL)? 'email': 'username';
Auth::attempt([$field => $username, 'password' => $password], true);
return redirect()->back()->with('info', 'You are now signed in.');
}
Start of Home controller:
public function getIndex() {
if (Auth::check()) {
if (Auth::viaRemember()) {
dd('test');
}
Edit: I changed the code a bit to explain why the current answer isn't working for me.

You may pass a boolean value as the second argument to the attempt method, which will keep the user authenticated indefinitely, or until they manually logout. Of course, your users table must include the string remember_token column, which will be used to store the "remember me" token.
if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
// The user is being remembered...
}
If you are using the built-in LoginController that is shipped with
Laravel, the proper logic to "remember" users is already implemented
by the traits used by the controller.
If you are "remembering" users, you may use the viaRemember method to determine if the user was authenticated using the "remember me" cookie:
if (Auth::viaRemember()) {
//
}
EDIT :
Check your config/session.php setting:
'lifetime' => 10080,
'expire_on_close' => true,
Just set your expire_on_close to true
Hope this helps you!

Related

Laravel 5.4 Can't login the user

When I register new User, it logs in, but when I logout and try to login it just redirects me back to login page with custom error message 'Check your credentials again'. I can't figure out what's wrong.
First you are not hashing the password. In RegistrationController change your store() function like this.
use Hash;
class RegistrationContoller extends Controller
{
...
public function store()
{
...
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password) //<-- you were missing this.
]);
}
}

Can Laravel Auth::attempt() handle relationships?

I'm using entrust for managing role based permissions in Laravel 5.3, and naturally using manual/custom logins for different user types. Is it possible for Auth::attempt() to handle foreign table relationships? Basically, I want to do something like this:
if(Auth::attempt(['email' => $request->email, 'password' => $request->password, hasRole('teacher') => true])) {
return redirect()->intended('teacher/dashboard');
}
But I keep getting the error that hasRole() is an undefined function. I have included use Zizaco\Entrust\Traits\EntrustUserTrait; and use EntrustUserTrait;, which I thought would provide me with access to the function, but apparently not.
I appreciate the fact that hasRole() is a method for user objects, and at the time of checking I don't have a user object but I can't do a role check after attempt has succeeded because then the user has already been logged in, and if the role was wrong I would need to log them out as their credentials are correct, but not for the role; which seems slow and not pragmatic.
How should I go about handling this? Is there an alternative to Auth::attempt that I can use that will not log in the user, but check the user exists with specified input, and then run the role check, and then use another function to start an authenticated session?
If useful my LoginController is here:
<?php
namespace App\Http\Controllers\Teacher;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Validator;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class LoginController extends Controller {
use EntrustUserTrait;
public function showLoginForm() {
return view('teacher/login');
}
public function authenticate(Request $request) {
Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
])->validate();
if(Auth::attempt(['email' => $request->email, 'password' => $request->password, hasRole('teacher') => true])) {
return redirect()->intended('teacher/dashboard');
}
return redirect('admin/login')->with('invalid', 'Invalid username or password');
}
}
Any help or direction would be much appreciated. Thanks.
what you can do is:
if(Auth::attempt(['email' => $request->email, 'password' => $request->password)) {
if($user = Auth::user()->hasRole('teacher')) {
return redirect()->intended('teacher/dashboard');
} else {
return redirect()->intended('teacher/dashboard');
}
}
so this is what I did on login check role
$user = User::whereEmail($request->email)->first();
// I added this is because the customer
// are not suppose to login from here
if(!$user || $user->hasRole(['customer'])){
return $this->sendFailedLoginResponse($request);
}
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
then if you wanna to change the route base on user role you can try to replace the redirectPath method by simply
public function redirectPath()
{
$user = Auth::user();
if($user->hasRole(['admin', 'system_admin']))
return '/backend';
elseif($user->hasRole(['teacher']))
return '/teacher';
}
I ended up manually doing the authentication check and using Auth::login($user) to create the authenticated session. This way the user was only logged in provided they met the role requirements for the specific login portal and controller.
public function authenticate(Request $request) {
Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
])->validate();
$user = User::where('email', $request->email)->first();
if($user) {
if(Hash::check($request->password, $user->password) && $user->hasRole('teacher')) {
Auth::login($user);
return redirect()->intended('teacher/dashboard');
}
}
return redirect('teacher/login')->with('invalid', 'Invalid username or password');
}

Laravel user update problems

Will try make this clear as much as I can.
Im rolled out a make Auth call in order to use the login and registeration function of laravel and later just used the template to provide the needs I wanted that is.
If user is admin he/she can register a new user.
public function openNewUser(){
return view('auth.register');
}
NB. Part for update.
public function registerNewUser(Request $request){
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:120',
'password' => 'required|min:4|confirmed']);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = encrypt($request->password);
if (Gate::denies('register-user')) {
return redirect()->back();
}
$user->save();
return view('home');
}
Problem 1 - I also want to update user , which is giving problems. The password inputs return empty fields , which i understand. When I try to change it doenst work the confirm password always give a mismatch even though they are the same. When I leave it blank too it doesnt work because the field is required to be filled. I took them off the form and tried if i could edit the email only but only didnt work.
public function userUpdate (Request $request,$user_id) {
$this->validate($request,[
'email' => 'required|email',
'name' => 'required|max:120',
'password' => 'required|min:4|confirmed']);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = encrypt($request->password);
if (Gate::allows('register-user')) {
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('view_users');
}elseif (Gate::denies('register-user')) {
if (Auth::id() == $user_id) {
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('view_users');
}else{
return redirect()->back();
}
}
}
Problem 2. I just realized all logins I am doing with my new registration gives These credentials do not match our records.Even though the credentials are there and was registered correctly.
I am using the login provided by laravel but I created my own registration.
Please how can I edit and update my users and also be able to login after registration
What version of Laravel are you using?
Here is my (v5.3) register() method in RegisterController.php, at least part for registration:
public function register(Request $request)
{
...
// save and login user
$user = $this->create($request->all());
$this->guard()->login($user);
...
}
...
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'lastname' => $data['lastname'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
and the login() method from LoginController.php
public function login(Request $request)
{
$credentials = $this->credentials($request);
...
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
}
Hopefully I haven't miss anything.
Keep in mind that things have changed here from version 5.2.
I found out what was wrong , Since I am using Laravel's login my registration had to use bycrypt for the encryption which is what Laravel registration was using , but I was using encrypt when I created my own registration so there was a conflict when logging in. (Remembere I was using Laravels login not my own written Login). I hope this helps someone

custom authenticate and password encryption laravel 5

Currently, i'm working a laravel 5 project.
I want to use my custom encryption for passwords, so I made a function, and i try to use it.
First, I override the postLogin function, and I added the new password Encryption.
public function postLogin(Request $request)
{
$email = $request->get('email');
$password = $this->hashPassword($request->get('password'));
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
// 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.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
$credentials = ['email' => $email, 'password' => $this->hashPassword($password)];
if (Auth::attempt(['email' => $email, 'password' => $this->hashPassword($password)])) {
// Authentication passed...
return $this->handleUserWasAuthenticated($request, $throttles);
}
// 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.
if ($throttles) {
$this->incrementLoginAttempts($request);
}
return redirect($this->loginPath())
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
As you can see in the code, I called the function hashPassword, and that works, but the problem is that "Auth::attempt" returns false always, despite I have the user in my database, with the right data.
Any solution please?
Thanks a lot
Kind Regards
try keeping the name ok password field other than 'password' such as 'mypass' or sth else.. auth automatically hashes the value you provide with password key.
You have to provide plain text password:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/**
* Handle an authentication attempt.
*
* #return Response
*/
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
}
Here is official reference:
https://laravel.com/docs/5.6/authentication#included-authenticating
I found a solution !!!
I changed "attempt" with "login", and it works well now :D
Thanks guys

Laravel 5 auth always results false?

Here its my controller for logging in. the register controller works well, it creates an user to database but when i try to log in with it fails it results always false pls help.
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
class loginController extends Controller
{
public function login(Request $request)
{
$_email = $request->input('emaillogin');
$_password = $request->input('passwordlogin');
if (Auth::attempt(['email' => $_email, 'password' => $_password])) {
Auth::login(Auth::user());
return redirect()->intended('/dashboard');
}
else {
return redirect()->intended('/');
}
}
}
Auth::attempt logs user into your application if passed, no need for second authentication
if (Auth::attempt(['email' => $_email, 'password' => $_password])) {
return redirect()->intended('/dashboard');
} else {
return redirect()->guest('/login');
}
As i said in the comment and i just tested it on my local pc, maybe it's wrong to you but for me it doesn't work if i use plain password save in database, here's my register file
protected function create(array $data)
{
$activation_code = str_random(60);
$user = User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'activation_code' => $activation_code
]);
if ($user->save()) {
$data = array(
'name' => $user->username,
'code' => $activation_code,
);
\Mail::queue('emails.activate', $data, function($message) use ($user) {
$message->to($user->email)->subject('Thank you for registering. Please activate your account!');
});
}
return $user;
}
you see i have crypted password
'password' => bcrypt($data['password']),
and if i test it just with:
'password' =>$data['password'],
The registration works but authentication fails because password must be encripted you should also remove Auth::login(Auth::user()); that is not necessary
if (Auth::attempt(['email' => $_email, 'password' => $_password])) {
return redirect()->intended('/dashboard');
}
This happens on my site when i don't use bcrypt on password in registration controller and try to login later
Whoops! There were some problems with your input.
These credentials do not match our records.
Also what i have seen from our login form inputs are not emaillogin and passwordlogin they are just email and password

Resources