Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

php - How to get login with different database table column name in Laravel 5.2?

I have to implement login functionality in Laravel 5.2. I have successfully done so using the official Laravel documentation except that I do not know how to authenticate the user using different database table column names, namely st_usernameand st_password.

I have searched the Internet for clues but to no avail. I don't know which class I need to use (like, use Illuminate.......) for Auth. If any one knows the answer, please let me know.

Here is my code:

Login View

@extends('layouts.app')
@section('content')

<div class="contact-bg2">
    <div class="container">
        <div class="booking">
            <h3>Login</h3>
            <div class="col-md-4 booking-form" style="margin: 0 33%;">
                <form method="post" action="{{ url('/login') }}">
                    {!! csrf_field() !!}

                    <h5>USERNAME</h5>
                    <input type="text" name="username" value="abcuser">
                    <h5>PASSWORD</h5>
                    <input type="password" name="password" value="abcpass">

                    <input type="submit" value="Login">
                    <input type="reset" value="Reset">
                </form>
            </div>
        </div>
    </div>

</div>
<div></div>


@endsection

AuthController

namespace AppHttpControllersAuth;

use AppUser;
use Validator;
use AppHttpControllersController;
use IlluminateFoundationAuthThrottlesLogins;
use IlluminateFoundationAuthAuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    protected $redirectTo = '/home';

    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
        $this->username = 'st_username';
        $this->password = 'st_password';
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
                    'name' => 'required|max:255',
                    'email' => 'required|email|max:255|unique:users',
                    'password' => 'required|confirmed|min:6',
        ]);
    }

Route File

Route::get('/', function () {
    return view('index');
});

Route::group(['middleware' => 'web'], function () {
    Route::auth();

    Route::get('/home', 'HomeController@index');
});

config/auth.php

return [
    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => AppUser::class,
        ],
//        'users' => [
//            'driver' => 'database',
//            'table' => 'users',
//        ],
    ],
    'passwords' => [
        'users' => [
            'provider' => 'users',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],
];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I searched a lot how to customize Laravel 5.2 authorisation form and this is what is working for me 100%. Here is from bottom to top solution.

This solution is originally from here: https://laracasts.com/discuss/channels/laravel/replacing-the-laravel-authentication-with-a-custom-authentication

but i had to make couple changes to make it work.

My web app is for the DJs so my custom column names are with 'dj_', for example name is dj_name

  1. config/auth.php

    // change this
    'driver' => 'eloquent',
    // to this
    'driver' => 'custom',
    
  2. in config/app.php add your custom provider to the list ...

    'providers' => [
        ...
        // add this on bottom of other providers
        AppProvidersCustomAuthProvider::class,
        ...
    ],
    
  3. Create CustomAuthProvider.php inside folder appProviders

    namespace AppProviders;
    
    use IlluminateSupportFacadesAuth;
    
    use AppProvidersCustomUserProvider;
    use IlluminateSupportServiceProvider;
    
    class CustomAuthProvider extends ServiceProvider {
    
        /**
         * Bootstrap the application services.
         *
         * @return void
         */
        public function boot()
        {
            Auth::provider('custom', function($app, array $config) {
           // Return an instance of             IlluminateContractsAuthUserProvider...
            return new CustomUserProvider($app['custom.connection']);
            });
        }
    
        /**
         * Register the application services.
         *
         * @return void
         */
        public function register()
        {
            //
        }
    }
    
  4. Create CustomUserProvider.php also inside folder appProviders

    <?php
    
    namespace AppProviders;
    use AppUser; use CarbonCarbon;
    use IlluminateAuthGenericUser;
    use IlluminateContractsAuthAuthenticatable;
    use IlluminateContractsAuthUserProvider;
    use IlluminateSupportFacadesHash;
    use IlluminateSupportFacadesLog;
    
    class CustomUserProvider implements UserProvider {
    
    /**
     * Retrieve a user by their unique identifier.
     *
     * @param  mixed $identifier
     * @return IlluminateContractsAuthAuthenticatable|null
     */
    public function retrieveById($identifier)
    {
        // TODO: Implement retrieveById() method.
    
    
        $qry = User::where('dj_id','=',$identifier);
    
        if($qry->count() >0)
        {
            $user = $qry->select('dj_id', 'dj_name', 'first_name', 'last_name', 'email', 'password')->first();
    
            $attributes = array(
                'id' => $user->dj_id,
                'dj_name' => $user->dj_name,
                'password' => $user->password,
                'email' => $user->email,
                '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 IlluminateContractsAuthAuthenticatable|null
     */
    public function retrieveByToken($identifier, $token)
    {
        // TODO: Implement retrieveByToken() method.
        $qry = User::where('dj_id','=',$identifier)->where('remember_token','=',$token);
    
        if($qry->count() >0)
        {
            $user = $qry->select('dj_id', 'dj_name', 'first_name', 'last_name', 'email', 'password')->first();
    
            $attributes = array(
                'id' => $user->dj_id,
                'dj_name' => $user->dj_name,
                'password' => $user->password,
                'email' => $user->email,
                'name' => $user->first_name . ' ' . $user->last_name,
            );
    
            return $user;
        }
        return null;
    
    
    
    }
    
    /**
     * Update the "remember me" token for the given user in storage.
     *
     * @param  IlluminateContractsAuthAuthenticatable $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 IlluminateContractsAuthAuthenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
    
        // TODO: Implement retrieveByCredentials() method.
        $qry = User::where('email','=',$credentials['email']);
    
        if($qry->count() > 0)
        {
            $user = $qry->select('dj_id','dj_name','email','password')->first();
    
    
            return $user;
        }
    
        return null;
    
    
    }
    
    /**
     * Validate a user against the given credentials.
     *
     * @param  IlluminateContractsAuthAuthenticatable $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
    
        // DIFFERENT THAN ORIGINAL ANSWER
        if($user->email == $credentials['email'] && Hash::check($credentials['password'], $user->getAuthPassword()))//$user->getAuthPassword() == md5($credentials['password'].Config::get('constants.SALT')))
        {
    
    
            //$user->last_login_time = Carbon::now();
            $user->save();
    
            return true;
        }
        return false;
    
    
    }
    }
    
  5. in App/Http/Controllers/Auth/AuthController.php change all 'name' to 'dj_name' and add your custom fields if you have them...you can also change 'email' to your email column name

  6. In IlluminateFoundationAuthUser.php add

    protected $table = 'djs';
    protected $primaryKey  = 'dj_id';
    
  7. In App/User.php change 'name' to 'dj_name' and add your custom fields. For changing 'password' column to your custom column name add

    public function getAuthPassword(){
        return $this->custom_password_column_name;
    }
    
  8. Now backend is all done, so you only have to change layouts login.blade.php, register.blade.php, app.blade.php...here you only have to change 'name' to 'dj_name', email, or your custom fields... !!! password field NEEDS to stay named password !!!

Also, to make unique email validation change AuthController.php

'custom_email_field' => 'required|email|max:255|unique:users',
to
'custom_email_field' => 'required|email|max:255|unique:custom_table_name',

Also, if you want to make custom created_at an updated_at fields change global variables in IlluminateDatabaseEloquentModel.php

const CREATED_AT = 'dj_created_at';
const UPDATED_AT = 'dj_updated_at';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...