500 errors in OTP implementation using speakeasy in EJS - node.js

The OTP function is being implemented using the package.
Current environments include: Express.js, SQL, MariaDB, EJS
When logging in using speakeasy, I will receive the OTP number together, and if there is no problem, I will log in and redirect it to the main page.
It is impossible to change in that technology because it only adds new functions of existing services.
The point where the current problem occurs is that the OTP code changes every certain time, but when you click login, it does not proceed by outputting otp is not defined.
ReferenceError: /Users/Desktop/otpsql/views/otp.ejs:17
15| <input type="password" id="password" name="password" required><br>
16| <label for="otp">OTP</label>
>> 17| <p><%= otp %></p>
18| <input type="text" id="otp" name="otp" required><br>
19| <button type="submit">Login</button>
20| </form>
otp is not defined
If the otp number is not printed at all, I understand that I wrote the wrong code, but if I enter username, password, and otp and click the submit button, that error occurs, so I don't know what the problem is.
Among the files I wrote, the part of the file that displays the error message is as follows.
at eval ("/Users/Desktop/otpsql/views/otp.ejs":12:26)
<form action="/otp" method="post">
<label for="username">username</label> <<< line 12
<input type="text" id="username" name="username" required><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" required><br>
<label for="otp">OTP</label>
<p><%= otp %></p>
<input type="text" id="otp" name="otp" required><br>
<button type="submit">Login</button>
</form>
at /Users/Desktop/otpsql/Router/otp.js:66:9
router.post('/', async (req, res, next) => {
const user = await query('SELECT * FROM users WHERE username = ?', [req.params.username]);
if (user.length > 0) {
const isPasswordValid = user[0].password === req.body.password;
const otpSecret = await query('SELECT otp_secret FROM otp_secrets WHERE user_id = ?', [user[0].id]);
if (isPasswordValid && speakeasy.totp.verify({
secret: otpSecret[0].otp_secret,
encoding: 'base32',
token: req.body.otpCode,
window: 1
})) {
req.session.userId = user[0].id;
res.redirect('/');
} else {
res.render('otp', { error: 'Invalid username, password, or OTP' });
}
} else {
res.render('otp', { error: 'Invalid username, password, or OTP' });
} <<< line 66
});
What code should I modify in that part?

Related

Nodejs req.query.token undefined from url

