MysqlAdapter.php 2.3 KB

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