Angularjs: date expiration for $cacheFactory - caching

I have added cache in my application with $cacheFactory, but when the user close the browser and then reopen, the cache data about the browsed products is expired.
Are there any way to make it longer? put a date of expiration or something like that?
Thanks.
Edit: I would maybe have to use Breeze.js, but before this I wanted to know if any of you know if it is possible to do it with angularjs (I read the API and there is no info about it :S).
Edit 2: to help, the way in which I use $cacheFactory is like this JSFiddle code.
factory('SomeCache', function($cacheFactory) {
return $cacheFactory('someCache', {
capacity: 3 // optional - turns the cache into LRU cache
});
}).
Edit 3: Lawnchair is not an option, it stores in a javascript array and doesn't persists the data after closing the browser..

$cacheFactory uses in-memory browser storage, which means it doesn't persist across even a page refresh, let alone closing and re-opening the browser.
If you want to cache data across page loads and browser sessions, you're looking for localStorage. See here for a very simple example:
http://jsbin.com/acokis/2/edit
I think you'll want to look at amplify.js or lawnchair.js as they provide nice wrappers for managing localStorage, also also provide fallback adapters for browsers that don't support localStorage (fallback options won't persist across page refreshes though).

Related

How firefox fetches correct data from Browser Cache

Once we open a link in a new tab in Firefox, the data corresponding to that web page(static or dynamic) gets stored in Browser Cache. Then, when we switches at that tab again, it extracts data of that page from Cache(not requesting from the server of that site) and paints it at the frame buffer of the screen.
I want to know that how Firefox fetches this data in correct sequence?
What kind of mapping does the Firefox uses to extract the page data from its Cache?
Firefox (like any other browser) uses heuristics to decide when and what to cache. This is assuming no caching information is included in the resources. When no caching information is provided, Firefox might still decide to cache the files for certain period of time.
If you want to avoid Firefox to cache your resources altogether, you must include the following response header on your resources:
Cache-Control:no-cache, no-store
Now, the exact algorithm that Firefox uses to fetch from cache I don't think is public. Maybe somebody from Mozilla is able to answer this.

CodeIgniter CSRF protection and page caching

I've searched around but couldn't find anything about this. Am I the only one who have experienced that CSRF protection in CodeIgniter doesn't work with page caching?
What do I have:
A webpage which will be cached trough this line:
$this->output->cache( 120 );
In the Javascript on that page I've got a Ajax call where the data contains the CSRF token too. Everything works fine when caching is disabled or when I disable CSRF protection.
Does somebody know a workaround or something so I can have caching and CSRF protection enabled?
Thanks!
I'm somewhat surprised that form_open() doesn't handle that for you, in a similar way that benchmarking functions' output aren't cached.
Here are two possible workarounds.
Use the caching driver (!= output->cache())
Instead of using Output class caching, which caches a completely rendered page, you could employ the caching driver's key-value cache to save rendered portions of your page.
If the form containing this problematic CSRF token is complex and contains a lot of dynamic content from an external data source, cache those database results (either with the caching driver or by enabling database result caching) and feed the cached values into a dynamic form.
Warning about file-based cache from the manual:
Unlike caching from the Output Class, the driver file-based caching
allows for pieces of view files to be cached. Use this with care, and
make sure to benchmark your application, as a point can come where
disk I/O will negate positive gains by caching.
Of course, if you have access to memcached or APC, use that instead.
Disable output caching for that page and profile.
Intercepting the output cache (fully-rendered page) and replacing the CSRF token value
I came across an interesting solution on Caching forms with CSRF tokens (in Symfony). To paraphrase the original author:
Before setting the cached response, find and replace CSRF tokens.
Store the position of the tokens with the response (so it gets cached as well).
Before returning a response from the cache inject fresh CSRF tokens.
In CodeIgniter, intercepting the cache seems to require use of the pre_system hook-point, though in your case, you may be able to use cache_override. Take a look at this excellent article on the way in which CodeIgniter implements CRSF tokens for inspiration. I don't think it would be trivial to implement, though.
Don't cache that page and don't worry about it
This is obviously the simplest solution. Test it. Depending on your page complexity, the negative performance impact of not caching that subset of pages may well outweigh the pain of implementing either of the above two solutions. (Since we don't know what your views or controller look like, whether or not this is an acceptable solution in your case isn't immediately obvious). If it's an isolated login form in an SPA, you can probbaly get away with it.

Prevent a session from expiring?

We have a simple CCTV system in our office that shows a live image from each of our security cameras. The CCTV system doesn't have an API or any method of extracting the live images. You can however view the image from another browser by creating a basic HTML page with the image link:
http://192.168.1.6/media/getimage_sid.php?sid=a09c4ecb72bade3802e7bf563b0d0bd6&card=1&camera=1&width=384&height=288
This works perfectly, until the session expires and/or timesout. I don't know very much about cookies and sessions but when I inspected the page in Google Chrome I noticed the following cookie:
Name Value Domain Path Expires Size
PHPSESSID a09c4ecb72bade3802e7bf563b0d0bd6 192.168.1.6 / Session 41
there is also a HTTP column and a Secure column but both are empty.
What I am trying to figure out, is how do I keep that cookie alive or trigger it to recreate with the same value? I'm assuming that a rake task to log in to the system wouldn't work because that would reset the session ID every time.
The intranet is a Rails application, so one way would be to create a script that logs in and stores the current session ID to the database and then putting the last recorded sessions ID into the IMG links from the database. It's a bit of a long way around though, I'm hoping for a better solution.
I have read a few articles showing how to do this with AJAX but that would appear to rely on the intranet being viewed all the time. I need this to work if no-one has viewed the intranet for the weekend.
This project is so we can put a couple of live (when the page refreshes!) images on our intranet so we don't have to continuously go to the CCTV system, log in and find the right camera just to see who is at the garage door etc.
Any help would be appreciated.
It's a bit of hack but I've made a small script to pull in the latest session ID and then put it into the image links.
A random different approach: does the following URL get the right image, without having to worry about the session id?
http://192.168.1.6/media/getimage_sid.php?card=1&camera=1&width=384&height=288
The session ID used in the cookie seems to be the PHP generated one.
I don't think session ID should become stale if you 'notify' the server that you're still online.1 You should try to specify the Cookie: in your HTTP request headers. Specifying the SID via the URL is probably not be enough to indicate to the server that you're actually using it.2
If your web-pages are fetching the images directly (i.e. you have an <img src="http://192.168.1.6/..."> in the HTML page) you might work like this:
make an AJAX request (XMLHttpRequest) to a URL which returns a session ID.
any subsequent request to the server on that page should automatically include the session in the headers.3
Otherwise, if you can't specify a Cookie: header, you may choose to make the time before a session becomes stale longer. If you have access to the computer hosting the PHP interface (192.168.1.6) then you can configure PHP to do so (via the php.ini configuration file, I believe). Information about session configuration is available here, and specifically the gc-maxlifetime options seems useful:
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and potentially cleaned up. Garbage collection may occur during session start (depending on session.gc_probability and session.gc_divisor).
Alternatively, if none of the above appeal to you, your solution to fetch (GET) a page to obtain a valid, fresh session ID seems logical and good. You could optimize this by measuring how long it takes before session IDs become stale and fetching new session IDs only at that interval.
1 I looked for a valid reference for this but couldn't find one.
2 specifically PHP uses a PHPSESSID= token in the URL whereas in your example it looks like sid=. It is also generally considered bad practice security-wise I believe (this article explains how it might be used for XSS), since you're exposing user information in the URL, though I think this has little to no effect in this case
3 according to the XMLHttpRequest spec of the send() method:
If the user agent supports HTTP State Management it should persist, discard and send cookies

Any good jQuery caching plugin?

When I log-in to my Gmail Inbox it starts caching the mails one-by-one in JavaScript.
When I click on a mail in the Inbox, it doesn't send an Ajax request then to fetch the mail contents.
Instead it serves from an already cached JavaScript array.
Is there any good jQuery plugin to implement this?
I came across a few but they don't seem to be under active development.
http://plugins.jquery.com/project/jCache
http://plugins.jquery.com/project/jCacher
Any better plugin?
Edit1:
My requirement is exactly same as what Gmail is doing.
There is a ticket management system which shows a list of open tickets(say 100 tickets on a page) and once you click on a ticket its details are displayed. I want to cache the details of all 100 tickets displayed on the page.
I am planning to implement the cache as object of key-value pairs only. But I am looking for a plugin which takes care of tasks like setting/getting values from cache, auto-updating the cache periodically etc.
Storing in JS object shall be enogh for me. I don't see any advantages of using HTML5 local storage as
* No offline browsing is required and
* I wan't to load fresh data every time a new window is opened
* I won't need huge amount of memory
You could use some of the new html5 localstorage http://diveintohtml5.ep.io/storage.html
I think Google is rather using HTML5 local storage than caching. They seem to be big fans of HTML5 and adopt anything as soon as it's available. If you must use cookies, I'd recommend this one.
As Pointy suggested, the cache implementation was indeed heavily dependent on my application. Hence I have written my own code to handle this requirement. Thanks to all.

Clear all website cache?

Is it possible to clear all site cache? I would like to do this when the user logs out or the session expires instead of instructing the browser not to cache on each request.
As far as I know, there is no way to instruct the browser to clear all the pages it has cached for your site. The only control that you, as a website author, have over caching of a page occurs when the browser tries to access that page. You can specify that cached versions of your pages should expire at a certain time using the Expires header, but even then the browser won't actually clear the page from its cache at that time.
i certainly hope not - that would give the web site destructive powers over the client machine!
If security is your main concern here, why not use HTTPS? Browsers don't cache content received via HTTPS (or cache it only in memory).
One tricky way to mimic this would be to include the session-id as a parameter when referencing any static piece of content on the site. When the user establishes the session, the browser will recognize all the pieces of content as new due to the inclusion of this parameter. For the duration of the session the browser will used the static content in its cache. After the user logs out and logs back in again, the session-id parameter for the static contents will be different, so the browser will recognize this is as completely new content and will download everything again.
That being said... this is a hack and I wouldn't recommend pursuing it.. For what reason do you want the user's cache to be cleared after their session expires? There's probably a better solution that can fit your situation as opposed to what you are currently asking for.
If you are talking about asp.net cache objects, you can use this:
For Each elem As DictionaryEntry In Cache
Cache.Remove(elem.Key)
Next
to remove items from the cache, but that may not be the full-extent of what you are trying to accomplish.

Resources