| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <?php
- namespace App\Services;
- use App\Mail\PasswordResetCode;
- use App\Models\User;
- use App\Enums\UserTypeEnum;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Hash;
- use Illuminate\Support\Facades\Mail;
- use Carbon\Carbon;
- class PasswordResetService
- {
- private const CODE_TTL_MINUTES = 15;
- public function sendCode(string $email, string $tipo): bool
- {
- $user = User::where('email', $email)->first();
- if (!$user || $user->type->value !== $tipo) {
- return false;
- }
- $code = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
- DB::table('password_reset_tokens')->updateOrInsert(
- ['email' => $email],
- [
- 'token' => Hash::make($code),
- 'created_at' => Carbon::now(),
- ]
- );
- Mail::to($email)->send(new PasswordResetCode($code, $user->name));
- return true;
- }
- public function verifyCode(string $email, string $code): bool
- {
- $record = DB::table('password_reset_tokens')
- ->where('email', $email)
- ->first();
- if (!$record) {
- return false;
- }
- if (Carbon::parse($record->created_at)->addMinutes(self::CODE_TTL_MINUTES)->isPast()) {
- return false;
- }
- return Hash::check($code, $record->token);
- }
- public function resetPassword(string $email, string $code, string $password): ?User
- {
- if (!$this->verifyCode($email, $code)) {
- return null;
- }
- $user = User::where('email', $email)->first();
- if (!$user) {
- return null;
- }
- $user->update(['password' => Hash::make($password)]);
- DB::table('password_reset_tokens')->where('email', $email)->delete();
- return $user;
- }
- }
|