0

he creado un helper con una funcion propia para hashear el password(de nombre CustomHash) y registra bien pero no loguea, siguiendo un tutorial de preguntas similares hice lo siguiente:

Cree una carpeta libraries => App\libraries la cual contiene 2 archivos:

  • CustomHasher.php
  • CustomHashServiceProvider.php

el archivo CustomHasher.php se ve asi:

<?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;
      }

}

El archivo CustomHashServiceProvider.php se ve asi:

<?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');
    }

}

mi app/helpers.php

<?php

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

modifique el composer.json para cargar mis librerias

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

        "app/libraries"
    ]
},

entonces en App\config\app.php Providers comente:

//'Illuminate\Hashing\HashServiceProvider',

y puse debajo:

'CustomHashServiceProvider',

luego corri en consola

composer dump-autoload

y me tira el siguiente error:

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

que me falta o que estoy haciendo mal?

1 respuesta 1

1

Voy a explicarte la forma como funciona el login en Laravel y tu determinas cual es el mejor camino para lograr lo que deseas, que clases extender, etc:

Todo empieza después de las validaciones y de recibir los datos en Illuminate\Foundation\Auth\AuthenticatesUsers , en el método login():

/**
 * 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);
}

A continuación, en la siguiente línea es donde se realiza la verificación, o el "intento" de autenticación:

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

Esta línea nos lleva a Illuminate\Auth\SessionGuard , al métood 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;
}

Aquí nos importa la siguiente línea, en la cual se determina si las credenciales ingresadas son validas o no:

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

Eso nos lleva al método que está justo después del que estamos analizando (en el mismo archivo):

/**
 * 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);
}

Este método nos lleva al método validateCredentials() del proveedor, el cual puede estar localizado en:

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

Según la configuración de tu aplicación, en cualquiera de los dos casos, el contenido del método es el mismo:

/**
 * 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());
}

Aquí la segunda línea del método nos lleva al método check() del proveedor del hasher, el cual se encuentra en 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);
}

Como puedes ver finalmente se usa la función de php password_verify() para verificar la clave ingresada, por lo cual puedes intentar haciendo un override de este método o utilizando extensiones de los métodos que lo llaman, entre tantas otras posibilidades como reemplazar el Hasher. También podrías crear un servicio para este efecto.

3
  • wow gracias : analizando las funciones importantes serian function make y Hasher::needsRehash o la cosa es con password_verify()?? xd el 3 sep. 2016 a las 0:01
  • Por favor lee la respuesta bien, ahí están expuestos los métodos implicados.
    – Shaz
    el 3 sep. 2016 a las 2:47
  • no entiendo tu acertijo hombre porque no mejor dar una respuesta directa el 5 sep. 2016 a las 21:05

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.