Stop user to access Admin panel in php - php

I am trying to make a login system for normal user and AdminUser. If a normal user types in browser http://localhost/project the login screen comes in and user can login using his Id and Password. But while logged in if user types in browser http://localhost/project/admin the normal user also gets the access in adminpanel which i want to stop. How can I do that ?I am stuck here for long time. Any Help Please?
Login for user:
$query = "SELECT * FROM user WHERE eid='$eid'and password='$password'";
$result = $db->select($query);
if ($result != false) {
$value = $result->fetch_assoc();
Session::set("login", "userLogin");
Session::set("username", $value['username']);
Session::set("email", $value['email']);
Session::set("uid", $value['uid']);
Session::set("image", $value['image']);
header("Location: index.php");
} else { $loginErr = "Username
or Password Not Matched !!";}
Session function for User:
public static function checkSession(){
self::init();
if (self::get("userLogin")!== false) {
self::destroy();
header("Location:login.php");
}
}
Session check for User:
Session::checkSession();
Login for admin
$query = "SELECT * FROM afcadmin WHERE adminname='$adminname'and password='$password'";
$result = $db->select($query);
if ($result != false) {
$value = $result->fetchassoc();
Session::set("loginadmin", "adminLogin");
Session::set("adminname", $value['adminname']);
Session::set("adminemail", $value['adminemail']);
Session::set("adminid", $value['adminid']);
header("Location: index.php");
} else {
$loginErr = "Usernameor Password Not Matched !!";
}
Session function for admin:
public static function checkSessionAdmin(){
self::init();
if (self::get("adminLogin")!== false) {
self::destroy();
header("Location:login.php");
}
}
Session check for admin
Session::checkSessionAdmin();

You don't have to be using different tables for the user and admin login. You just need a column that will help you check if a user has admin privileges. For example: You could create an is_admin column and set it's value to 1 if the user is an admin and 0 if he/she isn't.
# Your query
$stmt = "SELECT
users.id as uid,
users.username as username,
users.is_admin as is_admin
FROM users
WHERE users.username='{$username}'
AND users.password='{$password}'
LIMIT 1
";
You then add the results to a session like you are doing already.
var_dump($_SESSION['user']);
Array {
'uid' => '125',
'username' => 'SomeGuy',
'is_admin' => '1',
}
Your session will now contain a value is_admin and so you can check if a user is an administration by using a simple if statement.
if ($_SESSION['user']['is_admin'] == 1) {
// Admin only stuff here
}

As I can see you having two separate tables for user and admin to store their data, so i think that shouldn't be any problem for your query, when its for user we can not stop to brows them any page.
But if user can use its own detail to log in admin panel that means you have multiple data in your both table, that may be caused because of you may insert same data in both table or there is something wrong in your insert Query.
But as a solution i think its better to add Roles field in both database which define where there its user or admin and after your select query make if condition to check if they fall in with your requirements and than set the session.
But From My point of view best thing is to have single Table for both Users and Admin to store all comment data and make Admin table to store user_id and some priority. when you make checking query check where there user_id is belongs to admin table or not and define them as admin or user and than set session.
This may solve your issue, but if need more help let me know.

You can have user_type field in the database and in the admin session you can see if the user_type is admin or customer. If its admin then redirect him to the admin dashboard otherwise to the customer dashboard. In the admin header, put a check for the same.
Hope this helps.

I've found the solution. I replaced the following code.
Code for User login:
Replaced Session::set("login", "userLogin"); by Session::set("login", "true");
Code for Session Function User:
Replaced if (self::get("login")!== false) by if (self::get("login")== false)
Code for Admin login:
Replaced Session::Session::set("loginadmin", "adminLogin"); by Session::set("adminlogin", "true");
Code for Session Function Admin:
Replaced if (self::get("adminlogin")!== false) by if (self::get("adminlogin")== false)

Related

PHP If/else/elseif with multiple conditions

Please note, similar questions have been asked multiple times.
**** Though, not this one as far as my search goes! ****
The goal:
I need help on how to build a script that shows the page with user settings. It should be based on account level and if the user_id matches with the variable of 'id' in the url. So, basically.. the admin should always be able to see the user settings no matter if the user_id matches the 'id' from the url.
The problem:
I can't get it to work with the two variables (user status = 'id' in url, and if the user is admin? Then always show) in a good way, since I don't want to duplicate the "juicy" stuff in two places.
My current state:
I'm thinking something like this:
#DB:USERS
user_id user_name user_level ....
1 ADAM 3 (admin)
2 BRYAN 1 (suspended)
3 CODY 2 (user)
4 DAVID 3 (admin)
CODE:
<?php
// Get the logged in user data..
$sql = "SELECT * FROM users where user_name = '".$_SESSION['username']."'";
$user_level = $row["user_level"];
$query... (SELECT * #DB:USERS);..
$url_id = $_GET['id'];
$user_id = $row['user_id'];
if ($url_id == $user_id) {
#Show all the juicy user setting stuff#
} else {
echo 'ACCESS DENIED';
}
?>
So far so good, but how to add the step that says, if the user status is equal to 3 (admin).. then show the jucy stuff anyway?
Thanks in advance!
If I understood your question, you need to test if user is admin in addition of the test of user ID, use or condition :
// not sure of variable name for userlevel
if ($url_id == $user_id || $_SESSION['userlevel'] == 3) {
#Show all the juicy user setting stuff#
} else {
echo 'ACCESS DENIED';
}

How can I make destroy session when I change my password?

I am an intermediate in CodeIgniter framework
I am going to develop a new system that having "Admin, Manager, Employee" Roles. I need if admin or manager changes any employee password, the employee session need to destroy and logout from their account.
I didn't have any idea about that. Anyone can help how to do this and for this which type of session save path I have to select?
There is a simple solution for that:
1 - Add a field in your users table called "forcelogout" for example, It can be an ENUM with 2 choices 'Y' or 'N' and default value 'N'
ALTER TABLE `users` ADD COLUMN `forcelogout` ENUM('Y','N') NOT NULL DEFAULT 'N' COMMENT 'Y: force user to logout, N: nothing to do'
2 - When updating the user password, update that field value to 'N'
3 - In you parent controller (application/core/MY_Controller.php), check "forcelogout" value and logout user if it's 'Y'. Then update the value to 'N' to avoid loop
public function __construct()
{
$this->do_we_need_to_logout_user();
}
private function do_we_need_to_logout_user(){
$this->load->model('users_model');
$user = $this->users_model->get_user($this->session->user_id);
if ( $user[0]->forcelogout == 'Y' ){
$user_id = $this->session->user_id;
$this->session->sess_destroy();
$user = array();
$user['forcelogout'] = 'N';
$this->users_model->update_user($user_id, $user);
redirect('/login');
}
}
Admin, manager side : They change employee password.
In Employee side : Each time you retrieve employee data, check if password status is changed. If so, then destroy session for the employee.
On successful login again, set password status to null or something.

Account activation, CodeIgniter

I want to create an account activation where after registering, a link would be sent to an administrator (or one) email whereby the admin just has to click that link to activate that account.
I have the registration and login working. I'm using MySQL Workbench and have a "flag" or rather just a field in my accounts table (named user_login) to tell whether the account is enabled or disabled, which is disabled by default after registration.
I am stuck and sending a link through email, I'm not sure where to begin. That link that I want to send would contain a random string and would be sent to the admin, say abc/123/random?stringis=1234. Then the admin would just have to open his email and click on the string and then that specific user's account would be activated. I found this and this but that's just for how to send a link through email.
I don't have an idea on the logic. Do I create a function whereby the link would go directly to the function and from there, it would change the value in my table to enabled or whatever I call it so that the user's account is counted as activated? Do I need to create a new field to match the random generated string then?
Main idea is I'm trying to do like those typical sites whereby a link would be sent to the user to activate the account once he/she clicks it in the email, but this time just to a specific email which is the admin's.
EDIT:
In controller
public function activate_user($activation_code)
{
$result = $this->home_model->activate($activation_code);
if($result != FALSE)
{
echo "You have activated :".$result[0]->user_id.".";
}
else
{
echo "Activation failed, something went wrong.";
}
}
In Model:
public function activate($activation_link)
{
$this->db->select('*');
$this->db->from('user_login');
$this->db->where('activation_link', $activation_link);
$query = $this->db->get();
if($query->num_rows() == 1)
{
return $query->result();
}
else
{
return FALSE;
}
}
First
Database
add two column
activation_token{varchar|255}
activation_time{datetime}
After registration Success
add some randome has into activation_token(md5 or sha1(up to you))
add time if registration using Current timestamp(now())
Link
link should be
I strongly prefer userid in activation url
because it's remove the link duplication.
http://sitename.com/activation/{user_id}/{hash}
in controller
public function activation($user_id,$hash)
{
$timeOfexpiration = 3600;
$data = $this->model->get_data($id,$hash);
if(!$data)
{
return false
}
//if user found
//check expiration of linke
//like
if($data['activation_time']+$timeOfexpiration < now())
{
return true;
}
else
{
return false;
}
}
for that you need to add one more field in table called activation_linkwhen user register in site then generate random string and store that in activation_link and send link to the user so once user back then check the link and activate that user.

Codeigniter Active records Account Validation

I have the following code:
MODEL:
function check_account($account_details){
$query = $this->db->get_where('admin', array('username' => $account_details['username'] ,
'password' => $account_details['password']) )->result_array();
if(!empty($query)){
return 'Admin';
}
else{
$query2 = $this->db->get_where('user_mst', array('username' => $account_details['username'],
'password' => $account_details['password']) )->result_array();
if(!empty($query2)){
return 'User';
}
else return FALSE;
}
}
I only posted my model because view only consist of input fields for username and password and in the controller it only retrieves the data inputted and passed on to the function in the model. The above code snippet is the function which was called by the controller.
I only have 1 log in page, it checks first if the account inputted exists in the admin table, if not, then checks if it exists in the user table. IF the account inputted does not belong to the 2 tables, it returns false.
I checked admin table first because accounts in the admin belongs to the minority. whereas in the user will be most of the majority accounts. For example, if i have 5 admin accounts and 1000 user accounts.
Instead of checking if the account inputted is one of those 1000 it firsts checks if it belongs to the 5 in the admin table.
Hope my explanation is clear or at least understandable.
My question is, when i input say, SampleAccount as username even though in the database its all in small caps it still returns as though its the same.
SampleAccount(inputted) = sampleaccount(database) - should not return in the query.
Also, i would like to read some professional's opinion on how im checking the account, or should i just make 2 login pages for both user and admins.
foreach($query as $arr => $result){
if($account_details['username'] == $result['username']){
echo ' equal';
}
else echo ' not equal';
}
If inputted is UseRname and in the database it is Username then this is ideal.
But is there anyway, to add this in the query itself?
get_where(); like limit, etc.
bro you had big mistake make 1 table but make coulmn name it role
check if 1 user 2 admin
function premission_check($role){
switch($role){
case 1 :
return 'user';
break;
case 2 :
return 'admin';
break;
default :
return 'bad role'
break;
}}

Checking whether a user already exists in drupal

When a user enters his login information and hits submit, i want to check if the user already exists or not.
So, i have the following two questions
1. Which hook is needed to be implemented , for the case when user hits the submit button on the login form. I need the username entered by the user.
2. How to check if a user already exists in drupal or not programmatically ?
Some sample code would be really appreciated.
Please help.
Thank You.
Drupal 7 provides a function to get a user object by name :
$user = user_load_by_name($name);
if(!$user){
// User doesn't exist
}
else {
// User exists
}
http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_load_by_name/7
This can be done with hook_form_alter:
function module_(&$form, &$form_state, $form_id) {
$user_login_forms = array('user_login', 'user_login_block');
if (in_array($form_id, $user_login_forms)) {
$form['#validate'][] = 'my_validate_function';
}
}
function my_validate_function(&$form, &$form_state) {
$name = $form_state['values']['name'];
// Drupal 6:
if (!db_result(db_query("SELECT COUNT(*) FROM {users} WHERE name = '%s';", $name))) {
// User doesn't exist
}
// Drupal 7:
if (!db_query("SELECT COUNT(*) FROM {users} WHERE name = :name;", array(':name' => $name))->fetchField()) {
// User doesn't exist
}
}
It's better to query the DB directly in this case than than using user_load as it hooks into other modules as well.
In Drupal 7, substitute for this in the validation function:
if (!db_query("SELECT COUNT(*) FROM {users} WHERE name = :name", array(':name' => $name))->fetchField()) {
// User doesn't exist
}
I realize this is almost 2 years old, but user_authenticate does this nicely.
$existing_user = user_authenticate($name,$password);
if($existing_user)
// user exists
else
// user doesn't exist
Hope this helps someone else.
You can try to look on these 2 modules for inspiration: friendly_register and username_check.

Categories