Real Dilemma when using Sessions, Cookies in Yii - session

I have set sessions for my properties/methods in WebUser like following
public function getRole(){
$user = $this->loadUser(Yii::app()->user->id);
$this->setState('roleId', $user->roles_id);
return $user->roles_id;
}
In the config, I have set autostart sessions to 'true', cookieMode to 'only'. I understand that when i 'setState', the cookie with the same name is also created along with the session variable. Currently I am calling these variables using Yii::app()->user->roleId;
My question is this:
a) To utilize from the cookies and/or the session variables already set, should i call them using Yii::app()->request->cookies['roleId']; or Yii::app()->session['roleId']?
b) Will calling Yii::app()->user->roleId get me the value if it is already set as Cookie or Session instead of running the whole method again?
I appreciate your support!

I would only use sessions for that. Cookies can be easily tampered with and a user could probably assign himself another role id. Session is somewhat safer.
Use your WebUsers getRole() for that, which caches it in the session like you have above. This is fine. Just put a check at the top, if there is a session var roleId instantly return it. If not, load the user and get it there like you already have.

Related

Is it ok to use $_SESSION['variables'] in Drupal 8?

I need a way to store temporary data for anonymous users.
Apparently this is not possible with:
\Drupal::service('user.private_tempstore')
Unless you write a custom constructor for the session management and stuff, which seems a little far-fetched to me?
I tried using
\Drupal::service('user.shared_tempstore')
But that saves the temp data for all anonymous users. So it's not linked to a single user.
Using raw $_SESSION['data'] works fine, but I'm not sure if I'm supposed to be doing this in Drupal and how safe/unsafe it is to do this?
Sessions (Drupal 8) are used via the simple Session implementation of SessionInterface interface. See Complete Tutorial of Sessions (Drupal 8).
Example:
use Symfony\Component\HttpFoundation\Session\Session;
$session = new Session();
$session->start();
// set and get session attributes
$session->set('name', 'Yash');
$session->get('name');
// set flash messages
$session->getFlashBag()->add('notice', 'Profile updated');
// retrieve messages
foreach ($session->getFlashBag()->get('notice', array()) as $message) {
echo '<div class="flash-notice">'.$message.'</div>';
}
I am not answering your specific question (regarding $_SESSION) because I have successfully used:
$session = \Drupal::service('user.private_tempstore')->get('your_module');
$session->set('whatever', $whatever);
from within procedural code (i.e. hooks, themes) without problems.
Pay attention that this private tempstore has to be assigned to a module (for the lack of a better way of saying this) which is the purpose of this line
$session = \Drupal::service('user.private_tempstore')->get('your_module')
After you get the private tempostore you can now set and get the session values:
$session->get('whatever');
$session->set('whatever', $whatever);
EDIT
Sorry, you explained correctly. I didn't get the critical part 100% ;)
You can always access the Session object from the request.
$session = \Drupal::request()->getSession();
$session->set('whatever', 'hello');
$value = $session->get('whatever', 'default');
I've been using plain PHP $_SESSION variables for a while now.
Did some research on them and they should be perfectly safe to use.
They're working correctly everywhere I use them and they have been working correctly for a while.
Don't think there's any issue using them in Drupal 8.

how to logout from a php session - session_destroy doesn't seem to be enough

