nodejs using rest api in the front end - node.js

I've multiple newbie questions regarding Nodejs.
I've build api for the auth/login and i'm questionning about the connection frontend and backend.
so first, I would like to know in my form the action, should I put the url of my api? or another route?
<div class="container">
<div class="boxlogin">
<img id="img-logo" src="img/logo.png" alt="Logo">
<h1>Sign in</h1>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<form action="????" method="POST">
<input type="email" name="email" id="email" placeholder="Email" class="input-box" required>
<input type="password" name="password" id="password" placeholder="Password" class="input-box" required>
<button type="submit" class="btn-signup">Log in</button>
<p class="compte-deja-cree">Don't have an Account yet ? Sign In</p>
</form>
</div>
<div class="imglogin"><img id="img-login" src="img/undraw_Active_support_re_b7sj.svg" alt="Logologin"></div>
</div>
also in my controller there is a try catch, I would like to display the errors (err of password, or err of email) and I don't know at all how I have to do it.
For information i'm using nodejs/mongodb/express/ejs.
here some pieces of my code for understanding.
server.js
app.use("/css", express.static(__dirname + "public/css"));
app.use("/img", express.static(__dirname + "public/img"));
app.set("view-engine", "ejs");
app.get("*", checkUser);
app.get("/jwtid", requireAuth, (req, res) => {
res.status(200).send(res.locals.user._id);
});
const userRoutes = require("./routes/user.routes");
const mainRoutes = require("./routes/main.routes");
app.use("/api/user", userRoutes);
app.use('/', mainRoutes);
authController :
const SellerModel = require("../models/sellerModel");
const SuperUserModel = require("../models/superUserModel");
const UserModel = require("../models/userModel");
const LoginModel = require("../models/loginModel");
const jwt = require("jsonwebtoken");
const { signUpErrors, signInErrors } = require("../utils/errorsUtils");
const maxAge = 3 * 24 * 60 * 60 * 1000;
const createToken = (id) => {
return jwt.sign({ id }, process.env.TOKEN_SECRET, {
expiresIn: maxAge,
});
};
module.exports.sellerSignUp = async (req, res) => {
const {company,email,password,telephone,address,zipcode,city} = req.body;
try {
const user = await SellerModel.create({company,email,password,telephone,address,zipcode,city});
res.redirect("/");
} catch (err) {
const errors = signUpErrors(err);
res.status(200).send({ errors });
}
};
module.exports.userSignUp = async (req, res) => {
const {email,password,telephone,address,zipcode,city} = req.body;
try {
const user = await UserModel.create({email,password,telephone,address,zipcode,city});
res.redirect("/");
} catch (err) {
const errors = signUpErrors(err);
res.status(200).send({ errors });
}
};
module.exports.superUserSignUp = async (req, res) => {
const { email, password } = req.body;
try {
const user = await SuperUserModel.create({ email, password });
res.redirect("/");
} catch (err) {
const errors = signUpErrors(err);
res.status(200).send({ errors });
}
};
module.exports.signIn = async (req, res) => {
const { email, password } = req.body;
try {
const user = await LoginModel.login(email, password);
const token = createToken(user._id);
res.cookie("jwt", token, { httpOnly: true, maxAge });
if (user.role == "seller") {
res.redirect("/success");
} else if (user.role == "user") {
res.redirect("/success-user");
} else if (user.role == "superuser") {
res.redirect("/success-admin");
};
} catch (err) {
const errors = signInErrors(err);
res.status(200).json({ errors });
}
};
module.exports.logout = (req, res) => {
res.cookie("jwt", "", { maxAge: 1 });
res.redirect("/");
};
user.routes:
const router = require("express").Router();
const authController = require("../controllers/authController");
router.post("/register/seller", authController.sellerSignUp);
router.post("/register/user", authController.userSignUp);
router.post("/register/admin", authController.superUserSignUp);
router.post("/login", authController.signIn);
router.get("/logout", authController.logout);
module.exports = router;
main.routes:
const router = require("express").Router();
router.get("/", (req, res) => {
res.render("login.ejs");
});
router.get("/signup-user", (req, res) => {
res.render("signup-user.ejs");
});
router.get("/signup-seller", (req, res) => {
res.render("signup-seller.ejs");
});
router.get("/success", (req, res) => {
res.render("sucessful.ejs");
});
router.get("/success-user", (req, res) => {
res.render("sucessful-user.ejs");
});
router.get("/success-admin", (req, res) => {
res.render("sucessful-admin.ejs");
});
module.exports = router;
Wish you a awesome Sunday !

