Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /* requires sql.class.php to function */
- class Session
- {
- private $link;
- /*
- * initialize the session
- */
- public function Session($sql)
- {
- session_start();
- $this->link = $sql;
- }
- /*
- * login utils
- */
- // only needed on registration and password change.
- public function GenerateSalt()
- {
- $salt = uniqid(rand(), true);
- $salt = md5($salt);
- return substr($salt, 0, 8);
- }
- public function GenerateHash($plainText, $salt)
- {
- $hash = $salt . sha1($salt . $plainText);
- return $hash;
- }
- /*
- * check if user is logged in
- */
- public function IsLogged()
- {
- if( !isset($_SESSION['uid']) )
- return false;
- return $this->TestPassword($_SESSION['uid'],$_SESSION['pass']);
- }
- /*
- * get password/salt for a given user
- */
- private function GetSalt($uid)
- {
- $uid = mysql_fetch_array($this->link->Query("SELECT salt FROM users WHERE id='?' LIMIT 1", $uid));
- return $uid[0];
- }
- private function GetPassword($uid)
- {
- $password = mysql_fetch_array($this->link->Query("SELECT password FROM users WHERE id='?' LIMIT 1", $uid));
- return $password[0];
- }
- /*
- * make sure the stored password matches the given one.
- */
- private function TestPassword($uid,$password)
- {
- // get password from cookie
- $password = $_SESSION['pass'];
- // get known password
- $knownpass = $this->GetPassword($uid);
- // if this returns false, someone has tampered with the cookie.
- return $password == $knownpass;
- }
- /*
- * returns true if successful
- */
- public function Login()
- {
- // get the uid from the posted password
- $uid = mysql_fetch_array($this->link->Query("SELECT id FROM users WHERE username='?' LIMIT 1",$_POST['username']));
- $uid = $uid[0];
- $password = $_POST['password'];
- $salt = $this->GetSalt($uid);
- $password = $this->GenerateHash($password,$salt);
- $_SESSION['pass'] = $password;
- if( $this->TestPassword($uid, $password) )
- {
- $_SESSION['uid'] = $uid;
- return true;
- }
- // don't leave the password hash there if the login failed (paranoia)
- unset($_SESSION['pass']);
- return false;
- }
- /*
- * logout, as if I'm actually doing something.
- */
- public function Logout() { session_destroy(); }
- }
- $session = new Session($link); // make sure $link is a database connection, e.g.
- // you may wish to change these if you want your site to behave differently!
- if( isset($_POST['login']) && !isset($_SESSION['uid']) )
- {
- $login = $session->Login();
- }
- elseif( $_GET['logout'] )
- $session->Logout();
Add Comment
Please, Sign In to add comment