Clear cookies in yii2 after function call - php

I am facing some issues regarding clearing cookies in yii2. When i am calling a logout function on button click i am trying to perform following actions:
Set authtoken, and its expiration value to null
if Step got performed then clear session and cookies
but the problem is after setting the authtoken and its expiration value to null control is not going under if block (Where i am clearing session and cookies).
public function actionLogout()
{
$userId = \Yii::$app->user->identity->id;
$restobj = new RestController();
$this->token = NuLL;
$expire = Null;
$data = ['userId'=>$userId,'token'=>$this->token,'expire'=>$expire];
$data = json_encode($data);
$authtoken = $restobj->updateItem(\app\urls\urls::setauthtoken, $data);
if($authtoken)
{
$session = new Session();
$session->close();
$session->destroy();
$cookies = \Yii::$app->response->cookies;
unset($cookies['user_cookies']);
Yii::$app->user->logout();
return $this->goHome();
}
}
updateItem function is calling this authtoken function:
<?php
namespace app\actions\userloginactions;
use Yii;
use yii\rest\ActiveController;
use app\models\Authmaster;
use yii\base\Action;
class AuthtokenAction extends Action
{
//function used in rest api call for user token
public function run()
{
$data = Yii::$app->getRequest()->getBodyParams();
$userId = $data['userId'];
$token = $data['token'];
$expire = $data['expire'];
$result = Authmaster::setauthtoken($userId,$token,$expire);
return true;
}
}
setauthtoken function in model called from AuthtokenAction
public static function setauthtoken($userId,$token,$expire)
{
return Authmaster::updateAll(['token'=>$token,'expire'=>$expire],['user_id'=>$userId]);
}
when i click logout button it successfully sets the authtoken and expiration to null but it directly displays true as a result of AuthtokenAction function and control doesn't goes under if block.
that function call is creating some problem if i comment that and write cookies clearing block directly then cookies gets cleared without any problem.

Please check following code to clear all cookies. It is working for me, hope will work for you too.
Yii::$app->cache->flush()

Please try to use following line
$cookies = Yii::$app->response->cookies;
$cookies->remove('user_cookies');
Can you try this one?
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}

Hope this helps others...
$cookies = Yii::$app->response->cookies;
$cookies->remove('username');
unset($cookies['username']);
Found in the following referenced link: http://www.bsourcecode.com/yiiframework2/cookies-handling-in-yii-framework2-0/

Related

PHP Sessions and session_regenerate_id

