Nodejs: How do you differentiate between users? - node.js

I am new to backend. Only way i can think of is this:
at visit if doesn't have cookie then do next step
generate unique id and then set it as cookie
then upon every request check if that id is present in database and if not go to step 1.
if it's present then fetch data under that id and respond as needed.
Now is it safe?, Is it logical. What does actually happen.
Scenario to use in:
This is meant for not logged in users. Basically, users visit my site, click something that takes time.. so user is redirected to a page with waiting gif all the while using ajax (long polling) server is requested for results. Now to differentiate between requests from multiple users i am thinking this will work. It's important because data i'm going to be sending back is going to be private from 3rd party.

You have to decide up front if you want a:
Temporary session for a given browser that will only work for that user in one specific browser and may be reset at any time
or
A longer term session associated with a particular user that they user can use any time and from any browser.
The first can be done with a server or client generated cookie that is any globally unique value. You can then use that id as a key into your database to get the user's server-side settings/data on any given request. In node.js, there are a number of session related NPM modules that will handle the generation of a sessionID for you automatically. The problem with this first method is that it relies on the preservation of a cookie value in the user's browser. Not only can cookies be temporal (they can be cleared), but they are only set in one specific browser.
If you're only planning on using it for the duration of one session, then this first method should work just fine. It is common to use a time value (e.g. Date.now()) combined with a random number for a unique id. Since no two requests can be processed in the same ms, this guarantees a unique id value. Add the random number to make it not be predictable. Other NPM session modules offer further features such as an encryption key, etc...
The second method requires some sort of identifier that the user must enter in order to know which user it is (often an email address). If you don't want other people to be able to impersonate a user by only knowing their user id, then you also need to require a password. This essentially requires a sign-up process on your site where the user ends up with a userID and password that they use to login to your site.
It is not uncommon to see the first method used for short term storage on behalf of the user. For example, a shopping cart on a site that you are not registered for.
The second method is used by all the sites that have a user login.

Related

How to restrict the route access to certain limit(say 3) for non-sign up user

I've routes that offer some features to the users. I want new users to access the routes say for 3 times after that they should be routed back to login page.
We can do it in many ways but which one would be the most robust approach?
For e.g we can save the user session in cookies but if user clear the cookies they can access the routes and that is not what I want.
Any help would be appreciated
Storing cookies on the client devices is not a safe solution. Users can delete their cookies. But it can be useful if you combine this with other methods.
You probably don't have a 100% solution as users can change every information you collect from them for unification. But you can make it as hard as possible.
Let's talk about device unification solutions.
IP: You can get the user IP, store it on your backend. And link it with user type to detect if the user has access to content or not. There are some downsides of this solution; you need to implement a system to update user access. This means another complexity at the backend; most of your users have dynamic IP addresses. They can change it, and this will cost them 10 minutes.
Cookie: As you said, they can delete them easily.
Fingerprinting: There are some unique ways to detect devices. This library is one of them. It abuses some browser features to create unique ids. It is a clientside library, and you can create an id and send it to your backend for persisting. The downside of this solution: It blocks the browser for a second or something like that. But even incognito, it creates the same id.
My way: I would combine all of them and use storage with TTL at the backend. My document would be like this:
Random generated device id at cookie: string
Fingerprint: string
IP: string
User features: bit flag value
Visit number for the feature: int
Whenever a user deletes or changes cookies, I would identify the user from IP or fingerprint. Whenever a user changed its IP, I will identify it from other unique ids I have. And also, on each change, I would update this document. When the user bought new features, I would update the bit flag value. Also, if I can't link this visit with any of the previous visits already existing in the database, I would create a new document.

Is there a way for me to "persist" data on an expressjs app?

guys!
I got an expressjs application, an app service. On one of my routers the user will be redirected to another server(e.g: monkeyserver), some data is sent to monkeyserver (a random value, a url to send the user back to my expressjs application and some other stuff). The monkeyserver will send me back that random value so I can check if we are still friends.
So the doubt here is that random value variable(e.g: me_var). What's the simplest way for me to save that me_var so when the user is sent back to my app I can check if me_var value is still the same.
It's hard to understand the exact circumstances you're describing. If you have a way to identify a given http request as belonging to a particular user (session cookie created at user login is the usual way to do this), then you can store information for a particular user in a session store that is tied to the session cookie. Then, sometime later when the user returns, you can still access that same data that corresponds to that user. A session store may be long term persistent (database) or it may be shorter term only (memory store), depending upon how you implement your own session storage.
So, for your random value that will come back to you later in an URL, you can just store the original in the session store. Then, when the user comes back, that route they come back to can check the value in the URL (presumably as a query parameter) and compare it to the value in the session store to see if they still match and you can then act accordingly.

Making a login session cookie id not theftable by regenerating itself repeatedly

