custom auth and hashing laravel 5.1

2020-03-08 07:30发布

问题:

I have an existing database.

users :
username => varchar
password => md5 hashing

I am new to laravel, I was try to create simple login and register from laravel docs, thats work fine, but in docs are create for laravel, now I want to create same login/register but with existing datas.

I was read some Question from How to use SHA1 encryption instead of BCrypt in Laravel 4? but I dont understand how to use it.

any adv?

sory for my bad grammer.

回答1:

I'll Try to answer my question. I take it from Facebook Group Laravel Indonesia

  • Create directory app/libraries

  • Add app/libraries to composer.json

    "classmap": ["database","app/libraries"],

  • Create MD5Hasher.php in app/libraries

    <?php    
    namespace App\Libraries;        
    use Illuminate\Contracts\Hashing\Hasher as HasherContract;
    
    class MD5Hasher implements HasherContract {
    
    public function make($value, array $options = array()) {
    $value = env('SALT', '').$value;
    return md5($value);
    }
    
    public function check($value, $hashedValue, array $options = array()) {
    return $this->make($value) === $hashedValue;
    }
    
    public function needsRehash($hashedValue, array $options = array()) {
    return false;
    }
    
    }
    
  • Create MD5HashServiceProvider.php in app/libraries

    <?php
    
    namespace App\Libraries;
    
    use Illuminate\Support\ServiceProvider;
    
    class MD5HashServiceProvider extends ServiceProvider {
    
    /**
    * Register the service provider.
    *
    * @return void
    */
    public function register() {
    $this->app['hash'] = $this->app->share(function () {
    return new MD5Hasher();
    });
    
    }
    
    /**
    * Get the services provided by the provider.
    *
    * @return array
    */
    public function provides() {
    return array('hash');
    }
    
    }
    
  • in config/app.php

    Find Illuminate\Hashing\HashServiceProvider::class,

    Change to App\Libraries\MD5HashServiceProvider::class,

  • in AuthController.php

    Add protected $username = 'username';

    return Validator::make($data, [
                //'name' => 'required|max:255',
                'username' => 'required',
                'password' => 'required|confirmed|min:5',
            ]);
    
    return User::create([
                //'name' => $data['name'],
                'username' => $data['username'],
                'password' => md5($data['password']),
            ]);
    
  • in App\Users.php

    Change protected $fillable = ['name', 'email', 'password'];

    To protected $fillable = ['username', 'password'];

  • Don't forget to run composer dumpautoload

I don't know what I am doing is right or not.

Regard