LoginService.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace app\api\service;
  3. use app\BaseService;
  4. use app\common\model\AdminModel;
  5. use app\common\model\AuthGroupAccessModel;
  6. use app\common\model\AuthGroupModel;
  7. use app\common\model\StoreModel;
  8. use think\facade\Cache;
  9. class LoginService extends BaseService
  10. {
  11. private $model;
  12. private $storeModel;
  13. private $groupModel;
  14. private $groupAccessModel;
  15. public function __construct()
  16. {
  17. $this->model = new AdminModel();
  18. $this->groupModel = new AuthGroupModel();
  19. $this->storeModel = new StoreModel();
  20. $this->groupAccessModel = new AuthGroupAccessModel();
  21. }
  22. public function loadByLogin($username, $password) {
  23. $admin = $this->model->loadByLogin($username,$password);
  24. if (!$admin)
  25. return $this->fail(lang('The account password is incorrect'));
  26. $access = $this->groupAccessModel->findByAdminId($admin->id);
  27. if (!$access)
  28. return $this->fail(lang('Background permission is not set'));
  29. $group = $this->groupModel->findById($access->group_id);
  30. if (!$group)
  31. return $this->fail(lang('The role group does not exist'));
  32. $stores = $this->storeModel->findByIds($admin->store_ids ? explode(',', $admin->store_ids) : []);
  33. $admin['group'] = $group;
  34. $admin['stores'] = $stores;
  35. $token = \Jwt::getToken([
  36. 'iss'=>'jwt_user', //该JWT的签发者
  37. 'iat'=>time(), //签发时间
  38. 'exp'=>time()+7200*7, //过期时间
  39. 'nbf'=>time(), //该时间之前不接收处理该Token
  40. 'jti'=>md5(uniqid('JWT').time()), //该Token唯一标识
  41. 'admin_id' => $admin->id,
  42. 'account' => $admin->account,
  43. 'nickname' => $admin->nickname,
  44. 'group_id' => $group->id,
  45. 'group_name' => $group->name,
  46. ]);
  47. if($token === false) return $this->fail(lang('Failed to obtain token'));
  48. $admin->token = $token;
  49. // $redis = Cache::store('redis')->handler(); //返回句柄对象,可执行其它高级方法
  50. // $sadd = $redis->sadd('user:infos', $token);
  51. $refreshToken = $this->model->refreshToken($admin->id, $token);
  52. return $refreshToken ? $this->ok($admin) : $this->fail("Fail");
  53. }
  54. }