Check expiration times jQuery cookie - cookies

I have set a cookie using the jQuery cookie plugin. I've set the expiration on the cookie to one hour, so after that time the cookie is deleted. I want to display the remaining time left until the cookie expires to the user by retrieving this info from the cookie itself. is this possible using the jQuery cookies plugin? If not is there an eloquent way to achieve this?
I've set the expiration in this way:
jQuery.cookie('Cookie', timedCookie, { expires: new Date(+new Date() + (60 * 60 * 1000)) });

It's impossible to get a cookie's expiration using JavaScript. The only way to do this would be to store the expiration date somehow, such as in a javascript variable or in another cookie or local storage.
Here's an example:
var MINUTES = 1000 * 60;
var expireTime = new Date(+new Date + (60 * MINUTES)); // store the expiration time
jQuery.cookie('Cookie', timedCookie, { expires: expireTime });
var updateMessage = function(msg){
document.getElementById('time-left').innerHTML = msg;
};
var i = setInterval(function(){ // calculate time difference every ~1 min
var timeLeft = expireTime - new Date;
if(timeLeft <= 0){
updateMessage('Your session has expired.');
clearInterval(i);
} else {
updateMessage('You have ' + (timeLeft / MINUTES | 0) + ' minute(s) left in your cookied session.');
}
}, MINUTES);

Related

Javascript: - Refresh a page with a different time of refresh depending which page anchor they are viewing

