Home > Mobile >  Middleware for 2 step authorization
Middleware for 2 step authorization

Time:03-08

I am beginner in Laravel. I make my application in Laravel 8 and spatie/laravel-permission. Actually i have persimmons: individual|company

Route::group(['prefix' => '', 'middleware' => ['role:individual|company']], function () {
    Route::get('/cms-historia-przesylek-nadanych', 'Account\SendPackageController@index')->name('cms-history-send-packages')->middleware('company');
    Route::get('/cms-przesyleka-nadana/{id}', 'Account\SendPackageController@show')->name('cms-view-send-package')->middleware('company');
    Route::get('/cms-przesyleka-nadana-zwrot/{id}', 'Account\SendPackageController@returnBackPackage')->name('cms-view-send-package-return')->middleware('company');
    Route::post('/cms-przesyleka-nadana-zwrot/zamow-paczke/{id}', 'Account\SendPackageController@orderPackage')->name('cms-view-send-package-return-order')->middleware('company');
    Route::get('/cms-pobierz-przesyleke-nadana/{id}', 'Account\SendPackageController@getPdf')->name('cms-get-send-package')->middleware('company');
    Route::get('/cms-historia-przesylek-odebranych', 'Account\ReceivedPackageController@index')->name('cms-history-received-packages')->middleware('company');
    Route::get('/cms-przesyleka-odebrana/{id}', 'Account\ReceivedPackageController@show')->name('cms-view-received-package')->middleware('company');
    Route::get('/cms-pobierz-przesyleke-odebrana/{id}', 'Account\ReceivedPackageController@getPdf')->name('cms-get-received-package')->middleware('company');
    Route::get('/cms-dwu-stopniowa-weryfikacja', 'Account\TwoStepVerificationController@index')->name('cms-two-step-verification');
});

And this is my USER.php:

<?php

namespace App\Models;

use App\Traits\ScopeActiveTrait;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;

class User extends Authenticatable
{
    use Notifiable,
        ScopeActiveTrait,
        HasRoles,
        SoftDeletes,
        HasSlug;

    /**
     * Get the options for generating the slug.
     */
    public function getSlugOptions() : SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom(['company_name', 'id'])
            ->slugsShouldBeNoLongerThan(250)
            ->saveSlugsTo('slug');
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'enable',
        'company_id',
        'surname',
        'email_verified_at',
        'description',
        'is_company',
        'package1',
        'package2',
        'package3',
        'sms',
        'phone',
        'street',
        'building_number',
        'city',
        'postal_code',
        'revicer_default_inpost_parcel',
        'shipping_default_inpost_parcel',
        'file_name',
        'nip',
        'company_name',
        'remember_token',
        'subdomain',
        'lng',
        'lat',
        'show_map',
        'ofert_type',
        'discount_value1',
        'discount_value2',
        'discount_value3',
        'discount_value4',
        'discount_value5',
        'is_two_step_authorization',
        'two_step_authorization_token',
    ];

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'company_id' => 'integer',
        'enable'=>'boolean',
        'isCompany'=>'boolean',
        'show_map'=>'boolean',
    ];


    /* User Login history */
    public function loginHistory()
    {
        return $this->hasMany('App\Models\UserLoginHistory');
    }

    /* User images */

    public function images()
    {
        return $this->hasManyThrough('App\Models\UploadFile', 'App\Models\User', 'id', 'file_id');
    }

    public function mainImage()
    {
        return $this->images()->where('file_type', 'DZ_ADMIN');
    }

    /* Admin Avatar */

    public function getAvatar()
    {
        return $this->images()->where('file_type', 'DZ_ADMIN')->orderBy('order', 'ASC')->first();
    }

    public function isCompany(): bool
    {
        return $this->is_company == 1;
    }
}

When I have is_two_step_authorization = 1.- then I need run new middleware for 2 step authorization,.

How can I make it?

is_two_step_authorization = 0 - 2 factorial authorization is disabled. is_two_step_authorization = 1 - Two-factor authentication is enabled.

I think use this tutorial: https://www.itsolutionstuff.com/post/laravel-8-two-factor-authentication-with-smsexample.html but this middleware work always for route with middleware 2fa.

In my case, selected routs may require 2-step security (if the user has chosen so in the settings) or not (the user has disabled security).

How can I change the code from the tutorial to get it?

CodePudding user response:

You need to update the middleware from the tutorial in order to only redirect to 2fa index if the logged user has is_two_step_authorization on. Of course you may need other checks, or to ensure that the user is logged in and so on, but just for this specific usecase, this line of code should do the trick.

app/Http/Middleware/Check2FA.php

public function handle(Request $request, Closure $next)
{
    if ($request->user()->is_two_step_authorization && !Session::has('user_2fa')) {
        return redirect()->route('2fa.index');
    }

    return $next($request);
}

CodePudding user response:

Tweak the code from that example...

<?php
  
namespace App\Http\Middleware;
  
use Closure;
use Illuminate\Http\Request;
use Session;
  
class Check2FA
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if ($request->user()->is_two_step_authorization == 1) {
            return redirect()->route('2fa.index');
        }
  
        return $next($request);
    }

If the requested user has the property of is_two_step_authorization with value one only then it will redirect to the 2fa page, otherwise not

  • Related