ApiAuthService.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\api\service;
  4. use app\api\service\auth\Adapter;
  5. use app\common\model\User;
  6. use app\common\model\UserToken;
  7. use app\common\service\AuthService;
  8. class ApiAuthService extends AuthService
  9. {
  10. protected $allowFields = ['id', 'nickname', 'mobile', 'avatar', 'balance', 'score'];
  11. private Adapter $adapter;
  12. public function userinfo(bool $allinfo = false)
  13. {
  14. $user=$this->adapter->userinfo();
  15. if(!$user){
  16. return false;
  17. }
  18. if($allinfo){
  19. return $user;
  20. }else{
  21. return array_intersect_key($user,array_flip($this->allowFields));
  22. }
  23. }
  24. public function logout()
  25. {
  26. $this->adapter->logout();
  27. }
  28. public function getToken()
  29. {
  30. $usertoken=$this->adapter->getUserToken();
  31. return $usertoken->token;
  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. $this->adapter->login($token,$user);
  47. $this->login_user=$this->adapter->userinfo();
  48. }
  49. public function loginByMobile(string $mobile, string $code)
  50. {
  51. // TODO: Implement loginByMobile() method.
  52. }
  53. public function updateToken(array $arr)
  54. {
  55. $usertoken=$this->adapter->getUserToken();
  56. UserToken::where('id',$usertoken->id)->update($arr);
  57. }
  58. }