This commit is contained in:
2025-10-22 20:08:22 +05:00
commit 736e3bef18
2573 changed files with 120385 additions and 0 deletions

View File

@@ -0,0 +1,184 @@
<?php
namespace App\Modules\BaseAuth\Controllers;
use App\Models\User;
use App\Modules\BaseLocale\Middleware\SetLocale;
use Illuminate\Contracts\View\View;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class LoginController extends Controller
{
use AuthenticatesUsers, ValidatesRequests;
/**
* Middleware
*/
public function __construct()
{
$middleware = [];
if (module('BaseLocale')->isEnabled()) {
array_push($middleware, SetLocale::class);
}
$this->middleware($middleware)->except('logout');
}
/**
* Get the login username to be used by the controller, also send via request.
*/
public function username(): string
{
return config()->string('module.base-auth.default_username');
}
/**
* Supports multiple usernames
*/
public function supportsMultipleUsernames(): bool
{
return config()->boolean('module.base-auth.multiple_usernames');
}
/**
* Supports multiple usernames
*
* @return array<int, string>
*/
public function usernames(): array
{
/** @var array<int, string> */
$usernames = config()->array('module.base-auth.usernames');
return $usernames;
}
/**
* Show the application's login form.
*/
public function showLoginForm(): View
{
return view('module.base-auth::pages.login');
}
/**
* The user has been authenticated.
*/
protected function authenticated(Request $request, User $user): JsonResponse|RedirectResponse
{
$redirect = redirect()->intended($this->redirectPath());
return $request->wantsJson()
? new JsonResponse([
'redirect' => $redirect->getTargetUrl(),
], 200)
: $redirect;
}
/**
* Log the user out of the application.
*/
public function logout(Request $request): RedirectResponse
{
$this->guard()->logout();
$request->session()->invalidate();
return redirect()->intended($this->redirectPath());
}
/**
* Get the post register / login redirect path.
*/
public function redirectPath(): string
{
return config()->string('module.base-auth.redirect_path');
}
/**
* Validate the user login request.
*
*
* @throws \Illuminate\Validation\ValidationException
*/
protected function validateLogin(Request $request): void
{
$request->validate([
$this->username() => ['required', 'string', 'max:250'],
'password' => ['required', 'string', 'max:250'],
]);
}
/**
* Handle a login request to the application.
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
*
* @throws \Illuminate\Validation\ValidationException
*/
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if (method_exists($this, 'hasTooManyLoginAttempts') && $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$user = User::query()
->when($this->supportsMultipleUsernames(), function ($query) use ($request) {
foreach ($this->usernames() as $username) {
$query->orWhere($username, $request->username);
}
}, function ($query) use ($request) {
$query->where($this->username(), $request->username);
})
->first();
if (! $user) {
return $this->sendFailedLoginResponse($request);
}
if (Hash::check($request->string('password'), $user->password)) {
Auth::login($user);
if ($request->hasSession()) {
$request->session()->put('auth.password_confirmed_at', time());
}
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
/**
* Send the response after the user was authenticated.
*/
protected function sendLoginResponse(Request $request): RedirectResponse|JsonResponse
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user()); // @phpstan-ignore-line
}
}

View File

