skip to Main Content

I really don’t know why, when I log Auth::user() in web.php, it will get the wrong auth user. But when I try to log in AuthController.php, it actually fine. I think there is a problem with sync or something else that must be frustating.

This is web.php

<?php

use IlluminateSupportFacadesRoute;
use AppHttpControllersAuthController;
use AppHttpControllersPantiController;
use AppHttpControllersProductController;
use AppHttpMiddlewareCheckRole;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesLog;

Route::get('/register', [AuthController::class, 'showRegisterForm'])->name('register');
Route::get('/login', [AuthController::class, 'showLoginForm'])->name('login');

Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);

Route::get('/product/{id}', [ProductController::class, 'show'])->name('product.detail');
Route::get('/panti/{id}', [PantiController::class, 'show'])->name('panti.detail');

Route::middleware('auth')->group(function () {
    Route::get('/', function (){
        $user = Auth::user();

        Log::info('Currently User logged in:', ['user' => $user]);

        if($user->role == 'donor'){
            return view('page.home.home-donor', ['user' => $user]);
        }else if($user->role== 'panti'){
            return view('page.home.home-panti', ['user' => $user]);
        }else if($user->role == 'admin'){
            return view('page.home.home-admin', ['user' => $user]);
        }
    })->name('home');

    Route::get('/catalog', function () {
        return view('page.catalog');
    })->name('catalog');
    
    Route::get('/panti', function () {
        return view('page.panti');
    })->name('panti');
    
    Route::get('/about', function () {
        return view('page.about');
    })->name('about');

    Route::get('/product/{id}', [ProductController::class, 'show'])->name('product.detail');
    
    Route::get('/panti/{id}', [PantiController::class, 'show'])->name('panti.detail');

    Route::get('/profile', function () {
        $user = Auth::user(); // Get the authenticated user
        return view('page.profile', ['user' => $user]);
    })->name('profile');

    Route::post('/logout', [AuthController::class, 'logout']);
});

This is AuthController.php

<?php

namespace AppHttpControllers;

use AppModelsUser;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesLog;
use IlluminateSupportFacadesValidator;

class AuthController extends Controller
{
    // Show the registration form
    public function showRegisterForm()
    {
        return view('auth.register');
    }

    // Show the login form
    public function showLoginForm()
    {
        return view('auth.login');
    }

    // Register user
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|string|max:100|unique:users',
            'name' => 'required|string|max:100',
            'email' => 'required|string|email|max:100|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'role' => 'required|in:donor,panti,admin',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        User::create([
            'username' => $request->username,
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => $request->role,
        ]);

        return redirect('/login')->with('success', 'Registration successful! Please login.');
    }

    // Login user
    public function login(Request $request)
    {
        $credentials = $request->only('username', 'password');

        $user = User::where('username', $credentials['username'])->first();

        if (!$user || !Hash::check($credentials['password'], $user->password)) {
            return redirect()->back()->withErrors(['login_error' => 'Invalid username or password.']);
        }
        
        Auth::login($user, true);
        $request->session()->regenerateToken();

        Log::info('User logged in:', ['user' => $user]);
        
        if (Auth::check()) {
            return redirect('/')->with('success', 'Login successful!');
        } else {
            return redirect('/login')->withErrors(['login_error' => 'Authentication failed.']);
        }        
    }

    // Logout
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();  // Invalidates the session
        $request->session()->regenerateToken();  // Regenerates the CSRF token to prevent CSRF attacks
        return redirect('/login')->with('success', 'Logged out successfully!');
    }
}

Here’s the log:

[2024-12-22 03:32:27] local.INFO: User logged in: {"user":{"App\Models\User":{"user_id":0,"username":"handphone","name":"handphone","email":"[email protected]","role":"donor","user_image":null,"remember_token":"fcvFDZa6WaOlVZTeVbEkLZN078B9RWR1jULhQZGzyHWCEsoZKRnQ7SLMzvYs","created_at":"2024-12-14T13:20:00.000000Z","updated_at":"2024-12-14T20:51:41.000000Z"}}} 
[2024-12-22 03:32:27] local.INFO: Currently User logged in: {"user":{"App\Models\User":{"user_id":0,"username":"sandwich","name":"sandwich","email":"[email protected]","role":"admin","user_image":null,"remember_token":"pZCLwvv2aMwnRwJPzULk403cTwWuYUcYPjvNi4EL8p7yVzMle7nC2gYP3Pho","created_at":"2024-12-15T13:48:17.000000Z","updated_at":"2024-12-15T20:48:23.000000Z"}}}

Look at the log, these are resulting different user. The correct user must be the "User logged in:" from AuthController.php and the wrong user is "Currently User logged in:" from web.php

I want to get login user attributes from web.php

2

Answers


  1. In your post Login method, I would suggest you replace the regenerateToken to just regenerate on the session. i.e

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

    to

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

    That way, the regenerate method deletes the previous session file and creates a fresh one for the newly authenticated user.

    Login or Signup to reply.
  2. Add $request->session()->regenerate(); in your login() method after Auth::login($user, true); to regenerate the session ID.

    Auth::login($user, true);
        $request->session()->regenerate();  
        $request->session()->regenerateToken();
    
        Log::info('User logged in:', ['user' => $user]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search