Commit eae52eb4 by Amshar

WEEK 9 - ROLES, PERMISSIONS & DYNAMIC MENU

parent 36003fc5
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
use App\Models\Position; use App\Models\Position;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Gate;
class StaffController extends Controller class StaffController extends Controller
{ {
...@@ -36,6 +37,15 @@ class StaffController extends Controller ...@@ -36,6 +37,15 @@ class StaffController extends Controller
public function index(Request $request) public function index(Request $request)
{ {
// Policy check: may this user see the staff list at all?
// viewAny runs first, so a Staff user gets a 403 here
// before any database query runs.
Gate::authorize('viewAny', Staff::class);
// The Policy decides WHETHER you may see the list.
// The query below decides WHICH rows you see.
$user = $request->user();
// Validate the sort value — only allow these three options. // Validate the sort value — only allow these three options.
// If someone tampers with the URL and sends ?sort=hackme, // If someone tampers with the URL and sends ?sort=hackme,
// Laravel rejects it silently and $sort stays null. // Laravel rejects it silently and $sort stays null.
...@@ -44,6 +54,9 @@ public function index(Request $request) ...@@ -44,6 +54,9 @@ public function index(Request $request)
: 'name'; : 'name';
$staff = Staff::with(['department', 'position']) $staff = Staff::with(['department', 'position'])
// Scope: when the logged-in user is a Manager, only show staff
// from their own department. Admins skip this line completely.
->when($user->isManager(), fn ($query) => $query->where('department_id', $user->department_id)) // this line only applies to manager
->when($request->search, function ($query, $term) { ->when($request->search, function ($query, $term) {
// Wrap the OR conditions in a group so the department // Wrap the OR conditions in a group so the department
// filter still works. Without the group, a department // filter still works. Without the group, a department
...@@ -85,7 +98,14 @@ public function index(Request $request) ...@@ -85,7 +98,14 @@ public function index(Request $request)
->withQueryString(); ->withQueryString();
// The department list is for the filter dropdown, not the staff data // The department list is for the filter dropdown, not the staff data
$departments = Department::orderBy('name')->get(); // Get the departments for the filter dropdown, sorted A-Z.
$departments = Department::orderBy('name')
// If the logged-in user is a Manager, keep only their own department,
// so the dropdown doesn't offer departments they can't see.
// Admins skip this line and get the full list.
->when($user->isManager(), fn ($query) => $query->where('id', $user->department_id))
// Run the query and return the results.
->get();
// Same thing for positions — we need the full list so the // Same thing for positions — we need the full list so the
// filter dropdown can show all available positions to pick from. // filter dropdown can show all available positions to pick from.
$positions = \App\Models\Position::orderBy('name')->get(); $positions = \App\Models\Position::orderBy('name')->get();
...@@ -101,6 +121,8 @@ public function index(Request $request) ...@@ -101,6 +121,8 @@ public function index(Request $request)
*/ */
public function create() public function create()
{ {
Gate::authorize('create', Staff::class);
// We need the full list of departments and positions so the // We need the full list of departments and positions so the
// form can show them as dropdown options for the user to pick from. // form can show them as dropdown options for the user to pick from.
$departments = Department::orderBy('name')->get(); $departments = Department::orderBy('name')->get();
...@@ -128,6 +150,8 @@ public function create() ...@@ -128,6 +150,8 @@ public function create()
*/ */
public function store(StoreStaffRequest $request) public function store(StoreStaffRequest $request)
{ {
Gate::authorize('create', Staff::class);
// Get all validated fields EXCEPT the photo file object. // Get all validated fields EXCEPT the photo file object.
// We handle the photo and file with the datas separately below because we need to // We handle the photo and file with the datas separately below because we need to
// save to storage/app/public/staff-photos/ (the public disk, accessible by URL) for photos. // save to storage/app/public/staff-photos/ (the public disk, accessible by URL) for photos.
...@@ -170,6 +194,10 @@ public function store(StoreStaffRequest $request) ...@@ -170,6 +194,10 @@ public function store(StoreStaffRequest $request)
*/ */
public function show(Staff $staff) public function show(Staff $staff)
{ {
// Is this user allowed to open THIS exact profile?
// This is what stops a Manager typing /staff/42 from another department.
Gate::authorize('view', $staff);
return view('staff.show', compact('staff')); return view('staff.show', compact('staff'));
} }
...@@ -181,6 +209,8 @@ public function show(Staff $staff) ...@@ -181,6 +209,8 @@ public function show(Staff $staff)
*/ */
public function edit(Staff $staff) public function edit(Staff $staff)
{ {
Gate::authorize('update', $staff);
// Same dropdown lists as create(), plus the existing staff record // Same dropdown lists as create(), plus the existing staff record
// so the form can pre-fill every field with their current values. // so the form can pre-fill every field with their current values.
$departments = Department::orderBy('name')->get(); $departments = Department::orderBy('name')->get();
...@@ -200,9 +230,14 @@ public function edit(Staff $staff) ...@@ -200,9 +230,14 @@ public function edit(Staff $staff)
*/ */
public function update(UpdateStaffRequest $request, Staff $staff) public function update(UpdateStaffRequest $request, Staff $staff)
{ {
Gate::authorize('update', $staff);
// Get all validated fields except the photo and contract file objects, // Get all validated fields except the photo and contract file objects,
// same as store(). We handle files separately below. // same as store(). We handle files separately below.
$data = $request->safe()->except(['photo', 'contract']); $data = $request->safe()->except(['photo', 'contract']); //What unset does, it removes that one item (in this case departmen_id since we want to avoid manager to change the department) from the list before saving.
// So that's why we said we drop it
// If the user picked a new photo... // If the user picked a new photo...
if ($request->hasFile('photo')) { if ($request->hasFile('photo')) {
...@@ -250,6 +285,8 @@ public function update(UpdateStaffRequest $request, Staff $staff) ...@@ -250,6 +285,8 @@ public function update(UpdateStaffRequest $request, Staff $staff)
*/ */
public function destroy(Staff $staff) public function destroy(Staff $staff)
{ {
Gate::authorize('delete', $staff);
// Remove the photo file from disk if one exists. // Remove the photo file from disk if one exists.
if ($staff->photo_path) { if ($staff->photo_path) {
Storage::disk('public')->delete($staff->photo_path); Storage::disk('public')->delete($staff->photo_path);
...@@ -275,6 +312,11 @@ public function destroy(Staff $staff) ...@@ -275,6 +312,11 @@ public function destroy(Staff $staff)
*/ */
public function downloadContract(Staff $staff) public function downloadContract(Staff $staff)
{ {
// Contracts are private files. Anyone who may view this profile
// may download its contract. Without this line, a Staff user could
// download ANY contract just by typing /staff/{id}/contract.
Gate::authorize('view', $staff);
// If there's no contract, show a 404 instead of an error // If there's no contract, show a 404 instead of an error
if (! $staff->contract_path) { if (! $staff->contract_path) {
abort(404); abort(404);
......
<?php
namespace App\Http\Controllers;
use App\Models\Department;
use App\Models\Staff;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
class UserController extends Controller
{
// The three allowed roles, kept in one place so the validation
// rule and the dropdown in the form can never disagree.
// rejects if someone opens devtoool and change from staff role
//to admin
private const ROLES = ['admin', 'manager', 'staff'];
/**
* List all users, 10 per page, sorted by name.
*
* Every action starts with Gate::authorize('manage-users'). The route
* group already blocks non-admins, so this is a second lock on the
* same door: if someone later moves the route, the controller
* still refuses.
*/
public function index()
{
Gate::authorize('manage-users');
$users = User::orderBy('name')->paginate(10);
return view('users.index', compact('users'));
}
/**
* Show the "add user" form.
* new User gives the form an empty user, so the same form file
* can be used for both create and edit.
*/
public function create()
{
Gate::authorize('manage-users');
return view('users.create', [
'user' => new User,
'roles' => self::ROLES,
'departments' => Department::orderBy('name')->get(),
'staffList' => Staff::orderBy('name')->get(),
]);
}
/**
* Save a new user with a random temporary password.
*
* Str::password(12) makes a random 12-character password.
* We show it ONCE in the flash message, because only the hash is
* stored, so nobody (not even the Admin) can read it again later.
*/
public function store(Request $request)
{
Gate::authorize('manage-users');
$validated = $request->validate([
'name' => ['required', 'string', 'max:100'],
'email' => ['required', 'email', 'max:255', 'unique:users,email'],
'role' => ['required', Rule::in(self::ROLES)],
// A Manager must be linked to a department. For other roles it is optional.
'department_id' => ['nullable', 'required_if:role,manager', 'exists:departments,id'],
'staff_id' => ['nullable', 'exists:staff,id'],
]);
$password = Str::password(12);
User::create([
...$validated,
'password' => Hash::make($password),
'is_active' => true,
]);
return redirect()->route('users.index')
->with('success', "User created. Temporary password (shown once): {$password}");
}
/**
* Show the edit form for one user.
*/
public function edit(User $user)
{
Gate::authorize('manage-users');
return view('users.edit', [
'user' => $user,
'roles' => self::ROLES,
'departments' => Department::orderBy('name')->get(),
'staffList' => Staff::orderBy('name')->get(),
]);
}
/**
* Update a user's name, email, role and links.
* The password is NOT changed here. That has its own button.
*/
public function update(Request $request, User $user)
{
Gate::authorize('manage-users');
$validated = $request->validate([
'name' => ['required', 'string', 'max:100'],
// ignore($user) lets the user keep their own email without
// failing the unique check against themselves.
'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user)],
'role' => ['required', Rule::in(self::ROLES)],
'department_id' => ['nullable', 'required_if:role,manager', 'exists:departments,id'],
'staff_id' => ['nullable', 'exists:staff,id'],
]);
// An Admin must not be able to lock themselves out by
// changing their own role, so we block that here.
if ($user->is($request->user()) && $validated['role'] !== 'admin') { // is the account being edited the same person as the one logged in? and is the role is admin?
return back()
->withErrors(['role' => 'You cannot change your own role.'])
->withInput();
}
$user->update($validated);
return redirect()->route('users.index')
->with('success', 'User updated.');
}
/**
* Switch a user between active and disabled.
* The Week 5 'active' middleware signs a disabled user out
* on their very next request.
*/
public function toggle(Request $request, User $user)
{
Gate::authorize('manage-users');
// An Admin cannot deactivate their own account (422 = invalid request).
abort_if($user->is($request->user()), 422, 'You cannot deactivate your own account.');
$user->update(['is_active' => ! $user->is_active]);
return back()->with('success', 'Status changed.');
}
/**
* Give an existing user a new password, shown once.
*/
public function resetPassword(User $user)
{
Gate::authorize('manage-users');
$password = Str::password(12);
$user->update(['password' => Hash::make($password)]);
return back()->with('success', "New password for {$user->name} (shown once): {$password}");
}
}
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureUserHasRole
{
/**
* Check that the logged-in user has one of the allowed roles.
*
* Think of this as a guard at the door of a corridor. It checks
* your badge (role) once as you enter. If the role isn't on the
* allowed list, you're turned away with a 403 Forbidden page.
*
* ...$roles collects everything written after the colon in the route.
* role:admin gives ['admin']
* role:admin,manager gives ['admin', 'manager']
*
* in_array(..., true) is a strict match, so a missing or mistyped
* role never slips through by accident.
*/
public function handle(Request $request, Closure $next, string ...$roles): Response
{
// If the user's role is NOT in the allowed list, stop here.
if (! in_array($request->user()?->role, $roles, true)) {
abort(403);
}
// Role is allowed, so let the request carry on to the controller.
return $next($request);
}
}
\ No newline at end of file
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
#[Fillable(['name', 'email', 'password', 'is_active', 'last_login_at'])] #[Fillable(['name', 'email', 'password', 'is_active', 'last_login_at', 'role', 'department_id', 'staff_id'])]
#[Hidden(['password', 'remember_token'])] #[Hidden(['password', 'remember_token'])]
class User extends Authenticatable class User extends Authenticatable
{ {
...@@ -29,4 +29,32 @@ protected function casts(): array ...@@ -29,4 +29,32 @@ protected function casts(): array
'password' => 'hashed', 'password' => 'hashed',
]; ];
} }
/**
* Is this user an Admin?
* A small helper so we can write $user->isAdmin() everywhere
* instead of repeating $user->role === 'admin'.
*/
public function isAdmin(): bool
{
return $this->role === 'admin';
}
/**
* Is this user a Manager?
*/
public function isManager(): bool
{
return $this->role === 'manager';
}
/**
* Is this user plain Staff?
* You don't actually need this. But you can add it
* if you want
*/
public function isStaff(): bool
{
return $this->role === 'staff';
}
} }
<?php
namespace App\Policies;
use App\Models\Staff;
use App\Models\User;
use Illuminate\Auth\Access\Response;
class StaffPolicy
{
/**
* Runs BEFORE every other method in this Policy.
*
* true = "definitely allowed", Laravel stops and skips the rest.
* null = "I have no opinion", Laravel carries on and asks the
* specific method (viewAny, view, and so on).
*
* We return null instead of false for non-admins. false would mean
* "definitely blocked" and would lock out Managers and Staff too.
*/
public function before(User $user): ?bool
{
return $user->isAdmin() ? true : null;
}
/**
* Can this user see the staff LIST page?
* No $staff here, because there is no single record yet.
* Only Managers get here (Admins were already passed by before()).
*/
public function viewAny(User $user): bool
{
return $user->isManager();
}
/**
* Can this user open ONE staff profile?
* - Manager: only if that person is in the manager's own department.
* - Staff: only their own profile (the one their staff_id points to).
*/
public function view(User $user, Staff $staff): bool
{
if ($user->isManager()) {
return $staff->department_id === $user->department_id;
}
return $staff->id === $user->staff_id;
}
/**
* Can this user add a new staff member?
* Admins were already allowed by before(), so everyone else is blocked.
*/
public function create(User $user): bool
{
return false;
}
/**
* Can this user edit this staff member?
* - Admin: always (before() already passed them). (This code is at the top of this page)
* - Manager: only staff in their own department.
* - Staff: never.
*/
public function update(User $user, Staff $staff): bool
{
return $user->isManager()
&& $staff->department_id === $user->department_id;
}
/**
* Can this user delete this staff member? Admin only.
*/
public function delete(User $user, Staff $staff): bool
{
return false;
}
}
\ No newline at end of file
...@@ -4,7 +4,9 @@ ...@@ -4,7 +4,9 @@
namespace App\Providers; namespace App\Providers;
use App\Models\User;
use Illuminate\Pagination\Paginator; use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider class AppServiceProvider extends ServiceProvider
...@@ -23,5 +25,20 @@ public function register(): void ...@@ -23,5 +25,20 @@ public function register(): void
public function boot(): void public function boot(): void
{ {
Paginator::useBootstrapFive(); Paginator::useBootstrapFive();
/*
| Gates: named yes/no rules about general actions.
| Define a rule once here, then ask about it anywhere with
| Gate::allows('name'), Gate::authorize('name') or @can('name').
| Laravel passes the logged-in user in automatically.
*/
// Only Admins may manage users and see the activity log.
Gate::define('manage-users', fn (User $user) => $user->isAdmin());
// Admins and Managers may see Assets. Staff may not.
// || means "or", so either role passes.
Gate::define('view-assets', fn (User $user) => $user->isAdmin()
|| $user->isManager());
} }
} }
...@@ -12,9 +12,10 @@ ...@@ -12,9 +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 // Give our middleware short names so we can use 'active' and 'role' in routes
$middleware->alias([ $middleware->alias([
'active' => \App\Http\Middleware\EnsureUserIsActive::class, 'active' => \App\Http\Middleware\EnsureUserIsActive::class,
'role' => \App\Http\Middleware\EnsureUserHasRole::class,
]); ]);
}) })
->withExceptions(function (Exceptions $exceptions): void { ->withExceptions(function (Exceptions $exceptions): void {
......
<?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 the three access-control columns to users.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
// The user's role: admin, manager or staff.
// Defaults to 'staff' so a new account gets the least access.
$table->string('role', 20)->default('staff')->after('email');
// The department a Manager is responsible for.
// Nullable because Admins and Staff don't need one.
$table->foreignId('department_id')
->nullable()
->after('role')
->constrained();
// Links a login (users table) to its own profile (staff table).
// 'staff' is passed explicitly because the table name is
// singular, so Laravel can't guess it from "staff_id".
// basically users table only has email and password for login
// purposes, and to know the details of a staff (name, position etc)
// you connect it to staff table. nullable bcs admin and manager
// don't have staff_id
$table->foreignId('staff_id')
->nullable()
->after('department_id')
->constrained('staff');
});
}
/**
* Reverse the migration: drop the foreign keys first, then the columns.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropConstrainedForeignId('staff_id');
$table->dropConstrainedForeignId('department_id');
$table->dropColumn('role');
});
}
};
\ No newline at end of file
...@@ -25,8 +25,8 @@ public function run(): void ...@@ -25,8 +25,8 @@ public function run(): void
$this->call([ $this->call([
DepartmentSeeder::class, DepartmentSeeder::class,
PositionSeeder::class, PositionSeeder::class,
UserSeeder::class,
StaffSeeder::class, // must come after DepartmentSeeder StaffSeeder::class, // must come after DepartmentSeeder
UserSeeder::class, // must come after StaffSeeder, because staff@ links to a staff record
]); ]);
} }
} }
\ No newline at end of file
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
namespace Database\Seeders; namespace Database\Seeders;
use App\Models\Department;
use App\Models\Staff;
use App\Models\User; use App\Models\User;
use Illuminate\Database\Seeder; use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Hash;
...@@ -10,24 +12,58 @@ ...@@ -10,24 +12,58 @@
class UserSeeder extends Seeder class UserSeeder extends Seeder
{ {
/** /**
* Create two test users for local development. * Create test users for local development.
* *
* "password" is the plain-text password for both. * "password" is the plain-text password for all of them.
* Hash::make() turns it into a bcrypt hash before saving, * Hash::make() turns it into a bcrypt hash before saving,
* so the database never stores the real password. * so the database never stores the real password.
* *
* One user is active (can log in), the other is disabled * Roles (Week 9):
* (will be blocked by the EnsureUserIsActive middleware later). * - aina@ = admin (the Week 5 user, now promoted)
* - manager@ = manager (linked to a department)
* - staff@ = staff (linked to their own staff record)
*/ */
public function run(): void public function run(): void
{ {
// Grab one real department and one real staff record to link to.
// They exist because DatabaseSeeder runs DepartmentSeeder and
// StaffSeeder before this one.
$department = Department::first();
$staffRecord = Staff::first();
// Admin: the existing Aina user from Week 5, now with the admin role.
User::create([ User::create([
'name' => 'Aina Rahman', 'name' => 'Aina Rahman',
'email' => 'aina@minioffice.test', 'email' => 'aina@minioffice.test',
'password' => Hash::make('password'), 'password' => Hash::make('password'),
'is_active' => true, 'is_active' => true,
'role' => 'admin',
]);
// Manager: responsible for one department. department_id is what
// lets us later limit them to staff from that department only.
User::create([
'name' => 'Manager User',
'email' => 'manager@minioffice.test',
'password' => Hash::make('password'),
'is_active' => true,
'role' => 'manager',
'department_id' => $department->id, // this got the first department id in the database (which is finance). This is because $department = Department::first();
]);
// Staff: linked to a real staff profile through staff_id.
// This is how "My profile" knows which profile to open.
User::create([
'name' => $staffRecord->name,
'email' => 'staff@minioffice.test',
'password' => Hash::make('password'),
'is_active' => true,
'role' => 'staff',
'staff_id' => $staffRecord->id,
]); ]);
// Existing test users. They get the default 'staff' role
// and have no staff_id, so they have no profile to open.
User::create([ User::create([
'name' => 'Disabled User', 'name' => 'Disabled User',
'email' => 'disabled@minioffice.test', 'email' => 'disabled@minioffice.test',
...@@ -49,4 +85,4 @@ public function run(): void ...@@ -49,4 +85,4 @@ public function run(): void
'is_active' => false, 'is_active' => false,
]); ]);
} }
} }
\ No newline at end of file
...@@ -5,53 +5,42 @@ ...@@ -5,53 +5,42 @@
<a href="{{ route('services') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('services')])>Services</a> <a href="{{ route('services') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('services')])>Services</a>
<a href="{{ route('contact') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('contact')])>Contact</a> <a href="{{ route('contact') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('contact')])>Contact</a>
<hr class="my-2"> {{--A horizontal rule. my-2 — Controls the vertical spacing around the line.--}} <hr class="my-2"> {{--A horizontal rule. my-2 controls the vertical spacing around the line.--}}
<p class="text-muted text-uppercase small fw-bold mb-1 px-3">Modules</p> <p class="text-muted text-uppercase small fw-bold mb-1 px-3">Modules</p>
<a href="{{ route('departments.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('departments.*')])>Departments</a>
<a href="{{ route('positions.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('positions.*')])>Positions</a> {{--
<a href="{{ route('staff.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('staff.*')])>Staff</a> Each link below uses the SAME check its controller uses.
</nav> Remember: hiding a link is not security. The controller or middleware
still blocks the URL. The sidebar only stops people seeing links
{{-- that would give them a 403.
- route('home') — outputs the URL for that named route, --}}
same idea as the header link
- class([...]) — this is the clever bit. It always adds {{-- Departments: guarded by the role:admin middleware (not a Gate), so we check the role directly. --}}
nav-link. Then the part after => is a condition: request()->routeIs('home') @if (auth()->user()->isAdmin())
asks "is the user currently on the home route?" If yes, it also adds active <a href="{{ route('departments.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('departments.*')])>Departments</a>
fw-bold. If no, it skips those classes. So the current page's link always <a href="{{ route('positions.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('positions.*')])>Positions</a>
looks different from the others @endif
--}}
{{-- Staff list: the same question StaffController::index asks (StaffPolicy::viewAny). Admin and Manager pass. --}}
{{-- @can('viewAny', App\Models\Staff::class)
What is named route? <a href="{{ route('staff.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('staff.*')])>Staff</a>
Think of it like saving a contact in your phone. @endcan
You could memorise your friend's number (012-345-6789) and type it out every {{-- Assets (Week 10): uncomment when the assets routes exist, otherwise route('assets.index') will crash.
time you call them. But if your friend changes their number, you'd have to @can('view-assets')
remember the new one and update it everywhere you wrote it down. <a href="{{ route('assets.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('assets.*')])>Assets</a>
@endcan
Or you could save the contact as "Ali" and just tap "Ali" whenever you want --}}
to call. If Ali changes his number, you update it once in your contacts, and
every call to "Ali" still works. {{-- Users: the manage-users Gate, same as UserController. Admin only. --}}
@can('manage-users')
Named routes are the same idea. Instead of writing the URL /about in 10 different <a href="{{ route('users.index') }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->routeIs('users.*')])>Users</a>
Blade files, you give the route a name: {{-- Activity log (Week 12): add its link here when the activity routes exist. --}}
@endcan
Route::get('/about', 'about')->name('about');
{{-- My profile: shown to anyone whose login is linked to a staff record. This is how Staff reach their own page. --}}
Now everywhere in your app, you write route('about') instead of /about. @if (auth()->user()->staff_id)
If you later decide to change the URL to /about-us, you change it in one <a href="{{ route('staff.show', auth()->user()->staff_id) }}" @class(['nav-link rounded', 'active fw-bold bg-primary text-white' => request()->is('staff/' . auth()->user()->staff_id)])>My profile</a>
place (the route file), and every route('about') across your entire app @endif
automatically outputs /about-us. Nothing breaks. </nav>
--}} \ No newline at end of file
{{--
STYLING:
- nav-link — Bootstrap's default styling for navigation links. It adds padding, removes the underline, and makes the text a muted colour that darkens on hover.
- rounded — Adds slightly curved corners to the link. Without it, when the active link gets the blue background, it would have sharp square edges which looks harsh.
- active — A Bootstrap class that tells the browser "this is the current page." On its own it just slightly changes the text colour, which is why we add more classes alongside it.
- fw-bold — Makes the text bold. "fw" stands for font-weight. So the current page link is visually heavier than the others.
- bg-primary — Fills the background with Bootstrap's primary colour, which is blue by default. This creates a solid coloured block behind the active link so it really stands out from the rest.
- text-white — Changes the text to white. Without this, the text would stay dark and be hard to read against the blue background.
--}}
\ No newline at end of file
...@@ -114,10 +114,20 @@ ...@@ -114,10 +114,20 @@
--}} --}}
<div class="col-md-6"> <div class="col-md-6">
<label for="department_id" class="form-label">Department</label> <label for="department_id" class="form-label">Department</label>
{{--
A Manager editing staff cannot change the department, so we grey the
dropdown out. A disabled field is NOT sent by the browser, and the
Form Request says department_id is required, so we also send the
current value in a hidden input. The controller ignores it for
Managers anyway.
--}}
@php $lockDepartment = auth()->user()->isManager() && isset($staff); @endphp {{--lock the department dropdown only if the user is a Manager and this is the edit page and assign it to $lockDepartment--}}
<select <select
name="department_id" name="department_id"
id="department_id" id="department_id"
class="form-select @error('department_id') is-invalid @enderror" class="form-select @error('department_id') is-invalid @enderror"
@disabled($lockDepartment)
> >
{{-- The empty first option forces the user to make a choice --}} {{-- The empty first option forces the user to make a choice --}}
<option value="">-- Select Department --</option> <option value="">-- Select Department --</option>
...@@ -143,6 +153,13 @@ ...@@ -143,6 +153,13 @@
</option> </option>
@endforeach @endforeach
</select> </select>
{{--To blur out the dropdown if the user is manager--}}
@if ($lockDepartment)
<input type="hidden" name="department_id" value="{{ $staff->department_id }}">
<small class="text-muted">Only an Admin can change the department.</small>
@endif
@error('department_id') @error('department_id')
<div class="invalid-feedback">{{ $message }}</div> <div class="invalid-feedback">{{ $message }}</div>
@enderror @enderror
......
{{-- Shared fields for create and edit. $user is an empty User on create. --}}
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" name="name" id="name"
class="form-control @error('name') is-invalid @enderror"
value="{{ old('name', $user->name) }}">
@error('name')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input type="email" name="email" id="email"
class="form-control @error('email') is-invalid @enderror"
value="{{ old('email', $user->email) }}">
@error('email')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="mb-3">
<label for="role" class="form-label">Role</label>
<select name="role" id="role" class="form-select @error('role') is-invalid @enderror">
@foreach ($roles as $role)
{{-- @selected adds the "selected" attribute when the condition is true.
New users default to 'staff', the least access. --}}
<option value="{{ $role }}" @selected(old('role', $user->role ?? 'staff') === $role)>
{{ ucfirst($role) }}
</option>
@endforeach
</select>
@error('role')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="mb-3">
<label for="department_id" class="form-label">Department (required for Managers)</label>
<select name="department_id" id="department_id"
class="form-select @error('department_id') is-invalid @enderror">
<option value="">None</option>
@foreach ($departments as $department)
<option value="{{ $department->id }}"
@selected(old('department_id', $user->department_id) == $department->id)>
{{ $department->name }}
</option>
@endforeach
</select>
@error('department_id')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="mb-3">
<label for="staff_id" class="form-label">Linked staff profile (for "My profile")</label>
<select name="staff_id" id="staff_id"
class="form-select @error('staff_id') is-invalid @enderror">
<option value="">None</option>
@foreach ($staffList as $staffMember)
<option value="{{ $staffMember->id }}"
@selected(old('staff_id', $user->staff_id) == $staffMember->id)>
{{ $staffMember->staff_no }} - {{ $staffMember->name }}
</option>
@endforeach
</select>
@error('staff_id')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
\ No newline at end of file
@extends('layouts.app')
@section('title', 'Add User')
@section('content')
<h1>Add User</h1>
<p class="text-muted">A random temporary password is generated and shown once after saving.</p>
<form method="POST" action="{{ route('users.store') }}">
@csrf
@include('users._form')
<a href="{{ route('users.index') }}" class="btn btn-secondary">Cancel</a>
<button type="submit" class="btn btn-primary">Save</button>
</form>
@endsection
\ No newline at end of file
@extends('layouts.app')
@section('title', 'Edit User')
@section('content')
<h1>Edit User</h1>
<form method="POST" action="{{ route('users.update', $user) }}">
@csrf
@method('PUT') {{-- Edit forms are sent as PUT, same as Departments --}}
@include('users._form')
<a href="{{ route('users.index') }}" class="btn btn-secondary">Cancel</a>
<button type="submit" class="btn btn-primary">Update</button>
</form>
@endsection
\ No newline at end of file
@extends('layouts.app') {{-- Use the shared layout --}}
@section('title', 'Users') {{-- Tab name --}}
@section('content')
<div class="d-flex justify-content-between align-items-center mb-3">
<h1>Users</h1>
<a href="{{ route('users.create') }}" class="btn btn-primary">+ Add User</a>
</div>
<table class="table table-bordered table-hover">
<thead class="table-dark">
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@forelse ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
{{-- Pick a badge colour for each role --}}
@php
$roleColour = ['admin' => 'danger', 'manager' => 'primary', 'staff' => 'secondary'][$user->role] ?? 'secondary';
@endphp
<span class="badge bg-{{ $roleColour }}">{{ ucfirst($user->role) }}</span>
</td>
<td>
<span class="badge bg-{{ $user->is_active ? 'success' : 'secondary' }}">
{{ $user->is_active ? 'Active' : 'Disabled' }}
</span>
</td>
<td>
<a href="{{ route('users.edit', $user) }}" class="btn btn-sm btn-warning">Edit</a>
{{-- An Admin cannot deactivate themselves, so we don't show the button on their own row --}}
@unless ($user->is(auth()->user()))
<form method="POST" action="{{ route('users.toggle', $user) }}" class="d-inline">
@csrf
@method('PATCH') {{-- HTML forms only send GET or POST, so this hidden field tells Laravel it is a PATCH --}}
<button type="submit" class="btn btn-sm btn-secondary">
{{ $user->is_active ? 'Deactivate' : 'Activate' }}
</button>
</form>
@endunless
<form method="POST" action="{{ route('users.reset-password', $user) }}"
class="d-inline"
onsubmit="return confirm('Reset this user\'s password?')">
@csrf
@method('PATCH')
<button type="submit" class="btn btn-sm btn-info">Reset password</button>
</form>
</td>
</tr>
@empty
<tr>
<td colspan="5" class="text-center">No users found.</td>
</tr>
@endforelse
</tbody>
</table>
{{ $users->links() }}
@endsection
\ No newline at end of file
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
use App\Http\Controllers\PageController; use App\Http\Controllers\PageController;
use App\Http\Controllers\PositionController; use App\Http\Controllers\PositionController;
use App\Http\Controllers\StaffController; use App\Http\Controllers\StaffController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
/* /*
...@@ -47,9 +48,29 @@ ...@@ -47,9 +48,29 @@
Route::get('/services', [PageController::class, 'services'])->name('services'); Route::get('/services', [PageController::class, 'services'])->name('services');
Route::get('/contact', [PageController::class, 'contact'])->name('contact'); Route::get('/contact', [PageController::class, 'contact'])->name('contact');
// Departments are Admin only (see the access matrix).
// This group sits inside the auth + active group above, so the order is:
// 1. auth: are you logged in? (at line 39 of this pagge: Route::middleware(['auth', 'active']))
// 2. active: is your account enabled? (at line 39 of this pagge: Route::middleware(['auth', 'active']))
// 3. role:admin: are you specifically an Admin? (You will get )
Route::middleware('role:admin')->group(function () { // make sure to check with middleware first then
Route::resource('departments', DepartmentController::class); // allow to access
// Positions are Admin only too (same rule as Departments).
Route::resource('positions', PositionController::class);
// User management, Admin only (see the access matrix).
// except() leaves out show and destroy because we don't use them.
Route::resource('users', UserController::class)->except(['show', 'destroy']);
// Two extra actions that aren't part of the standard seven.
Route::patch('users/{user}/toggle', [UserController::class, 'toggle'])
->name('users.toggle');
Route::patch('users/{user}/reset-password', [UserController::class, 'resetPassword'])
->name('users.reset-password');
});
// CRUD modules from Month 1 // CRUD modules from Month 1
Route::resource('departments', DepartmentController::class);
Route::resource('positions', PositionController::class);
Route::resource('staff', StaffController::class); Route::resource('staff', StaffController::class);
Route::get('/staff/{staff}/contract', [StaffController::class, 'downloadContract']) Route::get('/staff/{staff}/contract', [StaffController::class, 'downloadContract'])
......
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