AuthController.php 23 KB

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