I run into a problem that I don't know how to solve and I can't find anything about it. Imagine that I have the following routes in an express application:
// app.js
app.use('/users', require('./routes/users'));
// routes/users.js
router.use(accesoExterno);
router.route('/login').get(...).post(...).put(...)
...
In the databaseaccesoExterno
, there must be a type column boolean
that says if the user has privileges to access "externally", that is, if he is not connected to the network from where he launched the server .
What should I do in the middleware accesoExterno
to perform this check?
function accesoExterno(req, res, next){
//PSEUDO-CODE
db.users.get('accesoExterno')
.then( tieneAcceso => {
if(!tieneAcceso){
// Si no tiene acceso comprobar que está conectado a la misma red
}
})
}
EDIT
Things I have tried:
- req.host -> It returns the host. I can check if it is running from "localhost", which would be an option. But what if you enter through "127.0.0.1" or directly from the IP?
- req.ip -> I think this would work for me, because if I'm connected to my network, it returns my network's IP, if not, it returns my device's IP?
Any clarification to my doubts would be of great help.
The value of
req.ip
gives you the "assumed" value of the ip of the user making the request. If you join that with the own configuration of your equipment you can determine if it belongs to the same ip range as you.To determine your own configuration you can use the native os module with the function os.networkInterfaces
From now on you just have to iterate over the values and check if at least one of them matches the one on your server. The middleware function would be something like this.
In the example I have used the ip module which brings some very convenient tools for managing ip and subnets.
You can read more about this process in the Wikipedia article
https://en.wikipedia.org/wiki/Subnetwork
Note that it
req.ip
may not work if the settingtrust-proxy
is set tofalse
, and that this value can be spoofed by the user or any of the proxies in the chain.