Authentication failure when using express-session - node.js

I wrote some code for login authentication using express. I used express-session. Code sample is
// Authentication and Authorization Middleware
var auth = function(req, res, next) {
if (req.session && req.session.admin) {
return next();
} else {
console.log("failed");
return res.sendStatus(401);
}
}
// Login endpoint
router.post('/login', function (req, res) {
var collection = db.get("login");
collection.find({}, function(err, details) {
if (!req.body.username || !req.body.password) {
res.send('login failed');
} else if(req.body.username === details[0].name && req.body.password === details[0].password ) {
req.session.admin = true;
var data = {
"status": "success",
"message": "login success!"
}
res.send(data);
} else {
var data = {
"status": "failure",
"message": "login failed"
}
res.send(data);
}
});
});
// Logout endpoint
router.get('/logout', auth, function (req, res) {
req.session.destroy();
res.send("logout success!");
});
//Getting Details endpoint
router.get("/data", auth, function(req, res) {
var collection = db.get('details');
collection.find({}, function(err, details){
if (err) throw err;
res.json(details);
});
});
After successful login req.session.admin is set to true. But, at Authentication middleware (auth), it is sending 401 status. Please help me solve this problem.
code:
//app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var getDetails = require('./routes/getDetails');
var app = express();
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
// view engine setup
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.cookieParser());
app.use(express.static(path.join(__dirname, 'routes')));
app.use(express.session({
secret: '2C44-4D44-WppQ38S',
resave: true,
saveUninitialized: true
}));
app.use('/getDetails',getDetails);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
//app.listen(3001);
module.exports = app;
//getDetails.js
var express = require('express');
var router = express.Router();
var monk = require('monk');
var db = monk('localhost:27017/saidb');
// Login endpoint
router.post('/login', function (req, res) {
var collection = db.get("login");
//var data;
collection.find({}, function(err, details) {
//res.json(details);
if (!req.body.username || !req.body.password) {
res.send('login failed');
} else if(req.body.username === details[0].name && req.body.password === details[0].password ) {
req.session.admin = true;
var data = {
"status": "success",
"message": "login success!"
}
res.send(data);
} else {
var data = {
"status": "failure",
"message": "login failed"
}
res.send(data);
}
});
});
var auth = function(req, res, next) {
if (req.session && req.session.admin) {
console.log("success");
return next();
} else {
console.log("failed");
return res.sendStatus(401);
}
}
// Logout endpoint
router.get('/logout', auth, function (req, res) {
req.session.destroy();
res.send("logout success!");
});
//Getting Details endpoint
router.get("/data", auth, function(req, res) {
var collection = db.get('details');
collection.find({}, function(err, details){
if (err) throw err;
res.json(details);
});
});
//Get details by ID endpoint
router.get("/data:id", auth, function(req, res) {
var collection = db.get('details');
collection.find({id: parseInt(req.params.id)}, function(err, details){
if (err) throw err;
res.json(details);
});
});
//Adding Details endpoint
router.post("/data", auth, function(req, res) {
var collection = db.get("details");
collection.count({id : parseInt(req.body.id)},function(err,count){
if(!err){
if(count>0){
//send the response that its duplicate.
//console.log(errorororrrroror);
res.send("r");
}
}
});
console.log("request", req.body);
collection.insert({ id: parseInt(req.body.id),
website: req.body.website,
subtitle: req.body.subtitle,
url: req.body.url },
function(err, details) {
if(err) throw err;
res.json(details);
})
});
//Editing Details endpoint
router.put("/data", auth, function(req,res){
var collection = db.get("details");
collection.update({id: parseInt(req.body.id)},
{id: parseInt(req.body.id), website: req.body.website, subtitle: req.body.subtitle, url: req.body.url},
function(err, details){
if(err) throw err;
res.json(details);
})
});
//Deleting details endpoint
router.delete("/data", auth, function(req,res){
var collection = db.get("details");
collection.remove({id: parseInt(req.body.id)}, function(err, details){
if(err) throw err;
res.json(details);
})
});
module.exports = router;

Use these lines in your server file at top after express object like this
var app = express();
app.use(express.cookieParser());
app.use(express.session({secret: "sdsddsd23232323" }));

Related

MongoDB/Mongoose Security for a MERN Stack [duplicate]

