1
0

LoginLogic.php 17 KB

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