LoginLogic.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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::create([
  51. 'sn' => $userSn,
  52. 'avatar' => $avatar,
  53. 'nickname' => '用户' . $userSn,
  54. 'account' => $params['account'],
  55. 'password' => $password,
  56. 'channel' => $params['channel'],
  57. ]);
  58. return true;
  59. } catch (\Exception $e) {
  60. self::setError($e->getMessage());
  61. return false;
  62. }
  63. }
  64. /**
  65. * @notes 账号/手机号登录,手机号验证码
  66. * @param $params
  67. * @return array|false
  68. * @author 段誉
  69. * @date 2022/9/6 19:26
  70. */
  71. public static function login($params)
  72. {
  73. try {
  74. // 账号/手机号 密码登录
  75. $where = ['account|mobile' => $params['account']];
  76. if ($params['scene'] == LoginEnum::MOBILE_CAPTCHA) {
  77. //手机验证码登录
  78. $where = ['mobile' => $params['account']];
  79. }
  80. $user = User::where($where)->findOrEmpty();
  81. if ($user->isEmpty()) {
  82. throw new \Exception('用户不存在');
  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. throw new \Exception('该微信已被绑定');
  284. }
  285. if (isset($response['unionid']) && !empty($response['unionid'])) {
  286. //在用unionid找记录,防止生成两个账号,同个unionid的问题
  287. $userAuth = UserAuth::where(['unionid' => $response['unionid']])
  288. ->findOrEmpty();
  289. if (!$userAuth->isEmpty() && $userAuth->user_id != $response['user_id']) {
  290. throw new \Exception('该微信已被绑定');
  291. }
  292. }
  293. //如果没有授权,直接生成一条微信授权记录
  294. UserAuth::create([
  295. 'user_id' => $response['user_id'],
  296. 'openid' => $response['openid'],
  297. 'unionid' => $response['unionid'] ?? '',
  298. 'terminal' => $response['terminal'],
  299. ]);
  300. return true;
  301. }
  302. /**
  303. * @notes 获取扫码登录地址
  304. * @return array|false
  305. * @author 段誉
  306. * @date 2022/10/20 18:23
  307. */
  308. public static function getScanCode($redirectUri)
  309. {
  310. try {
  311. $config = WeChatConfigService::getOpConfig();
  312. $appId = $config['app_id'];
  313. $redirectUri = UrlEncode($redirectUri);
  314. // 设置有效时间标记状态, 超时扫码不可登录
  315. $state = MD5(time().rand(10000, 99999));
  316. (new WebScanLoginCache())->setScanLoginState($state);
  317. // 扫码地址
  318. $url = WeChatRequestService::getScanCodeUrl($appId, $redirectUri, $state);
  319. return ['url' => $url];
  320. } catch (\Exception $e) {
  321. self::$error = $e->getMessage();
  322. return false;
  323. }
  324. }
  325. /**
  326. * @notes 网站扫码登录
  327. * @param $params
  328. * @return array|false
  329. * @author 段誉
  330. * @date 2022/10/21 10:28
  331. */
  332. public static function scanLogin($params)
  333. {
  334. Db::startTrans();
  335. try {
  336. // 通过code 获取 access_token,openid,unionid等信息
  337. $userAuth = WeChatRequestService::getUserAuthByCode($params['code']);
  338. if (empty($userAuth['openid']) || empty($userAuth['access_token'])) {
  339. throw new \Exception('获取用户授权信息失败');
  340. }
  341. // 获取微信用户信息
  342. $response = WeChatRequestService::getUserInfoByAuth($userAuth['access_token'], $userAuth['openid']);
  343. // 生成用户或更新用户信息
  344. $userServer = new WechatUserService($response, UserTerminalEnum::PC);
  345. $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
  346. // 更新登录信息
  347. self::updateLoginInfo($userInfo['id']);
  348. Db::commit();
  349. return $userInfo;
  350. } catch (\Exception $e) {
  351. Db::rollback();
  352. self::$error = $e->getMessage();
  353. return false;
  354. }
  355. }
  356. /**
  357. * @notes 更新用户信息
  358. * @param $params
  359. * @param $userId
  360. * @return User
  361. * @author 段誉
  362. * @date 2023/2/22 11:19
  363. */
  364. public static function updateUser($params, $userId)
  365. {
  366. return User::where(['id' => $userId])->update([
  367. 'nickname' => $params['nickname'],
  368. 'avatar' => FileService::setFileUrl($params['avatar']),
  369. 'is_new_user' => YesNoEnum::NO
  370. ]);
  371. }
  372. }