Validate http headers for authentication in every page using nuxt.js - node.js

I am trying to validate every HTTP request to the nuxt server for authorization.
In this official tutorial,
it requires me to add a validate function in every page, which seems not to work for me, as I'm seeking a way to write a middleware that validates all requests to the nuxt server.
And so, I found nuxt's middleware support, but the official document is really unfriendly, I can't understand at all.
What I'm expecting is a plugin-like module that allows me to put my middleware into nuxt.
Just like what can be achievable in Express (as following).
export default function (req, res, next)
So that I can easily validate headers per request to nuxt.
How can I achieve this? Thank you very much.

Go to your directory middleware/ and create an auth.js
The first argument is your context. Context contains alot of things like your store, app, route, redirect, and it also contains req
You can check out what context has in it: https://nuxtjs.org/api/context/
export default function ({ req, res, redirect }) {
let authenticated = false;
if(!authenticated) {
redirect("/login")
}
}
You can go now to on of your page, and add this to your export default {}
middleware: ["auth"]
Now if you try to access the page you should be redirected to login

I believe Nuxt Middleware is what you need.
In middleware/auth.js
// write any custom validation functions
export default function (context) {
context.userAgent = process.server
? context.req.headers['user-agent']
: navigator.userAgent
}
then in nuxt.config.js
// this will register the middleware functions above for every route
export default {
router: {
middleware: 'auth'
}
}

Related

Access URL query Params in an Express POST route

I have a NodeJS/Express application.
From an url endpoint titled: localhost:3000/form?someProp=someValue&somethingElse=someOtherValue
This page submits a form to another Express endpoint.
I submit to an Express POST endpoint. I know in a GET endpoint I could access the query params via req.query, but I cannot seem to do that in a POST request.
Is there a way to access the query params from the request in a POST route?
(other than splicing the header.referrer... which I may just have to do)
Here are some code snippets:
If I submit to the first route it works, if I submit to the second... it does not.
router.get('/test',
(req, res) => {
console.log(req.query); // {someProp: someValue, somethingElse: someOtherValue }
}
);
router.post('/test2',
(req, res) => {
console.log(req.query); // returns {}
}
);
So I tried to send a simple request to test it and got everything working without doing anything special (The only thing extra I have is that I'm using body-parser middleware from npm):
app.use(bodyParser.json({limit: '50mb'}));
Then I tried this simple route and got the result query params as you can see in the picture attached.
http://localhost:8080/test?test=1&what=2
Any chance you're sending the other form request from the client in a different way? try looking at the network in chrome and see if you sending what you expecting. Obviously, there is something missing here as it worked for me without doing anything special.

How to send data with redirect back in Express JS

Hello I am new to NodeJs. Currently I am working in node with Express framework.
I installed the express-back package in my project and now I want to send send back data to view from where post request fired.
Below is my code that I write:
routes.js
router.post('/register/user',Rules.UserRules.registerUser,UserController.registerUser)
UserController.js
const {check, validationResult} = require('express-validator');
registerUser = function (req, res, next) {
// Validate request parameters, queries using express-validator
const errors = validationResult(req)
console.log("==== errors ===")
console.log(errors.array())
if (!errors.isEmpty()) {
console.log("==== erorror founded ====")
return res.redirect('/signup',{errors:errors})
}else{
console.log('--- form body ----')
console.log(req.body)
}
}
module.exports = {registerUser}
When I submit my form to this route then control moves to UserController and I validations fails then I want to send it back to view without defining the redirect path I just want to send it back to view from where request received with errors. But I did not find any useful solution yet.
Is there any idea that how I can achieve this target. Suggest any useful link for nodejs beginner.
use res.send(errors) it send errors to client at this route. but if you want to redirect it to another route and then send it to client you have to create /signup route and use res.send(errors) it send errors to client. by default ``` res```` will redirect to redirected route.
router.post('/signup', (req, res)=>{
//send error or do somethings.
res.json(req.body.errors);
})
Use
app.locals.errors=errors
to make your error variable available to your template upon redirection as a general guide. Read more at http://expressjs.com/en/5x/api.html#app.locals. Remember, this will share the error variable across the application, so do not forget to apply logic that allows only the logged in user to view the error information relevant to that user.

Express JS match route without handling

Given an instance of a Express JS app or router, is it possible to match a request against the apps configured routes and receive a object that describes the route as registered with the app?
For instance, if a request for /users/1 were to be handled by the application, would it be possible for the app/router instance to programatically check if the app has a route that would satisfy this request given the URI and HTTP method?
Desirable sudo(ish) code:
const app = express();
app.use((req, res, next) => {
const handler = app.match(req);
// {
// 'method': 'GET',
// 'path': '/user/:id', <--- mainly looking for this
// 'handler': <function reference>
// }
next();
});
app.get('/user/:id', (req, res, next) => {
// fetch the user and do something with it
});
...
AFAIK there are no publicly documented Express router endpoints that provide the behavior you are describing based on its 4.x Documentation.
However, you could implement this yourself by creating a custom regular expression validator to check if the req.path string matches any defined path. The downside to this is that you would have to maintain that list separately from what is registered to Express, which might prove to be difficult to maintain.
You may be able to root through the internals of the app object to get the functionality you need, but note the instability of that approach will mean your solution could potentially be broken by non-major updates to Express.

Stop duplication of passportjs isAuthenticated code in Express route files

I am using passportjs for my authentication.
I have lots of different routes throughout the project, 95% of them require the following function:
// Middleware functions
function isAuthenticated(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/login');
}
At the moment, I am putting this function at the bottom of EVERY route file.
Is there a way to write it once, and be able to use it in all the route files?
If you add that middleware before the routes that require it, all requests will pass through it before they get forwarded to the correct route handler:
// doesn't require an authenticated request
app.use(router1);
// add the middleware just once
app.use(isAuthenticated);
// all following route(r)s require an authenticated request
app.use(router2);
app.use(router3);
...

How can a Sails controller get request history

I am developing a website using Nodejs (with Sails & Passport frameworks). I am wondering how a Sails controller get the request history of a user.
For instance, a user requests for '/', but a controller redirects the user to '/signin'. Then the user requests for '/signin' using res.redirect(). So the request history looks like
'/'
'/signin'.
Now a SignInController handles the request and at the end, it want to redirect the user back to '/'. So the controller should know the history of the user's request. I guess there should be some frameworks which can record request histories and store them using session or something. Could anyone give me some hints about this?
Let me know if I understood well but what you want to do is to redirect the user to whatever URL he was before a login, right?
To do that you can use the policies (which are executed for all requests, only on the methods you want).
What we do here is save the latest position only (Not the entire history)
In api/policies/ensureReturnToUrl:
'use strict';
module.exports = function (req, res, next) {
req.session.returnTo = req.url;
return next();
};
The configuration part look like that in config/policies.js:
'*': ['passport', 'isAuthenticated', 'ensureReturnToUrl'],
AuthController: {
'*': ['passport']
}
You will have to be careful here to put this policy in the right place only. For example, you don't want to have it on you "/signin" methods (That goes against the whole point)
Then, after a successful login, you just have to read the "returnTo" property and redirect the user: (For example in a AuthController)
if (req.session.returnTo) {
res.redirect(req.session.returnTo);
} else {
res.redirect('/');
}
Obviously this need to be adapted for your use case but the policies are definitely what you need.

Resources