Frontend.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace app\common\controller;
  3. use Throwable;
  4. use think\facade\Event;
  5. use app\common\library\Auth;
  6. use think\exception\HttpResponseException;
  7. use app\common\library\token\TokenExpirationException;
  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. $needLogin = !action_in_arr($this->noNeedLogin);
  35. try {
  36. // 初始化会员鉴权实例
  37. $this->auth = Auth::instance();
  38. $token = get_auth_token(['ba', 'user', 'token']);
  39. if ($token) $this->auth->init($token);
  40. } catch (TokenExpirationException) {
  41. if ($needLogin) {
  42. $this->error(__('Token expiration'), [], 409);
  43. }
  44. }
  45. if ($needLogin) {
  46. if (!$this->auth->isLogin()) {
  47. $this->error(__('Please login first'), [
  48. 'type' => $this->auth::NEED_LOGIN
  49. ], $this->auth::LOGIN_RESPONSE_CODE);
  50. }
  51. if (!action_in_arr($this->noNeedPermission)) {
  52. $routePath = ($this->app->request->controllerPath ?? '') . '/' . $this->request->action(true);
  53. if (!$this->auth->check($routePath)) {
  54. $this->error(__('You have no permission'), [], 401);
  55. }
  56. }
  57. }
  58. // 会员验权和登录标签位
  59. Event::trigger('frontendInit', $this->auth);
  60. }
  61. }