1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <?php
- /**
- * @Name
- * @Description
- * @Author 刘学玺
- * @Date 2024/8/23 10:16
- */
- namespace App\Http\Services\Backend\Server\System;
- use App\Enums\Common\Status;
- use App\Enums\System\Login\LogType;
- use App\Exceptions\ApiException;
- use App\Http\Services\Service;
- use App\Models\System\User;
- use BadMethodCallException;
- use Exception;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\Hash;
- use Illuminate\Support\Str;
- use Illuminate\Validation\ValidationException;
- use Symfony\Component\HttpFoundation\Response;
- class AuthService extends Service
- {
- /**
- * @throws ApiException
- */
- public function login($request)
- {
- // 校验验证码
- // validateCaptcha($data)
- // $verifyCodeResult = (new SmsService())->verifyCode($mobile, intval($code));
- // if(!$verifyCodeResult) return $this->fail('验证码错误!', 400);
- // 使用账号密码,进行登录
- $user = $this->authenticate($request);;
- // 创建 Token 令牌,记录登录日志
- return $this->createTokenAfterLoginSuccess($user, LogType::LOGIN_USERNAME);
- }
- /**
- * @throws ApiException
- */
- protected function authenticate($request)
- {
- $request->authenticate();
- // 校验是否禁用
- $user = $request->user();
- if ($user->status === Status::DISABLE) {
- //createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.USER_DISABLED);
- $this->error('AUTH_LOGIN_USER_DISABLED');
- }
- return $user;
- }
- /**
- * @throws ApiException
- */
- protected function createTokenAfterLoginSuccess($user, $logType)
- {
- // $password = Hash::make($user['password']);
- // $IsExistUser = User::query()->where('username',$user['name'])->where('password', $password)->exists();
- // if(!$IsExistUser){
- // //日志
- // //登录次数限制
- // $this->error('账号密码错误', 401);
- // }
- // 清理token历史
- $user->tokens()->where('tokenable_type', $user::class)->where('name', $user->name)->delete();
- $tokenResult = $user->createToken($user->name);
- $token = $tokenResult->plainTextToken;
- !$token && $this->error('授权错误', 401);
- // 设置refreshToken
- // $token->refreshToken = Str::random(40);
- // $token->save();
- // $tokenResult->last_used_at = time();
- // $tokenResult->save();
- $user->last_activity_at = time();
- $user->ip_address = request()->getClientIp();
- $user->save();
- // id: number // 编号
- // accessToken: string // 访问令牌
- // refreshToken: string // 刷新令牌
- // userId: number // 用户编号
- // userType: number //用户类型
- // clientId: string //客户端编号
- // expiresTime: number //过期时间
- return ['userId' => $user->id, 'userType' => 1, 'accessToken' => $token,'refreshToken' => $token];
- }
- }
|