123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- <?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\Requests\Backend\Server\System\AuthRequest;
- 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)
- {
- // $params = $request->safe(['username','password']);
- // 校验验证码
- // 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
- * @throws ValidationException
- */
- protected function authenticate(AuthRequest $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->username)->delete();
- $tokenResult = $user->createToken($user->username);
- $token = $tokenResult->plainTextToken;
- !$token && $this->error('授权错误', 401);
- // 设置refreshToken
- // $token->refreshToken = Str::random(40);
- // $token->save();
- // $tokenResult->last_used_at = time();
- // $tokenResult->save();
- $user->login_date = time();
- $user->login_ip = 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];
- }
- }
|