mocha : testing a signup process with email-verification framework - express

I try to test my signup router post function which use email-verification framework,but mocha shows me the error message below :
TypeError: Cannot read property 'findOne' of null
This my code :
function that invoke the error:
nev.resendVerificationEmail(email,(err,userExist) =>{
if(err){
return res.status(404).send('Error : resending verification email failed');}
if(userExist){
res.json({message : 'An email has been sent to you , again. Please check it to verify your account'});
}else{
res.json({message : 'Your verification code has expired . Please sign up again'});
and this is the implementation of resendVerificationEmail function
var resendVerificationEmail = function(email, callback) {
var query = {};
query[options.emailFieldName] = email;
options.tempUserModel.findOne(query, function(err, tempUser) { //this the error handler I guess
if (err) {
return callback(err, null);
}
// user found (i.e. user re-requested verification email before expiration)
if (tempUser) {
// generate new user token
tempUser[options.URLFieldName] = randtoken.generate(options.URLLength);
tempUser.save(function(err) {
if (err) {
return callback(err, null);
}
sendVerificationEmail(getNestedValue(tempUser, options.emailFieldName), tempUser[options.URLFieldName], function(err) {
if (err) {
return callback(err, null);
}
return callback(null, true);
});
});
} else {
return callback(null, false);
}
});
};
and this is my spec
describe(' SignUp : /POST Test with fake client request : ', () => {
let req, res, statusCode, sendData,user;
beforeEach((done) => {
SignupModal.remove({}, (err) => {
done();
});
user = {
firstName : 'ben',
secondName : 'wissem',
username : 'wiss',
email : 'xy#zt.sq',
password : 'wissem'
};
res = {
json: function (code, data) {
statusCode = code;
sendData = data;
}
};
});
it('should send 200 code', () => {
chai.request(server)
.post('/user/signup')
.send(user)
.end((err, res) => {
res.statusCode.should.equal(200);
});
});
Can any one help me please ?!

if you want to end-to-end test email verification try EmailE2E.com, it's a free API that let's you send and receive emails from randomly generated inboxes. It's perfect for Firebase, Amazon Cognito, or other OAuth providers that use email verification codes during sign up. It also has a Javascript client you can use with Mocha.

Related

get logged in ID from jwt so that only logged in user can see particular data in nodejs

I am using nodejs, jwt and mysql.
I want the current logged in user ID soo that I can show the data respective to it.
This is my code where SQL logic is written and here I am expecting to get a current user ID.
const pool = require('../../dbconfig/dbconfig');
module.exports = {
getProfile : (callBack) => {
var sql = 'SELECT name, shopStatus, phone, shopaddress.shopNo, shopaddress.complex, shopaddress.landmark, shopaddress.street, shopaddress.area, shopaddress.city FROM shop INNER JOIN shopaddress ON shop.id = shopaddress.shop_id WHERE shop.id = ?'
var insertSql = [ /* how can i get ID here.. */ ]
pool.query(sql, insertSql, (err, results, fields) => {
if(err) {
return callBack(err)
}
return callBack(null, results)
})
}
}
this happens to be jwt middleware code
const jwt = require('jsonwebtoken')
const config = require('../../config')
module.exports = {
isAuth: (req, res, next) => {
let token = req.get("authorization");
if (token) {
// Remove Bearer from string
token = token.slice(7);
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.json({
status: 'error',
message: "Invalid Token..."
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.json({
status: 'error',
message: "Access Denied! Unauthorized User"
});
}
}
};
and this is controller
const shopService = require('./shop.service')
module.exports = {
shopProfile : (req, res) => {
shopService.getProfile((err, results) => {
if(err){
return res.status(500).json({
status : 'error',
error : err,
message : 'Database connection error'
})
}
return res.status(200).json({
status:'success',
data : results
})
})
}
}

cannot access protected route with passport-jwt

I'm not able to authenticate the secret resource, I'm calling with login token still I'm getting unauthorized in response every time.
passport.use(
new JwtStrategy(
{
jwtFromRequest: ExtractJwt.fromHeader("Authorization"),
secretOrKey: jwtSecret
},
async (payload, done) => {
try {
const user = await User.findById(payload.sub);
console.log(payload.sub);
if (!user) {
return done(null, false);
}
done(null, user);
} catch (error) {
done(error, false);
}
}
)
);
controllers/users.js :
const signToken = user => {
return jwt.sign(
{
iss: "nikname",
iat: new Date().getTime(),
sub: user._id,
exp: new Date().setTime(new Date().getDate() + 1)
},
jwtSecret
);
};
route :
router.route('/secret')
.get(passport.authenticate('jwt',{session: false}),usersController.secret);
I'm not able to figure out the problem since the error is unclear.
any help ?
Thanks a lot
after using the jwt debugger , it appeared that there was an issue with payload , although the debugger showed a verified token sign, but the 'exp' and 'iat' showed wrong dates, so I changed the signToken constant like this :
const signToken = user => {
return jwt.sign(
{
iss: "nikname",
sub: user.id,
},
jwtSecret,
{
expiresIn: '2d'
}
);
};
also after researching, it appeard that fromHeader (the extractor) is not well functionning in passport-jwt#4.0.0 so I used fromAuthHeaderWithScheme instead . Like this :
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('JWT'),
and now it is working just fine .

undefined jwt token react/express

I am implementing a JWT authentication on a login/registration system. When there is a successful login/registration I am setting a user token in localStorage.
Problem is when I check my localStorage the user key is present but the value is undefined. I think the issue might be in my axios post or in my express file but I can't quite figure it out.
// my action creator
export function login(user, history) {
return async (dispatch) => {
axios.post('/api/login', { user })
.then(res => {
dispatch({ type: AUTHENTICATED });
localStorage.setItem('user', res.data.token);
history.push('/');
})
.catch((error) => {
dispatch({
type: AUTHENTICATION_ERROR,
payload: 'Invalid email or password'
});
});
};
}
The data is reaching my api correctly. The item is being set but the value res.data.token is undefined.. Below is my express file
// login.js (/api/login)
router.post('/', function(req, res) {
var email = req.body.user.email;
var password = req.body.user.password;
// TODO: create db file and import connection
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "dbname",
port: 3307
});
connection.connect(function(err) {
if(err) {
console.log(err);
} else {
connection.query("SELECT ID, Password FROM Users WHERE Email = ?", [email], function(err, result) {
if(err) {
console.log('Could not find account');
res.send(err);
} else {
var id = result[0].ID;
bcrypt.compare(password, result[0].Password, function(err, result) {
if(result) {
console.log(id);
res.json({ id });
} else {
console.log('Incorrect password');
}
});
}
});
}
});
});
Since the res.data.token in my action creator is returning undefined does that mean the response in my express file ( res.json([id]) ) is just returning defined?
You are not sending the response properly.
res.json([id]); Its just sending the array of id. That's why res.data.token is undefined. as data does not contain an object.
Send proper object like:
res.json({id});

Using async in express

Below is my rest API endpoint /signup. The problem I'm having now is that the endpoint does not stop after validateEmail. Even after it failed email form-validation and res.send() is done, the endpoint continues. So I'm keep getting the error 'Error: Can't set headers after they are sent.'. I would like to be able to finish the endpoint inside its functions like validateEmail , checkEmailInUse, makeUser, and so on.
router.post("/signup", async (req, res, next) => {
const { email, password } = req.body;
const users = req.app.get("users");
validateEmail(res, email);
await checkEmailInUse(res, users, email);
const user = await makeUser(res, users, email, password);
res.send({ message: "POST signup request OK", user });
});
function validateEmail(res, email) {
const isEmail = emailFilter.test(email);
if (!isEmail) {
res.status(400).send({
error: {
message: "Requested email is not email type",
type: "FormatValidation",
location: "validateEmail"
}
});
return;
}
}
async function checkEmailInUse(res, users, email) {
const query = { email };
try {
const user = await users.findOne(query);
if (user) {
res.send({ message: "The email is already used" });
}
} catch (err) {
res.status(400).send({
error: {
message: "Failed to find user",
type: "DatabaseError",
location: "checkEmailInUse"
}
});
return;
}
}
The code keeps going after a failed validate because you call:
validateEmail(res, email);
and then your code just keeps going. This is normal flow of control in Javascript. Your function keeps executing lines of code until you return in the function. The same issue is true for checkEmailInUse(). If you want to sometimes send the response inside those functions and be done, then you need a return value from those functions that you can check and then use if statements to determine whether your code should do more or not.
Following your style of sending the error response inside the validation functions (which is not how I would probably structure things), you could return values from those functions and test those return values in the request handler like this:
router.post("/signup", async (req, res, next) => {
const { email, password } = req.body;
const users = req.app.get("users");
if (validateEmail(res, email)) {
if (await checkEmailInUse(res, users, email)) {
const user = await makeUser(res, users, email, password);
res.send({ message: "POST signup request OK", user });
}
}
});
function validateEmail(res, email) {
const isEmail = emailFilter.test(email);
if (!isEmail) {
res.status(400).send({
error: {
message: "Requested email is not email type",
type: "FormatValidation",
location: "validateEmail"
}
});
return false;
}
return true;
}
async function checkEmailInUse(res, users, email) {
const query = { email };
try {
const user = await users.findOne(query);
if (user) {
res.send({ message: "The email is already used" });
return false;
} else {
return true;
}
} catch (err) {
res.status(400).send({
error: {
message: "Failed to find user",
type: "DatabaseError",
location: "checkEmailInUse"
}
});
return false;
}
}
}
But, I think you might find this is simpler if you get rid of the local functions because then when you send a response, you can just directly return from the main function and be done. Here's how that could look:
router.post("/signup", async (req, res, next) => {
function err(res, message, type, location) {
res.status(400).send({error: {message, type, location}});
}
const { email, password } = req.body;
if (!emailFilter.test(email)) {
err(res, "Requested email is not email type", "FormatValidation", "validateEmail");
return;
}
const users = req.app.get("users");
try {
const user = await users.findOne({email});
if (user) {
res.send({ message: "The email is already used" });
return;
}
} catch(e) {
err(res, "Failed to find user", "DatabaseError", "checkEmailInUse");
return;
}
try {
const user = await makeUser(res, users, email, password);
res.send({ message: "POST signup request OK", user });
} catch(e) {
err(res, "Failed to make user", "DatabaseError", "makeUser");
}
}

How to redirect after http basic auth to same url

I am able to bring a username and password pop up whenever i hit the url but i am able to verify the details with the one's present in database but not redirect it to same handler. It is stucking in else loop. How to do that ? After verifying if the logged in person has the right scope then it will give you response data.
My Server.js -
const simple_validate = function (request, reply, next) {
var credentials = auth(request);
if (!credentials || credentials.name !== 'john' || credentials.pass !== 'secret') {
reply('Not authorized').code(401);
reply().header('WWW-Authenticate', 'Basic realm="example"').hold();
reply('success');
} else {
next();
reply('Access granted');
}
}
server.register(Basic, (err) => {
server.auth.strategy('simple', 'basic', { validateFunc: simple_validate });
});
This is the right way of doing it.
const validate = function (request, email, password, callback) {
// validate your email and password here
User.findUser(email,password,function(err,result){
if(err)
callback(null,false);
else
//do whatever you wanna do
});
}
server.register(require('hapi-auth-basic'), (err) => {
server.auth.strategy('simple', 'basic', {
validateFunc: validateApi
});
});