Auth facade vs Middleware
- Laravel Auth facade is used for login, logout and to check whether logged in or not.
- On the other hand, auth middleware is used for redirection depending on logged in or not.
Notes:
- 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.
- $this->middleware(‘auth’) uses the default guard. $this->middleware(auth:admin) is called admin guard or protect against admin, it allows admin.
- $this->middleware(‘guest:admin’), it allows guest of admin. Users are also guest of admin.
- As view are returned from controller, we can set middleware in controller and/or router for access controlling.
- 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.
- session
- token
- eloquent
- 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.
- exception\handler.php: unauthenticated() function works on unauthenticated user when they try to access the dashboard.
- 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)
- view:
- admin.blade.php
- auth/admin-login.blade.php
- Controller:
- AdminController.php
- Auth/AdminLoginController.php
- Model: Admin.php
- Route: Create few routes
- 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:
- You should have a basic understanding of guard inside config/auth.php
- Kernel.php has two middlewares auth and guest. They create exceptions during unauthorized access. (Read above)
- 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.
- You can check the login in controller, view etc. using
if(Auth::guard('admin')->check()){}
- 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:
- Create two controllers and copy
- Auth/AdminForgetPasswordController.php
- Auth/AdminResetPasswordController.php
- Edit config/auth.php and add password broker. Notice : This file contains
- guard
- password broker
- View:
- auth/passwords/email-admin.blade.php
- auth/passwords/reset-admin.blade.php
- Model: Copy the sendPasswordNotification() method to the Admin model
- 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.
- Edit the routes/web.php file and copy the four links at the bottom of the file.
- 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
Multiauth using custom middleware (process 2)
Simply you can authenticate:
@auth
// The user is authenticated...
@endauth
@guest
// The user is not authenticated...
@endguest
- 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;
}
- Add the type column to the migration that created your users table
$table->string('role')->default('user');
- 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,
]);
}
- 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');
}
}
- Register the middleware you just created (routeMiddleware)
'is_admin' => \App\Http\Middleware\IsAdmin::class,
- 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');
- 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
id | name |
1 | Super admin |
2 | developer |
3 | admin |
4 | moderator |
5 | user |
Remember to use as like below
- The authentication occurs in blade
- 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: Laravel, Web development