Storing a 'user' in javascript - javascript

I would like to enable a user to save their preferences without having to log in. I was thinking of using the user's IP to save their preferences, but this doesn't work for 'workplaces' where multiple people will be on the same IP-connection.
What would be the best way to do this? Basically, I want to store a per-person session without using a database (and hopefully, without having to use a secondary data-store, such as redis).
Is it possible to do this in javascript?

Cookies are your best bet. Tied to the browser of a user, and available for your server too - https://developer.mozilla.org/en-US/docs/Web/API/document/cookie
You may also look at local storage - https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
Understand the difference between the two and make a choice - Local Storage vs Cookies

From your description, I think that saving these preferences on the user's machine is the best option. If it is small amount of data (less than 100KB), then use cookies. If it is big (but still within allowed limits approx 5MB) then use local storage (indexedDB or webStorage).

You can use localstorage. You can store key-value items.
Set value:
window.localstorage.setItem(key, value);
Get value:
var value = window.localstorage.getItem(key);
Example: http://jsfiddle.net/wasnvvo7/1/

Just give the user a unique key to store as a cookie and then use that key to keep track of that user's data. --WARNING!! if the user moves to a different machine or deletes his/her cookies, the session will not be usable.

Related

Is it possible to inject values in session storage manually for local testing?

I usually work on my local eclipse and local IDEs like Sublime Text and use XAMPP locally to work locally. Since local code doesn't involve authentication and many more stuff, I am wondering if its possible to manually inject the session storage values in my web browser so that I can use that in my local settings without having the need to deploy the code to server where I have access to all sessionStorage values I'm looking for.
For example, I have the following code:
var key = JSON.parse(sessionStorage.getItem("loggedInUser"));
var username = key.displayedValues;
console.log("Username retrieved below");
console.log(username);
And whenever I run this code locally, since I don't have any values stored in sessionstorage in my webbrowser, I run into issues. For local testing, I always have to hard code values and test which I don't want.
More clarifications:
I am wondering if I can add it manually in the browser in some manner so that in my code, I can get the value like this sessionStorage.getItem("loggedInUser"). I don't' want to set it first from my code and then access it.
just set it like:
sessionStorage.setItem('loggedInUser', {object details of your user})

how to find tab close and clear local storage

I am using onbeforeunload function in javascript but problem is that if browser is refresh then also clear local storage . I want to only clear local storage when browser close not refresh browser
window.onbeforeunload = function(e) {
localStorage.setItem('isLoggedIn', 'false');
};
You can use sessionStorage instead. It is automatically cleared when the browser is closed.
Example:
sessionStorage.setItem("isLoggedIn","true"); // Value will be set to null when browser is closed
You can be needed to learn about local storage, session storage, and Cookies. there are 3 options use for store data but it's one of the different another concept.
local storage store locally and it's permanent if you not remove this or clear browser.
session storage use for containing a status or a token or a user some information.
when you close the browser then session storage remove automatically. (note: if you went any running time you can change it like as logout).
Cookies is another powerful way to store data in the browser or client site. it also allows the time schedule or date. when expiring time or date then it's destroyed automatically.
there are 3 storage are the different their concept and work it's also different storage capacity each other.
Session storage operation:
sessionStorage.SessionName = "SessionData" ,
sessionStorage.getItem("SessionName") and
sessionStorage.setItem("SessionName","SessionData");
Cookie example simple operation:
you can also learn about more:
https://www.quora.com/What-is-the-difference-between-sessionstorage-localstorage-and-Cookies
https://developer.mozilla.org/en-US/docs/Mozilla/Gecko/DOM_Storage_implementation_notes
https://www.w3schools.com/js/js_cookies.asp
=== Thanks ===

Safe place to store an encrypt/decrypt key using PHP and JS

