Login.php 11 KB

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