I've been trying to solve this problem for many weeks now.
I've made a class to secure PHP sessions, and it works fine unless someone is trying to perform registration (its the problem #2) and if some of the functionality disabled (which is causing #2 to happen), the rest of the website work just fine.
So here are the problems:
session_regenerate_id - commented out
From here, everything works just fine, except for captcha creation mechanism (only on registration page), for login page it works just fine
session_regenerate_id(true) - uncommented
In here, registration works just fine, no problems, no captcha issues, but after few refreshes of the page, session just gone, so user need to log in for 6 more refreshes and $_SESSION again sets to null
I know where the problem might be, but i dont know how to solve it.
I have a private static function, which is called straight after session_start() is called
private static function GenerateSessionData()
{
$_SESSION['loggedin'] = '';
$_SESSION['username'] = '';
$_SESSION['remember_me'] = '';
$_SESSION['preferredlanguage'] = '';
$_SESSION['generated_captcha'] = '';
}
This is done to pre-define variables to be used by session (and i'm 90% sure that this is why session goes blank after).
The thing im not sure about, is WHY.
Here is the full session class:
<?php
Class Session
{
public static $DBConnection;
private static $SessionCreated = false;
public function __construct($Database)
{
session_set_save_handler(array($this, 'Open'), array($this, 'Close'), array($this, 'Read'), array($this, 'Write'), array($this, 'Destroy'), array($this, 'GarbageCollector'));
register_shutdown_function('session_write_close');
Session::$DBConnection = $Database::$Connection;
}
private static function GenerateSessionData()
{
$_SESSION['loggedin'] = '';
$_SESSION['username'] = '';
$_SESSION['remember_me'] = '';
$_SESSION['preferredlanguage'] = '';
$_SESSION['generated_captcha'] = '';
}
public static function UpdateSession($Data)
{
if(!isset($_SESSION['loggedin']))
Session::GenerateSessionData();
foreach($Data as $key=>$value)
$_SESSION[$key] = $value;
}
public static function GenerateCSRFToken()
{
$InitialString = "abcdefghijklmnopqrstuvwxyz1234567890";
$PartOne = substr(str_shuffle($InitialString),0,8);
$PartTwo = substr(str_shuffle($InitialString),0,4);
$PartThree = substr(str_shuffle($InitialString),0,4);
$PartFour = substr(str_shuffle($InitialString),0,4);
$PartFive = substr(str_shuffle($InitialString),0,12);
$FinalCode = $PartOne.'-'.$PartTwo.'-'.$PartThree.'-'.$PartFour.'-'.$PartFive;
$_SESSION['generated_csrf'] = $FinalCode;
return $FinalCode;
}
public static function ValidateCSRFToken($Token)
{
if(isset($Token) && $Token == $_SESSION['generated_csrf'])
{
unset($_SESSION['generated_csrf']);
return true;
}
else
return false;
}
public static function UnsetKeys($Keys)
{
foreach($Keys as $Key)
unset($_SESSION[$Key]);
}
public static function Start($SessionName, $Secure)
{
$HTTPOnly = true;
$Session_Hash = 'sha512';
if(in_array($Session_Hash, hash_algos()))
ini_set('session.hash_function', $Session_Hash);
ini_set('session.hash_bits_per_character', 6);
ini_set('session.use_only_cookies', 1);
$CookieParameters = session_get_cookie_params();
session_set_cookie_params($CookieParameters["lifetime"], $CookieParameters["path"], $CookieParameters["domain"], $Secure, $HTTPOnly);
session_name($SessionName);
session_start();
session_regenerate_id(true);
if(!Session::$SessionCreated)
if(!isset($_SESSION['loggedin']))
Session::GenerateSessionData();
Session::$SessionCreated = true;
}
static function Open()
{
if(is_null(Session::$DBConnection))
{
die("Unable to establish connection with database for Secure Session!");
return false;
}
else
return true;
}
static function Close()
{
Session::$DBConnection = null;
return true;
}
static function Read($SessionID)
{
$Statement = Session::$DBConnection->prepare("SELECT data FROM sessions WHERE id = :sessionid LIMIT 1");
$Statement->bindParam(':sessionid', $SessionID);
$Statement->execute();
$Result = $Statement->fetch(PDO::FETCH_ASSOC);
$Key = Session::GetKey($SessionID);
$Data = Session::Decrypt($Result['data'], $Key);
return $Data;
}
static function Write($SessionID, $SessionData)
{
$Key = Session::GetKey($SessionID);
$Data = Session::Encrypt($SessionData, $Key);
$TimeNow = time();
$Statement = Session::$DBConnection->prepare('REPLACE INTO sessions (id, set_time, data, session_key) VALUES (:sessionid, :creation_time, :session_data, :session_key)');
$Statement->bindParam(':sessionid', $SessionID);
$Statement->bindParam(':creation_time', $TimeNow);
$Statement->bindParam(':session_data', $Data);
$Statement->bindParam(':session_key', $Key);
$Statement->execute();
return true;
}
static function Destroy($SessionID)
{
$Statement = Session::$DBConnection->prepare('DELETE FROM sessions WHERE id = :sessionid');
$Statement->bindParam(':sessionid', $SessionID);
$Statement->execute();
Session::$SessionCreated = false;
return true;
}
private static function GarbageCollector($Max)
{
$Statement = Session::$DBConnection->prepare('DELETE FROM sessions WHERE set_time < :maxtime');
$OldSessions = time()-$Max;
$Statement->bindParam(':maxtime', $OldSessions);
$Statement->execute();
return true;
}
private static function GetKey($SessionID)
{
$Statement = Session::$DBConnection->prepare('SELECT session_key FROM sessions WHERE id = :sessionid LIMIT 1');
$Statement->bindParam(':sessionid', $SessionID);
$Statement->execute();
$Result = $Statement->fetch(PDO::FETCH_ASSOC);
if($Result['session_key'] != '')
return $Result['session_key'];
else
return hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
}
private static function Encrypt($SessionData, $SessionKey)
{
$Salt = "06wirrdzHDvc*t*nJn9VWIfET+|co*pm~CbtT5P*S2IPD-VmEfd+CX2wrvZ";
$SessionKey = substr(hash('sha256', $Salt.$SessionKey.$Salt), 0, 32);
$Get_IV_Size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$IV = mcrypt_create_iv($Get_IV_Size, MCRYPT_RAND);
$Encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $SessionKey, $SessionData, MCRYPT_MODE_ECB, $IV));
return $Encrypted;
}
private static function Decrypt($SessionData, $SessionKey)
{
$Salt = "06wirrdzHDvc*t*nJn9VWIfET+|co*pm~CbtT5P*S2IPD-VmEfd+CX2wrvZ";
$SessionKey = substr(hash('sha256', $Salt.$SessionKey.$Salt), 0, 32);
$Get_IV_Size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$IV = mcrypt_create_iv($Get_IV_Size, MCRYPT_RAND);
$Decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $SessionKey, base64_decode($SessionData), MCRYPT_MODE_ECB, $IV);
return $Decrypted;
}
}
?>
And i cant exclude that private static function (the first one mentioned) since then i wont be able to set the variables.
And you might say: 'but there is a UpdateSession method'....
Yeah.... kinda.... but the thing is, due to i guess lack of my knowledge, i messed up script somewhere, and the logic goes wrong.
Here are the links (to maybe simplify understanding):
Sessions.FreedomCore.php - Sessions Class
String.FreedomCore.php - Captcha Generation (pointed to exact line)
pager.php - Account Creation Process (works only with session_regenerate_id)
pager.php - Captcha display Process (works always in some cases)
pager.php - Perform Login Case (No issues in any case for some reason)
If you like super interested in how this actually works (i mean how it deauthorize users after 4 refreshes)
Please head over here
Username: test
Password: 123456
So the question is:
How to modify my class, to save session data with session_regenerate_id(true) with usage of current methods and to prevent it to be flushed after session_regenerate_id is called.
These links are pointing directly to problematic areas of the script.
Any help is really appreciated.
Thank you very much for any help!
You are experiencing what I call Cookie Race Condition.
As your are using session_regenerate_id(true) PHP creates a new session id (containing the data of the old session) and deletes the old session from your database for each request.
Now your website contains contains many elements which need to be loaded, e.g. /pager.php or /data/menu.json. And each time the browser gets assigned a new session id. Normally not a problem, but modern browsers do requests in parallel:
pager.php is requested with session_id = a
data/menu.json is requested with session_id = a
pager.php drops sessions_id = a and returns session_id = b to my browser.
data/menu.json cannot find session_id = a in the database and assumes I'm a new visitor and gives me the session_id = c
Now it depends which request is received and parsed by the browser in which order.
Case A data/menu.json is parsed first: the browser stores session_id = c. Then the response of pager.php is parsed and the browser overrides session_id with b. For any next request it will use session_id = b.
Case B pager.php is parsed first and then data/menu.json. The browser stores now session_id = c and you are logged out.
This explains why it's sometimes working (e.g., 4 or 6 refreshes) and sometimes not.
Conclusion: don't use session_regenerate_id(); without a very good reason!
Please raise a new question why the captcha creation mechanism does not work on registration page but on login page.
Some notes on your encryption.
Do NOT use AES with ECB Mode. This weakens the encryption.
You store the encryption key next to your data. Your encryption just blew up.