I just want everyone to know that I am in no way a professional web developer nor a security expert. Well, I'm not a beginner either. You can say that I am an amateur individual finding interest in web development.
And so, I'm developing a simple, small, and rather, a personal web app (though I'm thinking of sharing it to some friends and any individual who might find it interesting) that audits/logs every expense you take so you can keep track of the money you spend down to the last bit. Although my app is as simple as that (for now).
Since I'm taking my app to be shared to some friends and individuals as a factor, I already implemented a login to my application. Although it only needs the user key, which acts as the username and password at the same time.
I've used jQuery AJAX/PHP for the login authentication, as simple as getting the text entered by such user in the textbox, passing it to jQuery then passing it to the PHP on the server to verify if such user exists. And if yes, the user will be redirected to the main interface where his/her weekly expense will be logged.
Much for that, my main problem and interest is within the security, I've formulated a simple and a rather weak security logic where a user can't get to the main interface without having to login successfully first. The flow is like this.
when a user tries to go the main interface (dashboard.php) without successfully logging in on the login page (index.php), he will then be prompted something like "you are not able to view this page as you are not logged in." and then s/he will be redirected back to the login page (index.php)
How I've done this is rather simple:
Once a user key has been verified and the user is logged in successfully, cookies will then be created (and here is where my dilemma begins). the app will create 2 cookies, 1 is 'user_key' where the user key will be stored; and 2 is 'access_auth' where the main interface access is defined, true if logged in successfully and false if wrong or invalid user key.
Of course I'm trying to make things a little secure, I've encrypted both the cookie name and value with an openssl_encrypt function with 'AES-128-CBC' with PHP here, each and every user key has it's own unique iv_key to be used with the encryption/decryption of the cookie and it's values. I've encrypted the cookie so it wouldn't be naked and easily altered, since they won't know which is which. Of course, the encrypted text will vary for every user key since they have unique iv_keys although they have same 'key' values hard-coded in the PHP file.
pretty crazy right ?. yea i know, just let me be for that. and as how the main interface (dashboard.php) knows if a user has been logged in or not and to redirect them back to the login page (index.php) is purely easy. 'that' iv_key is stored together with the user_key row in the database.
I've attached a JavaScript in the main interface (dashboard.php) which will check if the cookie is equal to 2, if it is less than or greater than that, all those cookies will be deleted and then the user will redirected to the login page (index.php).
var x = [];
var y = 0;
//Count Cookie
$.each($.cookie(), function(z){
x[y] = z;
y++;
});
//Check if Cookie is complete
if (x.length != 2) {
//If incomplete Cookie - delete remaining cookie, prompt access denied, and redirect to login page
for (var i = 0; i < x.length; i++) {
$.removeCookie(x[i], { path: '/' });
};
alert("You are not allowed to enter this page as you are not yet logged in !.");
window.location.href = "index.php";
} else {
//If complete Cookie - authenticate cookie if existing in database
}
As you can see, the code is rather incomplete, what I want to do next after verifying that the count of the cookies stored is 2 is to dig in that cookie, decrypt it and ensure that the values are correct using the 'iv_key', the iv_key will then be used to decrypt a cookie that contains the user_key and check if it is existing in the database, at the same time the cookie that contains access_auth will also be decrypted and alter it's value depending on the user_key cookie's verification (returns true if user_key is found in database, otherwise false). Then after checking everything is legitimate, the cookies will then be re-encrypted using the same iv_key stored somewhere I don't know yet.
My question is and was, 'where is a safe location to store the encryption/decryption key?' and that is the 'iv_key'. I've read some threads and things about Session Variables, Local Storage, and Cookie. And I've put this things into consideration.
SESSION - I can use session storage of PHP to store the key in something like $_SESSION['user_key'] then access it later when needed be. But I've read an opinion saying that it is not recommended to store sensitive information including keys, passwords, or anything in session variable since they are stored somewhere on the server's public directory. And another thing is the session variable's lifespan, it lasts for around 30 minutes or so. I need to keep the key for as long as the user is logged in. The nice thing I find here is that, it'll be a little bit hard to alter the value and I don't need to encrypt it (the iv_key) here since it is server sided, and hidden to the naked eye, well not unless when being hacked of course. What I mean is, they don't appear on the debugging tools just like how localStorage and Cookies are visible there.
LOCAL STORAGE - this eliminates my problem of lifespan, since it will be stored in the localStorage vault of the browser not until I close the browser. But the problem here is that the values can easily be changed via console box of the debugger tool, I can eliminate this problem by encrypting the 'iv_key', but what's the point of encrypting the encryption/decryption key? Should I encrypt it using itself as the 'iv_key' too? Or I can use base64_encode?, which eliminates the security of needing a key, and can be decrypted so easily with no hassle.
COOKIE - this one adopts two problems, one from session variable and one from localstorage. From session variable, I mean is the lifespan. As far as I've read, cookies last for about 1 hour or so, but still depends if an expiry has been declared when setting the cookie. The other is from localStorage, since it can easily be altered via console box of the debugger tools too. Although I've already encrypted 2 Cookies beforehand, but what's the point of storing the encryption key together with the values you encrypted?, should I go on with this and encrypt the 'iv_key' by itself, just like what I might do with localStorage?.
I'm lost as to where I should save this sensitive 'encryption_key' as it is crucial in encrypting and decrypting the cookies and other information my app needs.
Why am I so devastated with such security, despite having a simple worthless app?.
Well, because I know and I believe that I can use this as a two-step further knowledge which I can used with my future projects. I maybe doing web development for fun right now. But I'm taking it to consideration as my profession. And so, I want my apps to be secure in any means.

