MysqlAdapter.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\api\service\auth;
  4. use think\facade\Cache;
  5. use app\common\model\UserToken;
  6. use app\common\model\User;
  7. use think\facade\Config;
  8. class MysqlAdapter
  9. {
  10. private UserToken $usertoken;
  11. public function ddddd()
  12. {
  13. $time=time();
  14. $usertoken=UserToken::where(function ($query) use ($token,$time){
  15. $token=md5($token);
  16. $query->where('token','=',$token);
  17. $query->where('expire','>',$time);
  18. })->withJoin('user','right')->find();
  19. if($usertoken){
  20. $auth=Config::get('site.auth');
  21. //当登陆时间小于保持登陆时间的一半时,自动续时
  22. if($auth['keepalive'] && $usertoken->expire-$time<$auth['keepalive_time']/2){
  23. $usertoken->expire=$time+$auth['keepalive_time'];
  24. $usertoken->save();
  25. }
  26. $usertoken->token=$token;
  27. $this->usertoken=$usertoken;
  28. }
  29. }
  30. public static function userinfo(string $token):int
  31. {
  32. return UserToken::where('token',$token)->where('expire','>', time())->value('user_id');
  33. }
  34. public static function getUserToken($token):bool
  35. {
  36. return boolval(UserToken::where('token',$token)->where('expire','>', time())->order('id','asc')->count());
  37. }
  38. public static function login(string $token,User $user)
  39. {
  40. $keepalive_time=Config::get('app.user_login.keepalive_time');
  41. $token = md5($token);
  42. UserToken::create([
  43. 'token'=> $token ,
  44. 'user_id'=>$user->id,
  45. 'expire'=>time()+$keepalive_time
  46. ]);
  47. $allow_device_num=Config::get('app.user_login.allow_device_num');
  48. //如果数据库中保存的设备数大于允许的设备数,如果超出则挤出去最早登陆的设备
  49. $time=time();
  50. $count=UserToken::where('user_id',$user->id)->where('expire','>',$time)->count();
  51. if($count>$allow_device_num){
  52. $usertoken=UserToken::where('user_id',$user->id)->where('expire','>',$time)->order('id','asc')->find();
  53. $usertoken->delete();
  54. }
  55. return $token ;
  56. }
  57. public function logout()
  58. {
  59. UserToken::where('token',$this->usertoken->token)->delete();
  60. }
  61. }