<?php
/**
 * Created by PhpStorm.
 * User: ywl
 * Date: 2017/4/13
 * Time: 下午12:03
 */

namespace App\Providers;

use App\User\Models\UserModel;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Support\Facades\Request;
use Tymon\JWTAuth\JWTAuth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Exceptions\ApiException;

class JwtUserProvider extends EloquentUserProvider
{
    /**
     * TODO 先将取用户与验证密码放到一个步骤里。 等新系统把取用户与验证密码分开成两个接口后再修改
     * @param array $credentials
     * @return UserModel|UserContract|null|void
     */
    public function retrieveByCredentials(array $credentials)
    {
        if (empty($credentials)) {
            return;
        }
        $userModel = new UserModel();
        $where = [];
        $where['user_name'] = $credentials['user_name'];
        $where['password'] = md5($credentials['password']);
        $where['status'] = 0;
        $userInfo = $userModel->alias('a')
            ->where($where)->selectRaw('a.*')->first();
        if (!empty($userInfo)) {
            $now = nowTime();
            $userInfo->last_login_time = $now;
            $userInfo->save();
            return $userInfo;
        } else {
            throw new ApiException(10001);
        }
    }

    public function validateCredentials(UserContract $user, array $credentials)
    {
        return true;
    }
}
