2
0
Web/auth/providers/MysqlUserProvider.php
2025-09-10 21:57:44 -05:00

205 lines
6.4 KiB
PHP

<?php
require_once __DIR__ . '/../UserProviderInterface.php';
require_once __DIR__ . '/../User.php';
/**
* MysqlUserProvider stores users in MySQL database
*/
class MysqlUserProvider implements UserProviderInterface
{
private PDO $db;
private string $table;
public function __construct(array $config, string $table = 'users')
{
$this->table = $table;
$dsn = sprintf(
'mysql:host=%s;port=%s;dbname=%s;charset=%s',
$config['host'] ?? 'localhost',
$config['port'] ?? 3306,
$config['database'],
$config['charset'] ?? 'utf8mb4'
);
try {
$this->db = new PDO(
$dsn,
$config['username'],
$config['password'],
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
]
);
$this->createTable();
} catch (PDOException $e) {
throw new Exception("Failed to connect to MySQL database: " . $e->getMessage());
}
}
/**
* Create users table if it doesn't exist
*/
private function createTable(): void
{
$sql = "CREATE TABLE IF NOT EXISTS {$this->table} (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) UNIQUE,
email VARCHAR(255) UNIQUE,
password VARCHAR(255) NOT NULL,
remember_token VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
attributes JSON,
INDEX idx_email (email),
INDEX idx_username (username),
INDEX idx_remember_token (remember_token)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
$this->db->exec($sql);
}
/**
* Map database row to User object
*/
private function mapToUser(array $row): User
{
$attributes = isset($row['attributes']) ? json_decode($row['attributes'], true) ?? [] : [];
return new User([
'id' => $row['id'],
'username' => $row['username'],
'email' => $row['email'],
'password' => $row['password'],
'rememberToken' => $row['remember_token'],
'createdAt' => $row['created_at'],
'updatedAt' => $row['updated_at'],
'attributes' => $attributes
]);
}
public function findById(int|string $id): ?User
{
$stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE id = :id");
$stmt->execute(['id' => $id]);
$row = $stmt->fetch();
return $row ? $this->mapToUser($row) : null;
}
public function findByEmail(string $email): ?User
{
$stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE email = :email");
$stmt->execute(['email' => $email]);
$row = $stmt->fetch();
return $row ? $this->mapToUser($row) : null;
}
public function findByUsername(string $username): ?User
{
$stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE username = :username");
$stmt->execute(['username' => $username]);
$row = $stmt->fetch();
return $row ? $this->mapToUser($row) : null;
}
public function findByCredentials(string $identifier): ?User
{
$stmt = $this->db->prepare(
"SELECT * FROM {$this->table} WHERE email = :identifier OR username = :identifier"
);
$stmt->execute(['identifier' => $identifier]);
$row = $stmt->fetch();
return $row ? $this->mapToUser($row) : null;
}
public function findByRememberToken(string $token): ?User
{
$stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE remember_token = :token");
$stmt->execute(['token' => $token]);
$row = $stmt->fetch();
return $row ? $this->mapToUser($row) : null;
}
public function create(array $data): User
{
$attributes = $data['attributes'] ?? [];
unset($data['attributes']);
$stmt = $this->db->prepare(
"INSERT INTO {$this->table} (username, email, password, remember_token, attributes)
VALUES (:username, :email, :password, :remember_token, :attributes)"
);
$stmt->execute([
'username' => $data['username'] ?? null,
'email' => $data['email'] ?? null,
'password' => $data['password'],
'remember_token' => $data['remember_token'] ?? null,
'attributes' => json_encode($attributes)
]);
$data['id'] = $this->db->lastInsertId();
$data['attributes'] = $attributes;
// Fetch created/updated timestamps
$user = $this->findById($data['id']);
return $user;
}
public function update(User $user, array $data): bool
{
$attributes = array_merge($user->attributes, $data['attributes'] ?? []);
unset($data['attributes']);
$fields = [];
$params = ['id' => $user->id];
foreach (['username', 'email', 'password'] as $field) {
if (isset($data[$field])) {
$fields[] = "$field = :$field";
$params[$field] = $data[$field];
$user->$field = $data[$field];
}
}
if (!empty($attributes)) {
$fields[] = "attributes = :attributes";
$params['attributes'] = json_encode($attributes);
$user->attributes = $attributes;
}
if (empty($fields)) {
return true;
}
$sql = "UPDATE {$this->table} SET " . implode(', ', $fields) . " WHERE id = :id";
$stmt = $this->db->prepare($sql);
return $stmt->execute($params);
}
public function updateRememberToken(User $user, ?string $token): bool
{
$stmt = $this->db->prepare(
"UPDATE {$this->table} SET remember_token = :token WHERE id = :id"
);
return $stmt->execute([
'id' => $user->id,
'token' => $token
]);
}
public function verifyPassword(User $user, string $password): bool
{
return password_verify($password, $user->password);
}
}