Role base access control system for admin and super_admin - php

I am trying to get this result -> Use access control logic for two user types: administrators and super administrators.
Administrators will have read access to all records within the system however they will have edit/delete access to only those records that are created by them.
Super administrators will have read/edit/delete access to all records. In this case what should i use? if any one know how to give Roll back accessing control in simple manner in above case then please tell me how to do this?
after login from admin_login.php my page comes here...
this is my controller page..
listing.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Listing extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('student');
$this->load->helper('url');
$this->load->helper('form');
$s = $this->session->userdata('admin_id');
log_message('error', 'Some variable did not contain a value.');
}
public function index()
{
$s = $this->session->userdata('admin_id');
$this->load->model('student',$s);
//$data['result'] = $this->student->listing();
$students = $this->student->listing();/////new line delete [resulet]time 5:42 29/03/16
//$this->load->view('list_view',$data); //// change here time 5:52 29/03/16
$this->load->view('list_view',array('students'=>$students)); /////listing->list_view name change
}
public function delete($id)
{
$result = $this->student->delete_operation($id);
$s = $this->session->userdata('admin_id');// session data call.
//$data['result'] = $this->student->listing();
$students = $this->student->listing();///new line 30/03 1230pm// change for list_view
$this->load->view('list_view',array('students'=>$students));///same as above//change for list_view
//$this->load->view('list_view',$data); ////////////////////////listing->list_view name change
}
public function edit($id)
{
if($id)
{
$s = $this->session->userdata('admin_id');
$result = $this->student->edit_record($id);
$data['action'] = 'edit';
$data['student_id'] = $result[0]->student_id;
$data['student_name'] = $result[0]->student_name;
$data['student_email'] = $result[0]->student_email;
$data['student_address'] = $result[0]->student_address;
$data['subject'] = $result[0]->subject;
$data['marks'] = $result[0]->marks;
}
$this->load->view('edit_student',$data);
}
public function add_student()
{
//$s['user'] = $this->session->userdata('admin_id');//get session data // new line30/03/16
$data['student_id'] = '';
$data['student_name'] = '';
$data['student_email'] = '';
$data['student_address'] ='';
$data['subject'] = '';
$data['marks'] = '';
//$data['admin_id']=''; //new line 12:39 30/03/16
$this->load->view('edit_student',$data);
}
public function add()
{
$data = array(
'student_name' => $this->input->post('txt_name'),
'student_email' => $this->input->post('txt_email'),
'student_address' => $this->input->post('txt_address'),
'subject' => $this->input->post('subject'),
'marks' => $this->input->post('marks'),
'admin_id' => $this->input->post('admin_id')//new line 12:39 31/03
);
$result = $this->student->add_record($id,$data);
header('location:'.base_url().'index.php/listing');
}
}

Probably the best way would be to use some roles in your system, for instance you can use the Ion auth library:
http://benedmunds.com/ion_auth/
With this you can define user groups (e.g.: user,administrator,superadministrator)
you can check the in_group() part of the manual to see how it works.
An example function to let you get some idea how can you check the record deleting:
function hasDeleteRight($record_author_id, $logged_in_user_id) {
// if the user has administrator role we check if he is the author of the record he can delete it
if ($this->ion_auth->in_group('administrator', $logged_in_user_id)) {
if($record_author_id == $logged_in_user_id) {
return true;
}
// if the user has superadministrator role he anyway can delete the record
} elseif ($this->ion_auth->in_group('superadministrator', $logged_in_user_id)) {
return true;
}
// other users cannot delete the record
return false;
}
You still can use this example as base of functions.
usage in your code:
public function delete($id)
{
$logged_user_id = $this->session->userdata('admin_id');
if(!hasDeleteRight($id, $logged_user_id))
{
return false;
}
//....your delete record code
update:
permission check without ion auth, only with session data and separated login (not preferred way):
in the super admin login code you can put the permission into session:
function super_admin_login() {
//your log in code
if($login_success) {
$this->session->set_userdata('permission', 'superadministrator');
}
}
similar for normal administrator login:
function admin_login() {
//your log in code
if($login_success) {
$this->session->set_userdata('permission', 'administrator');
}
}
function hasDeleteRight($record_author_id, $logged_in_user_id) {
// if the user has administrator role we check if he is the author of the record he can delete it
if ($this->session->userdata('permission') == 'administrator') {
if($record_author_id == $logged_in_user_id) {
return true;
}
// if the user has superadministrator role he anyway can delete the record
} elseif ($this->session->userdata('permission') == 'superadministrator') {
return true;
}
// other users cannot delete the record
return false;
}

Related

codeigniter admin panel automatic page creation

I want to create one controller file which is creating automatically a function if i create a menu dynamically and also want to create view page which is connencted to this main controller.. how to do that?
Current code:
public function our_history()
{
$data['category']= $this->menu_model->getCategory('$lang');
$data['subcategory']= $this->menu_model->getSubCategory('$lang');
$this->load->view('vwMain',$data);//Left Menu }
}
Follow below steps Hope that makes sense.
-- Admin section --
/*content.php -- controller starts here */
class Content extends VCI_Controller {
# Class constructor
function __construct()
{
parent::__construct();
$this->load->model('content_model');
}
/*
Add page logic
*/
function edit_page($id = null)
{
$this->_vci_layout('your_layoutname');
$this->load->library('form_validation');
$view_data = array();
//Set the view caption
$view_data['caption'] = "Edit Content";
//Set the validation rules for server side validation
// rule name editcontent should be defined
if($this->form_validation->run('editcontent')) {
//Everything is ok lets update the page data
if($this->content_model->update(trim($id))) {
$this->session->set_flashdata('success', "<li>Page has been edited successfully.</li>");
$this->output->set_header('location:' . base_url() . 'content/manage_content');
} else {
$this->session->set_flashdata('error', "<li>Unknown Error: Unable to edit page.</li>");
$this->output->set_header('location:' . base_url() . 'content/manage_content');
}
} else {
$page = $this->content_model->get_content_page(trim($id));
$view_data["id"] = $page->id;
$view_data["page_title"] = $page->page_title;
$view_data["page_menu_slug"] = $page->page_menu_slug;
$view_data["page_name"] = $page->page_name;
$view_data["page_content"] = $page->page_content;
$view_data["status"] = $page->status;
$this->_vci_view('content_editpage', $view_data);
}
}
/*
Edit page logic
*/
function add_page()
{
$this->_vci_layout('your_layoutname');
$this->load->library('form_validation');
$view_data = array();
$view_data['caption'] = "Edit Content";
if($this->form_validation->run('editcontent')) {
// after passing validation rule data to be saved
// editcontent rule must be defined in formvalidations file
//Everything is ok lets update the page data
if($this->content_model->add()) {
$this->session->set_flashdata('success', "<li>Page has been edited successfully.</li>");
$this->output->set_header('location:' . base_url() . 'content/manage_content');
} else {
$this->session->set_flashdata('error', "<li>Unknown Error: Unable to edit page.</li>");
$this->output->set_header('location:' . base_url() . 'content/manage_content');
}
} else {
$page = $this->content_model->get_content_page(trim($id));
$view_data["id"] = $page->id;
$view_data["page_title"] = $page->page_title;
$view_data["page_menu_slug"] = $page->page_menu_slug;
$view_data["page_name"] = $page->page_name;
$view_data["page_content"] = $page->page_content;
$view_data["status"] = $page->status;
$this->_vci_view('content_editpage', $view_data);
}
}
}
/**
* content.php -- controller ends here
*/
/*
Content_model starts here
*/
class Content_model extends CI_Model {
// update logic goes here
function update($id = null) {
if(is_null($id)) {
return false;
}
$data = array(
'page_title' => htmlspecialchars($this->input->post('page_title',true)),
'page_name' => htmlspecialchars($this->input->post('page_name',true)),
'page_content' => $this->input->post('page_content',true),
'page_menu_slug' => htmlspecialchars($this->input->post('page_menu_slug',true)),
'status' => htmlspecialchars($this->input->post('status',true))
);
$this->db->where('id', $id);
$this->db->update('content', $data);
return true;
}
// Add logic goes here
function add() {
$data = array(
'page_title' => htmlspecialchars($this->input->post('page_title',true)),
'page_name' => htmlspecialchars($this->input->post('page_name',true)),
'page_content' => $this->input->post('page_content',true),
'page_menu_slug' => htmlspecialchars($this->input->post('page_menu_slug',true)),
'status' => htmlspecialchars($this->input->post('status',true))
);
$this->db->where('id', $id);
$this->db->insert('content', $data);
return true ;
}
}
/*
Content_model ends here # Admin section changes ends here
*/
-- Add view files also to admin section content_editpage.php
Now go to your routes.php file for front section --
add below line at last --
$route['(:any)'] = 'page/view_usingslug/$1';
This will be for all urls like --- http://yourdomainname/your_slug_name
// create again a controller in front section page.php --
class page extends VCI_Controller {
function __construct()
{
parent::__construct();
}
function view_usingslug($slug='')
{
// retrieve the data by slug from content table using any model class and assign result to $view_dat
$this->_vci_view('page',$view_data);
//page.php will be your view file
}
}
Suppose Your URL is
www.example.com/controllername/methodname/menutitle1
or
www.example.com/controllername/methodname/menutitle2
So this is how you handle these pages.
public function method()
{
$menutitle = $this->uri->segment(3);
$query = $this->db->get_where('TableName',array('Menutitle'=>$menutitle))
$data['content'] = $query->row()->page_content;
$this->load->view('common_page',$data);
}

Cant write to database with cakePHP

I am new to cakePHP and am just starting to use it for my new job.
I have created an edit_company action in my Orders Controller. I updated the acos table to allow this action. Now the problem is, I can't access any sort of 'edit' action. It says "You are not authorized to access that location" whenever I try to acccess any action that writes or updates database. edit,edit_products,edit_shipping, etc...
The view action works just fine.
This was not happening before.
Heres a bit of the code:
class OrdersController extends AppController{
public $uses = array('Order');
public $hideActions = array('campaign','customer','shipping','review_order','place_order','products','payment','confirmation','cancel','edit_status','edit_order_type','edit_products','edit_tax','add_product','cancel_shipping_label','track_label','view_label','reprint_label','edit_shipping','create_shipping_label');
public $components = array('Payflow','Printer');
public $actionMap = array(
'create' => array('add','create','campaign','customer','shipping','review_order','place_order','payment','products'),
'read'=> array('index', 'view', 'display','confirmation','track_label','search'),
'update' => array('edit','cancel','edit_status','edit_order_type','edit_products','edit_company','edit_tax','add_product','cancel_shipping_label','reprint_label','edit_shipping','create_shipping_label'),
'delete' => array('delete','back_orders_by_state')
);
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('permissions','gen_acos');
}
public function permissions(){
$this->Acl->allow('Admin','Controllers/Orders');
$this->Acl->allow("Sales","Controllers/Orders",'read');
$this->Acl->allow("Sales","Controllers/Orders",'create');
$this->Acl->allow("Sales","Controllers/Orders",'update');
$this->Acl->deny("Shipping","Controllers/Orders",'update');
$this->Session->setFlash("Permissions Updated.");
$this->redirect("/orders/");
}
public function edit_shipping($id){
$sm_conditions = array();
if(!$this->Acl->check(array('User' => array('UserID' => $this->Auth->user("UserID"))), 'Controllers/Orders','delete')){
$sm_conditions['Restricted'] = 1;
}
$shipping_method_ids = $this->Order->ShippingMethod->find("list",array("conditions"=>$sm_conditions,"fields"=>array("ShippingMethodID","ShippingMethodName")));
$order = $this->Order->read(null,$id);
$this->set("order",$order);
$this->set("shipping_method_ids",$shipping_method_ids);
if($this->request->is('put')){
if($this->Order->save($this->data,null,array("ShippingAddress","ShippingMethodID"))){
$this->Session->setFlash("Order Shipping Updated.");
$this->Order->Note->create();
$this->Order->Note->save(
array("Note"=>array('OrderID'=>$id,"UserID"=>$this->Auth->user("UserID"),"NoteBody"=>"Order Shipping Information updated.","CreatedDate"=>date("Y-m-d H:i:s")))
);
$this->redirect("/orders/view/$id");
}
}else{
$this->request->data = $order;
}
}
public function create_shipping_label($id){
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if($this->request->is('put')){
$this->Order->save(array(
"Order"=>array(
"OrderID"=>$id,
"LabelPrinted"=>false,
"OrderStatusID"=>2,
"Notes"=>(!empty($this->data['Order']['Notes']))?$this->data['Order']['Notes']:null
)
));
$this->Session->setFlash("A new shipping label will be created momentarily.");
$this->Order->Note->create();
$this->Order->Note->save(
array("Note"=>array('OrderID'=>$id,"UserID"=>$this->Auth->user("UserID"),"NoteBody"=>"New shipping label will be created. ".((!empty($this->data['Order']['Notes']))?$this->data['Order']['Notes']:null),"CreatedDate"=>date("Y-m-d H:i:s")))
);
$this->redirect("view/".$id);
}else{
$this->request->data = $order;
}
}
public function cancel($id){
$order = $this->Order->read(null,$id);
if($this->request->is('post')){
//Check if note given
$this->Order->Note->data = $this->data;
if($this->Order->Note->validates()){
//Delete from Call table
$this->loadModel("Call");
$this->Call->deleteAll(array('Call.OrderID'=>$id));
//Add a note
$user_id = $this->Auth->user("UserID");
$this->Order->Note->create();
$this->Order->Note->save(
array("Note"=>array('OrderID'=>$id,"UserID"=>$user_id,"NoteBody"=>"Order Canceled. ","CreatedDate"=>date("Y-m-d H:i:s")))
);
$this->Order->Note->create();
$this->Order->Note->save(
array("Note"=>array('OrderID'=>$id,"UserID"=>$user_id,"NoteBody"=>"Reason For Cancellation: ".$this->data['Note']['NoteBody'],"CreatedDate"=>date("Y-m-d H:i:s")))
);
//Create a refund request if payment type is in TxType (1,2,3,7,11,9)
$txTypes = array(1,2,3,7,11,9);
$paid = 0;
foreach($txTypes as $txType){
$payments = Set::extract("/Payment[TransactionTypeID=$txType]/PaymentAmount",$order);
$paid += array_sum($payments);
}
if($paid>0){
$this->Order->refund($id,$paid);
}
//Change Status to Cancel (4) & LabelPrinted = 0
$this->Order->save(array("Order"=>array("OrderID"=>$id,"LabelPrinted"=>0,"OrderStatusID"=>4)));
//Update the total price
$this->Order->updateOrderTotal($id);
$this->Session->setFlash("Order was successfully canceled.");
$this->redirect("/orders/view/".$id);
}
}
$this->set("order",$order);
}
public function edit_products($id){
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if($this->request->is("post")){
$error = false;
while($error==false && ($oe=array_shift($this->request->data['OrderEntry']))){
if(!$this->Order->OrderEntry->save(array("OrderEntry"=>$oe))){
$error = true;
}
}
if($error==false){
$this->Session->setFlash("Products Updated.");
$this->Order->updateOrderTotal($id);
$this->redirect("/orders/view/$id");
}
}
}
public function edit_company () {
}
public function edit ($id=null) {
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if($this->request->is("post")){
$error = false;
while($error==false && ($oe=array_shift($this->request->data['OrderEntry']))){
if(!$this->Order->OrderEntry->save(array("OrderEntry"=>$oe))){
$error = true;
}
}
if($error==false){
$this->Session->setFlash("Products Updated.");
$this->Order->updateOrderTotal($id);
$this->redirect("/orders/view/$id");
}
}
}
Could anyone help me with this problem?
Thanks!
You are only giving non authenticaded users permission to access two actions:
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('permissions','gen_acos');
}
Add the new actions or log the user in before accesing the actions:
Giving permission to not authenticated users to your new actions:
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('permissions','gen_acos','edit_products','edit','cancel','create_shipping_label','edit_shipping');
}
If you don't want to grant access to non authenticated users to these actions login before trying to access them.
You can check more about Auth here
Also check this example that is part of the Blog Tutorial

