Nestjs request scope data during authentication - nestjs

What is an equivalent to res.locals from express in nest.js?
In other words what are the ways I can pass data about user between middlewares and to the controller?

In the nestjs it is common to assigned that data to the request because as you said using response directly will break the pipeline of interceptors and middlewares.
From controllers page:
From interceptors page:

Related

How to use `fastapi_another_jwt_auth` in the middleware instead of via dependency injection in FastAPI?

I have a FastAPI project which uses fastapi_another_jwt_auth as a way of authenticating users. I'd intend to implement it in most of my endpoints except for a few whitelisted ones, but I find it hard to unit test endpoints that require authentication so I'm thinking of implementing it in a middleware with a simple if-else check for whitelisted endpoints. This way, I just need to disable the middleware to run unit tests and testing for authentication becomes trivial since we're just testing against a whitelist.
The API for fastapi_another_jwt_auth seems designed around the concept of Dependency Injection for FastAPI. Is there a way to use the same library in the middleware?
I looked at the code for fastapi_another_jwt_auth. Apparently, when injecting, the framework runs the AuthJWT constructor, which takes in the Request and Response object. This is shown below.
class AuthJWT(AuthConfig):
def __init__(self,req: Request = None, res: Response = None):
...
Once it is successfully initialised, we can then use the .jwt_required() method.
So the way to implement it in the middleware is:
#app.middleware("http")
async def middleware_callback(req, call_next):
if not whitelisted: # this is pseudocode
auth = AuthJWT(req)
auth.jwt_required() # throws error when user is not authenticated
# rest of the logic
...
This way, I can manage all authentication at the middleware level and I don't have to inject the AuthJWT object into my view functions.

How to get HttpRequestContext when I am using Self Hosted Owin?

How to get HttpRequestContext when I am using Self Hosted Owin?
My class is being called by ApplicationInsights and not by a controller, so I don't have access to any context.
Is there any way similar to what we do using HttpContext?
There is no static class to retrieve the request when using OWIN self hosted, because you are essentially in a console application, which is unaware that you wrote code that receives http requests.
Owin is a pipeline. The request is passed from middleware to middleware by calling the next middleware with a context parameter containing the request (and the response for that matter).
Each middleware registered in the pipeline can inspect the request on the way in, in their registration order, and call the next middleware before processing the response.
It is very easy to write your own middleware, register it in the pipeline, and inspect the request object for each request coming in.
Take a look here if you need a quick code example : http://benfoster.io/blog/how-to-write-owin-middleware-in-5-different-steps

How to pass multiple parameters to the express js server api in a mean.js application?

The default serverside router for a mean.js application for a single parameter request is like this :
app.route('/articles/:articleId')
.get(articles.read)
.put(users.requiresLogin, articles.hasAuthorization, articles.update)
.delete(users.requiresLogin, articles.hasAuthorization, articles.delete);
// Finish by binding the article middleware
app.param('articleId', articles.articleByID);
How do I parse multiple parameters in the middleware for the request say :
app.route('/articles/:articleId/:lineId')
How do I define the middleware for this ?
I have tried doing :
app.param(['articleId','pageId'],articles.articleByID);
but it fails. Even the express.js API says that an array of arguments can be passed but it's vague on it's implementation.
I even tried accessing req.param in the middleware definition but it returned undefined.
Somebody please guide as to how to implement it?

How to use a callback array as the handler for a Sails.js route?

When using Express, it is possible to attach a callback array to a route like this:
app.get('/path', thisIsAnArrayOfFunctions);
And then, when making a request to http://route_to_server/path each function inside thisIsAnArrayOfFunctions is called.
Exactly how does that routing behaviour works in express? is it just an iteration through thisIsAnArrayOfFunctions, passing the arguments req, res and next?
Is it possible to achieve a simple implementation in Sails for this?
I know it works if I attach the routing as an express middleware, but I want to know if there's a solution using the Sails' (version 0.9.8) controller structure.
Thanks in advance.
The Sails-y way of chaining functions to a route is by using policies. The idea is that your controller code should be the last stop in handling your route. Anything that might modify the response (like a login check, or something that could change the params) should be implemented as a policy, which is middleware that can call next or send a response directly. Policies are mapped to controller actions, and multiple policies can be applied to a single action (or to all actions in a controller).
Docs for policies are here.

Express.js: Is this a RESTful interface?

I am pretty new to node and express.js and I'm new to the concept of REST applications as well. I want to code a typical CRUD app, some sort of diary. Hence, I have a collection of entries, can view a single entry and can add, edit and delete an entry.
I'm not quite getting yet, how URi's have to be set up to represent a REST conform API. I would create something like this in my app.js:
// GET REQUEST ROUTING
app.get('/', diary_router.home);
app.get('/entries/', diary_router.listEntries);
app.get('/entries/:id', diary_router.getSingleEntry);
// POST REQUEST ROUTING
app.post('/entries/', diary_router.addEntry);
// PUT REQUEST ROUTING
app.put('/entries/', diary_router.updateEntry);
// DELETE REQUEST ROUTING
app.delete('/entries/', diary_router.deleteEntry);
Could that be called a REST conform interface? Should I rather add the respective action in the routes, such as this and does the item-ID need to be shown in the URL for PUT and DELETE actions, too?:
// GET REQUEST ROUTING
app.get('/', diary_router.home);
app.get('/entries/', diary_router.listEntries);
app.get('/entries/show/:id', diary_router.getSingleEntry);
// POST REQUEST ROUTING
app.post('/entries/add/', diary_router.addEntry);
// PUT REQUEST ROUTING
app.put('/entries/update/:id', diary_router.updateEntry);
// DELETE REQUEST ROUTING
app.delete('/entries/delete/:id', diary_router.deleteEntry);
What would be best practice here? Any help is much appreciated.
B.
In the loose definition of REST that we seem to have converged on in web-land, the first option seems to fit best.
Edit: and yes, you should specify the ID in the PUT and DELETE routes.
HTTP is a really cool protocol for applying verbs (request methods) to nouns (URLs). In that spirit, it's probably best to use the request method to differentiate what you want to do to the resource that you're requesting.
Note: you can use the methodOverride middleware in express if you're worried about browsers not being able to use arbitrary HTTP methods.
The way the methodOverride middleware works is that you use an <input type="hidden" name="_method" value="PUT"> or similar to specify the method, despite it just being a regular POST request, and the methodOverride middleware will set the method property on the request that you get in your express application. This way, you can signal the intended request method without the client actually having to support that method.

Resources