112 lines
2.6 KiB
PHP
112 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Constants\Device;
|
|
use Illuminate\Auth\Authenticatable;
|
|
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
|
|
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\HasOne;
|
|
use Illuminate\Foundation\Auth\Access\Authorizable;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Laravel\Sanctum\HasApiTokens;
|
|
|
|
class User extends Model implements AuthorizableContract, AuthenticatableContract
|
|
{
|
|
use Authenticatable;
|
|
use Authorizable;
|
|
use HasFactory;
|
|
use HasApiTokens;
|
|
|
|
public const STATUS_FROZEN = -1; // 冻结
|
|
public const STATUS_INACTIVATED = 0; // 未激活
|
|
public const STATUS_ACTIVE = 1; // 正常
|
|
|
|
/**
|
|
* @var array
|
|
*/
|
|
protected $attributes = [
|
|
'status' => self::STATUS_ACTIVE,
|
|
];
|
|
|
|
/**
|
|
* @var array
|
|
*/
|
|
protected $fillable = [
|
|
'username',
|
|
'password',
|
|
'phone',
|
|
'phone_verified_at',
|
|
'email',
|
|
'email_verified_at',
|
|
'last_login_ip',
|
|
'last_login_at',
|
|
'register_ip',
|
|
'status',
|
|
'status_remark',
|
|
];
|
|
|
|
/**
|
|
* @var array
|
|
*/
|
|
protected $casts = [
|
|
'phone_verified_at' => 'datetime',
|
|
'email_verified_at' => 'datetime',
|
|
'last_login_at' => 'datetime',
|
|
'status' => 'int',
|
|
];
|
|
|
|
/**
|
|
* 属于此用户的个人信息
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\HasOne
|
|
*/
|
|
public function userInfo(): HasOne
|
|
{
|
|
return $this->hasOne(UserInfo::class);
|
|
}
|
|
|
|
/**
|
|
* 设置此用户的密码
|
|
*
|
|
* @param string $value
|
|
* @return void
|
|
*/
|
|
public function setPasswordAttribute($value): void
|
|
{
|
|
if ((string) $value === '') {
|
|
$value = null;
|
|
} elseif (Hash::needsRehash($value)) {
|
|
$value = Hash::make($value);
|
|
}
|
|
|
|
$this->attributes['password'] = $value;
|
|
}
|
|
|
|
/**
|
|
* 确认给定的密码是否正确
|
|
*
|
|
* @param string $password
|
|
* @return bool
|
|
*/
|
|
public function verifyPassword(string $password): bool
|
|
{
|
|
return $this->password && Hash::check($password, $this->password);
|
|
}
|
|
|
|
/**
|
|
* 创建设备授权令牌
|
|
*
|
|
* @param string $device
|
|
* @return array
|
|
*/
|
|
public function createDeviceToken(string $device = null): array
|
|
{
|
|
return [
|
|
'token' => $this->createToken($device ?: Device::PC)->plainTextToken,
|
|
];
|
|
}
|
|
}
|