52 lines
1.2 KiB
PHP
52 lines
1.2 KiB
PHP
<?php
|
|||
|
|
|
||
|
|
namespace Modules\Core\Auth\Services;
|
||
|
|
|
||
|
|
use Illuminate\Support\Facades\Mail;
|
||
|
|
use Modules\Core\Auth\Mail\OtpMail;
|
||
|
|
use Modules\Core\Auth\Models\Staff;
|
||
|
|
|
||
|
|
class OtpService
|
||
|
|
{
|
||
|
|
private const EXPIRY_MINUTES = 10;
|
||
|
|
private const CODE_LENGTH = 6;
|
||
|
|
|
||
|
|
public function generateAndSend(string $email): bool
|
||
|
|
{
|
||
|
|
$staff = Staff::where('email', $email)->first();
|
||
|
|
|
||
|
|
if (! $staff) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
$code = str_pad((string) random_int(0, 999999), self::CODE_LENGTH, '0', STR_PAD_LEFT);
|
||
|
|
|
||
|
|
$staff->otp_code = $code;
|
||
|
|
$staff->otp_expires_at = now()->addMinutes(self::EXPIRY_MINUTES);
|
||
|
|
$staff->save();
|
||
|
|
|
||
|
|
Mail::to($staff->email)->send(new OtpMail($staff->first_name, $code));
|
||
|
|
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function validate(string $email, string $code): ?Staff
|
||
|
|
{
|
||
|
|
$staff = Staff::where('email', $email)->first();
|
||
|
|
|
||
|
|
if (! $staff) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (! $staff->otp_expires_at || $staff->otp_code != $code || now()->isAfter($staff->otp_expires_at)) {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
$staff->otp_code = null;
|
||
|
|
$staff->otp_expires_at = null;
|
||
|
|
$staff->save();
|
||
|
|
|
||
|
|
return $staff;
|
||
|
|
}
|
||
|
|
}
|