LoginLogic.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 mnpPhoneCode(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 $userId
  232. * @throws \Exception
  233. * @author 段誉
  234. * @date 2022/9/20 19:46
  235. */
  236. public static function updateLoginInfo($userId)
  237. {
  238. $user = User::findOrEmpty($userId);
  239. if ($user->isEmpty()) {
  240. throw new \Exception('用户不存在');
  241. }
  242. $time = time();
  243. $user->login_time = $time;
  244. $user->login_ip = request()->ip();
  245. $user->update_time = $time;
  246. $user->save();
  247. }
  248. /**
  249. * @notes 小程序端绑定微信
  250. * @param array $params
  251. * @return bool
  252. * @author 段誉
  253. * @date 2022/9/20 19:46
  254. */
  255. public static function mnpAuthLogin(array $params)
  256. {
  257. try {
  258. //通过code获取微信openid
  259. $response = (new WeChatMnpService())->getMnpResByCode($params['code']);
  260. $response['user_id'] = $params['user_id'];
  261. $response['terminal'] = UserTerminalEnum::WECHAT_MMP;
  262. return self::createAuth($response);
  263. } catch (\Exception $e) {
  264. self::$error = $e->getMessage();
  265. return false;
  266. }
  267. }
  268. /**
  269. * @notes 公众号端绑定微信
  270. * @param array $params
  271. * @return bool
  272. * @throws \GuzzleHttp\Exception\GuzzleException
  273. * @author 段誉
  274. * @date 2022/9/16 10:43
  275. */
  276. public static function oaAuthLogin(array $params)
  277. {
  278. try {
  279. //通过code获取微信openid
  280. $response = (new WeChatOaService())->getOaResByCode($params['code']);
  281. $response['user_id'] = $params['user_id'];
  282. $response['terminal'] = UserTerminalEnum::WECHAT_OA;
  283. return self::createAuth($response);
  284. } catch (\Exception $e) {
  285. self::$error = $e->getMessage();
  286. return false;
  287. }
  288. }
  289. /**
  290. * @notes 生成授权记录
  291. * @param $response
  292. * @return bool
  293. * @throws \Exception
  294. * @author 段誉
  295. * @date 2022/9/16 10:43
  296. */
  297. public static function createAuth($response)
  298. {
  299. //先检查openid是否有记录
  300. $isAuth = UserAuth::where('openid', '=', $response['openid'])->findOrEmpty();
  301. if (!$isAuth->isEmpty()) {
  302. if($isAuth->user_id != $response['user_id']) {
  303. throw new \Exception('该微信已被绑定');
  304. }
  305. if($isAuth->user_id == 0) {
  306. //更新操作
  307. $isAuth->user_id = $response['user_id'];
  308. $isAuth->save();
  309. return true;
  310. }
  311. if($isAuth->user_id == $response['user_id']) {
  312. return true;
  313. }
  314. }
  315. if (isset($response['unionid']) && !empty($response['unionid'])) {
  316. //在用unionid找记录,防止生成两个账号,同个unionid的问题
  317. $userAuth = UserAuth::where(['unionid' => $response['unionid']])
  318. ->findOrEmpty();
  319. if (!$userAuth->isEmpty() && $userAuth->user_id != $response['user_id']) {
  320. throw new \Exception('该微信已被绑定');
  321. }
  322. }
  323. //如果没有授权,直接生成一条微信授权记录
  324. UserAuth::create([
  325. 'user_id' => $response['user_id'],
  326. 'openid' => $response['openid'],
  327. 'unionid' => $response['unionid'] ?? '',
  328. 'terminal' => $response['terminal'],
  329. ]);
  330. return true;
  331. }
  332. /**
  333. * @notes 获取扫码登录地址
  334. * @return array|false
  335. * @author 段誉
  336. * @date 2022/10/20 18:23
  337. */
  338. public static function getScanCode($redirectUri)
  339. {
  340. try {
  341. $config = WeChatConfigService::getOpConfig();
  342. $appId = $config['app_id'];
  343. $redirectUri = UrlEncode($redirectUri);
  344. // 设置有效时间标记状态, 超时扫码不可登录
  345. $state = MD5(time().rand(10000, 99999));
  346. (new WebScanLoginCache())->setScanLoginState($state);
  347. // 扫码地址
  348. $url = WeChatRequestService::getScanCodeUrl($appId, $redirectUri, $state);
  349. return ['url' => $url];
  350. } catch (\Exception $e) {
  351. self::$error = $e->getMessage();
  352. return false;
  353. }
  354. }
  355. /**
  356. * @notes 网站扫码登录
  357. * @param $params
  358. * @return array|false
  359. * @author 段誉
  360. * @date 2022/10/21 10:28
  361. */
  362. public static function scanLogin($params)
  363. {
  364. Db::startTrans();
  365. try {
  366. // 通过code 获取 access_token,openid,unionid等信息
  367. $userAuth = WeChatRequestService::getUserAuthByCode($params['code']);
  368. if (empty($userAuth['openid']) || empty($userAuth['access_token'])) {
  369. throw new \Exception('获取用户授权信息失败');
  370. }
  371. // 获取微信用户信息
  372. $response = WeChatRequestService::getUserInfoByAuth($userAuth['access_token'], $userAuth['openid']);
  373. // 生成用户或更新用户信息
  374. $userServer = new WechatUserService($response, UserTerminalEnum::PC);
  375. $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
  376. // 更新登录信息
  377. self::updateLoginInfo($userInfo['id']);
  378. Db::commit();
  379. return $userInfo;
  380. } catch (\Exception $e) {
  381. Db::rollback();
  382. self::$error = $e->getMessage();
  383. return false;
  384. }
  385. }
  386. /**
  387. * @notes 更新用户信息
  388. * @param $params
  389. * @param $userId
  390. * @return User
  391. * @author 段誉
  392. * @date 2023/2/22 11:19
  393. */
  394. public static function updateUser($params, $userId)
  395. {
  396. return User::where(['id' => $userId])->update([
  397. 'nickname' => $params['nickname'],
  398. 'avatar' => FileService::setFileUrl($params['avatar']),
  399. 'is_new_user' => YesNoEnum::NO
  400. ]);
  401. }
  402. public static function firmLogin($params)
  403. {
  404. try {
  405. // 账号/手机号 密码登录
  406. $where = ['account|mobile' => $params['account']];
  407. $user = User::where($where)->findOrEmpty();
  408. if ($user->isEmpty()) {
  409. throw new \Exception('用户不存在');
  410. }
  411. if($user->user_type != YesNoEnum::YES){
  412. throw new \Exception('普通用户不能登录后台');
  413. }
  414. //更新登录信息
  415. $user->login_time = time();
  416. $user->login_ip = request()->ip();
  417. $user->save();
  418. //设置token
  419. $userInfo = UserTokenService::setToken($user->id, $params['terminal']);
  420. //返回登录信息
  421. $avatar = $user->avatar ?: Config::get('project.default_image.user_avatar');
  422. $avatar = FileService::getFileUrl($avatar);
  423. return [
  424. 'nickname' => $userInfo['nickname'],
  425. 'sn' => $userInfo['sn'],
  426. 'mobile' => $userInfo['mobile'],
  427. 'avatar' => $avatar,
  428. 'token' => $userInfo['token'],
  429. ];
  430. } catch (\Exception $e) {
  431. self::setError($e->getMessage());
  432. return false;
  433. }
  434. }
  435. }