<?php

namespace App\Providers;

use App\Common\Facades\UserCenterFacade;
use App\Exceptions\ApiException;
use App\User;
use App\User\Facades\SysAdminUserFacade;
use App\User\Facades\UserFacade;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //配合 auth providers driver
       /* $this->app['auth']->provider('custom_database', function() {
            return new AppUserProvider(DB::connection(), $this->app['hash'], 'user');
        });*/
    }

    /**
     * Boot the authentication services for the application.
     *
     * @return void
     */
    public function boot()
    {
        $auth = app('auth');
        $reflClass = new \ReflectionClass($auth);
        $reflProp = $reflClass->getProperty('guards');
        $reflProp->setAccessible(true);
        $reflProp->setValue($auth, []);
        $reflProp = $reflClass->getProperty('customCreators');
        $reflProp->setAccessible(true);
        $reflProp->setValue($auth, []);
        $this->app['auth']->viaRequest('api', function ($request) {
            checkRedisPing();
            $token = $request->header('token');
            $token_update_time= config('cache.token_update_time');
            if(empty($token)){
                $token = $request->input('token');
            }
             if ($token) {
                $data = SysAdminUserFacade::findOneByToken($token);
                if (!empty($data)) {
                    //超过半小时 发送heartbeat
                    $time=time();
                    if ($data['expiration_time'] <($time + $token_update_time)) {
                        $data =   SysAdminUserFacade::updateUserInfoCache($token, $data);
                    }
                    return $data;
                }
            }
            return null;
        });
    }
}
