I want to create a login system, using Node JS and ExpressJS. The user types their credentials, then the server checks these to see if they are valid. If they are valid, the server will redirect the user the home page and send along data, including the user's credentials (for further use). This is RESTful.
const app = require("express")();
const bodyParser = require('body-parser');
app.get("/login", function(req, res)
{
res.sendFile(__dirname + "/front-end/login.html");
});
app.post("/login",function(req, res)
{
var username = req.body.username;
var password = req.body.password;
//returns whether the credentials work
var credentialsPassed = checkCredentials(username,password);
if(credentialsPassed)
{
//redirect to home-page and pass along the user's credentials for further use
}
});
I already read How do I redirect in expressjs while passing some context?. The answer sends data in the url. However, I need to send the user's credentials, so it would be insecure to pass it in the URL. The other alternative is to use EJS (or something similar), but I would have to download a pretty big module just for this 1 task.
Is there any better way?
If you don't want the data to be passed in the URL you can add it to req.users or res.locals/req.locals.Definition:
[req.locals vs. res.locals vs. res.data vs. req.data vs. app.locals in Express middleware
Also in the link you passed they said you could save that data in req.session maybe that is the best way to solve your problem
Related
Similar question (but NOT a duplicate): How do i store request-level variables in node.js?
Consider this following code:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
req.someVariable = "Hello";
res.send(req.someVariable + ' world!');
});
Where is req.someVariable stored? In a cookie? Does this apply for the user only or everyone? Also, what's the difference between these and storing them in sessions/cookies?
In addition to req being just a javascript object variable, stored in memory, do note express has a res.locals object variable that persist through the request/response cycle.
If you want to store any user information, you should be using the res.locals object so you do not accidentally overwrite other important objects.
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.
http://expressjs.com/en/5x/api.html#res.locals
app.use(function (req, res, next) {
res.locals.user = req.user
res.locals.authenticated = !req.user.anonymous
next()
})
Note: res.locals on it's own is not sent together with the response (e.g. res.send). It's only accessible in your nodejs app.
Cookies
Cookies are information bits that you want to send to the client's browser (stored in browser memory). The client can then send the cookie back to your nodejs app. These are different from req and res properties.
Cookie can store for example, an authentication token, which can be stored in the client's browser, and provided to the nodejs app on every request.
For security, you can use a httpOnly cookie which cannot be modified by browser javascript.
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.
What I want to do seems elementary; but, I am running into some blocks.
All I want to do is display pages based on a condition.
var express = require("express");
var app = express();
app.get('/', function(req, res) {
if (userIsLoggedIn()) {
res.sendFile(__dirname + '/public/index.html');
} else {
res.sendFile(__dirname + '/public/accessDenied.html');
}
});
I am looking to grab information from the browser – I want to call a function from another browserify-ed file, and use the return value to determine which page is displayed to the user.
I can't run the server from app.js because it needs to be browserify-ed since it requires Web3. And since the function relies on state, I am not sure how to access this state from the server file.
You have to post data from the browser to the server either with a form or query parameter.
For example:
web3.shh.post(object [, callback])
https://web3js.readthedocs.io/en/1.0/web3-shh.html#post
on the server site you need to extract those values and have to reply based on your posting.
How to process POST data in Node.js?
Unfortunately your use case is not clear ,but in general you might want to check out how to handle HTTP API communication.
I'm using active directory to authenticate users, so I thought I didn't need to use Passport and that all I would need to do is after the password checks out is to create a global(?) boolean with res.locals to indicate that the user has been authenticated.
I've tried something like this in a controller function:
ad.authenticate(username,password, function(err,auth) {
//some of the things I tried unsuccessfully -- should be true after logged in
res.locals.auth = auth
app.locals.auth = auth //app not defined
})
However, I've discovered that when I call a later function checking if the user is logged in as part of middleware for a diff route, res.locals.auth and app.locals.auth are either false or undefined. I've tried setting both vars in my server.js file at the beg with the code below but that didn't work either...
app.use((req, res, next) => {
app.locals.auth = false;
res.locals.auth = false;
next();
});
So my question is, what var/where should I be saving the authenticated status? Or should I just use passport instead because there's some security concern that I was unaware of? What is the point of the isMemberOf in passport setup example?
https://www.npmjs.com/package/passport-activedirectory
All I want to do is just check user credentials and basically recreate req.isAuthenticated in Passport because I couldn't figure out how to use it because of the isMemberOf.
Usually the server sends back a token containing some useful data (user or session id, expiration date) either by cookies or by JWT (json web token).
Then a client puts the token into every request to the server . The server validates expiration date and handles requests.
Cookies will be put into a request by the browser automatically. JWT should be put into a request by your client code.
I have a Node.js server. Lets say each client has his name saved on a variable. They switch page and I want each client to mantain their name on a variable.
This would be very easy with a php form, but I can't see how to do it with Node.js
If I do a form like I would do in php, I manage to send the name to the server:
app.post('/game.html', function(req, res){
var user = req.param('name');
console.log(user);
res.redirect('/game.html');
});
But it seems too complicated to then resend it again to each client it's own.
I just started with Node.js, I guess it's a concept error. Is there any easy way to pass a variable from one page in the client to another?
Thanks.
Instead of redirecting to a static file, you have to render the template ( using any engine that ExpressJS supports ):
app.post('/game.html', function(req, res){
var user = req.param('name');
console.log(user);
res.render( 'game.html', { user:user } );
});
( note that .render requires some additonal settings set on app )
Now user variable becomes available in game.html template.
You can use res.render and pass many variables, like that:
res.render('yourPage', {username:username, age:age, phone:phone});