js-cookie: Cookies.get('cookieName') returns undefined - javascript

I'm using this library for a JQuery plugin I'm coding... I save inside a cookie a specific data created by the user in this way:
// Update cookies checks if the cookie esists.
// If cookie exists => push data {myData:[obj1[, obj2, [...], objN]]}
// If cookie doesn't exists => create cookie with {myData:[obj1]}
function _updateCookie(name, cookie, data) {
// Check if cookie exists
var cookies = {myData:[]};
// _getCookie(name) { return Cookies.get(name) }
if (_getCookie(name) != undefined) {
cookies = _getCookie(name);
}
cookies.reminders.push(cookie);
Cookies.set(name, cookies, data);
}
DATA:
var data = {
expires: 1,
path: '/',
domain: '',
secure: true
}
COOKIE:
var cookie = {
myData: [
1: myObject1,
2: myObject2,
// [...]
n: myObjectN
],
}
When I call _getCookie(name) it always returns undefined. I've also tried to list the cookies with:
console.log(Cookies.get());
// log: Object {_ga: "GA1.1.402426237.1450622600"}
But if i look at chrome://settings/cookies i see:
2 cookies on localhost [_ga], [myCookie]
Any suggestion of what am I doing wrong?
EDIT
I saw that the problem comes out when i call Cookie.set(); with this values
Cookies.set('myCookie', {[expires: ...], path: '', domain: ''});
if I call
Cookies.set('myCookie'{[expires: ...]});
I can get the cookie with no problems.

Related

Javascript Cookies being reset after page reload

Good day.
I've been using js-cookie to set cookies in my application, they are set in the exact same way however one of them turns into undefined whenever i use window.location or reload the page. I set 2 cookies, one for a token and one for for the user role in my application but for whatever reason the user role cookie is reset.
Here is how i set it:
login ({dispatch }, payload) {
axios.get('/login',{
auth: {
username: payload.username,
password: payload.password
}
}).then(function (response) {
let in120Minutes = 1/12;
Cookies.set('user_role', response.data['permissions'].user_role, {expires: in120Minutes})
Cookies.set('token', response.data['x-access-token'], {expires: in120Minutes})
window.location.pathname = '/myPage'
}).catch(function (error) {
dispatch('errorHandler', error, { root: true })
})
},
Why does this happen exactly? I do the exact same thing into another application and it works fine.

Priority WebSDK getRows(1) returns no data

I am using the default code from https://www.npmjs.com/package/priority-web-sdk
var configuration = {
username: '<username>',
password: '<password>',
url: '<app server url>',
tabulaini: 'tabula.ini',
language: 3,
company: 'demo'
};
priority.login(configuration)
.then(()=> priority.formStart('CUSTOMERS', null, null, 'demo', 1))
.then(form=> form.getRows(1))
.then(rows=> console.log(rows))
.catch(err=> console.log(err));
if i run the code with my config i get no result however if i remove form.getRows(1) and pass the result of formStart i then get a response and the form info is logged to the console i just can't seam to get any more data?
I am using node but if i include the script on the client side and run it that way then it works fine but this is insecure so not a solution.
the soloution was to check if the window is undefined in my code
if it is then we should set it.
if (typeof window === 'undefined') {
global.window = {}
}

Intercepting response in dojo to read cookies

I have a filter on server side which adds a cookie myCookie to every response.
I am intercepting the response in a dojo widget as below:
define("mySolution/ServerCookieWidget", [
"dojo/request/notify",
"dojo/cookie"
], function (notify, cookie) {
notify("load", function(response) {
var cookieRead = cookie("myCookie");
console.log('Cookie read is: ', cookieRead);
});
});
I want to use the value read to do some calculation on client side.
How do I share the read cookie value with other widget?
I am new to dojo and thus not aware of the syntax and not able to find any example for my scenario.
Depending on the rest of your architecture, you might want to use Dojo's pubsub module dojo/topic:
https://dojotoolkit.org/reference-guide/1.10/dojo/topic.html
So for example, changing your code to:
define("mySolution/ServerCookieWidget", [
"dojo/request/notify",
"dojo/cookie",
"dojo/topic"
], function (notify, cookie, topic) {
notify("load", function(response) {
var cookieRead = cookie("myCookie");
// console.log('Cookie read is: ', cookieRead);
topic.publish("*/cookie/value", cookieRead);
});
});
You can create widgets which subscribe to the topic:
define("mySolution/SomeOtherWidget", [
"dojo/_base/declare",
"dojo/topic"
], function (declare, topic) {
var OtherWidget = declare(null, {
constructor: function (opt) {
this.topicHandle = topic.subscribe("*/cookie/value", this._handleCookieValue.bind(this));
},
_handleCookieValue: function (cookieVal) {
console.log("Cookie value is:", cookeVal);
}
});
return OtherWidget;
});

