These are the files that I have for my authentication. I have student, admins, and super_admins.
class AuthenticatedSessionController extends Controller
{
public function create(): View
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*/
public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
$request->session()->regenerate();
// Retrieve the authenticated user from the correct guard
$user = Auth::user();
// Check user's role and redirect accordingly
if ($user instanceof AppModelsStudent && $user->hasRole('student')) {
return redirect()->intended(route('student.dashboard'));
} elseif ($user instanceof AppModelsAdmin && $user->hasRole('academichead')) {
return redirect()->intended(route('admin.dashboard'));
} elseif ($user instanceof AppModelsSuperAdmin && $user->hasRole('registrar')) {
return redirect()->intended(route('superadmin.dashboard'));
} else {
// Default redirect if no specific role match found
return redirect()->intended('/');
}
}
/**
* Destroy an authenticated session.
*/
public function destroy(Request $request)
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
This is from my LoginController in Auth
class LoginController extends Controller
{
public function showLoginForm()
{
return view('auth.login');
}
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::guard('academichead')->attempt($credentials)) {
return redirect()->intended('/admin/dashboard');
} elseif (Auth::guard('registrar')->attempt($credentials)) {
return redirect()->intended('/superadmin/dashboard');
} elseif (Auth::guard('web')->attempt($credentials)) {
return redirect()->intended('/user/dashboard');
}
throw ValidationException::withMessages([
'email' => [trans('auth.failed')],
]);
}
public function logout()
{
if (Auth::guard('academichead')->check()) {
Auth::guard('academichead')->logout();
} elseif (Auth::guard('registrar')->check()) {
Auth::guard('registrar')->logout();
} else {
Auth::guard('web')->logout();
}
return redirect('/');
}
}
This is from my LoginRequest.php
class LoginRequest extends FormRequest
{
protected $guard;
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, IlluminateContractsValidationRule|array|string>
*/
public function rules(): array
{
return [
'email' => ['required', 'string', 'email'],
'password' => ['required', 'string'],
];
}
/**
* Attempt to authenticate the request's credentials.
*
* @throws IlluminateValidationValidationException
*/
public function authenticate(): void
{
$this->ensureIsNotRateLimited();
$credentials = $this->only('email', 'password');
// Try to authenticate against multiple guards
// if (Auth::guard('academichead')->attempt($credentials, $this->boolean('remember'))) {
// $this->guard = 'academichead';
// } elseif (Auth::guard('registrar')->attempt($credentials, $this->boolean('remember'))) {
// $this->guard = 'registrar';
// } elseif (Auth::guard('web')->attempt($credentials, $this->boolean('remember'))) {
// $this->guard = 'web';
// } else {
// RateLimiter::hit($this->throttleKey());
// throw ValidationException::withMessages([
// 'email' => trans('auth.failed'),
// ]);
// }
if (Auth::guard('academichead')->attempt($credentials)) {
$this->guard = 'academichead';
} elseif (Auth::guard('registrar')->attempt($credentials)) {
$this->guard = 'registrar';
} elseif (Auth::guard('web')->attempt($credentials)) {
$this->guard = 'web';
} else {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
/**
* Ensure the login request is not rate limited.
*
* @throws IlluminateValidationValidationException
*/
public function ensureIsNotRateLimited(): void
{
if (!RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*/
public function throttleKey(): string
{
return Str::transliterate(Str::lower($this->string('email')) . '|' . $this->ip());
}
/**
* Get the authenticated guard.
*/
public function authenticatedGuard(): string
{
return $this->guard;
}
}
This is from my web.php
Route::get('/', function () {
return view('welcome');
});
// Route::get('/admin/dashboard', function () {
// return view('admin.dashboard.index');
// });
Route::get('login', [LoginController::class, 'showLoginForm'])->name('login');
Route::post('login', [LoginController::class, 'login'])->name('login.post');
Route::post('logout', [LoginController::class, 'logout'])->name('logout');
Route::prefix('student')->middleware(['auth'])->group(function () {
Route::get('/dashboard', [StudentController::class, 'index'])->name('student.dashboard');
});
Route::prefix('academichead')->middleware(['auth:academichead'])->group(function () {
Route::get('/dashboard', [AdminDashboardController::class, 'index'])->name('admin.dashboard');
});
Route::prefix('registrar')->middleware(['auth:registrar'])->group(function () {
Route::get('/dashboard', [SuperAdminController::class, 'index'])->name('superadmin.dashboard');
});
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');
Route::middleware('auth')->group(function () {
Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});
require __DIR__ . '/auth.php';
When I log in, only the students will be authenticated. The admins and super_admins can’t. I’m not using the default Users because of our requirements.
3