password protection to URL - php

I've a website and its access should be restricted. So, on entering the page, before page load we should restrict the access with three fields i.e., username and password of client and specific password for that page, these three were created by me and are stored in a database.
I've basic knowledge of Javascript and PHP.
My idea is before the page load, Javascript should get the three field values entered by user and by PHP we have to validate using a database, if the match occurs then page should load if not the access to that page should be denied.
in brief on hitting URL and before page load connection to the database has to be made and user/client entered 3 fields should be taken and be verified with MYSQL database by PHP and on successful authentication page should be displayed.
Please come up with code suggestions. Thanks in advance :)

i have created a function which you may use:
<?php
function login($username,$password,$salt,$db,$table,$usercolumn,$passwordcolumn,$con)
{
$user=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$db=mysql_select_db($db,$con);
if(!$db)
{
return "connection error";
}
else
{
$sql="SELECT * FROM `$table` WHERE `$usercolumn`='$user';";
$enc=$password;
foreach($salt as $value)
{
if($value=="md5")
{
$enc=md5($enc);
}else
{
$enc=crypt($enc,$value);
}
}
$resource=mysql_query($sql);
$row=mysql_fetch_array($resource);
$passdb=$row[$passwordcolumn];
if($passdb==$enc)
{
$sucess=true;
}else
{
$sucess=false;
}
}
return $sucess;
}
?>
you may use this and if it returns true, that means username and passwords are correct now you have to validate your third option...
to use this function, you just need to call like this after copying that function to a file, if it is named to "logger.php",
<?php
require("logger.php");
$enc=array("salt","md5","differentsalt")//your encryption such as if you have encrypted using 'salt' at first then using md5 hash and again 'differentsalt',then you need to give like i have given
if(login($username,$password,$enc,$db,$table_name,$usercolumn,$passwordcolumn,$con))//$username is the username which user supplied,$password is password user supplied,$enc is the encryption and it must be an array... which is also given above,$db is database name,$table_name is the table where username and encrypted password are stored,$usercolumn is the column name where username are stored, $passwordcolumn is the column where encrypted password are stored, and last $con is the connection identifier, you may have given, $con=mysqli_connect("username","password");
//if all the parameters are supplied correctly, it will check for the username and password matching and you will have to check the third option
{
//now validate your third option here...
//if you are here, that means password and username has matched
}
else
{
//this means username and password didnt matched... so output the error
}
?>
for accepting username and password, you may create a form and ask password there and then submit...

Related

laravel 5 Hash::check not working

I want to check whether old password which user typed is matched with DB password using check hash, but its not working correctly please advice.
Below is my code which I used to update password function
fields which required are old_passwrord, new_password.
Currently it doesn't go to hash check fucntion and directly update password.
else if (Hash::check('password', $getPassword->password))
{
return ['error'=>['code'=>206, 'message'=>'old password is not matching']];
}
Replace
else if (Hash::check('password', $getPassword->password))
with
else if ( ! Hash::check('password', $getPassword->password))

Store the User information in a object on each load or grab the info when action is made

I have a Session which contain the "user id"
I have some information stored in the user table (that I need to grab)
The question is If I should grab all data and put it in a object on each request or just make the query when an action is made?
Example #1
//Update Password
//a user object contain all data from users table...
if ($user->password == $new_password) {
$errors[] = 'You can\'t choose the same password!';
}
Example #2
//Update Password
//$current_password = query password and fetch
if ($current_password == $new_password) {
//...
}
Etc...
For simple projects, it is best to put that data in a "user object", in the session. But, only place data in that object that is not subject to rapid change, such as their username, userid, privilege level, etc.
More to the point, do not keep the user's password hash in the session, and especially do not store the user's password in plaintext in your database or in the session data. By the looks of it, I believe you may be doing just that.
Instead, use a hash function to secure the password data from reversibility.

Sharing login and password for personal project with osCommerce store

I'm integrating an application with the osCommerce shopping cart and want users to be able to log into the app with the same account details they do with osCommerce.
Everything works fine but I got stuck on the user login system. I need to know how to check against a user entered password in my application against the osCommerce user's credentials. They're using a combination of MD5 and salt for generating the password.
How can I use that method to check my user's password?
To check against the password saved in osCommerce, just use the osCommerce function that checks the attempt against the one stored in the database. You'll find this function in the following:
catalog/includes/functions/password_funcs.php
////
// This funstion validates a plain text password with an encrpyted password
function tep_validate_password($plain, $encrypted) {
if (tep_not_null($plain) && tep_not_null($encrypted)) {
// split apart the hash / salt
$stack = explode(':', $encrypted);
if (sizeof($stack) != 2) return false;
if (md5($stack[1] . $plain) == $stack[0]) {
return true;
}
}
return false;
}
So all you need to do is extract the password column from the customers table, based on their entered email address, and compare.
tep_validate_password(password_attempt, password_from_osC)
If you're just going to include it, make sure you also include the catalog/includes/functions/general.php file since that's where the tep_not_null function is defined.

