113 lines
3.3 KiB
PHP
113 lines
3.3 KiB
PHP
<?php
|
|
namespace App\Models;
|
|
|
|
class Access extends \Core\Model
|
|
{
|
|
public function __construct()
|
|
{
|
|
$this->createTable(
|
|
'user',
|
|
[
|
|
'id int(3) NOT NULL AUTO_INCREMENT',
|
|
'username varchar(25) NOT NULL',
|
|
'password char(13) NOT NULL',
|
|
'salt char(23) NOT NULL',
|
|
'full_name varchar(50) NOT NULL',
|
|
'registered_at date NOT NULL DEFAULT CURRENT_TIMESTAMP',
|
|
'privilage int(3) NOT NULL DEFAULT 0',
|
|
'status tinyint NOT NULL DEFAULT 0',
|
|
'PRIMARY KEY (id)'
|
|
]
|
|
);
|
|
}
|
|
|
|
public function showAll()
|
|
{
|
|
try {
|
|
$db = static::connectDB();
|
|
|
|
$sql = "SELECT id, username, full_name, registered_at FROM user";
|
|
|
|
if ($stmt = $db->query($sql)) {
|
|
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
|
|
return $result;
|
|
}
|
|
return false;
|
|
} catch (PDOException $e) {
|
|
echo $e->getMessage();
|
|
}
|
|
}
|
|
|
|
public function showSingle($id)
|
|
{
|
|
try {
|
|
$db = static::connectDB();
|
|
|
|
$sql = "SELECT id, username, full_name, registered_at, privilage FROM user WHERE id = ?";
|
|
|
|
$query = $db->prepare($sql);
|
|
|
|
if ($query->execute([$id])) {
|
|
if ($query->rowCount() === 1) {
|
|
$result = $query->fetch(\PDO::FETCH_ASSOC);
|
|
return $result;
|
|
}
|
|
}
|
|
return false;
|
|
} catch (PDOException $e) {
|
|
throw new \Exception($e->getMessage(), 444);
|
|
}
|
|
}
|
|
|
|
public function login($args = [])
|
|
{
|
|
try {
|
|
$username = htmlspecialchars($args['username']);
|
|
$password = $args['password'];
|
|
|
|
$db = static::connectDB();
|
|
|
|
$sql = "SELECT id, password, salt FROM user WHERE username = ?";
|
|
|
|
$query = $db->prepare($sql);
|
|
$query->bindValue(1, $username);
|
|
|
|
if ($query->execute()) {
|
|
if ($query->rowCount() === 1) {
|
|
$result = $query->fetch(\PDO::FETCH_ASSOC);
|
|
|
|
$id = $result['id'];
|
|
$salt = $result['salt'];
|
|
$hash = $result['password'];
|
|
|
|
if (\Core\Hash::compare($password, $salt, $hash)) {
|
|
$user = $this->showSingle($id);
|
|
|
|
\Core\Session::put('userid', $user['id']);
|
|
\Core\Session::put('username', $user['username']);
|
|
\Core\Session::put('full_name', $user['full_name']);
|
|
\Core\Session::put('privilage', $user['privilage']);
|
|
|
|
$user_now = $user['username'];
|
|
|
|
\Core\Session::flash('info', "$user_now logged in");
|
|
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
\Core\Session::flash('info', 'Invalid username/password');
|
|
} catch (PDOException $e) {
|
|
throw new \Exception($e->getMessage(), 444);
|
|
}
|
|
}
|
|
|
|
public function logout($id)
|
|
{
|
|
if ($this->update('user', ['status' => 0], $id)) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
}
|