error_log('my test');
if(isset($_SESSION["userName"])){
// some user is present CHECK AND ALLOW THE LOGIN.
// Another user has already logged in. so check if the last session activity is more than the SESSIONTIMEOUT value.
$idleTime = (time() - $_SESSION['LAST_ACTIVE_TIME'])/60;
$idleTime=9;$sessionTimeOut=10;
if($idleTime<$sessionTimeOut) {
print("*****1*****");
$existingUser=$_SESSION["userName"];
// IDLE TIME IS LESSTHAN THE SESSIONTIMEOUT SO ONLY ALLOW IF IT IS AN OLD USER
if(strcasecmp( $existingUser, $name ) == 0){
print("*****2*****");
$_SESSION["userName"] = $name;
$_SESSION["ipaddr"] = $ipaddr;
$_SESSION["type"] = $type;
$_SESSION['LAST_ACTIVE_TIME'] = time();
updateUserInfo($name,$ipaddr,$type);
$url ="./PHome.php" ;
// header("Location: $url");
} else {
print("*****3*****");
// IDLE TIME IS LESSTHAN THE SESSIONTIMEOUT AND new user, SO don't allow
$url ="./Login.html" ;
//header("Location: $url?error=duplicateErr");
}
} else {
print("*****4*****");
// IDLE TIME IS MORE than sessionTimeOut, SO NEW SECOND USER HAS LOGGED IN
$_SESSION["userName"] = $name;
$_SESSION["ipaddr"] = $ipaddr;
$_SESSION["type"] = $type;
$_SESSION['LAST_ACTIVE_TIME'] = time();
updateUserInfo($name,$ipaddr,$type);
$url ="./PHome.php" ;
// header("Location: $url");
}
} else {
print("*****0*****");
error_log("errors occured");
// No user is present So Log in
$_SESSION["userName"] = $name;
$_SESSION["ipaddr"] = $ipaddr;
$_SESSION["type"] = $type;
$_SESSION['LAST_ACTIVE_TIME'] = time();
updateUserInfo($name,$ipaddr,$type);
$url ="./PHome.php" ;
//header("Location: $url");
}
// Logic,
First I am checking if the user has already logged in, if not I am allowing the user to Login,
Now if a second user comes since the session is already set it should not allow the user to login, But this is allowing.
Test Scenario - Login using Chrome first and then using an IE, a second user is able to log in.
I Can't use a database, as the db is getting locked and the whole application dies.
Any help is highly appreciated.
Though I'm not sure if you are trying, to stop a same "user" from "same ip" to login is different, but if you want to stop multiple logins in same user this can be the technique
Add a field in DB beside the user
On login turn it to 1 (You should keep an inactivity timer though to make it 0 after some hours/minutes)
While login just add a statement to check if that field is 0 or 1
Related
I have made easy login system according to one article on web. If I click remember me button it stores these data (member_login, random_password, random_selector) in cookies on device, where I am logged in. First I used it just on PC.
Later I added IP address verificaction step to enable login on more devĂces in same time due to I want to use my app also on mobile device.
Login system is working correctly on PC - there I can be logged in one month if I choose remember me during login.
On mobile devices, on every browser it randomly log out me after some random period.
I already checked if cookies are created on mobile and it is ok.
I could not find rootcause why. Can you please advice me what to check.
Here is my login code, where cookies are setted up:
<?php
require_once ($_SERVER['DOCUMENT_ROOT'] . '/_inc/functions.php');
require_once ($_SERVER['DOCUMENT_ROOT'] . '/_inc/auth/Util.php');
require_once ($_SERVER['DOCUMENT_ROOT'] . '/_inc/auth/Auth.php');
$auth = new Auth();
$db_handle = new DBController();
$util = new Util();
// Get Current date, time
$current_time = time();
$current_date = date("Y-m-d H:i:s", $current_time);
// Set Cookie expiration for 1 month (seconds from 1970 until current date + 1 month)
$cookie_expiration_time = $current_time + (30 * 24 * 60 * 60); // for 1 month
// Auth.php chcek if user is loggedin
if ($_SESSION["user_id"]) {
redirect_page("index.php");
exit;
}
// check if login form was submitted
if (! empty($_POST['login'])) {
$isAuthenticated = false;
// get username and password from form
$username = $_POST['username'];
$password = $_POST['password'];
// get user from db
$user = $auth->getMemberByUsername($username);
// verify entered password with hashed password in db for user got above
if (password_verify($password, $user[0]["password"])) {
$isAuthenticated = true; // password is verified, next rocess of login can start
}
// if user is authenticated start to create cookies
if ($isAuthenticated) {
$_SESSION["user_id"] = $user[0]["id"];
// Set Auth Cookies if 'Remember Me' checked
if (! empty($_POST["remember"])) {
$ip_address = $_SERVER['REMOTE_ADDR'];
// setcookie(string $name, string $value = "", int $expires = 0,)
setcookie("member_login", $username, $cookie_expiration_time, '/'); // '/' cookies are available on each page
$random_password = $util->getToken(16); // create token for cookie identification with db
setcookie("random_password", $random_password, $cookie_expiration_time, '/'); // '/' cookies are available on each page
$random_selector = $util->getToken(32);
setcookie("random_selector", $random_selector, $cookie_expiration_time, '/'); // '/' cookies are available on each page
// hash password and selector before inserting to db
$random_password_hash = password_hash($random_password, PASSWORD_DEFAULT);
$random_selector_hash = password_hash($random_selector, PASSWORD_DEFAULT);
$expiry_date = date("Y-m-d H:i:s", $cookie_expiration_time);
// mark existing token as expired if new login
$userToken = $auth->getTokenByUsername($username, 0);
/*
if (! empty($userToken[0]["id"])) {
$auth->markAsExpired($userToken[0]["id"]);
}
*/
// Insert new token
$auth->insertToken($username, $ip_address, $random_password_hash, $random_selector_hash, $expiry_date);
} else {
$util->clearAuthCookie();
}
redirect_page("index.php");
exit;
} else {
$_SESSION['login_error'] = 'Invalid password or username';
redirect_page("back");
exit();
}
}
Hrere is my validation code to check cookies on each page:
<?php
/* FLow:
-> index -> header -> validatecookies ()
-> continue index (logedin = true)
-> redirect login
*/
require 'Util.php';
require 'Auth.php';
// create objects
$auth = new Auth();
$db_handle = new DBController();
$util = new Util();
$isLoggedIn = false;
// Check if loggedin session and redirect if session exists
if (! empty($_SESSION["user_id"])) {
$isLoggedIn = true;
}
// Check if loggedin cookies exists
else if (! empty($_COOKIE["member_login"]) && ! empty($_COOKIE["random_password"]) && ! empty($_COOKIE["random_selector"])) {
// Initiate auth token verification directive to false
$isPasswordVerified = false;
$isSelectorVerified = false;
$isExpiryDateVerified = false;
// Get token for username from db
$userToken = $auth->getTokenByIPaddress($_SERVER['REMOTE_ADDR'],0);
// $userToken = $auth->getTokenByUsername($_COOKIE["member_login"],0);
if ($userToken) {
// check just in case of the same IP address
// dual control via selector and password due to time leake secure issue (if just one token than according to response time from db it is possible to guess password easier)
// Validate random password cookie with database
if (password_verify($_COOKIE["random_password"], $userToken[0]["password_hash"])) {
$isPasswordVerified = true;
}
// Validate random selector cookie with database
if (password_verify($_COOKIE["random_selector"], $userToken[0]["selector_hash"])) {
$isSelectorVerified = true;
}
// check cookie expiration by date
if( ($userToken[0]["expiry_date"] >= $current_date) & ($userToken[0]["is_expired"] != 1) ) {
$isExpiryDateVerified = true;
}
}
// Redirect if all cookie based validation returns true
// Else, mark the token as expired and clear cookies
if (!empty($userToken[0]["id"]) && $isPasswordVerified && $isSelectorVerified && $isExpiryDateVerified) {
$isLoggedIn = true;
} else {
if(!empty($userToken[0]["id"])) {
$auth->markAsExpired($userToken[0]["id"]);
}
// clear cookies
$util->clearAuthCookie();
header ("Location: login.php");
exit;
}
} else {
// is no session and no cookies exist, just redirect on login
header ("Location: login.php");
exit;
}
?>
``
actually, i could not understand why do we use "$_SESSION['authuser'] = 1;" in php code, my code as below
<?php
session_start();
$_SESSION['username'] = $_POST['user'];
$_SESSION['userpass'] = $_POST['pass'];
$_SESSION['authuser'] = 1;
//Check username and password information
if(($_SESSION['username'] == 'joe') and
($_SESSION['userpass'] == '123')) {
$_SESSION['authuser'] = 1;
}
else
{
echo 'Sorry, but you don\'t have permission to view this page!';
exit();
}
?>
Because session (and cookie) support needs it due to a many reasons.
Ie, otherwise it would be required for you (and your visitors) to enter username and password every single time when you CLICK on an any link of your page.
<?php
session_start();
$_SESSION['username'] = $_POST['user'];
$_SESSION['userpass'] = $_POST['pass'];
$_SESSION['authuser'] = 0; // user is not authenticated (just a GUEST), default is 0...
// if visitor is priviledged, show him in, let him see the page
if(($_SESSION['username'] == 'joe') and
($_SESSION['userpass'] == '123')) {
$_SESSION['authuser'] = 1; // insert 1 into DB and set cookie as 1 for user not to enter username and pswd anymore during browsing
}
else
{
//else, keep guest away from a page
echo 'Sorry, but you don\'t have permission to view this page!';
exit(); // shut down
}
?>
In your case the usage of SESSION for username and userpass seems to be redundant. This could be possible.
<?php
session_start();
/*Do not set sessions for username and userpass, only use them in the POST array
*Initialize authuser to 0 because by default a user is not logged in
*/
$_SESSION['authuser'] = 0;
//Check username and password information
if(($_POST['user'] == 'joe') and
($_POST['pass'] == '123')) { //Check the user and set it as authenticated
$_SESSION['authuser'] = 1;
} else { //If the user is not valid, stop execution
echo 'Sorry, but you don\'t have permission to view this page!';
exit();
}
?>
What I'm doing here is:
Starting session
Initializing user as not authenticated (this is optional)
Checking username and password
If they are valid, setting user as authenticated
If not, stopping execution.
Note that it could be useful to set a session for username and password once user is authenticated, instead of only remember the user is logged.
I am creating a small login facility. i would like it to be simple but also secure.
I wanted to timeout my session after 30 minutes of inactivity. I saw a solution for this here by Gumbo. However I am unsure where to add the code to my own code... Can somebody help me ...
Here is the solution which i want to add into my code (by Gumbo) and underneath that is my own login.php page:
Conclusion / best solution (from another stackoverflow post ):
The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request:
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Updating the session data with every request also changes the session file's modification date so that the session is not removed by the garbage collector prematurely.
You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
// session started more than 30 minutes ago
session_regenerate_id(true); // change session ID for the current session and invalidate old session ID
$_SESSION['CREATED'] = time(); // update creation time
}
login.php
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
require("database.php");
require("phpfunctions.php");
if(isset($_POST["log_out"]) && ($_POST["log_out"] == '1')) {
//this means we have come from another page after pressing the log out button
//so therefore we remove session variables and destroy session
session_unset();
session_destroy();
//$log_out_message = "You have been logged out";
}
if (isset($_SESSION["username"])) {
//if the username session variable is already set then they are already logged in so send them to the index page
//we will perform further checks there on the validity of the session variables
header("Location: index.php");
exit();
}
//collect the post data if the login form has been submitted
if (isset($_POST["username"]) && isset($_POST["password"])){
$username = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]); // filter everything but numbers and letters
//check if this username and password exist in our database and are therefore valid
$query = "SELECT * FROM users WHERE username=:username LIMIT 1";
$statement = $pdoConnection->prepare($query);
$statement->bindValue(':username', $username, PDO::PARAM_STR);
$statement->execute();
$statement->setFetchMode(PDO::FETCH_ASSOC);
$count = 0;
while($row = $statement->fetch()){
//username exists.
if (password_verify($password, $row["hashedPassword"])) {
//password is verified
//store the hashedPassword into a variable.
$dbHashedValue = $row["hashedPassword"];
$id = $row["userID"];
$count++;
}
}
//if count is 1 that means we found matching username in our database and also have verifed the password
if($count == 1){
//If our login credentials are matched with the database and therefore valid we store the values into session variables.
//$_SESSION['incorrectLogin'] = false;
$_SESSION["userID"] = $id;
$_SESSION["username"] = $username;
$_SESSION["password"] = $dbHashedValue;
//all login information is correct and we have stored it into SESSION variables so
//we are ready to allow the user in to our system
header("Location: index.php");
//exit the rest of the script
exit();
}else if($count == 0){
//create generic message without giving too much information away to the user in order to be more secure.
$incorrectLoginDetails = "Invalid Login! Please try again!";
}
}
?>
index.php
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
require("database.php");
require("phpfunctions.php");
//check if the username session variable exists
//this will exist only if the person has passed the login stage therefore we now know they are logged in
if(!isset($_SESSION['username'])){
header('Location: login.php');
exit();
}
//also need to check this username exists in the database and also that the session password matches up with the database.
?>
I wanted to implement the secure login script from WikiHow in my project. I have got it working in CodeIgniter. I want to modify it a bit by logging out a user when he closes the browser (unless he checked Remember Me on the login page).
This is the login function (assume every variable is set because the function won't be called unless they are).
public function login() {
$error_msg = array();
// the email and password validation is here
// if error is found its pushed into the $error_msg array
// find the user corresponding to the given email address
$sql = "SELECT user_id, username, password, salt FROM users WHERE email = ? LIMIT 1";
$query = $this->db->query($sql, $email);
if ($query) {
if ($query->num_rows() == 1) {
$result = $query->row();
// user is found
// hash the pass with the salt
$password = hash('sha512', $password.$result->salt);
// check for number of tries
if ($this->check_brute($result->user_id) == TRUE) {
// account locked for repeated failed login attempts
$error_msg[] = "<p>Account is locked due to repeated failed login attempts.</p>";
// return FALSE;
} else {
// check password
if ($password == $result->password) {
$user_browser = $this->security->xss_clean($_SERVER['HTTP_USER_AGENT']); // browser
$user_id = preg_replace("/[^0-9]+/", "", $result->user_id);
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $result->username);
// i want to set the cookie expiry time depending on the
// remember me checkbox
if ($_POST['remember']) {
}
// i am guessing somekinda cookie manipulation should
// take place here
// assign session variables
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password.$user_browser);
return TRUE; // login success
} else {
// wrong password input
// add activity in database
$sql = "INSERT INTO login_attempts (user_id, time) VALUES (?, ?)";
$this->db->query($sql, array($result->user_id, time()));
$error_msg[] = "<p>ERR PASS: Username/password combination is incorrect.</p>";
// return FALSE;
}
}
} else {
// user doesnt exist
// return FALSE;
$error_msg[] = "<p>NO USR: Username/password combination is incorrect.</p>";
}
}
return $error_msg;
}
And this is the code for the session starting:
public function sec_session_start() {
$session_name = "sec_session_id";
$secure = FALSE; // dev mode
$httponly = TRUE;
if(ini_set('session.use_only_cookies', 1) === FALSE) {
$error_msg = '<p>Could not initiate a secure session.</p>';
return $error_msg;
}
$cookieParams = session_get_cookie_params();
session_set_cookie_params(
$cookieParams['lifetime'],
$cookieParams['path'],
$cookieParams['domain'],
$secure,
$httponly);
session_name($session_name);
session_start();
session_regenerate_id(TRUE);
return TRUE;
}
The only place where there is a reference to cookies is in the logout function where it is unset. What should I do to set the cookie expiry time when a user logs in depending on their choice on "Remember me"?
I had the same problem using this script and this is the solution that I came up with.
In your login function, add this code:
(I am assuming $_POST['remember'] will be = 1 if user wants to be remembered, 0 otherwise)
if ($_POST['remember']) {
$_SESSION['remember'] = $_POST['remember'];
}
Then in the function sec_session_start() add this after session_start():
...
session_name($session_name);
session_start();
if($_SESSION['remember'] == 1){ session_set_cookie_params(60*60*24*60); }
session_regenerate_id(true);
...
The lifetime can obviously be changed to suit you. I chose 2 months for this example.
What this code is effectively doing is setting another session which contains the information as to whether or not the user wants to remembered.
The cookie is then initially set with the default value that your server has set for session lifetimes, but if the remember session has a value of 1, it changes this to the lifetime you have set.
I've not extensively tested this so let me know if any issues arise.
I've finally got the courage to make a user login system after who knows how long of putting it off. My only problem is that when I submit the login form it reloads the page and it says that I am logged in, great.
However if I reload the page or go to another page and come back to the original page it forces me to login again. Can anyone help with this? I have a session_start() in the base file that is included in all other page files before the database connection.
I then have the following code for my user login side of things, which as I said, works the first time around, but after that any other interaction will essentially log me out. Any help with this?
The user page which logs you in and creates the session...
Please note that this isn't a live environment so security is being put on the bench for now. However I am aware I will need some security measures in place in the future though.
// Check if the user is logged in or not
if((!empty($_SESSION['loggedin'])) && (!empty($_SESSION['username']))) {
$loggedin = true; // The user IS logged in
} else {
if(isset($_POST['login'])) {
// The login form has been submitted
if((empty($_POST['username'])) || (empty($_POST['password']))) {
// If either username or password fields are blank
$loginfail = true; // If the user could not be logged in
if(empty($_POST['username'])) { $nousername = true; }
if(empty($_POST['password'])) { $nopassword = true; }
} else {
// Username and password field were filled in okay
$username = $_POST['username'];
$password = $_POST['password'];
$checklogin = mysqli_query($sql, "SELECT * FROM users WHERE username = '$username' AND password = '$password'") or die($checklogin . "<br/>" . mysqli_error($sql));
if(mysqli_num_rows($checklogin) == 1) {
// If the login details match up, log them in
$loggedin = true; // The user IS NOT logged in
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = 1;
} else {
// If the login details don't match up, don't login
$loginfail = true; // If the user could not be logged in
}
}
}
}
Thanks!