I have an application built in CakePHP that is doing file uploads. For each file upload, I know the user's id, so I grab it from $this->Auth->user()
Now, what I have found is that when I am on the page, I will upload files while logged in but sometimes when I print_r the $this->Auth->user() it returns nothing back, and then the next time I try a file upload it will come back, all without e logging in or out. It seems extremely inconsistent, in that sometimes it is in there but other times it doesn't see it.
What am I missing? Thanks!
Why don't set a var in your app_controller to $this->Auth->userModel so it's accessible by the rest of the application.
In my app_controller I call the below in before_filter to set $current_user.
/**
* Sets a value for current user $current_user.
* #return boolean
*/
function __setCurrentUser() {
$user = null;
if ($user = $this->Auth->user()) {
$this->set('current_user', $user[$this->Auth->userModel]);
return true;
} else {
return false;
}
}
Elsewhere in my app, I can access $current_user's id via $current_user['id'].
You can also always grab userinfo from the Session that is created by AuthComponent. If $this->Auth->user('id') is empty.. I'm wondering if there is actually a valid session! Are you sure you haven't been logged out in the meantime and the page isn't requiring a login for some reason?
Related
We have a admin panel built in codeigniter, where two types of user get logged in (admin and super admin). Admin permissions are control by super admin. Admin permissions are stored in session at time of login. We are using codeigniter redis library for storing session data.
Now, the challenge is to update admin user session data without effecting admin login when permissions are changed by super admin.
if you want to do this on runtime i think with redis it shouldnt be really a problem
Create a pre Controller Hook where you check on every request if users session has been changed
since you use redis - you really don't need to use a DB Query in order to check it - just simply create an object which holds all changed users whose session have been changed and save it to redis
the hook could look like
class AppRefreshSession
{
private $ci;
public function __construct()
{
$this->ci = get_instance();
}
public function initialize()
{
if (!$this->isSessionValid())
{
//refresh users Session
}
}
private function isSessionValid()
{
$obj = $this->ci->cache->redis->get("ModifiedSessions_Object");
if ($obj->hasSessionModified())
{
return false;
}
return true;
}
}
And your modified sessions object should get filled with user ids or something like that whenever a superadmin changes the permission.
Save this object to redis and that should pretty much do what you want.
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();
...
}
I am building my first Laravel 4 Application (PHP).
I find myself needing to call somthing like this often in most of my Models and Controllers...
$this->user = Auth::user();
So my question is, is calling this several times in the application, hitting the Database several times, or is it smart enough to cache it somewhere for the remainder of the request/page build?
Or do I need to do it differently myself? I glanced over the Auth class but didnt have time to inspect every file (16 files for Auth)
Here is the code for the method Auth::user().
// vendor/laravel/framework/src/Illuminate/Auth/Guard.php
/**
* Get the currently authenticated user.
*
* #return \Illuminate\Auth\UserInterface|null
*/
public function user()
{
if ($this->loggedOut) return;
// If we have already retrieved the user for the current request we can just
// return it back immediately. We do not want to pull the user data every
// request into the method becaue that would tremendously slow the app.
if ( ! is_null($this->user))
{
return $this->user;
}
$id = $this->session->get($this->getName());
// First we will try to load the user using the identifier in the session if
// one exists. Otherwise we will check for a "remember me" cookie in this
// request, and if one exists, attempt to retrieve the user using that.
$user = null;
if ( ! is_null($id))
{
$user = $this->provider->retrieveByID($id);
}
// If the user is null, but we decrypt a "recaller" cookie we can attempt to
// pull the user data on that cookie which serves as a remember cookie on
// the application. Once we have a user we can return it to the caller.
$recaller = $this->getRecaller();
if (is_null($user) and ! is_null($recaller))
{
$user = $this->provider->retrieveByID($recaller);
}
return $this->user = $user;
}
To me, it looks like it will get the user from the database only once per request. So, you can call it as many times as you want. It will only hit the DB once.
Auth::user() only hits the DB once, so it's not a problem invokes it many times. Btw, you can cache useful information of the user that you want to access frequently.
Am creating a web application with the codeigniter framework, am working with version 2.0.3.
My makes ajax requests to update the page from time to time, and fetch notifications.
I've visited the codeigniter forums and asking questions about codeigniter sessions and ajax and found this snippet of code which i used, and saved in libraries and class "My_session.php"
class MY_Session extends CI_Session {
/**
* Update an existing session
*
* #access public
* #return void
*/
function sess_update() {
// skip the session update if this is an AJAX call! This is a bug in CI; see:
// https://github.com/EllisLab/CodeIgniter/issues/154
// http://codeigniter.com/forums/viewthread/102456/P15
if ( !($this->CI->input->is_ajax_request()) ) {
parent::sess_update();
}
}
}
But ever since i added this code i am unable to stay logged for more than five minutes without being logged out, or sometimes not being able to login in at all.
Does anyone have a similar experience?
If you want to stay logged in longer you have set sess_expiration for more then five minutes in your application/config/config.php
what happens when you evaluate the is_ajax_request()? in that code snippet add:
echo 'AJAX: ' . $this->CI->input->is_ajax_request(); exit;
to see if the if statement is working correctly. it might be returning false and updating the session each time. just a quick place to start :)
I would like to check, whether user's account is activated while loggin in, but cake's Auth component takes care of the login in a way I don't know how to control. Cake basically uses blank login function and I have no idea how to check value of User.active.
Thanks in advance
The AuthComponent has a property for setting additional conditions just like this, called $userScope.
Just include this line in your beforeFilter() Auth setup block:
$this->Auth->userScope = array('User.active' => true);
Note: the above applies to Cake 1.x. For 2.x use:
$this->Auth->scope = array('User.active' =>true);
Then you can leave your login method blank and the AuthComponent will append this extra condition when authenticating the visitor.
You can see all the additional properties here:
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#configuring-authentication-handlers
If you don't include this extra scope, then inactive users will still be able to log in and you'd have to log them out in your login() method after checking.
On your Users controller, or wherever you want to place it (the action that the login form links to):
function login() {
if ($this->Session->read('Auth.User')) {
$active = $this->Auth->user('active');
if ($active) {
//(do stuff)
}
else {
//(do other stuff)
}
}
}
This assumes that there is an "active" column in your User table that contains either true or false (or 1 or 0). $this->Auth->user() allows you to access the current logged in user's data. More information in here: http://book.cakephp.org/view/1264/user