Laravel 5. * add own hash

0

I have created a helper with a proper function to hash the password (named CustomHash) and it registers well but does not log in, following a tutorial of similar questions I did the following:

Create a folder libraries = > App \ libraries which contains 2 files:

  • CustomHasher.php
  • CustomHashServiceProvider.php

the CustomHasher.php file looks like this:

<?php

namespace Libraries;

class CustomHasher implements Illuminat\Contracts\Hashing\Hasher {

    /**
     * Hash the given value.
     *
     * @param  string  $value
     * @return array   $options
     * @return string
     */

    public function make($value, array $options = array()) {
        return hash('customHash', $value);
    }

    /**
     * Check the given plain value against a hash.
     *
     * @param string $value
     * @param string $hashedValue
     * @param array $options
     * @return bool
     */

     public function check($value, $hashedValue, array $options = array()) {
         return $this->make($value) === $hashedValue;
     }

     /**
      * Check if the given hash has been using the given options.
      * @param string $hashedValue
      * @param array $options
      * @return bool
      */

      public function needsRehash($hashedValue, array $options = array()) {
          return false;
      }

}

The CustomHashServiceProvider.php file looks like this:

<?php
namespace Libraries;

use Libraries\SHAHasher;
use Illuminate\Hashing\HashServiceProvider;

class SHAHashServiceProvider extends Illuminate\Support\ServiceProvider {

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register() {
        $this->app['hash'] = $this->app->share(function () {
            return new CustomHasher();
        });

    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides() {
        return array('hash');
    }

}

my app / helpers.php

<?php

function customHash($value) {
    $value = strtoupper(
         sha1(
             sha1($value, true)
         )
    );
    $value = '*' . $value;
    return $value;
}

modify the composer.json to load my libraries

"autoload": {
    "classmap": [
        // ...

        "app/libraries"
    ]
},

then in App \ config \ app.php Providers comment:

//'Illuminate\Hashing\HashServiceProvider',

and I put below:

'CustomHashServiceProvider',

Then I ran on console

composer dump-autoload

and it throws me the following error:

FatalThrowableError in ProviderRepository.php line 146:
Class 'CustomHashServiceProvider' not found

What am I missing or what am I doing wrong?

    
asked by Devil System 03.09.2016 в 00:21
source

1 answer

1

I will explain how the login in Laravel works and you determine which is the best way to achieve what you want, what classes to extend, etc:

It all starts after the validations and to receive the data in Illuminate \ Foundation \ Auth \ AuthenticatesUsers , in the login () method:

/**
 * Handle a login request to the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function login(Request $request)
{
    $this->validateLogin($request);

    // If the class is using the ThrottlesLogins trait, we can automatically throttle
    // the login attempts for this application. We'll key this by the username and
    // the IP address of the client making these requests into this application.
    $throttles = $this->isUsingThrottlesLoginsTrait();

    if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);

        return $this->sendLockoutResponse($request);
    }

    $credentials = $this->getCredentials($request);

    if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
        return $this->handleUserWasAuthenticated($request, $throttles);
    }

    // If the login attempt was unsuccessful we will increment the number of attempts
    // to login and redirect the user back to the login form. Of course, when this
    // user surpasses their maximum number of attempts they will get locked out.
    if ($throttles && ! $lockedOut) {
        $this->incrementLoginAttempts($request);
    }

    return $this->sendFailedLoginResponse($request);
}

Next, on the next line is where the verification is done, or the "attempt" to authenticate:

if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {

This line takes us to Illuminate \ Auth \ SessionGuard , to the method attempt ():

/**
 * Attempt to authenticate a user using the given credentials.
 *
 * @param  array  $credentials
 * @param  bool   $remember
 * @param  bool   $login
 * @return bool
 */
public function attempt(array $credentials = [], $remember = false, $login = true)
{
    $this->fireAttemptEvent($credentials, $remember, $login);

    $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);

    // If an implementation of UserInterface was returned, we'll ask the provider
    // to validate the user against the given credentials, and if they are in
    // fact valid we'll log the users into the application and return true.
    if ($this->hasValidCredentials($user, $credentials)) {
        if ($login) {
            $this->login($user, $remember);
        }

        return true;
    }

    // If the authentication attempt fails we will fire an event so that the user
    // may be notified of any suspicious attempts to access their account from
    // an unrecognized user. A developer may listen to this event as needed.
    if ($login) {
        $this->fireFailedEvent($user, $credentials);
    }

    return false;
}

Here we are interested in the following line, which determines whether the credentials entered are valid or not:

    if ($this->hasValidCredentials($user, $credentials)) {

That brings us to the method that is right after the one we are analyzing (in the same file):

/**
 * Determine if the user matches the credentials.
 *
 * @param  mixed  $user
 * @param  array  $credentials
 * @return bool
 */
protected function hasValidCredentials($user, $credentials)
{
    return ! is_null($user) && $this->provider->validateCredentials($user, $credentials);
}

This method takes us to the vendor's validateCredentials () method, which can be located at:

  • Illuminate \ Auth \ DatabaseUserProvider
  • Illuminate \ Auth \ EloquentUserProvider

Depending on the configuration of your application, in either case, the content of the method is the same:

/**
 * Validate a user against the given credentials.
 *
 * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
 * @param  array  $credentials
 * @return bool
 */
public function validateCredentials(UserContract $user, array $credentials)
{
    $plain = $credentials['password'];

    return $this->hasher->check($plain, $user->getAuthPassword());
}

Here the second line of the method takes us to the check () method of the hasher provider, which is in Illuminate \ Hashing \ BcryptHasher :

/**
 * Check the given plain value against a hash.
 *
 * @param  string  $value
 * @param  string  $hashedValue
 * @param  array   $options
 * @return bool
 */
public function check($value, $hashedValue, array $options = [])
{
    if (strlen($hashedValue) === 0) {
        return false;
    }

    return password_verify($value, $hashedValue);
}

As you can see finally the php function password_verify () is used to verify the key entered, so you can try doing an override of this method or using extensions of the methods that call it, among many other possibilities such as replacing the Hasher. You could also create a service for this purpose.

    
answered by 03.09.2016 в 01:00