Reputation: 39
I am creating a login page and need to authenticate user's username and password whenever he logs in. My Database is mongodb and i am using expressjs in nodejs. Signup functionality is working well and i am able to sign up users but Log In functionality is not working. Kindly help me with knowledge of MongoDB to authenticate users and store their cookies.
Here's my server code..
//------------modules used-------------//
const express = require("express");
const path = require("path");
const helmet = require("helmet");
const cookieparser = require("cookie-parser");
const mongoose = require("mongoose");
//------------modules used-------------//
const app = express();
app.use(helmet());
// allow the app to use cookieparser
app.use(cookieparser());
// allow the express server to process POST request rendered by the ejs files
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//-------------------mongodb-----------------//
mongoose.connect("mongodb://localhost:27017/loginDB", { useNewUrlParser: true });
const userSchema = new mongoose.Schema({
email: String,
pass: String,
})
const User = new mongoose.model("User", userSchema);
//-------------------mongodb-----------------//
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.get("/", (req, res) => {
// check if user is logged in, by checking cookie
let username = req.cookies.username;
if(username){
return res.render("mainpage", {
username,
});
}else{
res.redirect("/login");
}
});
app.get("/mainpage", (req, res) => {
// check if user is logged in, by checking cookie
let username = req.cookies.username;
if(username){
return res.render("mainpage", {
username,
});
}else{
res.redirect("/login");
}
});
app.get("/register", (req, res) => {
return res.render("signup");
});
app.get("/login", (req, res) => {
// check if there is a msg query
let bad_auth = req.query.msg ? true : false;
// if there exists, send the error.
if (bad_auth) {
return res.render("login", {
error: "Invalid username or password",
});
} else {
// else just render the login
return res.render("login");
}
});
app.post("/login", (req, res) => {
// get the data
let { username, password } = req.body;
User.find({email: username},(err)=>{
if(err){
res.redirect("/");
}else{
res.cookie("username", username, {
maxAge: 30 * 24 * 60 * 60 * 1000,
secure: true,
httpOnly: true,
sameSite: 'lax'
});
res.redirect("/mainpage");
}
})
// fake test data
// let userdetails = {
// username: "Bob",
// password: "123456",
// };
// // basic check
// if (
// username === userdetails["username"] &&
// password === userdetails["password"]
// ) {
// // saving the data to the cookies
// res.cookie("username", username, {
// maxAge: 30 * 24 * 60 * 60 * 1000,
// secure: true,
// httpOnly: true,
// sameSite: 'lax'
// });
// // redirect
// return res.redirect("/");
// } else {
// // redirect with a fail msg
// return res.redirect("/login?msg=fail");
// }
});
app.post("/register",(req,res)=>{
let { given_username, given_password } = req.body;
const newUser = new User({
email: given_username,
pass: given_password,
});
newUser.save((err)=>{
if(err){
console.log(err);
}else{
console.log('saved');
}
})
res.cookie("username", given_username, {
maxAge: 30 * 24 * 60 * 60 * 1000,
secure: true,
httpOnly: true,
sameSite: 'lax'
});
res.redirect("/")
})
app.get("/logout", (req, res) => {
// clear the cookie
res.clearCookie("username");
// redirect to login
return res.redirect("/login");
});
app.listen('3000', () => console.log(`server started`));
Upvotes: 0
Views: 1323
Reputation:
Use this code for login API
const bcrypt = require("bcryptjs")
app.post("/login", async (req, res) => {
let { username, password } = req.body;
const user = await User.findOne({ email: username }).lean()
if (!user) {
res.status(404).send({message: "No User Found"})
} else {
var validatePassword = await bcrypt.compare(password, user.password)
if (!validatePassword) {
res.status(400).send({message: "Invalid Password"})
} else {
res.cookie("username", username, {
maxAge: 30 * 24 * 60 * 60 * 1000,
secure: true,
httpOnly: true,
sameSite: 'lax'
});
res.redirect("/mainpage");
}
}
Upvotes: 1