To counteract login session cookie theft, sniffing etc i've been thinking about this scheme.
i already read http://jaspan.com/improved_persistent_login_cookie_best_practice and what i wish to do is something less-complicated, maybe performance-wise faster too and something that blends well with both remember me functionality and normal session'ed login.
when registration is successful add session id to user(:uid) table and generate session cookie id for example d6c89ddba79b4f68be07bd874c5ff566 and store it in user browser.
When user visits another,the same page,refreshes it; another id will be generated and the current id in the user(:uid) table, the cookie in the user browser will be updated with the new one making the old one useless || invalid.
If an observer tries to steal the cookie, be it in unprotected connection, for example non-https website it will be rendered useless at user's next visit or refresh.
But... i'm sure there's a flaw somewhere in this logic. can the observer create a sort of time warping technique or do something locally to annihilate the benefits of such a scheme?
One concern comes to mind now.. i think it will be a possible situation that an observer steals the cookie when the user is afk or idle, then the observer refreshes the current page with that cookie or visits another one. the problem is that now the user is logged out while the observer has full grip of his account and can therefore change password if it's not a system where password change is confirmed through email or inserting current password before.
is that right? in that case, how could this scheme be enforced without bringing possibly extra complexity?
Yes, this is a good way to prevent session sharing:
the server will generate a new Session ID to store in the cookie every n number of requests. The Set-Cookie header will only be sent once, so if there are two browsers logged into the same session, one of them will be using the old, invalid session
is that right? in that case, how could this scheme be enforced without bringing possibly extra complexity?
As you say, you can get the user to confirm their password whenever a high security function is invoked such as password change. You could also get the system to confirm their password to continue the session in the case that session sharing is detected (i.e. some requests have been logged using the old session ID).

Node.js user system

I'm currently working on a web application which deals with multiple users. Whilst it currently works, it relies on some real bad practises which I'll outline in a minute.
We're using MySQL as the database system, since we're updating our current application, we want to ensure everything is backwards compatible. Otherwise I'd look at MongoDB etc.
Our users are stored in a table aptly named login. This contains their username, email, hashed password etc and a field which contains a JSON encoded object of their preferences. There is no real reason for doing this over using a meta table.
So the bad practises:
We're storing the entire users login row, excluding their password (although this is an internal-only app) in a cookie. It's JSON encoded.
Once the user logs in we have a secure HTTP cookie, readable only via Node.js for their username and their password so that we can continue to keep the user logged in automatically.
We have a app.get('*') route which constantly ensures that the user has their three cookies and updates their acc cookie with new preferences. This means that every time the user switches page or accesses a new AJAX item (all under the same routes) they have an updated cookie.
Every time a user performs an action we do this to get their user id: JSON.parse(res.cookies.acc).agent_id yuck!
Now, each user is able to perform actions to certain elements on the page, this effects everyone as the application is internal and anybody can work on the data inside of it.
I know what I want to achieve and how it should be done in say PHP, but I can't figure out the most effective way in Node.js.
I've started creating a User module which would allow us to get the user who performed the action and neatly update their preferences etc. You can see this here bearing in mind that it's a WIP. The issue I'm having with the module is that it doesn't have access to the users cookies, since it's not "a part of" Express. Which explains the last bad practise.
What would be the best way to handle such a system and remain bad-practise free?
I doubt it meets all of your requirements but its worth checking out out Drywall; A website and user system for Node.js
Hopefully it (or parts of it) could be helpful to you.
http://jedireza.github.io/drywall/

Is this safe for client side code?

I'm writing a GWT application where users login and interact with their profile. I understand that each form entry needs to be validated on the server, however, I am unsure about potential security issues once the user has logged in.
Let me explain. My application (the relevant parts) works as follows:
1 - user enters email/pass
2 - this info is sent back to the server, a DB is queried, passwords are checked (which are salted and hashed)
3. if the passwords match the profile associated w/ the email, this is considered success
Now I am unsure whether or not it is safe to pass the profile ID back to the client, which would then be used to query the DB for information relevant to the user to be displayed on the profile page.
Is there a possibility for a potential user to manually provide this profile ID and load a profile that way? My concern is that somebody w/ bad intentions could, if they knew the format of the profile ID, load an arbitrary amount of information from my DB without providing credentials.
-Nick
What you are dealing with here is a session management issue. Ideally, you want a way to keep track of logged in users (using random values as the session key), know how long they have been idle, be able to extend sessions as the user is using the site, and expire sessions.
Simply passing the profile ID to the client, and relying on it to send it back for each request is not sufficient - you are correct with your concern.
You want to keep a list of sessions with expiration times in a database. Every time an action is executed that needs user permissions (which should be pretty much everything), check to see if the session is still valid, if it is, extend it by however long you want. If it is expired, kill the session completely and log the user out.
You can store your session keys in a cookie (you have to trust the client at some point), but make sure they are non-deterministic and have a very large keyspace so it cannot be brute forced to get a valid session.
Since you're logging a user in, you must be using a backend that supports sessions (PHP, .Net, JAVA, etc), as Stefan H. said. That means that you shouldn't keep any ids on your client side, since a simple id substitution might grant me full access to another user's account (depending on what functionality you expose on your client, of course).
Any server request to get sensitive info (or for any admin actions) for the logged in user should look something like getMyCreditCard(), setMyCreditCard(), etc (note that no unique ids are passed in).
Is there a possibility for a potential user to manually provide this profile ID and load a profile that way? My concern is that somebody w/ bad intentions could, if they knew the format of the profile ID, load an arbitrary amount of information from my DB without providing credentials.
Stefan H is correct that you can solve this via session management if your session keys are unguessable and unfixable.
Another way to solve it is to use crypto-primitives to prevent tampering with the ID.
For example, you can store a private key on your server and use it to sign the profile ID. On subsequent requests, your server can trust the profile ID if it passes the signature check.
Rule 1 - Avoid cooking up your own security solution and use existing tested approaches.
Rule 2 - If your server side is java then you should be thinking along the lines of jsessionid. Spring Security will give you a good starting point to manage session ids with additional security features. There will be similar existing frameworks across php too (i did not see server side language tags in the question).
Rule 3 - With GWT you come across javascript based security issues with Google Team documents and suggests XSRF and XSS security prevention steps. Reference - https://developers.google.com/web-toolkit/articles/security_for_gwt_applications

Resources