Token.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /**
  3. * Author: luzheng.liu
  4. * Time: 2020/8/26 18:54
  5. */
  6. namespace app\common\until;
  7. use app\api\exception\ApiException;
  8. use app\api\exception\TokenException;
  9. use Firebase\JWT\ExpiredException;
  10. use Firebase\JWT\JWT;
  11. class Token {
  12. public $jwtKey = '';
  13. public $expTime = 3600;
  14. public function __construct() {
  15. $this->jwtKey = env('app.jwt_key', 'Rn4zNAX9e3li5dfI6mBuWLvbacTZq123');
  16. }
  17. public function getToken(int $userId, string $visitor = '', $isAdmin = false) {
  18. $payload = [
  19. "iat" => time(),
  20. "exp" => time() + (3600 * 24 * 7),
  21. "userId" => $isAdmin ? 1 : $userId,
  22. "visitor" => $visitor,
  23. 'isAdmin' => $isAdmin ? 1 : 0,
  24. 'adminId' => $isAdmin ? $userId : 0,
  25. ];
  26. $token = JWT::encode($payload, $this->jwtKey);
  27. return $token;
  28. }
  29. public function decodeToken(): array {
  30. $token = request()->header('token') ?: request()->get('token');
  31. if (empty($token)) {
  32. throw new ApiException('token不能为空');
  33. }
  34. try {
  35. $decoded = JWT::decode($token, $this->jwtKey, ['HS256']);
  36. } catch (ExpiredException $e) {
  37. throw new TokenException('token到期,请刷新');
  38. } catch (\Exception $e) {
  39. throw new ApiException('token无效' . $e->getMessage());
  40. }
  41. $tokenInfo = (array)$decoded;
  42. if (time() - $tokenInfo['exp'] > 3600) {
  43. $GLOBALS['refreshToken'] = $this->getToken($tokenInfo['usrId']);
  44. }
  45. return (array)$decoded;
  46. }
  47. }