I am pretty new to nodejs. What i need to know is what is the right way to implement authentication in ember UI and express rest api. Express api runs on a subdomain for the application. Here is the code that i have for authentication
router
.post('/', function(req, res) {
response = {}
if (req.body.username == "") {
response.status = "error";
response.message = "Username field cannot be empty";
res.statusCode = 400;
return res.json(response);
};
if (req.body.password == "") {
response.status = "error";
response.message = "Password field cannot be empty";
res.statusCode = 400;
return res.json(response);
};
const db = req.db;
const users = db.get('users');
users.find({
username: req.body.username
}, {}, function(e, docs) {
if (docs.length != 0) {
response.status = "error";
response.message = "Same username already exists";
res.statusCode = 409;
res.json(response);
} else {
bcrypt.hash(req.body.password, 5, function(err, bcryptedPassword) {
users.insert({
username: req.body.username,
password: bcryptedPassword,
admin: false
});
res.statusCode = 200;
res.send();
});
}
});
})
.post('/authenticate', function(req, res) {
response = {}
if (req.body.username == "") {
response.status = "error";
response.message = "Username field cannot be empty";
res.statusCode = 400;
return res.json(response);
};
if (req.body.password == "") {
response.status = "error";
response.message = "Password field cannot be empty";
res.statusCode = 400;
return res.json(response);
};
const db = req.db;
const users = db.get('users');
users.find({
username: req.body.username
}, {}, function(e, docs) {
if (docs.length == 1) {
bcrypt.compare(req.body.password, docs[0].password, function(err, doesMatch) {
if (doesMatch) {
response.status = "success";
res.statusCode = 200;
var token = jwt.sign(docs[0], "test key", {
// expiresInMinutes: 1440 // expires in 24 hours
});
response.token = token;
res.json(response);
} else {
response.status = "error";
response.message = "Please check your username and password";
res.statusCode = 401;
res.json(response);
}
});
} else {
response.status = "error";
response.message = "Username not found";
res.statusCode = 404;
res.json(response);
}
});
});
Now the question is in two parts. First how can i implement a middleware kind of thing that will open authentication modal wherever the user needs to be signed up.
Secondly i am pretty sure that i am going wrong on the express side of server and if anyone can point me to a node module that provides restfull authentication, that would be much appreciated.
Aucun commentaire:
Enregistrer un commentaire