Laravel authentication

Auth facade vs Middleware

  1. Laravel Auth facade is used for login, logout and to check whether logged in or not.
  2. On the other hand, auth middleware is used for redirection depending on logged in or not.
Notes:
  1. Auth facades can be like Auth::check(), Auth::attempt(), Auth::once(). These are default guard. Default guard is web. That is it will allow only users. It will not allow guest and admin.
  2. $this->middleware(‘auth’) uses the default guard. $this->middleware(auth:admin) is called admin guard or protect against admin, it allows admin.
  3. $this->middleware(‘guest:admin’), it allows guest of admin. Users are also guest of admin.
  4. As view are returned from controller, we can set middleware in controller and/or router for access controlling.
  5. Any controller will have $this->middleware() and $this->validate();

config\auth.php

Vocabulary
Provider: Who provides the data during authentication. Example model name, table name of the user, admin or guest.
Driver: Technology by which the authentication will be controlled.
  1. session
  2. token
  1. eloquent
  2. database

app\http\kernel.php

In this file, you will see two important middlewares are auth and guest. auth middleware allows authenticated user where guest middleware allows unauthenticated user.
  1. exception\handler.php: unauthenticated() function works on unauthenticated user when they try to access the dashboard.
  2. app\http\middleware\RedirectIfAuthenticated.php: Works on authenticated user.

Tinker

php artisan tinker
$admin = new App\Admin
$admin->name = "Rejaul"
$admin->email = "rejauldu@gmail.com"
$admin->password = Hash::make('123456');
$admin->save();

Multi auth login (process 1)

  1. view:
    1. admin.blade.php
    2. auth/admin-login.blade.php
  2. Controller:
    1. AdminController.php
    2. Auth/AdminLoginController.php
  3. Model: Admin.php
  4. Route: Create few routes
  5. migration: create_admins_table
The above 5 steps will create your basic login for admin. You should visit these pages and need to clear your concepts as follows:
  1. You should have a basic understanding of guard inside config/auth.php
  2. Kernel.php has two middlewares auth and guest. They create exceptions during unauthorized access. (Read above)
  3. Inside LoginController.php, you will see there is no showLoginForm(), login(), logout() etc functions. Now notice that there is a imported file AuthenticatesUsers. This file contains all the functions.
  4. You can check the login in controller, view etc. using
    if(Auth::guard('admin')->check()){}
  5. Notice the following middleware:
    $this->middleware('guest:admin', ['except' => 'logout']);
The above part completes login, logout with proper redirection (video 1 to 4)

Forget password

Step 0: Click the “Forget Your Password?” link
Step 1: User fills our email request form.
Step 2: User gets email with reset link and click “Reset Password”
Step 3: We show a form to enter new password.
Step 4: Update pass in database and make user logged in.
Notice the route links in the image below:

Now do the following tasks:
  1. Create two controllers and copy
    1. Auth/AdminForgetPasswordController.php
    2. Auth/AdminResetPasswordController.php
  2. Edit config/auth.php and add password broker. Notice : This file contains
    1. guard
    2. password broker
  3. View:
    1. auth/passwords/email-admin.blade.php
    2. auth/passwords/reset-admin.blade.php
  4. Model: Copy the sendPasswordNotification() method to the Admin model
  5. Notification: sendPasswordNotification() method have used a notification. So create notification using the following command:
    php artisan make:notification AdminResetPasswordNotification
    A notification will be created in a new folder named Notifications. Now, copy this file.
  6. Edit the routes/web.php file and copy the four links at the bottom of the file.
  7. Config email server
    go to .env file
    Edit the following parameters:
    MAIL_HOST = mailtrap.io
    MAIL_PORT = 2525
    MAIL_USERNAME = ....
    MAIL_PASSWORD = ....
    MAIL_ENCRYPTION = null
Source video: https://www.youtube.com/watch?v=iKRLrJXNN4M&list=PLwAKR305CRO9S6KVHMJYqZpjPzGPWuQ7Q&index=1

Multiauth using custom middleware (process 2)

Simply you can authenticate:
@auth
    // The user is authenticated...
@endauth

@guest
    // The user is not authenticated...
@endguest
Follow the steps (modified from this link):
  1. Add the types you want to the User model and a method to check if a user is an admin.
    const ADMIN_TYPE = 'admin';
    const DEFAULT_TYPE = 'user';
    public function isAdmin()    {        
        return $this->role === self::ADMIN_TYPE;    
    }
  2. Add the type column to the migration that created your users table
    $table->string('role')->default('user');
  3. Add a type value to the create method in register controller
    protected function create(array $data)    {        
        return User::create([            
            'name' => $data['name'],
            'email' => $data['email'],            
            'password' => bcrypt($data['password']),            
            'role' => User::DEFAULT_TYPE,        
        ]);    
    }
  4. Create a custom middleware file to check if a user is an admin (Notice before checking if admin, we check if logged in). Generate this file using
    php artisan make:middleware IsAdmin
    namespace App\Http\Middleware;
    use Closure;
    use Illuminate\Support\Facades\Auth;
    class IsAdmin
    {
        public function handle($request, Closure $next)
        {
            if(Auth::check() && auth()->user()->isAdmin()) {
                return $next($request);
            }
        return redirect('home');
    }
    }
  5. Register the middleware you just created (routeMiddleware)
    'is_admin' => \App\Http\Middleware\IsAdmin::class,
  6. Add some routes that invoke the middleware
    Route::view('welcome');
        Auth::routes();
        Route::get('/home', 'HomeController@index')    
        ->name('home');
        Route::get('/admin', 'AdminController@admin')    
        ->middleware('is_admin')    
        ->name('admin');
  7. Create an admin controller with
    php artisan make:controller AdminController.
    This controller returns the dashboard for whatever view you want your admin to see.
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    class AdminController extends Controller
    {
        public function admin()
        {
            return view('admin');
        }
    }

Multiauth using role (process 3)

If you want to develop the website using roles table, then users table will have a role_id foreign key. roles
idname
1Super admin
2developer
3admin
4moderator
5user
Remember to use as like below
  1. The authentication occurs in blade
  2. As like
    @guest
    Write your code here for people those who not register
    @else
    Write your code here for logged in user.
    if(Auth::user()->role_id == 1) {}
    @endguest
    Code here will be executed for both user and guest

Labels: ,

© copyright-2020 Rejaul