Developer Snippet Diary

login / register in laravel, Auth + Redirect user to login if not authenticated || login throttling / account lockout.

With laravel we can make login, register pages and databases

1.Run command 

composer require laravel/ui 

it will create

???? app/Http/Controllers/Auth/

  1. LoginController.php
  2. RegisterController.php
  3. ForgotPasswordController.php
  4. ResetPasswordController.php
  5. VerificationController.php

it will create ui package , views, migration, model controller create inside vendor/laravel/ui

2. Run command 

php artisan ui bootstrap --auth

bootstrap is optional if you want to use your own design

it will create controllers, views and routes for login, register, forget, and migrations.

Controllers: Creates authentication-related controllers (e.g., LoginController, RegisterController) in app/Http/Controllers/Auth/.
Views: Generates Blade templates (e.g., login.blade.php, register.blade.php) in resources/views/auth/.
Routes: Adds authentication routes (e.g., /login, /register, /logout) to routes/web.php.
Migrations: Creates a migration file for the users table (and possibly password_resets) in database/migrations/.

3. Run migrations

php artisan migrate

 

 

AFTER THAT, Now you can Protect Routes , If user is not logged in → redirected to /login

Route::middleware(['auth'])->group(function () {

    Route::get('/dashboard', function () {
        return view('dashboard');
    });

});

Protect controller

public function __construct()
{
    $this->middleware('auth');
}

route prevent

Route::get('/', function () {
    return view('home');
})->middleware('auth');

Below commands 4,5 are optional, if you want to install bootsrap and compile then use these

4.Run command , below commands is to make design and install bootstrap

npm install

It installs JavaScript and CSS dependencies listed in your package.json file using npm (Node Package Manager) but they aren’t yet compiled or usable in your views until the next step.

5. Run command

npm run development

It will compile all CSS, JavaScript, etc using Laravel Mix, which is a wrapper around Webpack.. 
Compiles Bootstrap’s CSS and JavaScript (from node_modules/) into a single public/css/app.css and public/js/app.js.
Processes any custom JavaScript or Sass you’ve added in resources/.
You can include them in your Blade templates (e.g., <link href="{{ asset('css/app.css') }}" rel="stylesheet">) to apply Bootstrap styling.

NOTE:

IF there is any error run these commands

npm install --save-dev cross-env1
OR
rm -rf node_modules //remove node modules
rm package-lock.json yar.lock
npm cache clear --force
npm install

Also run migrations

REDIRECT USER TO login page if not authenticated

If you want to create a custom middleware to redirect users if they are not authenticated, you can create a RedirectIfNotAuthenticated middleware in Laravel. Here are the steps to implement it:
1.Create a new middleware class by running the following command in your Laravel project's root directory:

php artisan make:middleware RedirectIfNotAuthenticated

2. Open the app/Http/Middleware/RedirectIfNotAuthenticated.php file and modify the handle method to redirect the user if they are not authenticated. Here's an example implementation:

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class RedirectIfNotAuthenticated
{
    public function handle($request, Closure $next)
    {
        if (!auth()->check()) {
           return redirect('/login')->with("status","Login First to access this page");
        }

        return $next($request);
    }
}

3. Register the middleware in the app/Http/Kernel.php file. Locate the $routeMiddleware property and add the following line:

'notAuth' => \App\Http\Middleware\RedirectIfNotAuthenticated::class,

4. Now, you can apply the middleware to your routes or controllers using the notAuth middleware key. For example:

Route::controller(\App\Http\Controllers\AffliateController::class)->middleware(['notAuth'])->group(function () {
    Route::get('affliate', 'index')->name('affliate');
});

In this example, the notAuth middleware is applied to a group of routes that should only be accessible to unauthenticated users.

By creating and using the RedirectIfNotAuthenticated middleware, you can easily redirect users who are not authenticated to a specific URL or route in your Laravel application.

==================
                 LOGIC
==================

app/Http/Controllers/Auth/LoginController.php

use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
    use AuthenticatesUsers; 
    protected $redirectTo = '/home';
}

AuthenticatesUsers trait already contains full login logic:

  1. Validate email & password
  2. Check user in database
  3. Compare hashed password
  4. Create session
  5. Redirect after login

=======================
login throttling / account lockout
=======================
Laravel already has this feature built-in inside: Illuminate\Foundation\Auth\AuthenticatesUsers
It uses another trait internally: ThrottlesLogins

class LoginController extends Controller
{
    use AuthenticatesUsers;
    protected $redirectTo = '/dashboard'; //after successfull login
    protected $maxAttempts = 2; // allow only 2 attempts
    protected $decayMinutes = 60; // lock for 60 minutes
}

 Internally it use this file: vendor/laravel/framework/src/Illuminate/Foundation/Auth/ThrottlesLogins.php

It uses:

  1. Cache
  2. IP + email combination
  3. Rate limiter

If You Want Custom Error Message Override this method in LoginController:

protected function sendLockoutResponse(\Illuminate\Http\Request $request)
{
    $seconds = $this->limiter()->availableIn(
        $this->throttleKey($request)
    );

    $minutes = ceil($seconds / 60);

    throw \Illuminate\Validation\ValidationException::withMessages([
        'email' => "Too many login attempts. Please try again in $minutes minute(s)."
    ]);
}

 

Posted by: R GONDAL
Email: rizikmw@gmail.com