I am logging in successfully, however, I am getting unauthorized when I'm trying to access my authenticated-only route. I don't understand what I am doing wrong here, it successfully logs me in and returns the user, where am I wrong?
Here's my code:
This here is basically the server configuration for the backend.
server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors')
const passport = require('passport')
// passport
const cookieParser = require('cookie-parser')
const session = require('cookie-session')
const { COOKIE_NAME } = require('./client/src/common/config')
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB Config
const db = require ('./config/keys').mongoURI;
// Connect to MongoDB
mongoose
.connect(db, {useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false})
.then(() => console.log('Mongo DB Connected...'))
.catch(err => console.log(err));
// CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
const secret = process.env.APP_SECRET
const env = process.env.NODE_ENV || 'development'
const isLocal = env === 'development'
/* Session Setup */
app.use(cookieParser()) // read cookies (needed for auth)
if (!isLocal) {
app.set('trust proxy', 1)
}
app.use(
session({
httpOnly: false,
name: COOKIE_NAME,
keys: [secret],
secure: !isLocal,
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
})
)
/* Session management with Passport */
require('./passport')(passport)
app.use(passport.initialize())
app.use(passport.session())
// Register Schema
require('./models/User')
// Insert some default users
// require('./config/_insertDefaultUsers')
const patients = require('./routes/api/patients');
const auth = require('./routes/api/auth');
const drugs = require('./routes/api/drugs');
const trainees = require('./routes/api/trainees')
// Use Routes
app.use('/api/patients', patients);
app.use('/api/drugs', drugs);
app.use('/api/trainees', trainees)
app.use('/api/auth', auth);
app.use(cors())
// Connect to deployment port or localhost
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
access.js this is a basic middleware to check for authentication, so I can add it in my routes
const ROLES = require('.././client/src/common/roles')
/** Access middleware to ensure user is allowed to access certain routes */
const AccessMiddleware = {
hasAccess: (req, res, next) => {
if (!req.isAuthenticated()) {
req.session.redirectTo = req.originalUrl
return res.status(401).json({ success: false, error: 'unauthorized' })
}
next()
},
hasAdminAccess: (req, res, next) => {
if (!req.isAuthenticated() || req.user.role !== ROLES.ADMIN) {
req.session.redirectTo = req.originalUrl
return res.status(401).json({ success: false, error: 'unauthorized' })
}
next()
},
}
module.exports = AccessMiddleware
auth.js route and this is basically the authentication API which allows me to login and so on
const express = require('express');
const router = express.Router();
const passport = require('passport')
const AccessMiddleware = require('../../config/access')
const errorResponse = (res, error) => {
res.status(400).json({ success: false, error })
}
router.get('/test', (req, res) => {
res.json({ success: true, message: 'Test API route working fine!' })
})
router.get('/authenticated-only', AccessMiddleware.hasAccess, (req, res) => {
res.json({ success: true, message: 'You have auth access!' })
})
router.get('/admin-only', AccessMiddleware.hasAdminAccess, (req, res) => {
res.json({ success: true, message: 'You have admin access!' })
})
router.post('/login', (req, res, next) => {
const { email, password } = req.body
if (!email || !password) {
return errorResponse(res, 'Invalid credentials')
}
// Authenticate the user using the credentials provided
passport.authenticate('local', { session: true }, function (err, user) {
if (err) {
return errorResponse(res, 'Invalid credentials')
}
// When using passport with callback, we have to manually call req.login to set the Cookie
req.login(user, async () => {
res.json({ success: true, user })
})
})(req, res, next)
})
module.exports = router
exports.errorResponse = errorResponse
For anyone looking for a solution:
const secret = "secrethere"
app.use(cookieParser("secrethere"))
The issue seems to have been that I was not using the same secret within the server file.
Related
I can't get the logout function to work correctly and remove the session from the mongodb.
I'm able to store the session. logout was initially req.session.destroy(); but that kept returning an error. (destroy undefined)
I'm pretty new to nodejs/javascript, I'm trying to learn my apologies in advance for any ignorance!
Any help would be appreciated!!
app.js
const express = require('express'), url = require('url');
const path = require('path');
const dotenv = require('dotenv');
const connectToDatabase = require('./src/db/mongoose');
const helmet = require('helmet');
const router = require('./src/routes/routes');
const openApiDocumentation = require('./src/swagger/openApiDocumentation');
const swaggerUi = require('swagger-ui-express');
const cors = require('cors');
const bodyParser = require("body-parser");
var app = express();
const session = require('express-session');
const MongoStore = require('connect-mongo');
const port = process.env.PORT || 3000;
dotenv.config();
connectToDatabase(); //This removed to simplify the connection
app.use(express.json());
app.use(express.static('src/css'));
app.use(express.static('src/js'));
app.use(express.static('scripts'));
app.use(express.static('controllers'));
app.use(express.static(__dirname + '/views'));
app.use(express.static("views"));
app.use('/', express.static(path.join(__dirname, 'views'),{extensions:['html']}));
app.use('/api', swaggerUi.serve, swaggerUi.setup(openApiDocumentation));
app.use(function(req, res, next){
res.locals.user = req.user;
next();
});
app.use("/v1/login", session({
name: 'auth',
secret: 'mykey',
httpOnly: true,
secure: true,
maxAge: 1000 * 60 * 60 * 7,
resave: false,
saveUninitialized: true,
store: MongoStore.create({
mongoUrl: '<redacted>'
})
}));
app.get('/name', (req, res) => {
let name;
if (!req.session) {
return res.status(404).send();
}
name = req.session.user.name;
return res.status(200).send({name});
})
app.use(function (req, res, next) {
res.locals.session = req.session;
next();
});
router.get("/vl/login", function(req, res) {
if (
typeof reqsession.user != "object" || (
typeof req.session.user.name == "undefined" &&
typeof req.session.user.password == "undefined")
) {
res.render("pages/index");
}
res.redirect("Login");
});
app.use(function(req, res, next) {
console.log('%s %s', req.method, req.url);
next();
});
app.engine('.html', require('ejs').__express);
app.set('view engine', 'ejs');
// index page
app.get('/', function(req, res) {
res.render('pages/index');
});
// about page
app.get('/about', function(req, res) {
res.render('pages/about');
});
app.use(function(req, res, next){
res.locals.user = req.user;
next();
});
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(helmet());
app.use('/v1', router);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.listen(port, () => console.log(`Server is running on Port: ${port}`));
userController.js
login: async (req, res) => {
const { userName, password } = req.body
const user = await userModel.findOne({ userName }).lean()
if (!user) {
return res.json({ status: 'error', error: 'Invalid username/password' })
}
if (await bcrypt.compare(password, user.password)) {
// the username, password combination is successful
const token = jwt.sign(
{
id: userModel._id,
userName: userModel.userName
},
JWT_SECRET
)
const { name } = req.body;
req.session.user = {
name,
isLoggedIn: true
}
try {
await req.session.save();
} catch (err) {
console.error('Error saving to session storage: ', err);
return next(new Error('Error creating user'));
}
return res.json({ status: 'ok', data: token })
}
res.json({ status: 'error', error: 'Invalid username/password' })
},
logout: async (req, res, next) => {
try {
await await req.session == null;
} catch (err) {
console.error('Error logging out:', err);
return next(new Error('Error logging out'));
}
return res.json({ status: 'ok'})
},
routes.js
const express = require('express');
const router = express.Router();
const newUser = require('../controllers/userController');
const company = require('../controllers/companyController');
const upload = require('../controllers/upload');
const auth = require('../middleware/auth');
/* GET response for '/'/*
router.get('/', (req, res) => {
res.redirect('/');
}) */
//generate token
router.get('/token', newUser.generateToken);
//login
router.post('/login', newUser.login);
//logout
router.post('/logout', newUser.logout);
//create service user
router.post('/addServiceUser', newUser.addServiceUser);
//Add user
router.post('/users', newUser.addUser);
//remove user
router.delete('/users/:id',auth, newUser.removeUser);
//Get All users
router.get('/users',auth, newUser.getAllUsers);
//Get User
router.get('/user/:id',auth, newUser.getUser);
//Get first name
router.get('/users/:id/firstName',auth, newUser.getUserFirstName);
//Set first name
router.put('/users/:id/firstName',auth, newUser.setUserFirstName);
//Get last name
router.get('/users/:id/lastName',auth, newUser.getUserLastName);
//Set last name
router.put('/users/:id/lastName',auth, newUser.setUserLastName);
//Get user email
router.get('/users/:id/email',auth, newUser.getUserEmail);
//set user email
router.put('/users/:id/email',auth, newUser.setUserEmail);
//Get user phone
router.get('/users/:id/phone',auth, newUser.getUserPhone);
//set user phone
router.put('/users/:id/phone',auth, newUser.setUserPhone);
//get user age
router.get('/users/:id/age',auth, newUser.getUserAge);
//set user age
router.put('/users/:id/age',auth, newUser.setUserAge);
//set user status
router.put('/users/:id/status',auth, newUser.setUserStatus);
//get user status
router.get('/users/:id/status',auth, newUser.getUserStatus);
//set user level
router.put('/users/:id/level',auth, newUser.setUserLevel);
//get user level
router.get('/users/:id/level',auth, newUser.getUserLevel);
//get user gender
router.get('/users/:id/gender',auth, newUser.getUserGender);
//set user gender
router.put('/users/:id/gender',auth, newUser.setUserGender);
//set user address
router.put('/users/:id/address',auth, newUser.setUserAddress);
//get user address
router.get('/users/:id/address',auth, newUser.getUserAddress);
//get active users
router.get('/users/status/active',auth, newUser.getActiveUsers);
//get inactive users
router.get('/users/status/inactive',auth, newUser.getInActiveUsers);
//get non admin users
router.get('/users/level/intern',auth, newUser.getInternUsers);
//get mentor users
router.get('/users/level/mentor',auth, newUser.getMentorUsers);
//Get Avatar
router.get('/users/:id/avatar',auth, newUser.getUserAvatar);
//Set Avatar
router.put('/users/:id/avatar',auth, upload.single('avatar'), newUser.setUserAvatar);
//Delete Avatar
router.delete('/users/:id/avatar',auth, newUser.removeUserAvatar);
//Add Companies
router.post('/companies/:id/team', auth, company.setUserTeamName);
module.exports= router;
It looks like in your logout function, the way your attempting to "logout" the user is setting req.session to null.
As you've figured out this doesn't act how you've expected. The correct way to logout a user would be calling req.session.destroy() usually accompanied by a redirect back to the login page:
return res.redirect("/login");
This will completely remove or, destroy the session and log the user out.
So I am following a tutorial on how to use JSON tokens and I am getting an error, it was working fine using sessions but I can't figure out why I am having trouble, it is the exact code
this is my authenticate.js file:
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const User = require("./models/user");
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const jwt = require("jsonwebtoken"); // used to create, sign, and verify tokens
const config = require("./config.js");
exports.local = passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
exports.getToken = function (user) {
return jwt.sign(user, config.secretKey, { expiresIn: 3600 });
}; // config.secretKey is a string of random numbers
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secretKey;
exports.jwtPassport = passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
console.log("JWT payload:", jwt_payload);
User.findOne({ _id: jwt_payload._id }, (err, user) => {
if (err) {
return done(err, false);
} else if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
})
);
exports.verifyUser = passport.authenticate("jwt", { session: false });
This is my app.js file (the main file):
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const logger = require("morgan");
const config = require("./config");
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const mongoose = require("mongoose");
const passport = require("passport");
const url = config.mongoUrl;
const connect = mongoose.connect(url, {
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
});
connect.then(
() => console.log("Connected correctly to server"),
(err) => console.log(err)
);
const app = express();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser("12345-67890-09876-54321"));
app.use(passport.initialize());
app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use(express.static(path.join(__dirname, "public")));
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
module.exports = app;
this is the routes/users.js file (I believe the problem is here because I can sign-up (create new users) but I can't login with the same users)
const express = require("express");
const User = require("../models/user");
const passport = require("passport");
const authenticate = require("../authenticate");
const router = express.Router();
/* GET users listing. */
router.get(
"/",
function (req, res, next) {
res.send('send users')
}
);
router.post("/signup", (req, res) => {
User.register(
new User({ username: req.body.username }),
req.body.password,
(err, user) => {
if (err) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.json({ err: err });
} else {
if (req.body.firstname) {
user.firstname = req.body.firstname;
}
if (req.body.lastname) {
user.lastname = req.body.lastname;
}
user.save((err) => {
if (err) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.json({ err: err });
return;
}
passport.authenticate("local")(req, res, () => {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json({
success: true,
status: "Registration Successful!",
});
});
});
}
}
);
});
// I tried to add a console.log inside of the .post() route but it never reach it
router.post(
"/login",
passport.authenticate("local"),
(req, res) => {
const token = authenticate.getToken({ _id: req.user._id });
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json({
success: true,
token: token,
status: "You are successfully logged in!",
});
}
);
router.get("/logout", (req, res, next) => {
if (req.session) {
req.session.destroy();
res.clearCookie("session-id");
res.redirect("/");
} else {
const err = new Error("You are not logged in!");
err.status = 401;
return next(err);
}
});
module.exports = router;
Basically, every time that i go to localhost:3000/users/login and send a POST request with the username and password, it tells me that I need to use express-session but I am trying to use tokens instead of session
The problem is caused when passport.authenticate('local') is called in routes/users.js file. It is a middleware that automatically calls req.login function in case correct username and password is provided.
The req.login() in turn, implements sessions in order to serialise the user in the session.
You can solve the issue by adding another parameter to passport.authenticate() as passport.authenticate('local', {session: false}. This ensures sessions are not implemented in the 'local' strategy and subsequently login can be performed.
Thanks, it helped me. You have to remove app.use(passort.session) from app.js and do
router.post('/login', passport.authenticate('local', { session: false }), (req, res) => {
var token = authenticate.getToken({ _id: req.user._id });
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({ success: true, token: token, status: 'You are successfully logged in!' });
});
I am trying to access the req.user that passport creates when doing a google o auth strategy. I can access the req.user in the routes file below, but when I try to access it in my userController file it is showing up as undefined.
Why is user accessible in routes file but not userController?
googleAuthRoutes.js:
const passport = require('passport');
const requireLogin = require('../middlewares/requireLogin')
const cors = require('cors');
const axios = require('axios');
const Template = require('../models/Template');
const corsOptions ={
origin: true,
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200
}
module.exports = app => {
app.get('/auth/google',
passport.authenticate('google', {
scope: ['profile', 'email']
}));
app.get(
'/auth/google/callback',
passport.authenticate('google'),
(req, res) => {
res.redirect('/dashboard');
}
);
app.post('/templates/create', async (req, res) => {
const { template, body } = req.body
console.log(req.user)
const newTemplate = new Template({
template: template,
body: body,
_user: req.user.id
})
try {
await newTemplate.save()
return res.status(200).json({
message: "Successfully saved template"
})
} catch (err) {
return console.log(err)
}
});
app.get('/api/logout', cors(), (req, res) => {
req.logout();
res.redirect('http://localhost:3000');
});
app.get('/api/current_user', (req, res) => {
res.send(req.user);
})
}
when I call the res.send(req.user) here above it sends the user no problem
But it is undefined with the /templates/create route middleware.
the console.log(req.user) is coming back as undefined??
index.js:
const express = require('express');
const cors = require('cors')
const mongoose = require('mongoose');
const cookieSession = require('cookie-session');
const passport = require('passport');
const keys = require('./config/keys');
const bodyParser = require('body-parser')
require("dotenv").config();
require('./models/GoogleUserModel'); // the user model must be placed before this services passport// this must be ran after requiring model bcuz this needs the model. ORDER
require('./models/UserModel');
require('./services/passport');
const corsOptions ={
origin:'http://localhost:3000',
credentials: true, //access-control-allow-credentials:true
optionSuccessStatus:200
}
const app = express();
app.use(cors(corsOptions))
mongoose.connect(keys.mongoURI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
mongoose.connection.on('error', () => {
throw new Error (`unable to connect to database: ${keys.mongoURI}`)
});
app.use(bodyParser.json())
app.use(express.urlencoded( { extended: true }))
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.cookieKey]
})
)
app.use(passport.initialize());
app.use(passport.session());
require('./routes/userRoutes')(app);
require('./routes/googleAuthRoutes')(app);
require('./routes/messageRoutes')(app);
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
res.status(401).json({"error" : err.name + ": " + err.message})
} else if (err) {
res.status(400).json({"error" : err.name + ": " + err.message})
console.log(err)
}
})
const PORT = process.env.PORT || 5000;
app.listen(PORT);
Again, Why is the req.user available in the app.get to /api/current_user but available in a post request to /templates/create?
Im trying to add the user.id to the schema when it saves so i can retrieve each template by the user.id and not show everyone everybody elses templates lol
I want to send a variable value after succesful register but i have to do that without using res.render because i have some of flash messages if i want to show all of them i have to use res.redirect otherwise it does not work for example : who will try to register the flash message show "you cant use a password less than 6 character". How can i passs variable value to my ejs page for hide or display some of nav bar links according to after login or register or logout
// Here is my app.js file
// Config folder
require('dotenv').config();
const port = process.env.port;
const dbUrl = process.env.dbUrl;
// İmport required npms
const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
const connectMongo = require('connect-mongo');
const flash = require("connect-flash");
const passport = require("passport");
const app = express();
// Passport Config
require("./config/passport")(passport);
// Db Connection And Permissions
mongoose.connect(dbUrl, {
useNewUrlParser: process.env.useNewUrlParser,
useUnifiedTopology: process.env.useUnifiedTopology,
useCreateIndex: process.env.useCreateIndex
});
// Express-Session Settings , Permanenet Session
const mongoStore = connectMongo(session);
app.set('trustproxy', true)
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
store: new mongoStore({ mongooseConnection: mongoose.connection }),
cookie: {
maxAge: 86400000
}
}));
// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
// The Navbar Display Links According To Log in
app.use((req, res, next) => {
const userId = req.session;
if (userId) {
res.locals = {
displayLink: true
}
} else {
res.locals = {
displayLink: false
}
}
next();
});
// Set ejs settings, middleware, static folders
app.use(express.static("public"));
app.set("view engine", "ejs");
// Connect flash
app.use(flash());
// Global variables
app.use((req, res, next) => {
res.locals.success_msg = req.flash("success_msg");
res.locals.error_msg = req.flash("error_msg");
res.locals.error = req.flash("error");
next();
});
// Import Pages
const index = require("./routes");
const user = require("./routes/user");
// Routes
app.use("/", index);
app.use("/user", user);
app.listen(port, (err) => { if (err) throw err; console.log("No problem"); });
// Here is my user.js file
const express = require("express");
const router = express.Router();
const User = require("../models/User");
const bcrypt = require("bcrypt")
const bodyParser = require('body-parser');
const passsport = require("passport");
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
// Users Routing Operations
// Get Requests
// Login Page
router.get("/login", (req, res) => {
res.render("pages/login");
});
// Register Page
router.get("/register", (req, res) => {
res.render("pages/register");
});
// Post Requests
// After Finishing Register
router.post("/register", async (req, res) => {
const { name, email, password, rptPassword } = req.body;
let errors = [];
// Check required fields
if (!name || !email || !password || !rptPassword) {
errors.push({ msg: "Lütfen bütün alanları doldurunuz" });
}
// Check passwords match
if (password !== rptPassword) {
errors.push({ msg: "Şifreler eşleşmiyor" });
}
// Check password length
if (password.length < 6) {
errors.push({ msg: "Şifreniz en az 6 karakterden oluşmalı" });
}
if (errors.length > 0) {
res.render("pages/register", {
errors,
name,
email,
password,
rptPassword
});
} else {
User.findOne({ email: req.body.email }).then(async (user) => {
if (!user) { // If user doesnt exist before
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
req.body.password = hashedPassword;
User.create(req.body, () => { });
req.flash("success_msg", "Kayıt Tamamlandı");
res.redirect("/user/register");
} else { // If user already exist
errors.push({ msg: "Bu Email adresi kullanımda" })
res.render("pages/register", {
errors,
name,
email,
password,
rptPassword
});
res.redirect("/user/register");
}
});
}
});
// Login handle
router.post("/login", (req, res, next) => {
passsport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/user/login",
failureFlash: true
})(req, res, next);
});
// After Loging Out
router.get("/logout", (req, res) => {
req.logout();
req.flash("success_msg", "Çıkış Yaptınız");
res.redirect("/user/login");
});
module.exports = router;
I think one of the solutions for that is to use multiple query strings
and then you can handle the errors in the app.get functions like so
router.post("/register", async (req, res) => {
const { name, email, password, rptPassword } = req.body;
// Check required fields
if (!name || !email || !password || !rptPassword) {
res.redirect('/register?error=error-1')
}
then in the handle it like so
// Register Page
router.get("/register", (req, res) => {
if (req.query.error === 'error-1' )
res.render("pages/register" ,{
msg: "Lütfen bütün alanları doldurunuz"
});
});
and so you can handle all errors by giving them unique code
I have some problems with the express session where I cannot retrieve my session variable that I had stored previously. Below are parts of my codes that I had written.
server.js
let express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
config = require('./config/database'),
expressSession = require('express-session'),
uid = require('uid-safe'),
db;
let app = express();
//Import Routes
let auth = require('./routes/auth'),
chimerListing = require('./routes/chimer-listing'),
brandListing = require('./routes/brand-listing');
//Specifies the port number
let port = process.env.PORT || 3000;
// let port = 3000;
// Express session
app.use(expressSession({
secret: "asdasd",
resave: true,
saveUninitialized: false,
cookie: {
maxAge: 36000000,
secure: false
}
}));
//CORS Middleware
app.use(cors());
//Set Static Folder
var distDir = __dirname + "/dist/";
app.use(express.static(distDir));
//Body Parser Middleware
app.use(bodyParser.json());
//MongoDB
let MongoClient = require('mongodb').MongoClient;
MongoClient.connect(config.database, (err, database) => {
if (err) return console.log(err)
db = database;
//Start the server only the connection to database is successful
app.listen(port, () => {
console.log('Server started on port' + port);
});
});
//Make db accessbile to routers;
app.use(function(req, res, next) {
req.db = db;
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.set('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//Routes
app.use('/login', auth);
app.use('/user-listing', userListing);
app.use('/brand-listing', brandListing);
//Index Route
app.get('/', (req, res) => {
res.send('Invalid Endpoint');
});
genuuid = function() {
return uid.sync(18);
};
auth.js
let express = require('express'),
router = express.Router(),
db;
//Login Router for chimer
router.post('/chimer', (req, res, next) => {
db = req.db;
// let client = req.client;
db.collection('chimeUser').find({
Username: req.body.username,
Password: req.body.password
}).toArray().then(function(docs) {
//If there is such user
if (docs.length >= 1) {
req.session.chimerId = docs[0]._id;
console.log(req.session);
req.session.save(function(err) {
// session saved
if (err)
console.log(err)
res.json({
success: true,
chimerId: docs[0]._id
//objects: docs
});
})
} else {
res.json({
success: false,
//objects: docs
})
}
});
});
//Login Router brand
router.post('/brand', (req, res, next) => {
db = req.db;
db.collection('brand').find({
Username: req.body.username,
Password: req.body.password
}).toArray().then(function(docs) {
req.session.brand = docs;
console.log(req.session.brand);
//If there is such user
if (docs.length >= 1) {
res.json({
success: true,
//objects: docs
})
} else {
res.json({
success: false,
//objects: docs
})
}
//db.close()
});
});
});
module.exports = router;
user-listing.js
let express = require('express'),
moment = require('moment'),
router = express.Router(),
// ObjectID = require('mongodb').ObjectID,
db, client;
// let applyListing = require('../models/chimer-listing');
//Retrieve All Listing
router.get('/getAllListing', (req, res, next) => {
db = req.db;
console.log(req.session)
db.collection('listing').find().toArray().then(function(listing) {
//If there is any listing
if (listing.length >= 1) {
res.json({
success: true,
results: listing
})
} else {
res.json({
success: false,
})
}
//db.close()
});
});
module.exports = router;
So in my server.js, I have three routes file which is auth, user-listing, and brand-listing.
Firstly, a user will need to login with the web application which is developed in angular2 and this will trigger the auth route. It will then check for the credentials whether does it exist in the database if it exists I will then assign an ID to req.session.chimerId so that in other routes I will be able to use this chimerId.
Next, after the user has logged in, they will then retrieve an item listing. The problem arises where I can't seem to retrieve the req.session.chimerId that I had previously saved. It will be undefined
NOTE: I tried this using Postman and the browser. In the Postman it works, I am able to retrieve back the req.session.chimerId whereas when I use the angular2 application to hit the endpoints req.session.chimerId is always null