PHP simple method to check if user can access page - php

Use Case:
Some areas of a website is restricted for member only, if user is logged in display page else redirect to login / registration form.
My Logic
I created a method inside the Users() class which simply check if a $_SESSION['userID'] is set.
The logic is if the $_SESSION[] is not set, then the user is not logged in since the $_SESSION['userID'] variable gets set on login. I came up with the following...
Method
public static function isLogged(){
if(!isset($_SESSION['userID'])){
header(':Location: login.php');
die();
}
}
Considering the above, I simply add the isLogged() method to the start of the page, and if the $_SESSION('userID') super global is not set the user gets redirected.
My Problems / Questions
The problem with the above is I cant out my mind to rest since:
The method seems inefficient...i.e there is a better (more efficient way of doing this)?
Im unsure whether there are any work arounds that unauthorized users can perform to view the page
I'm perhaps missing some critical info inside the isLogged() method?
Additional INFO
Login Method
public function login_user($newEmail, $newPword)
{
global $db;
$this->email = $newEmail;
$this->password = $newPword;
$sql = "SELECT * FROM bru_users WHERE email = :email AND password = :pword";
$stmnt = $db->prepare($sql);
$stmnt->bindValue(':email', $newEmail);
$stmnt->bindValue(':pword', $newPword);
$stmnt->execute();
$is_registered = $stmnt->rowCount();
if ($is_registered > 0) {
$users = $stmnt->fetchAll();
foreach ($users as $user) {
$userInfo[] = array('userID' => $user['userID'], 'email' => $user['email'], 'userName' =>$user['userName'], 'firstname' => $user['firstname'],
'lastname' => $user['lastname'], 'reg_date' => $user['registration_date']);
}
if(isset($userInfo)){
foreach ($userInfo as $start) {
$_SESSION['userID'] = $start['userID'];
$_SESSION['email'] = $start['email'];
$_SESSION['userName'] =$start['userName'];
$_SESSION['firstname'] = $start['firstname'];
$_SESSION['lastname'] = $start['lastname'];
}
}
} else {
return false;
}
return true;
}
Would greatly appreciate it if a more experienced coder can have a quick scan through this. Many Thanks

The method seems inefficient...i.e there is a better (more efficient way of doing this)?
No, session variables are reasonably efficient. This is the normal way of doing it.
Im unsure whether there are any work arounds that unauthorized users can perform to view the page
Only if they can hijack the session of an authorized user. But then pretty much all bets are off as far as user authentication. Hijacking a session would require them to get the other user's cookies. If you encrypt your connections with SSL, you're as safe as you can get.
I'm perhaps missing some critical info inside the isLogged() method?
Nope, that's all there is to it.

Related

Sometimes Trying to get property of non-object

