I'm authenticating users with conditions i.e. if
User role = 1 Login should be successful else login should fail
Now what I'm doing for now is:
if (Auth::attempt(array('email' => $email, 'password' => $password, 'role' => 1)))
{
// Login User
} else {
return Redirect::route('admin.login')
->with('message', 'Unauthorized user Or wrong email / password combination');
}
It is working fine, but when authentication fails, I want to be able to figure out the reason why it failed so I will be able to display following messages based on the reason of failed authentication:
non-existing email address
wrong password
incorrect user role.
Is there a way to do these things?
The trick is to use Auth::validate() in the failed section. You'll have to do a couple of validates to work out which is the issue
if (Auth::attempt(array('email' => $email, 'password' => $password, 'role' => 1)))
{
// Login User
} else {
Auth::validate(array('email' => $email, 'password' => $password)) {
// Wrong role
} else {
if (User::where('email', $email)->first()) {
// Wrong password
} else {
// Wrong username
}
}
try validation first then try to attempt login
Validating Multiple Fields
http://laravel.com/docs/4.2/validation
I hope this might help
public function postSignIn() {
// checking for validation
$validator = Validator::make(Input::all(), array(
'email' => 'required|email',
'password' => 'required'
));
//if validation fails
if ($validator->fails()) {
return Redirect::route('sign-In')
->withErrors($validator)
->withInput();
} else {
$auth = Auth::attempt(array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'active' => 1,
));
if ($auth) {
return Redirect::route('home');
} else {
return Redirect::route('sign-In')->with('fails', 'Email/password wrong, or account not activated.') ;
}
on the view write these response validations on top or below every fields with field names where email is the field name
#if($errors->has('email'))
{{$errors->first('email')}}
#endif
#if($errors->has('password'))
{{$errors->first('passwrd')}}
#endif
Since I am new to laravel so I have been using the longer process
this is the function laravel use for auth purpose.
if you see here : vendor/laravel/framework/src/illuminate/Auth/Guard.php
public function attempt(array $credentials = array(), $remember = false, $login = true)
{
$this->fireAttemptEvent($credentials, $remember, $login);
$this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);
// If an implementation of UserInterface was returned, we'll ask the provider
// to validate the user against the given credentials, and if they are in
// fact valid we'll log the users into the application and return true.
if ($this->hasValidCredentials($user, $credentials))
{
if ($login) $this->login($user, $remember);
return true;
}
return false;
}
and if you see through source this function use hasValidCredentials function
and if you dig further the function is :
protected function hasValidCredentials($user, $credentials)
{
return ! is_null($user) && $this->provider->validateCredentials($user, $credentials);
}
and in UserProviderInterface interface you see this interface has been defined and you can implement it your self and return reason of auth problem instead of false or true
Thanks to #The Shift Exchange here is how I've figured it out:
if (Auth::attempt(array('email' => $email, 'password' => $password, 'role' => 1)))
{
dd('Login Successful');
} else {
if( Auth::validate( array( 'email' => $email, 'password' => $password ) ) )
{
// Wrong Role
dd('Unauthorized user');
} else {
dd('Wrong email / password');
}
}
This worked!!
Related
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;
}
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);
i set code to auth the admin only can login but the code look like ignored by login controller
i take code from laravel documentation and use on my loginController
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password, 'admin' => 1])) {
return redirect()->intended('home');
} else {
return redirect()->route('login');
}
}
i wan to login if my column admin is ==1 else return b to login and why the controller ignore the authenticate ?
You can't check admin => 1 in auth attempt. Try with this
if (Auth::attempt(['email' => $email, 'password' => $password])) {
if (Auth::User()->admin == '1') {
return redirect()->intended('home');
} else {
return redirect()->route('login');
}
}
I have created my API for logging users into my application, but then it responds with the else part as the response
{"error":true,"message":"Check your username or password"}
below is my controller
public function getLogin()
{
$user = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
if (Auth::attempt($user))
{
$user = User::find(Auth::user()->id);
$role = $user->roles;
if ($role[0]->name == 'Customer')
{
return Response::json(['error' => false, 'message' => 'Customer Logged in successfully', "user"=>$user]);
}
else
{
return Response::json(['error'=>true, 'message'=>'Check your login details']);
}
}
else
{
return Response::json(['error' => true, 'message' => 'Check your username or password']);
}
}
I want to Redirect my views inside the function like when admin goes to admin page, teacher goes to teacher page and student goes to student page.
Im getting an unexpected error with the else :(
Here's my function
public function postLogin()
{
$validator = Validator::make(Input::all(), array(
'username' => 'required',
'pass1' => 'required'
));
if($validator->fails())
{
return Redirect::route('getLogin')->withErrors($validator)->withInput();
}
else
{
$remember = (Input::has('remember')) ? true : false;
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('pass1')
), $remember);
if($auth)
{
$admin = User::where('isTeacher', '0')->where('isAdmin', '1')->get();
$teacher = User::where('isTeacher', '1')->where('isAdmin', '0')->get()
if($admin)
{
return Redirect::route('admin.index');
}
else if($teacher)
{
return Redirect::route('teacher.index');
}
else
return Redirect::route('student.index');
}
else
{
return Redirect::route('getLogin')->with('fail','You entered the wrong login credentials. Please try again.');
}
}
}
I want to redirect the route using the function instead inside of my blade. Is this possible?
if($auth)
{
$admin = User::where('isTeacher', '0')->where('isAdmin', '1')->get();
$teacher = User::where('isTeacher', '1')->where('isAdmin', '0')->get(); <-----
you missed a ; in that line.
Additional info:
User::where('isTeacher', '0')
you have to use an operand as 2nd argument. e.g.
User::where('isTeacher','=', '0')