I am trying to implement 2fa using the otplib package and it's working fine on the local machine but not on the live server.
Can somebody help me?
on live, I am getting an invalid 2FA.
Here is the code:
exports.enableTwoFactorAuthentication = async (req, res) => {
try {
let data = req.body;
console.log("data: ", data)
const { userId, one_time_password } = data;
const user = await CRMUser.findById(userId);
const { tfa_auth_secret_key } = user;
console.log('user', tfa_auth_secret_key, user)
console.log("authenticator.check(one_time_password, tfa_auth_secret_key): ",authenticator.check(one_time_password, tfa_auth_secret_key))
if (!one_time_password || !authenticator.check(one_time_password, tfa_auth_secret_key)) {
return res.status(200).send({ success: false, message: 'Invalid 2FA Code.'});
}
else {
user.tfa_auth_status = true;
await user.save();
return res.status(200).json({ success: true, message: '2FA enabled successfully.', tfa_auth_status: true, secretKey: user.tfa_auth_secret_key, qrImage: user.tfa_auth_qr_image });
}
} catch (error) {
return res.status(500).json({ success: false, message: error.message })
}
};
Related
Hello guys I have a problem trying to get my user session with passport on reactjs. I have no problem to get on post man , I cannot fetch the data with a Get method on react js, im getting undefined:(.
I configurated my cors and everything and still no data :(.
This is my fetch
const [user, setUser] = useState(null);
useEffect(() => {
const getUser = async () => {
try {
const response = await axios.get("http://localhost:8080/login/success");
const data = await response.json();
setUser(data);
} catch (error) {
throw new Error(`error fetching data ${error}`);
}
};
getUser();
}, []);
and this is my end point and passport js config.
function checkAuthentication(req, res, next) {
if (req.isAuthenticated()) next();
else {
res.status(401).json({
message: "Failure",
});
}
}
router.get("/login/success", checkAuthentication, (req, res) => {
if (req.user) {
res.status(200).json({
success: true,
message: "success user",
user: req.user,
});
console.log(req.user);
} else {
req.status(404).json({
success: false,
message: "No user",
})
}
});
passport.use(
"login",
new LocalStrategy(async (username, password, done) => {
try {
const user = await User.findOne({ username: username });
if (!user) {
return done(null, false, { message: "Incorrect username" });
}
const isMatch = await user.isValidPassword(password);
if (!isMatch) {
return done(null, false, { message: "Incorrect password" });
} else {
return done(null, user, { message: "Logged in successfully" });
}
} catch (error) {
console.log(error);
}
})
);
const login = (req, res) => {
// console.log(req.body);
// let email = req.body.email.toLowerCase();
sequelize.models.User.findOne({
where: {
email: req.body.email,
},
})
.then(async (user) => {
if (!user) {
// console.log(" email not found is true");
return res.status(401).json({
success: false,
message: " Authentication failed, Wrong Credentials",
});
}
if (user.isActive == false) {
// console.log("user is not activated", user.isActive);
return res.status(400).json({
success: false,
message: "account is not activated",
});
}
console.log("test entry");
await user.comparePassword(req.body.password, async (err, isMatch) => {
console.log(req.body.password);
if (isMatch && !err) {
console.log("user crap");
// role_id: user.role_id,
const payload = {
user_id: user.user_id,
};
const options = {
expiresIn: "10day",
};
const token = await jwt.sign(payload, process.env.SECRET, options);
console.log("sssssss", payload);
if (user.twoFactorAuth == false) {
return res.json({
success: true,
token,
});
} else {
// let mobile = user.phone;
await twoFactorAuth(user); // we call the 2fa that will send a otp to the users cellphone
// console.log("after cb");
}
} else {
return res.json({
success: false,
msg: "Authentication failed.",
});
}
});
// console.log("user crap", user.user_id);
})
.catch((error) => {
return res.status(400).send(error);
});
};
const twoFactorAuth = async (user) => {
var data = qs.stringify({
sender: "hehe",
mobile: user.phone,
channel: "sms",
});
var config = {
method: "POST",
url: "https://blablabla",
headers: {
Authorization: "Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
},
data: data,
};
axios(config)
.then( async function (response) {
console.log(JSON.stringify(response.data));
// await verifyTwoFactorAuth (realToken)
})
.catch(function (error) {
console.log(error);
});
};
const verifyTwoFactorAuth = async(req, res) => {
//console.log("tet",req);
let otpcode = req.body.otpcode;
let mobile = req.body.mobile;
var data = qs.stringify({ mobile: mobile, code: otpcode });
var config = {
method: "POST",
url: "https://blablabla",
headers: {
Authorization: "Bearer xxxxxxxxxxxxxxxxxxxxxxxx",
},
data: data,
};
axios(config)
.then(async function (response) {
console.log(JSON.stringify(response.data));
if (response.data.code == 63 || response.data.status == 200) {
return res.json({
success: true,
token,
});
} else if (response.data.code == 21 || response.data.status == 422) {
return res.status(400).json({
success: false,
message: "wrong code, check your sms again",
});
}
})
.catch(function (error) {
console.log(error);
});
};
Hello, I am looking for a structure solution to how I should implement what I want.
Scenario: user try to login, system checks for username and passoword and generates the TOKEN, system finds that 2fa is active in users settings, system sends OTP to users cellphone.
Now my struggle begins, I am not sure what to do next, I thought about storing the token in users fields as tempToken then i look for the user via users mobile and extract the token that way, but I dont believe that this is best practice.
Any ideas of how to tackle this would be appreciated ! thank you
While calling the service layer from the controller, the response is not waiting for the result in the controller.
So, I am not getting correct response (return value) from the service layer.
controller =>
const { serviceCreateData } = require("../services/data.servises");
module.exports.createData = async (req, res) => {
try {
const result = await serviceCreateData(req.body);
if (result) {
res.status(result.status).json({ message: result.msg });
}
} catch (error) {
res.status(500).json({ message: "Server is not responding!!" });
}
};
Service layer
/** #format */
const dataModel = require("../models/data.model");
module.exports.serviceCreateData = async (insertedData) => {
const { name, email, username, phone, address } = insertedData;
try {
dataModel.findOne({ email }).exec(async (error, user) => {
if (user) {
return { success: false, status: 400, msg: "Data already exist!!" };
} else {
const _data = new dataModel({
name,
email,
username,
phone,
address,
});
await _data.save((error, data) => {
if (error) {
return {
success: false,
status: 400,
msg: "Something went wrong!!",
};
}
if (data) {
return {
success: true,
status: 201,
body: "Data inserted successfully!!",
};
}
});
}
});
} catch (error) {
return { success: false, status: 400, msg: "Something went wrong!!" };
}
};
I need to return the value from the services layer to controller, so that I can send it to the client.
Right now I am getting error responses from the controller only.
All the help is appreciated.
I am new to async/await so I have an exercise like below code, I have converted this code to async/await many times and still no success. Please help me. Thanks very much!
My code is as follows:
exports.register = (req, res) => {
const user = req.body;
try {
// Validate the registration form
validateRegisterForm(user)
.then((response) => {
// If response is true, hash the password
if (response) {
Md5Password(user.password)
.then(async (hash) => {
const { name, email } = user;
const newUser = new User({
name,
password: hash,
});
// Save the user
const savedUser = await newUser.save();
res.status(200).json(savedUser);
})
.catch((error) => {
res.status(500).json({
message: error.message,
err: "500: Internal Server Error",
});
});
}
// But if response is false, show the error message
else {
res.status(401).json({
message: errorMessage(),
error: "401: Unauthorized",
});
}
})
.catch((error) => {
res.status(500).json({
message: error.message,
err: "500: Internal Server Error",
});
});
} catch (error) {
res.status(500).json({
error: error.message,
message: "registration failed",
e: "500: Internal Server Error",
});
}
};
Please help me, thanks a lot!
Not sure exactly what you're trying to achieve, but here's a version of your code with async/await:
exports.register = async (req, res) => {
const user = req.body;
try {
// Validate the registration form
const response = await validateRegisterForm(user);
// If response is true, hash the password
if (response) {
const hash = await Md5Password(user.password);
const { name, email } = user;
const newUser = new User({
name,
password: hash,
});
// Save the user
const savedUser = await newUser.save();
res.status(200).json(savedUser);
} else {
res.status(401).json({
message: errorMessage(),
error: "401: Unauthorized"
});
}
} catch (e) {
res.status(500).json({
message: e.message,
err: "500: Internal Server Error"
});
}
}
How can i used db.findAndUpdate table user and change my balance from previous amount to newer?
i have try to get balance and the result it show nothing, now i'm confuse to write in findAndUpdate. here's my code:
api:
app.post('/api/account/transfer', (req, res, next) => {
const { body } = req;
const {
sender,
receiver,
amount,
user,
balance,
} = body;
if (!sender) {
return res.send({
success: false,
message: 'Error: Sender cannot be blank!'
});
}
if (!receiver) {
return res.send({
success: false,
message: 'Error: Receiver cannot be blank!'
});
}
if (!amount) {
return res.send({
success: false,
message: 'Error: Fill Amount!'
});
} else if(balance < amount || balance == 0) {
return res.send({
success: false,
message: 'Insufficient funds!'
});
}
//save the new transaction
const newTransaction = new Transaction();
newTransaction.sender = sender;
newTransaction.receiver = receiver;
newTransaction.amount = amount;
newTransaction.save( (err, transaction) => {
if(err) {
return res.send({
success: false,
message: 'Error: Server error.'
});
}else{
return res.send({
success: true,
message: 'Transfer Success!'
});
}
});
//update user balance
User.findOneAndUpdate({
});
and here's the screenshoot:
so what i want is, if i'm as a receiver my balance will be increase.
Try this, the findOneAndUpdate operation does not wait for save operation to complete.
app.post('/api/account/transfer', (req, res, next) => {
const {
body
} = req;
const fields = ['sender', 'receiver', 'amount', 'balance'];
fields.forEach((field) => {
if (!body[field]) {
return res.send({
success: false,
message: 'Error: ' + field + ' cannot be blank!'
});
}
})
if (body.balance < body.amount || body.balance == 0) {
return res.send({
success: false,
message: 'Insufficient funds!'
});
}
//save the new transaction
let newTransaction = new Transaction();
// newTransaction = Object.assign(newTransaction, body); // If you want to copy all params from body to newTransaction
newTransaction.sender = body.sender;
newTransaction.receiver = body.receiver;
newTransaction.amount = body.amount;
newTransaction.save((err, transaction) => {
if (err) {
return res.send({
success: false,
message: 'Error: Server error.'
});
} else {
//update user balance
User.findOneAndUpdate({
/*query*/
}, {
/*body*/
}, (err, data) => {
if (err)
return res.send({
success: false,
message: 'Error: Server error.'
});
return res.send({
success: true,
message: 'Transfer Success!'
});
});
}
});
});