StaffAuth.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. <?php
  2. namespace addons\qingdongams\library;
  3. use addons\qingdongams\model\Staff;
  4. use addons\qingdongams\library\Token;
  5. use app\common\model\User;
  6. use fast\Random;
  7. use think\Config;
  8. use think\Db;
  9. use think\Exception;
  10. use think\Hook;
  11. use think\Request;
  12. use think\Validate;
  13. class StaffAuth {
  14. protected static $instance = null;
  15. protected $_error = '';
  16. protected $_logined = false;
  17. protected $_user = null;
  18. protected $_token = '';
  19. //Token默认有效时长
  20. protected $keeptime = 86400*30;
  21. protected $requestUri = '';
  22. protected $rules = [];
  23. //默认配置
  24. protected $config = [];
  25. protected $options = [];
  26. protected $allowFields = ['id', 'name', 'username', 'nickname', 'department_id','mobile', 'img', 'num','role','parent_id','group_ids'];
  27. public function __construct($options = []) {
  28. if ($config = Config::get('user')) {
  29. $this->config = array_merge($this->config, $config);
  30. }
  31. $this->options = array_merge($this->config, $options);
  32. }
  33. /**
  34. * @param array $options 参数
  35. * @return Auth
  36. */
  37. public static function instance($options = []) {
  38. if (is_null(self::$instance)) {
  39. self::$instance = new static($options);
  40. }
  41. return self::$instance;
  42. }
  43. /**
  44. * 获取User模型
  45. * @return User
  46. */
  47. public function getUser() {
  48. return $this->_user;
  49. }
  50. /**
  51. * 兼容调用user模型的属性
  52. * @param string $name
  53. * @return mixed
  54. */
  55. public function __get($name) {
  56. return $this->_user ? $this->_user->$name : null;
  57. }
  58. /**
  59. * 根据Token初始化
  60. * @param string $token Token
  61. * @return boolean
  62. */
  63. public function init($token) {
  64. if ($this->_logined) {
  65. return true;
  66. }
  67. if ($this->_error) {
  68. return false;
  69. }
  70. $data = Token::get($token,false,$this->options);
  71. if (!$data) {
  72. return false;
  73. }
  74. $login_id = trim($data['login_id']);
  75. $login_id = intval(substr($login_id, 5));
  76. if ($login_id) {
  77. $staff = Staff::get($login_id);
  78. if (!$staff) {
  79. $this->setError('Account not exist');
  80. return false;
  81. }
  82. $this->_user = $staff;
  83. $this->_logined = true;
  84. $this->_token = $token;
  85. //初始化成功的事件
  86. Hook::listen("user_init_successed", $this->_user);
  87. return true;
  88. } else {
  89. $this->setError('You are not logged in');
  90. return false;
  91. }
  92. }
  93. /**
  94. * 用户登录
  95. *
  96. * @param string $account 账号,用户名、邮箱、手机号
  97. * @param string $password 密码
  98. * @return boolean
  99. */
  100. public function login($account, $password)
  101. {
  102. $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'mobile');
  103. $staff = Staff::get([$field => $account]);
  104. if (!$staff) {
  105. $this->setError('Account is incorrect');
  106. return false;
  107. }
  108. if ($staff->status != 1) {
  109. $this->setError('Account is locked');
  110. return false;
  111. }
  112. if ($staff->password != $this->getEncryptPassword($password, $staff->salt)) {
  113. $this->setError('Password is incorrect');
  114. return false;
  115. }
  116. //直接登录会员
  117. $this->direct($staff->id);
  118. return true;
  119. }
  120. /**
  121. * 注册用户
  122. * @param string $nickname 用户名
  123. * @param string $mobile 手机号
  124. * @param array $extend 扩展参数
  125. * @return boolean
  126. */
  127. public function register($nickname, $mobile = '', $extend = []) {
  128. $data = [
  129. 'nickname' => $nickname,
  130. 'mobile' => $mobile,
  131. ];
  132. $params = array_merge($data, [
  133. 'status' => 1
  134. ]);
  135. $params = array_merge($params, $extend);
  136. //账号注册时需要开启事务,避免出现垃圾数据
  137. Db::startTrans();
  138. try {
  139. $staff = Staff::create($params, true);
  140. $this->_user = Staff::get($staff->id);
  141. //设置Token
  142. $this->_token = Random::uuid();
  143. Token::set($this->_token, 'staff' . $staff->id, $this->keeptime, $this->options);
  144. //设置登录状态
  145. $this->_logined = true;
  146. //注册成功的事件
  147. Hook::listen("staff_register_successed", $this->_user, $data);
  148. Db::commit();
  149. } catch (Exception $e) {
  150. $this->setError($e->getMessage());
  151. Db::rollback();
  152. return false;
  153. }
  154. return true;
  155. }
  156. /**
  157. * 直接登录账号
  158. * @param int $staff_id
  159. * @return boolean
  160. */
  161. public function direct($staff_id) {
  162. $staff = Staff::get($staff_id);
  163. if ($staff) {
  164. Db::startTrans();
  165. try {
  166. $this->_user = $staff;
  167. $this->_token = Random::uuid();
  168. Token::set($this->_token, 'staff' . $staff->id, $this->keeptime,$this->options);
  169. $this->_logined = true;
  170. //登录成功的事件
  171. Hook::listen("staff_login_successed", $this->_user);
  172. Db::commit();
  173. } catch (Exception $e) {
  174. Db::rollback();
  175. $this->setError($e->getMessage());
  176. return false;
  177. }
  178. return true;
  179. } else {
  180. return false;
  181. }
  182. }
  183. /**
  184. * 退出
  185. * @return boolean
  186. */
  187. public function logout() {
  188. if (!$this->_logined) {
  189. $this->setError('You are not logged in');
  190. return false;
  191. }
  192. //设置登录标识
  193. $this->_logined = false;
  194. //删除Token
  195. Token::delete($this->_token,$this->options);
  196. //退出成功的事件
  197. Hook::listen("staff_logout_successed", $this->_user);
  198. return true;
  199. }
  200. /**
  201. * 判断是否登录
  202. * @return boolean
  203. */
  204. public function isLogin() {
  205. if ($this->_logined) {
  206. return true;
  207. }
  208. return false;
  209. }
  210. /**
  211. * 获取当前Token
  212. * @return string
  213. */
  214. public function getToken() {
  215. return $this->_token;
  216. }
  217. /**
  218. * 获取员工基本信息
  219. */
  220. public function getUserinfo() {
  221. $data = $this->_user->toArray();
  222. $allowFields = $this->getAllowFields();
  223. $userinfo = array_intersect_key($data, array_flip($allowFields));
  224. $userinfo = array_merge($userinfo, Token::get($this->_token,$this->options));
  225. $group_ids=explode(',',$userinfo['group_ids']);
  226. $userinfo['role_type'] = 1;//基础和团队
  227. if (in_array(1, $group_ids)) {//超级管理员
  228. $userinfo['role_type'] = 9;
  229. }
  230. return $userinfo;
  231. }
  232. /**
  233. * 获取当前请求的URI
  234. * @return string
  235. */
  236. public function getRequestUri() {
  237. return $this->requestUri;
  238. }
  239. /**
  240. * 设置当前请求的URI
  241. * @param string $uri
  242. */
  243. public function setRequestUri($uri) {
  244. $this->requestUri = $uri;
  245. }
  246. /**
  247. * 获取允许输出的字段
  248. * @return array
  249. */
  250. public function getAllowFields() {
  251. return $this->allowFields;
  252. }
  253. /**
  254. * 设置允许输出的字段
  255. * @param array $fields
  256. */
  257. public function setAllowFields($fields) {
  258. $this->allowFields = $fields;
  259. }
  260. /**
  261. * 获取密码加密后的字符串
  262. * @param string $password 密码
  263. * @param string $salt 密码盐
  264. * @return string
  265. */
  266. public function getEncryptPassword($password, $salt = '') {
  267. return md5(md5($password) . $salt);
  268. }
  269. /**
  270. * 检测当前控制器和方法是否匹配传递的数组
  271. * @param array $arr 需要验证权限的数组
  272. * @return boolean
  273. */
  274. public function match($arr = []) {
  275. $request = Request::instance();
  276. $arr = is_array($arr) ? $arr : explode(',', $arr);
  277. if (!$arr) {
  278. return false;
  279. }
  280. $arr = array_map('strtolower', $arr);
  281. // 是否存在
  282. if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
  283. return true;
  284. }
  285. // 没找到匹配
  286. return false;
  287. }
  288. /**
  289. * 设置会话有效时间
  290. * @param int $keeptime 默认为永久
  291. */
  292. public function keeptime($keeptime = 0) {
  293. $this->keeptime = $keeptime;
  294. }
  295. /**
  296. * 设置错误信息
  297. * @param $error 错误信息
  298. * @return Auth
  299. */
  300. public function setError($error) {
  301. $this->_error = $error;
  302. return $this;
  303. }
  304. /**
  305. * 获取错误信息
  306. * @return string
  307. */
  308. public function getError() {
  309. return $this->_error ? __($this->_error) : '';
  310. }
  311. /**
  312. * 修改密码
  313. * @param string $newpassword 新密码
  314. * @param string $oldpassword 旧密码
  315. * @param bool $ignoreoldpassword 忽略旧密码
  316. * @return boolean
  317. */
  318. public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
  319. {
  320. if (!$this->_logined) {
  321. $this->setError('你当前还未登录');
  322. return false;
  323. }
  324. //判断旧密码是否正确
  325. if ($this->_user->password == $this->getEncryptPassword($oldpassword, $this->_user->salt) || $ignoreoldpassword) {
  326. Db::startTrans();
  327. try {
  328. $salt = Random::alnum();
  329. $newpassword = $this->getEncryptPassword($newpassword, $salt);
  330. Staff::where(['id'=>$this->_user->id])->update([
  331. 'password' => $newpassword,
  332. 'salt' => $salt,
  333. ]);
  334. Token::delete($this->_token);
  335. //修改密码成功的事件
  336. Db::commit();
  337. } catch (Exception $e) {
  338. Db::rollback();
  339. $this->setError($e->getMessage());
  340. return false;
  341. }
  342. return true;
  343. } else {
  344. $this->setError('旧密码不正确');
  345. return false;
  346. }
  347. }
  348. }