I want take the user info like email , username and display it on dashboard.ejs . i tried req.session.username and req.body.username but never worked . please help me in this !!
i want handle profile management for the web so by retriving the username help fetch the info about the user in the database
`
const express = require("express");
const app = express();
const bcrypt = require("bcryptjs");
const session = require("express-session");
const MongoDBSession = require("connect-mongodb-session")(session);
const mongoose = require("mongoose");
const UserModel = require("./models/user");
const mongoURI = "mongodb://localhost:27017/sessions";
mongoose.connect( mongoURI, {
useNewUrlParser : true,
// useCreateIndex : true,
// useUnifiedToplogy : true
}).then((res)=>{
console.log("MongoDB connected");
})
const store = new MongoDBSession({
uri : mongoURI,
collections : "mySessions"
})
const isAuth = (req,res,next)=>{
if(req.session.isAuth){
next();
}else{
res.redirect("/login");
}
}
app.use(session({
secret : "key that will sign a cookie",
resave : false,
saveUninitialized : false,
store : store
}))
app.set("view engine", "ejs");
app.use(express.urlencoded({ extended: true }));
app.get("/", (req,res)=>{
res.render("landing");
});
// Login Page
app.get("/login", (req,res)=>{
res.render("login");
} );
app.post("/login", async(req,res)=>{
const {email , password} = req.body;
const user = await UserModel.findOne({email});
if (!user){
return res.redirect("/login");
}
const isMatch =await bcrypt.compare(password , user.password);
if(!isMatch){
return res.redirect("/login");
}
req.session.isAuth = true;
res.redirect("/dashboard");
});
// Register Page
app.get("/register", (req,res)=>{
res.render("register");
});
app.post("/register", async (req,res)=>{
const {username , email , password } = req.body;
let user = await UserModel.findOne({email});
if (user){
return res.redirect("/register");
}
const hashPsw =await bcrypt.hash(password,12);
user = new UserModel({
username,
email,
password:hashPsw
});
user.save();
console.log("saved");
if (!user){
return res.redirect("/login");
}
const isMatch =await bcrypt.compare(password , user.password);
if(!isMatch){
return res.redirect("/login");
}
req.session.isAuth = true;
res.redirect("/dashboard");
});
// Dashboard Page
app.get("/dashboard", isAuth , (req,res)=>{
console.log(req.session);
res.render("dashboard");
});
app.post("/logout", (req,res)=>{
req.session.destroy((err)=>{
if (err) throw err;
res.redirect("/");
})
});
app.listen(3500 , ()=>{
console.log("server running on port 3500");
})
`
One of the options would be to supply that in the POST request's response. For example, Author has inserted it in a pug view here like h2 Username: #{user.name} and has supplied it as variable while page rendering in response here with res.render('profile', {title: "My Profile", user: req.cookies.userData});.
Since you have used ejs instead of pug, the injecting I did with #{} can be done with <%= YOUR_VARIABLE %> . Please, see this for a tutorial and ejs docs for more examples.
Related
When i make a post request containing the user data to log in, i get the response: Cannot post /login.
What is really weird about this is that you can see trough logging that the request get processed.
I was using postman and a html form to test and both didnt worked.
When i have a failure in the passport.js file it gets logged.
.
Thats my server.js file (shortened):
const express = require("express");
const cors = require("cors");
const flash = require("express-flash");
const passport = require("passport");
const session = require("express-session");
//app configuration
const app = express();
require("dotenv").config();
const initializePassport = require("./config/passport-config");
initializePassport(
passport,
require('./models/User')
)
app.use(
session({
secret: "Janniks whatsapp Klon",
resave: false,
saveUninitialized: false,
})
);
app.use(passport.initialize());
app.use(passport.session());
//For accepting post from data
const UserRouter = require("./api/User");
app.use(flash());
app.use(express.json());
app.use(bodyarser.urlencoded({ extended: true }));
app.use(
cors() //{ origin: "http://localhost:3000", origin: "http://localhost:3000" }
);
app.use("/user", UserRouter);
app.post('/login', passport.authenticate('local', {
sucessRedirect: 'http://localhost:3000/login',
failureRedirect: 'http://localhost:3000/login',
failureFlash: true
}),
)
and thats my passport-config.js file
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
//Password handle
function initialize(passport, User){
const authenticateUser = async(emailORnumber, password, done)=>{
//Find user with email or phone number
let user;
if(emailORnumber.includes('#')){
user = await User.findOne({ email: emailORnumber})
}else{
user = await User.findOne({ number: emailORnumber })
}
if(!user){
//User not found, error
console.log('User not found')
return done(null, false, { message: 'Falsches passwort oder falsche Handynummer' })
}
//Check if password is correct
try{
console.log('Checking password')
const isMatch= await bcrypt.compare(password, user.password);
if(!isMatch){
return done(null, false, { message: 'Falsches passwort'})
}else{
//If credentials are correct, return the user object
console.log('correct') //gets logged
return done(null, user)
}
}
catch(err){
console.log(err)
return done(err)
}
}
passport.use(new LocalStrategy({ usernameField: 'emailORnumber'}, authenticateUser)),
//Serialize user to store
passport.serializeUser((user, done)=>{
console.log('Serializing user') //gets logged
done(null, user.id)
})
//Deserialize user from store
passport.deserializeUser((id, done)=>{
console.log('Serializing user') //dont gets logged but there is no interaction
User.findById(id, (err, user)=>{
return done(err, user);
});
});
}
module.exports = initialize;
Thanks for all awnsers that can be provided!
this is my routes file
const User = require("./schema");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const express = require("express");
const server2 = express();
const routes = (server,app) => {
// this route is for signup
server.post("/api/signup", async (req,res) => {
const { fullName, emailId, password }=req.body;
const signupData = new User({
fullName,
emailId,
password: await bcrypt.hash(password,10),
});
const token = await signupData.generateToken();
console.log(`token: ${token}`);
if (token != undefined) {
res.cookie("token",token,{
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
maxAge: 1000*60*2
})
res.send({message:"signedup successfuly"});
res.end();
}
const saveUser = await signupData.save();
});
// this route is for user varification
server.get("/api", async (req,res) => {
const token = req.cookies.token;
console.log(`token: ${token}`);
if (token != undefined) {
const _id = jwt.verify(token,process.env.JWT_SECRET)._id;
const findUser = await User.findOne({ _id });
res.send(findUser);
} else {
res.send({fullName:""});
}
});
// this route is for logout
server.get("/api/logout",async (req, res) => {
try {
const token = req.cookies.token;
const _id = jwt.verify(token, process.env.JWT_SECRET)._id;
await User.updateOne({ _id }, { $pull: { tokens: { token }}});
res.clearCookie("token");
console.log(req.cookies.token)
res.send({message:""})
res.end();
} catch(err) {
console.log(err)
}
});
}
module.exports = routes;
When I do signup cookie is setting without reloading the page its working but that's not a problem the problem is when I do logout its not deleting cookie without reloading the page when I reload the page its working but without reloading the page its not working I am using custom express server in nextjs
I got a problem with the Passport.js module and Express.js.
This is my code and I just want to use a hardcoded login for the first try.
I always get the message:
I searched a lot and found some posts in stackoverflow but I didnt get the failure.
Code of my app.js
require('dotenv').config()
const express = require('express')
const bodyParser = require('body-parser')
const ejs = require('ejs')
const mongoose = require('mongoose')
const session = require('express-session')
const passport = require('passport')
const passportLocalMongoose = require('passport-local-mongoose')
const app = express();
const port = process.env.PORT
app.use(express.static('public'))
app.set('view engine','ejs')
app.use(bodyParser.urlencoded({extended:true}))
app.use(session({
secret: process.env.SECRET_KEY,
resave: false,
saveUninitialized: false,
}))
app.use(passport.initialize())
app.use(passport.session())
mongoose.connect("mongodb://localhost:27017/userDB")
const userSchema = new mongoose.Schema({
username: String,
password: String,
})
userSchema.plugin(passportLocalMongoose)
const User = new mongoose.model("User",userSchema)
passport.use(User.createStrategy())
passport.serializeUser(User.serializeUser())
passport.deserializeUser(User.deserializeUser())
//Home Route
app.get('/',(req,res)=>{
res.render('home')
})
//Login Route
app.route('/login')
.get((req,res)=>{
res.render('login')
})
.post((req,res)=>{
const user = new User({
username: req.body.username,
password: req.body.password
});
req.login(user, function(err){
if (err) {
console.log(err);
} else {
passport.authenticate("local")(req, res, function(){
res.redirect("/secrets");
});
}
});
})
//Register route
app.route('/register')
.get((req,res)=>{
res.render('register')
})
.post((req,res)=>{
User.register({username: req.body.username}, req.body.password,(err,user)=>{
if(err){
console.log(err);
res.redirect('/register')
}
else{
passport.authenticate("local")(req,res,()=>{
res.redirect("/secrets")
})
}
})
})
app.route('/secrets')
.get((req,res)=>{
res.set('Cache-Control', 'no-store');
if(req.isAuthenticated()){
res.render("secrets")
}
else{
res.redirect("/login")
}
})
app.listen(port,()=>console.log("server started at port "+port))
But its giving this error:
Error: Failed to serialize user into session
at pass (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:278:19)
at serialized (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:283:7)
at D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport-local-mongoose\index.js:212:7
at pass (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:291:9)
at Authenticator.serializeUser (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:296:5)
at SessionManager.logIn (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\sessionmanager.js:14:8)
This problem is occuring only in case of login. register is working fine.
This error means passport is not able to hash (serialize) your users. Try to implement your own User.serializeUser() function using the user's _id.
I have a few Problem with the session in express.
When i log in i'm setting the session.uid session.user and session.isAuth to its Parameter.
When i click on some other Sides where i need the Info of the Session. It sometimes work, sometimes it doesn't. Sometime i got the Error that 'user' is undefined....
I have this Code. And when i click for Example on editQuestion i got the Error. When i do the console.log in the '/' route it works.
Can someone tell me what i'm missing here?
var express = require("express");
const session = require("express-session");
const cookieParser = require("cookie-parser");
const flush = require("connect-flash");
var path = require("path");
const w2v = require("word2vec");
const port = 3000;
const background = require("./public/js/background.js")
const datahandler = require("./public/js/data_handling.js")
//var routes = require("./routes");
var app = express();
app.set("port", process.env.PORT || 3000);
app.set("views", path.join(__dirname, "public/html"));
//app.set("view engine", "ejs");
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(session({
cookie:{maxAge:60000},
resave: false,
saveUninitialized: false,
secret: "secret"
}));
//app.use(flush());
//Bodyparser
app.use(express.urlencoded({extended:true}));
const isAuth = (req, res, next)=>{
if(req.session.isAuth){
next();
}else{
res.redirect("/login");
}
}
app.get("/", function(req, res) {
res.render("index.html");
});
app.get("/question", function(req,res){
var Qid = Number(req.query.id)
})
app.get("/search", function(req,res){
var searchWords = req.query.search.split(' ');
w2v.loadModel('public/data/word_vectors.txt', (error, model) =>{
var word_vectors = model.getVectors(searchWords)
var avg_vector = background.averageVectors(word_vectors, model);
var questions = background.mostSimilarQuestions('/../data/qentities.txt', avg_vector);
var resultjson = datahandler.getQuestionsFromSimilar(questions);
res.json(resultjson)
})
});
app.get("/search/new", function(req,res){
var resultjson = datahandler.getNewestQuestions();
//console.log(resultjson);
res.json(resultjson);
});
app.get("/LogIn", function(req, res){
console.log(req.session.user);
res.render("LogIn.html");
})
app.post("/logIn",async(req, res) =>{
//LogIn
const{username, password} = req.body;
const user = datahandler.logIn(username, password);
if(!user){
return res.send("Log In failed!")
}else{
req.session.uid = user[0];
req.session.user = user[1];
req.session.isAuth = true;
req.session.save();
res.redirect("/");
}
});
app.get("/user",isAuth, (res, req)=>{
//res.send(req.session.user);
//res.json(req.session.user)
res.redirect("Profil.html");//Doesn't work ;(
});
app.get("/editQuestion", isAuth,(res, req)=>{
//console.log(req.session.user); Not working here. WHY?????
res.render("editQuestion.html");
});
app.get("/viewQuestion", isAuth,(res, req)=>{
console.log(req.session.user);
res.render("viewQuestion.html");
});
app.get('/logout',function(req,res){
console.log(req.session);
req.session.destroy(function(err) {
if(err) {
console.log(err);
} else {
res.redirect('/');
}
});
});
app.get("/Register", function(req,res){
res.render("Register.html")
})
app.post("/register", async(req,res)=>{
const{newUsername, password} = req.body;
const newuser = datahandler.registerNewUser(newUsername, password);
if(!newuser){
res.redirect("/Register");
}
else{
res.redirect("/");
}
})
app.get("/about", function(req, res) {
res.render("about.html");
});
app.all('*',(req,res)=>{
res.status(404).render('404.html');
});
app.listen(app.get("port"), function() {
console.log(`Example app listening at http://localhost:${port}`);
});
This is the Out i get when i click on editQuestion:
TypeError: Cannot read property 'user' of undefined
And this in the '/' what is correct:
TP
Ok. I solved it....
I swapped req and res in the functions...
I'm trying to create a Login functionality using express-jwt, and using the middleware function in my app.js file. But whenever I'm trying to send a get request using the postman, it sending request for infinite of time and never returns back any error or success message.
I'm using dynamoDB as database.
here's my Login.js file
const AWS = require("aws-sdk");
const express = require("express");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
require("dotenv").config();
AWS.config.update({ region: "us-east-2" });
const docClient = new AWS.DynamoDB.DocumentClient();
const router = express.Router();
router.post("/login", (req, res) => {
user_type = "customer";
const email = req.body.email;
docClient.get(
{
TableName: "users",
Key: {
user_type,
email,
},
},
(err, data) => {
if (err) {
res.send("Invalid username or password");
} else {
if (data && bcrypt.compareSync(req.body.password, data.Item.password)) {
const token = jwt.sign(
{
email: data.Item.email,
},
process.env.SECRET,
{ expiresIn: "1d" }
);
res.status(200).send({ user: data.Item.email, token: token });
} else {
res.status(400).send("Password is wrong");
}
}
}
);
});
module.exports = router;
Here's my jwt.js file:
const expressJwt = require("express-jwt");
require("dotenv").config();
function authJwt() {
const secret = process.env.SECRET;
return expressJwt({
secret,
algorithms: ["HS256"],
});
}
module.exports = authJwt;
And I'm trying to use the expressJwt like this in my app.js file:
app.use(authJwt); //If I'm not using this, then the code works fine without API protection
Can Anyone tell me what's wrong with my code?
Any help from your side is appreciated.
Remove function from your jwt.js ,it should look like this
const expressJwt = require('express-jwt');
const secret = process.env.secret
const authJwt = expressJwt({
secret,
algorithms:['HS256']
})
module.exports = authJwt;