How does Yii2 Url::remember() work?

How does Url::remember() work? I thought it stores the URL in a cookie, but I don't see it. It's working locally, but not on Heroku.
According to source code, it saves URL in session:
public static function remember($url = '', $name = null)
{
$url = static::to($url);
if ($name === null) {
Yii::$app->getUser()->setReturnUrl($url);
} else {
Yii::$app->getSession()->set($name, $url);
}
}
setReturnUrl will call:
Yii::$app->getSession()->set($this->returnUrlParam, $url);
Official docs:
Session set()
User setReturnUrl()

How to store and change Zend_Auth session ID?

I've recently started using Zend Framework and I'm still pretty used to session_start, and assigning variables to certain session names (ie: $_SESSION['username'] == $username)
I'm trying to figure out how to do something similar to this in Zend. Right now, my auth script checks the credentials using LDAP against my AD server and, if successful, authenticates the user.
I want to create a script that will allow an admin user to easily "enter" someone else's session. Let's say admin1 had an active session and wanted to switch into user1's session. Normally I would just change the $_SESSION['username'] variable and effectively change the identity of the user logged in.
But with Zend, I'm not quite sure how to change the session info. For what it's worth, here's my authentication script:
class LoginController extends Zend_Controller_Action
{
public function getForm()
{
return new LoginForm(array(
'action' => '/login/process',
'method' => 'post',
));
}
public function getAuthAdapter(array $params)
{
$username = $params['username'];
$password = $params['password'];
$auth = Zend_Auth::getInstance();
require_once 'Zend/Config/Ini.php';
$config = new Zend_Config_Ini('../application/configs/application.ini', 'production');
$log_path = $config->ldap->log_path;
$options = $config->ldap->toArray();
unset($options['log_path']);
require_once 'Zend/Auth/Adapter/Ldap.php';
$adapter = new Zend_Auth_Adapter_Ldap($options, $username, $password);
$result = $auth->authenticate($adapter);
if ($log_path) {
$messages = $result->getMessages();
require_once 'Zend/Log.php';
require_once 'Zend/Log/Writer/Stream.php';
require_once 'Zend/Log/Filter/Priority.php';
$logger = new Zend_Log();
$logger->addWriter(new Zend_Log_Writer_Stream($log_path));
$filter = new Zend_Log_Filter_Priority(Zend_Log::DEBUG);
$logger->addFilter($filter);
foreach ($messages as $i => $message) {
if ($i-- > 1) { // $messages[2] and up are log messages
$message = str_replace("\n", "\n ", $message);
$logger->log("Ldap: $i: $message", Zend_Log::DEBUG);
}
}
}
return $adapter;
}
public function preDispatch()
{
if (Zend_Auth::getInstance()->hasIdentity()) {
// If the user is logged in, we don't want to show the login form;
// however, the logout action should still be available
if ('logout' != $this->getRequest()->getActionName()) {
$this->_helper->redirector('index', 'index');
}
} else {
// If they aren't, they can't logout, so that action should
// redirect to the login form
if ('logout' == $this->getRequest()->getActionName()) {
$this->_helper->redirector('index');
}
}
}
public function indexAction()
{
$this->view->form = $this->getForm();
}
public function processAction()
{
$request = $this->getRequest();
// Check if we have a POST request
if (!$request->isPost()) {
return $this->_helper->redirector('index');
}
// Get our form and validate it
$form = $this->getForm();
if (!$form->isValid($request->getPost())) {
// Invalid entries
$this->view->form = $form;
return $this->render('index'); // re-render the login form
}
// Get our authentication adapter and check credentials
$adapter = $this->getAuthAdapter($form->getValues());
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if (!$result->isValid()) {
// Invalid credentials
$form->setDescription('Invalid credentials provided');
$this->view->form = $form;
return $this->render('index'); // re-render the login form
}
// We're authenticated! Redirect to the home page
$this->_helper->redirector('index', 'index');
}
public function logoutAction()
{
Zend_Auth::getInstance()->clearIdentity();
$this->_helper->redirector('index'); // back to login page
}
}
Is there any way to do what I have described? Thanks for any suggestions.
Given your code, the result of authenticating is stored in the PHP session through a Zend_Auth_Storage_Session object.
Calling Zend_Auth::getIdentity() gets access to the storage and returns the result if it is not empty. Likewise, you can change the stored identity by getting access to the underlying storage and changing its value. The actual identity stored as a result of authenticating with Zend_Auth_Adapter_Ldap is just a string value representing the LDAP username.
To effectively change the logged in user, you can do:
Zend_Auth::getInstance()->getStorage()->write('newUserName');
This assumes the default behavior which should be in place given your code.
What I do in my applications after successful authentication is to create a new object of some User model, and write that to the Zend_Auth session so that I have more information about the user available in each session, so you should be aware that different things can be in the storage depending on the application.
This is what I do for example:
$auth = new Zend_Auth(...);
$authResult = $auth->authenticate();
if ($authResult->isValid() == true) {
$userobj = new Application_Model_UserSession();
// populate $userobj with much information about the user
$auth->getStorage()->write($userobj);
}
Now anywhere in my application I call Zend_Auth::getInstance()->getIdentity() I get back the Application_Model_UserSession object rather than a string; but I digress.
The information that should help you is:
$user = Zend_Auth::getInstance()->getIdentity(); // reads from auth->getStorage()
Zend_Auth::getInstance()->getStorage()->write($newUser);