To resolve this, I add some dependencies :
connect-flash
express-session
express-messages
in my Server.js
app.use(session({
secret:"Secret",
cookie:{ maxAge : 60000},
resave: false,
saveUninitialized: true,
}))
app.use(flash());
app.use(require('connect-flash')());
app.use(function (req,res,next){
res.locals.messages = require('express-messages')(req,res);
next();
})
app.use(express.static("public"));
in authController
module.exports.sellerSignUp = async (req, res) => {
const {company,email,password,telephone,address,zipcode,city} = req.body;
try {
const user = await SellerModel.create({company,email,password,telephone,address,zipcode,city});
req.flash('info', `Successful Register`)
res.redirect("/");
} catch (err) {
const errors = signUpErrors(err);
console.log(errors);
req.flash('message', errors.email || errors.password );
res.redirect('/register-seller');
}
};
in my main route :
const router = require("express").Router();
const services = require('../service/render');
router.get("/", services.login);
router.get("/register-user",services.registerUser);
router.get("/register-seller",services.registerSeller);
router.get("/success",services.sucessful);
router.get("/success-user",services.sucessfull_t);
router.get("/success-admin",services.sucessful_a);
module.exports = router;
render.js:
exports.login = (req, res) => {res.render("login.ejs",{ errorMessage: req.flash('message'), successMsg: req.flash('info') })};
exports.registerUser = (req, res) => {res.render("register-user.ejs",{ message: req.flash('message')})};
exports.registerSeller = (req, res) => {res.render("register-seller.ejs",{ message: req.flash('message')})};
exports.sucessful = (req, res) => {
res.render("sucessful.ejs");
};
exports.sucessfull_t = (req, res) => {
res.render("sucessful-t.ejs");
};
exports.sucessful_a = (req, res) => {
res.render("sucessful-a.ejs");
};

Related

How can I enter three field in my database, with passport, passport-local-mongoose, and express-session

