From a99b99aa59c839b4bdd5b332c9623621325b7bab Mon Sep 17 00:00:00 2001
From: gopikrishnan <gopikrishnan8015@gmail.com>
Date: Mon, 2 May 2022 10:40:00 +0000
Subject: [PATCH] updated userSession

---
 libs/includes/UserSession.class.php | 68 +++++++++++++++++++++++++++--
 logintest2.php                      | 44 +++++++++++++++++++
 2 files changed, 108 insertions(+), 4 deletions(-)
 create mode 100644 logintest2.php

diff --git a/libs/includes/UserSession.class.php b/libs/includes/UserSession.class.php
index 4b582261..55ea45be 100644
--- a/libs/includes/UserSession.class.php
+++ b/libs/includes/UserSession.class.php
@@ -10,12 +10,12 @@ class UserSession
     public static function authenticate($user, $pass)
     {
         $username = User::login($user, $pass);
-        $user = new User($username);
         if ($username) {
+            $user = new User($username);
             $conn = Database::getConnection();
             $ip = $_SERVER['REMOTE_ADDR'];
             $agent = $_SERVER['HTTP_USER_AGENT'];
-            $token = md5(rand(0, 9999999) .$ip.$agent.time());
+            $token = md5(rand(0, 9999999) . $ip . $agent . time());
             $sql = "INSERT INTO `session` (`uid`, `token`, `login_time`, `ip`, `user_agent`, `active`)
             VALUES ('$user->id', '$token', now(), '$ip', '$agent', '1')";
             if ($conn->query($sql)) {
@@ -29,9 +29,34 @@ class UserSession
         }
     }
 
+    /*
+    * Authorize function have has 4 level of checks 
+        1.Check that the IP and User agent field is filled.
+        2.Check if the session is correct and active.
+        3.Check that the current IP is the same as the previous IP
+        4.Check that the current user agent is the same as the previous user agent
+
+        @return true else false;
+    */
     public static function authorize($token)
     {
-        $sess = new UserSession($token);
+        try {
+            $session = new UserSession($token);
+            if (isset($_SERVER['REMOTE_ADDR']) and isset($_SERVER["HTTP_USER_AGENT"])) {
+                if ($session->isValid() and $session->isActive()) {
+                    if ($_SERVER['REMOTE_ADDR'] == $session->getIP()) {
+                        if ($_SERVER['HTTP_USER_AGENT'] == $session->getUserAgent()) {
+                            return true;
+                        } else throw new Exception("User agent does't match");
+                    } else throw new Exception("IP does't match");
+                } else {
+                    $session->removeSession();
+                    throw new Exception("Invalid session");
+                }
+            } else throw new Exception("IP and User_agent is null");
+        } catch (Exception $e) {
+            return false;
+        }
     }
 
     public function __construct($token)
@@ -39,7 +64,7 @@ class UserSession
         $this->conn = Database::getConnection();
         $this->token = $token;
         $this->data = null;
-        $sql = "SELECT * FROM `session` WHERE `token`=$token LIMIT 1";
+        $sql = "SELECT * FROM `session` WHERE `token`='$token' LIMIT 1";
         $result = $this->conn->query($sql);
         if ($result->num_rows) {
             $row = $result->fetch_assoc();
@@ -62,17 +87,52 @@ class UserSession
      */
     public function isValid()
     {
+        if (isset($this->data['login_time'])) {
+            $login_time = DateTime::createFromFormat('Y-m-d H:i:s', $this->data['login_time']);
+            if (3600 > time() - $login_time->getTimestamp()) {
+                return true;
+            } else {
+                return false;
+            }
+        } else throw new Exception("login tiem is null");
     }
 
     public function getIP()
     {
+        return isset($this->data["ip"]) ? $this->data["ip"] : false;
     }
 
     public function getUserAgent()
     {
+        return isset($this->data["user_agent"]) ? $this->data["user_agent"] : false;
     }
 
     public function deactivate()
     {
+        if (!$this->conn)
+            $this->conn = Database::getConnection();
+        $sql = "UPDATE `session` SET `active` = 0 WHERE `uid`=$this->uid";
+
+        return $this->conn->query($sql) ? true : false;
+    }
+
+    public function isActive()
+    {
+        if (isset($this->data['active'])) {
+            return $this->data['active'] ? true : false;
+        }
+    }
+
+    //This function remove current session
+    public function removeSession()
+    {
+        if (isset($this->data['id'])) {
+            $id = $this->data['id'];
+            if (!$this->conn) $this->conn = Database::getConnection();
+            $sql = "DELETE FROM `session` WHERE `id` = $id;";
+            if ($this->conn->query($sql)) {
+                return true;
+            } else return false;
+        }
     }
 }
diff --git a/logintest2.php b/logintest2.php
new file mode 100644
index 00000000..eb018d1d
--- /dev/null
+++ b/logintest2.php
@@ -0,0 +1,44 @@
+<?php
+include 'libs/load.php';
+
+$user = "gopi";
+
+if (isset($_GET['logout'])) {
+    if (Session::isset("session_token")) {
+        $Session = new UserSession(Session::get("session_token"));
+        if ($Session->removeSession()) {
+            echo "<h3> Pervious Session is removing from db </h3>";
+        } else {
+            echo "<h3>Pervious Session not removing from db </h3>";
+        }
+    }
+    Session::destroy();
+    die("Session destroyed, <a href='logintest2.php'>Login Again</a>");
+}
+
+/*
+1. Check if session_token in PHP session is available
+2. If yes, construct UserSession and see if its successful.
+3. Check if the session is valid one
+4. If valid, print "Session validated"
+5. Else, print "Invalid Session" and ask user to login.
+*/
+
+if (Session::isset("session_token")) {
+    if (UserSession::authorize(Session::get("session_token"))) {
+        echo "<h1>Session Login, WELCOME $user </h1>";
+    } else {
+        Session::destroy();
+        die("<h1>Invalid Session, <a href='logintest2.php'>Login Again</a></h1>");
+    }
+} else {
+    $pass = isset($_GET['pass']) ? $_GET['pass'] : '';
+    if (!$pass) die("<h1>Password  is Empty</h1>");
+    if (UserSession::authenticate($user, $pass)) {
+        echo "<h1>New LOGIN Success,  WELCOME $user</h1>";
+    } else echo "<h1>New Login Failed! $user</h1>";
+}
+
+echo <<<EOL
+<br><br><a href="logintest2.php?logout">Logout</a>
+EOL;
-- 
GitLab