<?php

namespace Ignite\Core\Auth;

use Ignite\Core\Entities\User;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable;

class UserProvider extends EloquentUserProvider
{
    /**
     * 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)
    {
        // First check if User Account is Disabled
        if (! $user->status || (int) $user->status !== User::STAT_ACTIVE) {
            return false;
        }

        if (parent::validateCredentials($user, $credentials)) {
            return true;
        }

        $salt = trim(config('auth.password.salt'));
        $password = $credentials['password'];

        if ($this->validateSha1($user, $password, $salt)) {
            return true;
        }

        if ($this->validateSha512($user, $password, $salt)) {
            return true;
        }

        return false;
    }

    /**
     * Check the password against SHA-1 algorithm.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $password
     * @param  string $salt
     * @return bool
     */
    protected function validateSha1($user, $password, $salt)
    {
        $hash = sha1($salt . $password . $user->password_salt);

        return ($hash == $user->password);
    }

    /**
     * Check the password against SHA-512 algorithm.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable $user
     * @param  array  $password
     * @param  string $salt
     * @return bool
     */
    protected function validateSha512($user, $password, $salt)
    {
        $hash = hash('sha512', $salt . $password . $user->password_salt);

        return ($hash == $user->password);
    }
}
