ApiAuthService.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\api\service;
  4. use think\facade\Cookie;
  5. use app\api\service\auth\MysqlAdapter;
  6. use app\common\model\User;
  7. use app\common\model\UserToken;
  8. use app\common\service\AuthService;
  9. class ApiAuthService extends AuthService
  10. {
  11. protected $allowFields = ['id', 'nickname', 'mobile', 'avatar', 'balance', 'score'];
  12. public function userinfo(bool $allinfo = false)
  13. {
  14. $time=time();
  15. $token = Cookie::get('token');
  16. if(!$token){
  17. return false;
  18. }
  19. $user = UserToken::where('token',$token)->where('expire','>',$time)->field('mobile')->value('user_id');
  20. return $user?User::where('id',$user)->field($this->allowFields)->find()->toArray():false;
  21. }
  22. public function logout()
  23. {
  24. $adapter = new MysqlAdapter();
  25. $adapter->logout();
  26. }
  27. public static function getToken($token):int
  28. {
  29. $time=time();
  30. return UserToken::where('token',$token)->where('expire','>',$time)->count();
  31. }
  32. //登录
  33. public function login(string $username, string $password)
  34. {
  35. $token= uuid();
  36. $user=User::where('username',$username)->find();
  37. if(!$user){
  38. throw new \Exception('账号或密码错误');
  39. }
  40. if($user->password!=md5(md5($password.$user->salt))){
  41. throw new \Exception('账号或密码错误');
  42. }
  43. if($user->status!='normal'){
  44. throw new \Exception('账号已经被禁用');
  45. }
  46. $adapter = new MysqlAdapter();
  47. $token = $adapter->login($token,$user);
  48. $this->login_user=$adapter->userinfo();
  49. return ['userinfo' => $this->login_user, 'token' => $token];
  50. }
  51. public function loginByMobile(string $mobile, string $code)
  52. {
  53. // TODO: Implement loginByMobile() method.
  54. }
  55. public function updateToken(array $arr)
  56. {
  57. $usertoken=$this->adapter->getUserToken();
  58. UserToken::where('id',$usertoken->id)->update($arr);
  59. }
  60. }