LoginLogic.php 14 KB

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