I want to set cookie value in one function and their value use everywhere in cakephp 4 version.
Currently , i can use cookie value inside the only one function which i have set their value.
I can get cookie value in index() function but i can't get cookie value in viewusers() function.
Code is here :
use App\Controller\AppController;
use Cake\Http\Cookie\Cookie;
use Cake\Http\Cookie\CookieCollection
use DateTime;
class AdminController extends AppController {
function index(){
$cookie = array();
$cookie['admin_username'] = $requestData['username'];
$cookie['admin_password'] = $requestData['password'];
$cookies = new Cookie('AuthAdmin',$cookie, new DateTime('+1 weeks'));
$response = $this->response->withCookie($cookie);
return $this->redirect('admin/viewusers');
}
function viewusers() {
$cookies = new CookieCollection();
$data = $cookies->get('AuthAdmin');
print_r($data);
// cookie value not found in $data variable.
$response = $this->response->getCookie('Auth.Admin');
print_r($response);
// cookie value not found in $response variable.
}
}
I can get cookie value in index() function but i can't get cookie value in viewusers() function.
Try this:
function index(){
$cookie = array();
$cookie['admin_username'] = $requestData['username'];
$cookie['admin_password'] = $requestData['password'];
$cookies = new Cookie('AuthAdmin',$cookie, new DateTime('+1 weeks'));
return $this
// redirect returns a response object, so you can chain the cookie call onto that
->redirect('admin/viewusers')
// Note that this uses $cookies, not $cookie
->withCookie($cookies);
}
But again, I cannot stress strongly enough that sending a cookie with the user's username and password in it is a very bad thing from a security perspective.
Related
I'm testing my Rest APIs.
I want to pass a parameter to my request.
This is in my controller, I have:
public function index(Request $request)
{
$abuse = Abuse::where('bombId', $request->input('bombId'))->get();
}
Thing is with PhpUnit, I can never simulate the bombId parameter...
Here is my code:
$data['bombId'] = 25; // I also tried $bombId = 25;
$this->get('api/v1/abuse', $data])
->seeJson(['total' => 11]);
$this->assertResponseStatus(200);
EDIT:
When I use:
$this->call('GET','api/v1/abuse', $credentials);
Param is passed, but I can't use anymore SeeJson method :(
Any Idea?
I found my answer with Jeffrey Way:
$response = $this->call('GET', 'api/v1/abuse', $credentials);
$data = $this->parseJson($response);
$this->assertIsJson($data);
$this->assertEquals(11, $data->total);
I want to make a auto login when users used APP after first time.I tried to keep it in alloy.js and Ti.App.Properties.getString('login_token'),but they didn't work.
in my coffee:
result = JSON.parse this.responseText
console.info result.token #"dsfdsfds2142fds3r32rf32e3dfefwedf"
Ti.App.Properties.setString "token",result.token
console.info Ti.App.Properties.getString "token" # it's blank
I couldn't find a built in way to do this so i just created a getter and setter method and put it in alloy.js. Feels very hacky and dirty but it does work.
//retrieves the value of the token
// also checks if the token is valid and sets logged_in accordingly
function getToken(){
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'api.txt');
var content = f.read();
//if we can read this return it, otherwise return a blank value
if (content){
return content.text;
}
else {
return '';
}
}
//persists and sets the value of token to the new value
function setToken(key){
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'api.txt');
f.deleteFile();
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'api.txt');
f.write(key);
token = key;
}
I found this topic Zend Framework 2 - Cookie Concept while I was searching for info about setting cookie in ZF2, but seems like information included in that topic are out of date.
I have tried following code:
public function indexAction()
{
$request = $this->getRequest()->getHeaders()->get('Set-Cookie')->foo = 'bar;
$response = $this->getResponse()->getCookie()->baz = 'test';
var_dump($_COOKIE);
...
return new ViewModel();
}
Both lines output warning:
Warning: Creating default object from empty value
I tried also:
public function indexAction()
{
$cookie = new SetCookie('test', 'value', 60*60*24); // Zend\Http\Header\SetCookie instance
$header = new Cookie(); // Zend\Http\Cookies instance
$header->addCookie($cookie);
...
return new ViewModel();
}
It doesn't return any error or warning, everything seems to be ok, but when I try var_dump($_COOKIE) it still shows null.
Yes, my browser has enable cookie.
Here is my solution which I'm currently using.
$cookie = new SetCookie('key', 'value', time() + 365 * 60 * 60 * 24); // now + 1 year
$headers = $this->getResponse()->getHeaders();
$headers->addHeader($cookie);
I'm stuck on a common problem but I don't really know how to get out.
The browsers don't keep the auth session.
Here is my setup.
"application.ini"
resources.session.save_path = ROOT_DIR "/public/session"
resources.session.gc_maxlifetime = 864000
resources.session.remember_me_seconds = 864000
".htaccess"
php_value session.gc_maxlifetime 864000
php_value session.save_path /Users/user/mydomain.com/public/session/
"bootstrap.php" (_initSessionNamespaces it's the first method I call)
protected function _initSessionNamespaces()
{
$this->bootstrap('session');
Zend_Session::start();
}
"SigninController.php"
// set adapter
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
$authAdapter->setTableName('user')
->setIdentityColumn('email')
->setCredentialColumn('password')
->setCredentialTreatment($salt)
->setIdentity($values['email'])
->setCredential($values['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
$user = $authAdapter->getResultRowObject();
$auth->getStorage()->write($user);
// init session cookie
$session_auth = new Zend_Session_Namespace('identity');
$session_auth->setExpirationSeconds(864000);
return true;
}
the session file that has been created in the directory is this:
language|a:1:{s:6:"locale";s:2:"en";}identity|a:2:{s:14:"filterDistance";i:5;s:5:"email";s:15:"test#test.com";}Zend_Auth|a:1:{s:7:"storage";O:8:"stdClass":20:{s:2:"id";s:20:"8c3b329b0f3d71f4566c";s:12:"date_created";s:19:"2012-12-19 20:30:29";s:12:"date_updated";s:19:"2013-01-12 00:02:19";s:14:"date_lastlogin";s:19:"2013-01-16 15:30:01";s:7:"site_id";s:4:"this";s:14:"site_lastlogin";s:4:"this";s:6:"active";s:1:"1";s:4:"role";s:5:"admin";s:8:"username";s:5:"test";s:8:"password";s:40:"63fb7f1941083ca0284481d8ad557e2b0c5bf5f4";s:4:"salt";s:40:"70be1adbff1c0bd6f82sc1fcaf6d2fef3c869b6c";s:10:"first_name";s:5:"pippo";s:9:"last_name";s:0:"";s:5:"email";s:15:"test#test.com";}}__ZF|a:1:{s:9:"Zend_Auth";a:1:{s:3:"ENT";i:865358347332;}}
And usually in a Controller I call the user info in this way
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$this->info = $auth->getIdentity();
}
When I restart the browser it create a new empty session file like this:
language|a:1:{s:6:"locale";s:2:"it";}
I'm stuck here for 2 days... what can I do??
I solved it adding this in application.ini
resources.session.cookie_lifetime = 864000
I think this could help someone :)
I have a text field and a submit button. User submits an email id and on successful submission a lightbox will load. On successful submission I am setting a cookie and initially assigning a value of 1. Though I am able to set the increment I am not able to assign the incremented value to the cookie value.
var demoCookieCount = getCookie("democount");
$('#online-demo-lightbox-button').click(function (e) {
e.preventDefault();
demoCookiecount++;
});
You have to store the new value in the cookie by using setCookie() or something like
function setCookie(democount, ++demoCookiecount, 1)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
You don't save the new value into the cookie. Try something like that in the end:
document.cookie = cookieName + cookieContent + cookieExpires;
Finally somehow got through. This piece of code worked
//setting the Cookie democount with initial value of 1
setCookie("democount", '1');
//getting the value of 'democount' cookie and assigning it to a variable
var demoCookieCount = getCookie("democount");
$('#sample-button').click(function (e) {
e.preventDefault();
//increment the variable on every click
demoCookieCount++;
//set the incremented value of demoCookieCount variable to democount cookie
setCookie("democount",demoCookieCount);
// assigning the value of demoCookiecount to variable 123
var123 = getCookie("democount");
});