LoginService.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. if(count($stores) == 0) return $this->fail("该员工未绑定门店信息");
  34. unset($admin['password']);
  35. $admin['group'] = $group;
  36. $admin['stores'] = $stores;
  37. $token = \Jwt::getToken([
  38. 'iss'=>'jwt_user', //该JWT的签发者
  39. 'iat'=>time(), //签发时间
  40. 'exp'=>time()+7200*7, //过期时间
  41. 'nbf'=>time(), //该时间之前不接收处理该Token
  42. 'jti'=>md5(uniqid('JWT').time()), //该Token唯一标识
  43. 'admin_id' => $admin->id,
  44. 'account' => $admin->account,
  45. 'nickname' => $admin->nickname,
  46. 'group_id' => $group->id,
  47. 'group_name' => $group->name,
  48. ]);
  49. if($token === false) return $this->fail(lang('Failed to obtain token'));
  50. $admin->token = $token;
  51. // $redis = Cache::store('redis')->handler(); //返回句柄对象,可执行其它高级方法
  52. // $sadd = $redis->sadd('user:infos', $token);
  53. $refreshToken = $this->model->refreshToken($admin->id, $token);
  54. return $refreshToken ? $this->ok($admin) : $this->fail("Fail");
  55. }
  56. }