Commit a4a60e23 by Amshar

Authentication and middleware

parent 31e3e9e9
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/**
* Show the login form.
*
* This is what guests see when they visit /login.
*/
public function create()
{
return view('auth.login'); // returning the login form
}
/**
* Handle a login attempt.
*
* 1. Validate — make sure both fields are filled in properly
* 2. Attempt — find the user by email and check the hashed password
* 3. Regenerate — give the session a new ID to prevent session fixation attacks
* 4. Redirect — send them to the page they originally wanted, or home
*
* If login fails, we go back with one generic error message.
* We never say "wrong password" or "email not found" separately,
* because that tells an attacker which one was correct.
*/
public function store(Request $request)
{
// Step 1: basic validation — are the fields filled in?
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required',
]);
// Step 2: check if the "remember me" box was ticked
$remember = $request->boolean('remember');
// Step 3: try to log in with the given email and password
if (Auth::attempt($credentials, $remember)) {
// Step 4: new session ID so the old one can't be reused
$request->session()->regenerate();
// Save the current time as the user's last login
// now() gives a Carbon timestamp like "2026-10-29 10:30:00"
auth()->user()->update(['last_login_at' => now()]);
// Send them where they were trying to go, or home
return redirect()->intended(route('home'));
}
// Login failed — go back with a generic error on the email field
// onlyInput('email') refills the email but NOT the password
return back()->withErrors([
'email' => 'Invalid email or password.',
])->onlyInput('email');
}
/**
* Log the user out.
*
* Three things happen:
* 1. Auth::logout() — removes the user from this request
* 2. invalidate() — destroys all session data
* 3. regenerateToken() — new CSRF token so old forms can't be replayed
*/
public function destroy(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect()->route('login'); // Bring back to login page after logout
}
}
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class EnsureUserIsActive
{
/**
* Check if the logged-in user's account is still active.
*
* Think of this like a security guard at the office door.
* Even if you have a valid access card (session), the guard
* checks whether your card has been deactivated. If it has,
* you're escorted out.
*
* $request->user() gets the currently logged-in user.
* The ?-> (nullsafe operator) means: if there's no user,
* just return null instead of crashing.
*
* $next($request) passes the request on to the next layer.
* Without this line, the page would be completely blank —
* the request gets stuck here and never reaches the controller.
*/
public function handle(Request $request, Closure $next): Response
{
// If the user is logged in but their account is disabled...
if (! $request->user()?->is_active) {
// Log them out immediately
Auth::logout();
// Send them to the login page with an error message
return redirect()->route('login')
->withErrors(['email' => 'Account disabled.']);
}
// Account is active — let the request continue
return $next($request);
}
}
\ No newline at end of file
...@@ -12,7 +12,10 @@ ...@@ -12,7 +12,10 @@
health: '/up', health: '/up',
) )
->withMiddleware(function (Middleware $middleware): void { ->withMiddleware(function (Middleware $middleware): void {
// // Give EnsureUserIsActive a short name so we can use 'active' in routes
$middleware->alias([
'active' => \App\Http\Middleware\EnsureUserIsActive::class,
]);
}) })
->withExceptions(function (Exceptions $exceptions): void { ->withExceptions(function (Exceptions $exceptions): void {
$exceptions->shouldRenderJsonWhen( $exceptions->shouldRenderJsonWhen(
......
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
// RUN THE MIGRATION
/**
* Add an is_active flag to the users table.
*
* This lets us disable a user's account without deleting it.
* default(true) means every existing user stays active after
* the migration runs — nobody gets locked out by accident.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
// Place the new column right after the password column
// so the table reads in a logical order
$table->boolean('is_active')
->default(true)
->after('password');
});
}
// REVERSE THE MIGRATION
/**
* Undo: remove the column if we roll back.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('is_active');
});
}
};
\ No newline at end of file
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Add a last_login_at timestamp to the users table.
*
* This records the exact date and time of each successful login.
* We'll display it on the home page as a friendly "2 hours ago"
* using Carbon's diffForHumans() method.
*
* Nullable because when a user is first created (e.g. by the seeder),
* they haven't logged in yet, so there's no value to store.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
// timestamp() creates a datetime column in MySQL.
// nullable() allows NULL — without it, MySQL would require
// a value for every row, and our seeded users don't have one yet.
// after('is_active') places it right after is_active
// so the columns stay in a logical reading order.
$table->timestamp('last_login_at')
->nullable()
->after('is_active');
});
}
/**
* Undo: remove the column if we roll back.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('last_login_at');
});
}
};
\ No newline at end of file
...@@ -25,6 +25,7 @@ public function run(): void ...@@ -25,6 +25,7 @@ public function run(): void
$this->call([ $this->call([
DepartmentSeeder::class, DepartmentSeeder::class,
PositionSeeder::class, PositionSeeder::class,
UserSeeder::class,
]); ]);
} }
} }
\ No newline at end of file
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
class UserSeeder extends Seeder
{
/**
* Create two test users for local development.
*
* "password" is the plain-text password for both.
* Hash::make() turns it into a bcrypt hash before saving,
* so the database never stores the real password.
*
* One user is active (can log in), the other is disabled
* (will be blocked by the EnsureUserIsActive middleware later).
*/
public function run(): void
{
User::create([
'name' => 'Aina Rahman',
'email' => 'aina@minioffice.test',
'password' => Hash::make('password'),
'is_active' => true,
]);
User::create([
'name' => 'Disabled User',
'email' => 'disabled@minioffice.test',
'password' => Hash::make('password'),
'is_active' => false,
]);
User::create([
'name' => 'Amshar',
'email' => 'amshar@gmail.com',
'password' => Hash::make('password'),
'is_active' => true,
]);
User::create([
'name' => 'Ali',
'email' => 'ali@gmail.com',
'password' => Hash::make('password'),
'is_active' => false,
]);
}
}
{{--
Login page — the first thing a guest sees.
Uses the guest layout (no sidebar) instead of the main app layout.
The form POSTs to the 'login' route, which hits LoginController@store.
--}}
@extends('layouts.guest')
@section('title', 'Log in')
@section('content')
<div class="card shadow-sm">
<div class="card-body p-4">
<h3 class="card-title text-center mb-4">Mini Office</h3>
{{--
The form sends a POST request to /login (LoginController@store).
@csrf adds a hidden token so Laravel knows this form came from
our site, not from an attacker.
--}}
<form method="POST" action="{{ route('login') }}">
@csrf
{{-- Email field --}}
<div class="mb-3">
<label for="email" class="form-label">Email</label>
{{--
old('email') refills the email after a failed login attempt.
Remember in the controller we had onlyInput('email') — that's
what puts the email back into old() so the user doesn't have
to retype it.
@error('email') adds the 'is-invalid' class to make the
border red when there's an error.
--}}
<input type="email" name="email" id="email" value="{{ old('email') }}" class="form-control @error('email') is-invalid @enderror"
autofocus>
{{--
This only appears when validation fails or login is wrong.
$message contains whatever we put in withErrors() in the controller,
which was "Invalid email or password."
--}}
@error('email')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
{{--
Password field — notice there's no old() or value="" here.
We NEVER refill passwords. If login fails, the user has to
retype it. This is a security practice.
--}}
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" name="password" id="password" class="form-control">
</div>
{{--
Remember me checkbox.
In the controller, $request->boolean('remember') reads this.
If ticked, Auth::attempt() creates a long-lived "remember" cookie
so the user stays logged in even after closing the browser.
--}}
<div class="mb-3 form-check">
<input type="checkbox" name="remember" id="remember" class="form-check-input">
<label for="remember" class="form-check-label">Remember me</label>
</div>
{{-- w-100 makes the button full-width to match the form --}}
<button type="submit" class="btn btn-primary w-100">Log in</button>
</form>
</div>
</div>
@endsection
\ No newline at end of file
{{--
Guest layout — used for pages where the user is NOT logged in (like the login page).
This is separate from layouts/app.blade.php because guests shouldn't see
the sidebar, header, or navigation. It's just a centered card on a plain background.
--}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{-- Each page fills in its own title, e.g. "Log in - Mini Office" --}}
<title>@yield('title') - Mini Office</title> {{--If a child page used "@section('title', 'Register')" It will be Register - Mini Office--}}
{{-- Load Bootstrap CSS and JS through Vite, same as the main layout --}}
@vite('resources/js/app.js')
</head>
<body class="bg-light">
{{-- Center the content in a narrow column so the login form doesn't stretch full-width --}}
<div class="container">
<div class="row justify-content-center mt-5">
<div class="col-md-5">
@yield('content')
</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
...@@ -5,4 +5,20 @@ ...@@ -5,4 +5,20 @@
@section('content') {{--To put this content "@yield('content')" in layouts/app.blade.php--}} @section('content') {{--To put this content "@yield('content')" in layouts/app.blade.php--}}
<h1>Welcome to Mini Office</h1> <h1>Welcome to Mini Office</h1>
<p>This is the internal management system for our company.</p> <p>This is the internal management system for our company.</p>
{{--
Show when the user last logged in.
last_login_at is a timestamp like "2026-10-29 10:30:00".
Carbon::parse() turns it into a Carbon object so we can call
diffForHumans(), which converts it to a friendly string
like "2 hours ago" or "just now".
The @if check handles the first-ever login, where
last_login_at is still null (no previous login to show).
--}}
@if (auth()->user()->last_login_at)
<p class="text-muted">
Last signed in {{ \Carbon\Carbon::parse(auth()->user()->last_login_at)->diffForHumans() }}
</p>
@endif
@endsection @endsection
\ No newline at end of file
{{--
The top navigation bar.
navbar-brand is a Bootstrap class that makes the text
larger and bolder than regular nav links, so it stands
out as the site name. href="{{ route('home') }}" means
clicking it always takes you to the home page.
justify-content-between pushes the brand to the left
and the user info to the right.
--}}
<nav class="navbar navbar-dark bg-dark px-3 shadow-sm"> <nav class="navbar navbar-dark bg-dark px-3 shadow-sm">
<a class="navbar-brand fw-bold" href="{{ route('home') }}"> <a class="navbar-brand fw-bold" href="{{ route('home') }}">
Mini Office Mini Office
</a> </a>
</nav>
{{-- {{--
This is a link styled as the brand or logo of the site. Show the signed-in user's name and a Log Out button.
navbar-brand is a Bootstrap class that makes the text
larger and bolder than regular nav links, so it stands
out as the site name. href="{{ route('home') }}" means
clicking it always takes you to the home page. Remember,
route('home') looks up the named route we defined in
web.php and outputs /.
If you had defined the route as Route::get('/dashboard', 'home')->name('home'), auth()->user()->name pulls the name from the session —
then route('home') would output /dashboard instead. That's the whole benefit Laravel already knows who's logged in from the session cookie.
of named routes: you refer to the name, and Laravel figures out the actual URL
for you.
--}}
{{-- Logout is a POST form, not a plain link. Why? Because a GET link
STYLING could be triggered by a bot, a prefetch, or an <img> tag pointing
Added shadow-sm for a subtle drop shadow so the header to /logout — any of those would log the user out without them clicking.
feels like it floats above the content. A POST form with @csrf can only be submitted intentionally.
--}} --}}
\ No newline at end of file <div class="d-flex align-items-center gap-2">
{{--pulls the name from the session--}}
<span class="text-white">{{ auth()->user()->name }}</span>
<form method="POST" action="{{ route('logout') }}">
@csrf
<button type="submit" class="btn btn-sm btn-light">Log out</button>
</form>
</div>
</nav>
\ No newline at end of file
<?php <?php
use App\Http\Controllers\PositionController; use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\DepartmentController; use App\Http\Controllers\DepartmentController;
use App\Http\Controllers\PageController; use App\Http\Controllers\PageController;
use App\Http\Controllers\PositionController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::controller(PageController::class)->group(function () { //This tells Laravel "every route inside this group uses PageController and not DepartmentController /*
Route::get('/', 'home')->name('home'); // This is to route to home page |--------------------------------------------------------------------------
Route::get('/about', 'about')->name('about'); // This is to route to about page | Guest Routes
Route::get('/services', 'services')->name('services'); // This is to route to services page |--------------------------------------------------------------------------
Route::get('/contact', 'contact')->name('contact'); // This is to route to contact page |
}); | These routes are wrapped in the 'guest' middleware, which means
| only signed-out users can reach them. If a logged-in user tries
| to visit /login, they'll be redirected to the home page instead
| of seeing the login form again.
|
*/
Route::middleware('guest')->group(function () {
Route::get('/login', [LoginController::class, 'create'])
->name('login');
Route::resource('departments', DepartmentController::class); // registers seven routes that all point to your DepartmentController. Put this outside PageController Route::post('/login', [LoginController::class, 'store']);
Route::resource('positions', PositionController::class); // registers seven routes that all point to your PositionController.php. Put this outside PageController });
/* /*
Route::get creates one single route. Your About page |--------------------------------------------------------------------------
only needs one route: when someone visits /about, show | Authenticated Routes
the about page. That's it. No forms, no saving, no |--------------------------------------------------------------------------
deleting. One URL, one method, done. |
| Everything inside this group requires a logged-in user.
Route::resource creates seven routes at once. Your | If a guest tries to visit any of these, the 'auth' middleware
Departments module needs all seven because it has a | sends them to the route named 'login' — which is the GET /login above.
list page, a create form, saving, viewing, editing, |
updating, and deleting. You could write them all individually */
with Route::get, Route::post, Route::put, and Route::delete, Route::middleware(['auth', 'active'])->group(function () {
// Logout — a POST route so a link or image can't log someone out
Route::post('/logout', [LoginController::class, 'destroy'])
->name('logout');
// Static pages
Route::get('/', [PageController::class, 'home'])->name('home');
Route::get('/about', [PageController::class, 'about'])->name('about');
Route::get('/services', [PageController::class, 'services'])->name('services');
Route::get('/contact', [PageController::class, 'contact'])->name('contact');
// CRUD modules from Month 1
Route::resource('departments', DepartmentController::class);
Route::resource('positions', PositionController::class);
});
/* CHANGE FROM Route::middleware('auth')... to Route::middleware(['auth', 'active'])
The auth middleware only checks “is this person logged in?”
But it doesn’t know whether the account has been disabled
after they logged in.
Imagine you log in at 9am, and at 10am your admin disables your
account. Without the active middleware, you’d still be able to
use the app for the rest of the day because your session is still
valid. The auth middleware sees your session cookie and says “yep,
they’re logged in, let them through.”
Adding active means every request also checks the is_active column.
So the moment your account gets disabled, the very next page you
try to visit logs you out and shows “Account disabled.”
The square brackets ['auth', 'active'] just let you stack two
middleware together. The request passes through them one after
another, like two security checkpoints. First auth asks “do you
have a valid session?” and then active asks “is your account still
enabled?”
*/ */
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment