56 lines
1.6 KiB
PHP
56 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Config\Database;
|
|
|
|
class User
|
|
{
|
|
public static function findByUsername(string $username): ?array
|
|
{
|
|
$db = Database::getInstance();
|
|
$stmt = $db->prepare('SELECT * FROM users WHERE username = :username');
|
|
$stmt->execute(['username' => $username]);
|
|
$result = $stmt->fetch();
|
|
return $result ?: null;
|
|
}
|
|
|
|
public static function findById(int $id): ?array
|
|
{
|
|
$db = Database::getInstance();
|
|
$stmt = $db->prepare('SELECT * FROM users WHERE id = :id');
|
|
$stmt->execute(['id' => $id]);
|
|
$result = $stmt->fetch();
|
|
return $result ?: null;
|
|
}
|
|
|
|
public static function create(array $data): array
|
|
{
|
|
$db = Database::getInstance();
|
|
$stmt = $db->prepare('INSERT INTO users (username, password_hash, role) VALUES (:username, :password_hash, :role)');
|
|
$stmt->execute([
|
|
'username' => $data['username'],
|
|
'password_hash' => password_hash($data['password'], PASSWORD_DEFAULT),
|
|
'role' => $data['role'] ?? 'user',
|
|
]);
|
|
|
|
$user = self::findById((int) $db->lastInsertId());
|
|
unset($user['password_hash']);
|
|
return $user;
|
|
}
|
|
|
|
public static function verifyPassword(string $username, string $password): bool
|
|
{
|
|
$db = Database::getInstance();
|
|
$stmt = $db->prepare('SELECT password_hash FROM users WHERE username = :username');
|
|
$stmt->execute(['username' => $username]);
|
|
$result = $stmt->fetch();
|
|
|
|
if (!$result) {
|
|
return false;
|
|
}
|
|
|
|
return password_verify($password, $result['password_hash']);
|
|
}
|
|
}
|