|
CS479/579 - Web Programming II
|
Displaying ./code/images/auth.php
<?php
// +-------+-------------+------+-----+---------+-------+
// | Field | Type | Null | Key | Default | Extra |
// +-------+-------------+------+-----+---------+-------+
// | sid | varchar(32) | NO | PRI | | |
// | uid | int(11) | NO | MUL | 0 | |
// +-------+-------------+------+-----+---------+-------+
// +----------+---------------+------+-----+---------+----------------+
// | Field | Type | Null | Key | Default | Extra |
// +----------+---------------+------+-----+---------+----------------+
// | uid | int(12) | NO | PRI | NULL | auto_increment |
// | email | varchar(1024) | NO | MUL | | |
// | password | varchar(1024) | NO | | | |
// +----------+---------------+------+-----+---------+----------------+
class Auth {
private $myconn;
public $error;
public $sid, $uid, $ipaddr;
function __construct()
{
$this->myconn = new mysqli("localhost", "sbaker", "sbaker", "sbaker");
$this->uid = -1;
$this->ipaddr = "";
$this->error = null;
}
function authenticated() {
if (!isset($_COOKIE['IMG_SESSION'])) {
$this->error = "No session cookie";
return false;
}
$this->sid = $sid = $_COOKIE['IMG_SESSION'];
$stmt = $this->myconn->prepare("SELECT uid, ipaddr FROM img_session WHERE sid=?");
$stmt->bind_param("s", $sid);
$stmt->bind_result($this->uid, $this->ipaddr);
$stmt->execute();
if ($stmt->fetch()) {
$stmt->close();
if ($this->ipaddr != $_SERVER['REMOTE_ADDR']) $this->error = "IP Address does not match session IP";
return true;
} else {
$stmt->close();
$error = "No session found";
return false;
}
}
function createSID()
{
// 6 bits worth of character data:
$cookie_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-$";
$len = strlen($cookie_chars)-1;
$sid = "";
// Loop to generate 126 bits of randomness as a string:
for ($i = 0; $i < 21; $i++)
$sid .= $cookie_chars[rand(0, $len)];
return $sid;
}
function newsession($uid)
{
setcookie("IMG_SESSION", $this->sid = $sid = $this->createSID());
$stmt = $this->myconn->prepare("insert into img_session (sid, uid, ipaddr) values (?, ?, ?)");
if ($stmt == false) die("newsession" . $myconn->error);
$this->uid = $uid;
$this->ipaddr = $addr = $_SERVER['REMOTE_ADDR'];
$stmt->bind_param("sis",$sid, $uid, $addr);
$stmt->execute();
$stmt->close();
}
function logout()
{
$stmt = $this->myconn->prepare("DELETE FROM img_session WHERE sid = ?");
$stmt->bind_param("s", $this->sid);
$stmt->execute();
$stmt->close();
setcookie("IMG_SESSION", "", time()-24*60*60);
}
}
?>
|