Frontend.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace app\common\controller;
  3. use think\facade\Event;
  4. use think\facade\Cookie;
  5. use app\common\library\Auth;
  6. use think\exception\HttpResponseException;
  7. class Frontend extends Api
  8. {
  9. /**
  10. * 无需登录的方法
  11. * 访问本控制器的此方法,无需会员登录
  12. */
  13. protected $noNeedLogin = [];
  14. /**
  15. * 无需鉴权的方法
  16. */
  17. protected $noNeedPermission = [];
  18. /**
  19. * 权限类实例
  20. * @var Auth
  21. */
  22. protected $auth = null;
  23. public function initialize()
  24. {
  25. parent::initialize();
  26. $this->auth = Auth::instance();
  27. $routePath = $this->app->request->controllerPath . '/' . $this->request->action(true);
  28. $token = $this->request->server('HTTP_BA_USER_TOKEN', $this->request->request('ba-user-token', Cookie::get('ba-user-token') ?: false));
  29. if (!action_in_arr($this->noNeedLogin)) {
  30. $this->auth->init($token);
  31. if (!$this->auth->isLogin()) {
  32. $this->error(__('Please login first'), [
  33. 'routePath' => '/user/login'
  34. ], 302);
  35. }
  36. if (!action_in_arr($this->noNeedPermission)) {
  37. if (!$this->auth->check($routePath)) {
  38. $this->error(__('You have no permission'), [], 401);
  39. }
  40. }
  41. } elseif ($token) {
  42. try {
  43. $this->auth->init($token);
  44. } catch (HttpResponseException $e) {
  45. }
  46. }
  47. // 会员验权和登录标签位
  48. Event::trigger('frontendInit', $this->auth);
  49. }
  50. }