From 923309426734e058021f0a57b3f1e8c44edba932 Mon Sep 17 00:00:00 2001 From: Sven Slootweg Date: Wed, 19 Jun 2013 02:16:19 +0200 Subject: [PATCH] Add User class --- public_html/classes/user.php | 138 +++++++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 public_html/classes/user.php diff --git a/public_html/classes/user.php b/public_html/classes/user.php new file mode 100644 index 0000000..873d3cd --- /dev/null +++ b/public_html/classes/user.php @@ -0,0 +1,138 @@ + array( + 'Username' => "Username", + 'Hash' => "Hash", + 'Salt' => "Salt", + 'EmailAddress' => "EmailAddress" + ), + 'boolean' => array( + 'IsAdmin' => "Admin", + 'IsBanned' => "Banned" + ), + 'timestamp' => array( + "RegistrationDate" => "RegistrationDate" + ) + ); + + public function GenerateSalt() + { + $this->uSalt = random_string(10); + } + + public function GenerateHash() + { + if(!empty($this->uSalt)) + { + if(!empty($this->uPassword)) + { + $this->uHash = $this->CreateHash($this->uPassword); + } + else + { + throw new Exception("User object is missing a password."); + } + } + else + { + throw new Exception("User object is missing a salt."); + } + } + + public function CreateHash($input) + { + global $cphp_config; + $hash = crypt($input, "$5\$rounds=50000\${$this->uSalt}{$cphp_config->salt}$"); + $parts = explode("$", $hash); + return $parts[4]; + } + + public function VerifyPassword($password) + { + if($this->CreateHash($password) == $this->sHash) + { + return true; + } + else + { + return false; + } + } + + public function Authenticate() + { + $_SESSION['user_id'] = $this->sId; + $_SESSION['logout_key'] = random_string(32); + $_SESSION['is_admin'] = $this->sIsAdmin; + + $this->SetGlobalVariables(); + } + + public function Deauthenticate() + { + unset($_SESSION['user_id']); + unset($_SESSION['is_admin']); + } + + public function SetGlobalVariables() + { + NewTemplater::SetGlobalVariable("my-username", $this->sUsername); + NewTemplater::SetGlobalVariable("logout-key", $_SESSION['logout_key']); + } + + public static function CheckIfUsernameExists($username) + { + try + { + $result = User::FindByUsername($username); + return true; + } + catch (NotFoundException $e) + { + return false; + } + } + + public static function FindByUsername($username) + { + return self::CreateFromQuery("SELECT * FROM users WHERE `Username` = :Username", array(':Username' => $username), 0, true); + } + + public static function CheckIfEmailAddressExists($username) + { + try + { + $result = User::FindByEmailAddress($username); + return true; + } + catch (NotFoundException $e) + { + return false; + } + } + + public static function FindByEmailAddress($email) + { + return self::CreateFromQuery("SELECT * FROM users WHERE `EmailAddress` = :EmailAddress", array(':EmailAddress' => $email), 0, true); + } +}