Browse Source

userModel, eventModel, alertModel --> done; signup,login,getAllUsers,getUserById --> done

master
arnaucode 7 years ago
parent
commit
5772ddf438
8 changed files with 353 additions and 0 deletions
  1. +7
    -0
      .gitignore
  2. +8
    -0
      config.js
  3. +114
    -0
      controllers/userController.js
  4. +28
    -0
      models/alertModel.js
  5. +31
    -0
      models/eventModel.js
  6. +48
    -0
      models/userModel.js
  7. +20
    -0
      package.json
  8. +97
    -0
      server.js

+ 7
- 0
.gitignore

@ -0,0 +1,7 @@
node_modules
bower_components
.idea
npm-debug.log
platforms/
plugins/
www/lib/

+ 8
- 0
config.js

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

+ 114
- 0
controllers/userController.js

@ -0,0 +1,114 @@
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');
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,
email: req.body.email
});
user.save(function (err, user) {
if (err) return res.status(500).send(err.message);
//res.status(200).jsonp(user); en comptes de retoranr la data del signup, fem el login directament
console.log("signup fet correctament, redirigint al login internament automàtic");
exports.login(req, res);
});
};
exports.login = function (req, res) {
userModel.findOne({
email: req.body.email
})
.select('+password')
.exec(function (err, user) {
if (err) throw err;
if (!user) {
res.json({success: false, message: 'Authentication failed. User not found.'});
} else if (user) {
req.body.password = crypto.createHash('sha256').update(req.body.password).digest('base64');
if (user.password != req.body.password) {
res.json({success: false, message: 'Authentication failed. Wrong password.'});
} else {
var indexToken = -1;
for (var i = 0; i < user.tokens.length; i++) {
if (user.tokens[i].userAgent == req.body.userAgent) {
indexToken = JSON.parse(JSON.stringify(i));//stringify i parse pq es faci una còpia de la variable i, enlloc de una referència
}
}
console.log(indexToken);
if (indexToken == -1) {//userAgent no exist
var tokenGenerated = jwt.sign({foo: 'bar'}, app.get('superSecret'), {
// expiresIn: 86400 // expires in 24 hours
});
var newToken = {
userAgent: req.body.userAgent,
token: tokenGenerated,
os: req.body.os,
browser: req.body.browser,
device: req.body.device,
os_version: req.body.os_version,
browser_version: req.body.browser_version,
ip: req.body.ip,
lastLogin: Date()
};
user.tokens.push(newToken);
} else {//userAgent already exist
user.tokens[indexToken].token = "";
var tokenGenerated = jwt.sign({foo: 'bar'}, app.get('superSecret'), {
// expiresIn: 86400 // expires in 24 hours
});
user.tokens[indexToken].token = tokenGenerated;
user.tokens[indexToken].ip = req.body.ip;
user.tokens[indexToken].lastLogin = Date();
}
user.save(function (err, user) {
if (err) return res.send(500, err.message);
// return the information including token as JSON
user.password = "";
res.json({
user: user,
success: true,
message: 'Enjoy your token!',
token: tokenGenerated
});
});
}
}
});
};
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);
});
};
exports.getUserById = function (req, res) {
userModel.findOne({_id: req.params.userid})
.lean()
.populate('events', 'title description img 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);
}
});
};

+ 28
- 0
models/alertModel.js

@ -0,0 +1,28 @@
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var alertSchema = new Schema({
title: { type: String },
description: { type: String },
img: { type: String },
date: { type: Date },
location:{
direction: { type: String },
city: { type: String },
district: { type: String },
geolocation: {
lat: {type: Number},
long: {type: Number},
name: { type: String, required: true }
}
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'userModel'
}
});
alertSchema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('alertModel', alertSchema);

+ 31
- 0
models/eventModel.js

@ -0,0 +1,31 @@
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var eventSchema = new Schema({
title: { type: String },
description: { type: String },
img: { type: String },
date: { type: Date },
categories: [{
name: {type: String}
}],
location: {
direction: { type: String },
city: { type: String },
district: { type: String },
geolocation: {
lat: {type: Number},
long: {type: Number},
name: { type: String, required: true }
}
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'userModel'
}
});
eventSchema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('eventModel', eventSchema);

+ 48
- 0
models/userModel.js

@ -0,0 +1,48 @@
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var userSchema = new Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true },
password: { type: String, required: true, select: false },
tokens: [{
userAgent: {type: String},
token: {type: String, select: false},
os: {type: String},
browser: {type: String},
device: {type: String},
os_version: {type: String},
browser_version: {type: String},
ip: {type: String},
lastLogin: {type: Date},
birthdate: {type: Date},
}],
description: { type: String },
img: { type: String, default: "https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png" },
contact: {
twitter: { type: String },
facebook: { type: String },
telegram: { type: String },
web: { type: String },
phone: { type: Number }
},
location:{
direction: { type: String },
city: { type: String },
district: { type: String },
geolocation: {
lat: {type: Number},
long: {type: Number},
name: { type: String}
}
},
events: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'eventModel'
}]
});
userSchema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('userModel', userSchema);

+ 20
- 0
package.json

@ -0,0 +1,20 @@
{
"name": "openEventsPlatformServer",
"version": "0.0.1",
"description": "openEventsPlatformServer",
"repository": "https://github.com/arnaucode/openEventsPlatformServer",
"main": "server.js",
"scripts": {
"prestart": "npm install",
"start": "node server.js"
},
"dependencies": {
"body-parser": "latest",
"express": "^4.7.1",
"jsonwebtoken": "latest",
"method-override": "^2.1.2",
"mongoose": "latest",
"morgan": "latest",
"mongoose-unique-validator": "^1.0.2"
}
}

+ 97
- 0
server.js

@ -0,0 +1,97 @@
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 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');
});
app.set('superSecret', config.secret); // secret variable
// Middlewares
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(methodOverride());
// use morgan to log requests to the console
app.use(morgan('dev'));
var userMdl = require('./models/userModel')(app, mongoose);
var userCtrl = require('./controllers/userController');
var eventMdl = require('./models/eventModel')(app, mongoose);
//var eventCtrl = require('./controllers/eventController');
var alertMdl = require('./models/alertModel')(app, mongoose);
//var alertCtrl = require('./controllers/alertController');
//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();
});
// API routes ------------------------------------------------------
var apiRoutes = express.Router();
apiRoutes.route('/login')
.post(userCtrl.login);
apiRoutes.route('/signup')
.post(userCtrl.signup);
apiRoutes.route('/users')
.get(userCtrl.getAllUsers);
apiRoutes.route('/users/id/:userid')
.get(userCtrl.getUserById);
// 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.send(204, {
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(204).send({
success: false,
message: 'No token provided.'
});
}
}); //fi verificació de token
app.use('/api', apiRoutes);
// end of API routes -------------------------------------
// Start server
app.listen(config.port, function() {
console.log("Node server running on http://localhost:3000");
});

Loading…
Cancel
Save