I have set up a web application with some internal pages requiring a login. I used Node with Express.js to set up the server and controlling the routes and authentication works fine.
I came up to a #zanko suggestion in a question related to the same application to avoid the replication of the authentication code in the route of every page, like is now.
At the moment my app.js looks like this (the following is an excerpt):
var session = require('express-session');
//use sessions for tracking logins
app.use(session({
secret: 'mercuia',
resave: true,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: db
})
}));
// serve static files from template
app.use(express.static(__dirname + '/public'));
// include routes
var routes = require('./routes/router');
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('File Not Found');
err.status = 404;
next(err);
});
// error handler
// define as the last app.use callback
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send(err.message);
});
and my authentication method (in routes.js) looks like this (in the example, for the route /clientPage):
// GET route after registering
router.get('/clientPage', function (req, res, next) {
User.findById(req.session.userId)
.exec(function (error, user) {
if (error) {
return next(error);
} else {
if (user === null) {
var err = new Error('Not authorized! Go back!');
err.status = 400;
return next(err);
} else {
return res.sendFile(path.join(__dirname + '/../views/clientPage.html'));
}
}
});
});
How can I write an authentication middleware instead (using the same logic) and call it for all and only the requiring routes?
You can create a new module called auth.js and then use it to check if users are authorized or not:
auth.js
module.exports.isAuthorized = function(req, res, next) {
User.findById(req.session.userId).exec(function (error, user) {
if (error) {
return next(error);
} else {
if (user === null) {
var err = new Error('Not authorized! Go back!');
err.status = 401;
return next(err);
} else {
return next();
}
}
});
}
routes.js
var auth = require('./auth');
// GET route after registering
router.get('/clientPage', auth.isAuthorized, function (req, res, next) {
res.sendFile(path.join(__dirname + '/../views/clientPage.html'));
});
Create a module (a file that exports a function, in this case a middleware function). A middleware function has following signature function (req, res, next) { .... }
restrict.js
module.exports = function (req, res, next) {
User.findById(req.session.userId)
.exec(function (error, user) {
if (error) {
return next(error);
} else {
if (user === null) {
const err = new Error("Not authorized! Go back!");
err.status = 400;
return next(err); // This will be caught by error handler
} else {
return next(); // No error proceed to next middleware
}
}
});
};
app.js
// serve static files from template
app.use(express.static(__dirname + '/public'));
// include routes
const routes = require('./routes/router');
//If you have a more granular route you can split it
const someOtherRoute = require('./routes/someotherRoute');
const restrictMiddleware = require("./restrict");
app.use("/", someOtherRoute); // this route will not be check for authorization
app.use(restrictMiddleware);
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
const err = new Error('File Not Found');
err.status = 404;
next(err);
});
// error handler
// define as the last app.use callback
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send(err.message);
});
I would use const and let if your environment support it. Its 2017 :)

authenticate.getToken is not a function on node.js v12.18.2

I am receiving an authenticate.getToken is not a function error.
var express = require('express');
const bodyParser = require('body-parser');
var User = require('../models/user');
const passport = require('passport');
var authenticate = require('../authenticate');
var router = express.Router();
router.use(bodyParser.json());
/* GET users listing. */
router.get('/', function (req, res, next) {
res.send('respond with a resource');
});
router.post('/signup', (req, res, next) => {
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 {
passport.authenticate('local')(req, res, () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({ success: true, status: 'Registration Successful!' });
});
}
}
);
});
router.post('/login', passport.authenticate('local'), (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!' });
});
router.get('/logout', (req, res) => {
if (req.session) { req.session.destroy();
res.clearCookie('session-id');
res.redirect('/');
} else {
var err = new Error('you are not logged in');
err.status = 403;
next(err);
}
});
module.exports = router;
The error simply means that authenticate.getToken is not a function. have you exported correctly in your authenticate.js file? It may be worth posting your authenticate.js file to your OP.
It should look something like this for it to work:
authenticate.js
module.exports = {
getToken: function() {
// code here
}
}

NodeJS app using CSRF for web and JWT for API does async.parallel out of order