After login after some random time when i refresh any page on website, sometimes it works perfectly, but sometimes it shows error like Trying to get propert on different lines of model and controller file.
For example, when i refresh the page error was shown in below function of model named user_model and controller named User.php:
User_model.php:
public function get_client_id($email)
{
$this->db->select('id');
$this->db->where('email', $email);
$query = $this->db->get('crm_accounts');
$result = $query->row();
return $result->id; //line 135
}
Users.php:
$email = $_SESSION['email'];
$id = $this->user_model->get_client_id($email); //line 145
Setting the session value after login:
$email = $this->input->post("email");
$password = $this->input->post("pass");
$result = $this->user_model->login($email, $password);
if ($result == TRUE)
{
$this->session->set_userdata('email',$email);
$this->session->set_userdata('logged_in',TRUE);
$data = $this->user_model->get_username($email);
$this->session->set_userdata('data', $data);
redirect('admin_view');
}
else
{
$this->load->view('all_field');
}
code for deleting the session after logout:
$logged_in = $this->session->userdata('logged_in');
$log = $this->session->userdata('email');
if($logged_in || (!empty($log)))
{
$array_item = array('email', 'logged_in');
$this->session->unset_userdata($array_item);
redirect('');
}
else
{
$this->load->view('error_page');
}
Here, i got error on like
Tring to get property of non-object on line 135 of user_model.php and in backtrace it found error on Users.php on line 145
I have noticed that when i get this type of error in model, i am getting data in that particular method using session variable $email in which the session data is stored. But i have put such condition in controller:
public function index()
{
if(!empty($_SESSION['email']))
{
$email = $_SESSION['email'];
$data = $this->user_model->get_username($email);
$this->session->set_userdata('data',$data);
redirect('clientview');
//echo "You are already logged in";
}
else
{
$this->load->view('signup');
}
}
So, if the value of session variable $email is not set than it should go on signup page.
So, i am not getting what is actually problem. Because sometimes it works perfectly and sometimes not. Once if i get such error, i have to clear my history and than i have to log in again.
In Codeigniter you have a specific way to get form or set values in the session.
If you want to check if the session exist you need to do
$this->session->userdata('email');
Which will retrieve the stored value.
And as you already do:
$this->session->set_userdata('email', $email);
To set a value in the session.
Additionally when the user is logging out yoi need to reset the stored value, ptherwise it will never be empty.
$this->session->set_userdata('email', '');
NOTE: What you are doing is of course not the best way to do such kind of stuff, as a login and logout system. I suppose you are just learning and you are doing this not for a production application.
If you do, please try to use ionAuth authentication library for Codeigniter, that you can find here:
http://benedmunds.com/ion_auth/
And follow some tutorial about it:
http://www.tutorials.kode-blog.com/codeigniter-authentication
Just keep in mind that user authentication is a serious security matter so be carefull.

PHP login and session establishment

