73 lines
No EOL
2.9 KiB
PHP
73 lines
No EOL
2.9 KiB
PHP
<?php
|
|
class User {
|
|
private $db;
|
|
public function __construct() {
|
|
$this->db = new Database();
|
|
}
|
|
// Auth-Logic
|
|
public function authenticate($email, $password) {
|
|
$this->db->query("SELECT * FROM home_users WHERE email = :email AND status = 'Active'");
|
|
$this->db->bind(':email', $email);
|
|
$user = $this->db->single();
|
|
if ($user && password_verify($password, $user['password'])) {
|
|
$user['projects'] = json_decode($user['projects'], true) ?? [];
|
|
$user['is_admin'] = (bool)$user['is_admin'];
|
|
return $user;
|
|
}
|
|
return false;
|
|
}
|
|
// Data-Retrieval
|
|
public function getAll() {
|
|
$this->db->query("SELECT id, name, email, is_admin, status, projects FROM home_users ORDER BY id DESC");
|
|
$users = $this->db->resultSet();
|
|
foreach ($users as &$user) {
|
|
$user['projects'] = json_decode($user['projects'], true) ?? [];
|
|
}
|
|
return $users;
|
|
}
|
|
public function getById($id) {
|
|
$this->db->query("SELECT * FROM home_users WHERE id = :id");
|
|
$this->db->bind(':id', $id);
|
|
$user = $this->db->single();
|
|
if ($user) {
|
|
$user['projects'] = json_decode($user['projects'], true) ?? [];
|
|
}
|
|
return $user;
|
|
}
|
|
// Persistence
|
|
public function save($data, $id = null) {
|
|
if (is_array($data['projects'] ?? null)) {
|
|
$projectsList = array_values(array_filter($data['projects']));
|
|
} else {
|
|
$projectsStr = $data['projects'] ?? '';
|
|
$projectsList = !empty($projectsStr) ? array_values(array_filter(array_map('trim', explode(',', $projectsStr)))) : [];
|
|
}
|
|
$projectsJson = json_encode($projectsList);
|
|
if ($id) {
|
|
$sql = "UPDATE home_users SET name = :name, email = :email, projects = :projects, is_admin = :is_admin, status = :status ";
|
|
if (!empty($data['password'])) {
|
|
$sql .= ", password = :password ";
|
|
}
|
|
$sql .= "WHERE id = :id";
|
|
$this->db->query($sql);
|
|
$this->db->bind(':id', $id);
|
|
} else {
|
|
$sql = "INSERT INTO home_users (name, email, password, projects, is_admin, status) VALUES (:name, :email, :password, :projects, :is_admin, :status)";
|
|
$this->db->query($sql);
|
|
}
|
|
$this->db->bind(':name', $data['name']);
|
|
$this->db->bind(':email', $data['email']);
|
|
$this->db->bind(':projects', $projectsJson);
|
|
$this->db->bind(':is_admin', !empty($data['is_admin']) ? 1 : 0);
|
|
$this->db->bind(':status', $data['status']);
|
|
if (!$id || !empty($data['password'])) {
|
|
$this->db->bind(':password', password_hash($data['password'], PASSWORD_DEFAULT));
|
|
}
|
|
return $this->db->execute();
|
|
}
|
|
public function delete($id) {
|
|
$this->db->query("DELETE FROM home_users WHERE id = :id");
|
|
$this->db->bind(':id', $id);
|
|
return $this->db->execute();
|
|
}
|
|
} |