create custom authenticate controller with different database filed in Laravel - php

Auth::attempt(['u_email'=>$credentials['email'],'u_password'=>sha1($credentials['password'])])
i'm use this code for authentication but i'm getting Undefined index: password error can any one help for create custom authentication control without changing in vendor library
Thank you in advance for help me...

There are 3 things you need to do.
Pass plain-text password to Auth::attempt() as Laravel will hash that itself before verifying it against the hash stored in the database.
Auth::attempt(['u_email'=>$credentials['email'],'password' => $credentials['password']]);
Pass password as password, not u_password to Auth::attempt(). The key doesn't need to match the password column name (why? see point 3.), but it must be equal to password - see point 1 for example.
Implement getAuthPassword() method in your user model, that will return value of u_password column. This method is used by user provider to fetch the password hash that is later verified against what was passed to Auth::attempt()
//in your User.php
public function getAuthPassword() {
return $this->u_password;
}

Related

Laravel intervention to login post before start auth control

We imported some users from our old script.
But we can't decrypt this users password.
So I defined a default password to this imported users.
I have a imported column on my users table.
So I want to do this:
When a user post the login form I want to check user is imported or not by using user's email.
Like:
if (User::where("email", $email)->first()->imported == 1) {
//change password parameter and then start auth proccess.
} else {
//nothing. just normal auth proccess
}
If it's imported user, I need to change password parameter's value to my default password and make it successfully login. Then I will send a confirmation mail to this user and force change his/her password. If it's not a imported user, nothing gonna happen just make it login in normal way.
Note: We can use same password hash code instead of laravel's hash. But we don't want to do this.
So how can I intervention to login post before start auth control.
I just want to do: this imported users should be login without error. Because this user's password not gonna match with our db records. I defined a custom password like "123456". User will try his old password. But I want to change his old password with "123456" and user can login the system and I can send confirmation mail for change his password.
First, the logic is bad for some security reasons. If I As a guest user or anonymous use happened to know an email then I can log in to the user account with an invalid or random password.
It is better to do it in another way. First, check the user's email, and if found one then email him a reset password link and don't log him in.
If the user owns the email address then he/she can reset his/her password and log in easily.
But if know what you are really doing then you can create your own login or AuthenticationController. and use your logic there. you can sign in the user by id without the default password. You don't need a default password in this case anyway because the end-user is not typing the default password.
Below is an example:
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AuthencaticationController extends Controller{
public function login(Request $request){
$user = User::where('email', $request->email)->first();
//use might be null so you should first check
// otherwise an error will occure because we cannot use the property of null or non-object
if(is_null($user)) {
// redirect user back with error message
return back()->withErrors(['email => 'Email is incorrect']);
}
// for readbility i prefer to create isImproted() method in User model
// and return whatever to check if user is imported
if($user->imported) {
auth()->loginUsingId($user->id);
$request->session()->regenerate();
return redirect('email confirmation action path');
}
$request->session()->regenerate();
return redirect('redirect not imported users path');
}
}
Laravel documentation
Regenerating the session ID is often done in order to prevent malicious users from exploiting a session fixation attack on your application.
Note that this just a simple way to do that you can refactor it in many ways.

Authentication issue in laravel using SQLite

I use a SQLite database instead of MySQL for authentication on my Laravel app. The registration works perfectly, but the login does not work correctly.
I get the following error:
These credentials do not match our records.
Please, help me to solve it!
When you register a new user, the password about to be stored must be encrypted with the bcrypt() helper, such as bcryp($request->password).
Otherwise the credentials will not match during login time.
Also, if you did not use the users migration packed with Laravel, the password field must be a minimum of 64 characters in lenght.
Add this code in your User model
/**
* Hash password by bcrypt before save in database.
*
* #param type $password
*/
public function setPasswordAttribute($password)
{
if (isset($password)) {
$this->attributes['password'] = bcrypt($password);
}
}
everything is working but you have to ensure that
your SQLite DB is not open somewhere else
if it will open in DB browser or any other such type of tool just close that and try again later
will work fine

Symofny -'password' cannot be null

I have implemented function to check my password length in register api call like..
if($password){
$this->validatePassword($password);
}
from other api call..
public function validatePassword($password)
{
if (strlen($password) < 6)
{
throw new PasswordLength('Password must be minimum 6 characters long!');
}
}
and in my postman I am not returning an empty field but I keep getting error
Integrity constraint violation: 1048 Column 'password' cannot be null
In symfony, the plainPassword field is purely used to carry the users 'new' password into a method that would encode it and set it to password.
After the password field is populated, then the plainPassword field is blanked so that no plain text credentials are saved to the db. This is done by calling the implemented eraseCredentials method (found in the required UserInterface). Or, you can make the plainPassword method non-persistent in the user class.
Have a look here at the docs to see how to go about it all.
The docs show an extract from what should be a user manager utility class. Use this to set and update passwords as well as creating new users.
Theres a more complete explination here where the whole process is explained from end-to-end.
Solved!
if($password){
$this->validatePassword($password);
}
$user->setPassword($password);

In laravel I can get my username but I can't get my password

please please someone help me , my boss would kill me , this code is not working in laravel , because password is hashed , it is bcryted , how do i compare and get my us_id ( wich stands for username_id ) , the one that tried to login but has the wrong password , do you have any suggestioin , what i'm trying to do is very simple , i'm trying to understand if the user entered a wrong password but his/her username is right . i am beginner . sorry for that :( . i know this won't work , but what should i do to understand if the user entered a wrong password ?
public function login(Request $request, Logs $logs)
{
$password = $request->input('password');
$myuser = \DB::table('users')->where('password', $password)->first();
if (\Hash::check($password, $myuser->password)) {
$logdata = $myuser->id;
$logs->insert($logdata);
return view('MainPages.example', ['pass' => $password]);
}
}
The password is hashed by Laravel, so use the Hash::check() method:
if (\Hash::check($password, $myuser1->password)) {
The Laravel Hash facade provides secure Bcrypt hashing for storing user passwords. If you are using the built-in LoginController and RegisterController classes that are included with your Laravel application, they will automatically use Bcrypt for registration and authentication.
https://laravel.com/docs/5.5/hashing
You can't expect this to work.
Passwords are stored encrypted. Multiple people could theoretically have the exact same password, but none of them would look identical when stored. Therefore you don't know what to look for in the record, even if you know what password you are looking for because you don't know what salt was used for the particular record where it is stored.
You just can't retrieve a record on a password lookup like this. Rather, you have to retrieve the record first (based on some other key, eg. username or id) and then see if the password encrypts to match from the given password that has the ever important salt.

How can I update only certain fields in a Yii framework?

I dont want to update the password fields.how to use this.Im using md5 encode for password.So i dont want to update the password field in yii framework.any help appreciated??
I think a better approach would be to not use the scenario in this case. The next code in the rules just says to the scenario: the next fields are required. But not: skip the other else.
array('name, username, email', 'required', 'on' => 'update'),
For example, if we limit the length of the password up to 32 characters, but in a database is stored in a format sha1 (length 40), then we have a problem because the validator will block the database query.This is because when you make updating, the "validatŠµ" method checks all class properties (regards database table mapping), not just the new ones delivered by post.
Could use the method "saveAttributes", but then I noticed another problem. If the column "email" is unique in the database and in case edited email duplicate one of the existing, then the Yii message system defined in the rules can not notify and throws error code regards database query.
The easiest approach I think is: don't set scenario in this case. Just send as an argument the properties you want. This will keep the all CRUD features created by GII.
In your code it looks like this:
(in model)
public function rules() {
return array(
array('name, username, email, password', 'required'),
);
}
(in controller)
if($id==Yii::app()->user->id){
$model=$this->loadModel($id);
if(isset($_POST['JbJsJobResume'])) {
$model->attributes=$_POST['JbJsJobResume'];
if($model->save(true, array('name', 'username', 'email')))
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array( 'model'=>$model, ));
}
I noticed that you do not use RBAC. It is very convenient and flexible - try it.
http://www.yiiframework.com/doc/guide/1.1/en/topics.auth#role-based-access-control
In your model you must do something like this:
public function rules() {
return array(
array('name, username, email, password', 'required', 'on' => 'create'),
array('name, username, email', 'required', 'on' => 'update'),
);
}
Lets say that the scenario that you run now is the update. So I don't require the password there. I require it only in the create scenario that you may have. So in the view file that you have you remove the password field and inside the action that you have you include this:
$model->setScenario('update');
so it will not require the password and it will remain the same.
For the password change you can create a new action (ex. actionPassChange) where you will require to type twice the new password.
$model->attributes=$_POST['JbJsJobResume'];
instead of assign all attributes just assign those only you want to save,
as
$model->name=$_POST['JbJsJobResume']['name'];
$model->save();
1st option Just unset password field before setting it:
function update(){
$model=$this->loadModel($id);
unset($_POST['JbJsJobResume']['password']);
$model->attributes=$_POST['JbJsJobResume'];
$model->save();
}
2nd option: Use temp variable:
function update(){
$model=$this->loadModel($id);
$temPassword = $model->passwrod;
$model->attributes=$_POST['JbJsJobResume'];
$model->passwrod = $temPassword;
$model->save();
}
3rd option: use scenarios
I am not sure why this is a problem, and some code could help us to understand why. If you do not wish to capture / update the password, then why is the password field in the form?
If you remove the password field from the view, the value of the password field will not be posted back to controller and then it will not be updated.
There is a possibility that the above method does not work and this could be that in your User model, you are encrypting the password in the afterValidate method?:
protected function afterValidate()
{
parent::afterValidate();
$this->password = $this->encrypt($this->password);
}
public function encrypt($value)
{
return md5($value);
}
In this scenario, if you remove the password field from the view, and just update the name, username or email, then the md5 hash of the password will be re-hashed automatically and you will lose the real password.
One method to get around this is to md5 the password in the afterValidate method (create or update) however if the user wishes to change profile details, in the same form, ask the user to verify their password again.
FORM: user changes name and verifies password
Form posted
Controller calls authenticate method.
If authenticate true, overwrite the entry in user table (including verified pw)
I think #Gravy's answer is right,Thanks Gravy and Nikos Tsirakis. I have fixed nearly same issue as #faizphp. I add scenario for User model as Nikos Tsirakis said, but got same issue also. Then I found I encrypt password in User.afterValidate, so when update the User model everytime, the program encrypt the password in database again to wrong password. So i changed my function from
protected function afterValidate()
{
parent::afterValidate();
if (!$this->hasErrors())
$this->password = $this->hashPassword($this->password);
}
</code>
to
protected function afterValidate()
{
parent::afterValidate();
if (!$this->hasErrors() && $this->scenario==="create")
$this->password = $this->hashPassword($this->password);
}
.
It seems work.

Categories