Assignment s Of Day 10 Authentication Basics

Assignment s Of  Day 10

 Authentication Basics

Assignment 1: Setting Up User Registration and Login System

Task:

Create a simple user registration and login system using Laravel Breeze. After completing the registration, the user should be redirected to a "dashboard" page, which is accessible only to authenticated users.


Steps to Complete the Assignment:

1.  Install Laravel Breeze:

o    Open your terminal and navigate to your Laravel project folder.

o    Install Laravel Breeze using Composer:

composer require laravel/breeze --dev

2.  Install Breeze Frontend Scaffolding:

o    Once the package is installed, run the following command to install Breeze’s frontend:

php artisan breeze:install

3.  Install NPM Dependencies:

o    To manage the frontend assets (CSS and JS), run the following command to install necessary dependencies:

bash

Copy code

npm install

o    Compile the assets with:

bash

Copy code

npm run dev

4.  Run Migrations:

o    Breeze comes with a default migration for the users table. Run the migrations to create the necessary tables in your database:

bash

Copy code

php artisan migrate

5.  Set Up Routes:

o    Breeze automatically provides the routes for authentication, so you don’t need to create them manually. However, you need to create a route for the "dashboard" page, which will be protected by authentication.

o    Open the routes/web.php file and add the following route for the dashboard:

php

Copy code

Route::get('/dashboard', function () {

    return view('dashboard');

})->middleware(['auth']);

6.  Create a Blade View for the Dashboard:

o    Create a dashboard.blade.php file in the resources/views directory. This will be the view displayed when the user is authenticated.

blade

Copy code

<!-- resources/views/dashboard.blade.php -->

<!DOCTYPE html>

<html>

<head>

    <title>Dashboard</title>

</head>

<body>

    <h1>Welcome to your Dashboard!</h1>

    <p>You are logged in!</p>

</body>

</html>

7.  Testing the Registration and Login System:

o    Run the development server:

bash

Copy code

php artisan serve

o    Open your browser and go to http://localhost:8000/register to register a new user.

o    After successful registration, you should be redirected to the dashboard.

o    Log out and go to http://localhost:8000/login to log in with the credentials you just created.

8.  Testing the Auth Middleware:

o    Try accessing http://localhost:8000/dashboard without logging in. Laravel should redirect you to the login page since this route is protected by the auth middleware.


Solution Explanation:

  • Step 1 installs Laravel Breeze, which provides a simple way to implement authentication in Laravel.
  • Step 2 installs the Breeze frontend scaffolding (views, routes, and controllers).
  • Step 3 installs necessary npm dependencies (CSS, JS) for the frontend to work.
  • Step 4 runs the migrations to create the required users table in the database.
  • Step 5 adds a route for the dashboard page, which is protected by authentication middleware (auth), ensuring only logged-in users can access it.
  • Step 6 creates the dashboard.blade.php view, which will display a welcome message to the authenticated user.
  • Step 7 tests the functionality by registering and logging in a user, then verifying the redirection behavior.
  • Step 8 tests the auth middleware by ensuring unauthorized users cannot access protected routes.

Assignment 2: Customizing the Registration Form

Task:

Modify the registration form to include a user's role. Add a dropdown menu in the registration form that allows the user to choose between two roles: Admin and User. The role should be saved in the users table, and the user should be redirected to different dashboards based on their role.


Steps to Complete the Assignment:

1.  Add Role Column to Users Table:

o    Open the database/migrations/YYYY_MM_DD_create_users_table.php file.

o    Add a role column to the users table:

php

Copy code

public function up()

{

    Schema::create('users', function (Blueprint $table) {

        $table->id();

        $table->string('name');

        $table->string('email')->unique();

        $table->string('password');

        $table->enum('role', ['admin', 'user'])->default('user');  // Add this line

        $table->timestamps();

    });

}

o    Run the migration to update the table:

bash

Copy code

php artisan migrate

2.  Modify Registration Form:

o    Open the resources/views/auth/register.blade.php file.

o    Add a role dropdown to the form, allowing the user to choose between Admin and User.

blade

Copy code

<div class="mt-4">

    <x-label for="role" :value="__('Role')" />

    <select id="role" name="role" class="block mt-1 w-full">

        <option value="user">User</option>

        <option value="admin">Admin</option>

    </select>

</div>

3.  Handle Role in Registration Controller:

o    Open the app/Http/Controllers/Auth/RegisterController.php file.

o    Modify the create method to store the selected role in the users table:

php

Copy code

protected function create(array $data)

{

    return User::create([

        'name' => $data['name'],

        'email' => $data['email'],

        'password' => Hash::make($data['password']),

        'role' => $data['role'],  // Add this line

    ]);

}

4.  Modify Dashboard Based on Role:

o    Open the routes/web.php file and modify the /dashboard route to redirect users based on their role:

php

Copy code

Route::get('/dashboard', function () {

    if (auth()->user()->role == 'admin') {

        return view('admin.dashboard');  // Admin dashboard view

    }

    return view('user.dashboard');  // User dashboard view

})->middleware(['auth']);

