Here I have multiple users like Parent,Trainer,Provider.I wrote individual schemas, routes and verify codes for registration and login and for storing, collections also different for each.when I make to run the application it is properly running.And after that I opened the postman tool I registered as" parent" the response is "Registration Successfull" and login as parent I am getting token so that I can perform the functions what a Parent can do in my project.And after that I logout as parent.Next, when I try to registered as Trainer/Provider the response is "Unauthorized". But the fields what I am giving at time of registration are stored in respective collections in database.When I give same values what a parent gave at the time of registration to trainer registration and provider registration then the response is "Registration Successfull" when I give different values other than what a parent gave it shows me "Unauthorized".So, I want to know why this issue arises? And how can I fix this problem?
Here is my schema code
<!-- trainer schema -->
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var trainerUser= new Schema({
username:{type:String,required:true,unique:true},
email:{type:String,required:true,unique:true},
phone:{type:Number,required:true,unique:true },
password:{type:String});
trainerUser.plugin(passportLocalMongoose);
module.exports = mongoose.model('trainerUser', trainerUser);
<!-- parent schema -->
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User = new Schema({
username: String,
email:String,
password: String,
phonenumber:Number
});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('parentlog', User);
<!-- provider schema -->
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User= new Schema({
username:{type:String,required:true,unique:true},
email:{type:String,required:true,unique:true},
phone:{type:Number,required:true,unique:true },
password:{type:String});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User',User);
Here is my routes code for each module
//trainer route
<!-- trainer route -->
var express = require('express');
var router = express.Router();
var passport = require('passport');
var trainerUser = require('../models/traineruser');
var Verify = require('./trainerverify');
<!-- GET users listing. -->
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/register', function(req, res) {
trainerUser.register(new trainerUser({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password,
function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Could not log in user'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful!',
success: true,
token: token
});
});
})(req,res,next);
});
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
//parent route
const AuthenticationController = require('../controllers/authentication');
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/puser');
var Verify = require('./parentverify');
var mongoose=require('mongoose');
const requireLogin = passport.authenticate('local', { session: false });
router.route('/')
.get(function(req, res) {
User.find({},function(err,users){
if(err) {
return res.status(403).json({
err: 'You are not authorized to perform this operation!'
});
} else {
res.json(users);
}
});
});
router.post('/register', function(req, res) {
User.register(new User({ username : req.body.username,email:req.body.email,phonenumber:req.body.phonenumber }),
req.body.password, function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', requireLogin, AuthenticationController.login);
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
//provider route
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user');
var Verify= require('./userverify');
<!-- GET users listing. -->
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/register', function(req, res) {
User.register(new User({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password,
function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Could not log in user'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful!',
success: true,
token: token
});
});
})(req,res,next);
});
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
and app.js code is here
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 mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
<!-- we're connected! -->
console.log("Connected correctly to server");
});
var users = require('./routes/users');
var trainerusers = require('./routes/trainerusers');
var pusers = require('./routes/pusers');
var contacts=require('./routes/contactRouter');
var student=require('./routes/studentRouter');
var batch=require('./routes/batchRouter');
var venue=require('./routes/venueRouter');
var trainerrouter = require('./routes/trainerrouter.js');
var report=require('./routes/reportRouter');
var attendance=require('./routes/attendanceRouter');
var app = express();
<!-- view engine setup -->
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
<!-- 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());
<!-- passport config -->
var User = require('./models/user');
var trainerUser = require('./models/traineruser');
var Puser = require('./models/puser');
app.use(passport.initialize());
passport.use(new LocalStrategy(Puser.authenticate(),trainerUser.authenticate(),User.authenticate()));
passport.serializeUser(Puser.serializeUser(),trainerUser.serializeUser(),User.serializeUser());
passport.deserializeUser(Puser.deserializeUser(),trainerUser.deserializeUser(),User.deserializeUser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', users);
app.use('/trainerusers', trainerusers);
app.use('/pusers', pusers);
app.use('/contacts',contacts);
app.use('/student',student);
app.use('/batch',batch);
app.use('/venue',venue);
app.use('/report',report);
app.use('/trainer',trainerrouter);
app.use('/attendance',attendance);
<!-- 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.json({
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.json({
message: err.message,
error: {}
});
});
module.exports = app;
Related
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');
})
I am trying to generate token while logging in locally. Let's say I am normal user and want to sign in. Will token get generated while signing in? and how? Need guidance. Thanks
As I am using mongodb I require my users schema model in my routes code.Here is my routes code user.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/schema');
var Verify = require('./verify');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/register', function(req, res) {
User.register(new User({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password,
function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Could not log in user'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful!',
success: true,
token: token
});
});
})(req,res,next);
});
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
When you look at the code you will notice a verify variable.It is nothing but verification that is user is registered or not.If user registered then user will allow for login.After login user will get a successfull response along with token.So here is my veirfy code verify.js
var User=require('../models/schema');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('../config.js');
exports.getToken = function (user) {
return jwt.sign(user, config.secretKey, {
expiresIn: 3600
});
};
exports.verifyOrdinaryUser = function (req, res, next) {
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.secretKey, function (err, decoded) {
if (err) {
var err = new Error('You are not authenticated!');
err.status = 401;
return next(err);
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
var err = new Error('No token provided!');
err.status = 403;
return next(err);
}
};
If you observe the code there is a variable like config this is nothing but connection to my mongodb.Here is the code config.js
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl' : 'mongodb://localhost:27017/conFusion'
}
And the user schema is here schema.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User= new Schema({
username:{
type:String,
required:true,
unique:true
},
email:{
type:String,
required:true,
unique:true
},
phone:{
type:Number,
required:true,
unique:true
},
password:{
type:String
}
});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User',User);
And finally server 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 mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("Connected correctly to server");
});
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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')));
var User = require('./models/schema');
app.use(passport.initialize());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use('/users', users);
// 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 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');
});
app.listen(3000,function(){
console.log("Server Listening on 3000");
});
module.exports = app;
project structure must be as per my code
+app.js
+config.js
+routes(directory)
++user.js
++verify.js
+models(directory)
++schema.js
run the code node app.js
When you want to register use http://localhost:3000/users/register
and for login use http://localhost:3000/users/login
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.
I'm having trouble with my server routes, I had the server on heroku but now have it local to debug,
On browser inspection i get
404 (Not Found)
in browser window
Cannot GET /api/auth/register
My server.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var logger = require('morgan');
var bodyParser = require('body-parser');
var databaseConfig = require('./config/database');
var router = require('./app/routes');
//CORS middleware
var allowCrossDomain = function(req, res, next) {
if ('OPTIONS' == req.method) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
res.sendStatus(200);
}
else {
next();
}
};
app.use(allowCrossDomain);
mongoose.connect(databaseConfig.url);
app.listen(process.env.PORT || 8080);
console.log("App listening on port 8080");
app.use(bodyParser.urlencoded({ extended: false })); // Parses urlencoded bodies
app.use(bodyParser.json()); // Send JSON responses
app.use(logger('dev')); // Log requests to API using morgan
router(app);
My routes.js
var AuthenticationController = require('./controllers/authentication'),
ExerciseController = require('./controllers/exercises'),
express = require('express'),
passportService = require('../config/passport'),
passport = require('passport');
var requireAuth = passport.authenticate('jwt', {session: false}),
requireLogin = passport.authenticate('local', {session: false});
module.exports = function(app){
var apiRoutes = express.Router(),
authRoutes = express.Router(),
exerciseRoutes = express.Router();
// Auth Routes
apiRoutes.use('/auth', authRoutes);
//authRoutes.post('/register', AuthenticationController.register);
authRoutes.post('/register', function(req, res){
AuthenticationController.registerUser
});
authRoutes.post('/login', requireLogin, AuthenticationController.login);
authRoutes.get('/protected', requireAuth, function(req, res){
res.sendStatus({ content: 'Success'});
});
// Exercise Routes
apiRoutes.use('/exercises', exerciseRoutes);
exerciseRoutes.get('/', requireAuth, AuthenticationController.roleAuthorization(['client','trainer','admin']), ExerciseController.getExercises);
exerciseRoutes.post('/', requireAuth, AuthenticationController.roleAuthorization(['trainer','admin']), ExerciseController.createExercise);
exerciseRoutes.delete('/:exercise_id', requireAuth, AuthenticationController.roleAuthorization(['trainer','admin']), ExerciseController.deleteExercise);
// Set up routes
app.use('/api', apiRoutes);
}
And my Controller Authentication.js :
var jwt = require('jsonwebtoken');
var User = require('../models/user');
var authConfig = require('../../config/auth');
function generateToken(user){
return jwt.sign(user, authConfig.secret, {
expiresIn: 10080
});
}
function setUserInfo(request){
return {
_id: request._id,
email: request.email,
role: request.role,
trainer: request.trainer,
programs: request.programs
};
}
exports.login = function(req, res, next){
var userInfo = setUserInfo(req.user);
console.log(userInfo)
res.status(200).json({
token: 'JWT ' + generateToken(userInfo),
user: userInfo
});
}
exports.registerUser = function(req, res, next){
var email = req.body.email;
var password = req.body.password;
var role = req.body.role;
var trainer = req.body.trainer;
var programs= req.body.programs;
if(!email){
return res.status(422).send({error: 'You must enter an email address'});
}
if(!password){
return res.status(422).send({error: 'You must enter a password'});
}
User.findOne({email: email}, function(err, existingUser){
if(err){
return next(err);
}
if(existingUser){
return res.status(422).send({error: 'That email address is already in use'});
}
var user = new User({
email: email,
password: password,
role: role,
trainer: trainer,
programs: programs
});
user.save(function(err, user){
if(err){
return next(err);
}
var userInfo = setUserInfo(user);
res.status(201).json({
token: 'JWT ' + generateToken(userInfo),
user: userInfo
})
});
});
}
exports.roleAuthorization = function(roles){
return function(req, res, next){
var user = req.user;
User.findById(user._id, function(err, foundUser){
if(err){
res.status(422).json({error: 'No user found.'});
return next(err);
}
if(roles.indexOf(foundUser.role) > -1){
return next();
}
res.status(401).json({error: 'You are not authorized to view this content'});
return next('Unauthorized');
});
}
}
I dont have much experience with express/node so im not sure where im going wrong, could be something simple im just not able to see, anyways any help is greatly appreciated , not sure if you need more info, this is going to be the back end for an ionic 2 app
i get 404 error when rooting with param , whereas all other rootings defined on my rootes/users.js file work perfectly , for example i get the desire result when i call :
localhost:3000/users/users .
but get 404 when i call localhost:3000/users/users/12315454 which should correspond to the rooter /users:user_id in my users.js (you can find it below)
var express = require('express');
var router = express.Router();
var User = require('../models/user');
router.route('/users:user_id')
.get(function(req, res) {
console.log("attempting user");
User.findById(req.params.user_id, function(err, place) {
if (err)
res.send(err);
res.json(place);
});
})
.put(function(req, res) {
console.log("attempting to update user");
User.findById(req.params.user_id, function(err, place) {
if (err)
res.send(err);
user.username = req.body.name;
user.visitedPlaces = req.body.visitedPlaces;
user.likedItems = req.body.likedItems;
//user.local.email= req.body.email;
user.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'user updated!' });
});
});
})
.delete(function(req, res) {
User.remove({
_id: req.params.user_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
router.route('/users')
// get all the users (accessed at GET http://localhost:8080/api/users)
.get(function(req, res) {
User.find(function(err, places) {
if (err)
res.send(err);
res.json(places);
});
});
router.route('/adduser')
.post(function(req, res) {
var user = new User();
user.password = user.generateHash (req.body.password); // set the users name (comes from the request)
user.username = req.body.username;
console.log(req.body)
console.log("user name :"+req.body.username);
user.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'user created!' });
});
});
module.exports = router;
my app.js config
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var mongo = require('mongoskin');
var mongoose = require('mongoose');
var configDB = require('./config/database.js');
var port = process.env.PORT || 3030;
var router = express.Router();
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
//Facebook app credentials
var FACEBOOK_APP_ID = '******09';
var FACEBOOK_APP_SECRET = '9a*******3';
//app secret for dev = 9adfcaa6d7989d8adc12852badcf69f3
// app ifd for dev = 492502667544609
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'app')));
//var routes = require('./routes/index');
require('./config/passport')(passport); // pass passport for configuration
var users = require('./routes/users');
var places = require('./routes/places');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// set up our express application
app.use(logger('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
// required for passport
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session());
app.use(favicon());
//app.use(flash()); // use connect-flash for flash messages stored in session
// Make our db accessible to our router WARNING THIS MUST BE PUT before the rooting stuff above
app.use('/api', router);
app.use('/places', places);
app.use('/users', users);
// routes ======================================================================
require('./routes/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
app.get('/', function(req, res, next) {
res.sendfile('./app/index.html');
});
/// catch 404 and forwarding 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: {}
});
});
// test authentication
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { console.log("is authenticated");
return next(); }
console.log("not authenticated");
res.redirect('/')
}
// launch ======================================================================
console.log('The magic happens on port ' + port)
module.exports = app;
Add a slash in your route, between the users and :user_id:
router.route('/users/:user_id')
^---------here