NodeJS - Store value globally from request header - javascript

I need to store the value from a request header and use it in several parts of my app. Which is the best way to accomplish this?
Here is an example on how I get the value (app.js)
app.get('*', (req, res) => {
global.exampleHeader = req.headers['example-header'];
});
And then use this value whenever I want in all my app.
For the example I use the global object which solves my issue, but I'm not sure if it's the best way of doing something like this. Any other suggestions or improvement?
Thanks in advance!

res.locals
An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
source: http://expressjs.com/en/4x/api.html#res.locals

Related

Is it possible for function to have access to whole scope of wherever it gets called from

In nodejs router, I'm doing plenty of stuff with sessions. In Ruby on Rails I could have taken it out into its own class like session_helper then in route controller I'd only say something like this include sessions_helper then all of the sudden it'd have access to all data currently available in class then i could do session.renew
Right now only way I see is create a function, then pass req & res as parameter to it in router.
Is there a way to simply import the class and then start using it's methods, which requires them to have access to this scope.
In nodejs with the usual session functionality, the session for the current request will be in req.session. Since all code that operates on a request originates from the request handler that has access to the req object, you can simply pass along either req or req.session to any code that wants to operate on the session belonging to the current request. That is how things are typically done in nodejs.
It is not clear exactly what you mean by "import the class and then start using its methods). If you want to create a class that operates on a session, you can simply create some middleware such as:
app.use((req, res, next) => {
req.mySessionObject = new mySession(req.session);
next();
});
And then, req.mySessionObject will be your session object (initialized with the appropriate session for the current request) in all your requests and you can simply access req.mySessionObject anywhere and any methods you create on that object. You will still have to pass req or req.mySessionObject to any function that wants to use your session object or declare the function within the scope of your route handler and then you can directly access the req object at any time.
If this doesn't cover what you were trying to describe, then please show us a code example for what you want to be able to do.

Persist property to following middlewares in Express