How to save values in session?

I am working with cakephp.Recently I am facing problem in saving data in session.
I have created login page which will send value to controller/action. it will receives like this.
function ajaxCall() {
$this->autoRender = false;
$this->layout = 'ajax';
$arrData = $this->params['url'];
if(!empty($arrData)){
if($arrData['submit']=='Y'){
$userObj = new Api(); // create an instance of the user class
$userInfo = $userObj->login($arrData['email'],$arrData['password']); // call the api login user methods
$xml = simplexml_load_string($userInfo);
$userId = $xml->message->id;
if($userId != "0" && $userId != ""){
$this->setCurrentUserId($userId);
echo "success";
}
else{
echo "no";
}
}
}
}
public function setCurrentUserId($userId)
{
//Is session alive
//if not then redirect to session time out page
//session_start();
//session_register("");
if($userId == 419 || $userId == 423){
$userId1 = $this->Session->write('userId', $userId);
}else{
$userId1 = $this->Session->write('userId', $userId);
}
return $userId1;
}
my controller contain also these line to include helpers,component
public $components = array('Session');
public $helpers = array('Html','Session');
and in core.php file i set session as-
Configure::write('Session', array(
'defaults' => 'php', 'ini' => array('session.auto_start' => 1)
));
Please help me as i am unable to save userId in session
Thanks
On the internet there You can find CakePHP cookbook to create simple application with authentication and authorization: book.cakephp.org
Here You can find very simple example on how to create UsersController, User model and Views for login etc with login action using CakePHP's inbuilt Auth object - there is no need to write the whole login logic - Auth object will do most for You.
Hope You'll enjoy it!

