litespeedtech / lscache-laravel

LSCache for Laravel framework
GNU General Public License v3.0
51 stars 14 forks source link

LS cache causes loading unauthenticated page after login for the first time #15

Closed parsagholipour closed 3 years ago

parsagholipour commented 3 years ago

The 'guest mode only' is on. After user log in I redirect it to the home page. For the first time the home page for unauthenticated users loads but after a refresh, the page changes and shows the logged-in user's name and information. I tried to check the Auth::check() condition after a successful login and redirection in LSCacheMiddleware using the dd method but it seems it doesn't even get executed at the first redirection. Handle method in LSCacheMiddleware:

    public function handle($request, Closure $next, string $lscache_control = null)
    {
        $response = $next($request);
        if (!strpos(URL::current(), 'login')) // added line
            dd(Auth::check()); // added line
        ...

I added !strpos(URL::current(), 'login') condition to be able to login. After successful login attempt and redirection to home page url ( '/') although !strpos(URL::current(), 'login') is true but it is still loading the page from cache (I expected to at least get false bool) but after another refresh I get the true bool.

I found a workaround but it results in dirty coding and dispensable concerns. I purged the homepage cache before the redirection and it fixed it. LSCache::purge('/');

lscache config:

return [
    /**
     * Enable ESI
     */
    'esi' => env('LSCACHE_ESI_ENABLED', false),

    /**
     * Default cache TTL in seconds
     */
    'default_ttl' => env('LSCACHE_DEFAULT_TTL', 15),

    /**
     * Default cache storage
     * private,no-cache,public,no-vary
     */
    'default_cacheability' => env('LSCACHE_DEFAULT_CACHEABILITY', 'no-cache'),

    /**
     * Guest only mode (Do not cache logged in users)
     */
     'guest_only' => env('LSCACHE_GUEST_ONLY', true),
];

Laravel version: 6.2 PHP version in composer: 7.2 PHP version: 7.3

lucasRolff commented 3 years ago

Hi @parsagholipour,

I have to think of a good solution for this - likely what could be done is using the "vary" cookies in lscache, when people are logged in - this way when we see the cookie it won't cache it.

Depending on the name of the authentication cookie, you could temporarily use something like:

RewriteEngine On
RewriteRule .* - [E=Cache-Vary:my_auth_cookie_name]

That should do the trick!

parsagholipour commented 3 years ago

Thank you, It worked very well. RewriteRule .* - [E=Cache-Vary:Authorization]

parsagholipour commented 3 years ago

As this problem is so common documenting the solution would be awesome.