Cookies across multiple WAR files - http

I'm creating a facelets template for all my company's internal applications. Its appearance is based on the skin which the user selects (like gmail themes).
It makes sense to store the user's preferred skin in a cookie.
My "user-preferences" WAR can see this cookie. However, my other applications are unable to find the cookie. They are on the same domain/subdomain as the user-preferences WAR.
Is there some reason for this?
Here is my bean which is used to create/find the preferred skin. This same file is used in all the projects:
// BackingBeanBase is just a class with convenience methods. Doesn't
// really affect anything here.
public class UserSkinBean extends BackingBeanBase {
private final static String SKIN_COOKIE_NAME = "preferredSkin";
private final static String DEFAULT_SKIN_NAME = "classic";
/**
* Get the name of the user's preferred skin. If this value wasn't set previously,
* it will return a default value.
*
* #return
*/
public String getSkinName() {
Cookie skinNameCookie = findSkinCookie();
if (skinNameCookie == null) {
skinNameCookie = initializeSkinNameCookie(DEFAULT_SKIN_NAME);
addCookie(skinNameCookie);
}
return skinNameCookie.getValue();
}
/**
* Set the skin to the given name. Must be the name of a valid richFaces skin.
*
* #param skinName
*/
public void setSkinName(String skinName) {
if (skinName == null) {
skinName = DEFAULT_SKIN_NAME;
}
Cookie skinNameCookie = findSkinCookie();
if (skinNameCookie == null) {
skinNameCookie = initializeSkinNameCookie(skinName);
}
else {
skinNameCookie.setValue(skinName);
}
addCookie(skinNameCookie);
}
private void addCookie(Cookie skinNameCookie) {
((HttpServletResponse)getFacesContext().getExternalContext().getResponse()).addCookie(skinNameCookie);
}
private Cookie initializeSkinNameCookie(String skinName) {
Cookie ret = new Cookie(SKIN_COOKIE_NAME, skinName);
ret.setComment("The purpose of this cookie is to hold the name of the user's preferred richFaces skin.");
//set the max age to one year.
ret.setMaxAge(60 * 60 * 24 * 365);
ret.setPath("/");
return ret;
}
private Cookie findSkinCookie() {
Cookie[] cookies = ((HttpServletRequest)getFacesContext().getExternalContext().getRequest()).getCookies();
Cookie ret = null;
for (Cookie cookie : cookies) {
if (cookie.getName().equals(SKIN_COOKIE_NAME)) {
ret = cookie;
break;
}
}
return ret;
}
}
Can anyone see what I'm doing wrong?
Update: I've narrowed it down a bit...it works fine in FF, but IE still doesn't like it (of course).
Thanks,
Zack

I think you need to assign domain/subdomain to the cookies.
Like, (Note that the domain should start with a dot)
ret.setDomain(".test.com");
ret.setDomain(".test.co.uk");
http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Cookies.html

I found a solution.
I just used javascript on the client-side to create the cookies.
This worked fine.

Related

How to cache a JSON response in the Silverstripe Controller?

