public function testSessionKey() { $user = new User(); $user->regenerateSessionKey(); $key = $user->getSessionKey(); $this->assertNotEmpty($key); $this->assertTrue($user->validateSessionKey($key)); $user->regenerateSessionKey(); $this->assertNotEquals($key, $user->getSessionKey()); $this->assertFalse($user->validateSessionKey($key)); }
/** * Creates a new User based on the username and password pair. This IS the logged in user * Use this constructor to log in the user and if the user is doing something critical. * * A new session is started. * * This is where the session is created if the username/password are correct. * * The password should be passed already hashed * * @static * @param string $username * @param string $password * @return User */ public static function withUserNameAndPassword($username, $password) { $instance = null; $db = Database::getInstance(); $get_user_id_stmt = $db->prepare('SELECT id FROM Users WHERE username = ? AND password = ?'); $get_user_id_stmt->bind_param('ss', $username, $password); $get_user_id_stmt->execute(); if ($row = $db->getRow($get_user_id_stmt)) { $get_user_id_stmt->close(); // create the new user object if (!is_null($user = User::withId($row->id))) { // set the session for this user $session = User::getSessionKey($user); $insert_session_stmt = $db->prepare('INSERT INTO Sessions (session_key) VALUES (?)'); $insert_session_stmt->bind_param('s', $session); if ($insert_session_stmt->execute()) { $session_id = $db->insert_id; $insert_user_session_stmt = $db->prepare('INSERT INTO UserSessions (user_id, session_id) VALUES (?, ?)'); $insert_user_session_stmt->bind_param('ii', $user->getId(), $session_id); if ($insert_user_session_stmt->execute()) { $_SESSION[User::USER_SESSION] = $session; self::$current_logged_user = $instance = User::withSession(); } $insert_user_session_stmt->close(); } $insert_session_stmt->close(); } } return $instance; }