node.js with express having trouble with using csurf - node.js

I am using ejs, and express to do this. I am not sure why this is keep giving me error of invalid token and I am using csurf dependency
router.get("/recipeUpload", function (req, res) {
const csrfToken = req.csrfToken();
// if (!res.locals.isAdmin) {
// return res.status(401).redirect("/");
// }
const step = req.session.steps;
console.log(csrfToken);
console.log(req.body._csrf);
res.render("uploadrecipe", { steps: step, csrfToken: csrfToken });
});
the code above is my get
<form action="/recipeUpload" method="POST" enctype="multipart/form-data">
<h2>
<%= csrfToken %>
</h2>
<% for (let i=0; i < steps ; i ++){ %>
<%- include("includes/step") %>
<% } %>
<label for="reference">Any referred resource?</label>
<input type="text" value="#" name="reference" id="reference">
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button class="upload-item">Submit</button>
</form>
and this is my form
router.post("/recipeUpload", upload.array("image"), async function (req, res) {
console.log(req.body._csrf);
const uploadFiles = req.files;
const userData = req.body;
const reference = userData.reference;
const step = userData.step;
let imgPath = [];
for (let i = 0; i < uploadFiles.length; i++) {
imgPath.push(uploadFiles[i].path);
}
await db.getDB().collection("recipe").insertOne({
reference: reference,
step: step,
imgPath: imgPath,
});
res.redirect("/");
});
and this is my post and I checked with postman that csrfToken that is made in get is sent to ejs file and has value in input type hidden but when it is trying to submit it it gives ForbiddenError:Invalid csrf token. Can somebody share the knowledge why is this happening
I tried with csrf({cookie:true}) with cookie-parser but at that time it started to give me csrfmiscofiguration errors.

Related

File upload (with other inputs and textarea) using Angular 13 and Node Js

I am trying to upload files to server using Angular and Node, using multer.
I have Todo Model as :
export class TodoModel {
todo_id !:number;
todo_title !:string;
todo_description !:string;
todo_status !:number;
todo_deleted_flag !:boolean;
todo_image !:Object;
}
todo.component.ts
title:string;
desc:string;
selected_image:File = null;
fileUploadListener(event){
//console.log(event)
//console.log(event.target.files[0])
this.selected_image = <File>event.target.files[0]
console.log(this.selected_image)
}
onSubmit(form:NgForm){
const fd = new FormData()
if(this.selected_image) {
fd.append('todo_image',this.selected_image,this.selected_image.name)
}
console.log(fd);
const todo_model : TodoModel = {
todo_id: null,
todo_title:this.title,
todo_description:this.desc,
todo_status:1,
todo_deleted_flag:false,
todo_image:null
}
console.log(fd);
this.todoAdd.emit(todoadded);
this.todoAdd_DB.emit(todo_model);
this.addTodo_DB(todo_model, fd)
form.resetForm();
}
addTodo_DB(todo_db: TodoModel, fileUpload:Object){
//const todo_db
return this.http.post<{message:any}>('http://localhost:3000/api/todos/post_all_todos_db', todo_db,fileUpload).subscribe(data => {
console.log(data.message);
console.log(todo_db);
})
}
todo.component.html
<div class="col-md-12">
<form (ngSubmit)="onSubmit(todoForm)" #todoForm="ngForm">
<div class="mb-3">
<label for="todo_title" class="form-label">Title</label>
<input type="text" class="form-control" id="todo_title" [(ngModel)]="title" name="title">
</div>
<div class="mb-3">
<label for="label" class="form-label">Description</label>
<textarea class="form-control" id="todo_description" [(ngModel)]="desc" name="desc"></textarea>
</div>
<div class="mb-3">
<label for="todo_image" class="form-label">Image</label>
<input type="file" class="form-control" id='todo_image' (change)="fileUploadListener($event)">
</div>
<button type="submit" class="btn btn-success">Add To Do</button>
</form>
</div>
</div>
And on Server Side, using Node Js and PgSQL :-
app.post('/api/todos/post_all_todos_db',upload_using_multer.single('todo_images') , (req, res, next) => {
// const todo_post = req.body;
const files = req.file;
console.log(files) // - ----------> This does NOT work
console.log(req.body) //------> this works
//PGSQL insert query here
res.status(201).json({
message:"Post Added Successfully"
})
})
While doing console.log() in Angular side, I am getting the form data, but, on Node Js side, I get it as null.
Almost every tutorial I see, uses only one file upload , and that too, try to submit the form using the Form's action. I dont want to do that, so I tried doing this.
I
i once had the same issue and solved it with formdata, my example uploads multiple files. here is an example:
Node.JS
const serverRoutes = (function () {
const express = require('express');
const router = express.Router();
const multer = require('multer');
const upload = multer();
router.post('/myresource', upload.any(), (req, res) => {
console.log(req.files);
});
return router;
});
on angular
export class DataService {
constructor(private http: HttpClient) { }
sendMyFiles(file): Observable<MyResponse> {
const formData = new FormData();
formData.append("file", file);
return this.http.post<MyResponse>(
`${environment.backendAPI}myresource`,
formData
);
}
}

