1
0

LoginLogic.php 15 KB

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