在auth中间件中使用缓存

时间:2017-05-04 10:07:42

标签: php laravel

我想编写自己的auth路由中间件来使用用户缓存。如果我将在DB用户中使用缓存进行简单检查,那么我会看到

Call to a member function setCookie() on null

我应该使用UserProvider。但后来我不使用缓存。

是否可以像原始auth一样返回相同的结果但是在内部设置缓存?

我目前的代码是:

<?php
namespace Sakuicms\Auth\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Auth\AuthenticationException;


class Authenticate
{
    protected $auth;

    public function __construct(Auth $auth)
    {
      $this->auth = $auth;
    }

    protected function getName()
    {
      return 'login_'.config('auth.defaults.guard').'_'.sha1('Illuminate\Auth\SessionGuard');
    }

    public function handle($request, Closure $next, ...$guards)
    {
      $id = session($this->getName());
      if($id>0){
        $model = config('auth.providers.users.model');
        return \Cache::rememberForever('db.users.'.$id, function() use($model,$id){
          return $model::select(['id'])->where('id',$id)->first();
        });
      }
      throw new AuthenticationException('Unauthenticated.', $guards);
      return $next($request);
    }

}

修改 我解决了这个问题。当然这是我的错。我总是不返回$next($request)但是清除用户对象

以下是工作的代码

<?php
namespace Sakuicms\Auth\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Auth\AuthenticationException;
use Sakuicms\Auth\SessionGuard;

class Authenticate
{
    protected $auth;

    public function __construct(Auth $auth)
    {
      $this->auth = $auth;
    }

    protected function getName()
    {
      return 'login_'.config('auth.defaults.guard').'_'.sha1('Illuminate\Auth\SessionGuard');
    }

    public function handle($request, Closure $next, ...$guards)
    {
      $this->authenticate($guards);
      return $next($request);
    }

    protected function authenticate(array $guards)
    {
      if(empty($guards)){
        $id = session($this->getName());
        if($id>0){
          $model = config('auth.providers.users.model');
          return \Cache::rememberForever('db.users.'.$id, function() use($model,$id){
            return $model::select(['id'])->where('id',$id)->first();
          });
        }
      }

      foreach ($guards as $guard) {
          if ($this->auth->guard($guard)->check()) {
              return $this->auth->shouldUse($guard);
          }
      }

      throw new AuthenticationException('Unauthenticated.', $guards);
    }

}

可能存在更好/更优雅的解决方案,但现在对我来说没问题。我会在下一阶段重构它。

0 个答案:

没有答案
相关问题