Instantly share code, notes, and snippets.

Embed
What would you like to do?
Laravel implement user session timeout

Laravel implement session timeout.

Add last_seen_at column to User model

php artisan make:migration add_last_seen_to_users_table --table=users

database/migrations/<TIMESTAMP>add_last_seen_to_users_table.php

class AddLastSeenToUsersTable extends Migration
{
  public function up()
  {
    Schema::table('users', function (Blueprint $table) {
      $table->timestamp('last_seen_at')->nullable();
    });
  }

  public function down()
  {
    Schema::table('users', function (Blueprint $table) {
      $table->dropColumn('last_seen_at');
    });
  }
}

Update database

php artisan migrate:refresh

Create session timeout middleware

php artisan make:middleware SessionTimeout

app/Http/Middleware/SessionTimeout.php

class SessionTimeout
{
  public function handle($request, Closure $next)
  {
    // If user is not logged in...
    if (!Auth::check()) {
      return $next($request);
    }

    $user = Auth::guard()->user();

    $now = Carbon::now();

    $last_seen = Carbon::parse($user->last_seen_at);

    $absence = $now->diffInMinutes($last_seen);

    // If user has been inactivity longer than the allowed inactivity period
    if ($absence > config('session.lifetime')) {
      Auth::guard()->logout();

      $request->session()->invalidate();

      return $next($request);
    }

    $user->last_seen_at = $now->format('Y-m-d H:i:s');
    $user->save();

    return $next($request);
  }
}

Register middleware to web guard

app/Http/Kernel.php

class Kernel extends HttpKernel
{
  // ...
  protected $middlewareGroups = [
    'web' => [
      // ...
      \App\Http\Middleware\SessionTimeout::class,
  ],
}

Update user last seen upon login

app/Http/Controllers/Auth/LoginController

class LoginController extends Controller
{
  // ...
  protected function authenticated(Request $request, $user)
  {
    $user->last_seen_at = Carbon::now()->format('Y-m-d H:i:s');
    $user->save();
  }
}

Set session lifetime

.env

# Session lifetime in minutes
SESSION_LIFETIME=10
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
class SessionTimeout
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!Auth::check()) {
return $next($request);
}
$user = Auth::guard()->user();
$now = Carbon::now();
$last_seen = Carbon::parse($user->last_seen_at);
$absence = $now->diffInMinutes($last_seen);
if ($absence > config('session.lifetime')) {
Auth::guard()->logout();
$request->session()->invalidate();
return $next($request);
}
$user->last_seen_at = $now->format('Y-m-d H:i:s');
$user->save();
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment