AuthService.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Services;
  3. use App\Http\Api\UserApi;
  4. use App\Http\Api\AiAssistantApi;
  5. use Illuminate\Http\Request;
  6. use Firebase\JWT\JWT;
  7. use Firebase\JWT\Key;
  8. class AuthService
  9. {
  10. public static function getUserToken(string $userUid)
  11. {
  12. $user = UserApi::getByUuid($userUid);
  13. if (!$user) {
  14. $user = AiAssistantApi::getByUuid($userUid);
  15. }
  16. if ($user) {
  17. $ExpTime = time() + 60 * 60 * 24 * 365;
  18. $key = self::getJwtKey();
  19. $payload = [
  20. 'nbf' => time(),
  21. 'exp' => $ExpTime,
  22. 'uid' => $user['id'],
  23. 'id' => $user['sn'],
  24. ];
  25. $jwt = JWT::encode($payload, $key, 'HS512');
  26. return $jwt;
  27. }
  28. return null;
  29. }
  30. public static function getJwtKey()
  31. {
  32. return config('mint.app.jwt_secrets_key');
  33. }
  34. public static function getToken(Request $request)
  35. {
  36. $token = $request->bearerToken();
  37. return $token;
  38. }
  39. public static function current(Request $request)
  40. {
  41. $token = $request->bearerToken();
  42. if ($token) {
  43. try {
  44. $jwt = JWT::decode($token, new Key(self::getJwtKey(), 'HS512'));
  45. } catch (\Exception $e) {
  46. return false;
  47. }
  48. if ($jwt->exp < time()) {
  49. //过期
  50. return false;
  51. } else {
  52. //有效的token
  53. return ['user_uid' => $jwt->uid, 'user_id' => $jwt->id];
  54. }
  55. } else if (isset($_COOKIE['user_uid'])) {
  56. return [
  57. 'user_uid' => $_COOKIE['user_uid'],
  58. 'user_id' => $_COOKIE['user_id']
  59. ];
  60. } else {
  61. return false;
  62. }
  63. }
  64. }