How to authenticate email and password with laravel 5.3 manually? - php

Hello Everyone
My question is how can we authenticate our email and password in laravel 5.3 ?
I am not using Auth here , I am trying to create login system manually
This is user register method
public function post_register(Request $request){
$this->validate($request , [
'username' => 'required|' ,
'email' => 'required|email|unique:registers' ,
'password' => 'required|min:6',
'cp' => 'required|same:password']);
$data = new Register;
$data->username = $request->username;
$data->email = $request->email;
$data->password = bcrypt($request->password);
$data->save();
return Redirect::back()->with('success' , 'user registred');
}
This is login method
public function post_login(Request $request){
$this->validate($request , [
'email' => 'required|email' ,
'password' => 'required']);
$data = Register::where('email' , $request->email)->exists();
if($data){
Session::put('email' , $request->email);
return Redirect::to('profile');
}
else{
return Redirect::to('login');
}
this code is working , but problem is that if i enter registered email and unregistered password then it redirect to profile page.
i am not able to authenticate user with email and password because i am using bcrypt() hash function in password and when i try to match http request with stored password , it show error
Please help me ,Thanks

It wont work because you are comparing the string results of the hash which isnt correct.
Changes you Register Function
$data->password = Hash::make($request->password);
Change Your Login function
public function post_login(Request $request){
$this->validate($request , [
'email' => 'required|email' ,
'password' => 'required']);
$data = Register::where('email' , $request->email)->first();
if($data){
if(Hash::check($request->password, $data->password)){
Session::put('email' , $request->email);
return Redirect::to('profile');
}
}
return Redirect::to('login');
}
Explanation
These changes allow you to use Laravel's built in Hashing functionality for Generating Hashes At Registration & Calculating if a hash is valid during login.

Change your code to this.
$data = Register::where('email' , $request->email)
->where('password' ,bcrypt($request->password))
->exists();

Related

Lumen 5.8: Implement login

I'm new to Lumen. How can I implement login?
I've tried this code but I got an error. And I found out in the documentation that Lumen does not support session. So Auth::attempt() is not available.
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'password' => 'required|string'
]);
$credentials = $request->only('email', 'password');
if( !Auth::attempt($credentials) ) {
return response()->json([
'message' => 'Unauthorized'
], 401);
}
return response()->json(['message' => 'Successfully login'], 200);
}
How can I authenticate user using login method? Since Auth::attempt() is not working are there any alternatives? Thanks!
Take email and password and check in the database manually.
$email = $request->input('email');
$password = $request->input('password');
$result = DB::table('users')->where('email', $email)->first();
if (!is_null($result)) {
if($password == $result->password) {
return response(200);
}
}
Checking in table users, in columns email and password.

How can I decrypt password to login in laravel?

While changing the password I am using this function
public function passwordChange(Request $request, $userId)
{
$user = User::find($userId);
$user->password = Crypt::encrypt(Input::get('password'));
$user->save();
return redirect('my-profile');
}
So in my mongoDb database password insert in encrypted form, So whenever I have to login in system at that time how can I compare my password with password of database
public function authenticate(Request $request)
{
$rules = array(
'company_email' => 'required|email|exists:users,company_email',
'password' => 'required|string|max:20|min:4',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return view('pages.login')->with('v_errors', $validator->errors()->messages());
}
else
{
//get email and query
$authenticateMe = $request->only('company_email', 'password');
$user = User::where($authenticateMe)->first();
if (empty($user))
{
return view('pages.login')->with('not_exists', 'true');
}
//session set
// Session::put('key', $user->username, $user->file);
Session::put('key', ['username' => $user->username, 'email' => $user->company_email, 'userId' => $user->id, 'profilePicture' => $user->file]);
return redirect('my-profile');
}
}
I am not using php artisan make:auth
will anyone please help??
Instead of encrypting the password, use hashing. Laravel has its own documentation about how to use that: https://laravel.com/docs/5.8/hashing
Simply you can not decrypt an encrypted password but you can check user credentials by adding an array of user email & password to Auth::attempt() function Here is a link to the description: https://laravel.com/docs/5.8/authentication#authenticating-users?
Here is your function using Auth::attempt():
public function authenticate(Request $request)
{
$rules = array(
'company_email' => 'required|email|exists:users,company_email',
'password' => 'required|string|max:20|min:4',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return view('pages.login')->with('v_errors', $validator->errors()->messages());
}
else
{
//get email and query
$authenticateMe = $request->only('company_email', 'password');
if (Auth::attempt($authenticateMe)) {
$user = User::find(Auth::user()->id);
//session set
// Session::put('key', $user->username, $user->file);
Session::put('key', ['username' => $user->username, 'email' => $user->company_email, 'userId' => $user->id, 'profilePicture' => $user->file]);
return redirect('my-profile');
}else{
return view('pages.login')->with('not_exists', 'true');
}
}
}
And do not forget to add use Auth; to the function controller

