diff options
Diffstat (limited to 'includes/model/User.php')
-rw-r--r-- | includes/model/User.php | 71 |
1 files changed, 58 insertions, 13 deletions
diff --git a/includes/model/User.php b/includes/model/User.php index f2bd23d..13cbc03 100644 --- a/includes/model/User.php +++ b/includes/model/User.php @@ -6,18 +6,40 @@ const USER_LEVEL_MODERATOR = 1; class User { public $id; - public $name = 'Unknown'; + public $name; public $password; - public $date = 0; + public $date; public $level = 0; - function get_by_name($name): bool + private $has_value = false; + + // Can't use a constructor here because we have two possible ways to get the user from the database + // and PHP does not allow function overloading. + public function get_by_id($id) + { + $sql = "SELECT user_name, user_date, user_level, user_pass FROM users WHERE user_id = ?;"; + $result = Database::get()->query($sql, "i", $id); + + if (empty($result)) { + return; + } + + $this->id = $id; + $this->name = $result[0]['user_name']; + $this->password = $result[0]['user_pass']; + $this->date = $result[0]['user_date']; + $this->level = $result[0]['user_level']; + + $this->has_value = true; + } + + public function get_by_name($name) { $sql = "SELECT user_id, user_date, user_level, user_pass FROM users WHERE user_name = ?"; $result = Database::get()->query($sql, "s", $name); if (empty($result)) { - return false; + return; } $this->id = $result[0]['user_id']; @@ -26,18 +48,41 @@ class User $this->date = $result[0]['user_date']; $this->level = $result[0]['user_level']; - return true; + $this->has_value = true; } - function get_by_id($id) + public function has_value() { - $sql = "SELECT user_name, user_date, user_level, user_pass FROM users WHERE user_id = ?;"; - $result = Database::get()->query($sql, "i", $id); + return $this->has_value; + } - $this->id = $id; - $this->name = $result[0]['user_name']; - $this->password = $result[0]['user_pass']; - $this->date = $result[0]['user_date']; - $this->level = $result[0]['user_level']; + public static function register(string $username, string $pass_hash) + { + $sql = "INSERT INTO users(user_name, user_pass, user_date, user_level) VALUES(?, ?, NOW(), 0);"; + Database::get()->query($sql, "ss", $username, $pass_hash); } + + public function change_password(string $pass_hash) + { + if (!Session::get()->is_signed_in()) { + trigger_error('You are not signed in.'); + return; + } + + if (Session::get()->get_current_user()->id != $this->id) { + trigger_error("You can't change another user's password."); + return; + } + + $sql = "UPDATE users SET user_pass = ? WHERE user_id = ?;"; + Database::get()->query($sql, "si", $pass_hash, $this->id); + } +} + +function username_exists(string $username): bool +{ + $sql = "SELECT * FROM users WHERE user_name = ?;"; + $result = Database::get()->query($sql, "s", $username); + + return !empty($result); }
\ No newline at end of file |