I have a problem, I searched around a bit but could not find anything that would help me in my particular case.
I come to the point, I created a small function to log log (), inside of course step the variables $ username and $ password, everything works.
The problem is that last night I made a small change, inserting a string of code after the passage of SESSIONS, who was setcookie etc etc because I believed that in doing so the user's connection to last for a long time (I'm no expert).
This morning, the session was timed course, it makes a new login but the data are not passed. (So the User Account box is not refreshed with your username etc.).
I'll post some code:
class User {
private $db;
private $username;
private $password;
/**
* Construct
* #param type $pdo
*/
function __construct($pdo){
$this->db = $pdo;
}
public function login($username, $password){
$this->db->query("SELECT * FROM users WHERE username = :username AND status = :status LIMIT 1");
$this->db->bind(':username', $username);
$this->db->bind(':status', 1);
$row = $this->db->single();
$count = $this->db->rowCount();
if ($count > 0) {
if (password_verify($password, $row['password'])) {
$_SESSION['session'] = [
'id' => $row['id'],
'username' => $row['username'],
'email' => $row['email'],
];
return true;
} else {
return false;
}
}
}
public function isLoggedIn() {
if (isset($_SESSION['session'])) {
return true;
}
}
I do not understand what happened, I hope that I explained to the fullest, I apologize for my bad English.
Also another question, is it safe enough to protect the pages?
Some users told me to register the token, but do not know how to do.
Thank you
Try removing
","
after 'email' => $row['email'],
And yes, If not started your session, use
<?php session_start() ?>
Get PHP Session Variable Values
session variables are not passed individually to each new page,
instead they are retrieved from the session we open at the beginning
of each page (session_start())
Straight from http://www.w3schools.com/php/php_sessions.asp. In your case you have to start your session. You can start your session by using session_start();. But remember to do it once at the beginning of your script.

Session lost for user login

I ask for help to you, I explain my problem. In my User () class, I wrote a small function to log in, then recording sessions and setting cookies.
Here it is:
public function login($username, $password) {
$this->db->query("SELECT * FROM users WHERE username = :username AND status = :status LIMIT 1");
$this->db->bind(':username', $username);
$this->db->bind(':status', 1);
$row = $this->db->single();
$count = $this->db->rowCount();
if ($count > 0) {
if (password_verify($password, $row['password'])) {
$this->setSession($row);
return true;
} else {
return false;
}
}
}
public function setSession($row) {
$_SESSION['session'] = [
'id' => $row['id'],
'username' => $row['username'],
'email' => $row['email']
];
//set cookie
setcookie("name_cookie", md5($_SESSION['session']['username']/$_SESSION['session']['password']), time()+3600 * 24 * 365);
}
And here is the function to check if the user is connected or not, to protect the pages:
public function isLoggedIn() {
if(isset($_SESSION['session'])) {
return true;
}
return false;
}
My problem would be that even if cookies are set, unfortunately the session after a total time expires.
I set the cookies to a year, but as I said, the user's login session expires after a while. How can I correct this?
PHP sessions expire at the server level. The default is around 20 minutes, and you can control this in your php.ini settings.
You could use setcookie to save a cookie to the user's browser, and then check it using the $_COOKIE variable in PHP. See setcookie.
But be aware of the security risks with this. Anyone can steal the cookie and then get access to the site as that user. Some good ideas for securing your cookie can be found here.

PHP Login system hard coded username and password

I had to do a basic login system to protect a page, and I have no access to database so i store the username and password hard coded in php page.
My question is, can this login system hold againts an attack? I need it to hold about 1 month.
Any sugestions to improve will be helpefull.
The code is not in laravel, even if it might look like.
The username and password, will be changed to something stronger of course.
Thank you in advance.
<?php
class UserController {
private $username;
private $password;
private $isLoggedIn = false;
// Credentials
public function credentials() {
$credentials = array(
array(
"username" => "telekom",
"password" => "1234"
),
array(
"username" => "telekom2",
"password" => "1234"
)
);
return $credentials;
}
// Basic login
public function login() {
foreach ($this->credentials() as $credential) {
if ($this->username == $credential['username'] && $this->password == $credential['password']) {
Session::put('username', $this->username);
Session::put('password', $this->password);
$this->isLoggedIn = true;
}
}
}
// Get login status
public function isLoggedIn() {
return $this->isLoggedIn;
}
// Logout
public function logout() {
// Delete all sessions
Session::all();
redirect('/telekom/');
}
// Telekom
public function telekom() {
$form = new Form();
if (Input::get('logout') == 1) {
$this->logout();
}
// Post Data from login form
if (Input::has('username') || Input::has('password')) {
if (!$form->isCsrfValid()) {
$form->errors['CSRF'] = "CSRF Token";
} // CSRF protection is on, comment to disable
if (empty($form->errors)) {
$this->username = Input::get('username');
$this->password = Input::get('password');
// Check Login
$this->login();
if (!$this->isLoggedIn()) {
Session::put('login', 'Username and password do not match.');
} else {
redirect('/telekom/');
}
} else {
Session::put('login', '<p class="color-dark-red"><strong>Errors:</strong></p>
<p>' . $form->displayErrors($form->errors) . '</p>');
}
// Check if session has username and password
} elseif (Session::has('username') && Session::has('password')) {
$this->username = Session::get('username', false);
$this->password = Session::get('password', false);
// Check Login
$this->login();
}
}
}// EOF Class User
// Outside class
$user = new UserController();
// Outside class
if (!$user->isLoggedIn()) {
// display login form
} else {
// display protected content
}
?>
My comments are getting lengthy, so I'll just move them here. I would not recommend you put the username and password in the same file. If PHP ever fails to process the page, it will be dumped as plain text to the user. Even for database connections (where the un/pwd almost have to be stored plain text), most people don't put the information in the same file.
You have a couple options:
Make a separate PHP file that sets your UN/PWD variables, put it somewhere that isn't accessible from outside your server, and include it in index.php. In this case, I wouldn't include the file until right when you're going to compare the variables and let the local scope dump it as soon as possible.
Since this is such basic authentication, you could use Apache's built in password authentication module.
in my opinion, this solution is safe enough when you don't plan to use it forever.
What would I check is setting of your web server - some text editors makes backup copies of edited files, like index.php~, index.php.bkp or so. Make sure whether your web server do not serve those files, if any.
The problem with temporary solutions is that they've never temporary.
Never hard code passwords. Some of the reasons are:
It is harder to keep source code secret than it is a key.
Any vulnerabilities in your site that allow reading of source code may reveal the password.
Passwords from development will end up in production.
It is impossible to change passwords without redeploying.

Php login system, how to secure it

A php newbie here.
Below is the code I'm using to build a login system to enter mypage.php
It's working great but it is quite naive, anyone can type mypage.php in the url and avoid the login page.
How can I build it more secure?
Thanks a lot!
if(isset($_POST['submit'])) {
$user = $_REQUEST['user'];
$pass = $_REQUEST['pass'];
$sql = "SELECT * FROM login WHERE user='".$user."'";
$res = $this->new_db->select($sql);
$row = $this->new_db->get_row($res);
if (isset($row)) { //user exists?
if($row["pass"] == $pass){
$_SESSION['userId'] = $row['user'];// TRYING WITH SESSIONS
header("Location: mypage.php");
} else {
echo "wrong pass";
}
} else {
echo "user does not exist";
}
}
Then in mypage.php
if(isset($_SESSION['userId'])) {
//contents
} else {
echo "there's an error";
}
It is printing "there's an error"
why??
Thanks a lot
Three things:
Don't store passwords in plain text. Given this code, I can only assume that's what you're doing. You should store the passwords hashed, hash the password the user enters, and compare those.
You have a SQL injection vulnerability. Any time you're receiving input from the user that's destined for a database query, at the very least you should wrap it in mysql_real_escape_string().
On the logged-in page (on any logged-in page) you'll want to track whether or not the user is logged in. One simple way to do this is to have the login form set a $_SESSION value indicating the user's current logged-in status. Then on any page which requires a user to be logged in, check for that value. If it exists, they've previously logged in. If it doesn't, they haven't. It's simple, but good enough to get your going for what you need.
yes, there might be sql-injection in your code
in order to prevent you may use mysql_real_escape_string function
Check my answer here i posted before some time, which explains how you should go with login systems.
Open-source rich HTML editor
You will need to put something in mypage.php to check to see if the user is "logged in". I have done this in the past with the Zend Auth module from the Zend Framework. The cool thing about it is it can be used alone, (you don't have to make a whole Zend Framework site to use the Auth module). I used the Zend Auth Page to figure out how to use it.
Then, once I setup the auth session using the Zend Session, I just checked at any other page to see if the user was "logged in" with something like this:
private function _loggedIn()
{
$loggedIn = false;
$Namespace = new Zend_Session_Namespace('Zend_Auth');
foreach ($Namespace as $index => $value) {
$loggedIn = ($value->user_id);
}
return $loggedIn;
}
First of all, you have to protect your mysql query from sql injection. This can be achieved by adding mysql_real_escape_string like that:
$user = mysql_real_escape_string($_REQUEST['user']);
Then, if you don't want users to be able to visit mypage.php without being logged in, you should set some cookie in your login script if the login is successful, and then, on mypage.php, check that cookie to see if it matches in your database. Something like that:
login.php:
if($row["pass"] == $pass){
setcookie("userid",$user);
setcookie("passhash",sha1($pass));
...
mypage.php
$res = mysql_query("select * from login where user='".mysql_real_escape_string($_COOKIE['userid'])."' limit 1");
$row = mysql_fetch_assoc($res);
if($_COOKIE['passhash'] == sha1($row['pass']))
{
die("logged in OK");
}
else
{
die("please log in");
}
if (isset($_POST['submit'])) {
$user = $_REQUEST['user'];
$pass = $_REQUEST['pass'];
$sql = "SELECT user FROM login WHERE user='".mysql_real_escape_string($user)."' AND pass=SHA1('".mysql_real_escape_string($pass)."')";
$res = $this->new_db->select($sql);
$row = $this->new_db->get_row($res);
if ($row['user'] != "") { //user exists?
header("Location: mypage.php");
}else{
echo "username and password combination is wrong";
}
}

Categories