Codeigniter - sessions not working through controller and view

I'm trying to make a login using sessions in codeigniter at the time the username and password match, but I can't get it. I'm doing this:
Controller:
public function __construct()
{
parent::__construct();
$this->load->model('main_select');
$this->load->helper('url');
$this->load->library('session');
}
...code when username and password match:
if($pass === $user){
$this->session->set_userdata(array(
'user_id' => $login['id_user'],
));//we create the session 'user_id'
}
here it is supposed that we created a session called 'user_id'
in the view it doesn't work, I have this:
if( !$this->session->userdata('id_user') ){
//see this content
//first content
}else{
//see this other
//second content
}
but I always see the same content('second content').
trying to destroy it (but not working):
public function logout()
{
//session_unset();
// destroy the session
//session_destroy();
$this->session->unset_userdata('id_user');
header("Location: ".base_url() );
}
what am I doing wrong? thanks
EDIT1:
$password = md5( $this->input->post('inputpassword') );
$login = $this->login_select->get_username($username);
//si no coincide
if( $login['password'] !== $password ) {}
Note : Always use database to handle user logins. (Code is related to database login check)
in your database create table with user and add this 2 fields.
username
password
Add some user logins to it
Then in your code
public function __construct()
{
parent::__construct();
$this->load->model('main_select');
$this->load->helper('url');
$this->load->library('session');
}
// logging
public function loging()
{
$user = mysql_real_escape_string($_POST['username']);
$pass = md5(mysql_real_escape_string($_POST['password']));
$validate = $this->main_select->validate_user($user,$pass);
if(empty($validate) || $validate>1)
{
//Not a valid user
//redirect to login page
$this->load->view('loging');
}
else
{
//valid user
//set the session
$array = array('user_id' => '$user');
$this->session->set_userdata();
//redirect to normal page
$this->load->view('home_page');
}
}
//logout
public function logout()
{
$result= $this->session->sess_destroy();
if ((isset($result)))
{
header("Location: ".base_url() );
}
else
{
}
}
In Model
public function validate_user($user,$pass)
{
$query = $this->db->query("SELECT * FROM user WHERE username= '$user' AND password='$pass'");
$result = $query->result_array();
$count = count($result);
return $count;
}
modify this line of changes then your script will work as id_user need to set first to use in script.
if($pass === $login['password'] && $user===$login['username']){
$this->session->set_userdata(array(
'id_user' => $login['id_user'],
));//we create the session 'user_id'
}
here $login['password'] and $login['username'] are data come from tables and need to change fieldname pass or user according to your user table.