When a logged-in user gets to a page through the browser using EJS I'm able to get the function to do what it's supposed to but when I use the API with Ionic using a logged in user with JWT, the async.parallel function doesn't "wait" to do things in order.
Here is my function:
console.log('1');
async.parallel([
function(callback){
buildAlertButtonsArray.getRealTestAlerts(req,function(arrayAlerts) {
console.log('2');
callback(null, arrayAlerts);
});
},
function(callback) {
if(req.decoded) //API
callback('API');
else //EJS
functions.aclSideMenu(req, res, function (acl) {callback(null, acl);}); //aclPermissions sideMenu
}
],function(err, results){
console.log('3');
})
when I login through the browsed on my console.log() is 1, 2, 3 but when I login through the API using JWT I get 1, 3, 2.
Here is my app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var bluebird = require('bluebird');
//me
var mongoose = require('mongoose');
var db = mongoose.connection;
var cors = require('cors');
var session = require('client-sessions');
var flash = require('express-flash');
//.js file
var routesApi = require('./routes/api');
var routesEjs = require('./routes/ejs');
var routes = require('./routes/index');
//var login = require('./routes/authentication/login');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(cookieParser());
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true })); //was FALSE by default. was TRUE for auth Template
// middleware
app.use(session({
cookieName: 'session',
secret: 'mysecret',
duration: 30 * 60 * 1000,
activeDuration: 30 * 60 * 1000,
httpOnly: true, //doesn't let javascript access cookies ever
secure: true, // only use cookies over https
ephemeral: true // delete this cookie when the browser is closed (nice when people use public computers)
}));
app.use(flash());
app.use(function(req, res, next){
res.locals.success_messages = req.flash('success_messages');
res.locals.error_messages = req.flash('error_messages');
next();
});
// use cors
app.use(cors());
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/api', routesApi);
app.use('/', routes);
app.use('/', routesEjs);
//bluebird
mongoose.Promise = require('bluebird');
//connecting to database
mongoose.connect('mongodb://myip:2999/SMECS_database', { useMongoClient: true });
//if we connect successfully or if a connection error occurs
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
// yay!
});
// error handlers
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Here is my Login function for both EJS using CSRF and API using JWT:
module.exports.postLogin = function(req, res, next) {
if (req.body.pushToken) { // run SMECS API
models.Users.findOne({
email: req.body.email.toLowerCase()
}, function (err, user) {
if (err) throw err;
if (!user) {
res.json({success: false, message: 'Authentication failed. User not found.'});
} else if (user) {
//check if password matches
if (!bcrypt.compareSync(req.body.pin, user.pin)) {
res.json({success: false, message: 'Authentication failed. Wrong password.'});
} else {
// if user is found and password is right
// create a token
var token = jwt.sign({user: user}, config.secret, {
//expiresIn: 1440 // expires in 24 hours
});
user.save(function (err) {
if (err) {
res.json({
success: false,
message: 'contact your system administrator. pushToken not saved'
});
} else {
// return the information including token as JSON
res.json({
success: true,
message: 'Welcome aboard!',
token: token,
userRoleID: user.userRoleID,
userRoleName: user.userRoleName,
userPrivilegeID: user.userPrivilegeID,
userPrivilegeName: user.userPrivilegeName,
firstName: user.firstName,
lastName: user.lastName,
email: user.email
});
}
});
}
}
});
}
else { //run SMECS EJS
models.Users.findOne({email: req.body.email.toLowerCase()}, function (err, user) {
if (!user || user.softDeleted !== null) {
//Parent Self Registration Login
models.ParentSelfRegistration.findOne({email: req.body.email.toLowerCase()}, function (err, parentSelfRegistration) {
if (!parentSelfRegistration) {
res.render('login', {error: "ERROR: Incorrect email or pin.", csrfToken: req.csrfToken()});
} else {
if (req.body.pin == parentSelfRegistration.pin) {
req.session.user = parentSelfRegistration;
res.redirect('/parentsSelfRegistration/registerParentStep1');
} else {
res.render('login', {error: "ERROR: Incorrect email or pin.", csrfToken: req.csrfToken()});
}
}
});
//END OF checks for users in UtilityUsers database
} else {
if (bcrypt.compareSync(req.body.pin, user.pin)) { // if user is found and password is right
req.session.user = user;
res.redirect('/dashboard');
//}
} else {
//res.status(400).send('Current password does not match');
res.render('login', {error: "ERROR: Incorrect email or pin.", csrfToken: req.csrfToken()});
//res.render('login', { error: "ERROR: Incorrect email or pin."});
}
}
});
}
};
Here is my ejs.js file:
//Dependencies
var express = require('express');
var routerEjs = express.Router();
var login = require('./authentication/login');
var auth = require('./authentication/auth');
var chooseAlert = require('./alerts/sendingReceiving/1.chooseAlert');
var login = require('./authentication/login');
var csrf = require('csurf');
routerEjs.use(csrf());
/* GET login page. */
routerEjs.get('/login', login.getLogin, function(req, res) {});
routerEjs.post('/login', login.postLogin, function(req, res) {});
routerEjs.get('/logout', login.getLogout, function(req, res) {});
module.exports = routerEjs;
and my api.js file:
//Dependencies
var express = require('express');
var routerApi = express.Router();
var login = require('./authentication/login');
var auth = require('./authentication/auth');
var chooseAlert = require('./alerts/sendingReceiving/1.chooseAlert');
routerApi.post('/login', login.postLogin, function(req, res) {});
routerApi.get('/chooseGroup', auth.auth, chooseAlert.showGroups, function(req, res) {});
routerApi.get('/alerts/sending/chooseAlert', auth.auth, chooseAlert.showAlerts, function(req, res) {});
/* Update pushToken ------------------------------------*/
routerApi.post('/updatePushToken', auth.auth, auth.pin, function(req, res) {});
module.exports = routerApi;
I figured out my problem. I was missing a NULL on my callback...
console.log('1');
async.parallel([
function(callback){
buildAlertButtonsArray.getRealTestAlerts(req,function(arrayAlerts) {
console.log('2');
callback(null, arrayAlerts);
});
},
function(callback) {
if(req.decoded) //API
callback(NULL, 'API');
else //EJS
functions.aclSideMenu(req, res, function (acl) {callback(null, acl);}); //aclPermissions sideMenu
}
],function(err, results){
console.log('3');
})

