Laravel Auth::attempt() fails - laravel

When I register a new user and I want to sign him in by using auth attempt it doesn't work while the user is saved to database
static function register()
{
if(self::$validate['message'])
{
$user = User::create([
'name' => self::$values['name'],
'email' => self::$values['email'],
'password' => Hash::make(self::$values['password'])
]);
Auth::attempt($user,true);
Auth::attempt($user->only(['email','password']));
return result::repsonse(true);
} else
return self::$validate;
}

You can use Auth::login() method
static function register()
{
if(self::$validate['message'])
{
$user = User::create([
'name' => self::$values['name'],
'email' => self::$values['email'],
'password' => Hash::make(self::$values['password'])
]);
Auth::login($user);
return result::repsonse(true);
} else
return self::$validate;
}

Related

How to log in a user with custom guard in Laravel within a controller

I have a custom guard set up for 'customer' which has a LoginController that works absolutely fine. The login controller is as follows:
public function login(Request $request)
{
// Validate form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
// Attempt to log the user in
if(Auth::guard('customer')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember))
{
return redirect()->intended(route('customer.dashboard'));
}
// if unsuccessful
return redirect()->back()->withInput($request->only('email','remember'))
}
Now, within my workflow in another route where I check out customers; I have another controller where I create a new customer. I then attempt to log them in since I have all their details, this doesn't seem to work, does anyone have any idea on what I am doing wrong?
public function registerCustomer($data)
{
$pw = Hash::make($data->pw->main);
$customer = new Customer;
$customer->firstname = $data->customer->name;
$customer->lastname = $data->customer->lastname;
$customer->mobile = $data->customer->mobile;
$customer->email = $data->customer->email;
$customer->password = $pw;
$customer->save();
//I HAVE TRIED THIS
// if(Auth::guard('customer')->attempt(['email' => $data->customer->email, 'password' => $pw]))
// {
// dd('logged in');
// }
//AND NOW THIS...
$logged = Auth::guard('customer')->attempt([ 'email' =>$data->customer->email, 'password' => $pw ]);
dd($logged);
}
In registerCustomer function, $pw is an encrypted password. You could not use it for Auth::guard('customer'). You have to replace $pw by $data->pw->main.
$logged = Auth::guard('customer')->attempt([ 'email' =>$data->customer->email, 'password' => $data->pw->main ]);
dd($logged);

Auth::attempt value always false

