Browse Source

some clean, and rmMongodbDatabases

master
arnaucode 6 years ago
parent
commit
2c87f5b1b7
11 changed files with 111 additions and 133 deletions
  1. +8
    -2
      README.md
  2. +1
    -1
      adminCreator.js
  3. +1
    -3
      config.js
  4. +8
    -15
      controllers/adminController.js
  5. +6
    -12
      controllers/searchController.js
  6. +13
    -15
      controllers/travelController.js
  7. +26
    -46
      controllers/userController.js
  8. +1
    -0
      models/userModel.js
  9. BIN
      rmMongodbDatabases
  10. +16
    -0
      runDevEnvironment.sh
  11. +31
    -39
      server.js

+ 8
- 2
README.md

@ -2,9 +2,15 @@
- Current status:
- Server and App almost done, need to finish details.
- Not having time to develop. I'll try to finish a first stable and usable version.
- I'm focusing on having a first stable and usable version
- The plan is to have the first stable version in the middle of February 2018
- Comments:
- the code is not a good quality code, as:
- it was developed in a discontinued way
- in the process I learned stuff that I didn't know at the beginning
- Future plans:
- If somebody can do the frontend, I can focus on implementing the backend in Go lang
- If somebody can do the frontend, maybe we can implement the frontend app in React
- I can focus on implementing the backend in Go lang
---

+ 1
- 1
adminCreator.js

@ -15,7 +15,7 @@ mongoose.connect(config.database, function(err, res) {
var express = require("express");
var app = express();
var adminMdl = require('./models/adminModel')(app, mongoose);
var adminMdl = require('./models/adminModel');
var adminModel = mongoose.model('adminModel');

+ 1
- 3
config.js

@ -1,8 +1,6 @@
module.exports = {
/*'secret': process.env.SECRET,// production version
'database': process.env.MONGO_DSN,*/
'secret': 'secretfortoken',// local version
'database': 'mongodb://localhost/carsincommon',
'database': 'mongodb://localhost/commonroutes',
"port" : process.env.PORT || 3000,
"pageSize": 20
};

+ 8
- 15
controllers/adminController.js

@ -1,28 +1,21 @@
//File: controllers/userController.js
var mongoose = require('mongoose');
var adminModel = mongoose.model('adminModel');
var userModel = mongoose.model('userModel');
var userController = require('../controllers/userController');
var notificationModel = mongoose.model('notificationModel');
var travelModel = mongoose.model('travelModel');
var travelCtrl = require('../controllers/travelController');
var config = require('../config');
//var adminConfig = require('../adminConfig'); // get our config file
var pageSize = config.pageSize;
/* */
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var express = require("express");
var app = express();
var config = require('../config'); // get our config file
app.set('superSecret', config.secret); // secret variable
var crypto = require('crypto');
/* */
var request = require('request');
//data models
var mongoose = require('mongoose');
var adminModel = mongoose.model('adminModel');
var userModel = mongoose.model('userModel');
var userController = require('../controllers/userController');
var notificationModel = mongoose.model('notificationModel');
var travelModel = mongoose.model('travelModel');
var travelCtrl = require('../controllers/travelController');
//POST - Insert a new User in the DB
/*exports.signup = function(req, res) {

+ 6
- 12
controllers/searchController.js

@ -1,28 +1,22 @@
//File: controllers/userController.js
var mongoose = require('mongoose');
var userModel = mongoose.model('userModel');
var notificationModel = mongoose.model('notificationModel');
var travelModel = mongoose.model('travelModel');
var config = require('../config');
var pageSize=config.pageSize;
/* */
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var express = require("express");
var app = express();
var config = require('../config'); // get our config file
app.set('superSecret', config.secret); // secret variable
var crypto = require('crypto');
/* */
var mongoose = require('mongoose');
var userModel = mongoose.model('userModel');
var notificationModel = mongoose.model('notificationModel');
var travelModel = mongoose.model('travelModel');
exports.searchByString = function (req, res) {
console.log(req.params.searchstring);
userModel.find({
username: new RegExp(req.params.searchstring, "i")
})//perquè retorni tots els objectes que continguin l'string sense necessitat de que sigui exactament la mateixa string
})//to return all the objects containing the string, having exactly the same string
.limit(pageSize)
.skip(pageSize * Number(req.query.page))
.lean()
@ -35,7 +29,7 @@ exports.searchByString = function (req, res) {
{'to.name': new RegExp(req.params.searchstring, "i")},
{title: new RegExp(req.params.searchstring, "i")}
]
})//perquè retorni tots els objectes que continguin l'string sense necessitat de que sigui exactament la mateixa string
})//to return all the objects containing the string, without need of having the same string
.limit(pageSize)
.skip(pageSize * Number(req.query.page))
.lean()

