123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703 |
- <?php
- namespace App\Http\Controllers;
- use App\Components\Helpers;
- use App\Components\IP;
- use App\Http\Requests\Auth\RegisterRequest;
- use App\Mail\activeUser;
- use App\Mail\resetPassword;
- use App\Mail\sendVerifyCode;
- use App\Models\EmailFilter;
- use App\Models\Invite;
- use App\Models\User;
- use App\Models\UserLoginLog;
- use App\Models\Verify;
- use App\Models\VerifyCode;
- use Auth;
- use Cache;
- use Captcha;
- use Cookie;
- use Hash;
- use Illuminate\Http\RedirectResponse;
- use Illuminate\Http\Request;
- use Log;
- use Mail;
- use Redirect;
- use Response;
- use Session;
- use Str;
- use Validator;
- /**
- * 认证控制器.
- *
- * Class AuthController
- */
- class AuthController extends Controller
- {
- // 登录
- public function showLoginForm()
- {
- // 根据权限跳转
- if (Auth::check()) {
- if (Auth::getUser()->can('admin.index')) {
- return Redirect::route('admin.index');
- }
- return Redirect::route('home');
- }
- return view('auth.login');
- }
- public function login(Request $request)
- {
- $validator = Validator::make($request->all(), ['email' => 'required|email', 'password' => 'required']);
- if ($validator->fails()) {
- return Redirect::back()->withInput()->withErrors($validator->errors());
- }
- // 是否校验验证码
- $captcha = $this->check_captcha($request);
- if ($captcha !== false) {
- return $captcha;
- }
- // 验证账号并创建会话
- if (! Auth::attempt($validator->validated(), $request->input('remember'))) {
- return Redirect::back()->withInput()->withErrors(trans('auth.error.login_failed'));
- }
- $user = Auth::getUser();
- if (! $user) {
- return Redirect::back()->withInput()->withErrors(trans('auth.error.login_error'));
- }
- if ($request->routeIs('admin.login.post') && $user->cannot('admin.index')) {
- // 管理页面登录
- // 非权限者清场
- Auth::logout();
- return Redirect::route('login');
- }
- // 校验普通用户账号状态
- if ($user->status === -1) {
- Auth::logout(); // 强制销毁会话,因为Auth::attempt的时候会产生会话
- return Redirect::back()->withInput()->withErrors(trans('auth.error.account_baned'));
- }
- if ($user->status === 0 && sysConfig('is_activate_account')) {
- Auth::logout(); // 强制销毁会话,因为Auth::attempt的时候会产生会话
- return Redirect::back()->withInput()->withErrors(trans('auth.active.promotion.0').'<a href="'.route('active').'?email='.$user->email.
- '" target="_blank">👉【'.trans('common.active_item', ['attribute' => trans('common.account')]).'】👈</span></a><br>'.trans('auth.active.promotion.1'));
- }
- // 写入登录日志
- $this->addUserLoginLog($user->id, IP::getClientIp());
- // 更新登录信息
- $user->update(['last_login' => time()]);
- return redirect()->back();
- }
- // 校验验证码
- private function check_captcha(Request $request)
- {
- switch (sysConfig('is_captcha')) {
- case 1: // 默认图形验证码
- if (! Captcha::check($request->input('captcha'))) {
- return Redirect::back()->withInput()->withErrors(trans('auth.captcha.error.failed'));
- }
- break;
- case 2: // Geetest
- $validator = Validator::make($request->all(), [
- 'geetest_challenge' => 'required|geetest',
- ]);
- if ($validator->fails()) {
- return Redirect::back()->withInput()->withErrors(trans('auth.captcha.error.failed'));
- }
- break;
- case 3: // Google reCAPTCHA
- $validator = Validator::make($request->all(), [
- 'g-recaptcha-response' => 'required|NoCaptcha',
- ]);
- if ($validator->fails()) {
- return Redirect::back()->withInput()->withErrors(trans('auth.captcha.error.failed'));
- }
- break;
- case 4: // hCaptcha
- $validator = Validator::make($request->all(), [
- 'h-captcha-response' => 'required|HCaptcha',
- ]);
- if ($validator->fails()) {
- return Redirect::back()->withInput()->withErrors(trans('auth.captcha.error.failed'));
- }
- break;
- default: // 不启用验证码
- break;
- }
- return false;
- }
- /**
- * 添加用户登录日志.
- *
- * @param int $userId 用户ID
- * @param string $ip IP地址
- */
- private function addUserLoginLog(int $userId, string $ip): void
- {
- $ipLocation = IP::getIPInfo($ip);
- if (empty($ipLocation) || empty($ipLocation['country'])) {
- Log::warning(trans('error.get_ip').':'.$ip);
- }
- $log = new UserLoginLog();
- $log->user_id = $userId;
- $log->ip = $ip;
- $log->country = $ipLocation['country'] ?? '';
- $log->province = $ipLocation['province'] ?? '';
- $log->city = $ipLocation['city'] ?? '';
- $log->county = $ipLocation['county'] ?? '';
- $log->isp = $ipLocation['isp'] ?? ($ipLocation['organization'] ?? '');
- $log->area = $ipLocation['area'] ?? '';
- $log->save();
- }
- // 退出
- public function logout(): RedirectResponse
- {
- Auth::logout();
- return Redirect::route('login');
- }
- public function showRegistrationForm()
- {
- Session::put('register_token', Str::random());
- return view('auth.register', ['emailList' => (int) sysConfig('is_email_filtering') !== 2 ? false : EmailFilter::whereType(2)->get()]);
- }
- // 注册
- public function register(RegisterRequest $request)
- {
- $cacheKey = 'register_times_'.md5(IP::getClientIp()); // 注册限制缓存key
- $validator = Validator::make($request->all(), [
- 'username' => 'required',
- 'email' => 'required|email|unique:user',
- 'password' => 'required|min:6|confirmed',
- 'term' => 'accepted',
- ]);
- if ($validator->fails()) {
- return Redirect::back()->withInput()->withErrors($validator->errors());
- }
- $data = $request->validated();
- $register_token = $request->input('register_token');
- $code = $request->input('code');
- $verify_code = $request->input('verify_code');
- $aff = (int) $request->input('aff');
- // 防止重复提交
- if ($register_token !== Session::get('register_token')) {
- return Redirect::back()->withInput()->withErrors(trans('auth.error.repeat_request'));
- }
- Session::forget('register_token');
- // 是否开启注册
- if (! sysConfig('is_register')) {
- return Redirect::back()->withErrors(trans('auth.register.error.disable'));
- }
- // 校验域名邮箱黑白名单
- if (sysConfig('is_email_filtering')) {
- $result = $this->emailChecker($data['email'], 1);
- if ($result !== false) {
- return $result;
- }
- }
- // 如果需要邀请注册
- if (sysConfig('is_invite_register')) {
- // 校验邀请码合法性
- if ($code) {
- if (Invite::whereCode($code)->whereStatus(0)->doesntExist()) {
- return Redirect::back()->withInput($request->except('code'))->withErrors(trans('auth.invite.error.unavailable'));
- }
- } elseif ((int) sysConfig('is_invite_register') === 2) { // 必须使用邀请码
- return Redirect::back()->withInput()->withErrors(trans('validation.required', ['attribute' => trans('auth.invite.attribute')]));
- }
- }
- // 注册前发送激活码
- if ((int) sysConfig('is_activate_account') === 1) {
- if (! $verify_code) {
- return Redirect::back()->withInput($request->except('verify_code'))->withErrors(trans('auth.captcha.required'));
- }
- $verifyCode = VerifyCode::whereAddress($data['email'])->whereCode($verify_code)->whereStatus(0)->first();
- if (! $verifyCode) {
- return Redirect::back()->withInput($request->except('verify_code'))->withErrors(trans('auth.captcha.error.timeout'));
- }
- $verifyCode->status = 1;
- $verifyCode->save();
- }
- // 是否校验验证码
- $captcha = $this->check_captcha($request);
- if ($captcha !== false) {
- return $captcha;
- }
- // 24小时内同IP注册限制
- if (sysConfig('register_ip_limit') && Cache::has($cacheKey)) {
- $registerTimes = Cache::get($cacheKey);
- if ($registerTimes >= sysConfig('register_ip_limit')) {
- return Redirect::back()->withInput($request->except('code'))->withErrors(trans('auth.register.error.throttle'));
- }
- }
- // 获取可用端口 TODO: 修改判断&提示
- $port = Helpers::getPort();
- if ($port > sysConfig('max_port')) {
- return Redirect::back()->withInput()->withErrors(trans('auth.register.error.disable'));
- }
- // 获取aff
- $affArr = $this->getAff($code, $aff);
- $inviter_id = $affArr['inviter_id'];
- $transfer_enable = MB * ((int) sysConfig('default_traffic') + ($inviter_id ? (int) sysConfig('referral_traffic') : 0));
- // 创建新用户
- $user = Helpers::addUser($data['email'], $data['password'], $transfer_enable, sysConfig('default_days'), $inviter_id, $data['username']);
- // 注册失败,抛出异常
- if (! $user) {
- return Redirect::back()->withInput()->withErrors(trans('auth.register.failed'));
- }
- // 注册次数+1
- if (Cache::has($cacheKey)) {
- Cache::increment($cacheKey);
- } else {
- Cache::put($cacheKey, 1, Day); // 24小时
- }
- // 更新邀请码
- if ($affArr['code_id'] && sysConfig('is_invite_register')) {
- $invite = Invite::find($affArr['code_id']);
- if ($invite) {
- $invite->update(['invitee_id' => $user->id, 'status' => 1]);
- }
- }
- // 清除邀请人Cookie
- Cookie::unqueue('register_aff');
- // 注册后发送激活码
- if ((int) sysConfig('is_activate_account') === 2) {
- // 生成激活账号的地址
- $token = $this->addVerifyUrl($user->id, $user->email);
- $activeUserUrl = route('activeAccount', $token);
- $logId = Helpers::addNotificationLog(trans('common.active_item', ['attribute' => trans('auth.register.attribute')]),
- trans('common.request_url').':'.$activeUserUrl, 1, $user->email);
- Mail::to($user->email)->send(new activeUser($logId, $activeUserUrl));
- Session::flash('successMsg', trans('auth.active.sent'));
- } else {
- // 则直接给推荐人加流量
- if ($inviter_id) {
- $referralUser = User::find($inviter_id);
- if ($referralUser && $referralUser->expired_at >= date('Y-m-d')) {
- $referralUser->incrementData(sysConfig('referral_traffic') * MB);
- }
- }
- if ((int) sysConfig('is_activate_account') === 1) {
- $user->update(['status' => 1]);
- }
- Session::flash('successMsg', trans('auth.register.success'));
- }
- return Redirect::route('login')->withInput();
- }
- //邮箱检查
- private function emailChecker($email, $returnType = 0)
- {
- $emailFilterList = EmailFilter::whereType(sysConfig('is_email_filtering'))->pluck('words')->toArray();
- $emailSuffix = explode('@', $email); // 提取邮箱后缀
- switch (sysConfig('is_email_filtering')) {
- // 黑名单
- case 1:
- if (in_array(strtolower($emailSuffix[1]), $emailFilterList, true)) {
- if ($returnType) {
- return Redirect::back()->withErrors(trans('auth.email.error.banned'));
- }
- return Response::json(['status' => 'fail', 'message' => trans('auth.email.error.banned')]);
- }
- break;
- //白名单
- case 2:
- if (! in_array(strtolower($emailSuffix[1]), $emailFilterList, true)) {
- if ($returnType) {
- return Redirect::back()->withErrors(trans('auth.email.error.invalid'));
- }
- return Response::json(['status' => 'fail', 'message' => trans('auth.email.error.invalid')]);
- }
- break;
- default:
- if ($returnType) {
- return Redirect::back()->withErrors(trans('auth.email.error.invalid'));
- }
- return Response::json(['status' => 'fail', 'message' => trans('auth.email.error.invalid')]);
- }
- return false;
- }
- /**
- * 获取AFF.
- *
- * @param string|null $code 邀请码
- * @param int|null $aff URL中的aff参数
- *
- * @return array
- */
- private function getAff($code = null, $aff = null): array
- {
- $data = ['inviter_id' => null, 'code_id' => 0]; // 邀请人ID 与 邀请码ID
- // 有邀请码先用邀请码,用谁的邀请码就给谁返利
- if ($code) {
- $inviteCode = Invite::whereCode($code)->whereStatus(0)->first();
- if ($inviteCode) {
- $data['inviter_id'] = $inviteCode->inviter_id;
- $data['code_id'] = $inviteCode->id;
- }
- }
- // 没有用邀请码或者邀请码是管理员生成的,则检查cookie或者url链接
- if (! $data['inviter_id']) {
- // 检查一下cookie里有没有aff
- $cookieAff = \Request::hasCookie('register_aff');
- if ($cookieAff) {
- $data['inviter_id'] = User::find($cookieAff) ? $cookieAff : null;
- } elseif ($aff) { // 如果cookie里没有aff,就再检查一下请求的url里有没有aff,因为有些人的浏览器会禁用了cookie,比如chrome开了隐私模式
- $data['inviter_id'] = User::find($aff) ? $aff : null;
- }
- }
- return $data;
- }
- // 生成申请的请求地址
- private function addVerifyUrl($uid, $email)
- {
- $token = md5(sysConfig('website_name').$email.microtime());
- $verify = new Verify();
- $verify->user_id = $uid;
- $verify->token = $token;
- $verify->save();
- return $token;
- }
- // 重设密码页
- public function resetPassword(Request $request)
- {
- if ($request->isMethod('POST')) {
- // 校验请求
- $validator = Validator::make($request->all(), [
- 'email' => 'required|email|exists:user,email',
- ]);
- if ($validator->fails()) {
- return Redirect::back()->withInput()->withErrors($validator->errors());
- }
- $email = $request->input('email');
- // 是否开启重设密码
- if (! sysConfig('is_reset_password')) {
- return Redirect::back()->withErrors(trans('auth.password.reset.error.disabled', ['email' => sysConfig('webmaster_email')]));
- }
- // 查找账号
- $user = User::whereEmail($email)->first();
- // 24小时内重设密码次数限制
- $resetTimes = 0;
- if (Cache::has('resetPassword_'.md5($email))) {
- $resetTimes = Cache::get('resetPassword_'.md5($email));
- if ($resetTimes >= sysConfig('reset_password_times')) {
- return Redirect::back()->withErrors(trans('auth.password.reset.error.throttle', ['time' => sysConfig('reset_password_times')]));
- }
- }
- // 生成取回密码的地址
- $token = $this->addVerifyUrl($user->id, $email);
- // 发送邮件
- $resetPasswordUrl = route('resettingPasswd', $token);
- $logId = Helpers::addNotificationLog(trans('auth.password.reset.attribute'), trans('common.request_url').':'.$resetPasswordUrl, 1, $email);
- Mail::to($email)->send(new resetPassword($logId, $resetPasswordUrl));
- Cache::put('resetPassword_'.md5($email), $resetTimes + 1, Day);
- return Redirect::back()->with('successMsg', trans('auth.password.reset.sent'));
- }
- return view('auth.resetPassword');
- }
- // 重设密码
- public function reset(Request $request, $token)
- {
- if (! $token) {
- return Redirect::route('login');
- }
- if ($request->isMethod('POST')) {
- $validator = Validator::make($request->all(), [
- 'password' => 'required|min:6|confirmed',
- ]);
- if ($validator->fails()) {
- return Redirect::back()->withInput()->withErrors($validator->errors());
- }
- $password = $request->input('password');
- // 校验账号
- $verify = Verify::type(1)->whereToken($token)->firstOrFail();
- $user = $verify->user;
- if (! $verify) {
- return Redirect::route('login');
- }
- if ($user->status === -1) {
- return Redirect::back()->withErrors(trans('auth.error.account_baned'));
- }
- if ($verify->status === 1) {
- return Redirect::back()->withErrors(trans('auth.error.url_timeout'));
- }
- if (Hash::check($password, $verify->user->password)) {
- return Redirect::back()->withErrors(trans('auth.password.reset.error.same'));
- }
- // 更新密码
- if (! $user->update(['password' => $password])) {
- return Redirect::back()->withErrors(trans('auth.password.reset.error.failed'));
- }
- // 置为已使用
- $verify->status = 1;
- $verify->save();
- return Redirect::route('login')->with('successMsg', trans('auth.password.reset.success'));
- }
- $verify = Verify::type(1)->whereToken($token)->first();
- if (! $verify) {
- return Redirect::route('login');
- }
- if (time() - strtotime($verify->created_at) >= 1800) {
- // 置为已失效
- $verify->status = 2;
- $verify->save();
- }
- return view('auth.reset', ['verify' => Verify::type(1)->whereToken($token)->first()]); // 重新获取一遍verify
- }
- // 激活账号页
- public function activeUser(Request $request)
- {
- if ($request->isMethod('POST')) {
- $validator = Validator::make($request->all(), ['email' => 'required|email|exists:user,email']);
- if ($validator->fails()) {
- return Redirect::back()->withInput()->withErrors($validator->errors());
- }
- $email = $request->input('email');
- // 是否开启账号激活
- if (! sysConfig('is_activate_account')) {
- return Redirect::back()->withInput()->withErrors(trans('auth.active.error.disable'));
- }
- // 查找账号
- $user = User::whereEmail($email)->firstOrFail();
- if ($user->status === -1) {
- return Redirect::back()->withErrors(trans('auth.error.account_baned'));
- }
- if ($user->status === 1) {
- return Redirect::back()->withErrors(trans('auth.active.error.activated'));
- }
- // 24小时内激活次数限制
- $activeTimes = 0;
- if (Cache::has('activeUser_'.md5($email))) {
- $activeTimes = Cache::get('activeUser_'.md5($email));
- if ($activeTimes >= sysConfig('active_times')) {
- return Redirect::back()->withErrors(trans('auth.active.error.throttle', ['email' => sysConfig('webmaster_email')]));
- }
- }
- // 生成激活账号的地址
- $token = $this->addVerifyUrl($user->id, $email);
- // 发送邮件
- $activeUserUrl = route('activeAccount', $token);
- $logId = Helpers::addNotificationLog(trans('common.active_item', ['attribute' => trans('common.account')]), trans('common.request_url').':'.$activeUserUrl, 1, $email);
- Mail::to($email)->send(new activeUser($logId, $activeUserUrl));
- Cache::put('activeUser_'.md5($email), $activeTimes + 1, Day);
- return Redirect::back()->with('successMsg', trans('auth.active.sent'));
- }
- return view('auth.activeUser');
- }
- // 激活账号
- public function active($token)
- {
- if (! $token) {
- return Redirect::route('login');
- }
- $verify = Verify::type(1)->with('user')->whereToken($token)->firstOrFail();
- $user = $verify->user;
- if (! $verify) {
- return Redirect::route('login');
- }
- if (empty($user) || $verify->status > 0) {
- Session::flash('errorMsg', trans('auth.error.url_timeout'));
- return view('auth.active');
- }
- if ($user->status === 1) {
- Session::flash('errorMsg', trans('auth.active.error.activated'));
- return view('auth.active');
- }
- if (time() - strtotime($verify->created_at) >= 1800) {
- Session::flash('errorMsg', trans('auth.error.url_timeout'));
- // 置为已失效
- $verify->status = 2;
- $verify->save();
- return view('auth.active');
- }
- // 更新账号状态
- if (! $user->update(['status' => 1])) {
- Session::flash('errorMsg', trans('common.active_item', ['attribute' => trans('common.failed')]));
- return Redirect::back();
- }
- // 置为已使用
- $verify->status = 1;
- $verify->save();
- // 账号激活后给邀请人送流量
- $inviter = $user->inviter;
- if ($inviter) {
- $inviter->incrementData(sysConfig('referral_traffic') * MB);
- }
- Session::flash('successMsg', trans('common.active_item', ['attribute' => trans('common.success')]));
- return view('auth.active');
- }
- // 发送注册验证码
- public function sendCode(Request $request)
- {
- $validator = Validator::make($request->all(), ['email' => 'required|email|unique:user,email']);
- $email = $request->input('email');
- if ($validator->fails()) {
- return Response::json(['status' => 'fail', 'message' => $validator->getMessageBag()->first()]);
- }
- $ip = IP::getClientIP();
- // 校验域名邮箱黑白名单
- if (sysConfig('is_email_filtering')) {
- $result = $this->emailChecker($email);
- if ($result !== false) {
- return $result;
- }
- }
- // 是否开启注册发送验证码
- if ((int) sysConfig('is_activate_account') !== 1) {
- return Response::json(['status' => 'fail', 'message' => trans('auth.active.error.disable')]);
- }
- // 防刷机制
- if (Cache::has('send_verify_code_'.md5($ip))) {
- return Response::json(['status' => 'fail', 'message' => trans('auth.register.error.throttle')]);
- }
- // 发送邮件
- $code = Str::random(6);
- $logId = Helpers::addNotificationLog(trans('auth.register.code'), trans('auth.captcha.attribute').':'.$code, 1, $email);
- Mail::to($email)->send(new sendVerifyCode($logId, $code));
- VerifyCode::create(['address' => $email, 'code' => $code]); // 生成注册验证码
- Cache::put('send_verify_code_'.md5($ip), $ip, Minute);
- return Response::json(['status' => 'success', 'message' => trans('auth.captcha.sent')]);
- }
- // 公开的邀请码列表
- public function free()
- {
- return view('auth.free', ['inviteList' => Invite::whereInviterId(null)->whereStatus(0)->paginate()]);
- }
- // 切换语言
- public function switchLang(string $locale): RedirectResponse
- {
- Session::put('locale', $locale);
- return Redirect::back();
- }
- }
|