AuthController.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Components\Helpers;
  4. use App\Components\IPIP;
  5. use App\Components\QQWry;
  6. use App\Mail\activeUser;
  7. use App\Mail\resetPassword;
  8. use App\Mail\sendVerifyCode;
  9. use App\Models\EmailFilter;
  10. use App\Models\Invite;
  11. use App\Models\User;
  12. use App\Models\UserLoginLog;
  13. use App\Models\UserSubscribe;
  14. use App\Models\Verify;
  15. use App\Models\VerifyCode;
  16. use Auth;
  17. use Cache;
  18. use Captcha;
  19. use Cookie;
  20. use Hash;
  21. use Illuminate\Http\RedirectResponse;
  22. use Illuminate\Http\Request;
  23. use Log;
  24. use Mail;
  25. use Redirect;
  26. use Response;
  27. use Session;
  28. use Validator;
  29. /**
  30. * 认证控制器
  31. *
  32. * Class AuthController
  33. *
  34. * @package App\Http\Controllers
  35. */
  36. class AuthController extends Controller {
  37. protected static $systemConfig;
  38. public function __construct() {
  39. self::$systemConfig = Helpers::systemConfig();
  40. }
  41. // 登录
  42. public function login(Request $request) {
  43. if($request->isMethod('POST')){
  44. $validator = Validator::make($request->all(), [
  45. 'email' => 'required|email',
  46. 'password' => 'required'
  47. ], [
  48. 'email.required' => trans('auth.email_null'),
  49. 'password.required' => trans('auth.password_null')
  50. ]);
  51. if($validator->fails()){
  52. return Redirect::back()->withInput()->withErrors($validator->errors());
  53. }
  54. $email = $request->input('email');
  55. $password = $request->input('password');
  56. $remember = $request->input('remember');
  57. // 是否校验验证码
  58. $captcha = $this->check_captcha($request);
  59. if($captcha != false){
  60. return $captcha;
  61. }
  62. // 验证账号并创建会话
  63. if(!Auth::attempt(['email' => $email, 'password' => $password], $remember)){
  64. return Redirect::back()->withInput()->withErrors(trans('auth.login_error'));
  65. }
  66. $user = Auth::getUser();
  67. if(!$user){
  68. return Redirect::back()->withInput()->withErrors(trans('auth.login_error'));
  69. }
  70. // 校验普通用户账号状态
  71. if(!$user->is_admin){
  72. if($user->status < 0){
  73. Auth::logout(); // 强制销毁会话,因为Auth::attempt的时候会产生会话
  74. return Redirect::back()->withInput()->withErrors(trans('auth.login_ban',
  75. ['email' => self::$systemConfig['webmaster_email']]));
  76. }
  77. if($user->status == 0 && self::$systemConfig['is_activate_account']){
  78. Auth::logout(); // 强制销毁会话,因为Auth::attempt的时候会产生会话
  79. return Redirect::back()
  80. ->withInput()
  81. ->withErrors(trans('auth.active_tip').'<a href="/activeUser?email='.$email.'" target="_blank"><span style="color:#000">【'.trans('auth.active_account').'】</span></a>');
  82. }
  83. }
  84. // 写入登录日志
  85. $this->addUserLoginLog($user->id, getClientIp());
  86. // 更新登录信息
  87. User::uid()->update(['last_login' => time()]);
  88. // 根据权限跳转
  89. if($user->is_admin){
  90. return Redirect::to('admin');
  91. }
  92. return Redirect::to('/');
  93. }
  94. if(Auth::check()){
  95. if(Auth::getUser()->is_admin){
  96. return Redirect::to('admin');
  97. }
  98. return Redirect::to('/');
  99. }
  100. return Response::view('auth.login');
  101. }
  102. // 校验验证码
  103. private function check_captcha($request) {
  104. switch(self::$systemConfig['is_captcha']){
  105. case 1: // 默认图形验证码
  106. if(!Captcha::check($request->input('captcha'))){
  107. return Redirect::back()->withInput()->withErrors(trans('auth.captcha_error'));
  108. }
  109. break;
  110. case 2: // Geetest
  111. $validator = Validator::make($request->all(), [
  112. 'geetest_challenge' => 'required|geetest'
  113. ], [
  114. 'geetest' => trans('auth.captcha_fail')
  115. ]);
  116. if($validator->fails()){
  117. return Redirect::back()->withInput()->withErrors(trans('auth.captcha_fail'));
  118. }
  119. break;
  120. case 3: // Google reCAPTCHA
  121. $validator = Validator::make($request->all(), [
  122. 'g-recaptcha-response' => 'required|NoCaptcha'
  123. ]);
  124. if($validator->fails()){
  125. return Redirect::back()->withInput()->withErrors(trans('auth.captcha_fail'));
  126. }
  127. break;
  128. case 4: // hCaptcha
  129. $validator = Validator::make($request->all(), [
  130. 'h-captcha-response' => 'required|HCaptcha'
  131. ]);
  132. if($validator->fails()){
  133. return Redirect::back()->withInput()->withErrors(trans('auth.captcha_fail'));
  134. }
  135. break;
  136. default: // 不启用验证码
  137. break;
  138. }
  139. return 0;
  140. }
  141. /**
  142. * 添加用户登录日志
  143. *
  144. * @param string $userId 用户ID
  145. * @param string $ip IP地址
  146. */
  147. private function addUserLoginLog($userId, $ip): void {
  148. if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)){
  149. Log::info('识别到IPv6,尝试解析:'.$ip);
  150. $ipInfo = getIPInfo($ip);
  151. }else{
  152. $ipInfo = QQWry::ip($ip); // 通过纯真IP库解析IPv4信息
  153. if(isset($ipInfo['error'])){
  154. Log::info('无法识别IPv4,尝试使用IPIP的IP库解析:'.$ip);
  155. $ipip = IPIP::ip($ip);
  156. $ipInfo = [
  157. 'country' => $ipip['country_name'],
  158. 'province' => $ipip['region_name'],
  159. 'city' => $ipip['city_name']
  160. ];
  161. }else{
  162. // 判断纯真IP库获取的国家信息是否与IPIP的IP库获取的信息一致,不一致则用IPIP的(因为纯真IP库的非大陆IP准确率较低)
  163. $ipip = IPIP::ip($ip);
  164. if($ipInfo['country'] != $ipip['country_name']){
  165. $ipInfo['country'] = $ipip['country_name'];
  166. $ipInfo['province'] = $ipip['region_name'];
  167. $ipInfo['city'] = $ipip['city_name'];
  168. }
  169. }
  170. }
  171. if(empty($ipInfo) || empty($ipInfo['country'])){
  172. Log::warning("获取IP信息异常:".$ip);
  173. }
  174. $log = new UserLoginLog();
  175. $log->user_id = $userId;
  176. $log->ip = $ip;
  177. $log->country = $ipInfo['country'] ?? '';
  178. $log->province = $ipInfo['province'] ?? '';
  179. $log->city = $ipInfo['city'] ?? '';
  180. $log->county = $ipInfo['county'] ?? '';
  181. $log->isp = $ipInfo['isp'] ?? ($ipInfo['organization'] ?? '');
  182. $log->area = $ipInfo['area'] ?? '';
  183. $log->save();
  184. }
  185. // 退出
  186. public function logout(): RedirectResponse {
  187. Auth::logout();
  188. return Redirect::to('login');
  189. }
  190. // 注册
  191. public function register(Request $request) {
  192. $cacheKey = 'register_times_'.md5(getClientIp()); // 注册限制缓存key
  193. if($request->isMethod('POST')){
  194. $validator = Validator::make($request->all(), [
  195. 'username' => 'required',
  196. 'email' => 'required|email|unique:user',
  197. 'password' => 'required|min:6',
  198. 'confirmPassword' => 'required|same:password',
  199. 'term' => 'accepted'
  200. ], [
  201. 'username.required' => trans('auth.email_null'),
  202. 'email.required' => trans('auth.email_null'),
  203. 'email.email' => trans('auth.email_legitimate'),
  204. 'email.unique' => trans('auth.email_exist'),
  205. 'password.required' => trans('auth.password_null'),
  206. 'password.min' => trans('auth.password_limit'),
  207. 'confirmPassword.required' => trans('auth.confirm_password'),
  208. 'confirmPassword.same' => trans('auth.password_same'),
  209. 'term.accepted' => trans('auth.unaccepted')
  210. ]);
  211. if($validator->fails()){
  212. return Redirect::back()->withInput()->withErrors($validator->errors());
  213. }
  214. $username = $request->input('username');
  215. $email = $request->input('email');
  216. $password = $request->input('password');
  217. $register_token = $request->input('register_token');
  218. $code = $request->input('code');
  219. $verify_code = $request->input('verify_code');
  220. $aff = (int) $request->input('aff');
  221. // 防止重复提交
  222. if($register_token !== Session::get('register_token')){
  223. return Redirect::back()->withInput()->withErrors(trans('auth.repeat_request'));
  224. }
  225. Session::forget('register_token');
  226. // 是否开启注册
  227. if(!self::$systemConfig['is_register']){
  228. return Redirect::back()->withErrors(trans('auth.register_close'));
  229. }
  230. // 校验域名邮箱黑白名单
  231. if(self::$systemConfig['is_email_filtering']){
  232. $result = $this->emailChecker($email, 1);
  233. if($result !== false){
  234. return $result;
  235. }
  236. }
  237. // 如果需要邀请注册
  238. if(self::$systemConfig['is_invite_register']){
  239. // 必须使用邀请码
  240. if(self::$systemConfig['is_invite_register'] == 2 && !$code){
  241. return Redirect::back()->withInput()->withErrors(trans('auth.code_null'));
  242. }
  243. // 校验邀请码合法性
  244. if($code){
  245. $codeEnable = Invite::query()->whereCode($code)->whereStatus(0)->doesntExist();
  246. if($codeEnable){
  247. return Redirect::back()
  248. ->withInput($request->except(['code']))
  249. ->withErrors(trans('auth.code_error'));
  250. }
  251. }
  252. }
  253. // 注册前发送激活码
  254. if(self::$systemConfig['is_activate_account'] == 1){
  255. if(!$verify_code){
  256. return Redirect::back()
  257. ->withInput($request->except(['verify_code']))
  258. ->withErrors(trans('auth.captcha_null'));
  259. }
  260. $verifyCode = VerifyCode::query()
  261. ->whereAddress($email)
  262. ->whereCode($verify_code)
  263. ->whereStatus(0)
  264. ->firstOrFail();
  265. if(!$verifyCode){
  266. return Redirect::back()
  267. ->withInput($request->except(['verify_code']))
  268. ->withErrors(trans('auth.captcha_overtime'));
  269. }
  270. $verifyCode->status = 1;
  271. $verifyCode->save();
  272. }
  273. // 是否校验验证码
  274. $captcha = $this->check_captcha($request);
  275. if($captcha != false){
  276. return $captcha;
  277. }
  278. // 24小时内同IP注册限制
  279. if(self::$systemConfig['register_ip_limit'] && Cache::has($cacheKey)){
  280. $registerTimes = Cache::get($cacheKey);
  281. if($registerTimes >= self::$systemConfig['register_ip_limit']){
  282. return Redirect::back()
  283. ->withInput($request->except(['code']))
  284. ->withErrors(trans('auth.register_anti'));
  285. }
  286. }
  287. // 获取可用端口
  288. $port = self::$systemConfig['is_rand_port']? Helpers::getRandPort() : Helpers::getOnlyPort();
  289. if($port > self::$systemConfig['max_port']){
  290. return Redirect::back()->withInput()->withErrors(trans('auth.register_close'));
  291. }
  292. // 获取aff
  293. $affArr = $this->getAff($code, $aff);
  294. $referral_uid = $affArr['referral_uid'];
  295. $transfer_enable = MB * (self::$systemConfig['default_traffic'] + ($referral_uid? self::$systemConfig['referral_traffic'] : 0));
  296. // 创建新用户
  297. $uid = Helpers::addUser($email, Hash::make($password), $transfer_enable,
  298. self::$systemConfig['default_days'], $referral_uid);
  299. // 注册失败,抛出异常
  300. if(!$uid){
  301. return Redirect::back()->withInput()->withErrors(trans('auth.register_fail'));
  302. }
  303. // 更新昵称
  304. User::query()->whereId($uid)->update(['username' => $username]);
  305. // 生成订阅码
  306. $subscribe = new UserSubscribe();
  307. $subscribe->user_id = $uid;
  308. $subscribe->code = Helpers::makeSubscribeCode();
  309. $subscribe->times = 0;
  310. $subscribe->save();
  311. // 注册次数+1
  312. if(Cache::has($cacheKey)){
  313. Cache::increment($cacheKey);
  314. }else{
  315. Cache::put($cacheKey, 1, Day); // 24小时
  316. }
  317. // 更新邀请码
  318. if(self::$systemConfig['is_invite_register'] && $affArr['code_id']){
  319. Invite::query()->whereId($affArr['code_id'])->update(['fuid' => $uid, 'status' => 1]);
  320. }
  321. // 清除邀请人Cookie
  322. Cookie::unqueue('register_aff');
  323. // 注册后发送激活码
  324. if(self::$systemConfig['is_activate_account'] == 2){
  325. // 生成激活账号的地址
  326. $token = $this->addVerifyUrl($uid, $email);
  327. $activeUserUrl = self::$systemConfig['website_url'].'/active/'.$token;
  328. $logId = Helpers::addNotificationLog('注册激活', '请求地址:'.$activeUserUrl, 1, $email);
  329. Mail::to($email)->send(new activeUser($logId, $activeUserUrl));
  330. Session::flash('regSuccessMsg', trans('auth.register_active_tip'));
  331. }else{
  332. // 则直接给推荐人加流量
  333. if($referral_uid){
  334. $referralUser = User::find($referral_uid);
  335. if($referralUser && $referralUser->expire_time >= date('Y-m-d')){
  336. User::query()
  337. ->whereId($referral_uid)
  338. ->increment('transfer_enable', self::$systemConfig['referral_traffic'] * MB);
  339. }
  340. }
  341. if(self::$systemConfig['is_activate_account'] == 1){
  342. User::query()->whereId($uid)->update(['status' => 1]);
  343. }
  344. Session::flash('regSuccessMsg', trans('auth.register_success'));
  345. }
  346. return Redirect::to('login')->withInput();
  347. }
  348. $view['emailList'] = self::$systemConfig['is_email_filtering'] != 2? false : EmailFilter::query()
  349. ->whereType(2)
  350. ->get();
  351. Session::put('register_token', makeRandStr(16));
  352. return Response::view('auth.register', $view);
  353. }
  354. //邮箱检查
  355. private function emailChecker($email, $returnType = 0) {
  356. $emailFilterList = $this->emailFilterList(self::$systemConfig['is_email_filtering']);
  357. $emailSuffix = explode('@', $email); // 提取邮箱后缀
  358. switch(self::$systemConfig['is_email_filtering']){
  359. // 黑名单
  360. case 1:
  361. if(in_array(strtolower($emailSuffix[1]), $emailFilterList, true)){
  362. if($returnType){
  363. return Redirect::back()->withErrors(trans('auth.email_banned'));
  364. }
  365. return Response::json(['status' => 'fail', 'message' => trans('auth.email_banned')]);
  366. }
  367. break;
  368. //白名单
  369. case 2:
  370. if(!in_array(strtolower($emailSuffix[1]), $emailFilterList, true)){
  371. if($returnType){
  372. return Redirect::back()->withErrors(trans('auth.email_invalid'));
  373. }
  374. return Response::json(['status' => 'fail', 'message' => trans('auth.email_invalid')]);
  375. }
  376. break;
  377. default:
  378. if($returnType){
  379. return Redirect::back()->withErrors(trans('auth.email_invalid'));
  380. }
  381. return Response::json(['status' => 'fail', 'message' => trans('auth.email_invalid')]);
  382. }
  383. return false;
  384. }
  385. /**
  386. * 获取AFF
  387. *
  388. * @param string $code 邀请码
  389. * @param int|null $aff URL中的aff参数
  390. *
  391. * @return array
  392. */
  393. private function getAff($code = '', $aff = null): array {
  394. // 邀请人ID
  395. $referral_uid = 0;
  396. // 邀请码ID
  397. $code_id = 0;
  398. // 有邀请码先用邀请码,用谁的邀请码就给谁返利
  399. if($code){
  400. $inviteCode = Invite::query()->whereCode($code)->whereStatus(0)->first();
  401. if($inviteCode){
  402. $referral_uid = $inviteCode->uid;
  403. $code_id = $inviteCode->id;
  404. }
  405. }
  406. // 没有用邀请码或者邀请码是管理员生成的,则检查cookie或者url链接
  407. if(!$referral_uid){
  408. // 检查一下cookie里有没有aff
  409. $cookieAff = \Request::hasCookie('register_aff')? \Request::cookie('register_aff') : 0;
  410. if($cookieAff){
  411. $affUser = User::query()->whereId($cookieAff)->exists();
  412. $referral_uid = $affUser? $cookieAff : 0;
  413. }elseif($aff){ // 如果cookie里没有aff,就再检查一下请求的url里有没有aff,因为有些人的浏览器会禁用了cookie,比如chrome开了隐私模式
  414. $affUser = User::query()->whereId($aff)->exists();
  415. $referral_uid = $affUser? $aff : 0;
  416. }
  417. }
  418. return [
  419. 'referral_uid' => $referral_uid,
  420. 'code_id' => $code_id
  421. ];
  422. }
  423. // 生成申请的请求地址
  424. private function addVerifyUrl($uid, $email) {
  425. $token = md5(self::$systemConfig['website_name'].$email.microtime());
  426. $verify = new Verify();
  427. $verify->type = 1;
  428. $verify->user_id = $uid;
  429. $verify->token = $token;
  430. $verify->status = 0;
  431. $verify->save();
  432. return $token;
  433. }
  434. // 重设密码页
  435. public function resetPassword(Request $request) {
  436. if($request->isMethod('POST')){
  437. // 校验请求
  438. $validator = Validator::make($request->all(), [
  439. 'email' => 'required|email'
  440. ], [
  441. 'email.required' => trans('auth.email_null'),
  442. 'email.email' => trans('auth.email_legitimate')
  443. ]);
  444. if($validator->fails()){
  445. return Redirect::back()->withInput()->withErrors($validator->errors());
  446. }
  447. $email = $request->input('email');
  448. // 是否开启重设密码
  449. if(!self::$systemConfig['is_reset_password']){
  450. return Redirect::back()->withErrors(trans('auth.reset_password_close',
  451. ['email' => self::$systemConfig['webmaster_email']]));
  452. }
  453. // 查找账号
  454. $user = User::query()->whereEmail($email)->first();
  455. if(!$user){
  456. return Redirect::back()->withErrors(trans('auth.email_notExist'));
  457. }
  458. // 24小时内重设密码次数限制
  459. $resetTimes = 0;
  460. if(Cache::has('resetPassword_'.md5($email))){
  461. $resetTimes = Cache::get('resetPassword_'.md5($email));
  462. if($resetTimes >= self::$systemConfig['reset_password_times']){
  463. return Redirect::back()->withErrors(trans('auth.reset_password_limit',
  464. ['time' => self::$systemConfig['reset_password_times']]));
  465. }
  466. }
  467. // 生成取回密码的地址
  468. $token = $this->addVerifyUrl($user->id, $email);
  469. // 发送邮件
  470. $resetPasswordUrl = self::$systemConfig['website_url'].'/reset/'.$token;
  471. $logId = Helpers::addNotificationLog('重置密码', '请求地址:'.$resetPasswordUrl, 1, $email);
  472. Mail::to($email)->send(new resetPassword($logId, $resetPasswordUrl));
  473. Cache::put('resetPassword_'.md5($email), $resetTimes + 1, Day);
  474. return Redirect::back()->with('successMsg', trans('auth.reset_password_success_tip'));
  475. }
  476. return Response::view('auth.resetPassword');
  477. }
  478. // 重设密码
  479. public function reset(Request $request, $token) {
  480. if(!$token){
  481. return Redirect::to('login');
  482. }
  483. if($request->isMethod('POST')){
  484. $validator = Validator::make($request->all(), [
  485. 'password' => 'required|min:6',
  486. 'confirmPassword' => 'required|same:password'
  487. ], [
  488. 'password.required' => trans('auth.password_null'),
  489. 'password.min' => trans('auth.password_limit'),
  490. 'confirmPassword.required' => trans('auth.password_null'),
  491. 'confirmPassword.min' => trans('auth.password_limit'),
  492. 'confirmPassword.same' => trans('auth.password_same'),
  493. ]);
  494. if($validator->fails()){
  495. return Redirect::back()->withInput()->withErrors($validator->errors());
  496. }
  497. $password = $request->input('password');
  498. // 校验账号
  499. $verify = Verify::type(1)->with('user')->whereToken($token)->first();
  500. if(!$verify){
  501. return Redirect::to('login');
  502. }
  503. if($verify->status == 1){
  504. return Redirect::back()->withErrors(trans('auth.overtime'));
  505. }
  506. if($verify->user->status < 0){
  507. return Redirect::back()->withErrors(trans('auth.email_banned'));
  508. }
  509. if(Hash::check($password, $verify->user->password)){
  510. return Redirect::back()->withErrors(trans('auth.reset_password_same_fail'));
  511. }
  512. // 更新密码
  513. $ret = User::query()->whereId($verify->user_id)->update(['password' => Hash::make($password)]);
  514. if(!$ret){
  515. return Redirect::back()->withErrors(trans('auth.reset_password_fail'));
  516. }
  517. // 置为已使用
  518. $verify->status = 1;
  519. $verify->save();
  520. return Redirect::back()->with('successMsg', trans('auth.reset_password_new'));
  521. }
  522. $verify = Verify::type(1)->whereToken($token)->first();
  523. if(!$verify){
  524. return Redirect::to('login');
  525. }
  526. if(time() - strtotime($verify->created_at) >= 1800){
  527. // 置为已失效
  528. $verify->status = 2;
  529. $verify->save();
  530. }
  531. // 重新获取一遍verify
  532. $view['verify'] = Verify::type(1)->whereToken($token)->first();
  533. return Response::view('auth.reset', $view);
  534. }
  535. // 激活账号页
  536. public function activeUser(Request $request) {
  537. if($request->isMethod('POST')){
  538. $validator = Validator::make($request->all(), [
  539. 'email' => 'required|email|exists:user,email'
  540. ], [
  541. 'email.required' => trans('auth.email_null'),
  542. 'email.email' => trans('auth.email_legitimate'),
  543. 'email.exists' => trans('auth.email_notExist')
  544. ]);
  545. if($validator->fails()){
  546. return Redirect::back()->withInput()->withErrors($validator->errors());
  547. }
  548. $email = $request->input('email');
  549. // 是否开启账号激活
  550. if(self::$systemConfig['is_activate_account'] != 2){
  551. return Redirect::back()->withInput()->withErrors(trans('auth.active_close',
  552. ['email' => self::$systemConfig['webmaster_email']]));
  553. }
  554. // 查找账号
  555. $user = User::query()->whereEmail($email)->firstOrFail();
  556. if($user->status < 0){
  557. return Redirect::back()->withErrors(trans('auth.login_ban',
  558. ['email' => self::$systemConfig['webmaster_email']]));
  559. }
  560. if($user->status > 0){
  561. return Redirect::back()->withErrors(trans('auth.email_normal'));
  562. }
  563. // 24小时内激活次数限制
  564. $activeTimes = 0;
  565. if(Cache::has('activeUser_'.md5($email))){
  566. $activeTimes = Cache::get('activeUser_'.md5($email));
  567. if($activeTimes >= self::$systemConfig['active_times']){
  568. return Redirect::back()->withErrors(trans('auth.active_limit',
  569. ['time' => self::$systemConfig['webmaster_email']]));
  570. }
  571. }
  572. // 生成激活账号的地址
  573. $token = $this->addVerifyUrl($user->id, $email);
  574. // 发送邮件
  575. $activeUserUrl = self::$systemConfig['website_url'].'/active/'.$token;
  576. $logId = Helpers::addNotificationLog('激活账号', '请求地址:'.$activeUserUrl, 1, $email);
  577. Mail::to($email)->send(new activeUser($logId, $activeUserUrl));
  578. Cache::put('activeUser_'.md5($email), $activeTimes + 1, Day);
  579. return Redirect::back()->with('successMsg', trans('auth.register_active_tip'));
  580. }
  581. return Response::view('auth.activeUser');
  582. }
  583. // 激活账号
  584. public function active($token) {
  585. if(!$token){
  586. return Redirect::to('login');
  587. }
  588. $verify = Verify::type(1)->with('user')->whereToken($token)->first();
  589. if(!$verify){
  590. return Redirect::to('login');
  591. }
  592. if(empty($verify->user)){
  593. Session::flash('errorMsg', trans('auth.overtime'));
  594. return Response::view('auth.active');
  595. }
  596. if($verify->status > 0){
  597. Session::flash('errorMsg', trans('auth.overtime'));
  598. return Response::view('auth.active');
  599. }
  600. if($verify->user->status != 0){
  601. Session::flash('errorMsg', trans('auth.email_normal'));
  602. return Response::view('auth.active');
  603. }
  604. if(time() - strtotime($verify->created_at) >= 1800){
  605. Session::flash('errorMsg', trans('auth.overtime'));
  606. // 置为已失效
  607. $verify->status = 2;
  608. $verify->save();
  609. return Response::view('auth.active');
  610. }
  611. // 更新账号状态
  612. $ret = User::query()->whereId($verify->user_id)->update(['status' => 1]);
  613. if(!$ret){
  614. Session::flash('errorMsg', trans('auth.active_fail'));
  615. return Redirect::back();
  616. }
  617. // 置为已使用
  618. $verify->status = 1;
  619. $verify->save();
  620. // 账号激活后给邀请人送流量
  621. if($verify->user->referral_uid){
  622. $transfer_enable = self::$systemConfig['referral_traffic'] * MB;
  623. User::query()
  624. ->whereId($verify->user->referral_uid)
  625. ->increment('transfer_enable', $transfer_enable, ['enable' => 1]);
  626. }
  627. Session::flash('successMsg', trans('auth.active_success'));
  628. return Response::view('auth.active');
  629. }
  630. // 发送注册验证码
  631. public function sendCode(Request $request) {
  632. $validator = Validator::make($request->all(), [
  633. 'email' => 'required|email|unique:user'
  634. ], [
  635. 'email.required' => trans('auth.email_null'),
  636. 'email.email' => trans('auth.email_legitimate'),
  637. 'email.unique' => trans('auth.email_exist')
  638. ]);
  639. $email = $request->input('email');
  640. if($validator->fails()){
  641. return Response::json(['status' => 'fail', 'message' => $validator->getMessageBag()->first()]);
  642. }
  643. // 校验域名邮箱黑白名单
  644. if(self::$systemConfig['is_email_filtering']){
  645. $result = $this->emailChecker($email);
  646. if($result !== false){
  647. return $result;
  648. }
  649. }
  650. // 是否开启注册发送验证码
  651. if(self::$systemConfig['is_activate_account'] != 1){
  652. return Response::json(['status' => 'fail', 'message' => trans('auth.captcha_close')]);
  653. }
  654. // 防刷机制
  655. if(Cache::has('send_verify_code_'.md5(getClientIP()))){
  656. return Response::json(['status' => 'fail', 'message' => trans('auth.register_anti')]);
  657. }
  658. // 发送邮件
  659. $code = makeRandStr(6, true);
  660. $logId = Helpers::addNotificationLog('发送注册验证码', '验证码:'.$code, 1, $email);
  661. Mail::to($email)->send(new sendVerifyCode($logId, $code));
  662. $this->addVerifyCode($email, $code);
  663. Cache::put('send_verify_code_'.md5(getClientIP()), getClientIP(), Minute);
  664. return Response::json(['status' => 'success', 'message' => trans('auth.captcha_send')]);
  665. }
  666. // 生成注册验证码
  667. private function addVerifyCode($email, $code): void {
  668. $verify = new VerifyCode();
  669. $verify->address = $email;
  670. $verify->code = $code;
  671. $verify->status = 0;
  672. $verify->save();
  673. }
  674. // 公开的邀请码列表
  675. public function free(): \Illuminate\Http\Response {
  676. $view['inviteList'] = Invite::query()->whereUid(0)->whereStatus(0)->paginate();
  677. return Response::view('auth.free', $view);
  678. }
  679. // 切换语言
  680. public function switchLang($locale): RedirectResponse {
  681. Session::put("locale", $locale);
  682. return Redirect::back();
  683. }
  684. }