LoginLogic.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeadmin快速开发前后端分离管理后台(PHP版)
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
  8. // | github下载:https://github.com/likeshop-github/likeadmin
  9. // | 访问官网:https://www.likeadmin.cn
  10. // | likeadmin团队 版权所有 拥有最终解释权
  11. // +----------------------------------------------------------------------
  12. // | author: likeadminTeam
  13. // +----------------------------------------------------------------------
  14. namespace app\api\logic;
  15. use app\common\cache\WebScanLoginCache;
  16. use app\common\logic\BaseLogic;
  17. use app\api\service\{UserTokenService, WechatUserService};
  18. use app\common\enum\{LoginEnum, user\UserTerminalEnum, YesNoEnum};
  19. use app\common\service\{
  20. ConfigService,
  21. FileService,
  22. wechat\WeChatConfigService,
  23. wechat\WeChatMnpService,
  24. wechat\WeChatOaService,
  25. wechat\WeChatRequestService
  26. };
  27. use app\common\model\user\{User, UserAuth};
  28. use think\facade\{Db, Config};
  29. /**
  30. * 登录逻辑
  31. * Class LoginLogic
  32. * @package app\api\logic
  33. */
  34. class LoginLogic extends BaseLogic
  35. {
  36. /**
  37. * @param array $params
  38. * @return User|\think\Model
  39. * @throws \think\db\exception\DataNotFoundException
  40. * @throws \think\db\exception\DbException
  41. * @throws \think\db\exception\ModelNotFoundException
  42. */
  43. public static function register(array $params)
  44. {
  45. $userSn = User::createUserSn();
  46. $params['password'] = !empty($params['password'])?$params['password']:rand(100000,999999);
  47. $passwordSalt = Config::get('project.unique_identification');
  48. $password = create_password($params['password'], $passwordSalt);
  49. $avatar = ConfigService::get('default_image', 'user_avatar');
  50. $user = User::create([
  51. 'sn' => $userSn,
  52. 'avatar' => $avatar,
  53. 'nickname' => '用户' . $userSn,
  54. 'account' => $params['account'],
  55. 'mobile' => !empty($params['mobile'])?$params['mobile']:'',
  56. 'password' => $password,
  57. 'channel' => $params['channel'],
  58. 'user_type' => $params['user_type']??0,
  59. ]);
  60. return $user;
  61. }
  62. /**
  63. * @notes 账号/手机号登录,手机号验证码
  64. * @param $params
  65. * @return array|false
  66. * @author 段誉
  67. * @date 2022/9/6 19:26
  68. */
  69. public static function login($params)
  70. {
  71. try {
  72. // 账号/手机号 密码登录
  73. $where = ['account|mobile' => $params['account']];
  74. if ($params['scene'] == LoginEnum::MOBILE_CAPTCHA) {
  75. //手机验证码登录
  76. $where = ['mobile' => $params['account']];
  77. $params['mobile'] = $params['account'];
  78. }
  79. $user = User::where($where)->findOrEmpty();
  80. if ($user->isEmpty()) {
  81. //直接注册用户
  82. $params['channel'] = $params['terminal'];
  83. $user = self::register($params);
  84. }
  85. //更新登录信息
  86. $user->login_time = time();
  87. $user->login_ip = request()->ip();
  88. $user->save();
  89. //设置token
  90. $userInfo = UserTokenService::setToken($user->id, $params['terminal']);
  91. //返回登录信息
  92. $avatar = $user->avatar ?: Config::get('project.default_image.user_avatar');
  93. $avatar = FileService::getFileUrl($avatar);
  94. return [
  95. 'nickname' => $userInfo['nickname'],
  96. 'sn' => $userInfo['sn'],
  97. 'mobile' => $userInfo['mobile'],
  98. 'avatar' => $avatar,
  99. 'token' => $userInfo['token'],
  100. 'user_type'=>$userInfo['user_type']
  101. ];
  102. } catch (\Exception $e) {
  103. self::setError($e->getMessage());
  104. return false;
  105. }
  106. }
  107. /**
  108. * @notes 退出登录
  109. * @param $userInfo
  110. * @return bool
  111. * @throws \think\db\exception\DataNotFoundException
  112. * @throws \think\db\exception\DbException
  113. * @throws \think\db\exception\ModelNotFoundException
  114. * @author 段誉
  115. * @date 2022/9/16 17:56
  116. */
  117. public static function logout($userInfo)
  118. {
  119. //token不存在,不注销
  120. if (!isset($userInfo['token'])) {
  121. return false;
  122. }
  123. //设置token过期
  124. return UserTokenService::expireToken($userInfo['token']);
  125. }
  126. /**
  127. * @notes 获取微信请求code的链接
  128. * @param string $url
  129. * @return string
  130. * @author 段誉
  131. * @date 2022/9/20 19:47
  132. */
  133. public static function codeUrl(string $url)
  134. {
  135. return (new WeChatOaService())->getCodeUrl($url);
  136. }
  137. /**
  138. * @notes 公众号登录
  139. * @param array $params
  140. * @return array|false
  141. * @throws \GuzzleHttp\Exception\GuzzleException
  142. * @author 段誉
  143. * @date 2022/9/20 19:47
  144. */
  145. public static function oaLogin(array $params)
  146. {
  147. Db::startTrans();
  148. try {
  149. //通过code获取微信 openid
  150. $response = (new WeChatOaService())->getOaResByCode($params['code']);
  151. $userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_OA);
  152. $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
  153. // 更新登录信息
  154. self::updateLoginInfo($userInfo['id']);
  155. Db::commit();
  156. return $userInfo;
  157. } catch (\Exception $e) {
  158. Db::rollback();
  159. self::$error = $e->getMessage();
  160. return false;
  161. }
  162. }
  163. /**
  164. * @notes 小程序-静默登录
  165. * @param array $params
  166. * @return array|false
  167. * @author 段誉
  168. * @date 2022/9/20 19:47
  169. */
  170. public static function silentLogin(array $params)
  171. {
  172. try {
  173. //通过code获取微信 openid
  174. $response = (new WeChatMnpService())->getMnpResByCode($params['code']);
  175. $userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_MMP);
  176. $userInfo = $userServer->getResopnseByUserInfo('silent')->getUserInfo();
  177. if (!empty($userInfo)) {
  178. // 更新登录信息
  179. self::updateLoginInfo($userInfo['id']);
  180. }
  181. return $userInfo;
  182. } catch (\Exception $e) {
  183. self::$error = $e->getMessage();
  184. return false;
  185. }
  186. }
  187. /**
  188. * @notes 小程序-授权登录
  189. * @param array $params
  190. * @return array|false
  191. * @author 段誉
  192. * @date 2022/9/20 19:47
  193. */
  194. public static function mnpLogin(array $params)
  195. {
  196. Db::startTrans();
  197. try {
  198. //通过code获取微信 openid
  199. $response = (new WeChatMnpService())->getMnpResByCode($params['code']);
  200. $userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_MMP);
  201. $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
  202. // 更新登录信息
  203. self::updateLoginInfo($userInfo['id']);
  204. Db::commit();
  205. return $userInfo;
  206. } catch (\Exception $e) {
  207. Db::rollback();
  208. self::$error = $e->getMessage();
  209. return false;
  210. }
  211. }
  212. /**
  213. * @param array $params
  214. * @return array|false
  215. *
  216. */
  217. public static function mnpSessionKey(array $params)
  218. {
  219. Db::startTrans();
  220. try {
  221. //通过code获取微信 openid
  222. $response = (new WeChatMnpService())->getMnpResByCode($params['code']);
  223. Db::commit();
  224. return $response;
  225. } catch (\Exception $e) {
  226. Db::rollback();
  227. self::$error = $e->getMessage();
  228. return false;
  229. }
  230. }
  231. /**
  232. * @notes 小程序-手机号授权一键登录
  233. * @param $params
  234. * @return array
  235. * @author 段誉
  236. * @date 2022/9/6 19:26
  237. */
  238. public static function mnpPhoneLogin(array $params)
  239. {
  240. try {
  241. $where = ['mobile' => $params['mobile']];
  242. $params['account'] = $params['mobile'];
  243. $user = User::where($where)->findOrEmpty();
  244. //先检查openid是否有记录
  245. $isAuth = UserAuth::where('openid', '=', $params['openid'])->findOrEmpty();
  246. if (!$isAuth->isEmpty() && !$user->isEmpty()) {
  247. $authUser = UserAuth::where('user_id', '=', $user['id'])->findOrEmpty();
  248. if($isAuth->user_id != $authUser->user_id) {
  249. throw new \Exception('该微信已被绑定');
  250. }
  251. }
  252. if ($user->isEmpty()) {
  253. //直接注册用户
  254. $params['channel'] = 1;
  255. $user = self::register($params);
  256. }
  257. //更新登录信息
  258. $user->login_time = time();
  259. $user->login_ip = request()->ip();
  260. $user->save();
  261. if($isAuth->isEmpty()){
  262. UserAuth::create([
  263. 'user_id' => $user->id,
  264. 'openid' => $params['openid'],
  265. 'unionid' => $params['unionid'] ?? '',
  266. 'terminal' => 1,
  267. ]);
  268. }
  269. if(!$isAuth->isEmpty() && $isAuth->user_id==0){
  270. $isAuth->user_id = $user->id;
  271. $isAuth->save();
  272. }
  273. $userInfo = UserTokenService::setToken($user->id, 1);
  274. //返回登录信息
  275. $avatar = $user->avatar ?: Config::get('project.default_image.user_avatar');
  276. $avatar = FileService::getFileUrl($avatar);
  277. return [
  278. 'nickname' => $userInfo['nickname'],
  279. 'sn' => $userInfo['sn'],
  280. 'mobile' => $userInfo['mobile'],
  281. 'avatar' => $avatar,
  282. 'token' => $userInfo['token'],
  283. ];
  284. } catch (\Exception $e) {
  285. self::setError($e->getMessage());
  286. return [];
  287. }
  288. }
  289. /**
  290. * @notes 更新登录信息
  291. * @param $userId
  292. * @throws \Exception
  293. * @author 段誉
  294. * @date 2022/9/20 19:46
  295. */
  296. public static function updateLoginInfo($userId)
  297. {
  298. $user = User::findOrEmpty($userId);
  299. if ($user->isEmpty()) {
  300. throw new \Exception('用户不存在');
  301. }
  302. $time = time();
  303. $user->login_time = $time;
  304. $user->login_ip = request()->ip();
  305. $user->update_time = $time;
  306. $user->save();
  307. }
  308. /**
  309. * @notes 小程序端绑定微信
  310. * @param array $params
  311. * @return bool
  312. * @author 段誉
  313. * @date 2022/9/20 19:46
  314. */
  315. public static function mnpAuthLogin(array $params)
  316. {
  317. try {
  318. //通过code获取微信openid
  319. $response = (new WeChatMnpService())->getMnpResByCode($params['code']);
  320. $response['user_id'] = $params['user_id'];
  321. $response['terminal'] = UserTerminalEnum::WECHAT_MMP;
  322. return self::createAuth($response);
  323. } catch (\Exception $e) {
  324. self::$error = $e->getMessage();
  325. return false;
  326. }
  327. }
  328. /**
  329. * @notes 公众号端绑定微信
  330. * @param array $params
  331. * @return bool
  332. * @throws \GuzzleHttp\Exception\GuzzleException
  333. * @author 段誉
  334. * @date 2022/9/16 10:43
  335. */
  336. public static function oaAuthLogin(array $params)
  337. {
  338. try {
  339. //通过code获取微信openid
  340. $response = (new WeChatOaService())->getOaResByCode($params['code']);
  341. $response['user_id'] = $params['user_id'];
  342. $response['terminal'] = UserTerminalEnum::WECHAT_OA;
  343. return self::createAuth($response);
  344. } catch (\Exception $e) {
  345. self::$error = $e->getMessage();
  346. return false;
  347. }
  348. }
  349. /**
  350. * @notes 生成授权记录
  351. * @param $response
  352. * @return bool
  353. * @throws \Exception
  354. * @author 段誉
  355. * @date 2022/9/16 10:43
  356. */
  357. public static function createAuth($response)
  358. {
  359. //先检查openid是否有记录
  360. $isAuth = UserAuth::where('openid', '=', $response['openid'])->findOrEmpty();
  361. if (!$isAuth->isEmpty()) {
  362. if($isAuth->user_id != $response['user_id']) {
  363. throw new \Exception('该微信已被绑定');
  364. }
  365. if($isAuth->user_id == 0) {
  366. //更新操作
  367. $isAuth->user_id = $response['user_id'];
  368. $isAuth->save();
  369. return true;
  370. }
  371. if($isAuth->user_id == $response['user_id']) {
  372. return true;
  373. }
  374. }
  375. if (isset($response['unionid']) && !empty($response['unionid'])) {
  376. //在用unionid找记录,防止生成两个账号,同个unionid的问题
  377. $userAuth = UserAuth::where(['unionid' => $response['unionid']])
  378. ->findOrEmpty();
  379. if (!$userAuth->isEmpty() && $userAuth->user_id != $response['user_id']) {
  380. throw new \Exception('该微信已被绑定');
  381. }
  382. }
  383. //如果没有授权,直接生成一条微信授权记录
  384. UserAuth::create([
  385. 'user_id' => $response['user_id'],
  386. 'openid' => $response['openid'],
  387. 'unionid' => $response['unionid'] ?? '',
  388. 'terminal' => $response['terminal'],
  389. ]);
  390. return true;
  391. }
  392. /**
  393. * @notes 获取扫码登录地址
  394. * @return array|false
  395. * @author 段誉
  396. * @date 2022/10/20 18:23
  397. */
  398. public static function getScanCode($redirectUri)
  399. {
  400. try {
  401. $config = WeChatConfigService::getOpConfig();
  402. $appId = $config['app_id'];
  403. $redirectUri = UrlEncode($redirectUri);
  404. // 设置有效时间标记状态, 超时扫码不可登录
  405. $state = MD5(time().rand(10000, 99999));
  406. (new WebScanLoginCache())->setScanLoginState($state);
  407. // 扫码地址
  408. $url = WeChatRequestService::getScanCodeUrl($appId, $redirectUri, $state);
  409. return ['url' => $url];
  410. } catch (\Exception $e) {
  411. self::$error = $e->getMessage();
  412. return false;
  413. }
  414. }
  415. /**
  416. * @notes 网站扫码登录
  417. * @param $params
  418. * @return array|false
  419. * @author 段誉
  420. * @date 2022/10/21 10:28
  421. */
  422. public static function scanLogin($params)
  423. {
  424. Db::startTrans();
  425. try {
  426. // 通过code 获取 access_token,openid,unionid等信息
  427. $userAuth = WeChatRequestService::getUserAuthByCode($params['code']);
  428. if (empty($userAuth['openid']) || empty($userAuth['access_token'])) {
  429. throw new \Exception('获取用户授权信息失败');
  430. }
  431. // 获取微信用户信息
  432. $response = WeChatRequestService::getUserInfoByAuth($userAuth['access_token'], $userAuth['openid']);
  433. // 生成用户或更新用户信息
  434. $userServer = new WechatUserService($response, UserTerminalEnum::PC);
  435. $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
  436. // 更新登录信息
  437. self::updateLoginInfo($userInfo['id']);
  438. Db::commit();
  439. return $userInfo;
  440. } catch (\Exception $e) {
  441. Db::rollback();
  442. self::$error = $e->getMessage();
  443. return false;
  444. }
  445. }
  446. /**
  447. * @notes 更新用户信息
  448. * @param $params
  449. * @param $userId
  450. * @return User
  451. * @author 段誉
  452. * @date 2023/2/22 11:19
  453. */
  454. public static function updateUser($params, $userId)
  455. {
  456. return User::where(['id' => $userId])->update([
  457. 'nickname' => $params['nickname'],
  458. 'avatar' => FileService::setFileUrl($params['avatar']),
  459. 'is_new_user' => YesNoEnum::NO
  460. ]);
  461. }
  462. public static function firmLogin($params)
  463. {
  464. try {
  465. // 账号/手机号 密码登录
  466. $where = ['account|mobile' => $params['account']];
  467. $user = User::where($where)->findOrEmpty();
  468. if ($user->isEmpty()) {
  469. throw new \Exception('用户不存在');
  470. }
  471. if($user->user_type != YesNoEnum::YES){
  472. throw new \Exception('普通用户不能登录后台');
  473. }
  474. //更新登录信息
  475. $user->login_time = time();
  476. $user->login_ip = request()->ip();
  477. $user->save();
  478. //设置token
  479. $userInfo = UserTokenService::setToken($user->id, $params['terminal']);
  480. //返回登录信息
  481. $avatar = $user->avatar ?: Config::get('project.default_image.user_avatar');
  482. $avatar = FileService::getFileUrl($avatar);
  483. return [
  484. 'nickname' => $userInfo['nickname'],
  485. 'sn' => $userInfo['sn'],
  486. 'mobile' => $userInfo['mobile'],
  487. 'avatar' => $avatar,
  488. 'token' => $userInfo['token'],
  489. ];
  490. } catch (\Exception $e) {
  491. self::setError($e->getMessage());
  492. return false;
  493. }
  494. }
  495. }