I am trying to use passport-local-mongoose for registering my user with passport-jwt strategy for authentication on login route. I am not able to register my user and instead, getting back a MissingPasswordError on Postman.
Here is my code
const express = require('express');
const router = express.Router();
const passport = require('passport');
const User = require('../models/user');
router.post('/login', passport.authenticate('jwt', { session: false }), (req, res) => {
res.header({
status: '200',
'Content-Type': 'Application/Json',
});
res.json({
'status': 'ok',
'message': `You have successfully logged in, ${req.user.username} !`
})
});
router.post('/register', async (req, res) => {
const username = req.body.username;
try {
// here i am getting an error since password is not going through.
const user = await User.register(new User({ username }, req.body.password))
if (req.body.email) {
user.email = req.body.email;
}
const savedUser = await user.save();
console.log(savedUser);
res.json({
status: 200,
'Content-Type': 'Application/Json',
'message': `You have successfully regirstered yourself, ${savedUser.username}!`
})
} catch (err) {
err.statusCode = 500;
res.header({
status: '200',
'Content-Type': 'Application/Json',
});
res.json({ err });
}
});
module.exports = router;
I am also trying to use async/await instead of callbacks. The original syntax of register method is :-
User.register({username:'username'}, 'password', function(err, user) {
...
});
I have a few questions :-
- What's causing this problem ?
- Is my way of using
async\awaitincorrect ? What's the correct way to use `async\wait' here ? - Is it incorrect to
passport-local-mongoose'sregistermethod to register my User while I'm usingpassport-jwtstrategy for authentication ? - What's the correct way of solving this problem ?