Files
core/src/Auth/Services/UserOtpService.php
T

49 lines
1.2 KiB
PHP
Raw Normal View History

<?php
namespace Modules\Core\Auth\Services;
use Illuminate\Support\Facades\Mail;
use Modules\Core\Auth\Mail\UserOtpMail;
class UserOtpService
{
private const EXPIRY_MINUTES = 10;
private const CODE_LENGTH = 6;
public function generateAndSend(string $email): bool
{
$model = config('auth.providers.users.model');
$user = $model::firstOrCreate(['email' => $email]);
$code = str_pad((string) random_int(0, 999999), self::CODE_LENGTH, '0', STR_PAD_LEFT);
$user->otp_code = $code;
$user->otp_expires_at = now()->addMinutes(self::EXPIRY_MINUTES);
$user->save();
Mail::to($user->email)->send(new UserOtpMail($user->name ?? $user->email, $code));
return true;
}
public function validate(string $email, string $code)
{
$model = config('auth.providers.users.model');
$user = $model::where('email', $email)->first();
if (! $user) {
return null;
}
if (! $user->otp_expires_at || $user->otp_code != $code || now()->isAfter($user->otp_expires_at)) {
return null;
}
$user->otp_code = null;
$user->otp_expires_at = null;
$user->save();
return $user;
}
}