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?
Related
Hi I'm new to php and code igniter. what I tried is to get login info from view and validated user and need to send a message to user whether login details are incorrect.
Controller Code :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('login_model');
$this->load->helper('form');
$this->load->helper('url');
}
public function index()
{
//$this->load->helper('url');
$this->load->view('login/login');
}
public function login_check()
{
//$this->load->view('hello');
//echo "directed";
$user_id = $this->input->post('usernm');
$userPassword = $this->input->post('passwordd');
//echo $user_id.' and'.$userPassword;
$var = $this->login_model->check_login($user_id);
$status = 0;
if(empty($var))
{
echo "Invalid user";
$status = 0;
}
else
{
//echo var_dump($var);
$username = $var->username;
//echo $username;
$status = 1;
}
$this->load->helper('url');
redirect('login/login');
//$this->load_>view('login\login');// at this point it does not redirect to login page and instead of that displaying error 404.page not found.
//echo $status;
}
}
Same url ,earlier loaded when it called from from index function but fi it is calling from login check()function does not directed to the view and displaying error 404 page not found.
Any assistance regarding this world be a great help.
Thanks a Lot!
You need to write redirect('welcome'); instead of redirect('login/login');. Because login/login is the view page and you are trying to redirect direct on view without using controller. So you have two option which I had written bellow.
redirect('welcome');
$this->load->view('login/login');
My suggestion is please choose 1st option because 2nd option already you have implemented in first one.
I hope this one will work on you.
public function login_check()
{
$user_id = $this->input->post('usernm');
$userPassword = $this->input->post('passwordd');
$var = $this->login_model->check_login($user_id, $userPassword); //pass username and password to your model to authenticate if input exists.
$data['error'] = '';
if(!empty($var)) //check if var is not empty
{
$this->session->set_userdata($var); //set user_data to var
redirect('Account/page'); //redirect it to your account or success page
}else{
$data['error'] = 'Invalid Username or Password.';
}
$this->load->view('login/login',$data); //pass the error notification to your page.
}
I am building a website wherein I have an admin and user page. I have a problem wherein I can access the admin page via URL even though I am logged in as a user. I have validation checks at the login page, however if I am already logged in as a user or as an admin, I can access all the pages. I want to restrict the pages to their roles only.
This is my controller
class login extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('url','html');
$this->load->model('login_model');
}
public function index(){
$this->load->view('login');
}
public function verify_login()
{
$data = $this->login_model->verify_login();
if ($data) {
$userdata = array('id' => $data[0]['user_id'] , 'name' => $data[0]['full_name'], 'type' => $data[0]['user_type'] );
$this->session->set_userdata('login_info',$userdata);
if($userdata['type'] == 0) {
header("Location: ".base_url()."home");
}
else {
header("Location: ".base_url()."reports_controller");
}
}
else{
header("Location: ".base_url()."login");
}
}
public function logout(){
$this->session->sess_destroy('login_info');
header("Location: ".base_url()."login");
}
}
First you have to check what your session value will return,then you can restrict url.Use this to check your session
$session = $this->session->userdata('login_info');
$type = $session['type'];
I have two controllers
1.Login
2.Dashboard
In Login controller I have two methods
1.logged_in()
2.logged_out()
This is my Login Controller
public function logged_in()
{
$user_email =$this->input->post('user_email');
$user_password =$this->input->post('user_password');
$result=$this->Login_model->login_data($user_email,$user_password);
if(!$result)
{
$this->session->set_flashdata('failure', 'Login failed');
redirect(BASE_URL.'admin/Login');
}
else
{
$data=array(
'user_email'=>$result[0]['user_email'],
'user_password'=>$result[0]['user_password'],
);
$this->session->set_userdata('session_data',$data);
$this->session->set_flashdata('success', 'Login sucessfully');
redirect(BASE_URL.'admin/Dashboard');
}
}
public function logged_out()
{
$this->session->unset_userdata('session_data');
$this->session->sess_destroy();
$this->session->set_flashdata('success', 'Logout sucessfully');
redirect(BASE_URL.'admin/Login');
}
And this is Dashboard controller :
class Dashboard extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
if($this->session->userdata('session_data')!='')
{
$this->load->view('admin/dashboard');
}
else
{
$this->session->set_flashdata('admin_flash', 'Try again');
redirect(BASE_URL."admin/Login");
}
}
}
I have a problem while after login it enters in my view which I have to load but the problem is that if I go back it goes to login page which i don't want.
so suggest me solution?
My idea is to make something like a boolean called logged by default false and set it true when the user log into the page and false if you log out. Then check if the user is login in the login page and if he's login redirect the user to the homepage
simply check whether user logged in or not in your login page. If user is already logged in, redirect him/her to dashboard.
In your code:
public function logged_in()
{
// check whether user is logged in or not,
// if yes redirect them to dashboard
if($this->session->userdata('session_data')!='')
{
redirect(BASE_URL."admin/dashboard");
}
$user_email =$this->input->post('user_email');
$user_password =$this->input->post('user_password');
$result=$this->Login_model->login_data($user_email,$user_password);
if(!$result)
{
$this->session->set_flashdata('failure', 'Login failed');
redirect(BASE_URL.'admin/Login');
}
else
{
$data=array(
'user_email'=>$result[0]['user_email'],
'user_password'=>$result[0]['user_password'],
);
$this->session->set_userdata('session_data',$data);
$this->session->set_flashdata('success', 'Login sucessfully');
redirect(BASE_URL.'admin/Dashboard');
}
}
I want to get the roles of the registered users and show the content to the registered users according to their roles.
I have two users right now.
admin
user(authenticated)
The thing i am trying to do is that when the admin logs in via "webapp/user/login" a sidebarwidget which i have already made should be shown upon login and when the user(authenticated) gets logged in, the user(authenticated) should only be able to see the index.php page.
I am using Yii users and rights. I have looked around and found this piece of code which is for getting the role of the logged in user but I dont know where to place this piece of code to get the output.
Below are two pieces of codes, please do tell me which one will be more useful.
if($user = Users::model()->findAll()) {
foreach($user as $id => $user) {
if(!$user->checkAccess('Authenticated')) {
unset($user[$id]);
}
}
$users = array_values($user); // to reset indices (optional)
}
and this is another piece of code which i have found.
$command = Yii::app()->db->createCommand("SELECT * FROM `authassignment` WHERE userid={$user->id}");
$results = $command->queryAll();
$roles = array();
foreach ($results as $result)
{
$roles[] = $result['itemname'];
}
$this->setState('roles', $roles);
From what I have done following tutorials, here is a proposal.
The authentication can take place in file protected/components/UserIdentity.php :
public function authenticate($native=false){
$record=User::model()->findByAttributes(array('username'=>$this->username));
//can provide function "same" if needed - found it here:
//http://codereview.stackexchange.com/questions/13512
if($record!==null&&$this->same($record->password,crypt($this->password,$record->password)){
$authRoleName=Role::model()->findByAttributes(array('id'=>$record->role_id))->name;
$this->setState('role_name', $authRoleName);
$this->errorCode = self::ERROR_NONE;
}else{
$this->errorCode=self::ERROR_UNKNOWN_IDENTITY;
}
return !$this->errorCode;
}
In this case the several roles (admin, mobile, user, etc) are stored in db (table roles) and each user model has a role_id.
I assume the SiteController does the login (file protected/controllers/SiteController.php):
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login()){
$this->redirect(Yii::app()->user->returnUrl);
}
}
// display the login form
$this->render('login',array('model'=>$model));
}
File protected/models/LoginForm.php:
class LoginForm extends CFormModel
public $username;
public $password;
public $rememberMe;
private $_identity;
public function authenticate($attribute,$params)
{
if(!$this->hasErrors())
{
$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','False username or password.');
}
}
public function login()
{
if($this->_identity===null)
{
$this->_identity=new UserIdentity($this->username,$this->password);
$this->_identity->authenticate();
}
if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
{
$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
Yii::app()->user->login($this->_identity, duration);
return true;
}
else
return false;
}
In view you could do a role based decision making, like the example below in file protected/views/site/index.php :
<?php
$userModel =User::model()->findByAttributes(array('id'=>Yii::app()->user->getId()));
if($userModel){
if(Yii::app()->user->getState('role_name') == 'admin'){
$this->renderPartial(
//...
);
}else{
//...
}
}
Moreover, if RBAC is on your mind, and you manage to have a proper protected/data/auth.php (there are ways for this, I use command "./protected/yiic rbac" after creating file protected/commands/RbacCommand.php - I can post this latter file if needed) then in any place in your code you simply:
if(Yii::app()->user->checkAccess('admin')){
//staff for admins
}
Also, in this case, you could set the rights of whole actions in controller's function accessRules() by issuing roles instead of usernames:
public function accessRules()
{
return array{
array('allow',
'actions'=>array('index', 'index2', 'view','create','update','getRecordDetails', 'getTotalCount'),
'roles'=>array('admin'),
),
);
}
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.