Limiting the number of failed login attemps

I want to limit the failed login attempts. For example, if a specific user attempt to login with wrong username or password 4 times, i should show the CAPTCHA 4th time instead of blocking for some specific time, and keep showing CAPTCHA unless he supplies valid username and password. Once the user has successfully logged in, the login attempt is reset to ZERO.
Is the idea of checking the username instead of IP address OK in security point of view? Can this approach be implemented without using database?, as I think I don't need to store time because i will just show recaptcha?
Please give your opinion.
You don't want to use the database for the 'number of failed logins'-check? Then just use a cookie and check it. Sure, they can remove it, but it's a hassle.
However, I suspect that you already are getting the username and password from the database, why not also fetch the last number of failed logins while you are at it?
if (isset($_POST['submit_login'])) {
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
// id = unique primary key
$rs = mysql_query('SELECT id,Username,Password,Failed_logins,IP_address FROM Users WHERE Username = '.$username.'');
$num = mysql_num_rows($rs);
if ($num > 0) {
// I would add a password hash here to $password, and check against the hashed Password from the database
// But let's check the clean passwords
$row = mysql_fetch_array($rs);
if ($password == $row['Password']) {
// Successful login, set session or whatever you need
// Reset failed logins
mysql_query('UPDATE Users SET Failed_logins = 0 WHERE id = '.$row['id'].'');
header('location: success.php');
} else {
// Failed password check
if ($row['Failed_logins'] > 3) {
// Redirect to captcha
header('location: captcha.php');
} else {
$ip = $_SERVER['REMOTE_ADDR'];
if ($row['IP_address'] != $ip) {
// New ip adress, reset failed logins
$failed_logins = 0;
} else {
// Increment failed logins
$failed_logins = $row['Failed_logins']+1;
}
mysql_query('UPDATE Users SET Failed_logins = '.$failed_logins.',IP_address = '.$ip.' WHERE id = '.$row['id'].' ');
} // End check Failed_logins > 3
}
} else {
// No such Username found in database
$error = 'no_such_username';
} // End username check from database
} else {
// Either username or password is missing
$error = 'incomplete_form';
} // end check for username and password
} // end main submit_login check
Something like that.
EDIT:
This is really old code and I see some problems with it now. But, at least you should always use PDO (prepared statements) for inserting data in your database.
What are you protecting?
Random user-only content, username.
Banking information (I doubt..) or other sensitive data, IP might be okay, provided you use ranges.
Are you asking how to do it, or which you should use?
You do need time, how would you otherwise determine if an login attempt has expired? If I would fail to login 4 times over a 10 year time span I would get blocked. You want to block those who attempt multiple login attempts in a short time span.
I suggest you use an database - as you will keep an detailed history of logins at the same time. But an memory based solution like memcached could also suffice.
To elaborate on which security to implement: a combination!
Combine the used username and ip address and store them into your database.
Use the login attempts on your username to directly protect your users from attempts.
Use the ip address information to observe an detect only, and take action if needed.
You should save the attempts in a database and check the user.
The best way to do this is to use databases.
You need to create a separate table in your database, which would store three variables :
(a) IP address (where the person is trying to log in)
(b) Number of login attempts
(c) date/time (or : current-timestamp)
The ONLY problem with this approach is with the first variable : IP address
What if the person is in an Internet Cafe? Or using public Wi-fi? Or Hotspot? Or, a school? office? etc, etc
If you block the IP address, it affects everybody who is trying to log into your website from that location.
This is not a problem if your website concerns something like a bank, or military installation, or the Pentagon.
But, if your website is a business (buy-and-selling, game, whatever), then blocking a specific address will only piss off your customers!

help using password instead of gravatar

i am using jquery chat tutorial
for chatting. I am working on this to make registration separately using a username and password.
Right now it is taking username and gravatar for registration. I changed my code for registration. But if it gets a username in the database, it just updates its timestamp and password leaving the username unchanged. But i want to show error if the username already exists. How can i achieve this goal?
Also it is deleting the user from database after some time of idle state. How can i remove this functionality?
Set the name field in webchat_users to unique. Or insert following lines of code into your PHP class:
$userEnteredName = 'John';
$row = mysql_fetch_assoc(DB::query("SELECT `name` FROM `webchat_users` WHERE `name` LIKE '".mysql_real_escape_string($userEnteredName)."' LIMIT 1"));
if(!empty($row['name'])) {
// Username taken
die('Username taken.');
} else {
// Proceed registration.
}
For your second problem: Simply remove line 33 & 34 from Chat.class.php.

Categories