Compare commits

..

7 Commits

16 changed files with 162 additions and 422 deletions

View File

@@ -1,89 +0,0 @@
<?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

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

View File

@@ -1,32 +0,0 @@
<?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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,89 +0,0 @@
<?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

@@ -14,6 +14,7 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Laravel\Passport\ClientRepository;
use Throwable; use Throwable;
class GatewayManagementController extends Controller class GatewayManagementController extends Controller
@@ -23,11 +24,11 @@ class GatewayManagementController extends Controller
public function index(Request $request) public function index(Request $request)
{ {
return DataTableFacade::run( return DataTableFacade::run(
UserGateway::query()->where('user_id', '=', Auth::guard('web')->id()), UserGateway::query()->where('user_id', '=', Auth::guard('web')->user()->id),
$request, $request,
allowedFilters: ['*'], allowedFilters: ['*'],
allowedSortings: ['*'], allowedSortings: ['*'],
allowedSelects: ['id', 'name', 'domain', 'tax_id', 'bank_name', 'account_holder', 'iban', 'business_type_id', 'business_type_name'], allowedSelects: ['*'],
); );
} }
@@ -38,9 +39,15 @@ class GatewayManagementController extends Controller
{ {
$user = Auth::guard('web')->user(); $user = Auth::guard('web')->user();
$logo = $request->has('logo') ? FileFacade::save($request->file('logo'), "{$user->id}") : null; $logo = $request->hasFile('logo')
? FileFacade::save($request->file('logo'), "{$user->id}")
: null;
$passportClient = DB::transaction(function () use ($user, $logo, $request) {
$clientName = "Gateway {$request->name} - User {$user->id}";
$client = app(ClientRepository::class)->createPasswordGrantClient($clientName, 'users');
DB::transaction(function () use ($user, $logo, $request) {
UserGateway::query()->create([ UserGateway::query()->create([
'user_id' => $user->id, 'user_id' => $user->id,
'username' => $user->username, 'username' => $user->username,
@@ -53,15 +60,20 @@ class GatewayManagementController extends Controller
'business_type_id' => $request->business_type_id, 'business_type_id' => $request->business_type_id,
'business_type_name' => BusinessTypeEnum::name($request->business_type_id), 'business_type_name' => BusinessTypeEnum::name($request->business_type_id),
'logo' => $logo, 'logo' => $logo,
'client_id' => $client->id,
'client_secret' => $client->secret,
]); ]);
$user->update(['authority_level' => 1]); $user->update(['authority_level' => 1]);
return $client;
}); });
return $this->successResponse([
return $this->successResponse(); 'client_id' => $passportClient->id,
'client_secret' => $passportClient->secret,
]);
} }
public function show(UserGateway $gateway): JsonResponse public function show(UserGateway $gateway): JsonResponse
{ {
return $this->successResponse($gateway); return $this->successResponse($gateway);

View File

@@ -133,6 +133,24 @@ return [
'level' => 'error', '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

@@ -1,30 +0,0 @@
<?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');
}
};

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::table('user_gateways', function (Blueprint $table) {
$table->string('client_id')->nullable();
$table->string('client_secret')->nullable();
$table->integer('status')->default(0);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('user_gateways', function (Blueprint $table) {
$table->dropColumn(['client_id', 'client_secret','status']);
});
}
};

View File

@@ -77,7 +77,7 @@ Route::prefix('expert')
Route::prefix('profile') Route::prefix('profile')
->name('profile.') ->name('profile.')
->middleware('auth') ->middleware('auth:expert')
->controller(ProfileController::class) ->controller(ProfileController::class)
->group(function () { ->group(function () {
Route::get('info', 'info')->name('info'); Route::get('info', 'info')->name('info');