conn = $db; } private function sanitizeInputs() { $this->uid = sanitize($this->uid); $this->email = sanitize($this->email); $this->password = sanitize($this->password); $this->sid = sanitize($this->sid); } private function createSession() { $query = "INSERT INTO $this->tableSession (uid, sid, expiry) VALUES (:uid, :sid, :expiry)"; $stmt = $this->conn->prepare($query); $this->sid = uniqid(); $tomorrowDate = new DateTime("tomorrow"); $expiry = $tomorrowDate->format('Y-m-d H:i:s'); $stmt->bindParam(":uid", $this->uid); $stmt->bindParam(":sid", $this->sid); $stmt->bindParam(":expiry", $expiry); if ($stmt->execute()) { return true; } return false; } public function login() { $this->sanitizeInputs(); $query = "SELECT role, uid, name FROM " . $this->tableUsers . " WHERE email='" . $this->email . "' AND password = '" . $this->password . "'"; $stmt = $this->conn->prepare($query); $stmt->execute(); $num = $stmt->rowCount(); if ($num > 0) { $row = $stmt->fetch(PDO::FETCH_ASSOC); $this->uid = $row["uid"]; $this->role = $row["role"]; $this->name = $row["name"]; if ($this->createSession()) { return 200; } return 500; } return 401; } public function isValidSession() { $this->sanitizeInputs(); $query = "SELECT " . $this->tableSession . ".expiry, " . $this->tableUsers . ".role, " . $this->tableUsers . ".name FROM " . $this->tableSession . " LEFT JOIN " . $this->tableUsers . " ON " . $this->tableUsers . ".uid = " . $this->tableSession . ".uid WHERE " . $this->tableSession . ".uid='" . $this->uid . "' AND sid = '" . $this->sid . "'"; $stmt = $this->conn->prepare($query); $stmt->execute(); $num = $stmt->rowCount(); if ($num > 0) { $row = $stmt->fetch(PDO::FETCH_ASSOC); $now = new DateTime(); $expiry = new DateTime($row["expiry"]); if ($now > $expiry) { $query = "DELETE FROM " . $this->tableSession . " WHERE uid='" . $this->uid . "' AND sid = '" . $this->sid . "'"; $stmt = $this->conn->prepare($query); $stmt->execute(); return 440; } else { $this->role = $row["role"]; $this->name = $row["name"]; return 200; } } else { return 440; } } }