Loopback is not responding with modified data after 'loaded' hook

I have the following code in my Model.js file.
Model.observe('loaded', (ctx, next) => {
const {
data,
options: {
user
}
} = ctx;
const owner = (user && data && user.uid === data.userId) || false;
console.log(
`${data.id}: loaded - access by ${user && user.name}, owner:${owner}`
);
if (!owner) {
delete data.testProp1;
}
console.log('returning: ', ctx.data);
next();
});
When I make a request, I see the following log output (server logs):
f3f9ffd6-14dc-42e5-94ba-503aa3426faa: loaded - access by User1, owner:false
returning:
{
testProp2: true,
id: 'f3f9ffd6-14dc-42e5-94ba-503aa3426faa',
userId: 'sfeywkKSuBTlf0DwE4ZOFd8RX5E3'
}
But then in the actual response the browser receives I actually get:
{
testProp1: true,
testProp2: true,
id: 'f3f9ffd6-14dc-42e5-94ba-503aa3426faa',
userId: 'sfeywkKSuBTlf0DwE4ZOFd8RX5E3'
}
Is there something in the documentation I am missing? Deleting the property is exactly what it shows in the Loopback docs here. Also, I actually see the modified data as the data property on the ctx object before calling next(). Anyone run into this issue or know some caveat to the docs that isn't explicitly stated?

sessionStorage data not persist in AngularJS app with ngStorage

All,
I'm simply trying to store a user object in sessionStorage in an AngularJS app. If I step through this in either the Chrome or FF debugger, the sessionStorage never gets set. Here is my angular service code:
// Authentication/authorization Module
stonewall.authModule = angular.module("authModule", [
// Module dependencies
"ngStorage"
]);
// Authentication/authorization service tracks the current user
stonewall.authModule.service('authService', function ($localStorage, $sessionStorage) {
// Initialize current user
var currentUser = {};
restoreSession();
// Declare storage type-this may change if user selects
// "Keep me signed in"
var storageType = {};
// Return the current user object
this.getCurrentUser = function () {
return currentUser;
};
// Returns whether there is a currently authorized user
this.userAuth = function() {
return currentUser.sid != "";
};
// Logout function, initializes the user object
this.logout = function() {
currentUser = {
sid: "",
status: 0,
pswLastSet: 0,
id: "",
sigUID: "",
sig: ""
};
//persistSession();
};
// Login
this.login = function(user, subj) {
if (user == null) return;
currentUser = {
sid: user.Principal.SId,
status: user.Principal.ControlStatus,
pswLastSet: new Date(user.Principal.PasswordLastSet),
id: user.Identity.Id.DN,
sigUID: user.Identity.Certificates[0].UID,
sig: stonewall.hash(user.Principal.SId + subj.pswd),
};
persistSession();
};
// Persist to session storage
function persistSession() {
$sessionStorage.currentUser = currentUser;
};
// Restore session
function restoreSession() {
currentUser = $sessionStorage.currentUser;
if (currentUser == null) {
// Initialize to empty user
currentUser = {
sid: "",
status: 0,
pswLastSet: 0,
id: "",
sigUID: "",
sig: ""
};
}
};
});
And, here is a screencap that shows my FF debugging session. You can see that after persistSession is called that $sessionStorage has my user.
But, if I switch over to the DOM inspector, sessionStorage has no items in it...
Any help is, as always, appreciated.
Are you sure you are using angular's sessionStorage in the right way?
Session storage is a property of the $window object in angular, so I don't know if you have made your own service wrapper or something like that?
Anyway, here is a codepen that shows another approach that I use myself, using $window.sessionStorage instead: http://codepen.io/chrisenytc/pen/gyGcx

Categories