Implementing Database in HTML5 Mobile App

I am having trouble deciding hot to implement a database for my mobile app. I am using javascript with jquery mobile and phonegap to hopefully deploy to IOS and Android. The database is basically a list of about 60-70 location names, description, latitude and longitude. I need the data to be available even if the user does not have internet access and need to perform queries such as sorting the locations by closest distance.
Is there a way to create the database file beforehand and open as needed or do I need to create the database each time when my app opens? Does the database file reside on the device even after the app is closed or does it create it again when app is restarted?
Any suggestions or examples?
Thanks,
Robert
There are several types of browser storage such as localStorage they are all built in and can be used directly.
Storage objects are a recent addition to the standard. As such they may not be present in all browsers.........The maximum size of data that can be saved is severely restricted by the use of cookies.
Code sample:
function storeMyContact(id) {
var fullname = document.getElementById('fullname').innerHTML;
var phone = document.getElementById('phone').innerHTML;
var email = document.getElementById('email').innerHTML;
localStorage.setItem('mcFull',fullname);
localStorage.setItem('mcPhone',phone);
localStorage.setItem('mcEmail',email);
}
On the other hand, localStorage might not be enough, therefore, external libraries come to hand which actually utilize the browsers built in storage and make the db works cross browsers.
1- SQL like DB sequelsphere (looks like suitable for heavy lifting!)
Code sample for query that will run directly from the browser:
SELECT empl_id, name, age
FROM empl
WHERE age < 30
2- JSON like DB taffydb (looks like suitable for every day activity!)
// Create DB and fill it with records
var friends = TAFFY([
{"id":1,"gender":"M","first":"John","last":"Smith","city":"Seattle, WA","status":"Active"},
{"id":2,"gender":"F","first":"Kelly","last":"Ruth","city":"Dallas, TX","status":"Active"},
{"id":3,"gender":"M","first":"Jeff","last":"Stevenson","city":"Washington, D.C.","status":"Active"},
{"id":4,"gender":"F","first":"Jennifer","last":"Gill","city":"Seattle, WA","status":"Active"}
]);
// Find all the friends in Seattle
friends({city:"Seattle, WA"});
3- Since you mentioned mobile, then jstorage is a cross-browser key-value store database to store data locally in the browser - jStorage supports all major browsers, both in desktop (yes - even Internet Explorer 6) and in mobile.
If you would like to have more options ->(client-side-browser-database)
The easiest would be to use localStorage.
window.localStorage.setItem("key", "value");
var value = window.localStorage.getItem("key");
If you need to store more data and have complex queries use a real Database.
Both can be found in the Cordova Docs on Storage
There is also pouch db. I use it with my Ionic App. Works great and very simple to learn and use. I use local storage only for minor temporarily used data (within a session). To persist data even when app is closed and re-opened, Pouchdb works great. By default, it's calls are async. Works well with Promises.

Cookie with Multiple Values stored

I'm having trouble with cookies. I have a bunch of links that when clicked on, create a cookie. For each link I need to be able to save that cookie value to the main cookie name.
Here is the click function I'm using to create the cookie:
$j('a.createCookie').click(function(e) {
var cookieName = "InsightsCookie";
var cookieValue = $j(this).attr("id");
$j.cookie(cookieName, cookieValue, {expires: 365, path: '/'});
});
The end result would be "InsightsCookie: cookieValue, cookieValue, cookieValue" - where each link clicked on would add a value to InsightsCookie.
Any help would be much appreciated.
Cookies aren't intended to store structured data.
Typically the cookie has some kind of key value (a random integer, or alphanumerical value, for example) that is unique to that person. The web site uses that cookie to know who is visiting, and then keeps track of all the times/places the person with that cookie goes in some kind of database, thereby building a history.
So, basically, it's typically the web site's job to keep track of that, not the cookie on the user's machine.
If that's not an option for you for some reason, you could simply get the value that's already in the cookie, and then append the new value to it with each visit. If that user visits a lot of pages on your site, the cookie might get too big very quickly. There are restrictions on the maximum size of a cookie, and that's kind of a janky way to do it.

Categories