Login.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\index\service\passport;
  13. use think\facade\Cache;
  14. use think\helper\Str;
  15. use yiovo\captcha\facade\CaptchaApi;
  16. use app\api\model\{User as UserModel, Setting as SettingModel};
  17. use app\api\service\{user\Oauth as OauthService, user\Avatar as AvatarService, passport\Party as PartyService};
  18. use app\api\validate\passport\Login as ValidateLogin;
  19. use app\common\service\BaseService;
  20. use app\common\enum\Setting as SettingEnum;
  21. use cores\exception\BaseException;
  22. /**
  23. * 服务类:用户登录
  24. * Class Login
  25. * @package app\api\service\passport
  26. */
  27. class Login extends BaseService
  28. {
  29. /**
  30. * 用户信息 (登录成功后才记录)
  31. * @var UserModel|null $userInfo
  32. */
  33. private $userInfo;
  34. // 用于生成token的自定义盐
  35. const TOKEN_SALT = 'user_salt';
  36. /**
  37. * 执行用户登录
  38. * @param array $data
  39. * @return bool
  40. * @throws BaseException
  41. * @throws \think\Exception
  42. * @throws \think\db\exception\DataNotFoundException
  43. * @throws \think\db\exception\DbException
  44. * @throws \think\db\exception\ModelNotFoundException
  45. */
  46. public function login(array $data): bool
  47. {
  48. empty($data['partyData']) && $data['partyData'] = [];
  49. if ($data['isParty'] == 'true' || $data['isParty'] === true){
  50. $data['isParty'] = true;
  51. }else{
  52. $data['isParty'] = false;
  53. }
  54. // 数据验证
  55. $this->validate($data);
  56. // 自动登录注册
  57. $this->register($data);
  58. // 保存第三方用户信息
  59. $this->createUserOauth($this->getUserId(), $data['isParty'], $data['partyData']);
  60. // 记录登录态
  61. return $this->setSession();
  62. }
  63. /**
  64. * 快捷登录:微信小程序用户
  65. * @param array $form
  66. * @return bool
  67. * @throws BaseException
  68. * @throws \think\db\exception\DataNotFoundException
  69. * @throws \think\db\exception\DbException
  70. * @throws \think\db\exception\ModelNotFoundException
  71. * @throws \think\Exception
  72. */
  73. public function loginMpWx(array $form): bool
  74. {
  75. // 获取微信小程序登录态(session)
  76. $wxSession = PartyService::getMpWxSession($form['partyData']['code']);
  77. // 判断openid是否存在
  78. $userId = OauthService::getUserIdByOauthId($wxSession['openid'], 'MP-WEIXIN');
  79. // 获取用户信息
  80. $userInfo = !empty($userId) ? UserModel::detail($userId) : null;
  81. // 用户信息存在, 更新登录信息
  82. if (!empty($userInfo)) {
  83. // 更新用户登录信息
  84. $this->updateUser($userInfo, true, $form['partyData']);
  85. // 记录登录态
  86. return $this->setSession();
  87. }
  88. // 用户信息不存在 => 注册新用户 或者 跳转到绑定手机号页
  89. $setting = SettingModel::getItem(SettingEnum::REGISTER);
  90. // 后台设置了需强制绑定手机号, 返回前端isBindMobile, 跳转到手机号验证页
  91. if ($setting['isForceBindMpweixin']) {
  92. throwError('当前用户未绑定手机号', null, ['isBindMobile' => true]);
  93. }
  94. // 后台未开启强制绑定手机号, 直接保存新用户
  95. if (!$setting['isForceBindMpweixin']) {
  96. // 用户不存在: 创建一个新用户
  97. $this->createUser('', true, $form['partyData']);
  98. // 保存第三方用户信息
  99. $this->createUserOauth($this->getUserId(), true, $form['partyData']);
  100. }
  101. // 记录登录态
  102. return $this->setSession();
  103. }
  104. public function resetPassword($email,$smsCode,$password)
  105. {
  106. //todo 电子烟校验邮箱mobile的验证码是否匹配
  107. $mailCaptcha = new MailCaptcha();
  108. $mailCaptcha->checkCaptcha($smsCode, $email);
  109. $userInfo = !empty($email) ? UserModel::detail(['mobile'=>$email]) : null;
  110. if (empty($userInfo)){
  111. throwError('Not exit', 401, []);
  112. }
  113. $data = ['password' => md5($password . $userInfo['salt'])];
  114. // 更新用户记录
  115. return $userInfo->save($data) !== false;
  116. }
  117. /**
  118. * 快捷登录:微信小程序用户
  119. * @param array $form
  120. * @return bool
  121. * @throws BaseException
  122. * @throws \think\db\exception\DataNotFoundException
  123. * @throws \think\db\exception\DbException
  124. * @throws \think\db\exception\ModelNotFoundException
  125. * @throws \think\Exception
  126. */
  127. public function loginMpWxMobile(array $form): bool
  128. {
  129. // 获取微信小程序登录态(session)
  130. $wxSession = PartyService::getMpWxSession($form['code']);
  131. // 解密encryptedData -> 拿到手机号
  132. $wxData = OauthService::wxDecryptData($wxSession['session_key'], $form['encryptedData'], $form['iv']);
  133. // 整理登录注册数据
  134. $loginData = [
  135. 'mobile' => $wxData['purePhoneNumber'],
  136. 'isParty' => $form['isParty'],
  137. 'partyData' => $form['partyData'],
  138. ];
  139. // 自动登录注册
  140. $this->register($loginData);
  141. // 保存第三方用户信息
  142. $this->createUserOauth($this->getUserId(), $loginData['isParty'], $loginData['partyData']);
  143. // 记录登录态
  144. return $this->setSession();
  145. }
  146. /**
  147. * 保存oauth信息(第三方用户信息)
  148. * @param int $userId 用户ID
  149. * @param bool $isParty 是否为第三方用户
  150. * @param array $partyData 第三方用户数据
  151. * @return void
  152. * @throws BaseException
  153. * @throws \think\db\exception\DataNotFoundException
  154. * @throws \think\db\exception\DbException
  155. * @throws \think\db\exception\ModelNotFoundException
  156. */
  157. private function createUserOauth(int $userId, bool $isParty, array $partyData = []): void
  158. {
  159. if ($isParty) {
  160. $Oauth = new PartyService;
  161. $Oauth->createUserOauth($userId, $partyData);
  162. }
  163. }
  164. /**
  165. * 当前登录的用户信息
  166. */
  167. public function getUserInfo(): ?UserModel
  168. {
  169. return $this->userInfo;
  170. }
  171. /**
  172. * 当前登录的用户ID
  173. * @return int
  174. */
  175. private function getUserId(): int
  176. {
  177. return (int)$this->getUserInfo()['user_id'];
  178. }
  179. /**
  180. * 自动登录注册
  181. * @param array $data
  182. * @return void
  183. * @throws \think\Exception
  184. * @throws \think\db\exception\DataNotFoundException
  185. * @throws \think\db\exception\DbException
  186. * @throws \think\db\exception\ModelNotFoundException
  187. */
  188. private function register(array $data): void
  189. {
  190. // 查询用户是否已存在
  191. // 用户存在: 更新用户登录信息
  192. $userInfo = UserModel::detail(['mobile' => $data['mobile']]);
  193. if ($userInfo) {
  194. $this->updateUser($userInfo, $data['isParty'], $data['partyData']);
  195. return;
  196. }
  197. // 用户不存在: 创建一个新用户
  198. $this->createUser($data['mobile'], $data['isParty'], $data['partyData'], $data['password']);
  199. }
  200. /**
  201. * 新增用户
  202. * @param string $mobile 手机号
  203. * @param bool $isParty 是否存在第三方用户信息
  204. * @param array $partyData 用户信息(第三方)
  205. * @return void
  206. * @throws \think\Exception
  207. * @throws \think\db\exception\DataNotFoundException
  208. * @throws \think\db\exception\DbException
  209. * @throws \think\db\exception\ModelNotFoundException
  210. */
  211. private function createUser(string $mobile, bool $isParty, array $partyData = [], string $password = ''): void
  212. {
  213. $salt = Str::random(6);
  214. // 用户信息
  215. $data = [
  216. 'mobile' => $mobile,
  217. 'nick_name' => !empty($mobile) ? hide_mobile($mobile) : '',
  218. 'platform' => getPlatform(),
  219. 'last_login_time' => time(),
  220. 'store_id' => $this->storeId,
  221. 'salt' => $salt,
  222. 'password' => md5($password . $salt)
  223. ];
  224. // 写入用户信息(第三方)
  225. if ($isParty === true && !empty($partyData)) {
  226. $partyUserInfo = PartyService::partyUserInfo($partyData, true);
  227. $data = array_merge($data, $partyUserInfo);
  228. }
  229. // 新增用户记录
  230. $model = new UserModel;
  231. $status = $model->save($data);
  232. // 记录用户信息
  233. $this->userInfo = $model;
  234. }
  235. /**
  236. * 更新用户登录信息
  237. * @param UserModel $userInfo
  238. * @param bool $isParty 是否存在第三方用户信息
  239. * @param array $partyData 用户信息(第三方)
  240. * @return void
  241. */
  242. private function updateUser(UserModel $userInfo, bool $isParty, array $partyData = []): void
  243. {
  244. // 用户信息
  245. $data = [
  246. 'last_login_time' => time(),
  247. 'store_id' => $this->storeId
  248. ];
  249. // 写入用户信息(第三方)
  250. // 如果不需要每次登录都更新微信用户头像昵称, 下面4行代码可以屏蔽掉
  251. if ($isParty === true && !empty($partyData)) {
  252. $partyUserInfo = PartyService::partyUserInfo($partyData, true);
  253. $data = array_merge($data, $partyUserInfo);
  254. }
  255. // 更新用户记录
  256. $status = $userInfo->save($data) !== false;
  257. // 记录用户信息
  258. $this->userInfo = $userInfo;
  259. }
  260. /**
  261. * 记录登录态
  262. * @return bool
  263. * @throws BaseException
  264. */
  265. private function setSession(): bool
  266. {
  267. empty($this->userInfo) && throwError('未找到用户信息');
  268. // 登录的token
  269. $token = $this->getToken($this->getUserId());
  270. // 记录缓存, 30天
  271. Cache::set($token, [
  272. 'user' => $this->userInfo,
  273. 'store_id' => $this->storeId,
  274. 'is_login' => true,
  275. ], 86400 * 30);
  276. return true;
  277. }
  278. /**
  279. * 数据验证
  280. * @param array $data
  281. * @return void
  282. * @throws BaseException
  283. */
  284. private function validate(array $data): void
  285. {
  286. // 数据验证
  287. $validate = new ValidateLogin;
  288. if (!$validate->check($data)) {
  289. throwError($validate->getError());
  290. }
  291. // 验证短信验证码是否匹配
  292. // if (!CaptchaApi::checkSms($data['smsCode'], $data['mobile'])) {
  293. // throwError('短信验证码不正确');
  294. // }
  295. //todo 电子烟校验邮箱mobile的验证码是否匹配
  296. $mailCaptcha = new MailCaptcha();
  297. $mailCaptcha->checkCaptcha($data['smsCode'], $data['mobile']);
  298. }
  299. /**
  300. * 获取登录的token
  301. * @param int $userId
  302. * @return string
  303. */
  304. public function getToken(int $userId): string
  305. {
  306. static $token = '';
  307. if (empty($token)) {
  308. $token = $this->makeToken($userId);
  309. }
  310. return $token;
  311. }
  312. /**
  313. * 生成用户认证的token
  314. * @param int $userId
  315. * @return string
  316. */
  317. private function makeToken(int $userId): string
  318. {
  319. $storeId = $this->storeId;
  320. // 生成一个不会重复的随机字符串
  321. $guid = get_guid_v4();
  322. // 当前时间戳 (精确到毫秒)
  323. $timeStamp = microtime(true);
  324. // 自定义一个盐
  325. $salt = self::TOKEN_SALT;
  326. return md5("{$storeId}_{$timeStamp}_{$userId}_{$guid}_{$salt}");
  327. }
  328. }