How to get the hashed password to pass into my database? - javascript

I am able to run a test in Postman, but for some reason I am not passing my hashed password into the DB correctly.
const express = require("express");
// const helmet = require("helmet");
const { User } = require("./db/models");
const bcrypt = require("bcryptjs");
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync('bacon', 8);
const port = 4000;
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true, limit: "50mb" }));
// app.use(helmet());
app.get("/", (req, res) => {
res.send("Hello World!");
});
Here is where i suspect the issue is. I am passing the name, email, and password in. I am trying to figure out how to get the hash to pass into the DB as the password.
app.post("/register", async (req, res) => {
const user = await User.create({name:req.body.name, email:req.body.email, password:req.body.password});
bcrypt.genSalt().then(salt => {
bcrypt.hash("password", salt).then(hash =>{
console.log(hash);
});
})
console.log(req.body.name)
res.json(user);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});

Since you are in an async function you can use await to get the values before creating the User object
app.post("/register", async (req, res) => {
const salt = await bcrypt.genSalt();
const hashed_password = await bcrypt.hash(req.body.password,salt);
const user = await User.create({name:req.body.name, email:req.body.email, password:hased_password});
console.log(req.body.name)
res.json(user);
});

const hashedPwd = await bcrypt.genSalt().then(salt => {
return bcrypt.hash("password", salt);
})
is that you want?

You have to save the user collection. That is, after hashing the password, the user's password must be changed.
user.password = hash;
user.save()

Related

How to solve MongoServerError: E11000 duplicate key error?

Index.Js File:
const cookieSession = require("cookie-session");
const express = require("express");
const app = express();
const helmet = require("helmet");
const morgan = require("morgan");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const userRoute = require("./routes/user")
const authRoute = require("./routes/auth")
dotenv.config();
//Mongoose Connect
mongoose.connect(process.env.MONGO_URL, {useNewUrlParser: true}, (err) =>
{
console.log("mongdb is connected");
});
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
app.get("/", (req, res) => {
res.send("Welcome to home page");
})
app.use("/api/auth", authRoute);
app.use("/api/user", userRoute);
app.listen(5000,function(err)
{
if(err)
console.log("Server not connected")
console.log("Connnection is established");
})
Auth.Js File
const router = require("express").Router();
const User = require('../model/Users');
//REGISTER
router.get("/register", async (res,req)=> {
const user = await new User({
username: "gauravnegi",
password: "123456",
email: "gauravnegi#gmail.com",
});
await user.save();
res.send("ok");
});
module.exports = router;
Error:
return callback(new error_1.mongoservererror(res.writeerrors [0] ))
Full Error Snippet:
How to resolve above error?
Dear it is not a server side error it's a client side error b/c you have defined somewhere some field {unique:true} in your model! So you should wrap your function inside try-catch block for example
router.get("/register", async (res,req)=> {
try{
const user = await new User({
username: "gauravnegi",
password: "123456",
email: "gauravnegi#gmail.com",
});
await user.save();
res.send("ok");
}catch(error){
//check if it was a duplication error
if(error.code==11000) // show user that it is unique path
and handle other validation error
}
});

How would I send data from a post route to a get route in node js

I want to send data for products from my post request
router.post("/addProduct",(req, res) => {
const {addName, addDescription, addPrice, addImg} = req.body;
console.log(`${addName} added, the price is ${addPrice}`)
})
into the get request
router.get("/addProduct",(req, res) => {
//console.log(`getting ${addName}, and the price is ${addPrice}`)
console.log(`getting the response ${addName}`)
})
i want to send the const {addName, addDescription, addPrice, addImg} = req.body; into the get request, but I haven't found a lot of info on how to do that
You can, but it's against the convention.
const express = require("express");
const app = express();
const router = express.Router();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(router);
router.get("/addProduct", (req, res) => {
const { addName } = req.body;
console.log(`getting the response ${addName}`);
return res.json(addName);
});
app.listen(3000, (req, res) => {
console.log("listening...");
});

How to create totp verificator form to this serverjs

I've got a task in JavaScript but I don`t know anything about it. I found a video which helped to solve my problem but now I must create a form which check all results. In postman I entered token and pass.
const express = require('express');
const speakeasy = require('speakeasy');
const QRCode = require('qrcode');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const cod = 123
const secret = speakeasy.generateSecret();
console.log(secret);
app.get('/', (req, res) => {
res.send('hello');
})
app.get('/twofactorsetup', (req, res) => {
QRCode.toDataURL(secret.otpauth_url, (err, data_url) => {
res.send(
`<h1>setup authenticator</h1>
<img src=${data_url} >
<br>Manually: ${secret.base32}`
);
})
})
app.post('/verify', (req, res) => {
token = req.body.userToken;
const pass = req.body.pass;
token = token - cod;
console.log('first');
console.log(token);
token = token + pass
console.log('sec');
console.log(token);
const verfied = speakeasy.totp.verify({ secret: secret.base32, encoding: 'base32', token: token });
res.json({ success: verfied });
})
app.listen(3000, () => {
console.log('Server started ISZZI');
});
What should I do? Any videos or tutorials
Thank you!

Express node.js api app.post does work for / but not with /path

