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

前端 未结 3 1938
生来不讨喜
生来不讨喜 2020-12-28 11:19

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 th

相关标签:
3条回答
  • 2020-12-28 11:47

    A custom Auth::attempt() doesn't work for me by changing the model in auth.php like this:

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Person::class,
        ],
    ], 
    

    If I try to authenticate a Person via custom column names in Auth::attempt:

    if (Auth::attempt(['persUsername' => $request->user, 'persPassword' => $request->pass])) {
        return redirect()->intended('/');
    }
    

    I get the same error:

    ErrorException in EloquentUserProvider.php line 112: Undefined index: password

    But I can authenticate a Person like this:

    $person = Person
        ::where('persUsername', $request->user)
        ->where('persPassword', $request->pass)
        ->first();
    
    if (! is_null($person)) {
        if ($person->persUsername === $request->user && $person->persPassword === $request->pass) {
            Auth::login($person, false);
            return redirect()->intended('/');
        }
    }
    

    But that's not the way it should be, I guess.

    In the mentioned File (EloquentUserProvider.php), I see 'password' is hardcoded.

    public function retrieveByCredentials(array $credentials)
    {
        $query = $this->createModel()->newQuery();
    
        foreach ($credentials as $key => $value) {
            if (! Str::contains($key, 'password')) {
                $query->where($key, $value);
            }
        }
    
        return $query->first();
    }
    
    public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];
    
        return $this->hasher->check($plain, $user->getAuthPassword());
    }
    

    So there is actually no way to use a custom column name for passwords the easy way?

    0 讨论(0)
  • 2020-12-28 11:49

    This is easy simply use the desired column names in Auth::attempt()/method like so:

    if (Auth::attempt(['st_username' =>$username,'st_password' => $password])) { 
        // Authentication passed... 
        return redirect()>intended('dashboard'); 
    }
    

    Updated: If you also wish to change default authentication table which is users by default or change the model name or path App\User by default, you can find these settings in config\auth.php

    /*
    |--------------------------------------------------------------------------
    | 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' => 'users', 
    'table' => 'new_tables_for_authentication',
    
    
    
    /*
    |--------------------------------------------------------------------------
    | 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::class,
    'model' => App\Models\User::class,
    
    0 讨论(0)
  • 2020-12-28 12:01

    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
          App\Providers\CustomAuthProvider::class,
          ...
      ],
      
    3. Create CustomAuthProvider.php inside folder app\Providers

      namespace App\Providers;
      
      use Illuminate\Support\Facades\Auth;
      
      use App\Providers\CustomUserProvider;
      use Illuminate\Support\ServiceProvider;
      
      class CustomAuthProvider extends ServiceProvider {
      
          /**
           * Bootstrap the application services.
           *
           * @return void
           */
          public function boot()
          {
              Auth::provider('custom', function($app, array $config) {
             // Return an instance of             Illuminate\Contracts\Auth\UserProvider...
              return new CustomUserProvider($app['custom.connection']);
              });
          }
      
          /**
           * Register the application services.
           *
           * @return void
           */
          public function register()
          {
              //
          }
      }
      
    4. Create CustomUserProvider.php also inside folder app\Providers

      <?php
      
      namespace App\Providers;
      use App\User; use Carbon\Carbon;
      use Illuminate\Auth\GenericUser;
      use Illuminate\Contracts\Auth\Authenticatable;
      use Illuminate\Contracts\Auth\UserProvider;
      use Illuminate\Support\Facades\Hash;
      use Illuminate\Support\Facades\Log;
      
      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 = 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 \Illuminate\Contracts\Auth\Authenticatable|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  \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 = 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  \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
      
          // 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 Illuminate\Foundation\Auth\User.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 Illuminate\Database\Eloquent\Model.php

    const CREATED_AT = 'dj_created_at';
    const UPDATED_AT = 'dj_updated_at';
    
    0 讨论(0)
提交回复
热议问题