Having Login And Register On The Same Page NodeJS

I am setting up a simple blog site and am having problems making the user authentication setup section. What I want to be happening is to have both the Register form and the Login form on the same page (for style reasons) but my issue is is that, to my knowledge, you cannot have two POST methods on one page. I have tried multiple work arounds, like using PUT or checking if the fields are empty, but these all feel hacky and don't really work. Is there anyway to have two fully functional forms on the same page that both respond to the same route? This is my method for reference:
const express = require('express')
const bcrypt = require('bcrypt');
const passport = require('passport');
const router = express.Router()
const app = express()
const User = require('../models/User')
router.get('/', async (req, res) => {
res.render('pages/account', {
pageQuery: "Account"
});
// const allUsers = await User.find({})
// console.log(allUsers)
// User.remove({}, function(err) {
// console.log('collection removed')
// });
});
router.post('/', async (req, res) => {
let name = req.body.userNameSignUp
let password = req.body.userPasswordSignUp
let passwordConfirm = req.body.userPasswordSignUpConfirm
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({
userName: name,
userPassword: hashedPassword
});
if (!name || !password) {
res.render('pages/account', {
errorMessage: "*Please fill out all the fields",
pageQuery: "Account"
});
} else if (password !== passwordConfirm) {
res.render('pages/account', {
errorMessage: "*Passwords do not match",
pageQuery: "Account"
});
} else {
User.findOne({ userName: name })
.then(user => {
if (user) {
res.render('pages/account', {
errorMessage: "*Username Is Already In Use",
pageQuery: "Account"
});
}
})
}
try {
await newUser.save()
res.redirect('/account')
} catch (e) {
res.render('pages/account', {
errorMessage: "*Welp... The server's down. Come back later",
pageQuery: "Account"
});
}
});
module.exports = router;
and my ejs view for the forms:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cheese | Account</title>
<%- include('../partials/linkandsrc'); %>
<script src="js/signUpToggle.js" defer></script>
</head>
<body>
<%- include('../partials/header'); %>
<%- include('../partials/navigation'); %>
<section class="signInSec">
<div class="account-container">
<div class="user signInBx">
<div class="imgBx">
<img src="images/SignUp.jpg" alt="">
</div>
<div class="formBx">
<form action="/account" method="POST">
<h2>Sign Up</h2>
<%- include('../partials/errorMessage'); %>
<input type="text" name="userNameSignUp" placeholder="Username">
<input type="text" name="userPasswordSignUp" placeholder="Password">
<input type="text" name="userPasswordSignUpConfirm" placeholder="Confirm Password">
<input type="submit" value="Create Account">
<p class="signin">Already have an account ? Sign In.</p>
</form>
</div>
</div>
<div class="user signUpBx">
<div class="formBx">
<form action="/account" method="POST">
<h2>Sign In</h2>
<%- include('../partials/errorMessage'); %>
<input type="text" name="userNameLogIn" placeholder="Username">
<input type="text" name="userPasswordLogIn" placeholder="Password">
<input type="submit" value="Login">
<p class="signin">Don't have an account ? Sign Up.</p>
</form>
</div>
<div class="imgBx">
<img src="images/SignIn.jpg" alt="">
</div>
</div>
</div>
</section>
</body>
</html>
If you're sure you want to have the same route (/account) handle both the sign-up and the sign-in, then one approach might be to use hidden input fields.
You could place a hidden input in the sign-up form, with name formType (call it whatever you want, this is just an example) and value signup:
<form action="/account" method="POST">
<h2>Sign Up</h2>
<%- include('../partials/errorMessage'); %>
<input type="text" name="userNameSignUp" placeholder="Username">
<input type="text" name="userPasswordSignUp" placeholder="Password">
<input type="text" name="userPasswordSignUpConfirm" placeholder="Confirm Password">
<input type="hidden" name="formType" value="signup">
<input type="submit" value="Create Account">
<p class="signin">Already have an account ? Sign In.</p>
</form>
and similarly in the sign-in form, with name formType and value signin:
<form action="/account" method="POST">
<h2>Sign In</h2>
<%- include('../partials/errorMessage'); %>
<input type="text" name="userNameLogIn" placeholder="Username">
<input type="text" name="userPasswordLogIn" placeholder="Password">
<input type="hidden" name="formType" value="signin">
<input type="submit" value="Login">
<p class="signin">Don't have an account ? Sign Up.</p>
</form>
Then, in your route handler, you could have some logic that differentiates a sign-up from a sign-in using the received formType:
router.post('/', async (req, res) => {
if ('signup' === req.body.formType) {
// Server-sided sign-up logic can go here...
} else if ('signin' === req.body.formType) {
// Server-sided sign-in logic can go here....
} else {
// Something/someone has submitted an invalid form?
}
}

Updating array of objects in mongoose based off key in objects value

I have two ejs forms that when hit, make an HTTP post request to my /api/users/makePicks/:id route. This route hits my controller which updates the Users model in my mongodb with the NFL picks they submitted in the EJS form.
I need this route to create the picks object for each route if they do not exist for that particular week, and if they do exist it needs to update the picks that are already there. The picks are being stored in my User model in an array, this array contains objects for each weeks picks. Currently the code, with much help from Mohammed, is successfully pushing code to to array. But i cannot seem to figure out how to update the picks if an object with a key of that week exists.
My validation is finally working properly. What I mean is we are running a for loop on the picks array, it will console.log true if there is already a matching picks object with for that weeks picks, if the object with a first key value with the current weeks form doesn't exist, it will console.log false and push the new picks to the array.
The only part that isn't working is the if statement nested within my for loop, it is not updating the object if it already exists in the picks.array. But as I said, the validation is working correctly. I suspect the line of code
result.picks[i] = { [`week-${req.params.week}`]:req.body };
is for some reason not updating object with the updated req.body.
Controller
exports.makePicks = async (req, res, next) => {
const picks = req.body;
try {
let result = await User.findById(req.user._id);
if (result.picks.length > 0) {
for (let i = 0; i < result.picks.length; i++) {
if ((Object.keys(result.picks[i])[0] == [`week-${req.params.week}`])) {
console.log(chalk.green("true"));
result.picks[i] = { [`week-${req.params.week}`]:req.body };
break;
} else {
console.log(chalk.red("false"));
result.picks.push({ [`week-${req.params.week}`]: picks });
break;
}
}
} else {
result.picks.push({ [`week-${req.params.week}`]: picks });
console.log(chalk.yellow('results.picks is empty'))
}
await result.save();
res.redirect("/api/dashboard");
} catch (error) {
console.log(error);
}
};
result.picks example structure
[{"week-1":
{"jojo-0":"ARI","jojo-1":"ARI","jojo-2":"ARI"}
},
{"week-2":
{"jojo-0":"ATL","jojo-1":"ATL","jojo-2":"BAL"}
},
{"week-3":
{"jojo-0":"ARI","jojo-1":"ARI","jojo-2":"ARI"}
}]
Router
router.route('/makePicks/:week')
.post(controller.makePicks);
EJS
<% const teamsArr = ['ARI', 'ATL', 'BAL', 'BUF', 'CAR', 'CHI', 'CIN', 'CLE', 'DAL', 'DEN', 'DET', 'GB', 'HOU', 'IND', 'JAX',
'KC', 'LAC', 'LAR', 'LV', 'MIA', 'MIN', 'NE', 'NO', 'NYG','NYJ', 'PHI', 'PIT', 'SEA', 'SF', 'TB', 'TEN', 'WAS' ] %>
<form class="mt-3 mb-3" method="POST" action="/api/users/makePicks/1">
<% for(i=0; i < user.bullets; i++){ %>
<div class="form-group">
<label for="<%= `${user.name}-${i}` %>">Make your pick for bullet <%= `${i}` %></label>
<select class="form-control" name="<%= `${user.name}-${i}` %>" id="<%= `${user.name}-${i}` %>">
<% teamsArr.forEach(team => { %>
<option value="<%= team %>"><%= team %></option>
<% }) %>
</select>
</div>
<% }; %>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
<form class="mt-3 mb-3" method="POST" action="/api/users/makePicks/2">
<% for(i=0; i < user.bullets; i++){ %>
<div class="form-group">
<label for="<%= `${user.name}-${i}` %>">Make your pick for bullet <%= `${i}` %></label>
<select class="form-control" name="<%= `${user.name}-${i}` %>" id="<%= `${user.name}-${i}` %>">
<% teamsArr.forEach(team => { %>
<option value="<%= team %>"><%= team %></option>
<% }) %>
</select>
</div>
<% }; %>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
you want to using $push and $set in one findByIdAndUpdate, that's impossible, I prefer use findById() and process and save() so just try
exports.makePicks = async (req, res, next) => {
const picks = req.body;
try {
//implementation business logic
let result = await User.findById(req.user._id)
if(result.picks && result.picks.length > 0){
result.picks.forEach(item =>{
if([`week-${req.params.week}`] in item){
item[`week-${req.params.week}`] = picks
}
else{
result.picks.push({ [`week-${req.params.week}`] : picks })
}
})
}
else{
result.picks.push({ [`week-${req.params.week}`] : picks })
}
await result.save()
res.redirect('/api/dashboard');
} catch (error) {
console.log(error)
}
}
note: don't use callback and async/await together
exports.makePicks = async (req, res, next) => {
const picks = req.body;
const { week } = req.params;
try {
let result = await User.findById(req.user._id);
const data = { [`week-${week}`]: picks };
const allPicks = [...result.picks];
if (allPicks.length > 0) {
// Search index of peek
const pickIndex = _.findIndex(allPicks, (pick) => {
return Object.keys(pick)[0] == `week-${week}`;
});
// If found, update it
if (pickIndex !== -1) {
console.log(chalk.green("true"));
allPicks[pickIndex] = data;
}
// Otherwise, push new pick
else {
console.log(chalk.red("false"));
allPicks.push(data);
}
} else {
allPicks.push(data);
console.log(chalk.yellow('results.picks is empty'))
}
result.picks = allPicks;
console.log('allPicks', allPicks);
await result.save();
res.redirect("/api/dashboard");
} catch (error) {
console.log(error);
}
};

How to use packages in EJS template?

I'm trying to use timeago.js in an EJS template. I have tried to export the library like this:
src/lib/lib.js
const timeago = require('timeago.js');
exports.index = function(req, res){
res.render('links/list',{timeago: timeago});
}
The route is:
routes/links.js
router.get('/', (req, res)=>{
sequelize.query('SELECT * FROM links', {
type: sequelize.QueryTypes.SELECT
}).then((links)=>{
res.render('links/list', {links: links});
});
});
The EJS template is:
views/links/list.ejs
<div class="container p-4">
<div class="row">
<% for(i of links){ %>
<div class="col-md-3">
<div class="card text-center">
<div class="card-body">
<a target="_blank" href="<%= i.url %>">
<h3 class="card-title text-uppercase"><%= i.title %></h3>
</a>
<p class="m-2"><%= i.description %></p>
<h1><%= timeago.format(i.created_at); %></h1>
Delete Link
Edit
</div>
</div>
</div>
<% } %>
I need to use the library in the h1 to transform a timestamp I got from the database. However, I always get the same error: timeago is not defined.
How could I export Timeago correctly to use in EJS template? If I require the library in the routes file and send it to the EJS template through an object works perfectly, but not when I export it from another file.
I made the following test program to do a minimal test of timeago.js
const ejs = require('ejs');
const timeago = require('timeago.js');
let template = `
<% for(i of links){ %>
<h1> <%- i.created_at %>: <%- timeago.format(i.created_at) %> </h1>
<% } %>
`;
const renderData = {
links: [
{
created_at: new Date()
}
],
timeago
};
const output = ejs.render(template, renderData);
console.log(output);
Output:
<h1> Mon Sep 07 2020 00:01:57 GMT-0700 (Pacific Daylight Time): just now </h1>
So as long as you correctly pass the timeago object into your rendering data it will work.
The problem is likely here:
router.get('/', (req, res)=>{
sequelize.query('SELECT * FROM links', {
type: sequelize.QueryTypes.SELECT
}).then((links)=>{
res.render('links/list', {links: links});
});
});
Where you are not passing in the timeago object. This line:
res.render('links/list', {links: links});
Should probably be:
res.render('links/list', {links: links, timeago});
Edit:
More complete example using file paths specified in comments:
routes/links.js:
var express = require('express')
var router = express.Router();
const lib = require("../src/lib/lib");
router.get('/', (req, res)=>{
lib.index(req, res);
});
module.exports = router;
src/lib/lib.js
const timeago = require('timeago.js');
exports.index = function(req, res) {
const links = [
{
created_at: new Date()
}
];
res.render('links/list',{ timeago, links });
}

How do I have a variable available to display on my success page, after adding items to a database via a /POST route?

I would like to display the doc.id variable of a successful /POST of data to a route, on the success page that the user will be redirected to afterward. I'm trying to work out how to carry the variable teamId through to the Handlebar template page success.hbs
I've tried making it a variable, and setting up a Handlebar helper to display it, but nothing is working.
/POST route redirecting to success.hbs:
app.post('/create', (req, res) => {
var players = [];
var playerObj = {};
for (let i = 1; i < 21; i++) {
var playerObj = { playerName: req.body[`player${i}Name`], playerNumber: req.body[`player${i}Number`], playerPosition: req.body[`player${i}Position`] };
if (req.body["player" + i + "Name"] === '') {
console.log("Empty player name detected, disregarding");
} else {
players.push(playerObj);
}
}
var newTeam = new Team({
// WEB SETUP BELOW
"team.teamRoster.teamCoach": req.body.coachName,
"team.shortTeamName": req.body.teamShortName,
"team.teamName": req.body.teamName,
"team.teamRoster.players": players
});
newTeam.save().then((doc) => {
var teamId = doc.id;
console.log(teamId);
res.render('success.hbs');
console.log("Team Added");
}, (e) => {
res.status(400).send(e);
});
});
/views/success.hbs
<div class="container-fluid" id="body">
<div class="container" id="page-header">
<h1><span id="headline">Team Added Succesfully</span></h1>
<hr>
<h3><span id="subheadline">Input the following address as a JSON Data Source within vMix.</span></h3>
<span id="content">
<div class="row">
<div class="container col-md-12">
{{{teamId}}}
</div>
</div>
</span>
</div>
<hr>
</div>
I'd like a Handlebar helper to get the doc.id value of the /POST request, and store it as teamId to display on the success page. It's finding nothing at the moment.
Any help is appreciated.
Node.js can pass variables to the handlebars-view like this:
newTeam.save().then((doc) => {
var teamId = doc.id;
console.log(teamId);
res.render('success.hbs', {
teamId
});
console.log("Team Added");
}, (e) => {
res.status(400).send(e);
});

Resources