Auth
用户注册登录流程及多字段登录实现
基于多表的用户认证功能实现
授权方式 Gate 和 Policy
laravel-permission 中文文档
在app/Http/Kernel.php中注册中间件
全局注册:
protected $middleware = {
\App\Http\Middleware\authorize::class,
}
路由注册:
protected $routeMiddleware = {
'auth' => \App\Http\Middleware\authorize::class,
}
路由中绑定:
Route::get('post', 'PostController@index')->middleware('auth');
Route::middleware('auth')->group(function () {
Route::get('post', 'PostController@index');
});
控制器中指定:
class HomeController extends Controller {
public function __construct() {
//指定中间件,排除某些方法
return $this->middleware('auth:admin')->exerpt('index');
}
}
授权方式
php artisan make:policy PostPolicy --model=Post
控制器:
$this->authorize('update', $post);
if ($user->can('update', $post) {
}
指定另一个用户:
if (Gate::forUser($user)->allows('update-post', $post)) {
// 当前用户可以更新文章...
}
if (Gate::forUser($user)->denies('update-post', $post)) {
// 当前用户不能更新文章...
}
Blade模板:
@can('update', $post)
<!-- 当前用户可以更新文章 -->
@elsecan('create', App\Post::class)
<!-- 当前用户可以创建新文章 -->
@endcan
@cannot('update', $post)
<!-- 当前用户不能更新文章 -->
@elsecannot('create', App\Post::class)
<!-- 当前用户不能创建新文章 -->
@endcannot
不用模型:
@can('create', App\Post::class)
<!-- 当前用户可以创建文章 -->
@endcan
@cannot('create', App\Post::class)
<!-- 当前用户不能创建文章 -->
@endcannot
系统内置插件实现用户认证
重定向
if ($request->action === 'continue') {
return redirect()
->back()
->with('success', '文章已保存.');
}
return redirect()
->route('post.index')
->with('success', '文章已保存.');
唯一验证
unique:admins
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:admins'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
]);
}
public function __call($method, $parameters)
{
return $this->guard()->{$method}(...$parameters);
}
php artisan make:auth
php artisan migrate
npm install
npm run dev
$user = Auth::user(); // 获取当前登录用户的完整信息
$userId = Auth::id(); // 获取当前登录用户 ID
提供Blade指令
@auth
// 用户已登录...
@endauth
@guest
// 用户未登录...
@endguest
request实例
$user = $request->user();
在LoginController中设置登录重试次数
// 单位时间内最大登录尝试次数
protected $maxAttempts = 3;
// 单位时间值
protected $decayMinutes = 30;
在LoginController改email登录为用户名登录
重写 AuthenticatesUsers Trait 中的方法
public function username()
{
return 'name';
}