I have this node server running :
var server=http.createServer(function(request, responsehttp) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var POST = qs.parse(body);
processquery(POST, request, responsehttp);
});
} else {
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
console.log(query);
processquery(query, request, responsehttp);
}
});
I want to add login form for this server .so when user is authenticated then it will show .
function processquery(query, request, responsehttp){
var returnResult = function (data){
responsehttp.end(JSON.stringify(data));
};
if (!query.command) {
fileprocess(request, responsehttp);
}
responsehttp.writeHead(200, {"Content-Type": "application/json"});
switch(query.command) {
case 'logout':
logout(query, returnResult);
break;
case 'login':
login(query, returnResult);
break;
}
}
in process query function returning the files to client if any command is not given ,
so i can send the login command from client to server , but what server should do when it recieve the login command with username password , how it should hand the login request and return the login sucess or failure, for writing this part i need help .
what i tried .
function login(request, callback) {
if(request.username==users[request.username] && request.password==users[request.username].password) {
users[request.username].auth=true;
var data = {result:'success','message':'login successful'};
callback(data);
} else {
var data = {result:'error','message':'login incorrect'};
callback(data);
}
}
Please suggest how can i add session in this i tried adding , request variable in login function and tried setting request.session variable it says request.session is undefined .
Please suggest how can i write this login module which can maintain login authentication properly for every user .
Here’s how I do it with Express.js:
1) Check if the user is authenticated: I have a middleware function named CheckAuth which I use on every route that needs the user to be authenticated:
function checkAuth(req, res, next) {
if (!req.session.user_id) {
res.send('You are not authorized to view this page');
} else {
next();
}
}
I use this function in my routes like this:
app.get('/my_secret_page', checkAuth, function (req, res) {
res.send('if you are viewing this page it means you are logged in');
});
2) The login route:
app.post('/login', function (req, res) {
var post = req.body;
if (post.user === 'john' && post.password === 'johnspassword') {
req.session.user_id = johns_user_id_here;
res.redirect('/my_secret_page');
} else {
res.send('Bad user/pass');
}
});
3) The logout route:
app.get('/logout', function (req, res) {
delete req.session.user_id;
res.redirect('/login');
});
If you want to learn more about Express.js check their site here: expressjs.com/en/guide/routing.html
If there’s need for more complex stuff, checkout everyauth (it has a lot of auth methods available, for facebook, twitter etc; good tutorial on it here).
Actually this is not really the answer of the question, but this is a better way to do it.
I suggest you to use connect/express as http server, since they save you a lot of time. You obviously don’t want to reinvent the wheel. In your case session management is much easier with connect/express.
Beside that for authentication I suggest you to use everyauth. Which supports a lot of authentication strategies. Awesome for rapid development.
All this can be easily down with some copy pasting from their documentation!
To add to Farid’s pseudo-answer,
Consider using Passport.js over everyauth.
The answers to this question provide some insight to the differences.
There are plenty of benefits to offloading your user authentication to Google, Facebook or another website. If your application’s requirements are such that you could use Passport as your sole authentication provider or alongside traditional login, it can make the experience easier for your users.
@alessioalex answer is a perfect demo for fresh node user. But anyway, it’s hard to write checkAuth middleware into all routes except login, so it’s better to move the checkAuth from every route to one entry with app.use. For example:
function checkAuth(req, res, next) {
// if logined or it's login request, then go next route
if (isLogin || (req.path === '/login' && req.method === 'POST')) {
next()
} else {
res.send('Not logged in yet.')
}
}
app.use('/', checkAuth)