MysqlAdapter.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 static function userinfo(string $token):int
  12. {
  13. return UserToken::where('token',$token)->where('expire','>', time())->value('user_id');
  14. }
  15. public static function getUserToken($token):bool
  16. {
  17. return boolval(UserToken::where('token',$token)->where('expire','>', time())->order('id','asc')->count());
  18. }
  19. public static function login(string $token,User $user)
  20. {
  21. $keepalive_time=Config::get('app.user_login.keepalive_time');
  22. $token = md5($token);
  23. UserToken::create([
  24. 'token'=> $token ,
  25. 'user_id'=>$user->id,
  26. 'expire'=>time()+$keepalive_time
  27. ]);
  28. $allow_device_num=Config::get('app.user_login.allow_device_num');
  29. //如果数据库中保存的设备数大于允许的设备数,如果超出则挤出去最早登陆的设备
  30. $time=time();
  31. $count=UserToken::where('user_id',$user->id)->where('expire','>',$time)->count();
  32. if($count>$allow_device_num){
  33. $usertoken=UserToken::where('user_id',$user->id)->where('expire','>',$time)->order('id','asc')->find();
  34. $usertoken->delete();
  35. }
  36. return $token ;
  37. }
  38. public static function logout(int $uid)
  39. {
  40. $token = request()->header('token');
  41. UserToken::where('token', $token)->delete();
  42. Cache::store('redis')->delete('user_info_'.$uid);
  43. }
  44. }