Node.js locking to one user at a time - node.js

I am building a really simple web application with Node.js. The purpose of this application is to allow a user to edit settings of some running computations from a browser. I would like to restrict the application to allow only one user at a time, so to avoid any conflicts. If another user connects to the application while some user is already there, the second one should be notified, that the application is in use by another user.
What is a preffered way to achieve this with Node.js?

I would recommend you build a simple session object ("model") that manages the connected users and only allows one connected session at a time. Perhaps sessions could timeout after 90 seconds of inactivity.
Here's a quick sessions tutorial which shows you how to use a raw session (req.session), a redis backend, or a mongodb backend. A basic express middleware could be used to manage the sessions and set a limit of 1.
If you want something more advanced, maybe look into Passport.

Related

Handling connection loss when requesting a REST API multiple times / in a loop (client side)

I'm working on a project where I'm creating a full-stack web app for processing audit's on equipments. I use a SPA framework for the frontend and an express server with Nodejs for the backend (REST API).
In the app itself I work with sessions to log the answers of a questionary with a bunch of predefined questions (history function). Here an audit can have multiple sessions. A session can have multiple answers refering to the predefined questions (same as the previous session).
Therefore, each time the audit is opened by the user, a new session is generated in which all answers from the previous session are copied. When the session is created, many small requests are sent to the server on the client in a loop (Has to be atomic).
My question is, what is a good practice to handle connection loss while sending many small requests to the API in a loop (client side)? Because if the connection from the client to the server is aborted during session creation, inconsistent data will be generated. How do I deal with this problem to avoid inconsistencies?
One idea was, to apply business logic to the relevant request (session endpoint), where I create the session with the items internally on the server. But it is known that implementing business logic in a rest api is not good practice.
Analogous to this fact, you can take as an example order items and an order
Can someone help me with this problem or has any other ideas?
Seems you are trying to use sessions as part of your REST API and that's against RESTfulness (server functions should be stateless). You can use a JWT and make the client responsible for providing the data associated with its session (if data is small enough).

Dynamic connection for each user nodejs

Have created a web application with nodeJs, I have a situation now
consider a table with the columns
username, password, ip addresses, database name, dbusername, dbpassword etc...
The login from the web app should connect to this table and authenticate the user.
While authenticating the db detail columns are read for that user.
And after successful login the nodejs connection should use this loaded db (only for this user).
Now, Open one more instance of the app and login with different user, this time the node should use the db for this user (might be same / different).
Being a single threaded model is it possible to have dynamic connection for each user in nodeJS?
Does opening and closing connections (with different db config) work well in this case?
Thanks,
Saran
express-session comes with functionalities that manages sessions. https://github.com/expressjs/session
passport.js is a very good solution for authentication in node.js. http://passportjs.org/
There are many tutorials out there for passport.js and session management.
For example: https://scotch.io/tutorials/easy-node-authentication-setup-and-local
Also sessions have nothing to do with single-threaded model. Even if you are multiple threaded you don't keep the connection up for each user after sending them the page. Cookies are used to identify who is visiting the site. Node.js have native functions that can also launch a cluster of Node.js processes to take advantage of the multi-core systems. In that case session can still be managed even across processes by using things like redis.
About clusters: https://nodejs.org/api/cluster.html

Scaling nodejs app with pm2

