AuthController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. <?php
  2. /**
  3. * 认证控制器.
  4. *
  5. * @author nj <nj@gmail.com>
  6. * @date 2020-01-22 09:37:54
  7. */
  8. declare(strict_types=1);
  9. namespace Modules\Api\Controllers;
  10. use App\Constants\AdConstrant;
  11. use App\Constants\CreatorConstant;
  12. use App\Events\Task\DailyLoginEvent;
  13. use App\Events\Task\FillCodeEvent;
  14. use App\Events\Task\FirstRegisterEvent;
  15. use App\Events\Task\InviteFriendsEvent;
  16. use App\Events\Task\TimeTaskEvent;
  17. use App\Events\User\UserLoginEvent;
  18. use App\Model\UserModel;
  19. use App\Model\VersionModel;
  20. use App\Model\VipOrderModel;
  21. use App\Repositories\BannedIpRepository;
  22. use App\Repositories\ConfigRepoistory;
  23. use App\Repositories\MessageRepository;
  24. use App\Repositories\Service\CommonService;
  25. use App\Repositories\Service\QueueService;
  26. use App\Repositories\ShopsRepository;
  27. use App\Repositories\UserRepository;
  28. use App\Repositories\Utils\JwtRepository;
  29. use App\Repositories\Utils\M3u8CacheRepository;
  30. use App\Repositories\Utils\RandomUserInfoRepository;
  31. use App\Repositories\VersionRepository;
  32. use Carbon\Carbon;
  33. use Hyperf\Validation\Contract\ValidatorFactoryInterface;
  34. use Lcobucci\JWT\UnencryptedToken;
  35. use Modules\Api\Services\AuthService;
  36. use Modules\Api\Services\VideoService;
  37. use Psr\SimpleCache\CacheInterface;
  38. class AuthController extends BaseController
  39. {
  40. /**
  41. * Jwt受众.
  42. *
  43. * @var string
  44. */
  45. private $jwtAud = 'app-users';
  46. /**
  47. * 设备登录并返回Token.
  48. * @param ValidatorFactoryInterface $validatorFactory
  49. * @param AuthService $authService
  50. * @return mixed
  51. * @throws \Psr\SimpleCache\InvalidArgumentException
  52. */
  53. public function loginByDevice(
  54. ValidatorFactoryInterface $validatorFactory,
  55. AuthService $authService
  56. ) {
  57. // Json Body Raw获取
  58. $inputData = $this->getJsonData();
  59. // Demo 这是在控制器内校验器的写法.
  60. $rules = [
  61. 'code' => 'nullable', // 父级邀请人的UID
  62. 'token' => 'nullable',
  63. 'channel' => 'nullable', // 渠道UID
  64. 'version' => 'required',
  65. 'device_no' => 'required',
  66. 'device_type' => 'required|in:A,I,H',
  67. 'finger_hash' => 'nullable|string|max:32',
  68. 'self_sign' => 'nullable|string', // 苹果自签,yes=是的
  69. 'bundle_id' => 'nullable|string', // 包名
  70. ];
  71. $validator = $validatorFactory->make($inputData, $rules);
  72. if ($validator->fails()) {
  73. // 如果有错误(可能是多个信息),这里只取第一个错误信息返回.
  74. return json_fail($validator->errors()->first());
  75. }
  76. $clientIp = make(CommonService::class)->getIp();
  77. if(!filter_var($clientIp, FILTER_VALIDATE_IP)){
  78. return json_fail('认证失败8');
  79. }
  80. $inputData['device_no'] = strval($inputData['device_no']);
  81. $hVersion = strval(data_get($inputData, 'version', ''));
  82. $hDeviceNo = data_get($inputData, 'device_no', '');
  83. $hDeviceType = data_get($inputData, 'device_type', '');
  84. $hFingerHash = strval(data_get($inputData, 'finger_hash', ''));
  85. $hSelfSign = strval(data_get($inputData, 'self_sign', '')); // 苹果自签,yes字符串
  86. $hBundleId = strval(data_get($inputData, 'bundle_id', '')); // 包名
  87. $cache = make(CacheInterface::class);
  88. $user = null;
  89. $auth = [];
  90. //有token的情况
  91. if (!empty($inputData['token'])) {
  92. $jwtRepository = make(JwtRepository::class);
  93. $validateResult = $jwtRepository->validateToken($inputData['token'], $this->jwtAud);
  94. if (!$validateResult['is_valid']) {
  95. if ($validateResult['is_expired']) {
  96. return json_fail('认证过期', 401);
  97. }
  98. return json_fail('认证失败1', 403);
  99. } else {
  100. // 验证单点.
  101. /**
  102. * @var UnencryptedToken $tokenObj
  103. */
  104. $tokenObj = $validateResult['token_obj'];
  105. $deviceNo = $tokenObj->claims()->get('device_no');
  106. $deviceType = $tokenObj->claims()->get('device_type');
  107. $fingerHash = $tokenObj->claims()->get('finger_hash');
  108. $cacheKey = $authService
  109. ->getUserDeviceCacheKey($deviceNo, $deviceType);
  110. $cacheToken = $cache->has($cacheKey) ? $cache->get($cacheKey) : '';
  111. if (empty($cacheToken) || $cacheToken !== $inputData['token']) {
  112. return json_fail('认证失败2', 403);
  113. }
  114. if ($hDeviceNo !== $deviceNo || $hDeviceType != $deviceType) {
  115. return json_fail('认证失败3', 403);
  116. }
  117. $auth['token'] = $cacheToken;
  118. }
  119. }
  120. //没有token的情况
  121. if (empty($inputData['token'])) {
  122. // 可能串号,重复的设备号,做一次排序查询处理.
  123. $user = UserModel::query()->where(
  124. [
  125. 'device_no' => $hDeviceNo,
  126. 'device_type' => $hDeviceType,
  127. ]
  128. )->orderBy('id', 'ASC')->first();
  129. // 临时关闭ios指纹
  130. /*if (!$user) {
  131. if ($hDeviceType == 'I' && !empty($hFingerHash)) {
  132. // 仅iOS再查指纹.
  133. $user = UserModel::query()->where(['finger_hash' => $hFingerHash, 'device_type' => $hDeviceType])->first();
  134. }
  135. }*/
  136. }
  137. if ($hDeviceType == 'A') {
  138. if (version_compare($hVersion, '1.1.0', '<') || version_compare($hVersion, '1.99.1', '>')) {
  139. return json_fail('认证失败7', 403);
  140. }
  141. }
  142. //启动页广告
  143. $startup = null;
  144. // 视频内引导广告(多个)
  145. $adsGuide = null;
  146. //配置
  147. $config = [];
  148. $configModel = make(ConfigRepoistory::class);
  149. $config['rule'] = $configModel->gets(
  150. [],
  151. 'rule'
  152. );
  153. $config['sys'] = $configModel->gets(
  154. ['app_notice',
  155. 'notice',
  156. 'share_text',
  157. 'share_url',
  158. 'upload_url',
  159. 'skip',
  160. 'app_url',
  161. 'server_link',
  162. 'share_bg',
  163. 'video_preview_seconds',
  164. 'withdraw_usdt',
  165. 'withdraw_money',
  166. 'hotel_coin',
  167. 'ppvod_base_url',
  168. 'ppvod_upload_key',
  169. 'ppvod_sign_key',
  170. 'chat_coin',
  171. ],
  172. 'sys'
  173. );
  174. //公告
  175. if (empty($config['sys']['notice'])) {
  176. $config['sys']['app_notice'] = '';
  177. unset($config['sys']['notice']);
  178. }
  179. if (!empty($user)) {
  180. // 检查是否被删,是否被锁定.
  181. if (intval($user->status) != 1) {
  182. return json_fail('该用户被禁用');
  183. }
  184. make(QueueService::class)
  185. ->refreshLoginTimePush(
  186. [
  187. 'user_id' => $user->code,
  188. 'version' => $user->version,
  189. ],
  190. 1
  191. );
  192. } else {
  193. //注册
  194. $isBannedIp = make(BannedIpRepository::class)->isBanned($clientIp);
  195. if ($isBannedIp) {
  196. return json_fail('认证失败9', 403);
  197. }
  198. // 注册时,校验提交的版本和最新强制版本对比.
  199. $cacheVersionKey = 'force_version:' . $hDeviceType;
  200. $lastForceVersionInfo = make(VersionRepository::class)->getLastForce($hDeviceType);
  201. if (!empty($lastForceVersionInfo)) {
  202. if (version_compare($hVersion, $lastForceVersionInfo['version_code'], '<')) {
  203. return json_fail('认证失败8', 403);
  204. }
  205. }
  206. if (!empty($inputData['code'])) {
  207. $info = make(UserRepository::class)
  208. ->getUserInfoFromCache($inputData['code']);
  209. if ($info) {
  210. $parentUid = $info['code'];
  211. }
  212. }
  213. // 随机头像.
  214. $sysAvatars = make(UserRepository::class)->getSysAvatars();
  215. $sysAvatars[] = 'f2|/'. env('STATIC_DIR_NAME', 'doukui') . '/avatars/default.ceb';
  216. $randKey = array_rand($sysAvatars);
  217. $avatar = $sysAvatars[$randKey];
  218. $createData = [
  219. 'ip' => $clientIp,
  220. 'avatar' => $avatar,
  221. 'device_no' => $hDeviceNo,
  222. 'parent_uid' => $parentUid ?? '',
  223. 'channel_id' => $inputData['channel'] ?? '',
  224. 'device_type' => $hDeviceType,
  225. 'version' => $hVersion,
  226. 'finger_hash' => $hFingerHash ?? '',
  227. 'last_login_at' => Carbon::now()->toDateTimeString(),
  228. 'bundle_id' => $hBundleId,
  229. ];
  230. $user = UserModel::query()->create($createData);
  231. //生成邀请码
  232. $code = hashEncodeId($user->id);
  233. $user->code = $code;
  234. $user->nick = RandomUserInfoRepository::getNickname();
  235. $user->save();
  236. //会员裂变关系逻辑 丢队列异步执行
  237. if (!empty($parentUid)) {
  238. make(QueueService::class)
  239. ->createUserRelationJob(['invite_id' => $parentUid, 'invited_id' => $user->code], 1);
  240. // 绑定邀请码任务
  241. dispatch_event(new FillCodeEvent(['user_id' => $user->code]));
  242. // 邀请好友任务事件
  243. dispatch_event(new InviteFriendsEvent(['user_id' => $parentUid]));
  244. // 限时任务队列
  245. make(QueueService::class)->timeTaskSendRewardJob(['user_id' => $parentUid], 5);
  246. }
  247. //注册奖励事件
  248. $registerEventParams = [
  249. 'ip' => $clientIp,
  250. 'user_id' => $code,
  251. 'device_type' => $hDeviceType,
  252. 'self_sign' => $hSelfSign,
  253. ];
  254. dispatch_event(new FirstRegisterEvent($registerEventParams));
  255. $jobParams = [
  256. 'uid' => $user->id,
  257. 'dt' => $hDeviceType,
  258. 'is_vip' => 0,
  259. 'date' => Carbon::now()->toDateString(),
  260. ];
  261. //异步丢注册统计日志
  262. make(QueueService::class)->addRegisterJob($jobParams);
  263. //代理系统异步注册
  264. make(QueueService::class)->agentUserRegistJob($user->toArray());
  265. }
  266. if (empty($auth)) {
  267. $auth = $authService->createSingleJwt(
  268. $user->code,
  269. $hDeviceNo,
  270. $hDeviceType,
  271. $hVersion,
  272. $hFingerHash
  273. );
  274. }
  275. // 拼接版本里的zip_url
  276. $tmpHeaderVersion = $hVersion;
  277. $versionCacheKey = 'version:' . $hDeviceType . ':v'. $tmpHeaderVersion;
  278. $versionItem = make(CacheInterface::class)->remember(
  279. $versionCacheKey,
  280. 60 * 60,
  281. function () use ($inputData, $hVersion, $hDeviceType, $tmpHeaderVersion) {
  282. if ($hDeviceType == 'I') {
  283. // 针对马甲包,特例处理,状态可以是隐藏.
  284. $conditions = [
  285. 'device_type' => $hDeviceType,
  286. 'version_type' => 'free',
  287. 'version_code' => $tmpHeaderVersion,
  288. ];
  289. } else {
  290. $conditions = [
  291. 'status' => 1,
  292. 'device_type' => $hDeviceType,
  293. 'version_type' => 'free',
  294. 'version_code' => $hVersion,
  295. ];
  296. }
  297. $item = VersionModel::query()->where($conditions)->orderByDesc('version_code')->first();
  298. if (!empty($item)) {
  299. $item = $item->toArray();
  300. $item['app_url'] = make(ConfigRepoistory::class)
  301. ->get('share_url', 'sys');
  302. return $item;
  303. } else {
  304. return null;
  305. }
  306. }
  307. );
  308. $config['sys']['version_zip_url'] = !empty($versionItem['zip_url']) ? $versionItem['zip_url'] : '';
  309. // ppvod上传最大容量,单位MB
  310. $config['sys']['file_max_size_mb'] = CreatorConstant::VIDEO_MAX_SIZE_MB; // 文件最大多少MB
  311. //邀请链接组装
  312. $config['sys']['share_url'] .= '?invite_code=' . $user->code . '&channel_code=';
  313. $config['sys']['share_text'] = str_replace(
  314. '{{share_url}}',
  315. $config['sys']['share_url'],
  316. $config['sys']['share_text']
  317. );
  318. $config['sys']['share_bg'] = isset($config['sys']['share_bg']) ? M3u8CacheRepository::getImageUrl($config['sys']['share_bg']) : '';
  319. $videoService = make(VideoService::class);
  320. $startupItems = $videoService->getAdList('startup');
  321. $adsGuideItems = $videoService->getAdList(AdConstrant::VIDEO_GUIDE); // 视频内引导广告,多个
  322. if ($startupItems) {
  323. $randKey = array_rand($startupItems);
  324. $startupOne = $startupItems[$randKey];
  325. $startup = [
  326. 'title' => $startupOne['title'],
  327. 'cover' => M3u8CacheRepository::getImageUrl($startupOne['cover']),
  328. 'link' => $startupOne['link'],
  329. 'scheme' => $startupOne['scheme'],
  330. 'type' => $startupOne['type'],
  331. 'play' => !empty($startupOne['play']) ? M3u8CacheRepository::getVideoInnerUrl($startupOne['play'], $user->code, $startupOne['id'], 'ad') : '',
  332. 'resolution' => $startupOne['resolution'] ?? '',
  333. ];
  334. if (!empty($startup['link'])) {
  335. $startup['link'] = M3u8CacheRepository::getLinkUrl($startup['link'], ['user_code' => $user->code]);
  336. }
  337. }
  338. if (!empty($adsGuideItems)) {
  339. $adsGuide = [];
  340. foreach ($adsGuideItems as $v) {
  341. $tmpLink = $v['link'];
  342. if (!empty($tmpLink)) {
  343. $tmpLink = M3u8CacheRepository::getLinkUrl($tmpLink, ['user_code' => $user->code]);
  344. }
  345. $adsGuide[] = [
  346. 'title' => $v['title'],
  347. 'cover' => M3u8CacheRepository::getImageUrl($v['cover']),
  348. 'link' => $tmpLink,
  349. 'scheme' => $v['scheme'],
  350. ];
  351. }
  352. }
  353. $data['auth'] = $auth;
  354. $data['startup'] = $startup;
  355. $data['config'] = $config;
  356. $data['skip'] = $config['sys']['skip']; // 启动屏跳转秒数.
  357. $data['ads_guide'] = $adsGuide;
  358. $kefuUrl = isset($data['config']['sys']['server_link']) ? $data['config']['sys']['server_link'] : '';
  359. if (strripos($kefuUrl, '?')) {
  360. $kefuUrl .= '&user_code='. $user->code;
  361. } else {
  362. $kefuUrl .= '?user_code='. $user->code;
  363. }
  364. $data['config']['sys']['server_link'] = $kefuUrl;
  365. $data['config']['sys']['video_preview_seconds'] = intval($data['config']['sys']['video_preview_seconds']);
  366. $data['config']['sys']['withdraw_money'] = (int) $data['config']['sys']['withdraw_money'];
  367. $data['config']['sys']['withdraw_usdt'] = (int) $data['config']['sys']['withdraw_usdt'];
  368. $data['config']['sys']['hotel_coin'] = (int) $data['config']['sys']['hotel_coin'];
  369. $data['config']['sys']['chat_coin'] = $data['config']['sys']['chat_coin'];
  370. //使用redis统计日活
  371. // $jobParams = [
  372. // 'user_id' => $user->code,
  373. // 'version' => $hVersion,
  374. // 'device_type' => $hDeviceType,
  375. // ];
  376. // 触发事件(可以作为演示hyperf event+listener实现应用).
  377. $eventParams = [
  378. 'user_id' => $user->code,
  379. 'version' => $hVersion,
  380. 'device_type' => $hDeviceType,
  381. 'device_no' => $hDeviceNo,
  382. 'finger_hash' => $hFingerHash,
  383. 'ip' => $clientIp,
  384. ];
  385. dispatch_event(new UserLoginEvent($eventParams));
  386. //登陆奖励事件
  387. dispatch_event(new DailyLoginEvent(['user_id' => $user->code]));
  388. // 代理系统异步登陆
  389. if (empty($user->version)) {
  390. $user->version = $hVersion;
  391. }
  392. make(QueueService::class)->agentUserLoginJob($user->toArray());
  393. return json_success($data);
  394. }
  395. /**
  396. * 刷新Token并返回token
  397. *
  398. * @param ValidatorFactoryInterface $validatorFactory
  399. * @param JwtRepository $jwtRepository
  400. * @param AuthService $authService
  401. * @return mixed
  402. * @throws \Psr\SimpleCache\InvalidArgumentException
  403. */
  404. public function refreshToken(
  405. ValidatorFactoryInterface $validatorFactory,
  406. JwtRepository $jwtRepository,
  407. AuthService $authService
  408. ) {
  409. $inputData = $this->getJsonData();
  410. $rules = [
  411. 'device_no' => 'required',
  412. 'device_type' => 'required|in:I,A,H',
  413. 'old_token' => 'required',
  414. ];
  415. $validator = $validatorFactory->make($inputData, $rules);
  416. if ($validator->fails()) {
  417. // 如果有错误(可能是多个信息),这里只取第一个错误信息返回.
  418. return json_fail($validator->errors()->first());
  419. }
  420. $inputData['device_no'] = strval($inputData['device_no']);
  421. $hDeviceNo = data_get($inputData, 'device_no', '');
  422. $hDeviceType = data_get($inputData, 'device_type', '');
  423. $hOldToken = data_get($inputData, 'old_token', '');
  424. $hFingerHash = strval(data_get($inputData, 'finger_hash', ''));
  425. $hSelfSign = strval(data_get($inputData, 'self_sign', '')); // 苹果自签,yes字符串
  426. // 是否强制刷新.
  427. $validateResult = $jwtRepository
  428. ->validateToken($hOldToken, $this->jwtAud);
  429. if ($validateResult['is_illegal']) {
  430. return json_fail('旧token非法.');
  431. }
  432. $clientIp = make(CommonService::class)->getIp();
  433. if(!filter_var($clientIp, FILTER_VALIDATE_IP)){
  434. return json_fail('认证失败8');
  435. }
  436. /**
  437. * @var UnencryptedToken $tokenObj
  438. */
  439. $tokenObj = $validateResult['token_obj'];
  440. $userId = $tokenObj->claims()->get('user_id');
  441. $deviceNo = $tokenObj->claims()->get('device_no');
  442. $deviceType = $tokenObj->claims()->get('device_type');
  443. $version = $tokenObj->claims()->get('version');
  444. $fingerHash = $tokenObj->claims()->get('finger_hash');
  445. // 检查入参设备信息是否有效.
  446. if ($deviceNo!= $hDeviceNo) {
  447. return json_fail('无效数据匹配.');
  448. }
  449. if ($deviceType != $hDeviceType) {
  450. return json_fail('无效数据匹配.');
  451. }
  452. if (!$validateResult['is_valid'] && $validateResult['is_expired']) {
  453. $tokenInfo = $authService
  454. ->createSingleJwt($userId, $deviceNo, $deviceType, $version, $fingerHash);
  455. } else {
  456. return json_fail('旧Token无效或者未过期');
  457. }
  458. //更新登陆时间
  459. make(QueueService::class)->refreshLoginTimePush(['user_id' => $userId, 'version' => $version], 1);
  460. // 触发事件(可以作为演示hyperf event+listener实现应用).
  461. $eventParams = [
  462. 'user_id' => $userId,
  463. 'version' => $version,
  464. 'device_type' => $hDeviceType,
  465. 'device_no' => $hDeviceNo,
  466. 'finger_hash' => $hFingerHash,
  467. 'ip' => $clientIp,
  468. ];
  469. dispatch_event(new UserLoginEvent($eventParams));
  470. $data = [
  471. 'token' => $tokenInfo['token'],
  472. 'expired_at' => $tokenInfo['expired_at'],
  473. ];
  474. return json_success($data);
  475. }
  476. }