43 lines
850 B
PHP
43 lines
850 B
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Exceptions\UserNotFoundException;
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Session;
|
|
|
|
class OTPService
|
|
{
|
|
public function generate(User $user, int $length = 6): string
|
|
{
|
|
$code = \Str::random($length);
|
|
|
|
Cache::put("otp_$user->id", $code, now()->addMinutes(10));
|
|
Session::put('user_id', $user->id);
|
|
|
|
return $code;
|
|
}
|
|
|
|
/**
|
|
* @throws \Exception
|
|
*/
|
|
public function verify(string $otp): bool
|
|
{
|
|
$user = User::find(Session::get('user_id'));
|
|
|
|
if (! $user) {
|
|
throw new UserNotFoundException('User not found');
|
|
}
|
|
|
|
$code = Cache::get("otp_$user->id");
|
|
if ($code === $otp) {
|
|
Cache::forget("otp_$user->id");
|
|
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|