TokenService.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * @Name
  4. * @Description
  5. * @Author 刘学玺
  6. * @Date 2023/11/24 12:25
  7. */
  8. namespace App\Http\Services\Admin;
  9. use App\Exceptions\ApiException;
  10. use App\Exceptions\Code;
  11. use App\Exceptions\Message;
  12. use App\Http\Services\BaseService;
  13. use Exception;
  14. use Illuminate\Contracts\Routing\ResponseFactory;
  15. use Illuminate\Foundation\Application;
  16. use Illuminate\Http\Response;
  17. use Illuminate\Support\Facades\Config;
  18. use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
  19. use Tymon\JWTAuth\Facades\JWTAuth;
  20. class TokenService extends BaseService
  21. {
  22. public function __construct()
  23. {
  24. Config::set('auth.defaults.guard', 'admin');
  25. // Config::set('jwt.ttl',60);
  26. }
  27. public function setToken($data)
  28. {
  29. if (!$token = JWTAuth::attempt($data)) {
  30. $this->apiError('token生成失败');
  31. }
  32. return $this->respondWithToken($token);
  33. }
  34. /**
  35. * Notes : 刷新Token
  36. * Method : Interface refreshToken
  37. * @return \Illuminate\Contracts\Foundation\Application|ResponseFactory|Application|Response
  38. * @throws ApiException
  39. */
  40. public function refreshToken(): Application|Response|\Illuminate\Contracts\Foundation\Application|ResponseFactory
  41. {
  42. try {
  43. $oldToken = JWTAuth::getToken();
  44. $token = JWTAuth::refresh($oldToken);
  45. } catch (TokenBlacklistedException $e) {
  46. // token加入黑名单
  47. throw new ApiException(['code' => Code::TOKEN_ERROR_BLACK, 'message' => Message::TOKEN_ERROR_BLACK]);
  48. }
  49. return $this->apiSuccess('', $this->respondWithToken($token));
  50. }
  51. public function user(): object
  52. {
  53. return JWTAuth::parseToken()->touser();
  54. }
  55. public function info()
  56. {
  57. $data = $this->user();
  58. return $this->apiSuccess('', ['name' => $data['name']]);
  59. }
  60. public function logout()
  61. {
  62. try {
  63. JWTAuth::parseToken()->invalidate();
  64. } catch (Exception $e) {
  65. }
  66. }
  67. protected function respondWithToken($token): array
  68. {
  69. return [
  70. 'token' => $token,
  71. 'token_type' => 'Bearer',
  72. 'expires_in' => JWTAuth::factory()->getTTL() * 60
  73. ];
  74. }
  75. }