Good day,
Can anyone help me with this question, I send email to user with link which have token and email in it:
<p>To reset your password, please click the link link</p>
So with following code I'm trying to set new password for user:
router.post('/reset-password', authController.resetPassword);
exports.resetPassword = async (req, res, next) => {
let token = req.query.token;
let email = req.query.email;
console.log(token);
console.log(email);
...
Page form:
<form action="/auth/reset-password" method="POST">
<div class="form-group">
<input type="password1" id="newPassword" name="password" class="form-control" placeholder="Naujas slaptažodis" required>
</div>
<div class="form-group">
<input type="password2" id="newPasswordConfirm" name="passwordConfirm" class="form-control" placeholder="Pakartoti nauja slaptažodį" required>
</div>
<button type="submit" name="submit" class="btn btn-theme btn-block btn-form">Patvirtinti</button>
</form>
So my problem is that req.query.token return for me undefined.
Probably problem is that when user press submit, it send to new link (http://localhost:5000/auth/reset-password) which don't have token and email in new url.
How should I transfer it from my email url to new url, or maybe there is something else what I can do?
Thank you
I managed today to fix it, so if any one have familiar problem do as robertklep told me.

Node Express can't figure out how to update user details

Okay so once the user logs in, i am storing their details in req.user. The user should then be able to edit their details (fistname, lastname, email) in a form rendered with the /profile route as seen below:
app.get('/profile', checkAuthenticated, (req, res) => {
res.render('profile.ejs', req.user);
})
Here is the form:
<form class="form__inputs" action="/update-profile" method="post">
<div class="form__input">
<input id="firstname" name="firstname" type="text" value="<%=firstname%>" required />
<label for="firstname">Firstname</label>
</div>
<div class="form__input">
<input id="lastname" name="lastname" type="text" value="<%=lastname%>" required />
<label for="lastname">Lastname</label>
</div>
<div class="form__input form__email">
<input id="email" name="email" type="email" value="<%=email%>" required />
<label for="email">Email</label>
</div>
<button class="form__button" type="submit">Update</button>
</form>
After submitting the form the i want the user to be redirected to the /update-profile route, where i can perform an update to the database (MySQL).
app.put('/update-profile', (req, res) => {
console.log(req.params)
console.log(req.body)
res.redirect('/')
})
However I'm recieving a "Cannot POST /update-profile" error.
I was just going to use the user_id stored in req.user, and new user data (firstname, lastname, email) stored in req.body.params to update the database, but i've clearly gotten a bit mixed up with my routes.
Any help would be greatly appreciated, thanks so much for your time!
It seems you are listening to a PUT request in your express app, but sending a POST.
app.post('/update-profile', (req, res) => {
console.log(req.params)
console.log(req.body)
res.redirect('/')
});
If you change your code to this, it should work.

Getting an error while saving hidden type data in mongodb database using nodejs

I have got two things in form the first is add a password and the other is id which is no need to enter as it comes from the database directly when I click on add I got an error
Post method is
router.post('/', checkLogin, function (req, res, next) {
var user = localStorage.getItem('loginname');
var add_model = new pass_cat({
password: req.body.catename,
user_id: req.body.id
})
add_model.save(function (err, doc) {
if (err) throw err;
res.render('AddCategory', {
title: 'Password Management System',
user: user,
msg: 'Inserted Successfully'
})
})
});
And the ejs code for the form is
<form action="/add_category" id="EmployeeForm" class="form-horizontal" method="post" role="form">
<input type="hidden" name="id" value="<%= data%>" >
<div class="form-group">
<label for="Username" class="col-md-3 control-label">Add Category Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="catename" placeholder="Enter Password Category">
</div>
</div>
<div class="form-group">
<label for="User_id" class="col-md-3 control-label">User_id</label>
<div class="col-md-9">
<input type="text" class="form-control" name="userid" value="<%=data[0]._id%>" placeholder="Enter Password Category">
</div>
</div>
<input type="hidden" name="id" value="<%= data%>" >
there is no need of this line in the form, as data you are not setting anywhere, and its value is not defined.

Including multiple form fields via Nodemailer with Express and Node.js

I am trying to receive an e-mail everytime the user submits my contact form.
The form has the following fields:
- email
- subject
- name
- track
- number
- the message
However when the e-mail is sent I can only get whichever field I input into the "text" field under mail options. It won't work if I try to turn it into an array or object because it says the chunk needs to be a string.
How can I send more form fields than whatever I input into text? Here's my code:
Nodemailer POST Route :
app.post ("/contact" , urlencodedParser, function(req, res){
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'theemail',
pass: 'emailpassword' // naturally, replace both with your real credentials or an application-specific password
}
});
var subject = req.body.subject;
var email = req.body.email;
var data = [
req.body.name,
req.body.track,
req.body.number,
req.body.message,
]
const mailOptions = {
from: req.body.email,
subject: req.body.subject,
to: "theemail",
text: req.body.message,
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
res.render("../EN/views/contact-success");
});
Form HTML
<div class="fade-in serviceform text-center container form-group">
<form method ="POST" action = "/contact">
<p class=" text-center">Touring | Recording | Online sessions | Any other question</p>
<input type="email" name="email" class="contactform" placeholder=" E-mail" required>
<input type="text" name="subject" class="contactform" placeholder=" Subject" required>
<input type="text" name="name" class="contactform" placeholder=" First and last name" required>
<input type="text" name="track" class="contactform" placeholder=" Track Name" required>
<input type="number" name="number" class="contactform" placeholder=" +351919999999" required>
<textarea class="contactformtext" name="message" placeholder=" Write your message here." rows="3" required></textarea>
<div class="text-center">
<button type="submit" class="btn btn-outline-danger">Contact</button>
</div>
</form>
<div class ="text-center">
<a class="anchor" href="https://www.facebook.com/"><i class="fab fa-facebook-square"></i></a><a class="anchor" href="https://www.instagram.com//"><i class="fab fa-instagram"></i></a>
<p>Facebook | | Instagram </p>
</div>
```
just use the backticks it will considered itself as the string

How to post data from form in express.js?

I am trying to make a user registration router in express. The backend seemed to work fine since I verified it using it postman. However, when I tried to add the front end to it(adding form), I got an error saying
{"errors":[{"location":"body","param":"name","msg":"Name is required"},{"location":"body","param":"email","msg":"Please include a valid email"},{"location":"body","param":"password","msg":" Please enter a password with 6 or more characters"}]} Since I included name attribute in each input tag, I could not figure out where is the problem.
Here is some part of my codes.
server.js
app.use('/api/posts', require('./routes/api/posts'));
users.js
router.post(
'/',
[
check('name', 'Name is required')
.not()
.isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check(
'password',
' Please enter a password with 6 or more characters'
).isLength({ min: 6 })
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}
.
.
.
register.handlebars
<form class="form" action="/api/users" method="post">
<div class="form-group">
<input name="name" type="text" placeholder="Name" requried>
</div>
<div class="form-group">
<input name="email" type="email" placeholder="E-mail">
</div>
<div class="form-group">
<input name="password" type="text" placeholder="Password" minlength="6">
</div>
<input type="submit" value="Create account" class="button green-button" />
</form>ss
use body-parser
middleware with express
https://expressjs.com/en/resources/middleware/body-parser.html

Resources