I have some problem when I want to make login, I got an issue for my Auth::attempt always false value, Is am I got something wrong in my code?
Controller :
public function register(Request $register)
{
$validator = Validator::make($register->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
} else {
$name = $register->input('name');
$email = $register->input('email');
$pwd = $register->input('password');
$c_pwd = $register->input('c_password');
// Crypting password & c_password to md5
$md5_pwd = md5($pwd);
$md5_c_pwd = md5($c_pwd);
// Salt password & c_password
$password = crypt($md5_pwd, "asd");
$c_password = crypt($md5_c_pwd, "asd");
$data = new User();
if ($password == $c_password) {
$user = User::create([
'name' => $name,
'email' => $email,
'password' => $password,
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json(['error' => "Password doesn't match"], 401);
}
}
}
public function login()
{
$email = request('email');
$pwd = request('password');
$md5 = md5($pwd);
$password = crypt($md5, "asd");
if (Auth::attempt(['email' => $email, 'password' => $password])) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
}
I assume you messed up with Laravel Default Password Hashing System
public function register(Request $register)
{
$validator = Validator::make($register->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
} else {
$name = $register->input('name');
$email = $register->input('email');
$pwd = $register->input('password');
$c_pwd = $register->input('c_password');
// $data = new User();
$user = User::create([
'name' => $name,
'email' => $email,
'password' => bcrypt($password . 'salt'),
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
}
}
public function login()
{
$email = request('email');
$pwd = request('password');
if (Auth::attempt(['email' => $email, 'password' => $password . 'salt'])) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
}
Try this code. I don't know what happened to your code about the password you tried to encrypt it in attempt.
public function login(LoginRequest $request) {
if(!Auth::attempt([
'email' => $request->email,
'password' => $request->password,
'active' => true
])) {
return response()->json('Email or Password is incorrect', 500);
}
$this->user = Auth::user()->load('roles');
return $this->createUserAccessTokenResponse();
}
protected function createUserAccessTokenResponse() {
return response()->json([
'status' => 'success',
'data' => [
'token' => $this->user->createToken($this->user->name)->accessToken,
'user' => $this->user
],
], 200);
}
your problem is that laravel by default hashes the password. so when you do Auth::attempt it's going to hash the password you provided. And the result is what you get, it will always false.
Instead, you need to Other Authentication Methods.
Auth::login($user);
// Login and "remember" the given user...
Auth::login($user, true);
Above is the easiest way to fix your code.
It's recommended to hash your password rather than encrypting the password.
Hashing password in laravel is also
Hash::make($password);
And then you can use Auth::attempt to log in your user.
Laravel Auth uses the bcrypt hashing when saving password via model you may use either of the 2 method
$account->password = bcrypt("YOUR_PASSWORD"); or $account->password = Hash::make("YOUR_PASSWORD");
Then if you're dealing with the auth attempt function, just simply call the method like this
if($account = Auth::attemp(['email' => "YOUR_EMAIL#DOMAIN.COM", 'password' => "YOUR_PASSWORD"])){
//success login, do your extra job here
}else{
//invalid credentials here
}
Instead of using md5 or crypt use \Hash::make() it is much secure
I refactored your code and it does the same thing
You only need to rename your c_password to password_confirmation
Source
Below code does the same thing that your code do
public function register(Request $register)
{
$this->validate($register, [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
$user = User::create([
'name' => $register->input('name'),
'email' => $register->input('email'),
'password' => $register->input('password'),
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user,
]);
}
public function login(Request $request)
{
$request->merge(['password' => \Hash::make($request->input('password'))]);
if (Auth::attempt($request->only(['email', 'password']))) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user,
]);
}
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
when you hashing password using crypt it has a key to unlock it that's why there is a decrypt but when you use Hash::make() it doesn't have a key to break or unlock it, it will check it's algorithm to see if given password is matching the algorithm that already exists in the database that's why crypt is not safe and Hash::make is much much more safe

Auth::guard('admin')->user() is NULL in laravel 5.8

I'm trying to return the user logged in but I'm getting null
when I dd(Auth::guard('admin')->user() in the login Controller it works but when I try to use it in NiveauController it returns null.
LoginController:
public function VerifierLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('enseignant')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
Auth::guard('enseignant')->user();
return redirect()->intended(route('EnseignantDashboard'));
}
if (Auth::guard('superadmin')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
Auth::guard('superadmin')->user();
return redirect()->intended('/superadmin');
}
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
Auth::guard('admin')->user();
return redirect()->intended('/admin');
}
return back()->withInput($request->only('email', 'remember'))->with('error');
}
NiveauController:
public function showListNiveaux()
{
$admin=Auth::guard('admin')->user();
dd( $admin);
$niveaux = DB::table('niveaux')->where('id_etablissement',$admin->id_etablissement);
return view('Niveau:index',compact($niveaux));
}
This usually happens if you forget to put the auth middleware on your route/controller
Try putting this in your controller
public function __construct()
{
$this->middleware('auth');
//OR
// $this->middleware('web');
}
and see if this solves your issue.

Auto login after register in laravel 5.7

I want when I finished register it redirects me to the dashboard page (Auto login after the register).
this is the user register code :
public function store(Request $request)
{
$this->validator($request->all())->validate();
$apprenant = Apprenant::create([
'nom' => $request['nom'],
'prenom' => $request['prenom'],
'email' => $request['email'],
'niveau' => $request['niveau'],
'password' => Hash::make($request['password']),
]);
return redirect('/apprenant/dashboard');
}
But when I finished registring it redirects me to the login page
Hi if you are create a guard then run this code for after register login
Auth::guard(guard_name)->loginUsingId($id);
// example
public function register(Request $req)
{
$user = new User; // define here your model
$user->name = $req->name;
$user->email = $req->email;
$user->password = Hash::make($req->password);
if($user->save()){
Auth::guard(guard_name)->loginUsingId($user->id);
}
}
// logout overite
public function logout()
{
Auth::guard('guard_name')->logout();
return redirect("login_path");
}
When creating a new user, create() method, should return a new model object.
Use Auth::loginUsingId($apprenant->id); before redirecting to dashboard:
public function store(Request $request)
{
$this->validator($request->all())->validate();
$apprenant = Apprenant::create([
'nom' => $request['nom'],
'prenom' => $request['prenom'],
'email' => $request['email'],
'niveau' => $request['niveau'],
'password' => Hash::make($request['password']),
]);
Auth::loginUsingId($apprenant->id);
return redirect('/apprenant/dashboard');
}
source
https://laravel.com/docs/5.7/authentication#other-authentication-methods
Write this line before redirecting to the dashboard:
\Auth::login($apprenant);
or just,
auth()->login($apprenant);
That means, you code will look like:
public function store(Request $request)
{
$this->validator($request->all())->validate();
$apprenant = Apprenant::create([
'nom' => $request['nom'],
'prenom' => $request['prenom'],
'email' => $request['email'],
'niveau' => $request['niveau'],
'password' => Hash::make($request['password']),
]);
//login the user
\Auth::login($apprenant);
return redirect('/apprenant/dashboard');
}

laravel 5.2 custom login

I try to create custom login page but I got an error
Undefined index: password
my controller code
$this->validate($Request, [
'Email' => 'required',
'password' => 'required',
]);
$email = $Request['Email'];
$password = md5($Request['password']);
$login = new login();
$login = login::where('Email', $email);
if(empty($password))
{
return('404');
}
if(Auth::attempt(['Email' => $Request->input('Email'), 'Password' =>$password]))
{
return ('ok');
}
return ('no');
any one help my to create custom login
this is my new code
but again i gor undefined::passsword
public function logincheck(Request $request)
{
$this->validate($request, [
'Email' => 'required',
'password' => 'required',
]);
$email = $request->Email;
$password = md5($request->get('password'));
if(Auth::attempt(['Email' => $request->get('Email'), 'Password' =>md5($request->get('password'))]))
{
return ('ok');
}
return ('no');
}
Your error comes from
$Request['password']
You are treating Request as an array. It's an object. You do
public funciton login(Request $request)
{
$password = $request->password;
//or use the global helper
$password = request('password');
//Attempt login
if(Auth::attempt(['Email' => $request->get('Email'), 'Password' =>$password]))
{
return ('ok');
}
}
Also if you follow Laravel tutorial properly, you don't need md5 to hash password. Auth::attemp() will hash it for you

Resources