how to insert a value to a foreign key using session without overriding the other sessions in codeigniter?

I hope you're doing fine. Can somebody help me with my problem? I have 2 tables. The other one is for customers, it has an auto-increment value for customer_id. The other table is for orders, it has an auto-increment also for its orders_id and a foreign key from the other table (customers).
When I insert a new customer, if it is successful, I want the page to be redirected to the add new order page. In inserting new order, the customer_id field in my orders table should have the same value as the newly added customer. Adding customer and adding new order is of different function in my controller. I am having an error 1452 when inserting the new order, which means the value inserted for the foreign key customers_id in the orders table is different with the value in the other table (customers).
Now, I've got this solution using session. My problem is the other session for getting the last id is overriding the session for logging in.
Here's some code snippets from my controller:
Class MyController extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->c_id = 0;
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
if($session_data['username'] == 'administrator'){
$this->load->database('sample');
$this->load->model('samplemodel_model');
$this->load->library('form_validation');
} else {
redirect('home', 'refresh');
}
} else {
redirect('login', 'refresh');
}
}
public function index() {
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
//code for validation here
$customers = $this->samplemodel_model->get_entries('customers');
if($this->form_validation->run() == FALSE) {
//Field validation failed.
} else {
//Insert $data
//$data = array('xxxxxx');
//data is something like that
$this->create($data);
}
}
else
{
//If there's no session it will redirect to login page
}
}
//add new orders
public function addOrders() {
if($this->session->userdata('last_inserted_id')) //if I use this session, I can get the last inserted ID but the session data for the login will not be retrieved.
{
$session_data = $this->session->userdata('last_inserted_id');
$orders = $this->samplemodel_model->get_entries('orders');
if($this->form_validation->run() == FALSE) {
//Field validation failed.
} else {
//Insert data
$data = array('customer_id' => $session_data['customer_id'],
'order_type' => $this->input->post('order_type'));
$this->createItem($data);
}
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
//create customer
public function create($data) {
//Insert data
$customers = $this->samplemodel_model->get_entries('customers');
//$data = array(xxxxx);
//somethin' like that for data array
$this->load->samplemodel_model->create('customers', $data);
//***********************************************************//
// get and save last id inserted //
//***********************************************************//
//query the database
$result = $this->samplemodel_model->get_last_inserted($this->db->insert_id());
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array('customer_id' => $row->customer_id);
$this->session->set_userdata('last_inserted_id', $sess_array);
}
return TRUE;
}
else
{
echo "<script type='text/javascript'>alert('error');</script>";
return false;
}
session_start('last_inserted_id');
//********************************************************//
// end //
//********************************************************//
redirect('myController/addOrders', 'refresh');
}
public function createItem($data) {
//Insert data
$orders = $this->samplemodel_model->get_entries('orders');
$data = array('customer_id' => $session_data['customer_id'],
'order_type' => $this->input->post('order_type'));
$this->load->samplemodel_model->create('orders', $data);
//I'm not so sure if it is in this function that I should place the unset for the session 'last_inserted_id'
redirect('home', 'refresh');
}
}
And in my model, I inserted another function which helps me saving the last id inserted. Here's it:
public function get_last_inserted($id)
{
$this -> db -> select('customer_id');
$this -> db -> from('customers');
$this -> db -> where('customer_id', $id);
$this -> db -> limit(1);
$query = $this -> db -> get();
if($query -> num_rows() == 1)
{
return $query->result();
}
else
{
return false;
}
}
PLEEEASE! HELP :'( I would really appreciate if you have any other ideas. THANK YOU SOOOOO MUCH!
The issue is that you're redirecting, Each HTTP request is it's own process with it's own variables, and each request can't access the variables set in other requests.
Try passing the customer ID as a parameter to addOrders(), you can then use the codeigniter way of passing params around :
http://www.example.com/controller/method/paramter
Check the docs :
https://ellislab.com/codeigniter/user-guide/general/controllers.html
under the segment : Passing URI Segments to your Functions
Other possible solution : Store the customerID in the session, or in a user object you instantiate when you create a new user, but that's more dependent of the use case.

