Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all articles
Browse latest Browse all 595

Laravel MultiAuth

$
0
0

For the development of dynamic and higher level website Laravel is the best platform.

To manage the content and other stuffs of the site we always need an admin panel through which we can handle the content of the site.
To implement a separate admin panel in any laravel project we need to add multiple authentication functionality in site. Let us proceed to that.

Laravel 5.2 comes with new artisan command which will generate route, controller and views for users table.
Open terminal, go to your project directory and fire below command :

php artisan make:auth

After you fire this command your controller will have following files :

app/Http/Controllers/Auth/AuthController
app/Http/Controllers/Auth/PasswordController

Now create new table called admin (For simplicity you can create same migration for admin as users table)

Now create new directory called AdminAuth in app/Http/Controllers and copy above files to AdminAuth directory, the directory structure will be like:

app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController

Now Copy files from resources/views/auth directory to resources/views/admin/auth directory and update the action path of the forms accordingly.

Now let’s modify config/auth.php,
replace below code in auth.php

/* Authentication Guard*/

   ‘guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admin',
        ],
    ],

/*User Providers */

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admin' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ]
    ],

/* Resetting Passwords*/

'passwords' => [
        'users' => [
            'provider' => 'users',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'admins' => [
            'provider' => 'admin',
            'email' => 'admin.auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

Now let’s add new rules for admin in Routes.php

Route::group(['middleware' => ['web']], function () {
    //Admin Login Routes...
    Route::get('/admin/login','AdminAuth\AuthController@showLoginForm');
    Route::post('/admin/login','AdminAuth\AuthController@login');
    Route::get('/admin/logout','AdminAuth\AuthController@logout');

    /*Registration Routes...
    I have commented out registration routes for admin as in my case I don’t want to add registration functionality for admin, you can use it if you want to add the same functionality by just removing the comments */

    /*Route::get('admin/register', 'AdminAuth\AuthController@showRegistrationForm');
    Route::post('admin/register', 'AdminAuth\AuthController@register');*/

    Route::post('admin/password/email','AdminAuth\PasswordController@sendResetLinkEmail');
    Route::post('admin/password/reset','AdminAuth\PasswordController@reset');
    Route::get('admin/password/reset/{token?}','AdminAuth\PasswordController@showResetForm');

    Route::get('/admin', 'admin\Dashboard@index');
});

Now go to AdminAuth\AuthController.php and override two methods and variables below:

protected $redirectTo = '/admin';
    protected $redirectAfterLogout = '/admin/login';
    protected $guard = 'admin';

    public function showLoginForm(){
        if(session()->pull('url.intended') == URL::to('/')){
            session()->set('url.intended', URL::to('/admin'));
        }

        if(view()->exists('auth.authenticate')){
            return view('auth.authenticate');
        }
        return view('admin.auth.login');
    }

    public function showRegistrationForm(){

        return view('admin.auth.register');
    }

In above code you can see that we have overridden three protected variables which will change the actual behaviour of the laravel authentication library.

$redirectTo will be used to redirect the user once s/he successfully logged in to the admin panel.

$redirectAfterLogout will define where to redirect user after logout from admin panel.

$guard this is the crucial part of the Auth, here we are defining the guard for the panel as we have added new guard in Auth.php.

showLoginForm()  will override the actual behaviour of auth and will show the admin login form.

showRegistrationForm() will show the admin registration form. In my case, this is not needed as I have removed the registration functionality for admin.

Now create new middleware called RedirectIfNotAdmin using below command

php artisan make:middleware RedirectIfNotAdmin

Now add below code in the middleware

use Illuminate\Support\Facades\Auth;
use Illuminate\Session\Console;
use Session;
class RedirectIfNotAdmin 
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = 'admin')
    {
        if (!Auth::guard($guard)->check()) {
             session()->set('url.intended', $request->url());
            return redirect('/admin/login');
        }

        return $next($request);
    }
}

Now Register middleware in kernel.php

protected $routeMiddleware = [
    'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];

Now we will use this middleware in our AdminController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class AdminController extends Controller
{
    public function __construct(){
        $this->middleware('admin');
   }
public function index(){
        return view('admin.dashboard');
    }
}

That’s it!! this is all we needed to make it working.

Please Note:
We can access authenticated user details directly using Auth::user() but if we have multiple authentication then we have to use :

Auth::guard(‘guard_name’)->user();

For logout
Auth::guard(‘guard_name’)->user->logout();

And to get details of authenticated user in json format :
Auth::guard(‘guard_name’)->user();

For Password Reset

In App/Http/Controllers/AdminAuth/PasswordController.php  file, add two protected variables

protected $guard = ‘admin’; //For guard

protected $broker = ‘admins’; //For letting laravel know which config you’re going to use for resetting password

Now add below mentioned three public methods

public function getEmail()
{
    return $this->showLinkRequestForm();
}

public function showLinkRequestForm()
{
    if (property_exists($this, 'linkRequestView')) {
        return view($this->linkRequestView);
    }

    if (view()->exists('admin.auth.passwords.email')) {
        return view('admin.auth.passwords.email');
    }

    return view('admin.auth.password');
}

public function showResetForm(Request $request, $token = null)
{

    if (is_null($token)) {
        return $this->getEmail();
    }
    $email = $request->input('email');

    if (property_exists($this, 'resetView')) {
        return view($this->resetView)->with(compact('token', 'email'));
    }

    if (view()->exists('admin.auth.passwords.reset')) {
        return view('admin.auth.passwords.reset')->with(compact('token', 'email'));
    }

    return view('admin.passwords.auth.reset')->with(compact('token', 'email'));
}

public function getEmail()
{
    return $this->showLinkRequestForm();
}

public function showLinkRequestForm()
{
    if (property_exists($this, 'linkRequestView')) {
        return view($this->linkRequestView);
    }

    if (view()->exists('admin.auth.passwords.email')) {
        return view('admin.auth.passwords.email');
    }

    return view('admin.auth.password');
}

public function showResetForm(Request $request, $token = null)
{

    if (is_null($token)) {
        return $this->getEmail();
    }
    $email = $request->input('email');

    if (property_exists($this, 'resetView')) {
        return view($this->resetView)->with(compact('token', 'email'));
    }

    if (view()->exists('admin.auth.passwords.reset')) {
        return view('admin.auth.passwords.reset')->with(compact('token', 'email'));
    }

    return view('admin.passwords.auth.reset')->with(compact('token', 'email'));
}

That’s all with the Laravel MultiAuth functionality.

Chirag Malaviya

Chirag Malaviya | Web Developer

Chirag is a PHP Web Developer at Yudiz Solutions Pvt. Ltd., who has the knowledge of Codeigniter and laravel frameworks, Node.js and socket programming. He is always eager to learn latest technology and find the tricky ways to make the things easy. He likes to face the technological challenges. He likes to get in touch with people with whom he can do something innovative.

Viewing all articles
Browse latest Browse all 595

Trending Articles