LoginLogic.php 14 KB

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