How to access user model properties after finding? - node.js

I'm trying to implement a user search function.
I have this for for finding the user. I'm using a post request and taking the search parameter from the post request. That parameter is used to search for the username. However, when I try logging the user, nothing comes up.
router.get('/register', function(req, res) {
var tester;
User.find({username : "bob"}, function(err, p){
if (err) console.log("didn't find bob");
var lolz = p.username;
console.log(p);
tester = p;
console.log(tester);
});
console.log(tester);
res.render('register', {info : "stuff", testuser : tester});
});
And when I log tester before I render, it works. However, when I access the register page, and try to do console.log(testuser.username) I get undefined. I also get undefined for testuser,username within the posted function and on the register page.
Additionally, when I attempt to log tester.username within the routing, I get undefined.
What is the issue here? Because I would like to pass all the found usernames into rendering a page. Thanks!
Thanks!

User.find passes an error and an array of matching documents to the callback, so p is not a user object, it's an array of user objects (which could be empty if no users match). So you need to access p[0] to get the user object itself.
Your second issue if your use of the tester variable is incorrect for node's asynchronous IO. Just move your res.render call up inside the User.find callback function so the control flow and scope nesting is correct.

Related

is using res.locals decrease the performance in nodejs?

i was told that using res.locals will decrease the performance of my application , and it's better to attach variables on the request.
in my case i want to attach variables that are accessible only on the server side , and i don't want it to be sent back to the user , and i also came across sending the variable using
next(value) , what is the best approach for my case??
i have this middleware that gets the id of the user from jwt
jwt.verify(
accessToken,
process.env.ACCESS_TOKEN_KEY,
function (err, payload) {
if (err)
return res.status(401).send({
status: "failure",
response: "access token is not valid",
});
id = payload.id;
}
);
res.locals.userId = id;
next();
then this middleware that gets the role of the user based on the id
const RoleId = await sequelize.models.User.findByPk(res.locals.userId);
if (RoleId === 1) {
res.locals.title = "Admin";
next();
} else {
res.locals.title = "Customer";
next();
}
res.locals.xxx will have no different performance from setting res.xxx or req.xxx. No difference at all. So, without a specific reference to whomever said one would be slower than the other that somehow has more context, that's not correct.
And, res.locals are not sent to the client. Template engines doing server-side rendering by convention will look in res.locals to find variables that the template may reference that were not explicitly passed to res.render(). This is very useful for having common data (like a user's name) that you want the template to use, but don't want to have to manually pass to every single res.render() call.
This is entirely under your control since you, on the server, control both the template and the server-side rendering. This allows you to insert things into the page which is then sent to the user, but nothing goes in the template that you don't put there. So, res.locals is not a security risk unless you somehow give an outside agent control over your template (which would be subject to all sorts of security issues beyond just res.locals.
Another advantage of res.locals is that its an independent namespace that is entirely reserved for your use. No variable you use there will conflict with any existing functionality of the http class or Express or whatever web server engine you're using. The res object, on the other hand, has all sorts of existing methods and properties that you have to make sure you don't overwrite. So, res.locals is safer in that regard as it is specifically reserved for your own use. You can put any named property in there without any risk of conflict.
Passing a value to next(value) is how you abort further routing and immediately invoke your error handler, passing value to the error handler. This is not how middleware communicates data to downstream routing or rendering.
Both your code examples look like proper use of res.locals to me. That is exactly what it's for.
On a completely separate topic, your first code example has a coding error in it. You need to put these:
res.locals.userId = id;
next();
Inside the jwt.verify() callback. jwt.verify() is asynchronous. You won't have the id value until that callback is called. It should be like this:
jwt.verify(accessToken, process.env.ACCESS_TOKEN_KEY, function(err, payload) {
if (err) {
return res.status(401).send({
status: "failure",
response: "access token is not valid",
});
}
res.locals.userId = payload.id;
next();
});

Express.js : about the behavior of next()

I'm learning to create web applications using Express.js.
In the process, we tried to implement a feature to prevent users from accessing certain pages when they are not logged in.
// teamController.redirectView : Redirect the screen according to res.locals.redirect
app.get('/user/:id/team/member', teamController.showMember, teamController.redirectView)
// The following is a middleware function written in another file(teamController.js)
showMember: (req, res, next) => {
// I want to set the redirect to the '/login' and skip the following process when no user are logging in.
if(!res.locals.loggedIn) {
res.locals.redirect = 'login'
next()
}
// access the property that is set only when the user logs in
let userID = res.locals.currentUser.userID
// Other processes...
When I accessed the URI when the user was not logged in, I was indeed taken to the login page, but I got the following error in the console.
TypeError: Cannot read property 'userID' of undefined
at // the position of 'let userID...'
Error occured: TypeError: Cannot read property 'userID' of undefined
// Abbreviated below...
Does this mean that excuting next() does not skip the following process, like 'return' does?
Or is there some fatal error that is causing this error?
Can you please help me?
I could have avoided the error by enclosing all subsequent processes in 'else', but if there is a better way, I would appreciate it if you could tell me that too.
Does this mean that executing next() does not skip the following process, like 'return' does?
Exactly. Calling next() alone doesn't stop further execution.
This is actually intentional because it allows for additional logic without making the client wait longer (especially with multiple middle-wares).
However to solve your problem, you can combine your next() and a return:
if(!res.locals.loggedIn) {
res.locals.redirect = 'login';
return next();
}
This way you don't have to warp all the code below in an else.
It's a common practice as well, as described here.
You must use return next() or the code keeps executing after you call next()

Koa-router getting parsed params before hitting route

I'm using koa2 and koa-router together with sequelize on top. I want to be able to control user access based on their roles in the database, and it's been working somewhat so far. I made my own RBAC implementation, but I'm having some trouble.
I need to quit execution BEFORE any endpoint is hit if the user doesn't have access, considering endpoints can do any action (like inserting a new item etc.). This makes perfect sense, I realize I could potentially use transactions with Sequelize, but I find that would add more overhead and deadline is closing in.
My implementation so far looks somewhat like the following:
// initialize.js
initalizeRoutes()
initializeServerMiddleware()
Server middleware is registered after routes.
// function initializeRoutes
app.router = require('koa-router')
app.router.use('*', access_control(app))
require('./routes_init')
routes_init just runs a function which recursively parses a folder and imports all middleware definitions.
// function initializeServerMiddleware
// blah blah bunch of middleware
app.server.use(app.router.routes()).use(app.router.allowedMethods())
This is just regular koa-router.
However, the issue arises in access_control.
I have one file (access_control_definitions.js) where I specify named routes, their respective sequelize model name, and what rules exists for the route. (e.g. what role, if the owner is able to access their own resource...) I calculate whether the requester owns a resource by a route param (e.g. resource ID is ctx.params.id). However, in this implementation, params don't seem to be parsed. I don't think it's right that I have to manually parse the params before koa-router does it. Is anyone able to identify a better way based on this that would solve ctx.params not being filled with the actual named parameter?
edit: I also created a GitHub issue for this, considering it seems to me like there's some funny business going on.
So if you look at router.js
layerChain = matchedLayers.reduce(function(memo, layer) {
memo.push(function(ctx, next) {
ctx.captures = layer.captures(path, ctx.captures);
ctx.params = layer.params(path, ctx.captures, ctx.params);
ctx.routerName = layer.name;
return next();
});
return memo.concat(layer.stack);
}, []);
return compose(layerChain)(ctx, next);
What it does is that for every route function that you have, it add its own capturing layer to generate the params
Now this actually does make sense because you can have two middleware for same url with different parameters
router.use('/abc/:did', (ctx, next) => {
// ctx.router available
console.log('my request came here too', ctx.params.did)
if (next)
next();
});
router.get('/abc/:id', (ctx, next) => {
console.log('my request came here', ctx.params.id)
});
Now for the first handler a parameter id makes no sense and for the second one parameter did doesn't make any sense. Which means these parameters are specific to a handler and only make sense inside the handler. That is why it makes sense to not have the params that you expect to be there. I don't think it is a bug
And since you already found the workaround
const fromRouteId = pathToRegexp(ctx._matchedRoute).exec(ctx.captures[0])
You should use the same. Or a better one might be
var lastMatch = ctx.matched[ctx.matched.length-1];
params = lastMatch.params(ctx.originalUrl, lastMatch.captures(ctx.originalUrl), {})

What to do when one route "blocks" another?

I'm using nodejs (with sailsjs), and I'm having an issue with routing, here is the case:
I have one route that handles the url '/user/?variable'. It links to
a controller action that shows a profile, depending on the variable
given; if no user is found, it returns a 404 error.
I have a second route that handles '/user/find'. It is linked to a
controller action meant for an AJAX request that returns the user's
id given the variables passed to it.
However, when I call '/user/find/' with the AJAX request, then I get the 404 error; I guess this is because it still links to the "show profile" action, and the action can't find an user named "find".
Is this conflict common among frameworks? Are there ways to solve this? I've tried switching the order in which I declare the routes, but the response is the same. I guess it would probably cause conflict too if an user signs up with username 'find', in that case, how would I handle it? Or should I just use a completely different route?
I like /user/find because the name is very straightforward, though.
Thank you.
When you declare your routes in your app.js or whatever file you file order matters.
app.get("/user/find", function (request, response) {
//do something
});
app.get("/user/:variable", function (request, response) {
//do something
});
In the above example /user/find takes precedence over /user/:variable because it is declared first. If you need to do this I would suggest playing with the order of the declarations. If you switch it to the following it should work.
app.get("/user/:variable", function (request, response) {
//do something
});
app.get("/user/find", function (request, response) {
//do something
});

node.js middleware and js encapsulation

I'm new to javascript, and jumped right into node.js. I've read a lot of theory, and began well with the practical side (I'm writing an API for a mobile app), but I have one basic problem, which has lead me to middleware. I've successfully implemented a middleware function, but I would like to know if the use I'm giving the idea of middleware is OK, and also resolve the original problem which brought me to middleware. My question is two-fold, it's as follows:
1) From what I could gather, the idea of using middleware is repeating a process before actually processing the request. I've used it for token verification, as follows:
Only one of my urls doesn't receive a token parameter, so
app.js
app.get('/settings', auth.validateToken, auth.settings);
auth.js
function validateToken(req, res, next){ //code };
In validateToken, my code checks the token, then calls next() if everything is OK, or modifies res as json to return a specific error code.
My questions regarding this are: a) Is this a correct use of middleware? b) is there a [correct] way of passing a value onto the next function? Instead of calling next only if everything is OK, is there a [correct] way of calling next either way, and knowing from inside the next function (whichever it is), if the middleware was succesful or not? If there is, would this be a proper use of middleware? This precise point brings me to my original problem, and part two of this question, which is encapsulating functions:
THIS PART WAS FIXED, SEE MY SECOND COMMENT.
2) I discovered middleware trying to simply encapsulate validateToken, and be able to call it from inside the functions that the get handlers point to, for example auth.settings.
I'm used to common, sequential programming, and not in javascript, and haven't for the life of me been able to understand how to do this, taking into account the event-based nature of node.js.
What I want to do right now is write a function which simply verifies the user and password. I have it perfectly written inside a particular handler, but was about to copy-paste it to another one, so I stopped. I want to do things the right way from scratch, and understand node.js. One of the specific problems I've been having, is that the error code I have to return when user and password don't match are different depending on the parent function, so I would need this function to be able to tell the callback function "hey, the password and user don't match", so from the parent function I can respond with the correct message.
I think what I actually want is to write an asynchronous function I can call from inside another one.
I hope I've been clear, I've been trying to solve this on my own, but I can't quite finish wrapping my head around what my actual problem is, I'm guessing it's due to my recent introduction to node.js and JS.
Thanks in advance! Jennifer.
1) There is res.locals object (http://expressjs.com/api.html#res.locals) designed to store data local to the request and to pass them from one middleware to another. After request is processed this object is disposed of. If you want to store data within the session you can use req.session.
2) If I understand your question, you want a function asynchronously passing the response to the caller. You can do it in the same way most node's functions are designed.
You define a function in this way:
function doSomething(parameters, callback) {
// ... do something
// if (errorConddition()) err = errorCode();
if (callback) callback(err, result)
}
And the caller instead of using the return value of the function passes callback to this function:
function caller(req, res, next) {
//...
doSomething(params, function(err, result) {
if (! err && result) {
// do something with the result
next();
} else {
// do something else
next();
// or even res.redirect('/error');
}
});
}
If you find yourself writing similar callback functions you should define them as function and just pass the function as parameter:
//...
doSomething(param, processIt);
function processIt(err, result) {
// ...
}
What keeps you confused, probably, is that you don't treat functions as values yet, which is a very specific to JavaScript (not counting for languages that are little used).
In validateToken, my code checks the token, then calls next() if everything is OK, or modifies res as json to return a specific error code.
a) Is this a correct use of middleware?
b) is there a [correct] way of passing a value onto the next function?
Yes that is the correct way of using middleware, although depending on the response message type and specifications you could use the built in error handling of connect. That is in this example generate a 401 status code by calling next({status:401,stack:'Unauthorized'});
The middleware system is designed to handle the request by going through a series of functions until one function replies to the request. This is why the next function only takes one argument which is error
-> if an error object is passed to the next function then it will be used to create a response and no further middleware will be processed. The manner in which error response is created is as follows
// default to 500
if (res.statusCode < 400) res.statusCode = 500;
debug('default %s', res.statusCode);
// respect err.status
if (err.status) res.statusCode = err.status;
// production gets a basic error message
var msg = 'production' == env
? http.STATUS_CODES[res.statusCode]
: err.stack || err.toString();
-> to pass values down the middleware stack modifying the request object is the best method. This ensures that all processing is bound to that specific request and since the request object goes through every middleware function it is a good way to pass information down the stack.

Resources