Cannot retrieve session using express js

I am having trouble accessing already saved in MongoStore session. In short the algorithm is: client(http://localhost:8080) sends POST request to the server (http://localhost:3000/); the program successfully creates session, registers/logins user and after that redirects to client (http://localhost:8080/finish-registration) and that page in turn makes another POST request (http://localhost:3000/s) which tries to retrieve session, but it is unavailable as
router.post('/s', function(req, res) {
console.log('ID in POST: ', req.session.userId);
});
returns undefined.
Below is my server setup. For the backend I use expressjs, express-session, mongostore, frontend: React with axios to send requests. Does anyone know where I am doing a mistake? thanks
server.js:
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const routes = require('./routes/router');
// connect to MongoDB
mongoose.connect('mongodb://localhost/testForAuth');
const db = mongoose.connection;
// handle mongo error
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', () => {
console.log('we are connected');
});
// use sessions for tracking logins
app.use(
session({
secret: 'work_hard',
resave: true,
saveUninitialized: true,
store: new MongoStore({
mongooseConnection: db
})
})
);
app.use(function(req, res, next) {
// Website you wish to allow to connect
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
// parse incoming requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// serve static files from template
app.use(express.static(__dirname + ''));
// include routes
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
const err = new Error('File not found');
err.status = 400;
next(err);
});
// error handler
// define as the last app.use callback
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.send(err.message);
});
// listen on port 3000
app.listen(3000, () => {
console.log('Express app listening on port 3000');
});
routes/router.js:
const express = require('express');
const router = express();
const cors = require('cors');
const fs = require('fs');
const User = require('../models/user.js');
// POST route for updating data
router.post('/', function(req, res, next) {
if (req.body.email && req.body.password && req.body.confirmPassword) {
if (req.body.password !== req.body.confirmPassword) {
var err = new Error('Passwords do not match');
err.status = 400;
res.send('Passwords do not match');
return next(err);
} else {
console.log(req.body.email, req.body.password);
var userData = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
registrationFinished: false
};
User.create(userData, function(error, user) {
if (error) {
console.log("COULDN't create user");
return next(error);
} else {
console.log('ADDED NEW USER');
req.session.userId = user._id;
return res.redirect('/profile');
}
});
}
} else if (req.body.email && req.body.password) {
User.authenticate(req.body.email, req.body.password, function(error, user) {
if (error || !user) {
var err = new Error('Wrong email or password');
err.status = 401;
return next(err);
} else {
console.log('LOGIN!!!');
req.session.userId = user._id;
return res.redirect('/profile');
}
});
} else {
var err = new Error('All fields required');
err.status = 400;
return next(err);
}
});
router.post('/s', function(req, res) {
console.log('ID in POST: ', req.session.userId);
});
router.get('/s', function(req, res) {
console.log(req.session.userId);
return res.redirect('http://localhost:8080/finish-registration');
});
// GET route after registering
router.get('/profile', function(req, res, next) {
console.log(`Find by id: `, req.session.userId);
User.findById(req.session.userId).exec(function(error, user) {
if (error) {
return next(error);
} else {
if (user === null) {
var error = new Error('Not authorized! Go back!');
error.status = 400;
return next(error);
} else {
console.log('Client username check: ' + req.session.userId);
return res.redirect('http://localhost:8080/finish-registration');
}
}
});
});
// GET for logout logout
router.get('/logout', function(req, res, next) {
if (req.session) {
// delete session object
req.session.destroy(function(err) {
if (err) {
return next(err);
} else {
return res.redirect('/');
}
});
}
});
module.exports = router;
models/user.js
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
trim: true
},
password: {
type: String,
required: true
},
confirmPassword: {
type: String,
required: true
},
registrationFinished: {
type: Boolean,
required: false
}
});
// authenticate input against database
UserSchema.statics.authenticate = function(email, password, callback) {
User.findOne({ email: email }).exec(function(err, user) {
if (err) {
return callback(err);
} else if (!user) {
var err = new Error('User not found');
err.status = 400;
return callback(err);
}
bcrypt.compare(password, user.password, function(err, result) {
if (result === true) {
return callback(null, user);
} else {
return callback();
}
});
});
};
// hashing a password before saving it to the database
UserSchema.pre('save', function(next) {
var user = this;
console.log(user.email);
bcrypt.hash(user.password, 10, function(err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
var User = mongoose.model('User', UserSchema);
module.exports = User;
If anyone faces the same issue, the problem was related to axios. Adding
axios.defaults.withCredentials = true;
did the trick. Also note, that adding withCredentials: true as an option to post request did not help, i.e. this does not work:
axios
.post('http://localhost:3000/s', {
newUserInfo: jsonData,
withCredentials: true
})

MEAN stack application - getting details of a single user, querying by username

I have built an API to GET and POST values into a database(MongoDB) using NodeJS and Express.
I am able to get the total list of users stored on my database (localhost:3000/user)
But I want to get a single users details by either entering the userID or userName(localhost:3000/user/:username)(localhost:3000/user/:userID)
I am able to get a single users details through ObjectID(localhost:3000/user/:id)
App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//var routes = require('./routes/index');
//var users = require('./routes/users');
//Router for developers
var developer = require('./routes/developer');
//Router for TvShows
var tvshow = require('./routes/tvshow');
//Router for TvShows
var user = require('./routes/user');
//Router for TvShowRating
var tvshowrating = require('./routes/tvshowrating');
//Router for TvShowEpisodes
var tvshowepisodes = require('./routes/tvshowepisodes');
//Router for TvShowNewsFeed
var tvshownewsfeed = require('./routes/tvshownewsfeed');
//Router for TvShowSeason
var tvshowseason = require('./routes/tvshowseason');
//Router for TvShowRatingUser
var tvshowratinguser = require('./routes/tvshowratinguser');
// load mongoose package
var mongoose = require('mongoose');
// Use native Node promises
mongoose.Promise = global.Promise;
// connect to MongoDB
//mongoose.connect('<string>')
//mongoose.connect('mongodb://localhost/televisionary-api')
.then(() => console.log('connection succesful'))
.catch((err) => console.error(err));
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//Registering routers
app.use('/developer', developer);
app.use('/tvshow', tvshow);
app.use('/user', user);
app.use('/tvshowrating', tvshowrating)
app.use('/tvshowepisodes', tvshowepisodes)
app.use('/tvshownewsfeed', tvshownewsfeed)
app.use('/tvshowseason', tvshowseason)
app.use('/tvshowratinguser', tvshowratinguser)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
. routes/User.js
var express = require('express');
var router = express.Router();
var User = require('../models/User.js');
/* GET /user listing. */
router.get('/', function(req, res, next) {
User.find(function (err, user) {
if (err) return next(err);
res.json(user);
});
});
/* POST /user */
router.post('/', function(req, res, next) {
User.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /user/id */
router.get('/:id', function(req, res, next) {
User.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* PUT /user/:id */
router.put('/:id', function(req, res, next) {
User.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* DELETE /user/:id */
router.delete('/:id', function(req, res, next) {
User.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
. models/User.js
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
userId:Number,
userName: String,
userEmail: String,
userPassword: String,
userCreatedDateTime: Date,
userWatchList: [
{
watchListItemId:Number,
tvShowId: Number,
tvShowSeasonId: Number,
tvShowEpisodeId: Number,
tvShowAddedDateTime: Date
}
],
userFavouriteList: [
{
favouriteId:Number,
tvShowId: Number,
tvShowFavouritedDateTime: Date
}
],
userRatings: [
{
tvShowUserRatingId:Number,
tvShowId: Number,
tvShowSeasonId: Number,
tvShowEpisodeId: Number,
tvShowRatedDateTime: Date,
tvShowRating: Number,
tvShowUserTags:[String]
}
]
});
module.exports = mongoose.model('User', userSchema);
If you want to get user details by entering username or userid in one service then modify your service with this:
router.get('/:keyword', function(req, res, next){
User.findOne({$or:[{userName: req.params.keyword}{userId:req.params.keyword}]},
function (err, post) {
if (err) return next(err);
res.json(post);
});
});
You can use findOne method to get a specific user from a database.
router.get('/user/:username', function(req, res, next) {
User.findOne({userName: req.params.username}, function(err, user) {
if(err)
console.log(err);
else
//do something with user
})
});
Same for fetching user using userId.

Resources