Advertisement
Guest User

PHP Auth Juni 2018

a guest
Jun 13th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 8.95 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Description of class auth
  4.  * Used for session based login
  5.  * Depends on user class roles
  6.  * @property string $strUserName Username from POST var
  7.  * @property string $strPassword Password from POST var
  8.  * @property bool $iRemember Bool to set remember me cookie
  9.  * @property bool $strRemoteAddr IP address
  10.  * @property int $iTimeOutSeconds Number of session keep alive seconds
  11.  * @property string $doLogout GET var with logout action
  12.  * @property int $iUserID Users ID
  13.  * @property object $user User Object
  14.  *
  15.  */
  16. class Auth {
  17.     public $strUserName;
  18.     public $strPassword;
  19.     public $iRemember;
  20.     public $strRemoteAddr;
  21.     public $strErrMessage;
  22.     public $iTimeOutSeconds;
  23.     public $doLogout;
  24.     public $iUserID;
  25.     public $user;
  26.     public $loginWin;
  27.     public $iShowLoginForm;
  28.     public $errMessage;
  29.  
  30.     /* Error Constants */
  31.     const ERR_NOUSERFOUND = 1;
  32.     const ERR_NOSESSIONFOUND = 2;
  33.     const ERR_NOACCESS = 3;
  34.    
  35.     /**
  36.      * Class Constructor
  37.      * Set defaults
  38.      * Sets strUserName, strPassword, iRemember & doLogout to watch POST & GET vars
  39.      * Call method athentificate
  40.      * @global type $db
  41.      */
  42.     public function __construct() {
  43.         global $db;
  44.         $this->db = $db;
  45.         session_start();
  46.         $this->strUserName = filter_input(INPUT_POST, "login_username", FILTER_SANITIZE_STRING);
  47.         $this->strPassword = filter_input(INPUT_POST, "login_password", FILTER_SANITIZE_STRING);
  48.         $this->iRemember = filter_input(INPUT_POST, "remember", FILTER_SANITIZE_STRING);
  49.         $this->strRemoteAddr = filter_input(INPUT_SERVER,"REMOTE_ADDR",FILTER_VALIDATE_IP);
  50.         $this->doLogout = filter_input(INPUT_GET, "action", FILTER_SANITIZE_STRING);
  51.         $this->iTimeOutSeconds = 3600;
  52.         $this->iUserID = 0;
  53.         $this->iShowLoginForm = 1;
  54.         $this->loginWin = DOCROOT . "/cms/assets/incl/login.php";
  55.         $this->user = new User();
  56.         $this->errMessage = "";
  57.     }
  58.    
  59.     /**
  60.      * Method Authentificate
  61.      * If GET["action"] = logout run method logout
  62.      * If set strUserName & strPassword run method initUser
  63.      * Else run method getSession
  64.      */
  65.     public function authenticate() {
  66.         if($this->doLogout === "logout") {
  67.             $this->logout();
  68.         }
  69.         if($this->strUserName && $this->strPassword) {
  70.             $this->errMessage = $this->initUser();
  71.         } else {
  72.             if(!$this->getSession()) {
  73.                 if($this->iShowLoginForm) {
  74.                     echo $this->loginform();
  75.                 }
  76.             }
  77.         }
  78.     }
  79.    
  80.     /**
  81.      * Method Initialize User
  82.      * Selects user from username & password
  83.      * If true - insert session into usersession and call user object
  84.      * (User Obj sets roles)
  85.      */
  86.     private function initUser() {
  87.         $params = array($this->strUserName);
  88.         $strSelectUser = "SELECT iUserID, vcPassword FROM user " .
  89.                             "WHERE vcUserName = ? " .
  90.                             "AND iSuspended = 0 " .
  91.                             "AND iDeleted = 0";
  92.  
  93.         if($row = $this->db->_fetch_array($strSelectUser, $params)) {
  94.             if(password_verify($this->strPassword, $row[0]["vcPassword"])) {
  95.                 $this->iUserID = $row[0]["iUserID"];
  96.                 $params = array(
  97.                     session_id(),
  98.                     $this->iUserID,
  99.                     $this->strRemoteAddr,
  100.                     1,
  101.                     time(),
  102.                     time()
  103.                 );
  104.                 $strInsertSession = "INSERT INTO usersession (" .
  105.                     "vcSessionID," .
  106.                     "iUserID," .
  107.                     "iIpAddress, " .
  108.                     "iIsLoggedIn, " .
  109.                     "daLoginCreated, " .
  110.                     "daLastAction) " .
  111.                     "VALUES(?,?,?,?,?,?)";
  112.                 $this->db->_query($strInsertSession, $params);
  113.                 $this->user->getItem($this->iUserID);
  114.                 header("Location: " . $_SERVER["PHP_SELF"]);
  115.             }
  116.         } else {
  117.             if($this->iShowLoginForm) {
  118.                 /* Login for CMS section */
  119.                 echo $this->loginform(self::ERR_NOUSERFOUND);
  120.             } else {
  121.                 /* Login for extranet purposes */
  122.                 return $this->getError(self::ERR_NOUSERFOUND);
  123.             }
  124.         }
  125.  
  126.         if($this->iRemember) {
  127.             setcookie('elmando_username', $this->strUserName, time() + (86400 * 365),"/");
  128.             setcookie('elmando_password', $this->strPassword, time() + (86400 * 365),"/");
  129.         } else {
  130.             setcookie('elmando_username', '', time()-3600,"/");
  131.             setcookie('elmando_password', '', time()-3600,"/");        
  132.             unset($_COOKIE["elmando_username"]);
  133.             unset($_COOKIE["elmando_password"]);
  134.         }  
  135.        
  136.     }
  137.  
  138.     /**
  139.      * Method Get Session
  140.      * Checks if db usersession has a session id matching value
  141.      * If true check if session is outdates
  142.      * If true - insert session into usersession and call user object
  143.      * (User Obj sets roles)
  144.      * @return int $iUserID Returns the users ID
  145.      */
  146.     private function getSession() {
  147.         $params = array(session_id());
  148.         $strSelectSession = "SELECT iUserID, daLastAction FROM usersession " .
  149.                                 "WHERE vcSessionID = ? " .
  150.                                 "AND iIsLoggedIn = 1";
  151.         $row = $this->db->_fetch_array($strSelectSession, $params);
  152.         if(count($row) > 0) {
  153.             $row = call_user_func_array("array_merge", $row);
  154.             if($row["daLastAction"] > time()-($this->iTimeOutSeconds)) {
  155.                 $this->iUserID = $row["iUserID"];
  156.                 $this->user->getitem($this->iUserID);
  157.                 $this->updateSession();
  158.                 return $this->iUserID;
  159.             } else {
  160.                 $this->logout();
  161.             }
  162.         }
  163.     }
  164.    
  165.     /**
  166.      * Method Update Session
  167.      * Updates daLastAction in the current session
  168.      */
  169.     private function updateSession() {
  170.         $params = array(session_id());
  171.         $strUpdate = "UPDATE usersession " .
  172.                         "SET daLastAction = UNIX_TIMESTAMP() " .
  173.                         "WHERE vcSessionID = ?";
  174.         $this->db->_query($strUpdate,$params);        
  175.     }
  176.    
  177.     /**
  178.      * Method Logout
  179.      * Updates usersession iIsLoggedIn to false
  180.      * Destroys current session and resets session id
  181.      */
  182.     public function logout() {
  183.         $params = array(session_id());        
  184.         $strSessionUpdate = "UPDATE usersession SET iIsLoggedIn = 0 WHERE vcSessionID = ?";
  185.         $this->db->_query($strSessionUpdate,$params);
  186.         session_unset();
  187.         session_destroy();
  188.         session_start();
  189.         session_regenerate_id();
  190.     }
  191.  
  192.     /**
  193.      * Method Login Form
  194.      * Calls output buffer for rendering login form
  195.      * Includes a clean php file with login form html and css
  196.      * Get error messages and replaces error codes if any errors
  197.      * @param int $errCode
  198.      * @return string Returns full html of login window
  199.      */
  200.     public function loginform($errCode = 0) {
  201.         ob_start();
  202.         include_once $this->loginWin;
  203.         $strBuffer = ob_get_clean();
  204.         $strErrorMsg = self::getError($errCode);
  205.         $strContent = str_replace("@ERRORMSG@", $strErrorMsg , $strBuffer);
  206.         return $strContent;
  207.     }
  208.    
  209.     /**
  210.      * Method Check Session
  211.      * Checks if db usersession has a session id matching value
  212.      * @return bool Returns true or false
  213.      */
  214.     public function checkSession() {
  215.         $params = array(session_id());
  216.         $strSelectSession = "SELECT iUserID, daLastAction FROM usersession " .
  217.                                 "WHERE vcSessionID = ? " .
  218.                                 "AND iIsLoggedIn = 1";
  219.         $row = $this->db->_fetch_array($strSelectSession, $params);
  220.         if(count($row) > 0) {
  221.             $row = call_user_func_array("array_merge", $row);
  222.             if($row["daLastAction"] > time()-($this->iTimeOutSeconds)) {
  223.                 return TRUE;
  224.             } else {
  225.                 return FALSE;
  226.             }
  227.         }
  228.     }
  229.    
  230.    
  231.     /**
  232.      * Method getError
  233.      * Switches error constants to a string message
  234.      * @param int $int
  235.      * @return string Returns a string with error message
  236.      */
  237.     private function getError($int) {
  238.         switch($int) {
  239.             default:
  240.                 $strErr = '';
  241.                 break;
  242.             case self::ERR_NOUSERFOUND:
  243.                 $strErr = "Brugernavn eller password er forkert!";
  244.                 break;
  245.             case self::ERR_NOSESSIONFOUND:
  246.                 $strErr = "Bad Session!";
  247.                 break;
  248.             case self::ERR_NOACCESS:
  249.                 $strErr = "Du har ikke rettigheder til at se denne side!";
  250.                 break;
  251.         }
  252.         return $strErr;
  253.     }
  254. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement