88 lines
2.8 KiB
PHP
88 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
|
use App\Notifications\ResetPasswordNotification;
|
|
use App\Support\TwoFactorVerification;
|
|
use Database\Factories\UserFactory;
|
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
|
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Illuminate\Foundation\Auth\User as Authenticatable;
|
|
use Illuminate\Notifications\Notifiable;
|
|
use Illuminate\Support\Facades\App;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Laravel\Passport\HasApiTokens;
|
|
use Spatie\Permission\Traits\HasRoles;
|
|
|
|
#[Fillable(['name', 'email', 'password', 'is_active', 'approved_at'])]
|
|
#[Hidden(['password', 'remember_token', 'two_factor_secret', 'two_factor_recovery_codes'])]
|
|
class User extends Authenticatable
|
|
{
|
|
/** @use HasFactory<UserFactory> */
|
|
use HasApiTokens, HasFactory, HasRoles, Notifiable, SoftDeletes;
|
|
|
|
/**
|
|
* Get the attributes that should be cast.
|
|
*
|
|
* @return array<string, string>
|
|
*/
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'email_verified_at' => 'datetime',
|
|
'password' => 'hashed',
|
|
'is_active' => 'boolean',
|
|
'deleted_at' => 'datetime',
|
|
'approved_at' => 'datetime',
|
|
'two_factor_secret' => 'encrypted',
|
|
'two_factor_recovery_codes' => 'encrypted:array',
|
|
'two_factor_confirmed_at' => 'datetime',
|
|
];
|
|
}
|
|
|
|
public function isPending(): bool
|
|
{
|
|
return $this->approved_at === null;
|
|
}
|
|
|
|
public function hasTwoFactorEnabled(): bool
|
|
{
|
|
return $this->two_factor_confirmed_at !== null;
|
|
}
|
|
|
|
/**
|
|
* Hook que reconoce Passport\Bridge\UserRepository para el Password Grant.
|
|
* Sin esto, POST /oauth/token con grant_type=password sólo chequeaba la
|
|
* contraseña — un bypass real de 2FA si el usuario lo tenía activo para
|
|
* el login de sesión. Con 2FA activo exige además un campo "otp" (código
|
|
* TOTP o de recuperación) en el mismo request.
|
|
*/
|
|
public function validateForPassportPasswordGrant(string $password): bool
|
|
{
|
|
if (! Hash::check($password, $this->password)) {
|
|
return false;
|
|
}
|
|
|
|
if (! $this->hasTwoFactorEnabled()) {
|
|
return true;
|
|
}
|
|
|
|
$otp = request()->input('otp');
|
|
|
|
return is_string($otp) && $otp !== '' && TwoFactorVerification::verify($this, $otp);
|
|
}
|
|
|
|
/**
|
|
* Override del notification default de Laravel (en inglés, sin plantilla
|
|
* propia) — manda el email en el idioma de la sesión que originó el
|
|
* pedido, ver App\Notifications\ResetPasswordNotification.
|
|
*/
|
|
public function sendPasswordResetNotification($token): void
|
|
{
|
|
$this->notify(new ResetPasswordNotification($token, App::getLocale()));
|
|
}
|
|
}
|