How to take specific data from table and store it in a cookie codeigniter php?

I'm new to codeigniter and php, few days only, so I need a little help.
I'm trying to put some data in my cookie from table so I can check where to redirect user after login. In table users there are two columns named Admin and Company with one or zero if user is or not, and then i wish to insert that information to cookie.
function conformation in user_controler is:
function conformation(){
$this->load->model('user');
$q = $this->user->confr();
if($q){
$data = array(
'username' => $this->input->post('username'),
'Admin' => $this->input->post($a = $this->user->getAdmin), // get 1/0 from users column Admin
'Company' => $this->input->post($c = $this->user->getComp),
'login' => true
);
if( $a == 1 ){ //is admin redirect to admin view
$this->session->set_userdata($data);
redirect('user_controler/useradm');
}
if($c == 1){ //if company redirect to company view
$this->session->set_userdata($data);
redirect('user_controler/usercomp');
}
$this->session->set_userdata($data);// if common user redirect to user view
redirect('user_controler/userpro');
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
And in user model:
function getAdmin{
$this->db->where('Admin', 1);
$a = $this->db->get('users');
}
function getComp{
$this->db->where('Company', 1);
$a = $this->db->get('users');
}
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Also have site controller for checking login
class Site extends CI_Controller{
function __construct() {
parent::__construct();
$this->login();
}
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || login != TRUE){
$this->log;
die();
}
}
}
Of course it's not working because i should probably check these column some other way but I don't know how. I Also have enabled table ci_session and it's work perfectly without Admin and Company.
Hello and welcome to Stackoverflow.
Here are my updates to the code (I have annotated my changes):
function conformation(){
$this->load->model('user');
if($this->user->confr()){ //$q wasn't needed, as you are only using this twice
$user = $this->input->post('username'); //I have added this as I will be referring to it a couple of times.
$data = array(
'username' => $user,
'Admin' => $this->user->getAdmin($user), // Your method was questioning the original form looking for data that it would never find - This will question your model.
'Company' => $this->user->getComp($user), //Same as above
'login' => true
);
$this->session->set_userdata($data); //It doesn't matter who the user is, we shall set the data to start with.
if($this->user->getAdmin($user)){ //is admin redirect to admin view
redirect('user_controler/useradm');
}
elseif($this->user->getComp($user)){ //if company redirect to company view
redirect('user_controler/usercomp');
}
else { //Redirect non-privileged users.
redirect('user_controler/userpro');
}
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
Users Model:
function getAdmin($user){
$this->db->where('username', $user); //Before you was just returning everyone who is an admin This instead finds the user
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Admin"]==1) { return true; } //This finds if the user is a admin or not, and the function will now return a value (true)
}
}
function getComp($user) {
$this->db->where('username', $user);
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Company"]==1) { return true; }
}
} //Edited similar to the function above
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Lastly your login function:
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || $login != TRUE){ //You weren't referring to your $login variable
$this->log;
die();
}
}
Hopefully this helps with your problems, let me know if you need any amendments.

Categories