5.  Create Role-Based Dashboard Views:

o    Create two separate views: one for admin and one for user.

Admin Dashboard (resources/views/admin/dashboard.blade.php):

blade

Copy code

<h1>Welcome Admin!</h1>

<p>This is your admin dashboard.</p>

User Dashboard (resources/views/user/dashboard.blade.php):

blade

Copy code

<h1>Welcome User!</h1>

<p>This is your user dashboard.</p>

6.  Test the Role-Based Dashboard:

o    Register a new user and choose the Admin role from the dropdown.

o    Log in and ensure that the user is redirected to the admin.dashboard view.

o    Register another user with the User role and ensure they are redirected to the user.dashboard view.


Solution Explanation:

  • Step 1 adds a role column to the users table so we can store each user’s role (either admin or user).
  • Step 2 modifies the registration form to allow the user to select a role during registration.
  • Step 3 handles storing the selected role when the user registers.
  • Step 4 modifies the /dashboard route to redirect users to different views based on their role (admin.dashboard or user.dashboard).
  • Step 5 creates separate views for admin and user dashboards.
  • Step 6 tests the functionality by registering users with different roles and ensuring correct redirection after login.

These assignments allow students to practice setting up Laravel Breeze authentication, adding custom fields to the registration form, and implementing role-based routing and views.

4o mini

You said:

more

ChatGPT said:

ChatGPT

Assignment 3: Implementing Password Reset Feature in Laravel Breeze

Task:

Enable the password reset functionality for users in your Laravel Breeze application. The user should be able to request a password reset via email, set a new password, and log in with the updated password.


Steps to Complete the Assignment:

1.  Check for Password Reset Routes:

o    Laravel Breeze comes with built-in routes for password reset, including the ability to request a password reset and update the password. Open the routes/web.php file and verify the following routes are included:

php

Copy code

// Password reset routes

Route::get('forgot-password', [PasswordController::class, 'create'])

    ->middleware('guest')

    ->name('password.request');

 

Route::post('forgot-password', [PasswordController::class, 'store'])

    ->middleware('guest')

    ->name('password.email');

 

Route::get('reset-password/{token}', [PasswordController::class, 'edit'])

    ->middleware('guest')

    ->name('password.reset');

 

Route::post('reset-password', [PasswordController::class, 'update'])

    ->middleware('guest')

    ->name('password.update');

2.  These routes manage the process for requesting a password reset and updating the password. If they are missing, you can manually add them.

3.  Set Up Email Configuration:

o    To send password reset emails, you must configure your .env file with email settings. Make sure the following variables are correctly set:

env

Copy code

MAIL_MAILER=smtp

MAIL_HOST=smtp.mailtrap.io

MAIL_PORT=587

MAIL_USERNAME=your-mailtrap-username

MAIL_PASSWORD=your-mailtrap-password

MAIL_ENCRYPTION=tls

MAIL_FROM_ADDRESS=noreply@example.com

MAIL_FROM_NAME="${APP_NAME}"

o    You can use a service like Mailtrap to test emails locally.

4.  Ensure Default Authentication Views:

o    Breeze comes with views for password reset, including forgot-password and reset-password. These views are located in resources/views/auth. If they’re missing, you can publish the default authentication views with:

bash

Copy code

php artisan breeze:install --views

5.  Test the Password Reset Functionality:

o    Run the Laravel development server:

bash

Copy code

php artisan serve

