初始化仓库及v1.0.0提交
This commit is contained in:
55
app/Models/User.php
Normal file
55
app/Models/User.php
Normal file
@@ -0,0 +1,55 @@
|
||||
<?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']);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user