Laravel 5 custom login with username OR email using the Attempt method

In my laravel app, at the start I had decided to create my own custom login controller, rather than use the base one.
public function postSignin(Request $request, AppMailer $mailer) {
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if (!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
return redirect()->back()->with('info', 'Could not sign you in with those details.');
}
if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password'), 'verified' => 0]))
{
$mailer->sendEmailConfirmationTo(Auth::user());
Auth::logout();
return redirect()->back()->with('info', 'Email verification required.');
}
Auth::user()->last_login = new DateTime();
Auth::user()->save();
return redirect()->back()->with('info', 'You are now signed in.');
}
And now I want to edit this so that users can also login with their usernames and not just their emails, using the same field. However, the attempt method is confusing. It seems to expect an email even after I switch the values around.
The Auth documentation isn't very helpful in this case either. It asks me to add this:
public function username()
{
return 'username';
}
in the login controller, but obviously this is for a default setup.
You can use the 'FILTER_VALIDATE_EMAIL' checker.
$username = $request->get('username');
$password = $request->get('password');
$remember_me = $request->get('remember_me','1');
$field = filter_var($username,FILTER_VALIDATE_EMAIL)? 'email': 'username';
if(Auth::attempt([$field => $username,'password' => $password],$remember_me)){
//Auth successful here
}
Meaning FILTER_VALIDATE_EMAIL do check the string whether it is in email format or not.
I hope this sample code helps you.
-ken

Login is Not Working Laravel 5

Hello friends I am using users table column like (USERNAME,EMAIL,PASSWORD)
if i am changing to column name as small letters is working fine. To Change column name as caps is not working give me any suggestion
This is my controller
public function postLogin(Request $request)
{
$this->validate($request, array('username' => 'required', 'password' => 'required'));
$credentials = $request->only('USERNAME', 'PASSWORD');
if (Auth::validate($credentials))
{
$user = Auth::getLastAttempted();
Auth::login($user, $request->has('remember'));
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('USERNAME', 'remember'))
->withErrors([
'username' => $this->getFailedLoginMessage(),
]);
}
Both user providers that you get with Laravel (EloquentUserProvider and DatabaseUserProvider) expect password to be stored in lowercase password field.
In order to make authentication work with PASSWORD field you need to do 2 things.
First, let providers know that user's password is stored in PASSWORD column. You can do this by implementing getAuthPassword method in your User model:
public function getAuthPassword() {
return $this->PASSWORD;
}
Secondly, password needs to be stored with password key in the credentials array you pass to Auth::validate(). You'll need to change the name of the name of the form field that user inputs password into to password OR create credentials array manually:
$credentials = [
'USERNAME' => $request->get('USERNAME'),
'password' => $request->get('PASSWORD'),
];

Rule for Checking Old Password and New Password

I am checking for Old Password and New Password with Confirmation Password.
Here i want to check with whether OldPassword and New Password should not be same.
How can i do this ?
Here is my Rule :
public static $rulespwd = array('OldPassword' => 'required|pwdvalidation',
'NewPassword' => 'required|confirmed|min:1|max:10',
'NewPassword_confirmation' => 'required',
);
Here is my controller code for the validation :
$PasswordData = Input::all();
Validator::extend('pwdvalidation', function($field, $value, $parameters)
{
return Hash::check($value, Auth::user()->password);
});
$messages = array('pwdvalidation' => 'The Old Password is Incorrect');
$validator = Validator::make($PasswordData, User::$rulespwd, $messages);
if ($validator->passes())
{
$user = User::find(Auth::user()->id);
$user->password = Input::get('NewPassword');
$user->save();
return Redirect::to('changepassword')->with('Messages', 'The Password Information was Updated');
}
Note : I am using model for validation rule.. How can i do this in model ??
Just use the different validation rule - as described in the Laravel docs
public static $rulespwd = array('OldPassword' => 'required|pwdvalidation',
'NewPassword' => 'required|confirmed|min:6|max:50|different:OldPassword',
'NewPassword_confirmation' => 'required',
);
Also - why are you limiting a password to 10 chars? That is silly - there is no reason to limit it at all. All your are doing is reducing your application security.

Categories