o    Go to the Forgot Password page (http://localhost:8000/forgot-password).

o    Enter the email address of a registered user and request a password reset.

o    Check the email inbox (using the email service you configured, like Mailtrap).

o    Click the password reset link, which will redirect you to the Reset Password page (/reset-password/{token}).

o    Set a new password, submit the form, and log in with the updated password.

6.  Test the Full Flow:

o    Test the complete password reset process:

1.  Request password reset by submitting the email.

2.  Check email for the reset link.

3.  Enter a new password in the reset form.

4.  Log in with the new password.


Solution Explanation:

  • Step 1 checks that the necessary routes for password reset are present. These routes handle the user requests for password resets and updating the password.
  • Step 2 configures the email system to send reset links. Email configuration is essential for sending the reset instructions to users.
  • Step 3 ensures the default views are available, which includes the form to request a password reset and the form to enter the new password.
  • Step 4 runs the Laravel development server, and the student tests the password reset feature, ensuring everything is functioning properly.
  • Step 5 walks the student through the full password reset process to verify all components work together, from the request to the email confirmation to resetting the password.

Assignment 4: User Profile Page and Update Feature

Task:

Create a user profile page where users can view and update their personal details (name, email, and password). The page should be protected by authentication, and only the logged-in user should be able to access their profile.


Steps to Complete the Assignment:

1.  Create a User Profile Route:

o    In routes/web.php, add a route for the profile page that can only be accessed by authenticated users:

php

Copy code

Route::get('/profile', [ProfileController::class, 'index'])->middleware('auth')->name('profile');

2.  Create the Profile Controller:

o    Create a new controller named ProfileController to handle the logic for viewing and updating the user’s profile:

bash

Copy code

php artisan make:controller ProfileController

o    Open the newly created controller (app/Http/Controllers/ProfileController.php) and add the following methods:

php

Copy code

<?php

 

namespace App\Http\Controllers;

 

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\Hash;

use App\Models\User;

 

class ProfileController extends Controller

{

    // Show user profile

    public function index()

    {

        return view('profile.index', ['user' => Auth::user()]);

    }

 

    // Update user profile

    public function update(Request $request)

    {

        $request->validate([

            'name' => 'required|string|max:255',

            'email' => 'required|string|email|max:255',

            'password' => 'nullable|string|min:8|confirmed',

        ]);

 

        $user = Auth::user();

        $user->name = $request->input('name');

        $user->email = $request->input('email');

 

        if ($request->filled('password')) {

            $user->password = Hash::make($request->input('password'));

        }

 

        $user->save();

 

        return redirect()->route('profile')->with('success', 'Profile updated successfully!');

    }

}

3.  Create Profile View:

o    Create a Blade view to display and update the user profile. Create a file named profile/index.blade.php in the resources/views directory:

blade

Copy code

<!-- resources/views/profile/index.blade.php -->

<h1>Your Profile</h1>

 

<form method="POST" action="{{ route('profile.update') }}">

    @csrf

    @method('PUT')

 

    <div>

        <label for="name">Name:</label>

        <input type="text" name="name" id="name" value="{{ old('name', $user->name) }}">

    </div>

 

    <div>

        <label for="email">Email:</label>

        <input type="email" name="email" id="email" value="{{ old('email', $user->email) }}">

    </div>

 

    <div>

        <label for="password">New Password:</label>

        <input type="password" name="password" id="password">

    </div>

 

    <div>

        <label for="password_confirmation">Confirm Password:</label>

        <input type="password" name="password_confirmation" id="password_confirmation">

    </div>

 

    <button type="submit">Update Profile</button>

</form>

4.  Create Profile Update Route:

o    In routes/web.php, add a route to handle the form submission:

php

Copy code

Route::put('/profile', [ProfileController::class, 'update'])->middleware('auth')->name('profile.update');

5.  Test the Profile Page:

o    After completing the steps, run the development server:

bash

Copy code

php artisan serve

o    Visit http://localhost:8000/profile while logged in, and verify that the profile page is accessible.

o    Update the user’s details (name, email, and password) and submit the form.

o    Check if the changes are reflected in the database and the profile page.


Solution Explanation:

  • Step 1 defines the route for the profile page, ensuring it's protected by authentication middleware so only logged-in users can access it.
  • Step 2 creates the ProfileController, with methods to display the profile and handle the update process.
  • Step 3 creates a view for the profile page, where users can update their details.
  • Step 4 creates the route to handle the profile update form submission.
  • Step 5 walks through testing the feature by running the server, accessing the profile page, and updating the user's details.

Assignment 5: Implementing Email Verification

Task:

Enable email verification in your Laravel application. After registration, users should receive an email to verify their email address before they can log in.


Steps to Complete the Assignment:

1.  Enable Email Verification:

o    Open app/Models/User.php and make sure the MustVerifyEmail interface is implemented:

php

Copy code

use Illuminate\Contracts\Auth\MustVerifyEmail;

The User model should already implement MustVerifyEmail by default.

2.  Send Verification Email:

o    Laravel will automatically send the email verification link when a user registers. Make sure the RegisterController calls the sendEmailVerificationNotification() method:

php

Copy code

use Illuminate\Auth\Events\Registered;

 

protected function registered(Request $request, $user)

{

    event(new Registered($user));

    $user->sendEmailVerificationNotification();

}

3.  Update Routes for Email Verification:

o    In routes/web.php, ensure that the email.verify route is defined:

php

Copy code

Route::get('/email/verify', function () {

    return view('auth.verify');

})->middleware('auth')->name('verification.notice');

 

Route::get('/email/verify/{id}/{hash}', [VerificationController::class, 'verify'])

    ->middleware(['auth', 'signed'])

    ->name('verification.verify');

4.  Test Email Verification:

o    Register a new user, and ensure they receive a verification email.

o    After clicking the verification link, ensure the user is redirected to the appropriate page and is able to log in.


Solution Explanation:

  • Step 1 ensures that the User model supports email verification by implementing the MustVerifyEmail interface.
  • Step 2 ensures that the Registered event triggers the email verification notification after registration.
  • Step 3 verifies the presence of the email verification routes for handling the verification process.
  • Step 4 walks the student through testing the full email verification process, including receiving and using the verification link.

These assignments provide a detailed exploration of various key features in Laravel Breeze, including password reset, profile management, and email verification, helping students understand how to implement and extend authentication functionality in Laravel.


Comments

Popular posts from this blog

MCQs Of Day CRUD 8 Operations with Eloquent

Lecture Notes Of Day 24: Laravel Policies

MCQs of Day 7 Eloquent ORM Basics