We have a Silverstripe 4 project which acts as a headless CMS returning a group of complex data models formatted as JSON.
Here's an example of the code:
class APIController extends ContentController
{
public function index(HTTPRequest $request)
{
$dataArray['model1'] = AccessPointController::getModel1();
$dataArray['model2'] = AccessPointController::getModel2();
$dataArray['model3'] = AccessPointController::getModel3();
$dataArray['model4'] = AccessPointController::getModel4();
$dataArray['model5'] = AccessPointController::getModel5();
$dataArray['model6'] = AccessPointController::getModel6();
$this->response->addHeader('Content-Type', 'application/json');
$this->response->addHeader('Access-Control-Allow-Origin', '*');
return json_encode($dataArray);
}
The problem we're having is the data models have got so complex the generation time for the JSON is running into seconds.
The JSON should only change when site content has been updates so ideally we'd like to cache the JSON & rather than dynamically generating it for each call.
What is the best way to cache the JSON in the above example?
Have you looked at the silverstripe docs about caching?
They do provide a programmatic way to store things in cache. And configuration options what back-ends are to be used to store the cache.
A simple example might be:
I've extended the cache live time here, but still you should note that this cache is not intended for storing generated static content, but rather to reduce load. Your application will still have to compute the api response every 86400 seconds (24 hours).
# app/_config/apiCache.yml
---
Name: apicacheconfig
---
# [... rest of your config config ...]
SilverStripe\Core\Injector\Injector:
Psr\SimpleCache\CacheInterface.apiResponseCache:
factory: SilverStripe\Core\Cache\CacheFactory
constructor:
namespace: "apiResponseCache"
defaultLifetime: 86400
<?php // app/src/FooController.php
class FooController extends \SilverStripe\Control\Controller {
public function getCache() {
return Injector::inst()->get('Psr\SimpleCache\CacheInterface.apiResponseCache');
// or your own cache (see below):
// return new MyCache();
}
protected function hasDataBeenChanged() {
// alternative to this method, you could also simply include Page::get()->max('LastEdited') or whatever in your cache key inside index(), but if you are using your own cache system, you need to handle deleting of old unused cache files. If you are using SilverStripe's cache, it will do that for you
$c = $this->getCache();
$lastCacheTime = $c->has('cacheTime') ? (int)$c->get('cacheTime') : 0;
$lastDataChangeTime = strtotime(Page::get()->max('LastEdited'));
return $lastDataChangeTime > $lastCacheTime;
}
public function index() {
$c = $this->getCache();
$cacheKey = 'indexActionResponse';
if ($c->has($cacheKey) && !$this->hasDataBeenChanged()) {
$data = $c->get($cacheKey);
} else {
$dataArray['model1'] = AccessPointController::getModel1();
$dataArray['model2'] = AccessPointController::getModel2();
$dataArray['model3'] = AccessPointController::getModel3();
$dataArray['model4'] = AccessPointController::getModel4();
$dataArray['model5'] = AccessPointController::getModel5();
$dataArray['model6'] = AccessPointController::getModel6();
$data = json_encode($dataArray);
$c->set($cacheKey, $data);
$c->set('cacheTime', time());
}
$this->response->addHeader('Content-Type', 'application/json');
$this->response->addHeader('Access-Control-Allow-Origin', '*');
return json_encode($dataArray);
}
}
If you are looking for a permanent/persistent cache, that will only ever update when data changed, I suggest you look for a different back-end or just implement a simple cache yourself and use that instead of the silverstripe cache.
class MyCache {
protected function fileName($key) {
if (strpos($key, '/') !== false || strpos($key, '\\') !== false) {
throw new \Exception("Invalid cache key '$key'");
}
return BASE_PATH . "/api-cache/$key.json";
}
public function get($key) {
if ($this->has($key)) {
return file_get_contents($this->fileName($key));
}
return null;
}
public function set($key, $val) {
file_put_contents($this->fileName($key), $val);
}
public function has($key) {
$f = $this->fileName($key);
return #file_exists($f);
}

Symfony 3, detect browser language

I use Symfony 3.
My website is in 2 languages, French and English and people can switch via a select form.
Default language is French.
Main URL are:
example.com/fr for French version and example.com/en for English version
Well, now, I will like when the user arrives to the website to detect his browser language and redirect to the correct language automatically.
Exemple, if the browser is in French, he is redirected to the French version : example.com/fr
Else he is redirected to the English version: example.com/en
Is there a way to do that properly?
Thank you for your help
If you don't want to rely on other bundles like JMSI18nRoutingBundle
you have to make yourself familiar with Symfony's Event system, e.g. by reading up on the HttpKernel.
For your case you want to hook into the kernel.request event.
Typical Purposes: To add more information to the Request, initialize parts of the system, or return a Response if possible (e.g. a security layer that denies access).
In your custom EventListener you can listen to that event add information to the Request-object used in your router. It could look something like this:
class LanguageListener implements EventSubscriberInterface
{
private $supportedLanguages;
public function __construct(array $supportedLanguages)
{
if (empty($supportedLanguages)) {
throw new \InvalidArgumentException('At least one supported language must be given.');
}
$this->supportedLanguages = $supportedLanguages;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['redirectToLocalizedHomepage', 100],
];
}
public function redirectToLocalizedHomepage(GetResponseEvent $event)
{
// Do not modify sub-requests
if (KernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
// Assume all routes except the frontpage use the _locale parameter
if ($event->getRequest()->getPathInfo() !== '/') {
return;
}
$language = $this->supportedLanguages[0];
if (null !== $acceptLanguage = $event->getRequest()->headers->get('Accept-Language')) {
$negotiator = new LanguageNegotiator();
$best = $negotiator->getBest(
$event->getRequest()->headers->get('Accept-Language'),
$this->supportedLanguages
);
if (null !== $best) {
$language = $best->getType();
}
}
$response = new RedirectResponse('/' . $language);
$event->setResponse($response);
}
}
This listener will check the Accept-Language header of the request and use the Negotiation\LanguageNegotiator to determine the best locale. Be careful as I didn't add the use statements, but they should be fairly obvious.
For a more advanced version you can just read the source for the LocaleChoosingListener from JMSI18nRoutingBundle.
Doing this is usually only required for the frontpage, which is why both the example I posted and the one from the JMSBundle exclude all other paths. For those you can just use the special parameter _locale as described in the documentation:
https://symfony.com/doc/current/translation/locale.html#the-locale-and-the-url
The Symfony documentation also contains an example how to read the locale and make it sticky in a session using a Listener: https://symfony.com/doc/current/session/locale_sticky_session.html
This example also shows how to register the Listener in your services.yml.
Slight changes to #dbrumann's answer to work with my use case and setup:
List of available locales are defined in services.yml file:
parameters:
available_locales:
- nl
- en
- cs
I wanted to determine the locale on any landing page of the website. In case the parsing fails, it fallbacks to _locale parameter or the default one.
class LocaleDetermineSubscriber implements EventSubscriberInterface
{
private $defaultLocale;
private $parameterBag;
private $logger;
public function __construct(ParameterBagInterface $parameterBag,
LoggerInterface $logger,
$defaultLocale = 'en')
{
$this->defaultLocale = $defaultLocale;
$this->parameterBag = $parameterBag;
$this->logger = $logger;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
//do this on first request only
if ($request->hasPreviousSession()) {
return;
}
$allowedLocales = $this->parameterBag->get('available_locales'); //defined in services.yml
$determinedLocale = null;
// use locale from the user preference header
$acceptLanguage = $event->getRequest()->headers->get('Accept-Language');
if ($acceptLanguage != null) {
$negotiator = new LanguageNegotiator();
try {
$best = $negotiator->getBest($acceptLanguage, $allowedLocales);
if ($best != null) {
$language = $best->getType();
$request->setLocale($language);
$determinedLocale = $language;
}
} catch (Exception $e) {
$this->logger->warning("Failed to determine language from Accept-Language header " . $e);
}
}
//check if locale is set with _locale parameter if user preference header parsing not happened
if($determinedLocale == null) {
if ($locale = $request->attributes->get('_locale')) {
if(in_array($locale, $allowedLocales)) {
$request->getSession()->set('_locale', $locale);
} else {
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
} else {
//fallback to default
$request->setLocale($this->defaultLocale);
}
}
}
public static function getSubscribedEvents()
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 25]],
];
}
}
It uses the willdurand/negotiation package, so it needs to be installed first:
composer require willdurand/negotiation
https://packagist.org/packages/willdurand/negotiation

