how to restrict logged in user to see other URL in codeigniter - php

How to restrict user not to see others people data.
for example one user data is in this url
http://example.com/abc/xyz/1
i want to stop accessing
http://example.com/abc/xyz/2
I can stop it using normal php stuff but i want to know any thing in codeigniter that does that.

No, you need to handle this using your own code in the controller.
class Abc Extends CI_Controller {
public function xyz($var) {
if($var != some_condition_based_on_user)
show_some_error();
}
}

You can check the id of the user for example. When you log in you save the id of the user into session something like this in the model on login function:
$this->session->set_userdata(array('user_id' => $user['id']);
after into your function you can check if the get value is the same of the session like:
public function xyz($id) {
if($id != $this->session->userdata('user_id')){
//code error
}
}

Related

Is my CakePHP Session login secure?

I don't know how to use AuthComponent then this is the way I do user authentication with multiple roles is as follows:
There is 3 roles: Administrators, Resales and Clients.. one controller for each one, for individual views, and this is my beforeFilter for each Role/Controller:
AdministratorsController:
function beforeFilter(){
if (!$this->isAuth('Administrator'))
$this->redirect('/');
}
AppController:
function isAuth($strRole = NULL){
$data = $this->Session->read('User');
if (!$this->Session->check('User') || (!is_null($strRole) && $data['Role']['nome'] != $strRole))
return false;
return true;
}
In UsersController I do only authentication checking if $this->Session->read('User') exists, if the user exists, he gets all info and put in Session like this: $this->Session->write('User', $user); assuming that $user is the find from Model with all user information.
the question is, will I have problems? is that "right"? do not know if I was clear, if missing information, ask..
You're replicating logic the framework already implements for you.
See http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html#authorization-who-s-allowed-to-access-what
Taken from that page (you should still read it..):
public function isAuthorized($user) {
// Admin can access every action
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
// Default deny
return false;
}
The user data gets passed to it, no need to fetch the user data yourself.
And if you ever have to fetch the user data use $this->Auth->user():
// Some field
$this->Auth->user('someField');
// Whole data
$this->Auth->user();
If the session key ever changes for some reason all you direct calls to the Session->read('User') will be in trouble. A good and not so unlikely example here is when the application has to be extended with a 2nd auth adapter that is not using the session. Auth will know about the data, Session won't have it.

User authentication with Angular & PHP

I am quite inexperienced when it comes to the topic of server-side user authentication.
I want to use as few PHP code as possible to achieve the following:
A user can log in to my app. If he does so, i will store all of that users information, including the status of being authenticated to an Angular service.
As a user navigates through my app, i need to check whether or not he is logged in. If he ain't, i need to redirect him immediately.
The question
Would it be enough to set up two session variables when the user has been logged in successfully and then doing something like this on every route change, updating my service and handle the result client-side?
public function getLogStatus(){
return
$_SESSION["isLoggedIn"] == "true" &&
$_SESSION['useradr'] == $_SERVER['REMOTE_ADDR'] ?
true : false;
}
Yes it IS enough.
But I suggest this :
public function checkAuth(){
if(!$_SESSION["isLoggedIn"] || $_SESSION['useradr'] !=$_SERVER['REMOTE_ADDR'])
header('location:"thePage.php"');
}
and call it in the first line of every method that you dont want to non-authed visitors can gain .
public function method(){
$this->checkAuth();
...
}

How to get CodeIgniter to ignore the last segment entered into the URL-but still keep it there?

I'm using CodeIgniter to build a user profile section from scratch. What happens is, the user will put in the URL:
www.somesite.com/profile/view/<USERNAME>
(profile is the folder & view is the controller)
and I will use IF ELSE statements to check to see if $currentURL (see below) is in the DB and load the required page.
But what's happening right now is it's looking for a function(I think) inside view to execute. But there is none. Which results in a 404 error.
Is it possible for CodeIgniter to ignore the last segment of that URL but still keep it there so that I can use;
$currentURL = $this->uri->segment(3);
to grab the USERNAME?
Thanks for viewing my question,
Lewis.
If I understand you correctly:
declare your function as follows
public function view($var1, $username = "") {...}
where $var1 must be filled in but $username can be ommited and its default value is ""
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class View extends CI_Controller { //can not belive that View is not reserved word
public function __construct() {
parent::__construct();
}
public function index() {
//index() function can not have parameters
//redirect('view/show');
//if no username is set, do default thing like show list of users
//load view or something
}
public function show($username = "") {
//this function can have parameters
//load views from here
$this->load->view('abc_view');
}
}
Add to routes.php following
$route['profile/view/(:any)'] = "profile/view/show/$1";
this will allow you to have nice URL as you expect
site.com/profile/view/Peterson123
NOTE when using "routing" method do not redirect(profile/view/show) in index()
Another aproach that uses _remap() is explained here.

How to programmatically recreate php yii session?

From my application view I need to programmatically logout current user and login another one right after that.
I want to login the second user into his own different CHttpSession (with another sessionID and so on). I need it for a security reasons.
How to implement this in Yii framework ?
Code below
$oSession->destroy();
$oSession->open();
doesn't work as expected..
looks like you are trying to impersonate users:
Create a function in your UserIdentity that would alow you to login as another known user:
protected function logInUser($user)
{
if($user)
{
$this->_user = $user;
$this->_id=$this->_user->id;
$this->setState('name', $this->_user->name);
$this->errorCode=self::ERROR_NONE;
}
}
In your controller, call this function to get the UserIdentity object and then use the Yii's CWebUser login
$ui = null;
$user = User::model()->findByPk($userId);
if($user)
{
$ui = new UserIdentity($user->email, "");
$ui->logInUser($user);
}
Yii::app()->user->login($ui, 0);
Remember to protect this controller's action from non authorized users.
A possible tricky way (tested):
session_unset();
Yii::app()->user->id = $the_new_id;
When the above code is executed, nothing visible happens on the page so you may want to redirect the browser:
$this->redirect('somewhere');
Upon the next page load, the user with the $the_new_id will be logged in

Getting last login time in Yii Framework

I am a newbie to Yii framework. I had asked this question over Yii forum, but not got any good result, so I came here. Actually I want to show last logged in time when admin will login. It is available in Yii user module. So how to do that. Is it possible to get that time from user module to the index page.Any help and suggestions will be highly appreciable.
[Update]
I followed this link and I made Useridentity code like this as per instruction:
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$user=User::model()->findByAttributes(array('username'=>$this->username));
if($user===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($user->password!==md5($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$user->id;
$this->setState('lastLoginTime', $user->lastLoginTime);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
Now I have to call id and lastlogin in view file so that I can get the lastlogin time.So I have used this code in view file.
<?php echo Yii::app()->user->name;?>
<?php echo Yii::app()->user->lastLoginTime;?>
After all the changes I got the error like:
Property "CWebUser.lastLoginTime" is not defined.
You could try this:
Yii::app()->user->last_login = $usermodel->last_login;
$usermodel->last_login = time();
echo "welcome back - your last login was at:".Yii::app()->user->last_login;
you need just write that in your view when the user is logged
echo Yii::app()->user->lastLoginTime;
try it!
You can not access to variables assigned via setState() directly
If you are using setState() you have to use getState() to get it:
UserIdentity
$this->setState('lastLoginTime', $user->lastLoginTime);
view
Yii::app()->user->getState('lastLoginTime');
or you can add one more private property like $_id and use it the same way. (i recommend it!)
This might sound silly and be all in the spirit of "have you tried turning it on and off again?", but as per this comment, have you tried logging out and in again? I suspect the change hasn't affected your session yet which is why CWebUser.lastLoginTime cannot be accessed yet. See also the details of CWebUser.__get().

Categories