LoginLogic.php 17 KB

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