1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- <?php
- /**
- * @Name
- * @Description
- * @Author 刘学玺
- * @Date 2023/11/24 12:25
- */
- namespace App\Http\Services\Admin;
- use App\Exceptions\ApiException;
- use App\Exceptions\Code;
- use App\Exceptions\Message;
- use App\Http\Services\BaseService;
- use Exception;
- use Illuminate\Contracts\Routing\ResponseFactory;
- use Illuminate\Foundation\Application;
- use Illuminate\Http\Response;
- use Illuminate\Support\Facades\Config;
- use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
- use Tymon\JWTAuth\Facades\JWTAuth;
- class TokenService extends BaseService
- {
- public function __construct()
- {
- Config::set('auth.defaults.guard', 'admin');
- // Config::set('jwt.ttl',60);
- }
- public function setToken($data)
- {
- if (!$token = JWTAuth::attempt($data)) {
- $this->apiError('token生成失败');
- }
- return $this->respondWithToken($token);
- }
- /**
- * Notes : 刷新Token
- * Method : Interface refreshToken
- * @return \Illuminate\Contracts\Foundation\Application|ResponseFactory|Application|Response
- * @throws ApiException
- */
- public function refreshToken(): Application|Response|\Illuminate\Contracts\Foundation\Application|ResponseFactory
- {
- try {
- $oldToken = JWTAuth::getToken();
- $token = JWTAuth::refresh($oldToken);
- } catch (TokenBlacklistedException $e) {
- // token加入黑名单
- throw new ApiException(['code' => Code::TOKEN_ERROR_BLACK, 'message' => Message::TOKEN_ERROR_BLACK]);
- }
- return $this->apiSuccess('', $this->respondWithToken($token));
- }
- public function user(): object
- {
- return JWTAuth::parseToken()->touser();
- }
- public function info()
- {
- $data = $this->user();
- return $this->apiSuccess('', ['name' => $data['name']]);
- }
- public function logout()
- {
- try {
- JWTAuth::parseToken()->invalidate();
- } catch (Exception $e) {
- }
- }
- protected function respondWithToken($token): array
- {
- return [
- 'token' => $token,
- 'token_type' => 'Bearer',
- 'expires_in' => JWTAuth::factory()->getTTL() * 60
- ];
- }
- }
|