1
0

LoginLogic.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. * 获取微信用户openid信息
  139. */
  140. public static function getOpenIdByCode($params)
  141. {
  142. try {
  143. //通过code获取微信 openid
  144. $response = (new WeChatOaService())->getOpenIdByCode($params['code']);
  145. return $response;
  146. } catch (\Exception $e) {
  147. self::$error = $e->getMessage();
  148. return false;
  149. }
  150. }
  151. /**
  152. * @notes 公众号登录
  153. * @param array $params
  154. * @return array|false
  155. * @throws \GuzzleHttp\Exception\GuzzleException
  156. * @author 段誉
  157. * @date 2022/9/20 19:47
  158. */
  159. public static function oaLogin(array $params)
  160. {
  161. Db::startTrans();
  162. try {
  163. //通过code获取微信 openid
  164. $response = (new WeChatOaService())->getOaResByCode($params['code']);
  165. $userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_OA);
  166. $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
  167. // 更新登录信息
  168. self::updateLoginInfo($userInfo['id']);
  169. Db::commit();
  170. return $userInfo;
  171. } catch (\Exception $e) {
  172. Db::rollback();
  173. self::$error = $e->getMessage();
  174. return false;
  175. }
  176. }
  177. /**
  178. * @notes 小程序-静默登录
  179. * @param array $params
  180. * @return array|false
  181. * @author 段誉
  182. * @date 2022/9/20 19:47
  183. */
  184. public static function silentLogin(array $params)
  185. {
  186. try {
  187. //通过code获取微信 openid
  188. $response = (new WeChatMnpService())->getMnpResByCode($params['code']);
  189. $userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_MMP);
  190. $userInfo = $userServer->getResopnseByUserInfo('silent')->getUserInfo();
  191. if (!empty($userInfo)) {
  192. // 更新登录信息
  193. self::updateLoginInfo($userInfo['id']);
  194. }
  195. return $userInfo;
  196. } catch (\Exception $e) {
  197. self::$error = $e->getMessage();
  198. return false;
  199. }
  200. }
  201. /**
  202. * @notes 小程序-授权登录
  203. * @param array $params
  204. * @return array|false
  205. * @author 段誉
  206. * @date 2022/9/20 19:47
  207. */
  208. public static function mnpLogin(array $params)
  209. {
  210. Db::startTrans();
  211. try {
  212. //通过code获取微信 openid
  213. $response = (new WeChatMnpService())->getMnpResByCode($params['code']);
  214. $userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_MMP);
  215. $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
  216. // 更新登录信息
  217. self::updateLoginInfo($userInfo['id']);
  218. Db::commit();
  219. return $userInfo;
  220. } catch (\Exception $e) {
  221. Db::rollback();
  222. self::$error = $e->getMessage();
  223. return false;
  224. }
  225. }
  226. /**
  227. * @param array $params
  228. * @return array|false
  229. *
  230. */
  231. public static function mnpSessionKey(array $params)
  232. {
  233. Db::startTrans();
  234. try {
  235. //通过code获取微信 openid
  236. $response = (new WeChatMnpService())->getMnpResByCode($params['code']);
  237. Db::commit();
  238. return $response;
  239. } catch (\Exception $e) {
  240. Db::rollback();
  241. self::$error = $e->getMessage();
  242. return false;
  243. }
  244. }
  245. /**
  246. * @notes 小程序-手机号授权一键登录
  247. * @param $params
  248. * @return array
  249. * @author 段誉
  250. * @date 2022/9/6 19:26
  251. */
  252. public static function mnpPhoneLogin(array $params)
  253. {
  254. try {
  255. $where = ['mobile' => $params['mobile']];
  256. $params['account'] = $params['mobile'];
  257. $user = User::where($where)->findOrEmpty();
  258. //先检查openid是否有记录
  259. $isAuth = UserAuth::where('openid', '=', $params['openid'])->findOrEmpty();
  260. if (!$isAuth->isEmpty() && !$user->isEmpty()) {
  261. $authUser = UserAuth::where('user_id', '=', $user['id'])->findOrEmpty();
  262. if($isAuth->user_id != $authUser->user_id) {
  263. throw new \Exception('该微信已被绑定');
  264. }
  265. }
  266. if ($user->isEmpty()) {
  267. //直接注册用户
  268. $params['channel'] = 1;
  269. $user = self::register($params);
  270. }
  271. //更新登录信息
  272. $user->login_time = time();
  273. $user->login_ip = request()->ip();
  274. $user->save();
  275. if($isAuth->isEmpty()){
  276. UserAuth::create([
  277. 'user_id' => $user->id,
  278. 'openid' => $params['openid'],
  279. 'unionid' => $params['unionid'] ?? '',
  280. 'terminal' => 1,
  281. ]);
  282. }
  283. if(!$isAuth->isEmpty() && $isAuth->user_id==0){
  284. $isAuth->user_id = $user->id;
  285. $isAuth->save();
  286. }
  287. $userInfo = UserTokenService::setToken($user->id, 1);
  288. //返回登录信息
  289. $avatar = $user->avatar ?: Config::get('project.default_image.user_avatar');
  290. $avatar = FileService::getFileUrl($avatar);
  291. return [
  292. 'nickname' => $userInfo['nickname'],
  293. 'sn' => $userInfo['sn'],
  294. 'mobile' => $userInfo['mobile'],
  295. 'avatar' => $avatar,
  296. 'token' => $userInfo['token'],
  297. ];
  298. } catch (\Exception $e) {
  299. self::setError($e->getMessage());
  300. return [];
  301. }
  302. }
  303. /**
  304. * @notes 更新登录信息
  305. * @param $userId
  306. * @throws \Exception
  307. * @author 段誉
  308. * @date 2022/9/20 19:46
  309. */
  310. public static function updateLoginInfo($userId)
  311. {
  312. $user = User::findOrEmpty($userId);
  313. if ($user->isEmpty()) {
  314. throw new \Exception('用户不存在');
  315. }
  316. $time = time();
  317. $user->login_time = $time;
  318. $user->login_ip = request()->ip();
  319. $user->update_time = $time;
  320. $user->save();
  321. }
  322. /**
  323. * @notes 小程序端绑定微信
  324. * @param array $params
  325. * @return bool
  326. * @author 段誉
  327. * @date 2022/9/20 19:46
  328. */
  329. public static function mnpAuthLogin(array $params)
  330. {
  331. try {
  332. //通过code获取微信openid
  333. $response = (new WeChatMnpService())->getMnpResByCode($params['code']);
  334. $response['user_id'] = $params['user_id'];
  335. $response['terminal'] = UserTerminalEnum::WECHAT_MMP;
  336. return self::createAuth($response);
  337. } catch (\Exception $e) {
  338. self::$error = $e->getMessage();
  339. return false;
  340. }
  341. }
  342. /**
  343. * @notes 公众号端绑定微信
  344. * @param array $params
  345. * @return bool
  346. * @throws \GuzzleHttp\Exception\GuzzleException
  347. * @author 段誉
  348. * @date 2022/9/16 10:43
  349. */
  350. public static function oaAuthLogin(array $params)
  351. {
  352. try {
  353. //通过code获取微信openid
  354. $response = (new WeChatOaService())->getOaResByCode($params['code']);
  355. $response['user_id'] = $params['user_id'];
  356. $response['terminal'] = UserTerminalEnum::WECHAT_OA;
  357. return self::createAuth($response);
  358. } catch (\Exception $e) {
  359. self::$error = $e->getMessage();
  360. return false;
  361. }
  362. }
  363. /**
  364. * @notes 生成授权记录
  365. * @param $response
  366. * @return bool
  367. * @throws \Exception
  368. * @author 段誉
  369. * @date 2022/9/16 10:43
  370. */
  371. public static function createAuth($response)
  372. {
  373. //先检查openid是否有记录
  374. $isAuth = UserAuth::where('openid', '=', $response['openid'])->findOrEmpty();
  375. if (!$isAuth->isEmpty()) {
  376. if($isAuth->user_id != $response['user_id']) {
  377. throw new \Exception('该微信已被绑定');
  378. }
  379. if($isAuth->user_id == 0) {
  380. //更新操作
  381. $isAuth->user_id = $response['user_id'];
  382. $isAuth->save();
  383. return true;
  384. }
  385. if($isAuth->user_id == $response['user_id']) {
  386. return true;
  387. }
  388. }
  389. if (isset($response['unionid']) && !empty($response['unionid'])) {
  390. //在用unionid找记录,防止生成两个账号,同个unionid的问题
  391. $userAuth = UserAuth::where(['unionid' => $response['unionid']])
  392. ->findOrEmpty();
  393. if (!$userAuth->isEmpty() && $userAuth->user_id != $response['user_id']) {
  394. throw new \Exception('该微信已被绑定');
  395. }
  396. }
  397. //如果没有授权,直接生成一条微信授权记录
  398. UserAuth::create([
  399. 'user_id' => $response['user_id'],
  400. 'openid' => $response['openid'],
  401. 'unionid' => $response['unionid'] ?? '',
  402. 'terminal' => $response['terminal'],
  403. ]);
  404. return true;
  405. }
  406. /**
  407. * @notes 获取扫码登录地址
  408. * @return array|false
  409. * @author 段誉
  410. * @date 2022/10/20 18:23
  411. */
  412. public static function getScanCode($redirectUri)
  413. {
  414. try {
  415. $config = WeChatConfigService::getOpConfig();
  416. $appId = $config['app_id'];
  417. $redirectUri = UrlEncode($redirectUri);
  418. // 设置有效时间标记状态, 超时扫码不可登录
  419. $state = MD5(time().rand(10000, 99999));
  420. (new WebScanLoginCache())->setScanLoginState($state);
  421. // 扫码地址
  422. $url = WeChatRequestService::getScanCodeUrl($appId, $redirectUri, $state);
  423. return ['url' => $url];
  424. } catch (\Exception $e) {
  425. self::$error = $e->getMessage();
  426. return false;
  427. }
  428. }
  429. /**
  430. * @notes 网站扫码登录
  431. * @param $params
  432. * @return array|false
  433. * @author 段誉
  434. * @date 2022/10/21 10:28
  435. */
  436. public static function scanLogin($params)
  437. {
  438. Db::startTrans();
  439. try {
  440. // 通过code 获取 access_token,openid,unionid等信息
  441. $userAuth = WeChatRequestService::getUserAuthByCode($params['code']);
  442. if (empty($userAuth['openid']) || empty($userAuth['access_token'])) {
  443. throw new \Exception('获取用户授权信息失败');
  444. }
  445. // 获取微信用户信息
  446. $response = WeChatRequestService::getUserInfoByAuth($userAuth['access_token'], $userAuth['openid']);
  447. // 生成用户或更新用户信息
  448. $userServer = new WechatUserService($response, UserTerminalEnum::PC);
  449. $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
  450. // 更新登录信息
  451. self::updateLoginInfo($userInfo['id']);
  452. Db::commit();
  453. return $userInfo;
  454. } catch (\Exception $e) {
  455. Db::rollback();
  456. self::$error = $e->getMessage();
  457. return false;
  458. }
  459. }
  460. /**
  461. * @notes 更新用户信息
  462. * @param $params
  463. * @param $userId
  464. * @return User
  465. * @author 段誉
  466. * @date 2023/2/22 11:19
  467. */
  468. public static function updateUser($params, $userId)
  469. {
  470. return User::where(['id' => $userId])->update([
  471. 'nickname' => $params['nickname'],
  472. 'avatar' => FileService::setFileUrl($params['avatar']),
  473. 'is_new_user' => YesNoEnum::NO
  474. ]);
  475. }
  476. public static function firmLogin($params)
  477. {
  478. try {
  479. // 账号/手机号 密码登录
  480. $where = ['account|mobile' => $params['account']];
  481. $user = User::where($where)->findOrEmpty();
  482. if ($user->isEmpty()) {
  483. throw new \Exception('用户不存在');
  484. }
  485. if($user->user_type != YesNoEnum::YES){
  486. throw new \Exception('普通用户不能登录后台');
  487. }
  488. //更新登录信息
  489. $user->login_time = time();
  490. $user->login_ip = request()->ip();
  491. $user->save();
  492. //设置token
  493. $userInfo = UserTokenService::setToken($user->id, $params['terminal']);
  494. //返回登录信息
  495. $avatar = $user->avatar ?: Config::get('project.default_image.user_avatar');
  496. $avatar = FileService::getFileUrl($avatar);
  497. return [
  498. 'nickname' => $userInfo['nickname'],
  499. 'sn' => $userInfo['sn'],
  500. 'mobile' => $userInfo['mobile'],
  501. 'avatar' => $avatar,
  502. 'token' => $userInfo['token'],
  503. ];
  504. } catch (\Exception $e) {
  505. self::setError($e->getMessage());
  506. return false;
  507. }
  508. }
  509. }