How to set the timeout while using Zend_auth in Zend framework

I am using Zend_auth for authentication purposes.Code for the same is as follows:
$authAdapter = $this->getAuthAdapter();
$authAdapter->setIdentity($username)
->setCredential($password);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
# is the user a valid one?
if ($result->isValid()) {
# all info about this user from the login table
# ommit only the password, we don't need that
$userInfo = $authAdapter->getResultRowObject(null, 'password');
# the default storage is a session with namespace Zend_Auth
$authStorage = $auth->getStorage();
$authStorage->write($userInfo);
$emp_id = $userInfo->employee_id;
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$array_db = new Application_Model_SetMstDb();
$array_name = $array_db->getName($emp_id);
foreach ($array_name as $name) :
$fname = $name['first_name'];
$lname = $name['last_name'];
endforeach;
$firstname = new stdClass;
$lastname = new stdClass;
$userInfo->firstname = $fname;
$userInfo->lastname = $lname;
$privilege_id = $userInfo->privilege_id;
echo 'privilege in Login: ' . $privilege_id;
$this->_redirect('index/index');
} else {
$errorMessage = "Invalid username or password";
$this->view->error = $errorMessage;
}
where getAuthAdapter() as follows:
protected function getAuthAdapter() {
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
$authAdapter->setTableName('credentials')
->setIdentityColumn('employee_id')
->setCredentialColumn('password');
return $authAdapter;
}
I want to set a session timeout.I want to set a timeout of 5 mins and when user does not being active for 5 mins then session should be expired that is logout action should be called whose code is as follows:
public function logoutAction() {
// action body
Zend_Auth::getInstance()->clearIdentity();
$this->_redirect('login/index');
}
Thanks in advance.Plz Help me.Its urgent.
When I use
$session = new Zend_Session_Namespace( 'Zend_Auth' );
$session->setExpirationSeconds( 60 );
control redirects to login page automatically after 60 seconds but I want that if the user of the application in inactive for 60 seconds then only it redirects.At present whether user is active or not redirection occurs.
I wouldn't use init() for this. init() should be use to set object state.
I would use preDispatch(). But to avoid using it all controllers or making a base controller and then extending. You could do a plugin and add it on the Bootstrap.
class YourControllerPlugin extends Zend_Controller_Plugin_Abstract {
public function preDispatch() {
//check if expired
if(hasExpired()) {
//logout and redirect
}
}
}
to add it on Bootstrap :
public function __initYourPlugin () {
$this->bootstrap('frontController');
$plugin = new YourControllerPlugin();
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin($plugin);
return $plugin;
}
I'm looking at my code for this right now. This snippet is from a front controller plugin. Each time an authenticated user requests a page, I reset their session expiration so they've got 60mins from they were last "active".
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) {
//check whether the client is authenticated
if (Zend_Auth::getInstance()->hasIdentity()) {
$session = $this->_getAuthSession();
//update session expiry date to 60mins from NOW
$session->setExpirationSeconds(60*60);
return;
}
Aside: I'm looking over this code for a way to show the user a "your session has expired" message rather than the current "you're not authenticated" message.

Categories