ApiAuthService.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\api\service\auth;
  4. use app\api\service\auth\Adapter;
  5. use think\facade\Cache;
  6. use app\common\model\User;
  7. use app\common\model\UserToken;
  8. use think\facade\Config;
  9. class ApiAuthService
  10. {
  11. protected $allowFields = ['id', 'nickname', 'mobile', 'avatar', 'balance', 'score'];
  12. public function login(string $username, string $password)
  13. {
  14. $token=uuid();
  15. $user=User::where('username',$username)->find();
  16. if(!$user){
  17. throw new \Exception('账号或密码错误');
  18. }
  19. if($user->password!=md5(md5($password.$user->salt))){
  20. throw new \Exception('账号或密码错误');
  21. }
  22. if($user->status!='normal'){
  23. throw new \Exception('账号已经被禁用');
  24. }
  25. //刷新token
  26. $token = MysqlAdapter::login($token, $user);
  27. $user->loginfailure = 0;
  28. $user->logintime = time();
  29. $user->loginip = request()->ip();
  30. $user->save();
  31. Cache::store('redis')->set('user_info_'.$user->id, $user->toArray(), Config::get('app.user_login.keepalive_time'));
  32. return ['userinfo'=>$user,'token'=>$token];
  33. }
  34. public function updateToken(int $uid, array $arr)
  35. {
  36. return UserToken::where('user_id', $uid)->update($arr);
  37. }
  38. }