user login laravel 4 - laravel

can't manage to login anybody an idea? i still get redirected back to the login page
Route::post('login', function() {
// get POST data
$email = Input::get('username');
$password = Input::get('password');
if ( Auth::attempt(array('email' => $email,'password' => $password) ))
{
return Redirect::to('home');
}
else
{
// auth failure! lets go back to the login
return Redirect::to('login')
->with('login_errors', true);
}
});

change
if ( Auth::attempt(array('email' => $email,'password' => $password) ))
to
if ( Auth::attempt(array('username' => $email,'password' => $password) ))

Laravel has a setting that lets you specify the username as either 'username' or 'email' (or whatever else you may choose), check config. Like above indicated...
if ( Auth::attempt(array('username' => $email,'password' => $password) ))
Also, Laravel expects a hashed password by default.

To use email as username, try adding this to User model:
protected $primaryKey = 'email';
Also make sure email is the primary key on your 'user' table.

Related

Laravel 8 SSO implementation

I am tring to implement a SSO structure:
main application with all user to manage the login (sso-app)
multiple application that will authenticate to sso-app (app1, app2, ...)
I managed to make the base login with sso-app api using Laravel Passport package.
Here the app1 controller for the authorization process:
class SSOController extends Controller
{
public function getLogin(Request $request){
$request->session()->put("state", $state = Str::random(40));
$query = http_build_query([
'client_id' => env('SSO_CLIENT_ID'),
'redirect_uri' => env('APP_URL') . '/auth/callback',
'response_type' => 'code',
'scope' => '',
'state' => $state
]);
return redirect(env('SSO_HOST') . '/oauth/authorize?' . $query);
}
public function getCallback(Request $request){
$state = $request->session()->pull('state');
throw_unless(strlen($state) > 0 && $state == $request->state,
InvalidArgumentException::class
);
$response = Http::asForm()->post(
env('SSO_HOST') . '/oauth/token',
[
'grant_type' => 'authorization_code',
'client_id' => env('SSO_CLIENT_ID'),
'client_secret' => env('SSO_SECRET'),
'redirect_uri' => env('APP_URL') . '/auth/callback',
'code' => $request->code
]
);
$request->session()->put($response->json());
$token = $response->json()['access_token'];
$jwtHeader = null;
$jwtPayload = null;
$parsed_token = parse_jwt($token);
try{
$email = $parsed_token->payload->user->email;
}
catch(\Throwable $e){
return redirect('login')->withError("Failed to get login information! Try again.");
}
$user = User::firstOrCreate(['email' => $email], array_merge((array)$parsed_token->payload->user, ['name' => ($parsed_token->payload->user->first_name." ".$parsed_token->payload->user->last_name)]));
Auth::login($user);
return redirect(route('home'));
}
}
The app1 will redirect to sso-app login form than when user successfull login he will redirect back to app1.
Everything work as aspected, but how can I use this approach to authorize the api route?
This work only for the "web" guard because I had create a local user table for every app and made the login based on session as you can see on the end of SSOController.
But how can I use the token returned from sso-app to authenticate local app1, app2, ... api?
Should I have to create a middleware that call sso-app every time I call app1 api to check if the token is valid or there is a better approach to save time and increase speed?
Thanks.

Laravel auth attempt not working or returning false always?

I've been looking all over the place (I checked all the other duplicate questions and answers ), no luck. I don't understand what am I doing wrong, all the values are coming from post, but Auth:attempt keeps on failing/returning false, if I try to implement login manually it won't authenticate as I am expecting, Also do I have to make or use separate methods like for validation, credentials, username ..etc ?
Here is my login Controller > login method
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'usermail' => 'required|max:255',
'password' => 'required_with:usermail',
],[
'password.required_with' => "The password field is empty."
]);
if ($validator->fails()) {
return redirect()
->route('admin.login')
->withErrors($validator)
->withInput();
}
$usermail = $request->get('usermail');
$password = $request->get('password');
$remember = $request->get('rememberMe');
if(filter_var($usermail, FILTER_VALIDATE_EMAIL)) {
$isEmailExist = User::where('user_email',$usermail)->first();
if($isEmailExist != null){
if(Auth::attempt([
'user_email' => $usermail,
'user_pass' => $password
])){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the email address <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid email address.'
]);
}
}else{
$isUsernameExist = User::where('user_login',$usermail)->first();
if($isUsernameExist != null){
if(Auth::attempt([
'user_login' => $usermail,
'user_pass' => $password
],$remember)){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the username <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid username. Lost your password?'
]);
}
}
}
And this is my user migration schema,
Schema::create('vw_users', function (Blueprint $table) {
$table->bigIncrements('ID');
$table->string('user_login','60')->unique()->default('');
$table->string('user_pass');
$table->string('user_email','100')->unique()->default('');
$table->rememberToken();
});
Here is how i seed user,
User::create([
'user_login' => 'admin',
'user_pass' => Hash::make("123456"),
'user_email' => 'admin#gmail.com',
]);
OK OK OK,
I made it work, I think in laravel framework we can only create the column name for the password is "password" field in database authentication table.
I updated the following changes:-
I renamed the password field name from migration schema the "user_pass" to "password". (Also updated in login controller and user model).
Added following code into user model:-
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
...
}
I checked twice to confirm so I revert back it didn't work.
If i make any sense to anyone please let me know and help me understand.
I've looked into very similar posts like this Laravel: How can i change the default Auth Password field name
can I please have a reference book or blog for all the laravel predefined libraries and functions? I know the vendor folder is full of surprises but still, I need more references.
Thank you so much for your time.

