If there's someone logged in, this code checks the sessions and I can successfully view the page, but now I'd like to check if the user is admin. I tried checking in the model by Below is what I have tried and its not working.
method that checks session and if its an admin
public function index()
{
$this->load->library('authlib');
$loggedin = $this->authlib->is_loggedin();
///$admin = $this->auth->admin();
if ($loggedin === false) {
$this->load->helper('url');
redirect('/auth/login');
}
if ($this->auth->admin() === false) {
$message ['msg'] = "You are not an admin!";
$this->load->view('homeview', $message);
}
else
{
$this->load->view('add_view');
}
}
Auth Controller
public function authenticate()
{
$username = $this->input->post('uname');
$password = $this->input->post('pword');
$user = $this->authlib->login($username,$password);
**>> $this->admin($username,$password); << passes the posted in values**
if ($user !== false) {
$this->load->view('homeview',array('name' => $user['name']));
}
else {
$data['errmsg'] = 'Unable to login - please try again';
$this->load->view('login_view',$data);
}
}
public function admin($username,$password){
//$this->load-model('usermodel');
$admin = $this->authlib->adminlib($username,$password);
if ($admin == false){
return false;
//if ($res->num_rows() != 1){
//return false;
}
}
library authlib
public function adminlib($user,$pwd)
{
return $this->ci->usermodel->chkadmn($user,$pwd);
}
the model
function chkadmn($username,$password)
{
$this->db-where(array('username' => $username,'password' => sha1($password)));
$res = $this->db->get('users',array('type'));
if ($res->num_rows() != 1) {
return false;
}
}
Made some changes and now I get "Call to undefined function where() in C:\xampp\htdocs\ecwm604\application\models\usermodel.php on line 54"
personally i will replace all your if statments and i would test it as shown:
public function index()
{
$this->load->library('authlib');
$loggedin = $this->authlib->is_loggedin();
///$admin = $this->auth->admin();
if (!$loggedin) {
$this->load->helper('url');
redirect('/auth/login');
}
if (!$this->auth->admin()) {
$message ['msg'] = "You are not an admin!";
$this->load->view('homeview', $message);
}
else
{
$this->load->view('add_view');
}
}
public function admin(){
$this->load-model('usermodel');
$admin = $this->usermodel->chkadmn($username,$password);
if (!$admin){
return false;
//if ($res->num_rows() !== 1){
//return false;
}
}
function chkadmn($username,$password)
{
$this->db-where(array('username' => $username,'password' => sha1($password)));
$res = $this->db->get('users',array('type'));
if ($res->num_rows() !== 1) {
return false;
}
}
Related
I Have made a function add_items. and I Want if the slug already exists in the database then the form_validation runs and shows the error message. and that's work fine if the slug exists. But the main problem is that if I want to insert the new Data in the database which obviously has a different slug then the data is not inserted.
public function add_items()
{
if($this->input->post()){
if($this->input->is_ajax_request()){
$title = $this->input->post('title');
$url_title = url_title($title);
$this->form_validation->set_rules($url_title,'callback_slug_exists');
if($this->form_validation->run() == FALSE)
{
echo "FAIL::Slug Already Exist::error";
return;
}
$item_price = $this->input->post('item_price');
$item_description = $this->input->post('item_description');
$insertData = array('item_title' =>$title,'item_url'=>$url_title,'item_price' =>$item_price,'item_description'=>$item_description,
'big_pic' =>$image_path."/".$image);
$result = $this->common_model->insert_record('store_items',$insertData);
if($result){
echo "OK::Record Inserted Successfully::success";
return;
}
else {
echo "FAIL::Record Insertion Failled::success";
return;
}
}
}
$this->show('admin/add_items.php');
}
Here are The function slug_exists()
function slug_exists($slug)
{
$this->common_model->slug_exists($slug);
}
This is in Model
function slug_exists($slug)
{
$this->db->where('item_url',$slug);
$query = $this->db->get('store_items');
if ($query->num_rows() > 0){
return true;
}
else{
return false;
}
}
This is the insert_record()
function insert_record($tbl, $data)
{
$this->db->insert($tbl, $data);
return $this->db->insert_id();
}
And this is DB Structure
try this:you can post data direct in an array. no need define it.
$insertArray=array(
item_title' =>$this->input->post('title'),
'item_url'=>$this->input->post('url_title'),
'item_price' =>$this->input->post('item_price'),
'item_description'=>$this->input->post('item_description'),
'big_pic' =>$image_path."/".$image);
$this->db->insert('store_items', $insertArray);
Try like this
function slug_exists($slug)
{
$this->db->where('item_url',$slug);
$query = $this->db->get('store_items');
if ($query->num_rows() > 0){
return false;
}
else{
return true;
}
}
If slug already exists then you need to fail the validation to get the error so return false on existing
Also, return the answer/result to a callback function
function slug_exists($slug)
{
return $this->common_model->slug_exists($slug);
}
Update
Controller
if($this->form_validation->run() == FALSE){
echo "FAIL::Slug Already Exist::error";
return;
}else{
$item_price = $this->input->post('item_price');
$item_description = $this->input->post('item_description');
$insertData = array('item_title' =>$title,'item_url'=>$url_title,'item_price' =>$item_price,'item_description'=>$item_description,
'big_pic' =>$image_path."/".$image);
$result = $this->common_model->insert_record('store_items',$insertData);
if($result){
echo "OK::Record Inserted Successfully::success";
return;
}
else {
echo "FAIL::Record Insertion Failled::success";
return;
}
}
I got a codeigniter custom_result_object with this:
$user = $this->CI->db->get_where('users', array('email' => $email), 1)->custom_row_object(0,'entities\User');
and everything looks fine. I can update values with my setters.
Before I'm going to save i check my values with:
die(print_r($user));
and the values are correct.
I put my object in my update method.
$this->CI->db->update('users', $user, "id = ".$user->getId());
But the db is not updating. Am I missing something?
Thx!
EDIT:
So by using CI native db-method i can use:
public function save($user)
{
if($user->getId() == NULL){
$this->CI->db->insert('users', $user);
}else{
$this->CI->db->update('users', $user, "id = ".$user->getId());
}
}
Edit 2:
After some more checking I can see that it's not setting variables that are protected. CI is able to get the object through getters and setters but not able to save back to DB?
public function saveData($tbl,$data,$update = false,$previewStr = false){
$set_str = "NO_QUOTES()";
if(isset($data[$set_str])){
foreach($data[$set_str] as $set_key => $set_value){
$this->db->set($set_key, $set_value, FALSE);
}
unset($data[$set_str]);
}
if(isset($update[$set_str])){
foreach($update[$set_str] as $whr_key => $whr_value){
$this->db->where($whr_key." ".$whr_value,NULL,false);
}
unset($update[$set_str]);
if(is_array($update) and count($update) <= 0){
$update = true;
}
}
if($update == false){
$this->db->insert($tbl, $data);
if($previewStr){
return $this->db->last_query();
}else{
return $this->db->insert_id();
}
}else{
$result = NULL;
if(!is_array($update)){
if(is_array($data) and count($data) > 0){
foreach($data as $field => $value){
$this->db->set($field, $value);
}
}
$result = $this->db->update($tbl);
}else{
$result = $this->db->update($tbl, $data,$update);
}
if($previewStr){
return $this->db->last_query();
}else{
return $result;
}
}
}
public function delData($tbl = false,$where = array()){
if($tbl !== false){
return $this->db->delete($tbl, $where);
}else{
return false;
}
}
public function simpleQuery($query,$return_array = false,$return_single = false)
{
$ac = $this->db->query($query);
if($return_array === false){
return $ac;
}else{
if($return_single === false){
return $ac->result_array();
}else{
return $ac->row_array();
}
}
}
Use above code in your model and you i am giving you how to update it use below code in your controller you can insert update and delete by above code
$result=$this->Products_model->saveData("customer",array("customer_name"=>$name),array("cust_id"));
In the below codeigniter code I have placed the controller and model. My aim is to store the session college name in the db. I tried but it is not entering the session college name into db.college_name is in blank.
Controller
function create() {
$j=1;
$createcustomer = $this->input->post('createcustomer');
if( $this->input->post('createcustomer') != false ) {
foreach($createcustomer as $row_id) {
//this is validation command to update on the screen
$this->form_validation->set_rules("exam_name_" . $row_id, "'Exam name'","required");
$this->form_validation->set_rules("month_". $row_id,"`Month`","required");
$this->form_validation->set_rules("year_". $row_id,"`Year`","required","required|");
}
}
if ($this->form_validation->run() == FALSE) {
$data["message"]="";
$this->load->view("exam_view",$data);
} else {
while($j<=$this->uri->segment(3)) {
$data = array(
'exam_name' => $this->input->post('exam_name_'.$j),
'month' => $this->input->post('month_'.$j),
'year' => $this->input->post('year_'.$j)
);
$exam_name=$this->input->post('exam_name_'.$j);
$data1 = $this->session->userdata("college_name");
if ($exam_name != "") {
$this->exam_model->add_record($data,$data1);
// $this->load->view("success_msg",$data);
}
$j++;
} //end of while condition
} //end of if condition
redirect('exam_site', 'refresh');
//$this->index();
}
Model:
function add_record($data,$data1) {
$this->db->insert('exam_table', $data,$data1);
//$this->db->insert('exam_table', $data1);
if ($this->db->_error_number() == 1062) {
$this->session->set_flashdata('duplicate', 'duplicate');
}
if ($this->db->_error_number() == "") {
$this->session->set_flashdata('create', 'create');
}
return;
}
change this:
$this->db->insert('exam_table', $data,$data1);
to this:
$this->db->insert('exam_table', $data);
$this->db->insert('exam_table', $data1);
I'm wondering if there's a way to redirect to a specific page (like adminpanel_view) in Tank_auth.
I looked at the Auth.php controller but could not figure out how to redirect, if it's even possible..
I tried this:
(Auth.php)
public function login() //login functie
{
$this->breadcrumbs->page = array('link'=> base_url().'auth/login' ,'title' => 'Login');
$data['breadcrumbs'] = $this->breadcrumbs->get();
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('members/cpanel');
} elseif ($this->tank_auth->is_logged_in(FALSE)) { // logged in, not activated
redirect('/auth/send_again/');
} else {
$data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND
$this->config->item('use_username', 'tank_auth'));
$data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');
$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
$this->form_validation->set_rules('remember', 'Remember me', 'integer');
// Get login for counting attempts to login
if ($this->config->item('login_count_attempts', 'tank_auth') AND
($login = $this->input->post('login'))) {
$login = $this->security->xss_clean($login);
} else {
$login = '';
}
$data['use_recaptcha'] = $this->config->item('use_recaptcha', 'tank_auth');
if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
if ($data['use_recaptcha'])
$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
else
$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
}
$data['errors'] = array();
if ($this->form_validation->run()) { // validation ok
if ($this->tank_auth->login(
$this->form_validation->set_value('login'),
$this->form_validation->set_value('password'),
$this->form_validation->set_value('remember'),
$data['login_by_username'],
$data['login_by_email'])) { // success
redirect('');
} else {
$errors = $this->tank_auth->get_error_message();
if (isset($errors['banned'])) { // banned user
$this->_show_message($this->lang->line('auth_message_banned').' '.$errors['banned']);
} elseif (isset($errors['not_activated'])) { // not activated user
redirect('/auth/send_again/');
} else { // fail
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
}
}
$data['show_captcha'] = FALSE;
if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
$data['show_captcha'] = TRUE;
if ($data['use_recaptcha']) {
$data['recaptcha_html'] = $this->_create_recaptcha();
} else {
$data['captcha_html'] = $this->_create_captcha();
}
}
$this->load->view('views/header');
$this->load->view('auth/login_form', $data);
$this->load->view('views/footer');
}
}
make sure you have loaded url_helper before using function base_url, site_url or redirect. and your code could not run, because you missed a brace. it should be
public function login() //login functie
{
$this->load->helper('url');
$this->breadcrumbs->page = array('link'=> site_url('auth/login') ,'title' => 'Login');
$data['breadcrumbs'] = $this->breadcrumbs->get();
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('members/cpanel');
}
}
I am creating an application and handling common things in MY_Controller. I am using Message library to display common messages.
Here is MY_Controller.php:
<?php
class MY_Controller extends CI_Controller {
public $data = array();
public $view = TRUE;
public $theme = FALSE;
public $layout = 'default';
protected $redirect;
protected $models = array();
protected $controller_model;
protected $controller_class;
protected $controller_library;
protected $controller_name;
protected $partials = array(
'meta' => 'partials/meta',
'header' => 'partials/header',
'navigation' => 'partials/navigation',
'content' => 'partials/content',
'footer' => 'partials/footer'
);
public function __construct()
{
parent::__construct();
$this->output->enable_profiler(true);
$this->load->helper('inflector');
$this->load->helper('url');
$this->controller_class = $this->router->class;
if(count($this->models)>0)
{
foreach ($this->models as $model)
{
if (file_exists(APPPATH . 'models/' . $model . '.php'))
{
$this->controller_model = $model;
$this->load->model($model);
}
}
}else{
if (file_exists(APPPATH . 'models/' . $this->controller_model . '.php'))
{
$this->load->model($this->controller_model);
}
}
$this->controller_name = $this->router->fetch_class();
$this->action_name = $this->router->fetch_method();
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$this->run_filter('before', $parameters);
$return = call_user_func_array(array($this, $method),$parameters);
$this->run_filter('after', $parameters);
}else{
show_404();
}
if($this->theme === TRUE OR $this->theme === '')
{
$this->theme = 'default';
$this->template->set_theme($this->theme);
}else if(strlen($this->theme) > 0){
$this->template->set_theme($this->theme);
}else{
}
if($this->layout === TRUE OR $this->layout === '')
{
$this->layout = 'default';
$this->template->set_layout($this->layout);
}else if(strlen($this->layout) > 0){
$this->template->set_layout($this->layout);
}else{
}
if(isset($this->partials))
{
foreach($this->partials as $key => $value)
{
$this->template->set_partial($key,$value);
}
}
if(isset($this->data) AND count($this->data)>0)
{
foreach($this->data as $key => $value)
{
if(!is_object($value))
{
$this->template->set($key,$value);
}
}
}
if($this->view === TRUE OR $this->view === '')
{
if($this->parse == TRUE)
{
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$this->_call_content($this->router->method);
$this->template->build($this->router->method,array());
}
}else if(strlen($this->view) > 0){
if($this->parse == TRUE){
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$view = $this->view;
$this->_call_content($view);
$this->template->build($view,array());
}
}else{
$checkpoint = $this->session->flashdata('exit');
if($checkpoint){
exit();
}else{
$this->session->set_flashdata('exit',TRUE);
}
$this->redirect();
}
}
public function _call_content($view)
{
$value = $this->load->view($view,$this->data,TRUE);
$this->template->set('content',$value);
}
/* Common Controller Functions */
public function index()
{
$data[$this->controller_model] = $this->{$this->controller_model}->get_all();
$this->data = $data;
$this->view = TRUE;
if($this->input->is_ajax_request() || $this->session->flashdata('ajax')){
$this->layout = FALSE;
}else{
$this->layout = TRUE;
}
}
public function form()
{
if($this->input->is_ajax_request() OR !$this->input->is_ajax_request())
{
$this->load->helper('inflector');
$id = $this->uri->segment(4,0);
if($data = $this->input->post()){
$result = $this->{$this->controller_model}->validate($data);
if($result){
if($id > 0){
}else{
$this->{$this->controller_model}->insert($data);
}
$this->message->set('message','The page has been added successfully.');
$this->view = FALSE;
$this->layout = FALSE;
$this->redirect = "index";
}else{
$this->message->set('message','The Red fields are required');
}
}
$row = $this->{$this->controller_model}->where($id)->get();
$this->data[$module_name]= $row;
}
}
public function delete()
{
$id = $this->uri->segment(3,0);
if($id != 0){
$this->{$this->controller_model}->delete($id);
}
$this->view = FALSE;
$this->layout = FALSE;
}
public function redirect()
{
redirect($this->redirect);
}
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
public function query()
{
echo $this->db->last_query();
}
public function go($data = '')
{
if(isset($data)){
echo '<pre>';
print_r($data);
}else{
echo '<pre>';
print_r($this->data);
}
}
}
/**/
As you can see i am using Phil Sturgeon's template library and i am handling the layout with Jamierumbelow's techniques.
When i set a message on form insertion failure its fine. I can display it in the _remap like this
echo $this->message->display();
In the controller its working finebut when i call it in the partial navigation it does not display the message. What can possibly be the problem. I have tried on the different places in the My_Controller. Its working fine but not in the partial or even i have tried it in the failed form i am loading again.
This is the message library i am using
https://github.com/jeroenvdgulik/codeigniter-message
Here i s my navigation partial
<nav>
<div id = "navigation">
<ul id="menubar">
<li>Home</li>
<li>Downloads</li>
<li>About Us</li>
</ul>
</div>
<div id="breadcrumb">
<div class="breadcrumbs">
<!-- Here i will pull breadcrumbs dynamically-->
</div>
<!--<h3>Dashboard</h3>-->
</div>
<br clear = "all"/>
<div id="message">
<?php
$data['message'] = $message ;
$this->load->view('messages/success',$data);?>
</div>
</nav>
The message library is using session might be flashdata so i think its loosing session data somehow. Although i am using sessions correctly autoloading it.
I have found the issue. It was very simple. I was using the base url in config file as empty
$config['base_url'] = '';
I have to change it like this
$config['base_url'] = 'http://localhost/myproject/';