so I have rest api where i store user data in mongoDB, I want to add basic auth to my api but I'm stuck, I want to check if user is authorised on some paths, for example on /update, if user is auth perfom request, if not send that user is not authorized
my code where I store user is db
const addUser = async (req, res) => {
const checknick = await User.find({ nickname: req.body.nickname }) //checks if user exists with nickname
if (checknick.length !== 0) {
return res.send({
message: 'user already exists, please use another nickname',
})
}
const secretInfo = await hash(req.body.password).catch((err) =>
res.send('password is required!')
)
const user = new User({
name: req.body.name,
surname: req.body.surname,
nickname: req.body.nickname,
password: secretInfo.password,
salt: secretInfo.salt,
})
user.save((err, result) => {
if (err) {
return res.send(err)
}
res.send('user added sucesessfully')
})
}
and where I verify user
const verify = async (req, res) => {
const user = await User.findOne({ nickname: req.body.nickname })
if (!user) {
return
}
const { password } = await hash(req.body.password, user.salt).catch((err) =>
res.send('password is required')
)
const verifiedUser = await User.findOne({
nickname: req.body.nickname,
password: password,
})
if (!verifiedUser) {
return false
}
return true
}
and finally login logic
const login = async (req, res) => {
const access = await verify(req, res)
// console.log(req.headers)
if (access) {
res.send('logged in')
console.log(req.headers)
return
}
return res.status(401).send('failed to login')
}
everything works but I want to use authorizatuon header to send user and password information
This is how to restrict a route add this middleware function before the
route you want to restrict like this:
app.post("/update", restrictTo("admin"));
Every user must have a role to authorize. here I am handling error with a global error handler but you can handle error another way:
exports.restrictTo = (...roles) => {
return (req, res, next) => {
if (!roles.includes(req.user.role))
return next(
new AppError('You dont have permission to do this action', 403)
);
next();
};
};
Related
I am trying to create user login and sign up in NodeJS with mongoDB, but in login module i am getting this error -
existingUser = await User.findOne({email: email});
^^^^^
SyntaxError: await is only valid in async functions and the top level
bodies of modules.
Here is my code of "user-controller.js" file code.
const User = require('../model/User');
const bcrypt = require('bcryptjs');
// next is used to move to the next middleware task
const signup = async (req, res, next) => {
const { name, email, password } = req.body;
let existingUser;
try {
existingUser = await User.findOne({ email: email });
} catch (err) {
console.log(err);
}
if (existingUser) {
return res.status(400).jason({ message: 'User already exists! Login Instead' })
}
const hashedPassword = bcrypt.hashSync(password);
const user = new User({
name,
email,
password: hashedPassword,
});
try {
await user.save();
} catch (err) {
console.log(err);
}
return res.status(201).json({ message: user })
};
const login = (req, res, next) => {
const { email, password } = req.body;
let existingUser;
try {
existingUser = await User.findOne({ email: email });
} catch (err) {
return new Error(err);
}
if (!existingUser) {
return res.status(400).json({ message: "User not found. Signup Please" })
}
const isPasswordCorrect = bcrypt.compareSync(password, existingUser.password);
if (!isPasswordCorrect) {
return res.status(400).json({ message: "Invalid Email / Password" })
}
return res.status(200).json({ message: "Successfully logged in" })
}
exports.signup = signup;
exports.login = login;
How to resolve it?
We can only use await inside an async function, in your case
const login = async (req, res, next) => {
// We can use await here
}
Instead of try catch we can do something like this
try {
User.findOne({ email: email }).then((response)=>{
//do something
});
} catch (err) {
//do something
}
In the users table, I have two collections, one of which is admin and the other which is not.
Now I only want admin user to post data.
Here is the post request:
router.post("/bus/add", auth, async (req, res) => {
const bus = new Bus(req.body);
const user = await User.find({ admin: true });
try {
if (user) {
await bus.save();
res.status(201).send(bus);
} else {
return res.status(401).send("You are not allowed to perform this action");
}
} catch (e) {
res.status(500).json({
message: "Please enter the valid data",
});
}
});
I'm using JWT to determine whether or not the user is an admin. I've set one of the users' admin roles to 'true' in the user schema.
Authentication middleware:
const authentication = async (req, res, next) => {
try {
const token = req.header("Authorization").replace("Bearer ", "");
const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY);
const user = await User.findOne({ _id: decoded._id, "tokens.token": token });
if (!user) {
throw new error();
}
req.token = token
req.user = user
next();
} catch (e) {
res.status(401).send(e);
}
};
However, even non-admin users can post data, which is then saved to the database.
I want to restrict this.
I'm not sure how I can prevent non-admin users from posting data.
You need to check if the user is admin in the Auth middleware.
const authentication = async (req, res, next) => {
try {
const token = req.header('Authorization').replace('Bearer ', '');
const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY);
const user = await User.findOne({
_id: decoded._id,
'tokens.token': token,
admin: true
});
if (!user) {
throw new error();
}
req.token = token;
req.user = user;
next();
} catch (e) {
res.status(401).send(e);
}
};
And remove the line const user = await User.find({ admin: true }); and related if check in the route.
router.post("/bus/add", auth, async (req, res) => {
const bus = new Bus(req.body);
try {
await bus.save();
res.status(201).send(bus);
} catch (e) {
res.status(500).json({
message: "Please enter the valid data",
});
}
});
not really sure if my title is correct but my problem is that I have this reset password token checker in my api that seems to get affected by another api that finds a specific user, this api has user validation.
Here is what they look like:
//get specific user
router.get('/:id', validateToken, async (req, res) => {
const id = req.params.id
const user = await User.findByPk(id);
res.json(user);
});
//reset-password token check
router.get('/reset-pass', async (req, res) => {
await User.findOne({
where: {
resetPasswordToken: req.body.resetPasswordToken,
resetPasswordExpires: {
[Op.gt]: Date.now()
}
}
}).then(user => {
if(!user) {
res.status(401).json({ error: 'Password reset link is invalid or has expired.'})
} else {
res.status(200).send({
username: user.username,
message: 'Password reset link Ok!'
});
}
});
});
then here is the validateToken
const validateToken = (req, res, next) => {
const accessToken = req.cookies['access-token'];
if (!accessToken)
return res.status(401).json({error: 'User not authenticated!'});
try {
const validToken = verify(accessToken, JWT_SECRET)
req.user = validToken;
if(validToken) {
req.authenticated = true;
return next();
}
} catch(err) {
res.clearCookie('access-token')
return res.status(400).json({error: err}).redirect('/');
}
};
when I comment out the get specific user api the reset password token check works. If I remove validateToken it returns null instead of giving me the username and message.
One of the things I notice is the route param "/:id", that means that literally everything would be processed by get specific user because all routes start with "/", only use params in routes with a prefix like "/user/:id" that way only the routes that starts with "/user" will execute that code.
Change your code to:
//get specific user
router.get('/user/:id', validateToken, async (req, res) => {
const id = req.params.id
const user = await User.findByPk(id);
res.json(user);
});
I try to sign up, i submit the form then it logs me undefined, and it doesn't save the user into the database, even the code from the tutorial works perfectly.
Here's my code
exports.postSignup = (req, res, next) => {
const email = req.body.email;
const password = req.body.password;
const confirmPassword = req.body.confirmPassword;
User.findOne({ email: email })
.then(userDoc => {
if (userDoc) {
return res.redirect('/signup');
}
const user = new User({
email: email,
password: password,
cart: { items: [] }
});
return user.save();
})
.then(result => {
res.redirect('/login');
})
.catch(err => {
console.log(err);
});
};
I have to mention that the user model is correct.
Im not sure, but in my own code I dont save an object within the return line.
Maybe try this
exports.postSignup = (req, res, next) => {
const email = req.body.email;
const password = req.body.password;
const confirmPassword = req.body.confirmPassword;
User.findOne({ email: email })
.then(userDoc => {
if (userDoc) {
return res.redirect('/signup');
}
const user = new User({
email: email,
password: password,
cart: { items: [] }
});
try{
user.save();
}catch(err){
res.send(err);
}
return user; //only if you want to return a user ofc
})
Other things that maybe going on:
Is your ip whitelisted?
Did you include the connection string?
Do you return a jason object? then make sure to use a parser in your middleware.
I am trying to set up Passport with Express and MongoDB. At the moment I am able to register users in the database. But whenever I try to login, I get an error saying that data and hash arguments are required. Right now I have my Server.js file like this
const mongoose = require('mongoose');
const User = require('./models/users')
const initializePassport = require('./passport-config')
initializePassport(
passport,
email => User.find({email: email}),
id => User.find({id: id})
)
app.post('/register', checkNotAuthenticated, async (req, res) => {
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
const newUser = new User({
id: Date.now().toString(),
name: req.body.name,
email: req.body.email,
password: hashedPassword
})
res.redirect('/login')
console.log(newUser)
} catch {
res.redirect('/register')
}
And my Passport-Config.js file like this `
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt');
const User = require('./models/users')
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, password, done) => {
const user = getUserByEmail(email)
if (user === null) {
return done(null, false, { message: 'No user with that email' })
}
try {
if (await bcrypt.compare(password, user.password)) {
return done(null, user)
} else {
return done(null, false, { message: 'Password incorrect' })
}
} catch (e) {
return done(e)
}
}
passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => {
return done(null, User.findById({user: id}))
})
}
`
I've done some investigation using console.log() statements (not proud of it) but I think I've managed to find out the issue. If we add in the the first console log statement here:
app.post('/register', checkNotAuthenticated, async (req, res) => {
try {
console.log("BCRYPT COMPARE RUNS HERE")
const hashedPassword = await bcrypt.hash(req.body.password, 10)
const newUser = new User({
id: Date.now().toString(),
name: req.body.name,
email: req.body.email,
password: hashedPassword
})
res.redirect('/login')
console.log(newUser)
} catch {
res.redirect('/register')
}
and the second one here:
const initializePassport = require('./passport-config')
initializePassport(
passport,
email => User.find({email: email}).then((result) => { console.log("USER DATA EXTRACTED HERE") }).catch((err) => { console.log(err) }),
id => User.find({id: id})
)
The next time you click on login, you should see an output like:
Listening on port 3000
BCRYPT COMPARE HAPPENING
Error: data and hash arguments required
...
...
...
USER DATA EXTRACTED HERE
Notice that bcrypt.compare is being run before we are actually able to grab the user information from the DB? This means that all the arguments into that function are null, which is what is returning that error. Now, I'm no JS expert, but this can be fixed with an await statement added here:
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, password, done) => {
const user = await getUserByEmail(email)
if (user === null) {
return done(null, false, { message: 'No user with that email' })
}
Which makes sure that the user info is queried from the DB before moving along in the script.