@@ -0,0 +1,173 @@
<?php
namespace App\Modules\BaseAuth\Controllers;
use App\Http\Controllers\Controller;
use App\Models\System\Verification;
use App\Models\User;
use App\Modules\BaseAuth\Models\AuthEvent;
use App\Modules\BaseLocale\Middleware\SetLocale;
use App\Modules\OtpVerification\Rules\OtpVerificationRule;
use App\Modules\PhoneNumberVerification\Rules\PhoneNumberVerificationRule;
use Illuminate\Auth\Events\Registered;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/**
* Middleware
*/
public function __construct()
{
$middleware = [];
if (module('BaseLocale')->isEnabled()) {
array_push($middleware, SetLocale::class);
}
$this->middleware($middleware)->except('logout');
}
/**
* Show registration page
*/
public function showNovaRegisterpageForm(): View
{
return view('module.base-auth::pages.register');
}
/**
* Handle a registration request for the application.
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
public function register(Request $request)
{
if ($request->has('phone')) {
$request->merge([
'phone' => unMaskTurkmenNumber($request->string('phone')),
]);
}
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
Auth::guard()->login($user);
if (config('module.base-auth.store_auth_events')) {
storeAuthEvent(AuthEvent::REGISTER, $request);
}
if (config('module.base-auth.sms_verification')) {
sendSMSVerification((string) $user->phone);
return response()->json([
'url' => route('sms-verification'),
]);
}
return response()->json([
'url' => config('module.base-auth.redirect_path'),
]);
}
/**
* Get a validator for an incoming registration request.
*
* @param array<string, int|string> $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'phone' => ['required', new PhoneNumberVerificationRule, 'unique:users,phone'],
'username' => ['required', 'string', 'alpha_dash:ascii', 'max:255', 'unique:users,username'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array<string, int|string> $data
* @return \App\Models\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'phone' => $data['phone'],
'username' => $data['username'],
'password' => Hash::make((string) $data['password']),
'must_fill_profile' => true,
]);
return $user;
}
/**
* Sms verification
*/
public function smsVerification(): View
{
return view('module.base-auth::pages.sms-verification', ['phone' => Auth::user()?->phone]);
}
/**
* Change users phone number
*/
public function changePhone(Request $request): JsonResponse
{
if ($request->has('phone')) {
$request->merge(['phone' => unMaskTurkmenNumber($request->string('phone'))]);
}
$request->validate([
'phone' => ['required', new PhoneNumberVerificationRule, 'unique:users,phone'],
]);
/** @var User */
$user = Auth::user();
$user->update([
'phone' => $request->phone,
]);
storeAuthEvent(AuthEvent::PHONE_CHANGED, $request);
sendSMSVerification((string) $user->phone);
return response()->json([
'url' => route('sms-verification'),
]);
}
/**
* Verify sms code
*/
public function verifySmsCode(Request $request): RedirectResponse
{
/** @var User */
$user = Auth::user();
$request->validate([
'code' => ['bail', 'required', 'integer', new OtpVerificationRule($user->phone)],
]);
$user->update([
'phone_verified_at' => now(),
]);
storeAuthEvent(AuthEvent::PHONE_VERIFICATION, $request);
return redirect(config()->string('module.base-auth.redirect_path'));
}
}

View File

@@ -0,0 +1,110 @@
<?php
namespace App\Modules\BaseAuth\Controllers;
use App\Http\Controllers\Controller;
use App\Models\System\Verification;
use App\Models\User;
use App\Modules\BaseAuth\Models\AuthEvent;
use App\Modules\OtpVerification\Models\OtpVerification;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
class ResetPasswordController extends Controller
{
/**
* Reset password page
*/
public function index(): View
{
return view('module.base-auth::pages.reset-password');
}
/**
* Store new password
*/
public function store(Request $request): JsonResponse
{
$request->validate([
'username' => ['required', 'string', 'max:250', 'exists:users,username'],
'verification' => ['nullable', 'integer', Rule::requiredIf(fn () => $request->filled('step-verification'))],
'step-sms' => ['nullable'],
'step-verification' => ['nullable'],
'step-password' => ['nullable'],
'password' => ['bail', 'nullable', 'string', 'min:8', 'confirmed', Rule::requiredIf(fn () => $request->filled('step-password'))],
]);
/** @var User */
$user = User::where('username', $request->username)->first();
if ($request->filled('step-sms') && $request->isNotFilled('step-verification') && $request->isNotFilled('step-password')) {
return $this->sendVerification($request, $user);
}
if ($request->filled('step-verification') && $request->isNotFilled('step-password')) {
return $this->verify($request, $user);
}
if ($request->filled('step-password')) {
return $this->updatePassword($request, $user);
}
return response()->json();
}
/**
* Send verification code
*/
public function sendVerification(Request $request, User $user): JsonResponse
{
sendSMSVerification((string) $user->phone);
return response()->json([
'step' => 1,
'message' => __('We send you a verification code to').' ****'.substr((string) $user->phone, 4),
]);
}
/**
* Verify phone number
*/
public function verify(Request $request, User $user): JsonResponse
{
$verification = OtpVerification::where('username', $user->phone)
->where('code', $request->verification)
->first();
if (! $verification) {
return response()->json([
'errors' => [
'verification' => [
__('Incorrect verification code'),
],
],
'message' => __('Incorrect verification code'),
]);
}
return response()->json([
'step' => 2,
'message' => __("Now you can set your password, but please make sure that you don't forget it!"),
]);
}
/**
* Update password
*/
public function updatePassword(Request $request, User $user): JsonResponse
{
$user->update(['password' => bcrypt($request->string('password'))]);
storeAuthEvent(AuthEvent::PASSWORD_RESET, request());
return response()->json([
'step' => 3,
'message' => __('Your password has been updated'),
]);
}
}