I'd like to write own auth route middleware to use user cache. If I will simple check with cache in DB user then I see
Call to a member function setCookie() on null
I should use UserProvider probably. But then I don't use cache.
Does it any way to return same result like original auth but set cache inside?
My current code is:
<?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);
}
}
EDIT
I solve this problem. Of course it was my wrong. I always return not $next($request)
but clear user object
Below is code which work
<?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);
}
}
Probably exists better/more elegant solution but for now it's ok for me. I'll refactor it in next stage.