So I am in the process of making an admin panel for a client and I have setup a PHP
class which is called Login::isAdminLoggedIn.
So the way that I have to use this at the moment is by going through every page and adding it to the top.
Is there a way in which you can die()
a whole directory e.g.
--- Admin (die this one)
--- index.php (inherited)
--- logout.php (inherited)
As it takes a long time to go through and add them all and it's a lot of duplicated code.
If needed I can share the Login::isAdminLoggedIn
class.
If it can't be done with PHP
I am also using jQuery/Ajax
on the pages so that is also an option.
--- EDIT HERE IS THE CODE ---
<?php
class Login {
public static function isLoggedIn() {
if (isset($_COOKIE['TBCookie'])) {
if (DB::query('SELECT user_id FROM login_tokens WHERE token=:token', array(':token'=>sha1($_COOKIE['TBCookie'])))) {
$userid = DB::query('SELECT user_id FROM login_tokens WHERE token=:token', array(':token'=>sha1($_COOKIE['TBCookie'])))[0]['user_id'];
if (isset($_COOKIE['TBCookie_'])) {
return $userid;
} else {
$cstrong = True;
$token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
DB::query('INSERT INTO login_tokens VALUES (\'\', :token, :user_id)', array(':token'=>sha1($token), ':user_id'=>$userid));
DB::query('DELETE FROM login_tokens WHERE token=:token', array(':token'=>sha1($_COOKIE['TBCookie'])));
setcookie("TBCookie", $token, time() + 60 * 60 * 24 * 7, '/', NULL, NULL, TRUE);
setcookie("TBCookie_", '1', time() + 60 * 60 * 24 * 3, '/', NULL, NULL, TRUE);
return $userid;
}
}
}
return false;
}
public static function isLoggedInAdmin(){
$userid = Login::isLoggedIn();
$admin = DB::query('SELECT id FROM users WHERE id = :userid AND admin = 1', array(':userid' => $userid))[0]['id'];
if($admin === null){
die('You shouldn\'t be here <a href="index.php">Go Back</a>');
}else{
return intval($admin);
}
}
}
So how this works is it checks the cookie of the current user to one within a database of login_tokens
which has a column for user_id
, the user_id
is then returned from isLoggedIn
.
This is then taken in into isLoggedInAdmin
and checks whether the user with that id in users database also has an admin row equal to 1.
If admin is not found within the the user it gets returned null so then the page will die and say its message.
If the user has admin row equal to 1 then I return the userID
.
--- EDIT THE FUNCTIONALITY ---
If a normal user gets access to a link to the admin area I kill the page as they are not admin and do not want them to see any confidential stuff on tha back end that only admins are meant to see, this is done by calling the DIE
function within PHP.
When an admin comes along everything carries on as normal and they can access everything.
--- EDIT THE PROBLEM ---
The thing that I am asking is if their is a way to die
every page with lets say the "admin" directory
without having to go through and add the isLoggedInAdmin()
to the top of every page.