password comparison with bcrypt not working - javascript

i'm fairly new to express js i want to do a login app so far i did the register part but in login app i want to do the comparaison between the password in database and the password provided by the user and compare it with bcrypt since i'm using it to crypt password , but its not doing the comparaison , what i'm missing here
router
const express = require('express')
const router = express.Router()
const bcrypt = require('bcrypt');
const User = require('../models/user')
const jwt = require('jsonwebtoken')
router.get('/login', function (req, res) {
res.render('login')
})
router.get('/', function (req, res) {
res.render('home')
})
router.get('/register', function (req, res) {
res.render('register')
})
router.post('/register', async function(req,res){
User.beforeCreate((user, options) => {
return bcrypt.hash(user.password, 10)
.then(hash => {
user.password = hash;
})
.catch(err => {
throw new Error();
});
});
return User.create({
username: req.body.name,
password: req.body.password,
email: req.body.email,
createdAt: Date.now()
}).then(function (users) {
res.send(users);
}).catch((err)=>{
console.log(err)
})
})
router.post('/login', function(req,res){
User.findOne({
where:{
username:req.body.name
}
})
.then(user=>{
if(user){
if(bcrypt.compareSync(req.body.password,user.password)){
let token = jwt.sign(user.dataValues,secretKey,{
expiresIn:1440
})
res.send(token)
}
else {
res.status(400).json({
error:'error exissts'
})
}
}
})
.catch(err=>{
res.status(400).json({err:err})
})
})
module.exports = router
models
const sequelize = require('../database/db.js')
const Sequelize = require('sequelize');
const User = sequelize.define('authentication',{
username: {
type: Sequelize.STRING,
allowNull: false
},
password: {
type: Sequelize.STRING
// allowNull defaults to true
} ,
email: {
type: Sequelize.STRING
// allowNull defaults to true
},
created_at: {
field: 'createdAt',
type: Sequelize.DATE,
},
updated_at: {
field: 'updatedAt',
type: Sequelize.DATE,
},
}, {
freezeTableName: true
},
{
notNull: { args: true, msg: "You must enter a name" }
},
)
module.exports = User
index
const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const path = require('path');
// const passport = require('passport');
// const passportJWT = require('passport-jwt');
// Database
const db = require('./database/db');
// Test DB
db.authenticate()
.then(() => console.log('Database connected...'))
.catch(err => console.log('Error: ' + err))
const app = express();
// Handlebars
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
// Body Parser
app.use(bodyParser.urlencoded({ extended: false }));
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
// Importing files
const routes = require("./routes/route");
app.use("/", routes);
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on port ${PORT}`));

index.js
const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const path = require('path');
// const passport = require('passport');
// const passportJWT = require('passport-jwt');
// Database
const db = require('./database/db');
// Test DB
db.authenticate()
.then(() => console.log('Database connected...'))
.catch(err => console.log('Error: ' + err))
const app = express();
// Handlebars
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
// Body Parser
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
// Importing files
const routes = require("./routes/route");
app.use("/", routes);
const PORT = process.env.PORT || 4500;
app.listen(PORT, console.log(`Server started on port ${PORT}`));
route.js
const express = require('express')
const router = express.Router()
const bcrypt = require('bcrypt');
const User = require('../models/user')
const jwt = require('jsonwebtoken')
const uuid = require('uuidv4').default;
const secretKey = '321'
router.get('/login', function (req, res) {
res.render('login')
})
router.get('/', function (req, res) {
res.render('home')
})
router.get('/register', function (req, res) {
res.render('register')
})
router.post('/register', function(req,res){
User.beforeCreate((user, options) => {
return bcrypt.hash(user.password, 10)
.then(hash => {
user.password = hash;
})
.catch(err => {
throw new Error();
});
});
return User.create({
id: uuid(),
username: req.body.name,
password: req.body.password,
email: req.body.email,
createdAt: Date.now()
}).then(function (users) {
res.send(users);
}).catch((err)=>{
console.log(err)
})
})
router.post('/login', function(req,res){
User.findOne({
where:{
username:req.body.name
}
})
.then(user=>{
if(user){
if(bcrypt.compareSync(req.body.password,user.password)){
let token = jwt.sign(user.dataValues,secretKey,{
expiresIn:1440
})
res.send(token)
}
else {
res.status(400).json({
error:'error exissts'
})
}
}
})
.catch(err=>{
res.status(400).json({err:err})
})
})
module.exports = router
just add app.use(bodyParser.json()) in index.js and define secretKey also add id in user model for primary key and the code working properly

Related

Firebase functions can't access my middleware routes

///index.js
const functions = require("firebase-functions");
const express = require("express");
const app = express();
const productRouter = require('./routes/productRoutes');
const globalErrorHandler = require('./controllers/errorController');
const AppError = require('./utils/appError');
// Compressing upcompressed files which is been sent to client such text.
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.send('Hello World')
});
app.get('/homepage', (req, res) => {
res.send('Hello People of God')
});
app.use('/products', productRouter);
// Handing Unhandled Routes
app.all('*', (req, res, next) => {
next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});
app.use(globalErrorHandler);
exports.app = functions.https.onRequest(app);
///productRoutes.js
const express = require('express');
const {
getProduct,
getAllProduct,
} = require('./../controllers/productController');
const router = express.Router();
router
.route('/')
.get(getAllProduct);
router
.route('/:id')
.get(getProduct);
module.exports = router;
///productController.js
const AppError = require('../utils/appError');
const Product = require('../modals/productModels');
const catchAsync = require('../utils/catchAsync');
// GET SINGLE PRODUCT CONTROLLER
exports.getProduct = catchAsync(async (req, res, next) => {
const product = await Product.findById(req.params.id)
.populate('reviews');
if (!product) {
return next(new AppError('No product found with that ID', 404));
}
res.status(200).json({
status: 'success',
data: {
product
}
});
});
// GET ALL PRODUCT CONTROLLER
exports.getAllProduct = catchAsync(async (req, res, next) => {
const products = await Product.find();
res.status(200).json({
status: 'success',
results: products.length,
data: {
products
}
});
});
///server.js
const mongoose = require('mongoose');
const app = require('./index')
const dotenv = require('dotenv');
// CONNECTING TO MONGODB SERVER
dotenv.config({ path: './config.env' })
const DB = process.env.DATABASE.replace('<PASSWORD>', process.env.DATABASE_PASSWORD);
mongoose.connect(DB, {
useNewUrlParser: true,
safe: true,
strict: false,
useUnifiedTopology: true
}).then(con => console.log('DB connection successful'))
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`App running on port ${port}...`);
});
After running function serve on my terminal i can access the two '/' and 'homepage' app.get which return the res "Hello world" and "Hello people of God" but can't access app.use('/products', productRouter). Its does take some time to run and throw an error "{"code":"ECONNRESET"}" please why is this so.
Am expecting to get my list of products from my mongodb data base.

Error: Login sessions require session support

I have installed express-session yet i'm getting Error: Login sessions require session support. Did you forget to use express-session middleware?
the passport.authenticate doesn't works because of this
index.js
const ejs = require("ejs");
const url = require("url");
const session = require("express-session");
const cookieParser = require('cookie-parser')
const flash = require('connect-flash');
const toastr = require('express-toastr');
const Profile = require('./models/Profile.js');
const passport = require("passport");
const { customAlphabet } = require('nanoid');
const express = require("express"),
path = require('path')
const app = express();
const port = 3000;
const { Notyf } = require('notyf')
const { connect } = require('mongoose');
const LocalStrategy = require('passport-local');
const MemoryStore = require("memorystore")(session);
const methodOverride = require('method-override')
connect(process.env.mongodb);
const initializePassport = require('./utils/passport-config.js')
initializePassport(
passport,
email => Profile.find({ email_id: email }),
id => Profile.find({ user_id: email })
)
var bodyParser = require('body-parser');
app.use(cookieParser());
app.use(
session({
store: new MemoryStore({ checkPeriod: 86400000 }),
secret: "##%#&^$^$%#$^$&%#$%##$%$^%&$%^#$%##$%#E%#%#$FEErfgr3g#%GT%536c53cc6%5%tv%4y4hrgrggrgrgf4n",
resave: false,
saveUninitialized: false,
}),
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(toastr());
app.use('/assets', express.static(path.join(__dirname, 'assets')))
app.use('/scripts', express.static(path.join(__dirname, 'node_modules')))
app.set('views', './views');
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true,
}),
);
const checkAuth = (req, res, next) => {
try {
if (req.isAuthenticated()) return next();
req.session.backURL = req.url;
res.redirect("/login");
} catch (e) {
console.log(e)
}
};
app.get('/', async function(req, res){
res.render('index.ejs', { url: req.url })
});
app.get('/login', async function(req, res){
if (req.session.backURL) {
req.session.backURL = req.session.backURL;
} else if (req.headers.referer) {
const parsed = url.parse(req.headers.referer);
if (parsed.hostname === app.locals.domain) {
req.session.backURL = parsed.path;
}
} else {
req.session.backURL = "/";
}
res.render('login.ejs', { url: req.url })
});
app.get('/signup', async function(req, res){
res.render('signup.ejs', { url: req.url })
});
app.get('/newshop', async function(req, res){
res.render('shopcreate.ejs', { url: req.url })
});
app.get('/profile', async function(req, res){
res.render('profile.ejs', { url: req.url })
});
app.get('/settings', async function(req, res){
res.render('settings.ejs', { url: req.url })
});
app.post('/login', passport.authenticate('local', {
failureRedirect: '/login',
}), async (
err,
req,
res,
next,
) => {
try {
await console.log(req)
if (req.session.backURL) {
const backURL = req.session.backURL;
req.session.backURL = null;
res.redirect(backURL);
} else {
res.redirect('/');
}
} catch(e) {
console.log(e)
}
})
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));
passport-config.js -
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, password, done) => {
console.log(email)
const user = getUserByEmail(email)
if (user == null) {
return done(null, false, { message: 'User not found' })
}
try {
if (await bcrypt.compare(password, user.password)) {
return done(null, user)
} else {
return done(null, false, { message: 'Password incorrect' })
}
} catch (e) {
return done(e)
}
}
passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => {
return done(null, getUserById(id))
})
}
module.exports = initialize

login authorization problem, does not pass the token

I am trying to make a login system with authorization, unfortunately the token is not transferred.
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({ extended: false });
const mysql = require('mysql');
const validator = require('validator');
const jwt = require('jsonwebtoken');
require('dotenv').config().ACCESS_TOKEN;
const ACCESS_TOKEN = process.env.ACCESS_TOKEN;
const app = express();
app.use(express.json());
const publicDirectoryPath = path.join(__dirname, '../public');
console.log(publicDirectoryPath);
app.use(express.static(publicDirectoryPath));
function generateAccessToken(username) {
return jwt.sign(username, ACCESS_TOKEN, { expiresIn: '1800s' });
}
app.post('/login', urlencodedParser, (req, res) => {
res.get(req.body.username + req.body.password);
const token = generateAccessToken({ username: req.body.username });
res.json(token);
});
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
console.log(token)
if (token == null) return res.sendStatus(401)
jwt.verify(token, ACCESS_TOKEN, (err, user) => {
console.log(err)
if (err) return res.sendStatus(403)
req.user = user
next()
})
}
app.get('/admin', authenticateToken, (req, res) => {
res.send("admin panel");
})
const port = 3000;
app.listen(port, () => {
console.log(`Server run: http://localhost:${port}`);
})
wants him to be redirected to the admin panel after clicking the login button. However, I am stuck at this stage and do not know what to do next:
enter image description here
You should pass the token to the next route
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({ extended: false });
const mysql = require('mysql');
const validator = require('validator');
const jwt = require('jsonwebtoken');
require('dotenv').config().ACCESS_TOKEN;
const ACCESS_TOKEN = process.env.ACCESS_TOKEN;
const app = express();
app.use(express.json());
const publicDirectoryPath = path.join(__dirname, '../public');
console.log(publicDirectoryPath);
app.use(express.static(publicDirectoryPath));
function generateAccessToken(username) {
return jwt.sign(username, 'ACCESS_TOKEN', { expiresIn: '1800s' });
}
app.post('/login', urlencodedParser, (req, res) => {
res.get(req.body.username + req.body.password);
const token = generateAccessToken({ username: req.body.username });
res.redirect(`/admin?token=${token}`);
});
function authenticateToken(req, res, next) {
token = req.query.token;
if (token == null) return res.sendStatus(401);
jwt.verify(token, 'ACCESS_TOKEN', (err, user) => {
console.log(err);
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
app.get('/admin', authenticateToken, (req, res) => {
res.send('admin panel');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server run: http://localhost:${port}`);
});

PassportJs not saving sessions

I am using react and nodejs with passportjs. I called a post request to validate the username and password using local strategy. and on same page, I have a button that calls a get request to just console.log(req.user).
The issue is: on route /login - post, I am being able to console.log(req.user) while when I click on a button to make a get request to /getstatus, it gives me undefined.
If you check the /login post route, the res.send(req.user) also sends undefined, whereas the console.log(req.user) is showing the right information in the console.
I need help, do not know what I am doing wrong.
Below I have my code:
const express = require("express");
const bodyParser = require("body-parser");
require("dotenv").config();
const mongoose = require("mongoose");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const cookieParser = require("cookie-parser");
const expressSession = require("express-session");
const cors = require("cors");
const session = require("cookie-session");
const LocalStrategy = require("passport-local").Strategy;
//............................Initialization of middleware..........................
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
//..............connect to a database...............................
const Users = new mongoose.Schema({
username: String,
password: String,
});
Users.plugin(passportLocalMongoose);
const MyModel = mongoose.model("MyModel", Users);
passport.use(MyModel.createStrategy());
// passport.use(new LocalStrategy(MyModel.authenticate()));
passport.serializeUser(MyModel.serializeUser());
passport.deserializeUser(MyModel.deserializeUser());
mongoose.connect(
process.env.DB_HOST,
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
() => {
console.log("Database Connected");
}
);
// };
//......................Routes........................
app.post(
"/login",
cors(),
passport.authenticate("local", {
failureRedirect: "/failure",
}),
function (req, res, next) {
res.send(req.user);
console.log(req.user);
}
);
app.get("/failure", (req, res) => {
res.send({
name: "fff",
age: 23,
status: 500,
msg: "Invalid Username or Password",
color: "danger",
});
});
app.post("/reg", cors(), (req, res) => {
let username = req.body.username;
let password = req.body.password;
// connectdb();
MyModel.register({ username: username, active: false }, password, function (
err,
user
) {
if (err) {
console.log(err);
} else {
res.send("Success");
}
});
});
app.get("/getstatus", (req, res) => {
console.log(req.user);
});
//...........Start Server..........................
app.listen(5000, () => {
console.log("Server Started on Port 5000");
});
I got the solution, the issue is not with passportJS. it is with Axios.
This line of code is needed:
Axios.defaults.withCredentials = true;

Redirect after Post method , expressjs

I'm learing ExpressJS, and so far I did the user registration part but when I want to redirect to the home page after finishing the registration, it's not
showing the json after clicking on Submit button. May I know how I could do it.
Database
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:'reciepeapp'
});
module.exports = con
the ORM
const con = require('./db')
The ORM
const orm = {
insertOne: function (values, cb) {
const sqlQuery = "INSERT INTO authentication(username,password) VALUES ?";
con.query(sqlQuery, [values],function (err, data) {
if (err) {
console.log(err)
cb(err, null);
} else {
cb(null, data);
}
});
},
}
module.exports = orm;
The route.js
Here I insert the data obtained during registration (register index html) into a database. It's working well but I want to redirect to home page.
const express = require('express');
const app = express()
const router = express.Router()
const bcrypt = require('bcrypt');
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
const orm = require('../models/orm')
router.get('/',(req,res)=>
res.render('home')
)
router.get('/login',(req,res)=>
res.render('login')
)
router.get('/register',(req,res)=>
res.render('register')
)
router.post("/register", async (req, res) =>{
try {
const hashedPassword = await bcrypt.hash(req.body.password,10)
values = { username: req.body.name,
password:hashedPassword }
orm.insertOne(values, function(error) {
if (error) {
return res.status(401).json({
message: 'Not able to add'
});
}
values = { username: values.username,
password: values.password }
orm.insertOne(values, function(error) {
if (error) {
return res.status(401).json({
message: 'Not able to add'
});
}
**return res.send({
username: values.username,
password: values.password
});**
});
});
}
catch {
}
});
module.exports = router
const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const con = require('./models/db')
con.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var exphbs = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))
To do this you need to use express's redirect method.
Example:
var express = require('express');
var app = express();
const urlBase = 'localhost:3000/'
app.post('/', function(req, res) {
const redirectUrl = "index.html"
res.redirect(urlBase + redirectUrl);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Docs: Express 4.x Docs

Categories

Resources