Compare commits

..

1 Commits

Author SHA1 Message Date
99d24c38c7 create forgote password 2026-06-01 13:43:16 +03:30
14 changed files with 415 additions and 113 deletions

View File

@@ -0,0 +1,89 @@
<?php
namespace App\Admin\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\Auth\PasswordResetOtpService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Validation\ValidationException;
class ForgotPasswordOtpController extends Controller
{
public function __construct(
private readonly PasswordResetOtpService $otpService
) {}
public function sendOtp(Request $request): JsonResponse
{
$validated = $request->validate([
'email' => ['required', 'email', 'exists:users,email'],
]);
$email = $validated['email'];
$key = 'user-forgot-password-otp:' . $email . ':' . $request->ip();
if (RateLimiter::tooManyAttempts($key, 3)) {
throw ValidationException::withMessages([
'email' => ['Too many OTP requests. Please try again later.'],
]);
}
RateLimiter::hit($key, 600);
$user = User::query()->where('email', $email)->firstOrFail();
$this->otpService->sendOtp($user, 'user');
return response()->json([
'message' => 'OTP sent to your email.',
]);
}
public function verifyOtp(Request $request): JsonResponse
{
$validated = $request->validate([
'email' => ['required', 'email', 'exists:users,email'],
'otp' => ['required', 'digits:6'],
]);
$this->otpService->verifyOtp(
email: $validated['email'],
otp: $validated['otp'],
guard: 'user'
);
return response()->json([
'message' => 'OTP verified successfully.',
]);
}
public function resetPassword(Request $request): JsonResponse
{
$validated = $request->validate([
'email' => ['required', 'email', 'exists:users,email'],
'password' => ['required', 'confirmed',],
]);
$record = $this->otpService->ensureVerified(
email: $validated['email'],
guard: 'user'
);
$user = User::query()->where('email', $validated['email'])->firstOrFail();
$user->update([
'password' => Hash::make($validated['password']),
]);
$record->delete();
return response()->json([
'message' => 'User password reset successfully.',
]);
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class PasswordResetOtp extends Model
{
protected $guarded = ['id'];
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class ResetPasswordOtpNotification extends Notification
{
use Queueable;
public function __construct(
private readonly string $otp
) {}
public function via(object $notifiable): array
{
return ['mail'];
}
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject('Reset Password OTP')
->greeting('Hello!')
->line('Your password reset code is:')
->line($this->otp)
->line('This code will expire in 10 minutes.')
->line('If you did not request password reset, ignore this email.');
}
}

View File

@@ -0,0 +1,103 @@
<?php
namespace App\Services\Auth;
use App\Models\PasswordResetOtp;
use App\Notifications\ResetPasswordOtpNotification;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class PasswordResetOtpService
{
public function sendOtp(Model $user, string $guard = 'user'): void
{
$otp = (string) random_int(100000, 999999);
PasswordResetOtp::query()->where('email', $user->email)
->where('guard', $guard)
->delete();
PasswordResetOtp::query()->create([
'email' => $user->email,
'guard' => $guard,
'otp' => Hash::make($otp),
'expires_at' => now()->addMinutes(10),
]);
$user->notify(new ResetPasswordOtpNotification($otp));
}
public function verifyOtp(string $email, string $otp, string $guard = 'user'): void
{
$record = PasswordResetOtp::query()->where('email', $email)
->where('guard', $guard)
->latest()
->first();
if (! $record) {
throw ValidationException::withMessages([
'otp' => ['Invalid OTP.'],
]);
}
if ($record->isExpired()) {
$record->delete();
throw ValidationException::withMessages([
'otp' => ['OTP has expired.'],
]);
}
if ($record->attempts >= 5) {
$record->delete();
throw ValidationException::withMessages([
'otp' => ['Too many wrong attempts. Please request a new OTP.'],
]);
}
if (! Hash::check($otp, $record->otp)) {
$record->increment('attempts');
throw ValidationException::withMessages([
'otp' => ['Invalid OTP.'],
]);
}
$record->update([
'verified_at' => now(),
]);
}
public function ensureVerified(string $email, string $guard = 'user'): PasswordResetOtp
{
$record = PasswordResetOtp::query()->where('email', $email)
->where('guard', $guard)
->latest()
->first();
if (! $record || ! $record->isVerified()) {
throw ValidationException::withMessages([
'otp' => ['Please verify OTP first.'],
]);
}
if ($record->isExpired()) {
$record->delete();
throw ValidationException::withMessages([
'otp' => ['OTP has expired.'],
]);
}
return $record;
}
public function deleteOtp(string $email, string $guard = 'user'): void
{
PasswordResetOtp::query()->where('email', $email)
->where('guard', $guard)
->delete();
}
}

View File

@@ -11,13 +11,21 @@ class CancelPaymentService
{
protected string $url;
protected string $channelName;
protected AuthorizationService $authorizationService;
protected string $accessToken;
protected array $headers;
public function __construct(AuthorizationService $authorizationService)
public function __construct()
{
$this->url = config('fib.cancelPayment.url');
$this->channelName = '';
$this->authorizationService = $authorizationService;
}
public function setHeaders(): void
{
$this->headers = [
'Authorization' => 'Bearer ' . $this->accessToken,
'Content-Type' => 'application/json',
];
}
/**
@@ -42,26 +50,13 @@ class CancelPaymentService
/**
* @throws ConnectionException
* @throws Exception
*/
public function sendRequest(): array
{
return Http::withHeaders([
'Authorization' => 'Bearer ' . $this->getToken(),
'Content-Type' => 'application/json',
])
return Http::withHeaders($this->headers)
->throw()
->withoutVerifying()
->post($this->url)
->json();
}
/**
* @throws Exception
*/
public function getToken(): string
{
$data = $this->authorizationService->run();
return $data['access_token'];
}
}

View File

@@ -11,13 +11,11 @@ class CheckPaymentStatusService
{
protected string $url;
protected string $channelName;
protected AuthorizationService $authorizationService;
public function __construct(AuthorizationService $authorizationService)
public function __construct()
{
$this->url = config('fib.checkPaymentStatus.url');
$this->channelName = 'fib_status';
$this->authorizationService = $authorizationService;
$this->channelName = '';
}
/**
@@ -42,26 +40,12 @@ class CheckPaymentStatusService
/**
* @throws ConnectionException
* @throws Exception
*/
public function sendRequest(): array
{
return Http::withHeaders([
'Authorization' => 'Bearer ' . $this->getToken(),
'Content-Type' => 'application/json',
])
->throw()
return Http::throw()
->withoutVerifying()
->post($this->url)
->json();
}
/**
* @throws Exception
*/
public function getToken(): string
{
$data = $this->authorizationService->run();
return $data['access_token'];
}
}

View File

@@ -11,14 +11,27 @@ class CreatePaymentService
{
protected string $url;
protected string $channelName;
protected string $accessToken;
protected array $headers;
protected array $inputParameters;
protected AuthorizationService $authorizationService;
public function __construct(AuthorizationService $authorizationService)
public function __construct()
{
$this->url = config('fib.createPayment.url');
$this->channelName = 'fib_create_payment';
$this->authorizationService = $authorizationService;
$this->channelName = '';
}
public function setAccessToken(string $accessToken): void
{
$this->accessToken = $accessToken;
}
public function setHeaders(): void
{
$this->headers = [
'Authorization' => 'Bearer ' . $this->accessToken,
'Content-Type' => 'application/json',
];
}
public function setInputParameters(array $inputParameters): void
@@ -48,26 +61,13 @@ class CreatePaymentService
/**
* @throws ConnectionException
* @throws Exception
*/
public function sendRequest(): array
{
return Http::withHeaders([
'Authorization' => 'Bearer ' . $this->getToken(),
'Content-Type' => 'application/json',
])
return Http::withHeaders($this->headers)
->throw()
->withoutVerifying()
->post($this->url, $this->inputParameters)
->json();
}
/**
* @throws Exception
*/
public function getToken(): string
{
$data = $this->authorizationService->run();
return $data['access_token'];
}
}

View File

@@ -11,13 +11,21 @@ class RefundService
{
protected string $url;
protected string $channelName;
protected AuthorizationService $authorizationService;
protected string $accessToken;
protected array $headers;
public function __construct(AuthorizationService $authorizationService)
public function __construct()
{
$this->url = config('fib.refund.url');
$this->channelName = 'fib_refund';
$this->authorizationService = $authorizationService;
$this->channelName = '';
}
public function setHeaders(): void
{
$this->headers = [
'Authorization' => 'Bearer ' . $this->accessToken,
'Content-Type' => 'application/json',
];
}
/**
@@ -42,26 +50,13 @@ class RefundService
/**
* @throws ConnectionException
* @throws Exception
*/
public function sendRequest(): array
{
return Http::withHeaders([
'Authorization' => 'Bearer ' . $this->getToken(),
'Content-Type' => 'application/json',
])
return Http::withHeaders($this->headers)
->throw()
->withoutVerifying()
->post($this->url)
->json();
}
/**
* @throws Exception
*/
public function getToken(): string
{
$data = $this->authorizationService->run();
return $data['access_token'];
}
}

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Services\FIB\DTO;
namespace App\Services\Payments\DTO;
class FIBPaymentCreateDTO
{

View File

@@ -6,30 +6,22 @@ use App\Enums\PaymentStatusEnum;
use App\Models\FibTransaction;
use App\Models\Payment;
use App\Models\Transaction;
use App\Services\FIB\CreatePaymentService;
use App\Services\FIB\DTO\FIBPaymentCreateDTO;
use App\Services\FIB\FIBClient;
use App\Services\Payments\DTO\FIBPaymentCreateDTO;
use App\Services\Payments\DTO\PaymentCreateDTO;
use Exception;
use Illuminate\Support\Facades\DB;
use Throwable;
class PaymentService
{
protected CreatePaymentService $create_payment_service;
public $fib_client;
public function __construct(CreatePaymentService $create_payment_service)
public function __construct()
{
$this->create_payment_service = $create_payment_service;
$this->fib_client = new FibClient();
}
/**
* @throws Exception
* @throws Throwable
*/
public function createPayment(PaymentCreateDTO $dto)
{
return DB::transaction(function () use ($dto) {
try {
$payment = Payment::query()->create([
'user_id' => $dto->user_id,
'username' => $dto->username,
@@ -43,7 +35,7 @@ class PaymentService
'user_gateway_id' => $dto->user_gateway_id,
]);
$response = $this->create_payment_service->run();
$response = $this->fib_client->createPaymentService();
$fib_response_dto = FIBPaymentCreateDTO::fromResponse($response);
$transaction = Transaction::query()->create([
@@ -51,15 +43,15 @@ class PaymentService
'amount' => $payment->amount,
'currency' => $payment->currency,
'callback_url' => $payment->callback_url,
// 'description' => '',
// 'expires_in' => '',
// 'description' => '',
// 'expires_in' => '',
'payment_id' => $payment->id,
'payment_track_id' => $payment->track_id,
'user_gateway_id' => $payment->user_gateway_id,
// 'status' => '',
// 'status' => '',
]);
FibTransaction::query()->create([
$fib_transactions = FibTransaction::query()->create([
'transaction_id' => $transaction->id,
'qrcode' => $fib_response_dto->qrCode,
'readable_code' => $fib_response_dto->readableCode,
@@ -72,8 +64,9 @@ class PaymentService
'status_id' => PaymentStatusEnum::Unpaid->value,
'status_name' => PaymentStatusEnum::Unpaid->name,
]);
return $payment;
});
} catch (\Exception $exception) {
throw new \Exception($exception->getMessage());
}
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace App\User\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Expert;
use Illuminate\Http\Request;
use App\Services\Auth\PasswordResetOtpService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Validation\ValidationException;
class ForgotPasswordOtpController extends Controller
{
public function __construct(
private readonly PasswordResetOtpService $otpService
) {}
public function sendOtp(Request $request): JsonResponse
{
$validated = $request->validate([
'email' => ['required', 'email', 'exists:experts,email'],
]);
$email = $validated['email'];
$key = 'expert-forgot-password-otp:' . $email . ':' . $request->ip();
if (RateLimiter::tooManyAttempts($key, 3)) {
throw ValidationException::withMessages([
'email' => ['Too many OTP requests. Please try again later.'],
]);
}
RateLimiter::hit($key, 600);
$expert = Expert::query()->where('email', $email)->firstOrFail();
$this->otpService->sendOtp($expert, 'expert');
return response()->json([
'message' => 'OTP sent to your email.',
]);
}
public function verifyOtp(Request $request): JsonResponse
{
$validated = $request->validate([
'email' => ['required', 'email', 'exists:experts,email'],
'otp' => ['required', 'digits:6'],
]);
$this->otpService->verifyOtp(
email: $validated['email'],
otp: $validated['otp'],
guard: 'expert'
);
return response()->json([
'message' => 'OTP verified successfully.',
]);
}
public function resetPassword(Request $request): JsonResponse
{
$validated = $request->validate([
'email' => ['required', 'email', 'exists:experts,email'],
'password' => ['required', 'confirmed'],
]);
$record = $this->otpService->ensureVerified(
email: $validated['email'],
guard: 'expert'
);
$expert = Expert::query()->where('email', $validated['email'])->firstOrFail();
$expert->update([
'password' => Hash::make($validated['password']),
]);
$record->delete();
return response()->json([
'message' => 'Expert password reset successfully.',
]);
}
}

View File

@@ -23,7 +23,7 @@ class GatewayManagementController extends Controller
public function index(Request $request)
{
return DataTableFacade::run(
UserGateway::query()->where('user_id', '=', Auth::guard('web')->user()->id),
UserGateway::query()->where('user_id', '=', Auth::guard('web')->id()),
$request,
allowedFilters: ['*'],
allowedSortings: ['*'],

View File

@@ -133,24 +133,6 @@ return [
'level' => 'error',
],
'fib_create_payment' => [
'driver' => 'single',
'path' => storage_path('logs/fib/createPayment.log'),
'level' => 'error',
],
'fib_status' => [
'driver' => 'single',
'path' => storage_path('logs/fib/status.log'),
'level' => 'error',
],
'fib_refund' => [
'driver' => 'single',
'path' => storage_path('logs/fib/refund.log'),
'level' => 'error',
],
],
];

View File

@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('password_reset_otps', function (Blueprint $table) {
$table->id();
$table->string('email')->index();
$table->string('otp');
$table->string('guard_name');
$table->timestamp('expires_at');
$table->timestamp('verified_at')->nullable();
$table->unsignedTinyInteger('attempts')->default(0);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('password_reset_otps');
}
};