查看: 1611|回复: 0

[PHP代码] 二 laravel blog Auth前后台登录的后台理解

发表于 2018-3-12 08:00:03
  1. 因为时间有限就不展示自己前台代码的书写,就是想巩固一下自己对Auth后台的理解
复制代码

在RouteServriceProvider区分一下前后台路由代码` public function map()
{
$this->mapApiRoutes();

  1. $this->homeRoutes();
  2. $this->adminRoutes();
  3. //
  4. }
  5. /**
  6. * Define the "web" routes for the application.
  7. *
  8. * These routes all receive session state, CSRF protection, etc.
  9. *
  10. * @return void
  11. *
  12. * 前台路由
  13. */
  14. protected function homeRoutes()
  15. {
  16. Route::middleware('web')
  17. ->namespace($this->namespace.'\Home')
  18. ->group(base_path('routes/home.php'));
  19. }
  20. /*
  21. * 后台路由
  22. */
  23. protected function adminRoutes()
  24. {
  25. Route::middleware('web')
  26. ->namespace($this->namespace.'\Admin')
  27. ->group(base_path('routes/admin.php'));
  28. }
  29. /**
  30. * Define the "api" routes for the application.
  31. *
  32. * These routes are typically stateless.
  33. *
  34. * @return void
  35. */
  36. protected function mapApiRoutes()
  37. {
  38. Route::prefix('api')
  39. ->middleware('api')
  40. ->namespace($this->namespace)
  41. ->group(base_path('routes/api.php'));
  42. }`
复制代码

然后在config auth下注册guard(‘admin’)

  1. 'guards' => [
  2. 'web' => [
  3. 'driver' => 'session',
  4. 'provider' => 'users',
  5. ],
  6. 'admin' => [
  7. 'driver' => 'session',
  8. 'provider' => 'admins',
  9. ],
  10. 'api' => [
  11. 'driver' => 'token',
  12. 'provider' => 'users',
  13. ],
  14. ],
  15. 'providers' => [
  16. 'users' => [
  17. 'driver' => 'eloquent',
  18. 'model' => App\User::class,
  19. ],
  20. 'admins' => [
  21. 'driver' => 'eloquent',
  22. 'model' => App\Admin::class,
  23. ],
  24. // 'users' => [
  25. // 'driver' => 'database',
  26. // 'table' => 'users',
  27. // ],
  28. ],
复制代码

仿User创建Admin model层` use Notifiable;

  1. /**
  2. * The attributes that are mass assignable.
  3. *
  4. * @var array
  5. */
  6. protected $fillable = [
  7. 'name', 'password',
  8. ];
  9. /**
  10. * The attributes that should be hidden for arrays.
  11. *
  12. * @var array
  13. */
  14. protected $hidden = [
  15. 'password', 'remember_token',
  16. ];`
复制代码

迁移文件填充数据就不展示了

  1. class LoginController extends Controller
  2. {
  3. /*
  4. |--------------------------------------------------------------------------
  5. | Login Controller
  6. |--------------------------------------------------------------------------
  7. |
  8. | This controller handles authenticating users for the application and
  9. | redirecting them to your home screen. The controller uses a trait
  10. | to conveniently provide its functionality to your applications.
  11. |
  12. */
  13. use AuthenticatesUsers;
  14. /**
  15. * Where to redirect users after login.
  16. *
  17. * @var string
  18. */
  19. protected $redirectTo = '/admin';
  20. /**
  21. * Create a new controller instance.
  22. *
  23. * @return void
  24. */
  25. //我这里是更改了中间件判断当前用户是否认证通过,如果是admin的话跳转到/admin,就以注释的方式展示
  26. // public function handle($request, Closure $next, $guard = null)
  27. //{
  28. // if (Auth::guard($guard)->check()) {
  29. // return redirect($guard == 'admin' ? '/admin' : '/home');
  30. // }
  31. // return $next($request);
  32. // }
  33. //}
  34. //
  35. //
  36. public function __construct()
  37. {
  38. $this->middleware('guest:admin')->except('logout');
  39. }
  40. /*
  41. * 显示后台登录模板
  42. *
  43. */
  44. public function showLoginForm()
  45. {
  46. return view('admin.login');
  47. }
  48. /*
  49. * 验证name字段
  50. */
  51. public function username()
  52. {
  53. return 'name';
  54. }
  55. /*
  56. * 生成guard(‘admin’)
  57. */
  58. protected function guard()
  59. {
  60. return auth()->guard('admin');
  61. }
  62. /*
  63. * 验证表单
  64. */
  65. protected function validateLogin(Request $request)
  66. {
  67. $this->validate($request, [
  68. $this->username() => 'required|string|max:6',
  69. 'password' => 'required|string|max:6',
  70. ],[
  71. $this->username().'required'=>'账号必须填写',
  72. $this->username().'string'=>'账号必须填写字符串',
  73. $this->username().'max'=>'账号不大于6位',
  74. 'password.required'=>'密码必须填写',
  75. 'password.string'=>'密码必须填写字符串',
  76. 'password.max'=>'密码不大于6位',
  77. ]);
  78. }
  79. //重写提交登录失败信息
  80. protected function sendFailedLoginResponse(Request $request)
  81. {
  82. $name = $request->name;
  83. $user=Admin::where('name',$name)->first();
  84. if(empty($user))
  85. {
  86. throw ValidationException::withMessages([
  87. 'name'=>'没有此用户'
  88. ]);
  89. return false;
  90. }
  91. if (!Hash::check($request->password, $user->password)) {
  92. throw ValidationException::withMessages([
  93. 'password'=>'密码错误'
  94. ]);
  95. return false;
  96. }
  97. }
  98. //用户通过身份认证
  99. protected function sendLoginResponse(Request $request)
  100. {
  101. // 设置记住我的时间为60分钟
  102. $rememberTokenExpireMinutes = 60;
  103. // 首先获取 记住我 这个 Cookie 的名字, 这个名字一般是随机生成的,
  104. // 类似 remember_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d
  105. $rememberTokenName = Auth::guard('admin')->getRecallerName();
  106. // 再次设置一次这个 Cookie 的过期时间
  107. Cookie::queue($rememberTokenName, Cookie::get($rememberTokenName), $rememberTokenExpireMinutes);
  108. // 下面的代码是从 AuthenticatesUsers 中的 sendLoginResponse() 直接复制而来
  109. $request->session()->regenerate();
  110. $this->clearLoginAttempts($request);
  111. return $this->authenticated($request, $this->guard()->user())
  112. ?: redirect()->intended($this->redirectPath());
  113. }
  114. protected function authenticated(Request $request, $user)
  115. {
  116. info('测试日志');
  117. // return response()->json(['msg'=>200]);
  118. }
  119. }
复制代码

我们还要防止用户直接跳过登录访问别的页面
app下的Exceptions/Handler.php//前后端未登录的跳转 protected function unauthenticated($request, AuthenticationException $exception) { if (in_array('admin', $exception->guards())) { return $request->expectsJson() ? response()->json(['msg'=>'用户未登录'], 401) : redirect()->guest(url('admin/login')); } return $request->expectsJson() ? response()->json(['msg'=>'用户未登录'], 401) : redirect()->guest(route('login')); } }
ok然后在路由加个中间件



回复

使用道具 举报