Doctrine OneToMany with aggregate field, how to keep it up to date?

In doctrine2 I have a OneToMany association: One Application <=> Many ApplicationCost
// Application.php
/**
* #ORM\OneToMany(targetEntity="ApplicationCost", mappedBy="application", orphanRemoval=true)
*/
protected $costs;
// ApplicationCost.php
/**
* #ORM\ManyToOne(targetEntity="Application", inversedBy="costs")
* #ORM\JoinColumn(name="application_id", referencedColumnName="id")
*/
protected $application;
In Application entity I have an agregate field sumCosts:
/**
* #ORM\Column(type="decimal", scale=2)
*/
protected $sumCosts;
Which is updated when addCost and removeCost are called:
// Application.php
public function addCost(ApplicationCost $cost)
{
if (!$this->costs->contains($cost)) {
$this->sumCosts += $cost->getBalance();
$this->costs[] = $cost;
$cost->setApplication($this);
}
return $this;
}
public function removeCost(ApplicationCost $cost)
{
if ($this->costs->contains($cost)) {
$this->sumCosts -= $cost->getBalance();
$this->costs->removeElement($cost);
}
}
Assuming User can edit already existing ApplicationCost's and can change it's parent Application, how do I make sure that this agregate field is up to date?
My approach is:
// ApplicationCost.php
public function setApplication(Application $application = null)
{
if ($this->application !== null) {
$this->application->removeCost($this);
}
if ($application !== null) {
$application->addCost($this);
}
$this->application = $application;
return $this;
}
Is that good? Or am I makeing here some huge mistake here and sumCosts may be out of sync?
EDIT: I've read Doctrine's Aggregate Fields cookbook and I have the versioning (and I use locking mechanism). My question is not about concurrency.
EDIT: I've created some tests
public function testSumCosts()
{
$app = new Application();
$costA = new ApplicationCost();
$costA->setBalance(150);
$costB = new ApplicationCost();
$costB->setBalance(100);
$costC = new ApplicationCost();
$costC->setBalance(50);
$app->addCost($costA);
$app->addCost($costB);
$app->addCost($costC);
$app->removeCost($costC);
$this->assertEquals(250, $app->sumCosts(), 'Costs are summed correctly');
}
public function testCostsChangeApplication()
{
$appA = new Application();
$appB = new Application();
$costA = new ApplicationCost();
$costA->setBalance(100);
$costB = new ApplicationCost();
$costB->setBalance(50);
$appA->addCost($costA);
$appB->addCost($costB);
$costA->setApplication($appB);
$costB->setApplication(null);
$this->assertEquals(0, $appA->sumCosts(), 'Costs are removed correctly');
$this->assertEquals(100, $appB->sumCosts(), 'Costs are added correctly');
}
And after adding $cost->setApplication($this); to addEntry both tests are green. Though I still wonder if I might have missed something.
Okay, I think I finally achieved desired result. I'll describe it for future reference and anyone who might have the same problem:
First of all correct the class
// Application.php
public function addCost(ApplicationCost $cost)
{
if (!$this->costs->contains($cost)) {
$this->sumCosts += $cost->getBalance();
}
$this->costs[] = $cost;
return $this;
}
public function removeCost(ApplicationCost $cost)
{
if ($this->costs->contains($cost)) {
$this->sumCosts -= $cost->getBalance();
}
$this->costs->removeElement($cost);
}
If you compare this to my original code you'll see that only updateing the agregate field is under condition. It does not hurt as collections can't hold duplicate elements and can't remove non existing elements.
Second of all, configure the cascade={all} option on inverse side of association (that is, on costs inside Application.php). So whenever you add/remove costs they are persisted too.
to be continued... (have to test what happens when i change application it from the owning side and persist only ApplicationCost -> will both old and new Application be updated?)