I'm trying to learn PHP and using sessions. I seen examples about using session_destroy on logout, but I see this in the php documentation:
In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.
so what does one need to do upon logout ?
There's, like, an example answering your question just below the paragraph you just quoted:
http://php.net/manual/en/function.session-destroy.php
Example #1 Destroying a session with $_SESSION
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
In my opinion only this is nesessary
session_start();
unset($_SESSION["nome"]); // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**
I've never actually deleted the session ID from the session. I usually just unset the necessary variables from the session (so if, for instance, you set a logged in user as $_SESSION['user'] = $userModel; then I just unset($_SESSION['user']);). To remove the cookie from the user's browser (like the documentation says) do this:
setcookie(session_id(), "", time() - 3600);
Read Example #1 from the session_destroy() documentation for more info.
At the first: use the unset() function. So if you have a $_SESSION['user_id'], and you wanne destroy it: unset($_SESSION['user_id'])
You can also use the unset() for cookies or other vars
Second: can we have some code?
if you are using session id. then you can do this
session_start();
unset($_SESSION['id']);
session_destroy();
for cookies you can set the cookie time to some past date.
Only use session_unset() for older deprecated code that does not use
$_SESSION.
session_start();
session_unset($_SESSION['email-user']);
session_destroy();`

kohana 3.2 gets wrong session issue

case:
When using kohana driven site from 2 different devices I randomly get both session data on each device. I'm using native sessions to store few objects, but they should be private on each device. What am I doing wrong?
for example:
public function load()
{
$session = Session::instance();
$this->dialog = $session->get('dialog');
}
public function save()
{
$session = Session::instance();
$session->set('dialog', $this->dialog);
}
it looks like some kind of caching problem. I tried to regenerate session id every time. I've got 1st id, then 2nd, then 3rd and when i clicked a link a got 1st id again.
Make sure caching is turned off in your bootstrap file. And the cookie variables are set correctly, especially the Cookie::$domain.
Also verify your session config file too. You can find more info here: http://kohanaframework.org/3.2/guide/kohana/sessions

Manage multiple calls of Membership.GetUser().ProviderUserKey;

I was thinking yesterday how to solve this issue, because everything what i give or check about user is depended of his ProviderUserKey (ID).
So i made one static function like
public static Guid GetUserID()
{
string UserID = string.Empty;
if(HttpContext.Current.Session["UserID"] != null)
{
UserID = HttpContext.Current.Session["UserID"].ToString();
}
if(!string.IsNullOrEmpty(UserID))
{
return new Guid(UserID);
}
UserID = Membership.GetUser().ProviderUserKey.ToString();
HttpContext.Current.Session["UserID"] = UserID;
return new Guid(UserID);
}
Main point of this class is to reduce database connections to check/get user ID.
My problem with this function is not that this is not working, my problem is what if logged user log out and log with another account?
Or Is it better to add session value on log in and clear session value on log out?
Where you can see any other problem with this kind of "Get User ID"?
If you log the user out then you should also be killing the session.
When you login as another user you would also have the session reinitialized.
Note you'll want to keep the session and forms auth timeouts (assuming you are using forms auth) in sync with each other:
How can I handle forms authentication timeout exceptions in ASP.NET?
This should help keep the session in line with the forms auth token. You'll in turn need to kill the session on logout and intialize it upon login.
Another alternative is to implememt your own membership provider that caches this key to prevent constant db hits.
have you tried using the ProfileProvider?
you can use and customize with special properties and that's is managed by session each user.
example to get values:
HttpContext.Profile.GetPropertyValue["CustomProperty"]
In this video you can lean to implement it, create, configure and use...
http://www.asp.net/web-forms/videos/how-do-i/how-do-i-create-a-custom-profile-provider

flashdata not being stored between redirects when using Tank Auth

I'm using the latest version of Codeigniter and tank_auth 1.0.9 on a site I'm building.
When using set_flashdata() and flashdata() respectivly, nothing is being returned on redirect but if I set sess_use_database to FALSE in the config it works.
I've searched around and couldn't find an answer -- Has anyone else run into this issue and fixed it?
I was having the same issue and figured out the problem. If you're storing sessions in the database, it will not work.
Tank Auth runs this code from the main library ( $this->tank_auth->logout() ):
$this->delete_autologin();
// See http://codeigniter.com/forums/viewreply/662369/ as the reason for the next line
$this->ci->session->set_userdata(array('user_id' => '', 'username' => '', 'status' => ''));
$this->ci->session->sess_destroy();
Then it runs this code from the auth controller ( $this->_show_message() ):
$this->session->set_flashdata('message', $message);
redirect('/auth/');
The problem is that since sess_destroy() was run prior to setting the flashdata, there is no database row to add the flashdata to, so the flashdata never gets set.
At this point there are a few solutions:
Option 1:
Add $this->ci->session->sess_create(); immediately after $this->ci->session->sess_destroy(); in function logout() in application/libraries/Tank_auth.php
This works because you are creating a new blank session where flashdata can be stored. A potential con for this is that you are performing more operations on the database (delete+insert).
Option 2:
Comment out/delete $this->ci->session->sess_destroy(); in function logout() in application/libraries/Tank_auth.php
This works because the session is not destroyed, allowing CI to perform only an update query to add flashdata. This is probably better than option 1 unless you absolutely need to destroy the session.
Option 3:
Set $config['sess_use_database'] to FALSE.
This works because a session is automatically created when it is requested again, as opposed to how it works when you store sessions in the database. Potentially less secure.
In the end, it is up to you to decide which option is best for your application.
if tank_auth does any internal redirects then you may lose the flash data on that redirect request.
Exactly.
CodeIgniter documentation specifies here:
http://codeigniter.com/user_guide/libraries/sessions.html
=============================
Destroying a Session
To clear the current session:
$this->session->sess_destroy();
Note: This function should be the last one called,
and **even flash variables will no longer be available**.
If you only want some items destroyed and not all, use unset_userdata().
=============================
I've digged into the system/libraries/Session.php file and saving flashdata triggers the sess_write() method which only UPDATES the database as you said.
To me a better fix is checking to make sure the session exist before setting the flashdata in show_message().
function _show_message($message)
{
// Patch for show_message() after logout(). Make sure the session exist before set_flashdata().
if(!$this->session->sess_read())
{
$this->session->sess_create();
}
$this->session->set_flashdata('message', $message);
redirect('/auth/');
}

Resources