From da188b9b39c23bb324daf2e7037a00a4a919df9a Mon Sep 17 00:00:00 2001 From: arnaucode Date: Thu, 26 Jan 2017 00:06:19 +0100 Subject: [PATCH] RE-DOING and new Structure of project. Updating functionalities, and models --- controllers/travelController.js | 209 +++++++++++++++----------------- controllers/userController.js | 128 +++++++------------ models/carModel.js | 14 --- models/commentModel.js | 9 +- models/joinModel.js | 13 -- models/needtravelModel.js | 15 --- models/travelModel.js | 30 ++--- models/userModel.js | 40 +++--- server.js | 143 +++++++++++----------- 9 files changed, 256 insertions(+), 345 deletions(-) delete mode 100644 models/carModel.js delete mode 100644 models/joinModel.js delete mode 100644 models/needtravelModel.js diff --git a/controllers/travelController.js b/controllers/travelController.js index 9097d36..19b13f8 100644 --- a/controllers/travelController.js +++ b/controllers/travelController.js @@ -1,129 +1,93 @@ //File: controllers/travelController.js var mongoose = require('mongoose'); -var travelModel = mongoose.model('travelModel'); - var userModel = mongoose.model('userModel'); - -var joinModel = mongoose.model('joinModel'); +var travelModel = mongoose.model('travelModel'); var commentModel = mongoose.model('commentModel'); //GET -exports.findAllTravels = function(req, res) { +exports.getAllTravels = function(req, res) { //get travels with futures dates ($gte - greater than and equal than) - travelModel.find({date: {$gte: new Date()}}, function(err, travels) { - if(err) res.send(500, err.message); - - res.status(200).jsonp(travels); - }); - - + travelModel.find({date: {$gte: new Date()}}) + .limit(Number(req.query.pageSize)) + .skip(Number(req.query.pageSize) * Number(req.query.page)) + .exec(function (err, travels) { + if (err) return res.send(500, err.message); + res.status(200).jsonp(travels); + }); }; -//GET -exports.findById = function(req, res) { - travelModel.findById(req.params.id, function(err, travel) { - if(err) return res.send(500, err.message); - - console.log('GET /travel/' + req.params.id); - res.status(200).jsonp(travel); - }); -}; - -exports.findAllTravelsFromUsername = function(req, res) { - travelModel.find({ - owner: req.params.username, - date: {$gte: new Date()} - }, function(err, travels) { - - if (err) throw err; - - if (!travels) { - res.json({ success: false, message: 'no travels for user' }); - } else if (travels) { - console.log(travels); - // return the information including token as JSON - res.jsonp(travels); - - - } - - }); +exports.getTravelById = function (req, res) { + travelModel.findOne({_id: req.params.travelid}) + .lean() + .populate('joins', 'username avatar') + .populate('comments', 'comment user') + .exec(function (err, travel) { + if (err) return res.send(500, err.message); + if (!travel) { + res.json({success: false, message: 'travel not found.'}); + } else if (travel) { + + res.status(200).jsonp(travel); + } + }); }; exports.addTravel = function(req, res) { - console.log('POST new travel, title: ' + req.body.title); - userModel.find({ - token: req.headers['x-access-token'] - }, function(err, users){ - var user=users[0]; - - var travel = new travelModel({ - title: req.body.title, - description: req.body.description, - owner: user.username, - from: req.body.from, - to: req.body.to, - date: req.body.date, - periodic: req.body.periodic, - generateddate: req.body.generateddate, - seats: req.body.seats, - package: req.body.package, - icon: req.body.icon, - phone: user.phone, - telegram: user.telegram, - collectivized: req.body.collectivized, - modality: req.body.modality - }); - if(travel.title==undefined) - { - return res.status(500).jsonp("empty inputs"); - }else if(travel.description==undefined) - { - return res.status(500).jsonp("empty inputs"); - }else if(travel.from==undefined) - { - return res.status(500).jsonp("empty inputs"); - }else if(travel.to==undefined) - { - return res.status(500).jsonp("empty inputs"); - }else if(travel.date==undefined) - { - return res.status(500).jsonp("empty inputs"); - }else if(travel.title==undefined) - { - return res.status(500).jsonp("empty inputs"); - } + userModel.findOne({'token': req.headers['x-access-token']}) + .exec(function(err, user){ + if (err) return res.send(500, err.message); + if (!user) { + console.log("user not found"); + res.json({success: false, message: 'User not found.'}); + } else if (user) { + var travel = new travelModel({ + title: req.body.title, + description: req.body.description, + user: user._id, + from: req.body.from, + to: req.body.to, + date: req.body.date, + periodic: req.body.periodic, + generateddate: Date(), + seats: req.body.seats, + package: req.body.package, + collectivized: req.body.collectivized, + type: req.body.modality + }); - travel.save(function(err, travel) { - if(err) return res.send(500, err.message); - //res.status(200).jsonp(travel); - travelModel.find({date: {$gte: new Date()}}, function(err, travels) { - if(err) res.send(500, err.message); + travel.save(function(err, travel) { + if(err) return res.send(500, err.message); - res.status(200).jsonp(travels); - }); - });//end of travel.save + user.travels.push(travel._id); + user.save(function (err, user) { + if (err) return res.send(500, err.message); + exports.getAllTravels(req, res); + }); + });//end of travel.save + } });//end of usermodel.find }; -//PUT exports.updateTravel = function(req, res) { - ActivityModel.findById(req.params.id, function(err, tvshow) { - tvshow.title = req.body.petId; - tvshow.year = req.body.year; - tvshow.country = req.body.country; - tvshow.poster = req.body.poster; - tvshow.seasons = req.body.seasons; - tvshow.genre = req.body.genre; - tvshow.summary = req.body.summary; - - tvshow.save(function(err) { - if(err) return res.send(500, err.message); - res.status(200).jsonp(tvshow); - }); - }); + userModel.findOne({'token': req.headers['x-access-token']}) + .exec(function(err, user){ + if (err) return console.log(err); + console.log(user); + userModel.findOne({_id: user._id}) + .lean() + .populate('travels', 'title from to date') + .exec(function (err, user) { + if (err) return res.send(500, err.message); + if (!user) { + res.json({success: false, message: 'User not found.'}); + } else if (user) { + + res.status(200).jsonp(user); + } + }); + }); }; //DELETE @@ -149,14 +113,10 @@ exports.deleteTravel = function(req, res) { }); }; - /* join */ exports.addJoin = function(req, res) { - userModel.find({ - token: req.headers['x-access-token'] - }, function(err, users){ - var user=users[0]; - + userModel.findOne({'token': req.headers['x-access-token']}) + .exec(function(err, user){ travelModel.findById(req.params.travelId, function(err, travel){ console.log(travel.title); var join = { @@ -248,6 +208,31 @@ exports.getJoinsByTravelId = function(req, res) { }); }; +exports.findAllTravelsFromUsername = function(req, res) { + travelModel.find({ + owner: req.params.username, + date: {$gte: new Date()} + }, function(err, travels) { + + if (err) throw err; + + if (!travels) { + res.json({ success: false, message: 'no travels for user' }); + } else if (travels) { + console.log(travels); + // return the information including token as JSON + res.jsonp(travels); + + + } + + }); +}; + + + + + /* comment */ exports.addComment = function(req, res) { diff --git a/controllers/userController.js b/controllers/userController.js index 4c93479..261c5f4 100644 --- a/controllers/userController.js +++ b/controllers/userController.js @@ -14,16 +14,14 @@ var crypto = require('crypto'); /* */ //POST - Insert a new User in the DB -exports.addUser = function(req, res) { - console.log('POST new user, name: ' + req.body.username); - //console.log(req.body); +exports.signup = function(req, res) { var user = new userModel({ username: req.body.username, password: crypto.createHash('sha256').update(req.body.password).digest('base64'), description: req.body.description, avatar: req.body.avatar, - mail: req.body.mail, + email: req.body.email, phone: req.body.phone, telegram: req.body.telegram }); @@ -31,7 +29,7 @@ exports.addUser = function(req, res) { return res.status(500).jsonp("empty inputs"); } else if (user.password == undefined) { return res.status(500).jsonp("empty inputs"); - } else if (user.mail == undefined) { + } else if (user.email == undefined) { return res.status(500).jsonp("empty inputs"); } @@ -71,7 +69,7 @@ exports.login = function(req, res) { // if user is found and password is right // create a token - var token = jwt.sign(user, app.get('superSecret'), { + var token = jwt.sign({foo: 'bar'}, app.get('superSecret'), { //expiresInMinutes: 1440 // expires in 24 hours //expiresIn: '60m' }); @@ -98,65 +96,62 @@ exports.login = function(req, res) { }; //GET - Return all Users in the DB -exports.findAllUsers = function(req, res) { - userModel.find(function(err, users) { - if (err) res.send(500, err.message); - - //password deletion - for (var i = 0; i < users.length; i++) { - users[i].password = ""; - users[i].token = ""; - console.log(users[i].password); - } - - console.log('GET /users'); - res.status(200).jsonp(users); - }); +exports.getAllUsers = function(req, res) { + userModel.find() + .limit(Number(req.query.pageSize)) + .skip(Number(req.query.pageSize) * Number(req.query.page)) + .exec(function (err, users) { + if (err) return res.send(500, err.message); + res.status(200).jsonp(users); + }); }; //GET - Return a User with specified ID -exports.findById = function(req, res) { - userModel.findById(req.params.id, function(err, user) { +exports.getUserById = function (req, res) { + userModel.findOne({_id: req.params.userid}) + .lean() + .populate('travels', 'title from to date') + .exec(function (err, user) { if (err) return res.send(500, err.message); + if (!user) { + res.json({success: false, message: 'User not found.'}); + } else if (user) { - console.log('GET /users/' + req.params.id); - //password deletion - if (user != null) { - user.password = ""; - users.token = ""; + res.status(200).jsonp(user); } - res.status(200).jsonp(user); }); }; -exports.findUserByUsername = function(req, res) { - userModel.find({ - username: req.params.username - }, function(err, user) { - - if (err) throw err; - - if (!user) { - res.json({ - success: false, - message: 'no user found' - }); - } else if (user) { - // return the information including token as JSON - //res.jsonp(user); - user.password = ""; - users.token = ""; +exports.updateUser = function (req, res) { + userModel.update({'token': req.headers['x-access-token']}, req.body, + function (err) { + if (err) return console.log(err); console.log(user); - res.status(200).jsonp(user[0]); - + userModel.findOne({_id: user._id}) + .lean() + .populate('travels', 'title from to date') + .exec(function (err, user) { + if (err) return res.send(500, err.message); + if (!user) { + res.json({success: false, message: 'User not found.'}); + } else if (user) { - } + res.status(200).jsonp(user); + } + }); + }); +}; +//DELETE - Delete a user with specified ID +exports.deleteUser = function(req, res) { + userModel.findOne({'token': req.headers['x-access-token']}) + .exec(function(err, user) { + user.remove(function(err) { + if (err) return res.send(500, err.message); + res.status(200).jsonp("deleted"); + }) }); }; - - - /* fav */ exports.addFav = function(req, res) { var tokenuser; @@ -238,34 +233,3 @@ exports.doUnfav = function(req, res) { }); }); }; - -//PUT - Update a user already exists -exports.updateUser = function(req, res) { - userModel.findById(req.params.id, function(err, user) { - user.username = req.body.username; - user.password = md5(req.body.password); - user.description = req.body.description; - user.avatar = req.body.avatar; - user.mail = req.body.mail; - user.phone = req.body.phone; - user.telegram = req.body.telegram; - - user.save(function(err) { - if (err) return res.send(500, err.message); - user.password = ""; - users.token = ""; - res.status(200).jsonp(user); - }); - }); -}; - -//DELETE - Delete a user with specified ID -exports.deleteUser = function(req, res) { - userModel.findById(req.params.id, function(err, user) { - user.remove(function(err) { - if (err) return res.send(500, err.message); - res.status(200).jsonp(req.params.id); - console.log('DELETE /users/' + req.params.id); - }) - }); -}; diff --git a/models/carModel.js b/models/carModel.js deleted file mode 100644 index 883bef7..0000000 --- a/models/carModel.js +++ /dev/null @@ -1,14 +0,0 @@ -var mongoose = require('mongoose'), - Schema = mongoose.Schema; - - -var carSchema = new Schema({ - title: { type: String }, - description: { type: String }, - owner: { type: String }, - zone: { type: String }, - available: { type: Boolean }, - generateddate: { type: Date }, - seats: { type: Number } -}) -module.exports = mongoose.model('carModel', carSchema); diff --git a/models/commentModel.js b/models/commentModel.js index de44312..8f6ee7b 100644 --- a/models/commentModel.js +++ b/models/commentModel.js @@ -3,11 +3,10 @@ var mongoose = require('mongoose'), var commentSchema = new Schema({ - travelId: { type: String }, - commentUserId: { type: String }, - commentUsername: { type: String }, comment: { type: String }, - commentAvatar: { type: String } - + user: { + type: mongoose.Schema.Types.ObjectId, + ref: 'userModel' + } }); module.exports = mongoose.model('commentModel', commentSchema); diff --git a/models/joinModel.js b/models/joinModel.js deleted file mode 100644 index 9d5dcaa..0000000 --- a/models/joinModel.js +++ /dev/null @@ -1,13 +0,0 @@ -var mongoose = require('mongoose'), - Schema = mongoose.Schema; - - -var joinSchema = new Schema({ - travelId: { type: String }, - joinedUserId: { type: String }, - joinedUsername: { type: String }, - acceptedUserId: { type: String }, - joinedAvatar: { type: String } - -}); -module.exports = mongoose.model('joinModel', joinSchema); diff --git a/models/needtravelModel.js b/models/needtravelModel.js deleted file mode 100644 index 5a95a09..0000000 --- a/models/needtravelModel.js +++ /dev/null @@ -1,15 +0,0 @@ -var mongoose = require('mongoose'), - Schema = mongoose.Schema; - - -var needtravelSchema = new Schema({ - title: { type: String }, - description: { type: String }, - owner: { type: String }, - from: { type: String }, - to: { type: String }, - date: { type: Date }, - generateddate: { type: Date }, - seats: { type: Number } -}) -module.exports = mongoose.model('needtravelModel', needtravelSchema); diff --git a/models/travelModel.js b/models/travelModel.js index 778fa16..d8b3e33 100644 --- a/models/travelModel.js +++ b/models/travelModel.js @@ -3,32 +3,28 @@ var mongoose = require('mongoose'), var travelSchema = new Schema({ - title: { type: String }, + title: { type: String, required: true }, description: { type: String }, - owner: { type: String }, - from: { type: String }, - to: { type: String }, + user: { + type: mongoose.Schema.Types.ObjectId, + ref: 'userModel' + }, + from: { type: String, required: true }, + to: { type: String, required: true }, date: { type: Date }, periodic: { type: Boolean }, generateddate: { type: Date }, - seats: { type: Number }, + seats: { type: Number, required: true }, package: { type: Boolean }, - icon: { type: String }, - phone: { type: Number }, - telegram: { type: String }, collectivized: { type: Boolean }, - modality: { type: String }, //if is an offering travel or asking for travel + type: { type: String }, //if is an offering travel or asking for travel joins: [{ - joinedUserId: { type: String }, - joinedUsername: { type: String }, - acceptedUserId: { type: String }, - joinedAvatar: { type: String } + type: mongoose.Schema.Types.ObjectId, + ref: 'userModel' }], comments: [{ - commentUserId: { type: String }, - commentUsername: { type: String }, - comment: { type: String }, - commentAvatar: { type: String } + type: mongoose.Schema.Types.ObjectId, + ref: 'commentModel' }] }) module.exports = mongoose.model('travelModel', travelSchema); diff --git a/models/userModel.js b/models/userModel.js index e381614..186ff45 100644 --- a/models/userModel.js +++ b/models/userModel.js @@ -5,30 +5,40 @@ var mongooseUniqueValidator = require('mongoose-unique-validator'); var userSchema = new Schema({ - username: { type: String, unique: true }, - password: { type: String }, - token: { type: String }, + username: { type: String, required: true, unique: true }, + password: { type: String, required: true, selected: false }, + token: { type: String, selected: false }, description: { type: String }, avatar: { type: String }, - mail: { type: String }, + email: { type: String, required: true }, phone: { type: String }, telegram: { type: String }, valorations: [{ - username: { type: String }, - value: { type: Number }, - comment: { type: String } + user: { + type: mongoose.Schema.Types.ObjectId, + ref: 'userModel' + }, + value: { type: Number }, + comment: { type: String } }], favs: [{ - username: { type: String }, - userId: { type: String }, - avatar: { type: String } + user: { + type: mongoose.Schema.Types.ObjectId, + ref: 'userModel' + }, + date: {type: Date} + }], + travels: [{ + type: mongoose.Schema.Types.ObjectId, + ref: 'travelModel' }], notifications: [{ - type: { type: String },//fav, comment, join - otherusername: { type: String }, - description: { type: String }, - date: { type: Date }, - link: { type: String } + state: {type: String},//viewed, pendent + message: {type: String}, + link: {type: String},//aquí oju, a la app i a la web calen links diferents, però ho podem fer posant sempre a la app i a la web el prefix del link (#!/app) o (#/app/), i després afegint-hi la pàgina on volem enviar el routing, per exemple (dashboard) + icon: {type: String}, + date: {type: Date}, + dateviewed: {type: Date} }] }) diff --git a/server.js b/server.js index ed66ff2..828296e 100755 --- a/server.js +++ b/server.js @@ -1,24 +1,26 @@ -var express = require("express"), - app = express(), - bodyParser = require("body-parser"), - methodOverride = require("method-override"), - mongoose = require('mongoose'); +var express = require("express"), + app = express(), + bodyParser = require("body-parser"), + methodOverride = require("method-override"), + mongoose = require('mongoose'); -var morgan = require('morgan'); -var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens +var morgan = require('morgan'); +var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens var config = require('./config'); // get our config file mongoose.Promise = global.Promise; // Connection to DB mongoose.connect(config.database, function(err, res) { - if(err) throw err; - console.log('Connected to Database'); + if (err) throw err; + console.log('Connected to Database'); }); app.set('superSecret', config.secret); // secret variable // Middlewares -app.use(bodyParser.urlencoded({ extended: false })); +app.use(bodyParser.urlencoded({ + extended: false +})); app.use(bodyParser.json()); app.use(methodOverride()); @@ -26,12 +28,11 @@ app.use(methodOverride()); app.use(morgan('dev')); // Import Models and controllers -var userMdl = require('./models/userModel')(app, mongoose); +var userMdl = require('./models/userModel')(app, mongoose); var userCtrl = require('./controllers/userController'); -var travelMdl = require('./models/travelModel')(app, mongoose); -var joinMdl = require('./models/joinModel')(app, mongoose); -var commentMdl = require('./models/commentModel')(app, mongoose); +var travelMdl = require('./models/travelModel')(app, mongoose); +var commentMdl = require('./models/commentModel')(app, mongoose); var travelCtrl = require('./controllers/travelController'); /*// Example Route @@ -45,82 +46,80 @@ app.use(express.static(__dirname + '/www')); //CORS app.use(function(req, res, next) { - res.header("Access-Control-Allow-Origin", "*"); - res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Access-Token"); - next(); + res.header("Access-Control-Allow-Origin", "*"); + res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); + res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Access-Token"); + next(); }); // API routes ------------------------------------------------------ var apiRoutes = express.Router(); -apiRoutes.route('/users') - .get(userCtrl.findAllUsers) - .post(userCtrl.addUser); -apiRoutes.route('/users/:id') - .get(userCtrl.findById); -apiRoutes.route('/users/byusername/:username') - .get(userCtrl.findUserByUsername); -apiRoutes.route('/travels/user/:username') - .get(travelCtrl.findAllTravelsFromUsername); - -apiRoutes.route('/auth') +apiRoutes.route('/login') .post(userCtrl.login); - +apiRoutes.route('/signup') + .post(userCtrl.signup); +apiRoutes.route('/users') + .get(userCtrl.getAllUsers); +apiRoutes.route('/users/getById/:userid') + .get(userCtrl.getUserById); apiRoutes.route('/travels') - .get(travelCtrl.findAllTravels); + .get(travelCtrl.getAllTravels); +apiRoutes.route('/travels/getById/:travelid') + .get(travelCtrl.getTravelById); -apiRoutes.route('/travels/:id') - .get(travelCtrl.findById); -apiRoutes.route('/travels/join/:travelId') - .get(travelCtrl.getJoinsByTravelId); -apiRoutes.route('/travels/comment/:travelId') - .get(travelCtrl.getCommentsByTravelId); // OJU AQUÏ TREC la verificació de token temporalment, per fer les proves des de l'app // route middleware to verify a token apiRoutes.use(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, app.get('superSecret'), function(err, decoded) { - if (err) { - return res.json({ success: false, message: 'Failed to authenticate token.' }); - } else { - // if everything is good, save to request for use in other routes - req.decoded = decoded; - //console.log("decoded " + decoded); - next(); - } - }); - - } else { - - // if there is no token - // return an error - return res.status(201).send({ - success: false, - message: 'No token provided.' - }); - - } + // 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, app.get('superSecret'), function(err, decoded) { + if (err) { + return res.json({ + success: false, + message: 'Failed to authenticate token.' + }); + } else { + // if everything is good, save to request for use in other routes + req.decoded = decoded; + //console.log("decoded " + decoded); + next(); + } + }); + + } else { + + // if there is no token + // return an error + return res.status(201).send({ + success: false, + message: 'No token provided.' + }); + + } }); //fi verificació de token apiRoutes.route('/users/:id') - .put(userCtrl.updateUser) - .delete(userCtrl.deleteUser); - + .put(userCtrl.updateUser) + .delete(userCtrl.deleteUser); apiRoutes.route('/travels') - .post(travelCtrl.addTravel); - + .post(travelCtrl.addTravel); +//FINS AQUÏ COMPROVAT apiRoutes.route('/travels/:id') - .put(travelCtrl.updateTravel) - .delete(travelCtrl.deleteTravel); + .put(travelCtrl.updateTravel) + .delete(travelCtrl.deleteTravel); + +apiRoutes.route('/travels/addJoin/:travelId') + .get(travelCtrl.getJoinsByTravelId); +apiRoutes.route('/travels/comment/:travelId') + .get(travelCtrl.getCommentsByTravelId); /*apiRoutes.route('/travels/join/:travelId') .post(travelCtrl.addJoin); @@ -145,5 +144,5 @@ app.use('/api', apiRoutes); // Start server app.listen(config.port, function() { - console.log("Node server running on http://localhost:3000"); + console.log("Node server running on http://localhost:3000"); });