Laravel validator check existence for multiple fields

I'm creating a user login form where user can use his/her username or email to login with Laravel, so on the backend, I want to validate if the user input is either an existed username or an existed email address, something like
$validator = Validator::make(
array('username_or_email' => $username_or_email),
array('username_or_email' => 'exists:users,username|exists:users,email)
);
but I doubt the above is the correct syntax for it, so how should I write my validator?
Assuming you don't allow # in username you could do it this way:
if (strpos($username_or_email, '#') === false) {
$rule = 'exists:users,username';
}
else {
$rule = 'exists:users,email;
}
$validator = Validator::make(
array('username_or_email' => $username_or_email),
array('username_or_email' => $rule)
);

How to set remember_token NULL in laravel

I have an application in laravel which have a Users table with a column remember_tokenand the User model has the three function mentioned here: http://laravel.com/docs/upgrade#upgrade-4.1.26
getRememberToken(), setRememberToken($value), getRememberTokenName()
In my login form, I have email, password and a remember me checkbox field. What I want is if user ticked that Remember Me checkbox, then only laravel should remember the user, else it should set the column as NULL.
But at the moment it is remembering it all the time, and I don't know how to set it to NULL.
My doLogin function code is below:
public function doLogin()
{
$rules = array(
'email' => 'required|email',
'password' => 'required|alphaNum|min:7'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$remember = Input::get('remember');
$userData = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($userData, true)) {
return Redirect::to('/');
} else {
return Redirect::to('login')->with('loginError', 'Incorrect email or password.');
}
}
}
Please tell me what modification I need to make so that it set remember_token as null in database when remember checkbox is not ticked by user.
To quote the documentation
If you would like to provide "remember me" functionality in your
application, you may pass true as the second argument to the attempt
method, which will keep the user authenticated indefinitely (or until
they manually logout).
You are hard coding the second parameter to true instead of using the value taken from the user input.
You are already setting the input to the $remember variable, so try passing that instead.
Auth::attempt($userData, $remember)

CodeIgniter password not validating against database

I've setup my login functions in CodeIgniter (email/password). The email field is validating properly against the database, but as long as the email is validated any password is accepted--even blank passwords.
I need to figure out why only the email field is being checked against the database and how to get the password field to validate against the database.
Sidebar: I'm planning to encrypt the passwords next, but want to be sure the field is validating against the database first. Then I'll add the security layers.
From the login controller:
function login_validation()
{
$this->load->model('foo_model');
$query = $this->foo_model->validate();
if($query)
{
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('foodash');
}
else
{
$this->index(); // login page
}
}
From the foo model:
function validate()
{
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('footable');
if($query->num_rows == 1)
{
return true;
}
}
}
FIGURED IT OUT:
I was masking my password field using jquery so that the text wasn't visible when entered. I had to change the name of my password field--once I changed it in the model, everything worked perfectly.
FIGURED IT OUT:
I was masking my password field using jquery so that the text wasn't visible when entered. I had to change the name of my password field--once I changed it in the model, everything worked perfectly.
Try returning false in your validate() function after your IF statement.
Also try a different syntax:
$query = $this->db->get_where('footable', array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
));
The password is validating against the database, but the return value of validate() is undefined, when the email or password is wrong. This can result in unpredictable results. I recommend:
function validate()
{
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('footable');
return ($query->num_rows() == 1);
}

Resources