Frontend.php 1.8 KB

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