My express app has some auth middleware which determines the current user from the session ID. I want to "persist" the user through to the following middlewares. I've tried attaching the user object to the res object, but this doesn't work (presumably because JS doesn't pass function arguments by reference).
I realise that something like Passport handles this specific scenario for you, but I'm interested in solving the general problem of persisting a value through to all subsequent middlewares.
The fact that I can't find any references to this on SO or elsewhere leads me to believe I'm trying to do something Fundamentally Wrong™ so please feel free to call me out. I'd love to hear alternative design approaches.
You can use something called locals
res.locals
for example in your case you can set
res.locals.id = 'something'
this value will persist throughout the request in all middlewares, until the response is sent.

With Sails.js how can I make /users/me a route that works with associations?

I have a main model Accounts, then I have a few Has Many models like Notifications and Friends
In my main.js
I'd like to be able to do things like:
socket.get('/users/me/notifications');
instead of like:
socket.get('/users/ + g_userAccountId + '/notifications');
^^ That works for right now, but it is set asynchronously so if any code loads before g_userAccountId is set it will try to use undefined instead which is bad.. Very bad..
I understand policies and all that I'm just wondering how I can make this work with the REST blueprints and what not. If I'm not clear please let me know
Is there a way to do this without setting findOne methods in each controller? Like to automatically fill in /me/ with 1
The easiest way I can imagine doing this without setting findOne methods in each controller would be to create a policy that matches the /users/me/notifications route, redirecting it to the current session's user id. You could potentially use something like the following, and update the /config/policy file.
if (session.authenticated) {
return res.redirect('/users/' + req.session.user.id + '/notifications');
}
If you wanted to do something to handle anytime the /users/me route is hit, you could modify this policy, tweak the req.url and redirect to the new one that uses the user ID, and apply it to all relevant routes in policy config file, or setup a custom middleware to handle the problem the same way.

Make Parse Data Modification Only Accessible from the Cloud

I am trying to create an app on Parse. That app uses data, but in order to make the data storage more secure, you would not like the clients to be able to run it. Instead, only the server should be able to modify data,
So far, I haven't seen any options as to how to achieve that, except by using user/role-based authentication, and that is something I'd rather avoid because it is the environment, not the user or role I would like to make the data access depend on.
Are there any ways to do that?
Turn off write access for everyone on each class, then in your Cloud Code use the master key which lets you bypass permissions.
You could use a beforeSave handler in Cloud Code...
Parse.Cloud.beforeSave('myClassName', function(req, res) {
if (req.master) {
res.success();
} else {
res.error('Cannot change this data.');
}
}
Then only requests made using the Master Key can alter this data.
In other places in Cloud Code, you can pass this option for individual requests like this:
obj.save(null, { useMasterKey: true });
Or turn it on for actions that follow:
Parse.Cloud.useMasterKey();

Understanding how to use NodeJS to create a simple backend

I have been trying to develop a rather simple server in nodejs. Basically, what I am going for is a simple API that requires authentication (simple username/password style). What I do not need is any kind of frontend functionality (templating etc.). My problem is, I can't seem to get my head around the approach of express/node.
Specifically, my questions are:
How do I wire in the authentication? Do I pass several handlers into every route that requires authentication, or is there a more elegant way to do this?
How does the Express middleware (like app.use(express.bodyParser())) work? Do they alter contents of the request or response object? Specifically, if I use the body parser (internally formidable?), where do I access the request data this is supposed to parse?
When using authentication and I have, say, credentials stored in a database with more information about the individual client associated, at what point do I extract that information? I.e., when a user logs in, do I fetch the user record on login and pass it on, or do I fetch it in every handler that requires the information?
Ultimately, do you know of an open source application that I could take a look at? I'd like to see something that has simple authentication and maybe even utilizes formidable, since uploading a file is one of my requirements.
As I mentioned earlier, I believe my problem is ultimately a difficulty with the function-oriented approach in node (also, I have rather limited experience in webservice programming). If you know a resource where I could read up on how to approach architecting a nodejs app, please don't hesitate to point me to it.
How do I wire in the authentication? Do I pass several handlers into
every route that requires authentication, or is there a more elegant
way to do this?
You should use the session middleware. Here is some pseudo code:
var http = require('http');
var app = express();
var authorize = function(req, res, next) {
if(req.session && req.session.appname && req.session.appname === true) {
// redirect to login page
return;
}
next();
}
app.use(express.session());
app.all('/admin*', authorize, function(req, res, next) {
});
How does the Express middleware (like app.use(express.bodyParser()))
work? Do they alter contents of the request or response object?
Specifically, if I use the body parser (internally formidable?), where
do I access the request data this is supposed to parse?
Every middleware have an access to the request and response object. So, yes, it modifies it. Normally attach properties to it. This means that inside your handler (which is also a middleware) you may write:
if(req.body && req.body.formsubmitted && req.body.formsubmitted === 'yes') {
var data = {
title: req.body.title,
text: req.body.text,
type: req.body.type
}
// store the data
}
When using authentication and I have, say, credentials stored in a
database with more information about the individual client associated,
at what point do I extract that information? I.e., when a user logs
in, do I fetch the user record on login and pass it on, or do I fetch
it in every handler that requires the information?
I think that you should do the things the same way as in any other server side language. Keep the state of the user (logged/not-logged) inside a session. You may also keep the user's id and fetch the data for him whatever you need. It depends of your case, but you have the ability to cache information. Because node is not like PHP for example, I mean it's not dieing.
Ultimately, do you know of an open source application that I could
take a look at? I'd like to see something that has simple
authentication and maybe even utilizes formidable, since uploading a
file is one of my requirements.
Yep. I wrote an article about really simple MVC web site with admin panel. It is available here. And the code of it is here.
A simple way to implement authentication (if you don't want to use additional modules):
var checkAuth = function(req, res, next) {
if(!req.session.user)
{
// Redirect to login form
res.redirect("/login");
}
else
{
// Proceed to member's area
next();
}
};
app.get("/member/page", checkAuth, function(req, res) {
// render view, etc
});
bodyParser parses / converts the body of a POST request into an object, which helps with getting form submission values.
The route that handles your login form submission can access username / password like this:
var username = req.body.username;
var password = req.body.password;
At this point you'd query your database to select from users where the username and password matches (you'd want to use password encryption in a production environment).
If you get a record back in the query result, set it in the session. A simple way to do this is:
req.session.user = userRecord
(Adjust for your session middleware)
If you are looking for REST, I recommend using either Restify or booster
For authentication (distinct from authorization), use standard Basic, which can be handled by express.basicAuth() just to parse it and place it on the req object. Personally, I don't like basicAuth because it returns a 401 if there is no login, whereas the process of authenticating is different than determining if authentication is necessary.
For more advanced authentication, as well as session management, use cansecurity or passport. For authorization, you either can put individual middleware in each route, use cansecurity's middlewares, or use its declarative authorization.
Disclosure: I am the author of both booster and cansecurity.
If your goal is to build a RESTful API in Node.js, my best bet would be Restify, which uses a similar aproach of routes like Express, but eliminates all the high level stuff(templating, etc.) and ads backend functionalities(ie: body parser, ip blacklist, requests per hour).
For the authentication part, I would use another library perhaps, and wire it to a particular route. There are ORM's too that can solve your database needs(mongo and mysql are well supported, both for the "noSQL" fans and the classic db aproach ones).

Categories

Resources