Login.php 11 KB

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