I am new at Node.js and trying to make an API that will do CRUD operations in sql server. The problem for me is that I can get the data but cannot post it, and get the error "cant get /". I know there are similar questions about this subject but nothing works for me so I thought maybe my code has different kinds of error. Any help will be appreciated and save my life in a way. Also, this is my first question on stackoverflow, sorry for the possible mistakes..
Here is the server.js
const sql = require('mssql');
const express = require('express');
const bodyParser = require('body-parser');
var port = process.env.port || 5000;
const sqlConfig = require('./connection/connect')
const app = express();
app.use(express.json()); // json desteklemesi için
app.use(express.urlencoded({ extended: true }));
app.get("/test", (req, res, next) => {
new sql.ConnectionPool(sqlConfig).connect()
.then(pool => {
return pool.query('select * from tblProfile')
})
.then(result => {
res.send(result);
})
})
app.post('/test', (req, res) => {
let name = req.query.name;
let lastname = req.query.lastname;
let email = req.query.email;
let password = req.query.password;
let sql = "INSERT INTO tblProfile(name,lastname,email,password) VALUES(? ? ? ?)";
conn.query(sql, [name, lastname, email, password], (err, result) => {
if (err) throw err;
res.write("inserted.");
res.end();
});
app.listen(port, () => {
console.log("working: " + port)
})
});
This is the connect.js
var sqlConfig = {
server: '192.168.1.2',
database: 'profile',
user: 'username',
password: 'user',
};
module.exports = sqlConfig;
This is happening because you aren't responding or sending anything to that route
So if you want to get rid of the error
Run
app.get('/', (req,res)=>{
res.send('hello world')
}
But if you want to send a static file to the route
Create a folder call public * note it can be anything
And type
var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
Then you can access code in the dir
And as for the writing I think you should try this
app.post('/test', (req, res) => {
let name = req.body.name;
let lastname = req.body.lastname;
let email = req.body.email;
let password = req.body.password;
let sql = "INSERT INTO tblProfile(name,lastname,email,password VAUES(? ? ? ?)";
conn.query(sql, [name, lastname, email, password], (err, result) => {
if (err) throw err;
res.write("inserted.");
res.end();
});
Change query to body
Since you installed body-parser
Taking a quick look over your code, the only issues I can see are in your query to submit the data. Within your query statement, I added a closed parentheses after the variables to be entered into the database and made a typo correction to the word Values. I also changed up how the data is retrieved from req.query to destructure it and simply the code a bit. Based on everything else I saw, and the fact that you are able to get data from the database, this should work out fine. If it doesn't, I would recommend inserting some console.log() statements in the post query to see where it might be having issues and why. For example, you could run console.dir(req.query); in your post route to see what data is actually coming from the req and make sure it is all there. If something is missing, then the query won't actually execute. If this doesn't work, let me know, along with the information from any console logs you did and I'll take another look at it.
const sql = require('mssql');
const express = require('express');
const bodyParser = require('body-parser');
var port = process.env.port || 5000;
const sqlConfig = require('./connection/connect')
const app = express();
app.use(express.json()); // json desteklemesi için
app.use(express.urlencoded({ extended: true }));
app.get("/test", (req, res, next) => {
new sql.ConnectionPool(sqlConfig).connect()
.then(pool => {
return pool.query('select * from tblProfile')
})
.then(result => {
res.send(result);
})
})
app.post('/test', (req, res) => {
//console.dir(req.query);
let {name, lastname, email, password} = req.query;
let sql = "INSERT INTO tblProfile(name,lastname,email,password) VALUES(? ? ? ?)";
conn.query(sql, [name, lastname, email, password], (err, result) => {
if (err) throw err;
res.write("inserted.");
res.end();
});
app.listen(port, () => {
console.log("working: " + port)
})
});

How to print out jwt token

I am trying to generate a jwt token and print it out by calling res.json() after the user has been authenticated, the problem is that I get the following error:
Cannot set headers after they are sent to the client
I tried solving the issue by using async and await but it still gives me the error. How can I res.json my token successfully?
Here is my node.js server:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const BASE_URL = process.env.BASE_URL;
const PORT = process.env.PORT || 1337;
const jwt = require('jsonwebtoken');
let Post = require('./models/post.model.js');
app.use(cors());
app.use("/assets", express.static(__dirname + "/assets"));
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(BASE_URL, { useNewUrlParser: true, useUnifiedTopology: true })
const connection = mongoose.connection;
connection.once('open', function () {
console.log('Connection to MongoDB established succesfully!');
});
app.set('view-engine', 'ejs');
app.get('/', (req, res) => {
res.render('index.ejs');
});
app.post('/', (req, res) => {
let username = req.body.username;
let password = req.body.password;
if (username !== process.env.USER_NAME && password !== process.env.USER_PASSWORD) {
res.json('Invalid credentials');
} else {
const token = jwt.sign({
username: username,
password: password
}, process.env.SECRET_KEY, {
expiresIn: '1h'
});
res.redirect('/dashboard');
res.json(token);
}
});
app.get('/dashboard', (req, res) => {
res.render('dashboard.ejs');
});
app.get('/dashboard/createPost', (req, res) => {
res.render('post.ejs');
});
app.post('/dashboard/createPost', async (req, res) => {
let collection = connection.collection(process.env.POSTS_WITH_TAGS);
res.setHeader('Content-Type', 'application/json');
let post = new Post(req.body);
collection.insertOne(post)
.then(post => {
res.redirect('/dashboard')
})
.catch(err => {
res.status(400).send(err);
});
});
app.listen(PORT);
You are calling res.redirect('/dashboard'); before the res.json(token);, you can't send a response twice that's why it's giving you the Cannot set headers after they are sent error.
What you can do instead is sending the token as a query via the redirect like this:
res.redirect(`/dashboard?token=${token}`);
Then you can get the token value from the front-end app by checking the query value.
Although this is not a very safe method

Categories