I am stuck with this code. I want to insert three fields in my database using User.register(), but my passport.authenticate() is giving me bad request and redirect me to register page again and again, but my data got inserted into the database.
Here is my app.js:
require('dotenv').config()
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const _ = require("lodash");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const app = express();
app.set("view engine", 'ejs');
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.set("strictQuery", true);
mongoose.connect("mongodb://127.0.0.1:27017/My1stProjectDb", (err) => {
if (err) {
console.log(err);
} else {
console.log("Success !!!");
}
});
const userSchema = new mongoose.Schema({
name: String,
email: 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());
app.get("/", function (req, res) {
res.render("home");
});
app.get("/sell", function (req, res) {
res.render("sell");
});
app.get("/categories", function (req, res) {
res.render("categories");
});
app.get("/register", function (req, res) {
res.render("register");
});
app.get("/login", function (req, res) {
res.render("register")
})
app.get("/secrets", function (req, res) {
if (req.isAuthenticated()) {
res.render("secrets")
} else {
res.render("register")
}
});
app.get("/logout", function (req, res) {
req.logout((err) => {
if (err) {
console.log(err);
} else {
res.redirect("/");
}
});
});
app.post("/register", function (req, res) {
const registerUser = new User({ email: req.body.useremail, username: req.body.username });
User.register(registerUser, req.body.userpassword, function (err, user) {
if (err) {
console.log(err);
} else{
passport.authenticate("local",{ failureRedirect: '/register' })(req, res, function () {
res.redirect("/secrets");
});
}
});
});
app.listen(3000, function () {
console.log("Server started at port 3000");
});
Here is registration page
<form action="/register" method="POST">
<div class="form sign-up">
<h2>Create your Account</h2>
<label>
<span>Name</span>
<input type="text" name="username" />
</label>
<label>
<span>Email</span>
<input type="email" name="useremail" />
</label>
<label>
<span>Password</span>
<input type="password" name="userpassword"/>
</label>
<button type="submit" class="submit">Sign Up</button>
</div>
</form>
I want to make my code compatible for three fields entry in userSchema into database and successfully redirect it to secrets page with authentication.

How to Authenticate signup and login frontend form with Passport JS at backend

Getting my signup and login form to connect to my local MongoDB is not working. I am using a Passport for authentication. At first, it threw up "no username was given error". I fixed that by defining usernameField. Now, when I fill in details on the frontend form, it is not sending to the MongoDB database on clicking submit. The values are just there.
Here is My Server.js
const express = require("express"),
connect = require("./config/db"),
passport = require("passport"),
bodyParser = require("body-parser"),
User = require("./model/trialModel");
LocalStrategy = require("passport-local").Strategy,
routes = require('./route/userRoute')
const path = require('path')
connect()
const app = express();
app.engine('html', require('ejs').renderFile)
app.set("view engine", "html");
app.set('views', path.join(__dirname, 'views'))
app.use(bodyParser.urlencoded({ extended: true }));
app.use(require("express-session")({
secret: "Rusty is a dog",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
// passport.use(User.createStrategy());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
//=====================
// ROUTES
//=====================
// Showing home page
app.get("/", function (req, res) {
res.render("home");
});
// Showing secret page
app.get("/secrete", isLoggedIn, function (req, res) {
res.render("secrete");
});
// Showing register form
app.get("/register", function (req, res) {
res.render("register");
});
//Showing registration success page
app.get("/success", function (req, res) {
res.render("success");
});
// // Handling user signup
// app.post("/register", function (req, res) {
// var username = req.body.username
// var password = req.body.password
// var fullname = req.body.fullname
// var email = req.body.email
// User.findByUsername(username, function(err, user) {
// if (err) {
// console.log(err)
// } else if (user){
// res.send('username already exist!')
// } else{
// User.register(new User({ username: username, fullname: fullname, email: email}), password,
// function (err, user) {
// if (err) {
// console.log(err);
// return res.render("register");
// } else{
// res.redirect('/success')
// }
// passport.authenticate("local")(
// req, res, function () {
// res.render("secrete");
// });
// });
// }
// })
// });
//Showing login form
app.get("/login", function (req, res) {
res.render("login");
});
// //Handling user login
// app.post("/login", passport.authenticate("local", {
// successRedirect: "/secrete",
// failureRedirect: "/login"
// }), function (req, res) {
// });
// //Handling user logout
// app.get("/logout", function (req, res) {
// req.logout(function(err){
// if (err){
// return next(err)
// }
// res.redirect("/");
// });
// });
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect("/login");
}
app.use('/', routes)
var port = process.env.PORT || 4000;
app.listen(port, function () {
console.log("Server Has Started!");
});
Here is my controller.js
const User = require('../model/trialModel')
passport = require("passport")
//sign up
exports.signUp = (req, res) => {
var username = req.body.username
var password = req.body.password
var fullname = req.body.fullname
var email = req.body.email
User.findByUsername(username, function(err, user) {
if (err) {
console.log(err)
} else if (user){
res.send('username already exist!')
} else{
User.register(new User({ username: username, fullname: fullname, email: email}), password,
function (err, user) {
if (err) {
console.log(err);
return res.render("register");
} else{
passport.authenticate("local")(
req, res, function () {
res.send('User registered successfully')
})}
});
}
})
};
//login
exports.login = passport.authenticate("local", {
successRedirect: "/secrete",
failureRedirect: "/login"
}), function (req, res) {
}
//logout
exports.logout = (req, res) => {
req.logout(function(err){
if (err){
return next(err)
}
res.redirect("/");
});
}
Here is my Schema Model:
const {Schema, model} = require('mongoose')
const passportLocalMongoose = require('passport-local-mongoose');
const newSchema = new Schema({
username: {
type: String,
require : true
},
fullname: {type: String,
require: true
},
email: {
type: String,
require: true
}
},
{timestamps: true})
newSchema.plugin(passportLocalMongoose,{
usernameField: 'fullname'
});
const todoModel = model('trial', newSchema);
module.exports = todoModel
Here is my HTML for Signup:
<h1> Sign up form </h1>
<h1>Auth-wiki</h1>
<h2>Create your free account</h2>
<form action="" id="register">
<div class="input-details">
<label for="">Full name</label> <br />
<input type="text" name="fullname" placeholder="Enter full name" id="" />
<br />
<label for="">Username</label> <br />
<input type="text" name="username" placeholder="Enter username" id="" />
<br />
<label for=""> Email</label> <br />
<input
type="email"
name="email"
placeholder="Enter username or email"
id="email"
/>
<h5 id="email-msg"></h5>
<br />
<label for="">Password</label> <br />
<input
type="password"
name="password"
placeholder="Enter Password"
id="Password"
/>
<h5 id="pass-msg"></h5>
</div>
<div class="check">
<input type="checkbox" id="checkbox" />
<label for="">Remember Password</label>
</div>
<button id="creat-account" type="submit">Create account</button>
</form>
<h1>This is home page</h1>
<li>Sign up!!</li>
<li>Login</li>
<li>Logout</li>
Here is my codes to consume the API from the Frontend:
const registerForm = document.getElementById('register')
function registerUser(event) {
event.preventDefault();
let fullname = event.target.fullname.value
let username = event.target.username.value
let password = event.target.password.value
//validation
if (!username || !password || !fullname) {
alert('All fields must be entered')
return;
}
let userObj = {
fullname,
username,
password
}
console.log(userObj)
fetchAPI(userObj,'register', 'POST').then((data) =>{
if (data) {
alert('user created successfully! Click ok to sign in')
// window.location.href = "../"
}
})
}
const API = 'http://localhost:4000';
async function fetchAPI(data, endpointurl, method) {
try {
//response from form
const response = await fetch(`${API}/${endpointurl}`, {
method: 'POST',
headers: {
"content-type": "application/json"
},
body:JSON.stringify(data) //convert the plain data to json so server is able to read it
})
const result = await response.json()
console.log(result)
} catch (error) {
}
}
registerForm.addEventListener('submit', registerUser)

localhost redirected you too many times in NodeJS and Express-session

i am following the tutorial on youtube the code is working fine on his computer but not running on my system.
i am getting error.
"This page isn't working at the momentlocalhost redirected you too many times.
To fix this issue, try clearing your cookies."
the '/' page is working fine when i have try to jump on /home page it doesn't work can anyone help where is the mistake actually? i have followed the tutorial and rewrite the code 5 times unfortunately every time i am getting the same error which is unexpected
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const TWO_HOUR = 1000 * 60 * 60 * 2
const {
PORT = 3000,
NODE_ENV = 'development',
SESS_NAME = 'sid',
SESS_SECRET = 'SADFSDF#*9SDF',
SESS_LIFETIME = TWO_HOUR
} = process.env
const IN_PROD = NODE_ENV === 'production'
const users = [
{id: 1, name: 'Asad', email: 'asad_gmail.com', password: '123'},
{id: 2, name: 'Abdullah', email: 'abdullah_gmail.com', password: '123'},
{id: 3, name: 'Shehroz', email: 'shehroz_gmail.com', password: '123'}
]
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(session({
name: SESS_NAME,
resave: false,
saveUninitialized: false,
secret: SESS_SECRET,
cookie:{
maxAge: SESS_LIFETIME,
sameSite: true,
secure: IN_PROD
}
}))
const redirectLogin = (req, res, next) => {
if(!req.session.userId){
res.redirect('/login')
} else{
next()
}
}
const redirectHome = (req, res, next) => {
if(!req.session.userId){
res.redirect('/home')
} else{
next()
}
}
app.get('/', (req, res) => {
const {userId} = req.session
//const userId = 1
res.send(`
<h1>Welcome!</h1>
${userId ? `
<a href='/home'>home</a>
<form method='post' action='/logout'>
<button>Logout</button>
</form>
` : `
<a href='/login'>Login</a>
<a href='/register'>Register</a>
`}
`)
})
app.get('/home', redirectLogin, (req, res) => {
res.send(`
<h1>Home</h1>
<a href='/'>Main</a>
<ul>
<li>Name:</li>
<li>Email:</li>
</ul>
`)
})
app.get('/login', redirectHome, (req, res) => {
res.send(`
<h1>Login</h1>
<form method='post' action='/login'>
<input type='email' name='email' placeholder='email' required />
<input type='password' name='password' placeholder='password' required />
<input type='submit' />
</form>
<a href='/register'>Register</a>
`)
})
app.get('/register', redirectHome, (req, res) => {
res.send(`
<h1>Register</h1>
<form method='post' action='/register'>
<input type='text' name='name' placeholder='name' required />
<input type='email' name='email' placeholder='email' required />
<input type='password' name='password' placeholder='password' required />
<input type='submit' />
</form>
<a href='/login'>Login</a>
`)
})
app.post('/login', redirectHome, (req, res) => {
const {email, password } = req.body
if(email && password) {
const user = users.find(user => user.email === email && user.password === password)
if(user) {
req.session.userId = user.id
return res.redirect('/home')
}
}
res.redirect('/login')
})
app.post('/register', redirectHome, (req, res) => {
const {name, email, password } = req.body
if(name && email && password) {
const exists = users.some(
user => user.email === email
)
if(!exists) {
const user = {
id: users.length + 1,
name,
email,
password
}
users.push(user)
req.session.userId = user.id
return res.redirect('/home')
}
}
res.redirect('/register')
})
app.post('/logout', redirectLogin, (req, res) => {
req.session.destroy(err => {
if(err){
return res.redirect('/home')
}
res.clearCookie(SESS_NAME)
res.redirect('/login')
})
})
app.listen(PORT, () => console.log(
`http://localhost:${PORT}`
))
// npm run dev
It is because there is a loop redirection path. If you try consolelog("Textsomething") at redirectHome and redirectLogin if statement, you will find a redirect loop.
One solution is to modify the logic of the redirection function, you can delete the exclamation point in the redirectHome if statement because it requires a user ID before the / home page can be accessed, etc.

How to authenticate user with company account on Actions on Google?

I'm building a 3rd server to authenticate users with company accounts on google action. I use account linking with OAuth, Linking type: Implicit. I used ngrok.io to build.
auth.js:
const jwtHelper = require("../helpers/jwt.helper");
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET || "xxx";
let auth = async (req, res) => {
try {
const userFakeData = {
email: req.body.email,
};
const accessToken = await jwtHelper.generateToken(userFakeData, accessTokenSecret);
return res.status(200).json({"token_type": "Bearer", accessToke);
} catch (error) {
return res.status(500).json(error);
}
}
login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login Form Tutorial</title>
</head>
<body>
<div class="login-form">
<h1>Login Form</h1>
<form action="login" method="POST">
<input type="text" name="email" placeholder="email" required>
<input type="submit">
</form>
</div>
</body>
</html>
jwt.helper.js
const jwt = require("jsonwebtoken");
let generateToken = (user, secretSignature, tokenLife) => {
return new Promise((resolve, reject) => {
const userData = {
email: user.email,
}
jwt.sign(
{data: userData},
secretSignature,
{
algorithm: "HS256",
expiresIn: tokenLife,
},
(error, token) => {
if (error) {
return reject(error);
}
resolve(token);
});
});
}
let verifyToken = (token, secretKey) => {
return new Promise((resolve, reject) => {
jwt.verify(token, secretKey, (error, decoded) => {
if (error) {
return reject(error);
}
resolve(decoded);
});
});
}
module.exports = {
generateToken: generateToken,
verifyToken: verifyToken,
};
middelware auth.js:
const jwtHelper = require('../helpers/jwt.helper');
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET || "xxx";
let isAuth = async(req, res, next) =>{
const tokenFromCLient = req.body.token || req.query.token || req.headers["access-token"];
if ( tokenFromCLient) {
//thuc hien giai ma xem co hop len khong
try{
const decode = await jwtHelper.verifyToken(tokenFromCLient, accessTokenSecret);
req.jwtDecoded = decode;
next();
}
catch (error) {
return res.status(401).json({ message: Unauthorized})
}
}
else {
return res.status(403).send({message: 'No token provided'})
}
}
module.exports = {
isAuth: isAuth
}
router.js
const express = require("express");
const router = express.Router();
const AuthMiddleWare = require("../middleware/auth");
const AuthController = require("../controllers/AuthController");
let initAPIs = (app) => {
router.post("/auth", AuthController.login);
router.use(AuthMiddleWare.isAuth);
return app.use("/", router);
}
module.exports = initAPIs;
server.js
const express = require("express");
const app = express();
const initAPIs = require("./routes/router");
var bodyParser = require('body-parser');
var path = require('path');
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/public/login.html'));
});
initAPIs(app);
app.listen(2310, () => {
console.log("server is working in localhost:2310")
})
My account linking setup
My Credentials Google Cloud :
This is what happened when I "talk to fun app"
After submit form :
Click link :
Click link:
Nothing happened in Google Console

NodeJS. Cannot get Credentials after auth login on client-side of React

I trying to understand what is the wrong with my credetrials inside my server code, because when I make Login from the client side, the credetrials does not recorgonizes inside the router.get('/auth/login') method, but when I do the same login action by the Postman with POST method and then reload the page with GET method the credetrials recorgonizes normally and I got the message, that I already loggined.
So, I actually want to say, that I do not have any problem with loginnig from the client side by "POST" method for router.post('/auth/login'), as for logs - user info transmits normally and credentials also creates, but on router.get('/auth/login') it does not callbacks in the res.json({session: req.session.userId, session2: req.session, log: 'You already logined!'});, where I gets just empty string...
My server code:
'use strict'
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
const bcrypt = require('bcrypt-nodejs');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const app = express();
const router = express.Router();
const EmployersSchemaDB = require('./SchemaDB/EmployersSchemaDB');
const User = require('./SchemaDB/ShemaAuthtificaion');
mongoose.connect('mongodb://myDB');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
res.setHeader('Cache-Control', 'no-cache');
next();
});
app.use(session({
secret: 'work hard',
resave: true,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
router.get('/', (req, res) => {
res.json('Hello on Homepage!');
});
router
.get('/auth/login', (req, res) => {
User.find((err, users) => {
if (err) { res.send(err) }
if (req.session.userId !== undefined) { // there is where I always falls...
res.json({session: req.session.userId, session2: req.session, log: 'You already logined!'});
} else {
console.log('User credentials!:', req.session.userId);
res.json({session: req.session.userId, session2: req.session});
console.log('---===--- \n Employers showed!: \n', users + '\n ---===---');
}
});
})
.post('/auth/login', (req, res, next) => {
if (req.body.password !== req.body.passwordConf) {
var err = new Error('Passwords do not match.');
err.status = 400;
res.send("passwords dont match");
return next(err);
}
if (req.body.email &&
req.body.username &&
req.body.password &&
req.body.passwordConf) {
let user = new User();
user.email = req.body.email;
user.username = req.body.username;
user.password = req.body.password;
user.passwordConf = req.body.passwordConf;
user.save((err) => {
if (err) { res.send(err) }
res.json({ message: 'Comment successfully added!', user });
console.log('---===--- \n Employer added: \n', user + '\n ---===---');
});
} else if (req.body.logemail && req.body.logpassword) {
User.authenticate(req.body.logemail, req.body.logpassword, function (error, user) {
if (error || !user) {
var err = new Error('Wrong email or password.');
err.status = 401;
return next(err);
} else { // this is the where credentials are creates. All work good!
req.session.userId = user._id;
console.log('Signed Cookies: ', req.session.userId, req.signedCookies)
console.log('User logined and redirected!');
return res.redirect('/employers');
}
});
} else {
var err = new Error('All fields required.');
err.status = 400;
return next(err);
}
});
app.use('/', router);
const port = process.env.API_PORT || 3016;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
My client code (just for info) : UPDATED FOR KEVIN
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import axios from 'axios';
class LoginPage extends Component {
constructor(props) {
super(props);
this.state = {
navigate: false
}
}
handleSubmit = (e) => {
e.preventDefault();
let userLogin = {
logemail: e.target.email.value,
logpassword: e.target.password.value
}
axios.post('http://localhost:3016/auth/login', userLogin)
.then(function(){
axios.get('http://localhost:3016/auth/login', {withCredentials: true})
.then(res => console.log(res.data))
.catch(err => console.log(err));
this.setState({
navigate: true
})
})
.catch(err => {
console.error(err);
});
};
render() {
// if (this.state.navigate) {
// return <Redirect to="/employers" />
// }
return (
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="exampleInputEmail1">Email address</label>
<input name="email" type="email" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" />
<small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div className="form-group">
<label htmlFor="exampleInputPassword1">Password</label>
<input name="password" type="password" className="form-control" id="exampleInputPassword1" placeholder="Password" />
</div>
<div className="form-check">
<input type="checkbox" className="form-check-input" id="exampleCheck1" />
<label className="form-check-label" htmlFor="exampleCheck1">Check me out</label>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
)
}
}
export default LoginPage;
This may be a cross domain problem as you can login successfully with Postman.
AJAX calls will not send cookies in CORS environment by default. You need to set the withCredentials field of XMLHttpRequest object as true to send cookies even cross domain. Here is the official document.
As you are using axios, hope this setting would be helpful.
axios.defaults.withCredentials = true;
Update:
Please update your client code and make sure GET /auth/login are requested after POST /auth/login are completed, otherwise the Get request might be sent while POST request has not complete authenticate and set session. I recommend you change your code like following (put Get request after POST request are resolved):
axios.post('http://localhost:3016/auth/login', userLogin)
.then(function(){
axios.get('http://localhost:3016/auth/login').then(res => console.log(res.data).catch(e => console.log(e));
this.setState({
navigate: true
})
})
.catch(err => {
console.error(err);
});
```

Resources