is it possible to value store cookies in Flash or Flex?

In PHP there is a setcookie function based to store it. In Flash is it possible ?.
If it is possible then how?
I want to store value.
First off: PHP runs on the server and therefore can send the necessary HTTP header to set a cookie, Flash runs in the client's browser and thus can not do the same.
However, there is a way to access and store cookies from flash/flex by using the flash.external.ExternalInterface and calling JavaScript functions to get and set cookies.
I've developed a class for doing this very easily:
package de.slashslash.util {
import flash.external.ExternalInterface;
/**
* The Cookie class provides a simple way to create or access
* cookies in the embedding HTML document of the application.
*
*/
public class Cookie {
/**
* Flag if the class was properly initialized.
*/
private static var _initialized:Boolean = false;
/**
* Name of the cookie.
*/
private var _name:String;
/**
* Contents of the cookie.
*/
private var _value:String;
/**
* Flag indicating if a cookie was just created. It is <code>true</code>
* when the cookie did not exist before and <code>false</code> otherwise.
*/
private var _isNew:Boolean;
/**
* Name of the external javascript function used for getting
* cookie information.
*/
private static const GET_COOKIE:String = "cookieGetCookie";
/**
* Name of the external javascript function used for setting
* cookie information.
*/
private static const SET_COOKIE:String = "cookieSetCookie";
/**
* Javascript code to define the GET_COOKIE function.
*/
private static var FUNCTION_GET_COOKIE:String =
"function () { " +
"if (document." + GET_COOKIE + " == null) {" +
GET_COOKIE + " = function (name) { " +
"if (document.cookie) {" +
"cookies = document.cookie.split('; ');" +
"for (i = 0; i < cookies.length; i++) {" +
"param = cookies[i].split('=', 2);" +
"if (decodeURIComponent(param[0]) == name) {" +
"value = decodeURIComponent(param[1]);" +
"return value;" +
"}" +
"}" +
"}" +
"return null;" +
"};" +
"}" +
"}";
/**
* Javascript code to define the SET_COOKIE function.
*/
private static var FUNCTION_SET_COOKIE:String =
"function () { " +
"if (document." + SET_COOKIE + " == null) {" +
SET_COOKIE + " = function (name, value) { " +
"document.cookie = name + '=' + value;" +
"};" +
"}" +
"}";
/**
* Initializes the class by injecting javascript code into
* the embedding document. If the class was already initialized
* before, this method does nothing.
*/
private static function initialize():void {
if (Cookie._initialized) {
return;
}
if (!ExternalInterface.available) {
throw new Error("ExternalInterface is not available in this container. Internet Explorer ActiveX, Firefox, Mozilla 1.7.5 and greater, or other browsers that support NPRuntime are required.");
}
// Add functions to DOM if they aren't already there
ExternalInterface.call(FUNCTION_GET_COOKIE);
ExternalInterface.call(FUNCTION_SET_COOKIE);
Cookie._initialized = true;
}
/**
* Creates a new Cookie object. If a cookie with the specified
* name already exists, the existing value is used. Otherwise
* a new cookie is created as soon as a value is assigned to it.
*
* #param name The name of the cookie
*/
public function Cookie(name:String) {
Cookie.initialize();
this._name = name;
this._value = ExternalInterface.call(GET_COOKIE, name) as String;
this._isNew = this._value == null;
}
/**
* The name of the cookie.
*/
public function get name():String {
return this._name;
}
/**
* The value of the cookie. If it is a new cookie, it is not
* made persistent until a value is assigned to it.
*/
public function get value():String {
return this._value;
}
/**
* #private
*/
public function set value(value:String):void {
this._value = value;
ExternalInterface.call(SET_COOKIE, this._name, this._value);
}
/**
* The <code>isNew</code> property indicates if the cookie
* already exists or not.
*/
public function get isNew():Boolean {
return this._isNew;
}
}
}
Yes. Flash applications can store up to 100kb of data (by default) on a user's computer. This is stored in Flash cookies (Separate from browser cookies). Users can adjust how much applications can store by right clicking on a flash application and going to settings.
Here is the SharedObject API for AS3:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/SharedObject.html
You can get more info by googling "Flash SharedObject"
Make sure to be prepared to handle cases where a user does not let you put data into SharedObjects. This is becoming a popular trend among tech-savy users that are concerned about their privacy.
Good luck!
for an actual code example:
import flash.net.SharedObject;
// get/create the shared object with a unique name.
// If the shared object exists this grab it, if not
// then it will create a new one
var so: SharedObject = SharedObject.getLocal("UniqueName");
// the shared object has a propery named data, it's
// an object on which you can create, read, or modify
// properties (you can't set the data property itself!)
// you can check to see if it already has something set
// using hasOwnProperty, so we'll check if it has a var
// use it if it does, or set it to a default if it doesn't
if (so.data.hasOwnProperty("theProp"))
{
trace("already has data! It reads: " + so.data.theProp);
}
else
{
so.data.theProp = "default value";
so.flush(); // flush saves the data
trace("It didn't have a value, so we set it.");
}
Paste this in flash, publish it twice and see how it stored the data :)

