Spaces:
Running
Running
File size: 5,081 Bytes
907b200 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | <?php
namespace App\Services;
use App\Models\User;
use App\Notifications\SendOtpNotification;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
class OtpService
{
const OTP_EXPIRATION_MINUTES = 5;
/**
* Send OTP to user via email
*/
public function sendOtp(User $user, string $type): int
{
$otp = random_int(100000, 999999);
$columns = $this->getOtpColumns($type);
$user->{$columns['otp']} = $otp;
$user->{$columns['expires']} = now()->addMinutes(self::OTP_EXPIRATION_MINUTES);
$user->save();
try {
Log::info("Sending OTP to: {$user->email}, Type: {$type}, OTP: {$otp}");
$user->notify(new SendOtpNotification($otp, $type));
Log::info("OTP email sent successfully to: {$user->email}");
} catch (\Exception $e) {
Log::error("Failed to send OTP email: " . $e->getMessage());
throw $e;
}
return $otp;
}
/**
* Verify OTP and clear it from database
*
* @throws \Exception
*/
public function verifyOtp(User $user, string $type, string|int $otp): bool
{
$columns = $this->getOtpColumns($type);
if ((int) $user->{$columns['otp']} !== (int) $otp) {
throw new \Exception('Invalid OTP');
}
if ($user->{$columns['expires']} < now()) {
throw new \Exception('OTP expired');
}
$user->{$columns['otp']} = null;
$user->{$columns['expires']} = null;
$user->save();
return true;
}
/**
* Resend OTP with cooldown check
*
* @throws ValidationException|InvalidArgumentException
*/
public function resendOtp(User $user, string $type = 'email_verification'): string
{
if (!in_array($type, ['email_verification', 'password_reset'])) {
throw new InvalidArgumentException("Invalid OTP type: {$type}");
}
$otpExpiresField = $type === 'password_reset'
? 'password_reset_otp_expires_at'
: 'email_verification_otp_expires_at';
if ($type === 'email_verification' && $user->is_verified) {
throw ValidationException::withMessages([
'email' => 'Email already verified.'
]);
}
if ($user->$otpExpiresField && now()->lt($user->$otpExpiresField)) {
$secondsRemaining = now()->diffInSeconds($user->$otpExpiresField);
$timeText = $this->formatRemainingTime((int) $secondsRemaining);
throw ValidationException::withMessages([
'otp' => "Please wait {$timeText} before requesting a new OTP."
]);
}
$this->sendOtp($user, $type);
return $user->email;
}
/**
* Reset password using OTP
*
* @throws \Exception|ValidationException
*/
public function resetPasswordWithOtp(User $user, string $inputOtp, string $newPassword): void
{
$this->verifyOtp($user, 'password_reset', $inputOtp);
$user->update([
'password' => Hash::make($newPassword),
]);
}
/**
* Get database columns for OTP type
*
* @throws InvalidArgumentException
*/
private function getOtpColumns(string $type): array
{
return match ($type) {
'email_verification' => [
'otp' => 'email_verification_otp',
'expires' => 'email_verification_otp_expires_at',
],
'password_reset' => [
'otp' => 'password_reset_otp',
'expires' => 'password_reset_otp_expires_at',
],
default => throw new InvalidArgumentException("Invalid OTP type: {$type}"),
};
}
/**
* Check if user can resend OTP or still has active one
*
* @return array ['can_resend' => bool, 'remaining_seconds' => int|null]
*/
public function canResendOtp(User $user, string $type): array
{
$columns = $this->getOtpColumns($type);
$expiresField = $columns['expires'];
if (!$user->$expiresField || now()->gte($user->$expiresField)) {
return ['can_resend' => true, 'remaining_seconds' => null];
}
$remainingSeconds = now()->diffInSeconds($user->$expiresField);
return ['can_resend' => false, 'remaining_seconds' => $remainingSeconds];
}
/**
* Format remaining time to human readable string
*/
public function formatRemainingTime(int $seconds): string
{
if ($seconds >= 3600) {
$hours = ceil($seconds / 3600);
return "{$hours} " . ($hours === 1 ? 'hour' : 'hours');
}
if ($seconds >= 60) {
$minutes = ceil($seconds / 60);
return "{$minutes} " . ($minutes === 1 ? 'minute' : 'minutes');
}
$seconds = (int) $seconds;
return "{$seconds} " . ($seconds === 1 ? 'second' : 'seconds');
}
}
|