Im trying to do login/register module in my project. This is my login function. I would like to have one function that will validate all things for me so I dont have to use so many "if" statements. I was trying to do with pure function but completely don't know how to do it. Can someone help me ?
const loginUser = async (req, res, next) => {
const { password, email } = req.body;
if (!email) {
return res.status(400).json({
message: "Error: Email cannot be blank.",
});
}
if (!password) {
return res.status(400).json({
message: "Error: Password cannot be blank.",
});
}
try {
const user = await User.findOne({ email: email });
if (!user)
return res.status(400).json({
message: "Invalid user",
});
if (!validPassword(password, user.password))
return res.status(400).json({
message: "Invalid password",
});
const { name, likedArr, _id } = user;
const token = crypto.randomBytes(32).toString("hex");
const userSession = new UserSession({ userId: _id, token });
await userSession.save();
return res.status(200).json({
message: "Valid login",
token: token,
user: {
name,
likedArr,
userId: _id,
},
});
} catch (err) {
next(err);
}
};
Abstracting my comments into an answer.
On Pure Functions:
If I understand pure functions correctly, I don't think you can have a pure function that calls an external API which may fail, since the same inputs may possibly return different results depending on the external state of the API (unless that API is guaranteed pure itself somehow). (Definition of a pure function)
On Repetition:
I genuinely think you don't have a lot of repetition here. Your code is clear and only has 4 conditionals, all for things you need to test for. You could abstract the similarities of your JSON returns into something like a template string depending on the conditions, but I think that could add clutter and opacity to your code, which isn't a good trade-off if you do it too much.
If you want an example of what I mean here:
if (!email) {
return res.status(400).json({
message: "Error: Email cannot be blank.",
});
}
if (!password) {
return res.status(400).json({
message: "Error: Password cannot be blank.",
});
}
Can become...
if (!email || !password) {
return res.status(400).json({
message: `Error: ${!email ? 'Email' : 'Password'} cannot be blank.`,
});
}
Related
I am making a user signup API, where name and email are set to be unique. When I send a JSON object which has a the same email address as an existing user, it gives an error as expected.
But there is no message in that error, which i can then use to give a more usable message.
Below is the error object that i'm getting.
{ "index": 0,
"code": 11000,
"keyPattern": {
"email": 1
},
"keyValue": {
"email": "pranatkarode#rocketmail.com"
}
}
And this is my controller module,
const User=require("../models/userModels.js");
exports.signUp=(req,res)=>{
const user=new User(req.body);
user.save((err,user)=>{
if(err){
res.send(err)
}
else{
res.json({
user
})
}
})
}
Mongoose's default error object is designed for non limited use cases. So you need to look at it and depending on what it contains add custom messages. For this specific use case of yours, you can for example do it like so:
const User = require("../models/userModels.js");
exports.signUp = async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.json({
user,
});
} catch (err) {
if (err.code === 11000 && err?.keyPattern.hasOwnProperty("email")) {
err.message = "This email is alrady used.";
} else if (err.code === 11000 && err?.keyPattern.hasOwnProperty("name")) {
err.message = "This name is alrady taken.";
}
res.send(err);
}
};
I'm using async/await syntax here to have a better looking code, yours would work as well.
The solution is quite simple, just remove the await before the await user.save and boom everything should be fine... but if problem persist then check your username and password in your .env file and make sure they are correct, also you should make sure your IP address is set to both 0.0.0.0 and your current IP in the atlas.
Before:
await user.save();
After:
user
To start off, I do want to clarify that I know how to use APi's created in NodeJS in Angular. The problem I have is a little tricky.
I have a function that verifies the email used in registering:
exports.confirmEmail = function (req, res) {
ConfirmToken.findOne({
token: req.params.token
}, function (err, token) {
if (err) {
return res.status(500).send({
message: "Internal Server Error " + err
})
}
// token is not found into database i.e. token may have expired
if (!token) {
return res.status(400).send({
message: 'Your verification link may have expired. Please click on resend for verify your Email.'
});
}
// if token is found then check valid user
else {
Account.findOne({
_id: token._accountId,
email: req.params.email
}, function (err, user) {
if (err) {
return res.status(500).send({
message: "Internal Server Error " + err
})
}
// User does not exist
if (!user) {
return res.status(401).send({
message: 'The account does not exist'
});
}
// user is already verified
else if (user.isVerified) {
return res.status(200).send('User has been already verified. Please Login');
}
// verify user
else {
// change isVerified to true
user.isVerified = true;
user.save(function (err) {
// error occur
if (err) {
return res.status(500).send({
message: err.message
});
}
// account successfully verified
else {
return res.status(200).send('Your account has been successfully verified');
}
});
}
});
}
})
}
This is the response I get when I register an account
Now my question is: is there a way to pass in html code or have it show in a custom Angular component instead of displaying as simple plain text on the web browser as such
Your service should send a isVerified status back to the client. You are sending only a string at the moment
return res.status(200).send('Your account has been successfully verified');
based on this status, let's call it, isVerified your angular app would render a isVerfiedComponent.ts or notVerifiedComponent.ts
So basically, I'm trying to separate my code that handles data (mongoose) from my express Router code, since I might want to use it elsewhere too.
The first thing I did was, I got rid of the res.json() calls, since I don't want the code to only work returning a http response. I want it to return data, so I can then return that data from my router as a http response, but still use it as regular data elsewhere.
Here is a function I wrote to get data from mongoose.
module.exports.user_login = data => {
console.log(data);
ModelUser.findOne({email: data.email}).then(user => {
if(!user){
console.log({email: 'E-mail address not found'});
return {
status: response_code.HTTP_404,
response: {email: 'E-mail address not found'}
}
}
bcrypt.compare(data.password, user.password).then(isMatch => {
if(!isMatch){
console.log({password: 'Invalid password'});
return {
status: response_code.HTTP_400,
response: {password: 'Invalid password'}
}
}
const payload = {
id: user.id,
email: user.email
};
jwt.sign(
payload,
config.PASSPORT_SECRET,
{
expiresIn: "1h"
},
(err, token) => {
console.log({
status: response_code.HTTP_200,
response: {
success: true,
token: token
}
});
return {
status: response_code.HTTP_200,
response: {
success: true,
token: token
}
}
}
);
});
});
};
When this code gets executed in my route like so:
router.post("/login", (req, res) => {
const { errors, isValid } = validateLogin(req.body);
if(!isValid) return res.status(400).json(errors);
console.log("ret", dm_user.user_login(req.body));
});
The log says the return value of user_login() is undefined, even though right before the return statement in user_login() I am logging the exact same values and they are getting logged.
Before I changed it to a log, I tried to store the return value in a variable, but obviously that remained undefined as well, and I got the error: 'Cannot read propery 'status' of undefined' when trying to use the value.
I am definitely missing something..
Well you have an small callback hell here. It might be a good idea to go with async / await and splitting up your code into smaller chunks instead of putting everyhing in 1 file.
I rewrote your user_login function:
const { generateToken } = require("./token.js");
module.exports.user_login = async data => {
let user = await ModelUser.findOne({ email: data.email });
if (!user) {
console.log({ email: "E-mail address not found" });
return {
status: response_code.HTTP_404,
response: { email: "E-mail address not found" }
};
}
let isMatch = await bcrypt.compare(data.password, user.password);
if (!isMatch) {
console.log({ password: "Invalid password" });
return {
status: response_code.HTTP_400,
response: { password: "Invalid password" }
};
}
const payload = {
id: user.id,
email: user.email
};
let response = await generateToken(
payload,
config.PASSPORT_SECRET,
response_code
);
return response;
};
I have moved your token signing method into another file and promisfied it:
module.exports.generateToken = (payload, secret, response_code) => {
return new Promise((res, rej) => {
jwt.sign(
payload,
secret,
{
expiresIn: "1h"
},
(err, token) => {
if (err) {
rej(err);
}
res({
status: response_code.HTTP_200,
response: {
success: true,
token: token
}
});
}
);
});
};
Now you need to change your router function into an async:
router.post("/login", async (req, res) => {
const { errors, isValid } = validateLogin(req.body);
if(!isValid) return res.status(400).json(errors);
let result = await dm_user.user_login(req.body);
console.log(result);
});
In addition: You get undefined because you return your value to an callback function
I also would seperate your routes from your controllers instead of writing your code inside an anonymous function
Please notice that whenever you are trying to return any value you are always present in the callback function and that is definitely not going to return any value to its intended place.
There are a couple of things you can improve about your code :
1.Donot use jwt inside your code where you are making database calls, instead move it where your routes are defined or make a separate file.
2.If you are intending to re-use the code, I would suggest you either use async-await as shown in the answer above by Ifaruki or you can use something like async.js. But the above shown approach is better.
Also always use 'error' field when you are making db calls like this:
ModelUser.findOne({email: data.email}).then((error,user) => {
I am new in node with koa and postgresql. I have a created a user login api but i'm getting 404 not found error. My queries and checks are working as i checked on console but ctx.body not working. How i can handle multiple responses with koa ctx.body? Don't know why no ctx.body is working. How we can solve this issue?
Hope you understand my issue.
router.post('/userLogin', async (ctx) => {
var email = ctx.request.body.email;
var password = ctx.request.body.password;
if (
!email ||
!password
) {
ctx.response.status = 400;
ctx.body = {
status: 'error',
message: 'Please fill all the fields'
}
} else {
await ctx.app.pool.query("SELECT * FROM users WHERE email = $1",
[`${email}`],
async (err, result) => {
if(err){
console.log(err);
throw err;
}
if (result) {
await bcrypt.compare(password, result.rows[0].password).then(function (res) {
if (res === true) {
ctx.body = {
status: 200,
message: "User login successfully",
data: result.rows[0],
};
}else{
ctx.body = {
status: 400,
message: "Incorrect password",
}
}
});
}else{
ctx.body = {
status: 400,
message: "Invalid email",
}
}
});
}
});
In regards to your 404 issue:
HTTP 404 implies that your route does not exist yet. Please make sure your router.post('/userLogin') router is actually getting registered via app.use(router.routes()).
Refering to your question in regards to using ctx.body for multiple responses:
You can set ctx.body multiple times but only the last one will be used in the response.
For example:
ctx.body = 'Hello'
ctx.body = 'World'
This example will respond with World.
You can either concatenate your values in order to have them sent as one string/object, or use streaming where you control the read-stream-buffer. Check https://stackoverflow.com/a/51616217/1380486 and https://github.com/koajs/koa/blob/master/docs/api/response.md#responsebody-1 for documentation.
Seems like error messages are wrapped in text. Say in a model validation I just want to send "exists" to the client if a record already exists.
One the server maybe I do something like:
validate: {
isEmail: true,
isUnique: function (email, done) {
console.log("checking to see if %s exists", email);
user.findOne({ where: { email: email }})
.then(function (user) {
done(new Error("exists"));
},function(err) {
console.error(err);
done(new Error('ERROR: see server log for details'));
}
);
}
}
On the client maybe I do:
feathers.service('users').create({
email: email,
password: password
})
.then(function() {
console.log("created");
})
.catch(function(error){
console.error('Error Creating User!');
console.log(error);
});
The error printed to console is:
"Error: Validation error: exists"
How to I just send the word "exists" without the extra text? Really I'd like to send back a custom object, but I can't seem to find any examples of doing this. The closest I've seen is this: https://docs.feathersjs.com/middleware/error-handling.html#featherserror-api
But I haven't figured out how to make something like this work in the validator.
Feathers does not change any error messages so the Validation error: prefix is probably added by Mongoose.
If you want to change the message or send an entirely new error object, as of feathers-hooks v1.6.0 you can use error hooks:
const errors = require('feathers-errors');
app.service('myservice').hooks({
error(hook) {
const { error } = hook;
if(error.message.indexOf('Validation error:') !== -1) {
hook.error = new errors.BadRequest('Something is wrong');
}
}
});
You can read more about error and application hooks here