How do I get an already (basic) authenticated context to call a web service behind the same authentication?

I have a site behind basic authentication (IIS6).
Part of this site calls a web service that is also part of the site and thus behind basic authentication as well.
However, when this happens the calling code receives a 401 Authentication Error.
I've tried a couple of things, with the general recommendation being code like this:
Service.ServiceName s = new Service.ServiceName();
s.PreAuthenticate = true;
s.Credentials = System.Net.CredentialCache.DefaultCredentials;
s.Method("Test");
However, this does not seem to resolve my problem.
Any advice?
Edit
This seems to be a not uncommon issue but so far I have found no solutions.
Here is one thread on the topic.
Solution: (I am almost certain this will help someone)
See this link for the source of this solution in VB (thanks jshardy!), all I did was convert to C#.
NB: You must be using ONLY basic authentication on IIS for this to work, but it can probably be adapted. You also need to pass a Page instance in, or at least the Request.ServerVariables property (or use 'this' if called from a Page code-behind directly). I'd tidy this up and probably remove the use of references but this is a faithful translation of the original solution and you can make any amendments necessary.
public static void ServiceCall(Page p)
{
LocalServices.ServiceName s = new LocalServices.ServiceName();
s.PreAuthenticate = true; /* Not sure if required */
string username = "";
string password = "";
string domain = "";
GetBasicCredentials(p, ref username, ref password, ref domain);
s.Credentials = new NetworkCredential(username, password, domain);
s.ServiceMethod();
}
/* Converted from: http://forums.asp.net/t/1172902.aspx */
private static void GetBasicCredentials(Page p, ref string rstrUser, ref string rstrPassword, ref string rstrDomain)
{
if (p == null)
{
return;
}
rstrUser = "";
rstrPassword = "";
rstrDomain = "";
rstrUser = p.Request.ServerVariables["AUTH_USER"];
rstrPassword = p.Request.ServerVariables["AUTH_PASSWORD"];
SplitDomainUserName(rstrUser, ref rstrDomain, ref rstrUser);
/* MSDN KB article 835388
BUG: The Request.ServerVariables("AUTH_PASSWORD") object does not display certain characters from an ASPX page */
string lstrHeader = p.Request.ServerVariables["HTTP_AUTHORIZATION"];
if (!string.IsNullOrEmpty(lstrHeader) && lstrHeader.StartsWith("Basic"))
{
string lstrTicket = lstrHeader.Substring(6);
lstrTicket = System.Text.Encoding.Default.GetString(Convert.FromBase64String(lstrTicket));
rstrPassword = lstrTicket.Substring((lstrTicket.IndexOf(":") + 1));
}
/* At least on my XP Pro machine AUTH_USER is not set (probably because we're using Forms authentication
But if the password is set (either by AUTH_PASSWORD or HTTP_AUTHORIZATION)
then we can use LOGON_USER*/
if (string.IsNullOrEmpty(rstrUser) && !string.IsNullOrEmpty(rstrPassword))
{
rstrUser = p.Request.ServerVariables["LOGON_USER"];
SplitDomainUserName(rstrUser, ref rstrDomain, ref rstrUser);
}
}
/* Converted from: http://forums.asp.net/t/1172902.aspx */
private static void SplitDomainUserName(string pstrDomainUserName, ref string rstrDomainName, ref string rstrUserName)
{
rstrDomainName = "";
rstrUserName = pstrDomainUserName;
int lnSlashPos = pstrDomainUserName.IndexOf("\\");
if (lnSlashPos > 0)
{
rstrDomainName = pstrDomainUserName.Substring(0, lnSlashPos);
rstrUserName = pstrDomainUserName.Substring(lnSlashPos + 1);
}
}
The Line:
s.Credentials = System.Net.CredentialCache.DefaultCredentials();
Maybe you should try :
s.Credentials = HttpContext.Current.User.Identity;

Resources