How to make a site "unique" from each user? - javascript

I have made a "dating app" website where you can like hard-coded users - just an assignment not implemented in real life:).
Whenever a user logs in - which it only can if it has SignUp - and likes a hard-coded match it gets saved via local storage. So whenever an other user logs in, that user has the exact same site and liked profiles.
So my question is, how do you save a user action individually on a website - in theory - so not everyone share the same site. Links for articles would also be much appreciated, cause I investigated myself, but couldn't find any usefull articles.
Thank you for your help in advance!

I'm assuming you don't have a backend and that is why you are using local storage.
logalstorage is a set of (key, value) pairs. You'll need to make the key unique depending on the user that is logged in.
For example:
let user = "Greg"
localStorage.setItem.(user + "likes", likes);
and to get the data later
let likes = localStorage.getItem.(user + "likes");
This idea of a unique key is exactly how databases work.

Related

localStorage does not work with user accounts

I'm building an application whereby if a user wishes to add an item to a personal watchlist, they must be logged in. I use localStorage to store this personal watchlist data and to retrieve it. The problem I am having is that if account 'A' adds an item to their watchlist and then logs out and account 'B' then logs in, the previous stored data is returned from account 'A'.
How can I prevent this from happening so that the data is only saved/returned for each particular user account? Should I be using something instead of localStorage like sessionStorage? Any help is appreciated.
I've solved this personally by including an identifier for the user in the local storage key. You'll have an entry per user and do the lookup based on the identifier. Something like:
localStorage.setItem(`watchlist:${user.id}`, data) // set
const watchlist = localStorage.getItem(`watchlist:${user.id}`) // get
As noted by #AlexB in the comments, be aware that multiple users on the same device will have the local data of any other users in their localStorage, so be sure to consider privacy.
Save your data with userId as key(unique for all user) and corresponding watchlist as data
localStorage.setItem('userId', data);
and then fetch it with the login user Id
localStorage.getItem('loginUserId');

How to login a user using firebase authentication

I'm currently using firebase-admin to create a web Dashboard with node.js as a backend which will have multiple users and those users have user specific data in my database, note that I need them to be able to delete or add stuff to the database as well, I've managed to add new users to Autentication using firebase.auth().createUser() programmatically, but how would one go about logging in a user, and then from there controlling which uid is logged in and displaying his data (giving him access to the correct data, obviously don't want him messing with someone elses data).
I know this might seem like a really newbie question, and it probably is, but firebase docs always get me confused for some reason. Any tips? I'd greatly appreciate.
Any questions don't hesitate.
To login a new user, try this:
firebase.auth().signInWithEmailAndPassword(email, password)
this returns a Firebase.Promise which you can use to track the operation progress. If successful, it will return the corresponding Firebase.User object.
From there, the logged-in user will also be available in the firebase.auth().currentUser property. You can then use the user's uid property as a key for his JSON branch on the database.

Mysql read the "just-now" updated value

I have searched and found something related to isolation level and "prevent dirty read". What I understood from my search was that I needed to isolate transaction level with READ COMMITED option (I am not sure about that though, still mysql begginner). What I want, however, is to make sure that when I get the information with SELECT it is, for sure, the updated information (the information could have been updated just instants ago and I would get the old info if I don't do anything about it...).
I think I understood the theory but I can't say the same about practice.
My old query was like this (js):
var query = "SELECT name FROM user_info WHERE id = "+user_id+"";
// doesn't solve my problem...
How can I perform what I want? Something like this?
var query = "SET TRANSACTION ISOLATION LEVEL READ COMMITED SELECT name FROM user_info WHERE id = "+user_id+"";
Thank you.
EDIT: (this might help explaining...)
The client is able to perform certain actions and I want to forbide clients from doing those multiple actions too fast. When a client action is sent to the server I check in db if the player is able to do the action or not. If the action is done I update the db so the player cannot act until some time has passed. If the player clicks too fast he sends multiple calls to the server and before the action state is updated in db the if conditional that checks in the db if the player can act returns true (he can do it) and it shouldn't. The info doesn't get updated fast enough.

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.

How to Share session between different clients accessing a Meteor website? Collaborative ToDos?

I am learning web development and lately Meteor has caught my fancy.
I went through the starter tutorial of creating to-dos and use save button to commit the list to database. It allows everybody who opens the website to see the same to-dos list.
I added user log in system in to-dos so that people can login and see only their own to-do list.
Now, I'm trying to extend above example, for Collaborative to-dos.
Here is a sample use case:
My boss logs-in at do.com and starts creating his to-do list. While the Boss is logged in, I also happen to open do.com from my laptop and I see a message flashing - A session is already open. Do you want to collaborate with Boss? If I say 'Yes', Boss will be notified at his screen to allow me access to his list, and on granting access, I will be able to collaborate with Boss's to-do with both of our changes in the list reflecting on each other's screen but the final save/commit button remains frozen for me (because I came later) and remains active only for Boss. So, when Boss hits the save button, the list is committed to database with his and my changes.
If Boss chooses to not allow me to contribute, I get to see my own to-do.
On the other hand, if I choose NO, I get a fresh start at my to-do list with no bearing on already open sessions elsewhere.
The scenario should work other way round too. If I am the one who has an active session at do.com and Boss happens to open his own later, he should get the message whether he wants to collaborate with me and so on.
What would be the best way to implement this in Meteor? I came across this Persistent Session package which could be the solution but I am not able to adapt it to my use-case of allowing/denying another user via message/notification. Appreciate, any help on this. I'm a complete newbie here, pls excuse of any un-necessary verbiage, I wanted to explain my question well.
Thanks in advance.
Session is not the right tool for this, you want to use the server db (Collections) to mediate this collaboration.
Given that you created todo lists specific to users, I'm going to assume you have a publication somewhat like this:
Tasks = new Mongo.Collection("tasks");
if (Meteor.isServer) {
Meteor.publish("tasks", function () {
return Tasks.find({owner: this.userId});
});
}
So the next step is to change this so you can see your own tasks, and also those belonging to any user who shares their tasks with you. This could be created like this:
Tasks = new Mongo.Collection('tasks');
CanView = new Mongo.Collection('canView');
// CanView holds docs with this schema:
// {
// user: 'DzxiSdNxEhiHMaoi6',
// taskLists: ['DzxiSdNxEhiHMaoi6', '7X97ZhPxjX6J4eNWx']
// }
if (Meteor.isServer) {
Meteor.publish('tasks', function () {
var canView = CanView.findOne({user: this.userId}).taskLists;
return Tasks.find({owner: {$in: canView}});
});
}
On the client tasks could be displayed as one single list, or segregated by the owner property.
How you add and remove ids into the CanViews tasklist list will depend on the workflow for requesting access/offering to share, etc.
The other part of the workflow you mentioned is only the Boss being able to save the changes, but still have them reactively update on both screens. This would take more work as you would need to implement a 2 step process, with two collections on the server. i.e. Boss's (task owner's) saves are committed directly to the canonical Tasks collection, and other users saves to a second TaskUpdates Collection. Both published to the clients, which then have to overlay the data from TaskUpdates over the actual Tasks in a way that is clear and meaningful.

Categories