I have this refresh script that refresh the page every 30 seconds.
<script>
var time = new Date().getTime();
$(document.body).bind("mousemove keypress", function(e) {
time = new Date().getTime();
});
function refresh() {
if(new Date().getTime() - time >= 30000)
window.location.reload(true);
else
setTimeout(refresh, 10000);
}
setTimeout(refresh, 10000);
</script>
Is it possible to set a different time of page refresh depending on the page anchor the user is viewing?
If user is viewing the default anchor page.php#main then the page will refresh every 30 seconds. But if the user is viewing anchor page #view1, then the page refresh is set to 60 seconds. Then on refresh returns the page to page.php#view1
SOLVED: I found an answer to my problem.
Using the window.name attribute I was able to set a value in seconds in the window.name and then a small javascript in each anchor area of the page which changed the window.name value when I needed a different time for refresh. I setup different values in the javascript function as follows.
function refresh() {
var secs;
if (window.name == '1'){
secs = '60000';
} else if (window.name == '2') {
secs = '120000';
} else if (window.name == '3'){
secs = '0';
} else {
secs = '180000'
}
if((new Date().getTime() - time >= secs)&&(secs != '0'))
window.location.reload(true);
Then in the html where the anchors are I added following scripts where I needed different times for refresh. I used a paragraph tag to help get it working.
<p id='demo'></p>
<script>
window.name = '1';
document.getElementById('demo').innerHTML = window.name;
</script>
<script>
window.name = '2';
document.getElementById('demo').innerHTML = window.name;
</script>

NextAuth Cookie not being set in production

I have a React + Nextjs application which uses NextAuth. I'm trying to set a refresh token in a cookie which works fine on localhost but doesn't work when deployed on to production (HTTPS). The function setting the cookie is shown below. Is there something that I've missed?
From [...nextauth].ts:
const setRefreshTokenCookie = (
cookies: Cookies,
refresh_token: string
): Cookies => {
const date = new Date();
const time = date.getTime();
const expireTime = time + 24 * 60 * 60 * 1000 * 90; // 90 days
date.setTime(expireTime);
const currentCookies = cookies.set(
`${useSecureCookies ? "__Host-" : ""}test.refresh-token`,
refresh_token,
{
sameSite: "strict",
overwrite: true,
expires: date,
httpOnly: useSecureCookies,
}
);
return currentCookies ;
};
Notes:
NextAuth's useSecureCookie
localhost cookies:
test.csrf-token
test.refresh-token
test.callback-url
test.session-token
production cookies:
__Host-test.csrf-token
__Secure-test.callback-url
__Secure-test.session-token

Expiring a Cookie after 30 days

I'm just need to make sure I have this correct. I don't have 30days (or even a day) to test this.
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
I think all I have to do is add this line of code:
var days = "30";
Is this correct? How can I test that this works after 1 minute while still using the days var? I'm not very good at math :x
I can rest easy knowing everything is working.
I am testing every half-minute with the code below.
var days = "0.00034722222";

How to set expiry date for a cookie in Angular 2?

How to add expiry date to Angular 2 cookie. I am trying with Angular 2.0.0-beta.15. When i try to add options like below:
var expireDate = new Date (new Date().getTime() + (1000 * data.expires_in));
this._cookieService.put('token', this.token, {expires: expireDate});
above code throwing error like "[ts] Argument of type '{ expires: Date; }' is not assignable to parameter of type 'CookieOptionsArgs'.
Property 'path' is missing in type '{ expires: Date; }'. (local var)
expireDate: Date"
I can see on https://www.npmjs.com/package/angular2-cookie to override default options globally. I doubt if this is the method to add expiry date to cookie? Can somebody help me to understand more on this?
I have used this library with success: https://github.com/BCJTI/ng2-cookies. Use it like below with setting expiry date:
Include the lib:
import {Cookie} from 'ng2-cookies/ng2-cookies';
Set a cookie with expiry date of 365 days:
Cookie.setCookie("cookie-key", "cookie-value", 365);
A little bit late but Should be something like this
let key = 'testCookieKey';
let value = 'testCookieValue';
let opts: CookieOptionsArgs = {
expires: new Date('2030-07-19')
};
cookieService.put(key, value, opts);
Hope that
For Expiry date parameter in set cookies the value should be seconds to days calculation.
i.e. 2 min = (2/1440)
//use for 2 minutes....
auth-cookies.ts
import { Injectable } from '#angular/core';
import { Cookie } from 'ng2-cookies/ng2-cookies';
#Injectable()
export class AuthCookie {
constructor() { }
getAuth(): string {
return Cookie.get('id_token');
}
setAuth(value: string): void {
//0.0138889=20 minuts
//this accept day not minuts
//use for 20 minuts
Cookie.set('cookie_token', value, 0.0138889);
//use for 2 minuts
// Cookie.set('cookie_token', value,0.00138889)
}
deleteAuth(): void {
Cookie.delete('id_token');
}
}
i post it too late but hope this will be useful.

How to disable a date range in Jquery datepicker

I want to disable a range of dates which I are fetched using Ajax. I'm doing it as follows -
$("#date_frm").datepicker({
dateFormat: 'yy-mm-dd',
constrainInput: true,
beforeShow:function(input, inst) {
$.ajax({
type: "POST",
url: "/admin/get_time_span",
data: "",
success: function(data) {
disabled_day = data;
},
});
},
beforeShowDay: disableRangeOfDays
});
function disableRangeOfDays(d)
{
//var arr = "2012-04-19 to 2012-04-26,";
var arr = disabled_day.split(",");
var arr = arr.split(",");
var cnt = arr.length-1;
for(i=0; i<cnt; i++) {
arr1 = arr[i].split(" to ");
//create date for from_date
frm_dt = arr1[0].split('-');
//create date for to_date
to_dt = arr1[1].split('-');
if(d >= new Date(frm_dt[0],(frm_dt[1]-1),frm_dt[2]) &&
d <= new Date(to_dt[0],(to_dt[1]-1),to_dt[2])) {
return [false];
}
}
return [true,''];
}
This works but not for the first time. When I open the date picker first time, the date range still selectable. But, after I close and reopen it, the date range is disabled. Also, if I change the month and come back to the current month then also it works. How can I disable the date range for the first time I open the date picker ? Also, for each month, I want to fetch the date ranges and disable them. How can I do this ?
After spending much time in checking possibilities, I fetched all the date ranges only once while loading the page and assigned all to a hidden field. I removed the Ajax call and used the value of the hidden field directly in the function disableRangeOfDays(d) and it worked as expected.