+ 13
- 15
controllers/travelController.js

@ -1,13 +1,13 @@
//File: controllers/travelController.js
var config = require('../config');
var pageSize=config.pageSize;
//import data models
var mongoose = require('mongoose');
var userModel = mongoose.model('userModel');
var notificationModel = mongoose.model('notificationModel');
var travelModel = mongoose.model('travelModel');
var commentModel = mongoose.model('commentModel');
var config = require('../config');
var pageSize=config.pageSize;
//GET
exports.getAllTravels = function(req, res) {
//get travels with futures dates ($gte - greater than and equal than)
travelModel.find({date: {$gte: new Date()}})
@ -98,7 +98,6 @@ exports.updateTravel = function(req, res) {
});
};
//DELETE
exports.deleteTravel = function(req, res) {
userModel.findOne({'token': req.headers['x-access-token']})
.exec(function(err, user){
@ -118,7 +117,7 @@ exports.deleteTravel = function(req, res) {
});
};
/* join */
exports.addJoinPetition = function(req, res) {
userModel.findOne({'token': req.headers['x-access-token']})
.exec(function(err, userJoining){
@ -205,9 +204,9 @@ exports.unJoin = function(req, res) {
.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) {
//notification
res.json({success: false, message: 'User not found.'});
} else if (user) {
//notification
var notification = new notificationModel({
concept: "unjoin",
message: "user "+userJoining.username+" unjoins your travel "+travel.title,
@ -343,9 +342,9 @@ exports.acceptJoin = function(req, res) {
.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) {
//notification
res.json({success: false, message: 'User not found.'});
} else if (user) {
//notification
var notification = new notificationModel({
concept: "travel",
message: "user "+userOwner.username+" accepts your petition for "+travel.title,
@ -437,8 +436,7 @@ exports.leave = function(req, res) {
/* comment */
//currently not used
exports.addComment = function(req, res) {
/*var comment = new commentModel({
travelId: req.params.travelId,
@ -499,7 +497,7 @@ exports.addComment = function(req, res) {
});
});//end of userModel.find
};
//currently not used
exports.getCommentsByTravelId = function(req, res) {
commentModel.find({
travelId: req.params.travelId

+ 26
- 46
controllers/userController.js

@ -1,28 +1,28 @@
//File: controllers/userController.js
var mongoose = require('mongoose');
var userModel = mongoose.model('userModel');
var notificationModel = mongoose.model('notificationModel');
var travelModel = mongoose.model('travelModel');
var config = require('../config');
var pageSize = config.pageSize;
/* */
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var crypto = require('crypto');
var request = require('request');
var express = require("express");
var app = express();
var config = require('../config'); // get our config file
app.set('superSecret', config.secret); // secret variable
var crypto = require('crypto');
/* */
var pageSize = config.pageSize;
var request = require('request');
//import data models
var mongoose = require('mongoose');
var userModel = mongoose.model('userModel');
var notificationModel = mongoose.model('notificationModel');
var travelModel = mongoose.model('travelModel');
function getRand(min, max) {
function getRand(min, max) {//inclusive
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRandomInt(min, max) {//the maximum is exclusive and the minimum is inclusive
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
return Math.floor(Math.random() * (max - min)) + min;
}
function getAvatar(n) {
@ -68,7 +68,7 @@ exports.signup = function(req, res) {
//get random avatar
var r = getRand(1, 10);
randAvatar = getAvatar(r);
console.log(req.body);
var user = new userModel({
username: req.body.username,
@ -77,7 +77,8 @@ exports.signup = function(req, res) {
avatar: randAvatar,
email: req.body.email,
phone: req.body.phone,
telegram: req.body.telegram
telegram: req.body.telegram,
localNode: req.body.localNode
});
if (user.username == undefined) {
return res.status(500).jsonp("empty inputs");
@ -89,7 +90,6 @@ exports.signup = function(req, res) {
user.save(function(err, user) {
if (err) return res.send(500, err.message);
exports.login(req, res);
});
};
@ -134,8 +134,6 @@ exports.login = function(req, res) {
user.token = token;
user.save(function(err, user) {
if (err) return res.send(500, err.message);
//res.status(200).jsonp(travel);
console.log(user);
// return the information including token as JSON
user.password = "";
res.json({
@ -183,6 +181,7 @@ exports.getUserById = function(req, res) {
}
});
};
exports.getUserByToken = function(req, res) {
userModel.findOne({
'token': req.headers['x-access-token']
@ -254,7 +253,6 @@ exports.getNumNotificationsByToken = function(req, res) {
message: 'User not found.'
});
} else if (user) {
res.status(200).jsonp(user.notifications);
}
});
@ -273,7 +271,6 @@ exports.getNotifications = function(req, res) {
message: 'User not found.'
});
} else if (user) {
notificationModel.find({
'user': user._id,
'state': 'pendent'
@ -287,7 +284,7 @@ exports.getNotifications = function(req, res) {
message: 'No pendent notifications.'
});
} else if (notifications) {
//here, maybe in the future is better delete the viewed notifications
//here, maybe in the future is better delete the viewed notifications, for the moment let's keep in the database
notificationModel.update({
state: "pendent"
}, {
@ -321,12 +318,6 @@ exports.getNotifications = function(req, res) {
});
};
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
function postImage(req, res, filename, fileImg) {
url = "http://127.0.0.1:3050/image";
var importFile = function(fileImg) {
@ -361,19 +352,9 @@ exports.updateUser = function(req, res) {
if (req.body.newAvatar) {
urlImg = postImage(req, res, "avatar_" + req.body.username, req.body.newAvatar);
}
/*if (req.body.newFaircoin) {
urlImg = postImage(req, res, "fairdir_"+req.body.username,req.body.newFaircoin);
}*/
if (!req.body.newAvatar) {
updateUserWithNewImages(req, res, req.body.avatar);
}
/*userModel.update({
'token': req.headers['x-access-token']
}, req.body,
function(err) {
if (err) return console.log(err);
exports.getUserByToken(req, res);
});*/
};
//DELETE - Delete a user with specified ID
@ -392,7 +373,7 @@ exports.likeUser = function(req, res) {
userModel.findOne({
'token': req.headers['x-access-token']
})
.exec(function(err, userL) {
.exec(function(err, userL) {//userL is the user that is performing the like
if (err) return res.send(500, err.message);
if (!userL) {
res.json({
@ -400,7 +381,6 @@ exports.likeUser = function(req, res) {
message: 'no user with that token, login again'
});
} else if (userL) {
userModel.findOne({
_id: req.params.userid,
likes: {
@ -415,7 +395,6 @@ exports.likeUser = function(req, res) {
message: 'Like not posible, user not exist, or like was already done'
});
} else if (user) {
//res.status(200).jsonp(user);
var notification = new notificationModel({
concept: "like",
message: "user " + userL.username + " adds a like to you",
@ -445,7 +424,7 @@ exports.unlikeUser = function(req, res) {
userModel.findOne({
'token': req.headers['x-access-token']
})
.exec(function(err, userL) {
.exec(function(err, userL) {//userL is the user that is performing the unlike
if (err) return res.send(500, err.message);
if (!userL) {
res.json({
@ -453,7 +432,6 @@ exports.unlikeUser = function(req, res) {
message: 'no user with that token, login again'
});
} else if (userL) {
userModel.findOne({
_id: req.params.userid,
likes: userL._id
@ -466,7 +444,6 @@ exports.unlikeUser = function(req, res) {
message: 'Unlike not posible'
});
} else if (user) {
//res.status(200).jsonp(user);
var notification = new notificationModel({
concept: "like",
message: "user " + userL.username + " removes like on you",
@ -493,7 +470,8 @@ exports.unlikeUser = function(req, res) {
} //end of else if userL
});
};
/* fav */
//currently not used
exports.addFav = function(req, res) {
var tokenuser;
userModel.find({
@ -550,6 +528,7 @@ exports.addFav = function(req, res) {
});
};
//currently not used
exports.doUnfav = function(req, res) {
var tokenuser;
userModel.find({
@ -575,6 +554,7 @@ exports.doUnfav = function(req, res) {
});
});
};
exports.changePassword = function(req, res) {
userModel.findOne({
'token': req.headers['x-access-token'],

+ 1
- 0
models/userModel.js

@ -15,6 +15,7 @@ var userSchema = new Schema({
email: { type: String, required: true, select: false },
phone: { type: String },
telegram: { type: String },
localNode: { type: String },
validated: { type: Boolean, default: false },
validatedBy: {
type: mongoose.Schema.Types.ObjectId,

BIN
rmMongodbDatabases


+ 16
- 0
runDevEnvironment.sh

@ -0,0 +1,16 @@
# simple bash script to run the system locally without Docker
SESSION='CommonRoutes_Dev'
tmux new-session -d -s $SESSION
tmux split-window -d -t 0 -v
tmux split-window -d -t 0 -h
tmux split-window -d -t 2 -h
tmux send-keys -t 0 'node server.js' enter
tmux send-keys -t 1 'cd ../commonroutesApp && ionic serve' enter
tmux send-keys -t 2 'cd ../commonroutesAdminWeb && http-server' enter
tmux attach

+ 31
- 39
server.js

@ -18,11 +18,6 @@ mongoose.connect(config.database, function(err, res) {
app.set('superSecret', config.secret); // secret variable
// Middlewares
/*app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());*/
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(methodOverride());
@ -31,22 +26,19 @@ app.use(methodOverride());
app.use(morgan('dev'));
// Import Models and controllers
/*
var userMdl = require('./models/userModel')(app, mongoose);
var notificationMdl = require('./models/notificationModel')(app, mongoose);
var travelMdl = require('./models/travelModel')(app, mongoose);
var commentMdl = require('./models/commentModel')(app, mongoose);
var adminMdl = require('./models/adminModel')(app, mongoose);
*/
var userMdl = require('./models/userModel');
var notificationMdl = require('./models/notificationModel');
var travelMdl = require('./models/travelModel');
var commentMdl = require('./models/commentModel');
var adminMdl = require('./models/adminModel');
var userCtrl = require('./controllers/userController');
var searchCtrl = require('./controllers/searchController');
var travelCtrl = require('./controllers/travelController');
var adminCtrl = require('./controllers/adminController');
/*// Example Route
var router = express.Router();
router.get('/', function(req, res) {
res.send("Hello world!");
});
app.use(router);*/
app.use(express.static(__dirname + '/www'));
@ -61,6 +53,7 @@ app.use(function(req, res, next) {
// API routes ------------------------------------------------------
var apiRoutes = express.Router();
// public routes
apiRoutes.route('/login')
.post(userCtrl.login);
apiRoutes.route('/signup')
@ -80,16 +73,13 @@ apiRoutes.route('/admin/login')
/*apiRoutes.route('/admin/signup')
.post(adminCtrl.signup);*/
// 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) {
// route middleware to verify the 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
if (token) {// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
return res.send(204,
@ -97,28 +87,25 @@ apiRoutes.use(function(req, res, next) {
success: false,
message: 'Failed to authenticate token.'
});
} else {
// if everything is good, save to request for use in other routes
} 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
// if there is no token, return an error
return res.status(204).send({
success: false,
message: 'No token provided.'
});
}
}); //fi verificació de token
}); //end token verification middleware
//admin
// private routes (needs to be logged)
//admin routes
apiRoutes.route('/admins')
.get(adminCtrl.getAllAdmins);
apiRoutes.route('/admin/network')
@ -134,12 +121,15 @@ apiRoutes.route('/admin/users/validate/id/:userid')
apiRoutes.route('/admin/users/unvalidate/id/:userid')
.post(adminCtrl.unvalidateUser);
// general routes
apiRoutes.route('/search/:searchstring')
.get(searchCtrl.searchByString);
apiRoutes.route('/numnotifications')
.get(userCtrl.getNumNotificationsByToken);
apiRoutes.route('/notifications')
.get(userCtrl.getNotifications);
// user routes
apiRoutes.route('/users/token')
.get(userCtrl.getUserByToken);
apiRoutes.route('/users')//agafa l'user a partir del token
@ -147,7 +137,14 @@ apiRoutes.route('/users')//agafa l'user a partir del token
.delete(userCtrl.deleteUser);
apiRoutes.route('/changePassword')//agafa l'user a partir del token
.put(userCtrl.changePassword);
apiRoutes.route('/users/id/likes/:userid')
.get(userCtrl.getUserLikes);
apiRoutes.route('/users/id/like/:userid')
.post(userCtrl.likeUser);
apiRoutes.route('/users/id/unlike/:userid')
.post(userCtrl.unlikeUser);
//travels routes
apiRoutes.route('/users/id/travels/:userid')
.get(userCtrl.getTravelsByUserId);
apiRoutes.route('/travels')
@ -167,18 +164,10 @@ apiRoutes.route('/travels/acceptJoin/:travelid')
.post(travelCtrl.acceptJoin);
apiRoutes.route('/users/id/likes/:userid')
.get(userCtrl.getUserLikes);
apiRoutes.route('/users/id/like/:userid')
.post(userCtrl.likeUser);
apiRoutes.route('/users/id/unlike/:userid')
.post(userCtrl.unlikeUser);
//FINS AQUÏ COMPROVAT
//not yet used routes
apiRoutes.route('/travels/comment/:travelid')
.get(travelCtrl.getCommentsByTravelId);
/*apiRoutes.route('/travels/join/:travelId')
.post(travelCtrl.addJoin);
apiRoutes.route('/travels/unjoin/:travelId')
@ -197,6 +186,9 @@ apiRoutes.route('/users/:userId/unfav')
apiRoutes.route('/travels/:travelId/comment')
.post(travelCtrl.addComment);
app.use('/api', apiRoutes);
// end of API routes -------------------------------------

Loading…
Cancel
Save