Authentication and Tips

Authentication and Tips

Here’s a quick explanation on how you go about Authentication and some tips.

Building Registration & Login Forms

  • Create register.blade.php and login.blade.php views under an auth directory.
  • Use the form components to build inputs for first name, last name, email, password, and password confirmation.
  • Add required attributes for client-side validation.

Defining Authentication Routes and Controllers

  • Add routes for showing registration and login forms (GET /register, GET /login).
  • Add routes for handling form submissions (POST /register, POST /login).
  • Create corresponding controllers like RegisteredUserController and SessionController with create and store methods.

Displaying Content Conditionally

Use Blade directives to show login and register links only to guests:

PHP
@guest
    <x-nav-link href="/login">Login</x-nav-link>
    <x-nav-link href="/register">Register</x-nav-link>
@endguest

Use @auth to show content only to authenticated users.

Registration Process

When a user submits the registration form, the following steps occur:

  1. Validation: Use $request->validate() to ensure required fields like first name, last name, email, and password meet your criteria. Laravel provides many validation rules, including a fluent Password helper for complex password requirements.
  2. Creating the User: After validation, create the user in the database. You can pass the validated attributes directly to User::create().
  3. Logging In: Use Auth::login($user) to sign in the newly registered user.
  4. Redirecting: Redirect the user to a desired page, such as the jobs listing or dashboard.

Example Validation Rules

PHP
$request->validate([
    'first_name' => ['required', 'min:1'],
    'last_name' => ['required', 'min:1'],
    'email' => ['required', 'email'],
    'password' => ['required', 'confirmed', Password::min(6)],
]);

The confirmed rule requires a matching password_confirmation field.

Login Process

When a user submits the login form:

  1. Validation: Validate the email and password fields.
  2. Authentication Attempt: Use Auth::attempt($credentials) to try logging in.
  3. Session Regeneration: On successful login, regenerate the session token for security.
  4. Redirect: Redirect the user to the intended page.
  5. Handling Failure: If login fails, throw a validation exception with an appropriate error message.

Preserving Input on Validation Errors

Use the old() helper in Blade to repopulate form fields after validation errors, improving user experience.

PHP
<input name="email" value="{{ old('email') }}" />

Remember to prefix with : in Blade to treat as an expression:

PHP
:value="old('email')"

Authentication Tips

1. Establishing Relationships for Authorization

To perform user authorization on a job, there must be a relationship between the job and a user. Currently, jobs relate to employers, but employers don’t relate to users. Fix this by adding a foreign key user_id to the employers table and updating the Employer factory to associate an employer with a user.

2. Inline Authorization in Controller

Add a simple authorization check in your job controller’s edit action:

  • Redirect guests to login.
  • Check if the authenticated user is responsible for the job.
  • If not authorized, abort with a 403 status.

Use Eloquent relationships to traverse from job to employer to user, and compare with the authenticated user using the is method.

3. Gates

Extract authorization logic into gates for reusability and clarity.

  • Define gates in AppServiceProvider using the Gate facade.
  • Gates return a boolean indicating authorization.
  • Use Gate::authorize('edit-job', $job) in your controller to enforce authorization.

Gates automatically abort with 403 if authorization fails, but you can use Gate::allows or Gate::denies for custom handling.

4. Using can and cannot Methods

Your User model has can and cannot methods to check permissions against gates. Use these in controllers or Blade views to conditionally allow actions.

PHP
@can('edit', $job)
    <p class="mt-6">
        <x-button href="/jobs/{{ $job->id }}/edit">Edit Job</x-button>
    </p>
@endcan

This code allows a user to only see the edit Job button if he’s authorized to do so. In this case that would be if he created the note.

5. Middleware Authorization

Apply authorization at the route level using middleware:

PHP
Route::patch('/jobs/{job}', [JobController::class, 'update'])
    ->middleware(['auth', 'can:edit,job']);

This ensures users are authenticated and authorized before accessing the route.

You can specify middleware per route or group routes for cleaner code.

6. Policies

Policies are classes that encapsulate authorization logic for a model.

  • Generate a policy with php artisan make:policy JobPolicy --model=Job.
  • Define methods like edit, delete to control access.
  • Register policies in AuthServiceProvider.
  • Use policies via gates or can methods.

Policies provide a structured, scalable way to manage complex authorization rules.

Tags: