RAUSHAN KUMAR RAUSHAN KUMAR - 1 month ago 5
PHP Question

Change the laravel hasing mechanism to encrypt and store the password in users table

As laravel uses its own mechanism to encrypt and save the password in users table. But i want to change the password encryption mechanism and want to write my own, also the two inbuilt function of laravel authentication should work according to my my password encryption mechanism


check() and attempt()


Anyone please tell me how to do that..

Answer

Replacing the laravel authentication with a custom authentication

I had built my laravel project and then had a task to replace the larevel default authentication with a custom authentication module I could not find any post that could help me fix this issue and had to refer to many articles . There fore i decided to make a post on how this could be done So as to help any one else facing the similar issue.

1.Files needed to be modified a) config/auth.php: Replace your eloquent driver with your custom driver return [

/*
|--------------------------------------------------------------------------
| Default Authentication Driver
|--------------------------------------------------------------------------
|
| This option controls the authentication driver that will be utilized.
| This driver manages the retrieval and authentication of the users
| attempting to get access to protected areas of your application.
|
| Supported: "database", "eloquent"
|
*/

// 'driver' => 'eloquent', 'driver' => 'custom',

    /*
|--------------------------------------------------------------------------
| Authentication Model
|--------------------------------------------------------------------------
|
| When using the "Eloquent" authentication driver, we need to know which
| Eloquent model should be used to retrieve your users. Of course, it
| is often just the "User" model but you may use whatever you like.
|
*/

'model' => 'App\User',

/*
|--------------------------------------------------------------------------
| Authentication Table
|--------------------------------------------------------------------------
|
| When using the "Database" authentication driver, we need to know which
| table should be used to retrieve your users. We have chosen a basic
| default value but you may easily change it to any table you like.
|
*/

'table' => 'user',

/*
|--------------------------------------------------------------------------
| Password Reset Settings
|--------------------------------------------------------------------------
|
| Here you may set the options for resetting passwords including the view
| that is your password reset e-mail. You can also set the name of the
| table that maintains all of the reset tokens for your application.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/

'password' => [
    'email' => 'emails.password',
    'table' => 'password_resets',
    'expire' => 60,
],

];

b) config/app.php: Add your custom provider to the list of providers 'App\Providers\CustomAuthProvider',

2.Files needed to be added a. providers/CustomAuthProvider.php: Create a new Custom Provider that uses the custom driver that was defined earlier

use App\Auth\CustomUserProvider; use Illuminate\Support\ServiceProvider;

class CustomAuthProvider extends ServiceProvider {

/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{

    $this->app['auth']->extend('custom',function()
    {

        return new CustomUserProvider();
    });
}

/**
* Register the application services.
*
* @return void
*/
public function register()
{
    //
}

}

Auth/CutomerUserProvider.php :This class will replace the eloquentUserProvider and where all house keeping procedues can be initiated (after login / before logout) .

namespace App\Auth; use App\UserPoa; use Carbon\Carbon; use Illuminate\Auth\GenericUser; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider;

class CustomUserProvider implements UserProvider {

/**
* Retrieve a user by their unique identifier.
*
* @param  mixed $identifier
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveById($identifier)
{
    // TODO: Implement retrieveById() method.


    $qry = UserPoa::where('admin_id','=',$identifier);

    if($qry->count() >0)
    {
        $user = $qry->select('admin_id', 'username', 'first_name', 'last_name', 'email', 'password')->first();

        $attributes = array(
            'id' => $user->admin_id,
            'username' => $user->username,
            'password' => $user->password,
            'name' => $user->first_name . ' ' . $user->last_name,
        );

        return $user;
    }
    return null;
}

/**
* Retrieve a user by by their unique identifier and "remember me" token.
*
* @param  mixed $identifier
* @param  string $token
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByToken($identifier, $token)
{
    // TODO: Implement retrieveByToken() method.
    $qry = UserPoa::where('admin_id','=',$identifier)->where('remember_token','=',$token);

    if($qry->count() >0)
    {
        $user = $qry->select('admin_id', 'username', 'first_name', 'last_name', 'email', 'password')->first();

        $attributes = array(
            'id' => $user->admin_id,
            'username' => $user->username,
            'password' => $user->password,
            'name' => $user->first_name . ' ' . $user->last_name,
        );

        return $user;
    }
    return null;



}

/**
* Update the "remember me" token for the given user in storage.
*
* @param  \Illuminate\Contracts\Auth\Authenticatable $user
* @param  string $token
* @return void
*/
public function updateRememberToken(Authenticatable $user, $token)
{
    // TODO: Implement updateRememberToken() method.
    $user->setRememberToken($token);

    $user->save();

}

/**
* Retrieve a user by the given credentials.
*
* @param  array $credentials
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
    // TODO: Implement retrieveByCredentials() method.
    $qry = UserPoa::where('username','=',$credentials['username']);

    if($qry->count() >0)
    {
        $user = $qry->select('admin_id','username','first_name','last_name','email','password')->first();




        return $user;
    }
    return null;


}

/**
* Validate a user against the given credentials.
*
* @param  \Illuminate\Contracts\Auth\Authenticatable $user
* @param  array $credentials
* @return bool
*/
public function validateCredentials(Authenticatable $user, array $credentials)
{
    // TODO: Implement validateCredentials() method.
    // we'll assume if a user was retrieved, it's good

    if($user->username == $credentials['username'] && $user->getAuthPassword() == md5($credentials['password'].\Config::get('constants.SALT')))
    {

        $user->last_login_time = Carbon::now();
        $user->save();

        return true;
    }
    return false;


}

}

UsePoa (This is my model for the admin table): This is a Model class that i created for my admin table .It implements Illuminate\Contracts\Auth\Authenticatable use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model;

use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

class UserPoa extends Model implements AuthenticatableContract {

use Authenticatable;
protected $table = 'admin';
protected $primaryKey  = 'admin_id';
public $timestamps = false;

}

3.Files need to know about Guard.php : This is the class that will call your User Provider depending on what is defined in the driver. Originally it use to be the EloquentUserProvider .But in this case I have replaced it with the CustomUserProvider Below is how the methods in the CustomUserProvider are called by the Guard . 1 . Login : 1. retrieveByCredentials is called to check if the user exists 2.ValidateCredentials is called to verify if the username and password are correct .Note The object that was produced in the retrieveByCredentials is sent to the ValidateCredentials and therefore no second db access is required.

Authenticate a page: When ever an attempt is made to see if a user has been loged in retrieveById($identifier) is called Logout with remember me setup the method updateRememberToken(Authenticatable $user, $token) will be called.

Comments