I have an app that receives data from several sources in realtime using logins and passwords. After data is recieved it's stored in memory store and replaced after new data is available. Also I use sessions with mongo-db to auth user requests. Problem is I can't scale this app using pm2, since I can use only one connection to my datasource for one login/password pair.
Is there a way to use different login/password for each cluster or get cluster ID inside app?
Are memory values/sessions shared between clusters or is it separated? Thank you.
So if I understood this question, you have a node.js app, that connects to a 3rd party using HTTP or another protocol, and since you only have a single credential, you cannot connect to said 3rd party using more than one instance. To answer your question, yes it is possibly to set up your clusters to use a unique use/pw combination, the tricky part would be how to assign these credentials to each cluster (assuming you don't want to hard code it). You'd have to do this assignment when the servers start up, and perhaps use a a data store to hold these credentials and introduce some sort of locking mechanism for each credential (so that each credential is unique to a particular instance).
If I was in your shoes, however, what I would do is create a new server, whose sole job would be to get this "realtime data", and store it somewhere available to the cluster, such as redis or some persistent store. The server would then be a standalone server, just getting this data. You can also attach a RESTful API to it, so that if your other servers need to communicate with it, they can do so via HTTP, or a message queue (again, Redis would work fine there as well.
'Realtime' is vague; are you using WebSockets? If HTTP requests are being made often enough, also could be considered 'realtime'.
Possibly your problem is like something we encountered scaling SocketStream (websockets) apps, where the persistent connection requires same requests routed to the same process. (there are other network topologies / architectures which don't require this but that's another topic)
You'll need to use fork mode 1 process only and a solution to make sessions sticky e.g.:
https://www.npmjs.com/package/sticky-session
I have some example code but need to find it (over a year since deployed it)
Basically you wind up just using pm2 for 'always-on' feature; sticky-session module handles the node clusterisation stuff.
I may post example later.

Going session-less with NodeJS

I've been doing a lot of research lately and it appears to me that going stateless serverside brings benefits to both performance & scalability.
I am although trying to figure out how to achieve session-less-ness on Node.JS. It seems to me that basically all I have to do is assign a token to a logged in user, so I would have something like this in my DB:
{ user:'foo#example.com', pass:'123456', token:'long_id_here' }
so that the token can be send with every HTTP request like this:
/set/:key/:val/:token
to be checked against aforementioned DB object. Is this what it is actually meant to be a session-less web service?
If this is the right way, then I do not understand things like token expiry, and other security issues. I would like to be pointed out to NPM package of some sort?
On a side note, is it best for a token, to use a hash of the user+password, or to assign a different one at every login?
The reason to go sessionless is that most default session implementations use an in-memory store. That means that the session information is stored in memory local to that instance. Most websites these days are scaling out as traffic increases. This means they add more servers and balance the load between the servers. The problem with in-memory session stores is your user can log into Server 1, but if their next request is routed to Server 2, they don't have a session created yet and will appear to be logged off.
You don't necessarily need to go sessionless to scale out with node or any other server side language. You just need to use a session that isn't in local memory that would be accessible to all nodes. If you're using something like Express or Connect, you can easily use a session implementation like connect-redis which will enable you to have a fast session store which is accessible to all of your node instances so it doesn't matter which one is hit.

How to implement session using nodeJS TCP server with MongoDB?

I am creating a TCP based game server for iOS, it involves registration and login.
Users will be stored as a collection in MongoDB.
when login is done, I generate a unique session id - How ?
I wanted to know what all data remains with node server and what can be stored in db.
data like session tokens, or collection of sockets if I am maintaining a persistent connection etc.
Node.JS does not have any sessions by default. In fact, there is a plug-in for managing sessions with MongoDB.
It's not clear that you really need sessions however. If you're opening a direct socket with socket.io, that is a defacto session.
Node.js itself does not manage sessions for you. It simply exposes an API to underlying unix facilities for Socket communication. HTTP in it self is a stateless protocol and does not have sessions either. SSH on the other hand is a stateful protocol, but I do not think either one would be good for you.
Creating a uniuqe ID is really simple, all you need to do is hash some data about the user. Their SHA(IP address + time + username). See: http://nodejs.org/api/crypto.html
One approach a lot of applications take is to create their own protocol and send messages using that. You will have to handle a lot of cases with that. And I myself have never dealt with mobile where you have serious connectivity challenges and caching requirements that are not a big problem on desktops.
To solve these problem, founder of Scribd started a company called Parse which should make it much easier for your to do things. Have a look at their website: https://parse.com/.
If you want to do some authentication however, have a look at Everyauth, it provides a lot of that for you. You can find it here: https://github.com/bnoguchi/everyauth/.

Resources