91 lines
2.6 KiB
PHP
91 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use CodeIgniter\Model;
|
|
|
|
class UserModel extends Model
|
|
{
|
|
protected $table = 'users';
|
|
protected $primaryKey = 'id';
|
|
protected $useAutoIncrement = true;
|
|
protected $returnType = 'array';
|
|
protected $useSoftDeletes = true;
|
|
protected $protectFields = true;
|
|
protected $allowedFields = [
|
|
'name',
|
|
'email',
|
|
'password',
|
|
'avatar',
|
|
'role',
|
|
'email_verified',
|
|
'verify_token',
|
|
'reset_token',
|
|
'reset_token_expiry',
|
|
'api_token',
|
|
'is_active',
|
|
'last_login_at',
|
|
'theme_preference',
|
|
];
|
|
|
|
protected bool $allowEmptyInserts = false;
|
|
protected bool $updateOnlyChanged = true;
|
|
|
|
protected array $casts = [];
|
|
protected array $castHandlers = [];
|
|
|
|
// Dates
|
|
protected $useTimestamps = true;
|
|
protected $dateFormat = 'datetime';
|
|
protected $createdField = 'created_at';
|
|
protected $updatedField = 'updated_at';
|
|
protected $deletedField = 'deleted_at';
|
|
|
|
// Validation
|
|
protected $validationRules = [
|
|
'name' => 'required|min_length[3]|max_length[150]',
|
|
'email' => 'required|valid_email|max_length[255]|is_unique[users.email,id,{id}]',
|
|
'password' => 'permit_empty|min_length[8]|max_length[255]',
|
|
'role' => 'permit_empty|in_list[superadmin,user]',
|
|
];
|
|
protected $validationMessages = [];
|
|
protected $skipValidation = false;
|
|
protected $cleanValidationRules = true;
|
|
|
|
// Callbacks
|
|
protected $allowCallbacks = true;
|
|
protected $beforeInsert = ['hashPassword'];
|
|
protected $afterInsert = [];
|
|
protected $beforeUpdate = ['hashPassword'];
|
|
protected $afterUpdate = [];
|
|
protected $beforeFind = [];
|
|
protected $afterFind = [];
|
|
protected $beforeDelete = [];
|
|
protected $afterDelete = [];
|
|
|
|
public function findByEmail(string $email): ?array
|
|
{
|
|
return $this->where('email', $email)->first();
|
|
}
|
|
|
|
public function findByApiToken(string $token): ?array
|
|
{
|
|
return $this->where('api_token', hash('sha256', $token))->first();
|
|
}
|
|
|
|
protected function hashPassword(array $data): array
|
|
{
|
|
if (! isset($data['data']['password']) || $data['data']['password'] === '') {
|
|
return $data;
|
|
}
|
|
|
|
$info = password_get_info((string) $data['data']['password']);
|
|
if ($info['algo'] !== null) {
|
|
return $data;
|
|
}
|
|
|
|
$data['data']['password'] = password_hash((string) $data['data']['password'], PASSWORD_DEFAULT);
|
|
return $data;
|
|
}
|
|
}
|