laravel用户认证

用户认证

# laravel用户认证事实上是指用户从登录->登录成功的会话维持->退出登录结束会话。
# 主要是由守卫和提供者这两个方面入手

数据表

CREATE TABLE `admins` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `status` int(11) NOT NULL DEFAULT '1',
  `deleted_at` timestamp NULL DEFAULT NULL,
  `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `employees_email_unique` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
<?php
// app\Models\Admin.php(复制User模型)
namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];
    protected $hidden = [
        'password',
        'remember_token',
    ];
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

定义守卫

// config\auth.php
'guards' => [
    'admin' => [
        // 个人理解为会话的存储方式
        'driver' => 'session',
        // 提供者(提供需要的操作方式)
        'provider' => 'admins',
    ]
],

定义提供者

// config\auth.php
'providers' => [
    'admins' => [
        // 操作方式模型
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
],

重置密码方式(略)

'passwords' => [
    'admins' => [
        'provider' => 'admins',
        'table' => 'password_resets',
        'expire' => 60
    ]
]

会话的有效时间

// config\auth.php
'password_timeout' => 10800,

实现的流程部分

新增一个用户(bcrypt(‘123456’))

INSERT INTO admins(name, email,password) VALUES('yaoxs', 'abcdef@qq.com', '$2y$10$nrgOOalJ1lxtkm/CiUMG7uT14GsamVPSlDKS4KwiC9s3xcnAUvyti');

定义一个验证用户是否登录的中间件

<?php
namespace App\Http\Middleware;
use Closure;
class TestMiddleware
{
    public function handle($request, Closure $next)
    {
        // auth() 获取 Auth 对象,等同于 Auth Facade
        // guard 自定义看守器 默认为 `web` 这里是employee
        // check 判断当前用户是否已认证(是否已登录)
        if (!auth()->guard('admin')->check()) {
            // 存储session
            $request->session()->flash('error', 'You must be an employee to see this page');
            // redirect 返回重定向器实例以进行 重定向
            // route 根据命名路由算出 URL
            return redirect(route('loginView'));
        }
        return $next($request);
    }
}

注册路由中间件

// H:\laravel\blog\app\Http\Kernel.php
protected $routeMiddleware = [
    'test' => \App\Http\Middleware\TestMiddleware::class,
];

创建登录路由

Route::get('/login', function () {
    $details = [
        'email' => 'abcdef@qq.com',
        'password' => '123456'
    ];
    if(auth()->guard('admin')->attempt($details)){
        return '登录成功';
    }
    return '登录失败';
});

创建用户登录后进入主页的路由

Route::get('/home', function () {
    return '登录成功进入主页';
})->middleware('test')->name('home');

定义验证不同过的路由

Route::get('/loginView', function(){
    return '验证失败,请登录';
})->name('loginView');

定义退出登录的路由

Route::get('/logout', function () {
    // 这里的返回值是空,不是布尔值有点纳闷
    auth()->guard('admin')->logout();
    return '退出登录成功';
});
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!