SystemBadmin.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace app\models\system;
  3. use crmeb\services\CacheService;
  4. use crmeb\traits\JwtAuthModelTrait;
  5. use crmeb\traits\ModelTrait;
  6. use crmeb\basic\BaseModel;
  7. use Psr\SimpleCache\InvalidArgumentException;
  8. use think\facade\Cache;
  9. /**
  10. * Class SystemAdmin
  11. * @package app\models\system
  12. */
  13. class SystemBadmin extends BaseModel
  14. {
  15. /**
  16. * 数据表主键
  17. * @var string
  18. */
  19. protected $pk = 'id';
  20. /**
  21. * 模型名称
  22. * @var string
  23. */
  24. protected $name = 'system_badmin';
  25. /**
  26. * token令牌桶名
  27. * @var string
  28. */
  29. protected static $tokenPrefix = 'badmin_token';
  30. use ModelTrait;
  31. use JwtAuthModelTrait;
  32. protected $insert = ['add_time'];
  33. /**
  34. * 获取token缓存前缀
  35. * @return string
  36. */
  37. public static function getTokenPrefix()
  38. {
  39. return self::$tokenPrefix;
  40. }
  41. public static function getRolesAttr($value)
  42. {
  43. return explode(',', $value);
  44. }
  45. /**
  46. * 获取token并放入令牌桶
  47. * @param SystemAdmin $adminInfo
  48. * @param $type
  49. * @return array|bool
  50. */
  51. public static function createToken(SystemBadmin $adminInfo, string $type, array $params = [])
  52. {
  53. $tokenInfo = $adminInfo->getToken($type, $params);
  54. $exp = (int)bcadd($tokenInfo['params']['exp'] - $tokenInfo['params']['iat'], 60, 0);
  55. $res = CacheService::setTokenBucket($tokenInfo['token'], ['token' => $tokenInfo['token'], 'exp' => $exp], (int)$exp);
  56. if (!$res) return self::setErrorInfo('保存token失败');
  57. return $tokenInfo;
  58. }
  59. /**
  60. * 从令牌桶中删除token
  61. * @param string $token
  62. * @return bool
  63. * @throws InvalidArgumentException
  64. */
  65. public static function delTokenBucket(string $token)
  66. {
  67. if (Cache::has($token)) {
  68. return Cache::delete($token);
  69. }
  70. return true;
  71. }
  72. /**
  73. * 用户登陆
  74. * @param $account
  75. * @param $pwd
  76. * @return bool|SystemBadmin
  77. */
  78. public static function login($account, $pwd)
  79. {
  80. $adminInfo = self::get(compact('account'));
  81. if (!$adminInfo) return self::setErrorInfo('登陆的账号不存在!');
  82. if (!password_verify($pwd, $adminInfo['pwd'])) return self::setErrorInfo('账号或密码错误,请重新输入');
  83. if (!$adminInfo['status']) return self::setErrorInfo('该账号已被关闭!');
  84. event('SystemBAdminLoginAfter', [$adminInfo]);
  85. return $adminInfo;
  86. }
  87. }