I could use some review on this Auth class, as I'm sure it could use many improvements!
I wrote this fairly quickly, so please forgive any overseen bugs.
Example usage:
// Login a user
if (Auth::attempt($_POST['username'], $_POST['password']))
{
echo 'You have successfully logged in.';
}
// Check if the user is a guest
if (Auth::guest())
{
echo 'Please log in to see this page.';
}
// Logout a user
Auth::logout();
Source code:
<?php
class Auth {
/**
* Whether or not the user is currently logged in
*
* @var bool
*/
public static $user;
/**
* Attempts to log a user in with the given credentials
*
* @param string $username
* @param string $password
* @return bool
*/
public static function attempt($username, $password)
{
global $db;
$stmt = $db->prepare('SELECT * FROM `users` WHERE `username` = :username AND `password` = :password');
$stmt->execute(array(':username' => $username, ':password' => $password));
if ($user = $stmt->fetch(PDO::FETCH_ASSOC))
{
static::$user = $user;
static::login($user['id']);
return true;
}
return false;
}
/**
* Login the user with the given id
*
* @param int $user_id
* @return void
*/
public static function login($user_id)
{
if ($user_id)
{
$_SESSION['user_id'] = $user_id;
}
}
/**
* Log out the current user
*
* @return void
*/
public static function logout()
{
static::$user = null;
$_SESSION = array();
unset($_SESSION['user_id']);
session_destroy();
}
/**
* Checks if a user is currently logged in
*
* @return bool
*/
public static function check()
{
return isset($_SESSION['user_id']);
}
/**
* Checks if the current user is a guest
*
* @return bool
*/
public static function guest()
{
return ! isset($_SESSION['user_id']);
}
}
I'm also not sure if using all static methods in the class could lead to problems later on?
I know there is currently no password hashing - I'm still working on the hashing method.