Login.php 11 KB

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