AuthBase.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. /**
  3. * Created by PhpStorm
  4. * User:林志杰
  5. * Email:[email protected]
  6. * Motto:纵有疾风起,人生不言弃!
  7. * Time:2020/2/8 23:10
  8. */
  9. namespace app\api\controller;
  10. /**
  11. * API模块下的公共控制器
  12. * 如果不需要登录的场景继承ApiBase这个控制器
  13. * 如果需要登录的场景继承AuthBase这个控制器
  14. * Class ApiBase
  15. * @package app\api\controller
  16. */
  17. class AuthBase extends ApiBase
  18. {
  19. public $userId = 0;
  20. public $username = '';
  21. public $accessToken = '';
  22. public function initialize()
  23. {
  24. parent::initialize(); // TODO: Change the autogenerated stub
  25. $this->accessToken = $this->request->header('access-token');
  26. if (!$this->accessToken || !$this->isLogin()) {
  27. return $this->show(config('status.not_login'), '没有登录');
  28. }
  29. }
  30. /**
  31. * 判断用户是否登录
  32. * @return bool
  33. */
  34. public function isLogin(): bool
  35. {
  36. $userInfo = cache(config('redis.token_pre') . $this->accessToken);
  37. if (!$userInfo) {
  38. return false;
  39. }
  40. if (!empty($userInfo['id']) && !empty($userInfo['username'])) {
  41. $this->userId = $userInfo['id'];
  42. $this->username = $userInfo['username'];
  43. return true;
  44. }
  45. return false;
  46. }
  47. }