im working on a project at the moment that allows users to register and log into there own user area and add/edit/delete note snippets.
Im currently working on the edit class and im wondering how can i make it so that other users cant visit the same url and edit someones note? (all notes are stored in the same table in the database)
schema = id, title, description, snippet, user_id
for example if user1 wants to edit his note at http://domain.com/edit/1 (which is bound to his user_id in the database) how can i stop user2 from visiting that same url and editing his note?
here is the controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Mysnippets extends CI_Controller {
function __construct()
{
parent::__construct();
if (!$this->tank_auth->is_logged_in()) {
redirect('/login/');
}
$this->load->model('dashboard_model');
$this->data['user_id'] = $this->tank_auth->get_user_id();
$this->data['username']= $this->tank_auth->get_username();
}
public function index()
{
$this->data['private_snippets'] = $this->dashboard_model->private_snippets();
$this->load->view('dashboard/my_snippets', $this->data);
}
function edit_snippet($snippet_id) {
$snippet = $this->dashboard_model->get_snippet($snippet_id);
//validate form input
$this->form_validation->set_rules('title', 'Title', 'required');
if (isset($_POST) && !empty($_POST))
{
$data = array(
'title' => $this->input->post('title'),
);
if ($this->form_validation->run() === true)
{
$this->dashboard_model->update_snippet($snippet_id, $data);
$this->session->set_flashdata('message', "<p>Product updated successfully.</p>");
redirect(base_url().'mysnippets/edit_snippet/'.$snippet_id);
}
}
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$this->data['snippet'] = $snippet;
//display the edit product form
$this->data['title'] = array(
'name' => 'title',
'type' => 'text',
'value' => $this->form_validation->set_value('title', $snippet['title']),
);
$this->load->view('dashboard/edit_snippet', $this->data);
}
}
heres the model:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Dashboard_model extends CI_Model {
public function public_snippets()
{
$this->db->select('id, title, description, author, date_submitted');
$query = $this->db->get_where('snippets', array('state' => 'public'));
return $query->result_array();
}
public function private_snippets()
{
$this->db->select('id, title, description, date_submitted');
$query = $this->db->get_where('snippets', array('user_id' => $this->tank_auth->get_user_id()));
return $query->result_array();
}
public function add_snippet($data)
{
$this->db->insert('snippets', $data);
$id = $this->db->insert_id();
return (isset($id)) ? $id : FALSE;
}
public function get_snippet($snippet_id) {
$this->db->select('id, title');
$this->db->where('id', $snippet_id);
$query = $this->db->get('snippets');
return $query->row_array();
}
public function update_snippet($snippet_id, $data)
{
$this->db->where('id', $snippet_id);
$this->db->update('snippets', $data);
}
}
heres the view:
<?php echo $message;?>
<?php $snippet_id = $snippet['id']; ?>
<?php echo form_open("mysnippets/edit_snippet/$snippet_id");?>
<?php echo form_input($title); ?>
<?php echo form_submit('submit', 'Submit');?>
<?php echo form_close(); ?>
is there a way i can restrict it so if another user tried to go to that url i can redirect them or show a error message
Something like this might work.
public function edit_snippet(snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
// this depends on what you are using for sessions;
// recommend you use db sessions
if($snippet->user_id != $this->session->userdata('user_id');)
{
redirect('/mysnippets');
}
else
{
//allow editing
You could check whether the id you are editing is the same as the session id provided when you have logged in.
it could be something like :
if ($snippet_id != $this->session->userdata('login_id'))
{
//redirect to another page
}
I would just add a line to the following function in the model:
public function get_snippet($snippet_id) {
$this->db->select('id, title');
$this->db->where('id', $snippet_id);
//users can access only their own snippets
$this->db->where('user_id', $this->session->userdata('user_id'));
$query = $this->db->get('snippets');
return $query->row_array();
}
That prevents them from accessing the information, but I'd do something to prevent them from even being able to try in the first place, i.e. not giving them the choice.
Related
I made a user table that will link to his postings when he submits a post. (It parts works correctly)
So I have been trying to create a method in codeigniter 3. I have it set to where if the user is logged in and clicks his user name it will show all his submissions, by simply pulling from the table his user_id and then looping through his posts.
Well, I have two issues
when I enter in the url to call this function it wants a value for the uri. Example: localhost/CI/controller/account yet it will not load until I put something after account (account is the method name).
Like localhost/CI/controller/account/9
Also this function does not seem to work either for some reason, I do not know if it has something to do with it wanting another value.
I have researched this for the past hour with no luck.
Controller:
public function account(){
$data['title'] = 'Your submissions';
$data['posts'] = $this->post_model->user_posts();
$this->load->view('templates/header');
$this->load->view('users/profile', $data);
$this->load->view('templates/footer');
}
//view function the post by clicking on title
public function view ($slug=NULL){
$data['post'] = $this->post_model->get_posts($slug);
$post_id = $data['post']['id'];
$data['comments'] = $this->comment_model->get_comments($slug);
if(empty($data['post'])){
show_404();
}
$data['title'] = $data['post']['title'];
$this->load->view('templates/header');
$this->load->view('posts/view', $data);
$this->load->view('templates/footer');
}
Model:
public function user_posts (){
$usernum = $this->session->userdata('customer_id');
$this->db->order_by('created_time','DESC');
$query = $this->db->get_where('posts',array('customer_id ='=>'$usernum'));
return $query->result_array();
}
$query = $this->db->get_where('posts',array('slug'=>$slug));
return $query->row_array();
}
View:
<?php
echo $title;
foreach ($posts as $post): {
echo $post['title'];
}endforeach;
?>
Controller :
public function account($acno = "") {//changes
$data['title'] = 'Your submissions';
$data['posts'] = $this->Post_model->user_posts();//changes
echo'<pre>';print_r($data);die;//changes
$this->load->view('templates/header');
$this->load->view('users/profile', $data);
$this->load->view('templates/footer');
}
Model :
public function user_posts() {
$usernum = $this->session->userdata('customer_id');
$this->db->order_by('created_time', 'DESC');
$query = $this->db->get_where('posts', array('customer_id =' => $usernum));//changes
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return array();
}
}
Change model function like this
public function user_posts (){
$usernum = $this->session->userdata('customer_id');
$this->db->order_by('created_time','DESC');
$query = $this->db->get_where('posts', array('customer_id' => $usernum));
return $query->result_array();
}
The associative array does not need = in where() or get_where() to get the record
Do not need single quotes with $usernum
After trying somethings this is what corrected my issues
Public function user_posts (){
$this->db->order_by('created_time','DESC');
$query = $this->db->get_where('posts', array('customer_id' => $this->session->userdata('customer_id')));
return $query->result_array();
}
I believe by removing the $usernum = $this->session->userdata('customer_id'); and adding it to the query, now allows the user to call his own session id without the need to enter one into the function.
Thanks to those that gave me input
I dont know how your button click is set up but this is how you should do it.
Button click page
<?= site_url(); ?>controller_name/account
account function in controller
function account(){
//1. Check if user is Logged in
if (!$this->ion_auth->logged_in())
{
//If they are not logged in, redirect them to login page or do something
}
else{
//User is logged in so get submissions
//Get all submissions
$data['title'] = 'Your submissions';
$this->data['posts']= $this->post_model->user_posts();
$this->load->view('templates/header');
$this->load->view('users/profile', $data);
$this->load->view('templates/footer');
}}
User posts function in Model
function user_posts (){
$user = $this->ion_auth->user()->row();
$ref_id=$user->id; //Gets you user id
$this->db->where(['customer_id'=>$ref_id]);
$this->db->order_by('created_time','DESC');
$query=$this->db->get('posts');
if($query->result())
{
return $query->result();
}
else
{
return false;
}}
Also, consider using Ion Auth for your login in codeigniter as it allows you access session data easily without issues as the one you've been facing.
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;
}
view controller
<?php
class Site extends CI_Controller {
function homePage() {
$this->load->view('homePage');
}
function getValues($username) {
$this->load->model('customer_model');
$data['results']=$this->customer_model->getOne($username);
$this->load->view('view_db',$data);
}
}
I wanna display the logged in user details from database to a page. where the user logs in and it directs to home page and in that , there is link which directs to view the users details according to my design..
view Controller of login
<?php
class Login extends CI_Controller {
function index() {
//loads the main page to be displaye din the page
$this->load->view('login_form');
}
function validate_credentials() {
$this->load->model('customer_model');
$query = $this->customer_model->validate();
if ($query) {//if the user credidential is validated
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
//retrieving the session data
$this->session->set_userdata($data);
redirect('site/homePage');
} else {
$this->index();
}
}
the model view--- i have mentioned only getting a specific user
function getOne($username){
$query=$this->db->query('SELECT * FROM customer WHERE username = $username');
//$this->db->select('*');
//$query= $this->db->get('customer');
return $query->result();
}
and the view.. where now i just wanna retrieve the value and check later i can improve the interface ;)
<?php
//print_r($results);
foreach($results as $row) {
echo $row->id;
echo $row->last_name;
echo "<br/>";
}
?>
i know it should be done through a session .. but how to do it?
Ok so when this person who is now logged in clicks on the link that brings them to the getValues() method. You can just do a check to see if they are logged in, then if they are retrieve their information based on the sessions username key.
function getValues(){
if ($this->session->userdata('is_logged_in')) {
$username = $this->session->userdata('username');
//Get your db results
$this->load->model('customer_model');
$data['results']=$this->customer_model->getOne($username);
$this->load->view('view_db',$data);
} else{
//What you want to happen when they are not logged in.
}
Does that make sense?
First, sorry for my bad english, if you don't understand what I'm saying, you can ask for it and I will search for another suitable and precise words.
Now, I've been working with codeigniter in this last 2 weeks, so I got so many question for it, but I found 1 which is hanging on my mind.
I started with simple CRUD, then make it advanced, it's good so far, until I got stuck while updating data. When I click the "submit" button, I get only 404 page. And when I see the database, nothing change.
Here's the controller's code:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
Class Master_user extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('mod_master_user');
$this->load->library('datatables');
}
public function index(){
if ($this->session->userdata('type') == 'admin') {
$data['hasil'] = $this->mod_master_user->getall();
$datum['content'] = $this->load>view('master_user/view',$data,true);
$this->load->view('main',$datum);
} else if ($this->session->userdata('type') == 'user'){
$a= $this->load->model('m_absensi');
$aa["content"] = $this->load->view('absensi/form',$a,true);
$this->load->view("absensi/mainUser",$aa);
}
}
public function tambah_data(){
if($this->input->post('nama')){
$this->mod_master_user->tambah();
redirect('master_user');
}else{
$this->load->view('master_user/add');
}
}
public function update_data($id_user)**//i use this method for updating data**{
if($this->input->post('submit')){
$this->mod_master_user->update($id_user);
redirect('master_user/index');
}
$data['hasil']=$this->mod_master_user->getById($id_user);
$this->load->view('master_user/edit',$data);
}
public function delete_data($id_user){
$this->mod_master_user->delete($id_user);
redirect('master_user');
}
public function error()
{
$this->output->set_status_header('404');
$data['content'] = '404';
$this->load->view('master_user/404',$data);
}
public function print_report()
{
$this->load->view('master_user/print');
}
public function jam_masuk()
{
$this->load->view('master_user/jam_masuk');
}
}
Here comes the model's code:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
Class Mod_master_user extends CI_Model{
var $tabel_name = 'master_user';
function __construct() {
parent::__construct();
}
public function getall(){
$ambil_data = $this->db->get('master_user');//mengambil tabel master_user
if ($ambil_data->num_rows() > 0 ){ //jika data lebih dari 0
foreach ($ambil_data->result() as $data){
$hasil[] = $data;
}
return $hasil;
}
}
public function tambah(){
$id_user = $this->input->post('id_user');
$nama = $this->input->post('nama');
$password = $this->input->post('password');
$tanggal_lahir = $this->input->post('tanggal_lahir');
$tempat_lahir = $this->input->post('tempat_lahir');
$role = $this->input->post('role');
$data = array (
'id_user'=> $id_user,
'nama'=>$nama,
'password'=>md5($password),
'tanggal_lahir'=>date('Y-m-d',strtotime($tanggal_lahir)),
'tempat_lahir'=>$tempat_lahir,
'role'=>$role
);
$this->db->where('id_user',$id_user);
$this->db->insert('master_user', $data);
}
public function update($id_user)**//i use this method to updating data**{
$id_user=$this->input->post('id_user');
$nama=$this->input->post('nama');
$password=$this->input->post('password');
$tanggal_lahir=$this->input->post('tanggal_lahir');
$tempat_lahir=$this->input->post('tempat_lahir');
$role=$this->input->post('role');
$data = array (
'id_user' => $id_user,
'nama' => $nama,
'password'=> $password,
'tanggal_lahir'=> $tanggal_lahir,
'tempat_lahir'=> $tempat_lahir,
'role'=>$role
);
$this->db->where('id_user',$id_user);
$this->db->update('master_user',$data); //update data
}
public function getById($id_user){ //mengambil data dari db berdasarkan id (primary key)
return $this->db->get_where('master_user',array('id_user'=>$id_user))->row();
}
public function delete($id_user){
$this->db->where('id_user',$id_user);
$this->db->delete('master_user'); //query delete data
}
public function cek_user_login($username, $password) {
$this->db->select('*');
$this->db->where('NAMA', $username);
$this->db->where('PASSWORD', md5($password));
$query = $this->db->get($this->tabel_name, 1);
if ($query->num_rows() == 1) {
$this->db->limit(1);
return $query->row_array();
}
}
public function validasi()
{
$nama = $this->input->post('nama');
$password = $this->input->post('password');
$check = $this->mod_master_user->check($nama, md5($password));
if($check->num_rows() > 0)
{
//login berhasil, buat session
//$this->session->set_userdata('username',$username);
redirect('master_user');
}
else
{
//login gagal
//$this->session->set_flashdata('message','Username atau password salah');
redirect('users');
}
}
}
So far, I get no answer on other forums, so I asked for the answer here :)
Any answer/help will be appreciated. Thank you :)
It's been some time since I used CodeIgniter.
Are you loading the input class? so you can actually receive $_GET and $_POST data? I think it does this by default actually.
This might be a bit too simple, but are you calling the right URI and are you sure its reaching your view??
Might help to see your view, are you using the form helper for this? https://ellislab.com/codeIgniter/user-guide/helpers/form_helper.html
If you get 404, then the problem is in your form action tag. It means it doesn't post to the right url.
This is most likely (if not surely) due to a bad route.
In config/routes.php, you need a route like: $route['master_user/update/(:any)'] = 'master_user/update_data/$1;
And in your view you would need a form with the action pointing to that route, such as:
<form action="master_user/update_data/1">
<!-- your fields and submit button -->
</form>
Where the number 1 (in the action url) is the id of the register being updated.
I am currently trying to add data to the database using codeigniter. I have already set up a registration page using the active method and attempted to use the same method for the add news form but was unsuccessful.
When I click submit it is saying page cannot be found and the url shows the controller function name. This is the same when i purposely leave any fields blank. I have checked my database and no records have been added and no php log errors.
Here is my snippets of code:
View:
<?php echo form_open('add/add_article'); ?>
<?php echo form_input('title', set_value('title', 'Title')); ?><br />
<?php echo form_textarea('content', set_value('content', 'Content')); ?><br />
<?php echo form_input('author', set_value('author', 'Author')); ?>
<?php echo form_submit('submit', 'Add Article'); ?>
<?php echo validation_errors('<p class="error">' );?>
<?php echo form_close(); ?>
Controller:
class Add extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('admin/add');
}
public function add_article() {
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('content', 'Content', 'trim|required');
$this->form_validation->set_rules('author', 'Author', 'trim|required');
if($this->form_validation->run() == FALSE) {
$this->index();
}else{
$this->load->model('news_model');
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
}
}
}
Model:
public function __construct() {
parent::__construct();
}
function addArticle() {
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username'));
$insert = $this->db->insert('news', $data);
return $insert;
}
}
If it's the server that's throwing the page not found it's almost certainly a URL issue as opposed to a CI/PHP issue.
Is your base url defined properly in the config file? Is your .htaccess configured properly (an old configuration could be routing /add requests away from CI)?
Try adding the following action to the Add controller, and navigating to it directly at http://[base]/add/thetest
public function thetest() {
echo 'Controller accessed';
die;
}
If it still says page not found it's not your code, it's your config (either server config or CI).
Instead of insert use update in your model like:
$insert = $this->db->update('news', $data);
return $insert;
And I think that this part of your code in controller is wrong too (wrong if statement and no data send to model):
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
try this:
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username')
);
$query = $this->news_model->addArticle($data);
if($query)
{
// query ok
$this->load->view('news');
}
else {
// no query
$this->load->view('news');
}