Example #1
0
var express = require('express')
var router = express.Router()
var mongoose = require('mongoose')
var passport = require('passport')
var jwt = require('express-jwt')

var User = mongoose.model('User')
var Product = mongoose.model('Product')
var Note = mongoose.model('Note')

var auth = jwt({secret: process.env.TOKEN_SIGN, userProperty: 'payload'})

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index')
})

router.get('/notes', function(req, res, next) {
  Note.find(function(err, notes){
    if (err) return next(err)
    res.json(notes)
  })
})

router.param('note', function(req, res, next, id) {
  var query = Note.findById(id)

  query.exec(function (err, note){
    if (err) { return next(err) }
    if (!note) { return next(new Error('can\'t find note')) }
Example #2
0
var router = require('express').Router();
var authController = require('../controllers/authentication-controller');
var profileController = require('../controllers/profile-controller');
var friendController = require('../controllers/friend-controller');
var messageController = require('../controllers/message-controller');
var userController = require('../controllers/user-controller');
var jwt = require('express-jwt');


var auth = jwt({
    secret: process.env.JWT_SECRET,
    userProperty: 'payload',
    getToken: function (req) {
        if (req.headers.access_token) {
            return req.headers.access_token;
        } else return null;
    }
});

//AuthController
router.post('/auth/login', authController.login);
router.post('/auth/register', authController.register);

//ProfileController
router.get('/profile', auth, profileController.getProfile);

//FriendController
router.get('/friends', auth, friendController.getFriends);
router.get('/friends/requests', auth, friendController.getFriendsRequests);

Example #3
0
var express 	= require('express');
var router 		= express.Router();
var passport 	= require('passport');
var jwt 		= require('express-jwt');
var auth 		= jwt({ secret: 'SECRET', userProperty: 'payload' });

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

var mongoose = require('mongoose');
require('../models/Albums');
require('../models/Tracks');
require('../models/Users');
var User  = mongoose.model('User');
var Album = mongoose.model('Album');
var Track = mongoose.model('Track');

//get all albums from server
router.get('/albums', function(req, res, next){
	Album.find(function(err, albums){
		if(err){ return next(err); }

		res.json(albums);
	});
});

//BEGIN Define route Objects used in parameters
router.param('album', function(req, res, next, id){
	var query = Album.findById(id);
var db = mongoose.connect(config.dbLocation);

// Add headers
app.use(function(req, res, next) {

    res.setHeader('Access-Control-Allow-Origin', 'http://dev.sandbox.com:8080');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Key');

    next();
});

var port = process.env.PORT || 5000;


app.use(cors());
app.use(morgan('dev'));
app.use(express.static('public'));
app.use(bodyParser.json());
app.use('/api', expressJwt({
    secret: config.secret
}));
app.use('/api/wishitem', require('./app/routes/wishlistRoutes.js'));
app.use('/api/products', require('./app/routes/productRoutes.js'));
app.use('/auth', require('./app/routes/authRoutes.js'));

app.listen(port, function() {
    console.log('We are listening on port ' + port + '.');
});
Example #5
0
app.get('/ideas/device/:deviceID', routes.ideas.findAllForDevice);
app.get('/ideas/idea/:id', routes.ideas.findById);
app.get('/ideas', routes.ideas.findAll);
app.get('/ideas/feed', routes.ideas.findAllPublic);
//app.get('/ideas/feed/private', routes.ideas.findAllPrivate);

//ALL POST ROUTES
//app.post('/ideas/synchronize/:id', jwt({secret: cloudSecretToken}), tokenManager.verifyToken, routes.ideas.synchronize);
app.post('/ideas/synchronize/:id', routes.ideas.synchronize);
app.post('/ideas/idea', routes.ideas.addIdea);

//Create a new user/device
app.post('/user/register', routes.users.register);

//Login
app.post('/user/signin', routes.users.signin);


//app.post('/ideas/:id/inspire', routes.ideas.inspire);

//ALL DELETE ROUTES
app.delete('/ideas/delete/:id', jwt({secret: cloudSecretToken}), tokenManager.verifyToken, routes.ideas.deleteIdea);


var port = Number(process.env.PORT || 4000);
app.listen(port);

expireChecker.startCheckerJobInterval();


console.log('Listening on port 4000...');
Example #6
0
var express = require('express');
var router = express.Router()
var mongoose = require('mongoose');
var jwt = require('express-jwt');
var auth = jwt({secret: 'myLittleSecret'});
var passport = require('passport');

require('../config/passport');

var Post = require('../models/Posts');
var Comment = require('../models/Comments');
var User = require('../models/Users');

router.post('/register', function(req, res, next){
  if(!req.body.username || !req.body.password){
    return res.status(400).json({message: 'Please fill out all fields'});
  }

  var user = new User();

  user.username = req.body.username;

  user.setPassword(req.body.password)

  user.save(function (err){
    if(err){ return next(err); }

    return res.json({token: user.generateJWT()})
  });
});
Example #7
0
//Node modules
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var hresp = require('./resources/response.js');
var passport = require('passport');
var session = require('express-session');
var flash = require('connect-flash');
var cookieParser = require('cookie-parser');
var auth = require('basic-auth');
var jwt = require('jsonwebtoken');
var jwtC = require('express-jwt');
var jwtCheck = jwtC;
var token = jwt.sign({ foo: 'bar' }, 'shhhhh');
var jwtCheck = jwtC({
    secret: 'shhhhh'
});
var config = require('./config/config.js')();
//make app and router
var router = express.Router();
var app = express();
// call socket.io to the app
app.io = require('socket.io')();


//models
var Chat = require('./models/chat.js');
var Customer = require('./models/customer.js');
var Category = require('./models/category.js');
var Employee = require('./models/employee.js');
var Notification = require('./models/notification.js');
Example #8
0
var express = require('express');
var router = express.Router();
var jwt = require('express-jwt');
var auth = jwt({
  secret: process.env.JWT_SECRET,
  userProperty: 'payload'
});

var ctrlLocations = require('../controllers/locations');
var ctrlReviews = require('../controllers/reviews');
var ctrlAuth = require('../controllers/authentication');

router.get('/locations', ctrlLocations.locationsListByDistance);
router.post('/locations', ctrlLocations.locationsCreate);
router.get('/locations/:locationid', ctrlLocations.locationsReadOne);
router.put('/locations/:locationid', ctrlLocations.locationsUpdateOne);
router.delete('/locations/:locationid', ctrlLocations.locationsDeleteOne);

// reviews
router.post('/locations/:locationid/reviews', auth, ctrlReviews.reviewsCreate);
router.get('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsReadOne);
router.put('/locations/:locationid/reviews/:reviewid', auth, ctrlReviews.reviewsUpdateOne);
router.delete('/locations/:locationid/reviews/:reviewid', auth, ctrlReviews.reviewsDeleteOne);

// authentication
router.post('/register', ctrlAuth.register);
router.post('/login', ctrlAuth.login);

module.exports = router;
  stream: logger.stream
}));

var nconf = require('nconf');
nconf.env()
  .file({ file: './config.json' })
	.defaults({
		PORT: 7001
	});

/*
 * Middleware that will validate the incoming access token.
 */
var jwtCheck = jwt({
  secret: publicKey,
  audience: nconf.get('RESOURCE_SERVER'),
  issuer: 'https://' + nconf.get('AUTH0_DOMAIN') + '/'
});

/*
 * Middleware that checks if a scope is available in the current user.
 */
var requireScope = function(expected_scope){
  return function (req, res, next){
    if (!req.user || req.user.scope.split(' ').indexOf(expected_scope) < 0) {
      return next(new Error('Cannot perform action. Missing scope ' + expected_scope));
    }
    next();
  };
};
Example #10
0
var authRoute = require("./routes/auth");
var catRoute = require("./routes/category");
var feeRoute = require("./routes/fee");
var listingRoute = require("./routes/listing");
var memberRouter = require("./routes/member");
var statusRoute = require("./routes/status");
var watchlistRouter = require("./routes/watchlist");
var ConfigManager_1 = require("./utility/ConfigManager");
var config = new ConfigManager_1.ConfigManager.Configuration();
config.setEnvrionment(ConfigManager_1.ConfigManager.Environment.Sandbox);
var secretKey = new ConfigManager_1.ConfigManager.Configuration().get().SecretKey;
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({ resave: false, saveUninitialized: false, secret: secretKey }));
app.use(expressjwt({ secret: secretKey }).unless({ path: [/\/auth/i, /\/category/i] }));
app.use("/auth", authRoute.router);
app.use("/category", catRoute.router);
app.use("/fee", feeRoute.router);
app.use("/listing", listingRoute.router);
app.use("/member", memberRouter.router);
app.use("/status", statusRoute.router);
app.use("/watchlist", watchlistRouter.router);
app.use(function (err, req, res, next) {
    if (err.name === "UnauthorizedError") {
        res.status(401).json("No authorization token was found");
    }
});
var options = {
    key: fs.readFileSync("./src/cert/key.pem"),
    cert: fs.readFileSync("./src/cert/cert.pem")
Example #11
0
var app = express();

app.use("/", express.static(__dirname + '/pages'));
app.use('/js', express.static(__dirname + '/js'));
app.use('/images', express.static(__dirname + '/images'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));
app.use('/templates', express.static(__dirname + '/templates'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));

app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser());
app.use(express.bodyParser());

app.use('/api', jwtAuth({secret: 'fk139d0sl30sl'}));


var _connection = mysql.createConnection({
  host     : 'localhost',
  port     : '3306',
  user     : 'silentauction',
  database : 'SilentAuction',
  password : '11x6jcyKc08'
});

app.post('/authenticate', function (req, res) {
  //TODO - hash the password on the client.
  //if is invalid, return 401

  var password = crypto.createHash('md5').update(req.body.password).digest('hex');
Example #12
0
var md5 = require('md5');
var expressJwt = require('express-jwt');
var jwt = require('jsonwebtoken');
var knex = require('knex')({
    client: 'mysql',
    connection: {
        host     : '127.0.0.1',
        user     : 'root',
        password : 'shell',
        database : 'ams'
    }
});
app.use(express.json());
app.use(express.urlencoded());
var memberTypes = ['Artists','Venues','Advertisers','Event Promoters','Fans'];
app.use('/api/restricted',expressJwt({secret:secret}));
app.get('/api/restricted',function(req,res){
    "use strict";
    console.log('restricted route authorized');
    res.sendStatus(200);
});


app.get('/mysql-init',function(req,res){
    "use strict";
    var Events = mysql.define('events',{
        id:Sequelize.INTEGER.unsigned,
        ownerId:Sequelize.INTEGER.unsigned,
        title:Sequelize.STRING,
        description:Sequelize.STRING,
        date:Sequelize.DATE,
Example #13
0
require("./config/passport")(passport);

app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride(function(req, res){
  if (req.body && typeof req.body === "object" && "_method" in req.body){
    var method = req.body._method;
    delete req.body._method;
    return method;
  }
}));
app.use(passport.initialize());

app.use('/api', expressJWT({ secret: config.secret })
.unless({
  path: [
    { url: '/api/login', methods: ['POST'] },
    { url: '/api/register', methods: ['POST'] }
  ]
}));


app.use(function (err, req, res, next) {
  if (err.name === 'UnauthorizedError') {
    return res.status(401).json({message: 'Unauthorized request.'});
  }
  next();
});
Example #14
0
      user = utils.getCleanUser(user); //dont pass password and stuff

      //note: you can renew token by creating new token(i.e. refresh it) w/ new expiration time at this point, but I'm passing the old token back.
      // var token = utils.generateToken(user);

      res.json({
        user: user,
        token: token
      });

    });
  });
});

router.get('/resendValidationEmail', expressJwt({
  secret: process.env.JWT_SECRET
}), function(req, res, next) {

  User.findById({
    '_id': req.user._id
  }, function(err, user) {
    if (err) throw err;

    //send welcome email w/ verification token
    email.sendWelcomeEmail(user, req.headers.host, function(err) {
      if (err) {
        res.status(404).json(err);
      } else {
        res.send({
          message: 'Email was resent'
        })
Example #15
0
File: index.js Project: dcic/LDR
var jwt = require('express-jwt'),
  baseUrl = require('../config/baseUrl').baseUrl,
  config = require('../config/database');

var jwtCheck = jwt({
  secret: config.secret
});

module.exports = function(app) {
  'use strict';

  app.get(baseUrl + '/api/version', function(req, res) {
    res.status(200).send(require('../../../package.json').version);
  });

  app.use('/api/secure', jwtCheck);

  require('./users')(app);
  require('./admin')(app);
  require('./groups')(app);
  require('./metadata')(app);
  require('./releases')(app);

};
Example #16
0
var express = require("express");
var app = express();
var http = require("http");
var bodyParser = require("body-parser");
var server = http.createServer();
var expressJWT = require("express-jwt");
var port = 3000;

//MIS ARCHIVOS
var api = require('./routes/controllers/api');
var key = require("./functions/key").key();

//configurar app
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressJWT({secret: key}).unless({path: ['/login', '/usuarios/ingresar']}));
app.use(api.validar_token);
/*app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));*/

//******************************LLAMADAS***********************************************************************

//pagina inicial
app.get("/", api.main);
//obtener usuario por id
app.get("/usuarios/:id", api.obtener_usuario_por_id);
//obtener todos los usuarios api.obtener_usuarios
app.get("/usuarios", api.obtener_usuarios);
//obtener usuario por cuenta
app.get("/usuarios/cuenta/:usuario", api.obtener_usuario_por_cuenta);
//ingresar nuevo usuario forma
Example #17
0
import { Router } from 'express';
import sign from './controllers/sign';
import demo from './controllers/demo';
import jwt from 'express-jwt'
import config from './config'
const router = Router();

router.get('/test1', sign.test1)
router.get('/test2', jwt({secret: config.secret}), sign.test2)

// sign
router.post('/register', sign.register);
router.post('/login', sign.login);

// register verify 
// router.get('/verify', sign.verify);

// reset password
router.post('/reset', sign.reset)
router.post('/find_pwd', sign.findPwd)

// demo
router.get('/demos', jwt({secret: config.secret}), demo.list)
router.get('/demos/:id', jwt({secret: config.secret}), demo.get)
router.post('/demos', jwt({secret: config.secret}), demo.create)
router.put('/demos/:id', jwt({secret: config.secret}), demo.update)
router.delete('/demos/:id', jwt({secret: config.secret}), demo.remove)

// preview
router.get('/preview:id', demo.preview)
Example #18
0
module.exports = function(app, config) {
    var apiPrefix = '/api';
    var jwtOptions = {
        secret: config.sessionSecret
    };
    
    // auth
    app.post(apiPrefix + '/login', auth.login);
    app.post(apiPrefix + '/signup', user.checkUser, incode, auth.signup);
    app.get(apiPrefix + '/users/:userId/verify', auth.verify);

    // users
    app.get(apiPrefix + '/user', expressJwt(jwtOptions), user.getUserByToken);
    app.put(apiPrefix + '/user', expressJwt(jwtOptions), user.putUser)
    app.get(apiPrefix + '/users', user.getUsers);
    app.get(apiPrefix + '/users/:userId', user.getUserById);

    // sources
    app.get(apiPrefix + '/source/check', source.checkSource);
    app.get(apiPrefix + '/sources', source.getSources);
    app.post(apiPrefix + '/sources', expressJwt(jwtOptions), source.postSource);
    app.get(apiPrefix + '/sources/:sourceId', source.getSourceById);
    app.put(apiPrefix + '/sources/:sourceId', expressJwt(jwtOptions), source.putSourceById);
    app.get(apiPrefix + '/sources/:sourceId/characters', character.getCharactersBySourceId);

    // characters
    app.get(apiPrefix + '/character/check', character.checkCharacter);
    app.get(apiPrefix + '/characters', character.getCharacters);
    app.post(apiPrefix + '/characters', expressJwt(jwtOptions), character.postCharacter);
    app.get(apiPrefix + '/characters/:characterId', character.getCharacterById);
    app.put(apiPrefix + '/characters/:characterId', expressJwt(jwtOptions), character.putCharacterById);
    app.get(apiPrefix + '/characters/:characterId/quotes', quote.getQuotesByCharacterId);

    // quotes
    app.get(apiPrefix + '/quotes', quote.getQuotes);
    app.post(apiPrefix + '/quotes', expressJwt(jwtOptions), quote.postQuote);
    app.get(apiPrefix + '/quotes/:quoteId', customJwt(jwtOptions), quote.getQuoteById);
    app.put(apiPrefix + '/quotes/:quoteId', expressJwt(jwtOptions), quote.putQuoteById);
    app.put(apiPrefix + '/user/like/quotes/:quoteId', expressJwt(jwtOptions), quote.putQuoteLikerIdById);
    app.delete(apiPrefix + '/user/like/quotes/:quoteId', expressJwt(jwtOptions), quote.deleteQuoteLikerIdById);

    // search
    app.get(apiPrefix + '/search', search.search);

    // upload
    app.get(apiPrefix + '/upload/token', expressJwt(jwtOptions), qiniu.getUploadToken);

    // wechat
    app.use(wechat.router);

};
Example #19
0
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');

var jwtSecret = 'sjfhgsdfj345345/dfg';

var user = {
    username: 'ASDAlexey',
    password: "121314"
};

var app = express();

app.use(cors());
app.use(bodyParser.json());
app.use(expressJwt({secret: jwtSecret}).unless({path: ['/login']}));

app.get('/random-user', function(req, res){
    var user = faker.helpers.createCard();
    user.avatar = faker.image.avatar();
    res.json(user);
});
app.get('/me', function(req, res){
    res.json(req.user);
});
app.post('/login', authenticate, function(req, res){
    var token = jwt.sign({
        username: user.username
    }, jwtSecret);
    res.send({
        token: token,
Example #20
0
var constants = require('../constants/index');
var settings = require('./settings');
var expressJwt = require('express-jwt');
var logger = require(__common + '/tools/logger')('Authentificator');

var secret = new Buffer(__env.JWTSECRET, 'base64');
var anonymous = { isAuthenticated: false };
var cookieAge = 1000 * 60 * 60 * 24 * 7; //week

var jwtmidlware = expressJwt({
	secret: secret,
	getToken: function (req) {
		//console.log(req.cookies.authorization);
		
		if (req.cookies.authorization) {
			return req.cookies.authorization;
		}

		return jwt.sign(anonymous, secret);
	}
});

function sign(res, model) {
	var token = jwt.sign(model, secret);
	res.cookie('authorization', token, { maxAge: cookieAge, httpOnly: true });
	return token;
}


function logout(res) {
	var token = jwt.sign(anonymous, secret);
Example #21
0
File: service.js Project: agopu/sca
/**
 * @api {get} /service          GetService
 * @apiGroup                    Service
 * @apiDescription              Query for SCA services 
 *
 * @apiParam {Object} [find]    Mongo find query - defaults to {}
 * @apiParam {Object} [sort]    Mongo sort object - defaults to {}
 * @apiParam {String} [select]  Fields to load - defaults to 'logical_id'
 * @apiParam {Number} [limit]   Maximum number of records to return - defaults to 100
 * @apiParam {Number} [skip]    Record offset for pagination
 *
 * @apiHeader {String}          Authorization A valid JWT token "Bearer: xxxxx"
 *
 * @apiSuccess {Object[]}       Services Service detail
 */
router.get('/', jwt({secret: config.sca.auth_pubkey}), function(req, res, next) {
    var find = {};
    if(req.query.find) find = JSON.parse(req.query.find);
    find.user_id = req.user.sub; //always set this
    //logger.debug(find);

    db.Service.find(find)
    .select(req.query.select || 'name user_id register_date pkg git.clone_url git.description')
    .limit(req.query.limit || 100)
    .skip(req.query.skip || 0)
    .sort(req.query.sort || '_id')
    .exec(function(err, services) {
        if(err) return next(err);
        db.Service.count(find).exec(function(err, count) {
            if(err) return next(err);
            res.json({services: services, count: count});
Example #22
0
});

var kueIdentity = uuid.v4();
var singleNodeCache = {};

AWS.config.loadFromPath('./config.json');
nconf.file('./config.json');

app.use(logger('combined'));
app.use(express.bodyParser());
app.use(express.json());
app.use(express.urlencoded());

app.use("/", express.static(__dirname + '/public') );

app.use('/api/private/', expressJwt({secret: nconf.get("sha_noise")}));

var users = {};
users['john.doe'] = {
    uid : '231312',
    tid : '179373',
    name : 'John Doe',
    username : 'john.doe',
    password : 'foobar'
}
users['william.smith'] = {
    uid : '213789',
    tid : '481903',
    name : 'William Smith',
    username : 'william.smith',
    password : 'bar'
Example #23
0
var express = require("express");
var logfmt = require("logfmt");
var mongoose = require("mongoose");
var expressJwt = require('express-jwt');
var jwt = require('jsonwebtoken');
var app = express();


var secret = 'this is the secret secret secret 12356';
mongoose.connect('mongodb://phrumadb:cookie5910@ds039058.mongolab.com:39058/login');
var Schema = mongoose.Schema;

app.use(logfmt.requestLogger());

app.use('/api', expressJwt({secret: secret}));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.static(__dirname + '/public')); 	// set the static files location /public/img will be /img for users

var user = mongoose.model('User', new Schema({ 
  username: String,
  email : String,
  password : String
}),'users');

app.post('/newuser',function(req,res){

  user.find({username : req.body.username},function(err,data){
    console.log(data[0]);
    if(data[0] != null){
      console.log("ich geh hier rein");
Example #24
0
fs.readFile("./secret.txt", function(err, data) {
	if(err) {
		return console.log(err);
	}
	app.use(expressJWT({ secret: data }).unless({ path: ["/test", "/login", "/register"]}));
});
'use strict';

var mongoose = require('mongoose');
var passport = require('passport');
var config = require('../config/environment');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');
var compose = require('composable-middleware');
var User = require('../api/user/user.model');
var validateJwt = expressJwt({ secret: config.secrets.session });

/**
 * Attaches the user object to the request if authenticated
 * Otherwise returns 403
 */
function isAuthenticated() {
  return compose()
    // Validate jwt
    .use(function(req, res, next) {
      // allow access_token to be passed through query parameter as well
      if(req.query && req.query.hasOwnProperty('access_token')) {
        req.headers.authorization = 'Bearer ' + req.query.access_token;
      }
      validateJwt(req, res, next);
    })
    // Attach user to request
    .use(function(req, res, next) {
      User.findById(req.user._id, function (err, user) {
        if (err) return next(err);
        if (!user) return res.status(401).send('Unauthorized');
                        ", Latitude: " + geo.ll[0] + ", Longitude: " + geo.ll[1] + " Location: " + data.results[0].formatted_address;
                    logger.error({errorDescription: errorDescription, username: userDetails.username, errorCode: AuthenticationModuleErrorCodes.FOUNDER_SERVICES_RESTRICTED_ACCESS_ERRORCODE });
                });
            } catch (error) {
                var errorDescription = "The normal user: " + userDetails.username + " tried to access founder services";
                logger.error({errorDescription: errorDescription, username: userDetails.username, errorCode: AuthenticationModuleErrorCodes.FOUNDER_SERVICES_RESTRICTED_ACCESS_ERRORCODE});
            }
            response.json({InternalStatusCode: 423, ErrorMessage: 'User Dont Have Founder Previligers'});
        }
    } else {
        response.json({InternalStatusCode: 421, ErrorMessage: 'User Not Authenticated'});
    }
}


collegeToCorporateApp.use(expressJwt({secret: secret}).unless({path: ['/admin/*', '/founders/*', '/login', '/register', '/emailvalidation', '/checkforusername', '/checkforemail','/getStatus']}));
collegeToCorporateApp.all("/admin/*", adminCheck, function (request, response, next) {
    next();
});
collegeToCorporateApp.all("/founders/*", founderCheck, function (request, response, next) {
    next();
});


logger.add(logger.transports.File, { filename: 'collegeToCorporateAppLogFile.log', level: 'warn' });

//Creating mysql database connection
var sqlConnection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'peacock',
Example #27
0
module.exports = function(app) {
  var jwt = require('express-jwt');
  var admin = require('../controllers/admin_controller');
  var games = require('../controllers/games_controller');
  var series = require('../controllers/series_controller');
  var persons = require('../controllers/person_controller');
  var groups = require('../controllers/groups_controller');
  require('../controllers/event_handlers');

  var authCheck = jwt({
    secret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
    audience: process.env.AUTH0_CLIENT_ID
  });

  // SYSTEM VARS
  app.get('/api/systemVars', authCheck, persons.getSystemVars);

  // GAMES
  app.get('/api/games', authCheck, games.getGames);
  app.get('/api/notMyGames', authCheck, games.getNotMyGames);
  app.get('/api/gamesMatchList', authCheck, games.getGamesWithPossibleMatchInfo);
  app.get('/api/possibleGameMatches', authCheck, games.getPossibleGameMatches);

  app.post('/api/updategame', authCheck, games.updateGame);
  app.post('/api/updatePersonGame', authCheck, games.updatePersonGame);
  app.post('/api/addgame', authCheck, games.addGame);
  app.post('/api/addToMyGames', authCheck, games.addToMyGames);
  app.post('/api/addgameplay', authCheck, games.addGameplaySession);

  // TV
  app.get('/api/episodeGroupRating', authCheck, series.getEpisodeGroupRating);
  app.get('/api/episodeGroupRatings', authCheck, series.getEpisodeGroupRatings);
  app.get('/api/numShowsToRate', authCheck, series.getNumberOfShowsToRate);
  app.get('/api/viewingLocations', authCheck, series.getViewingLocations);
  app.get('/api/allPosters', authCheck, series.getAllPosters);
  app.get('/api/seriesViewingLocations', authCheck, series.getSeriesViewingLocations);
  app.get('/api/upcomingEpisodes', authCheck, series.getUpcomingEpisodes);
  app.get('/api/ratingYears', authCheck, series.getAllRatingYears);
  app.get('/api/episodeListForRating', authCheck, series.getEpisodesForRating);
  app.get('/api/tvdbMatches', authCheck, series.getTVDBMatches);
  app.get('/api/tvdbIDs', authCheck, series.getMatchedTVDBIDs);

  // ADMIN
  app.get('/api/tvdbErrors', authCheck, admin.getTVDBErrors);
  app.get('/api/services', authCheck, admin.getExternalServices);
  
  // API for iOS app
  app.get('/primeTV', authCheck, series.getPrimeTV);
  app.get('/primeSeriesInfo', authCheck, series.getPrimeSeriesInfo);

  app.post('/api/updateEpisode', authCheck, series.updateEpisode);
  app.post('/api/changeTier', authCheck, series.changeTier);
  app.post('/api/addSeries', authCheck, series.addSeries);
  app.post('/api/updateSeries', authCheck, series.updateSeries);
  app.post('/api/updateEpisodeGroupRating', authCheck, series.updateEpisodeGroupRating);
  app.post('/api/addEpisodeGroupRating', authCheck, series.addEpisodeGroupRating);
  app.post('/api/addViewingLocation', authCheck, series.addViewingLocation);
  app.post('/api/removeViewingLocation', authCheck, series.removeViewingLocation);
  app.post('/api/handleSeriesRequest', authCheck, series.handleSeriesRequest);

  // PERSONS
  app.get('/api/person', authCheck, persons.getPersonInfo);
  app.get('/api/persons', authCheck, persons.getPersons);

  // MY SHOWS
  app.get('/api/myShows', authCheck, persons.getMyShows);
  app.get('/api/myQueueShows', authCheck, persons.getMyQueueShows);
  app.get('/api/myPendingShows', authCheck, persons.getMyPendingShows);
  app.get('/api/notMyShows', authCheck, persons.getNotMyShows);
  app.get('/api/getMyEpisodes', authCheck, persons.getMyEpisodes);
  app.get('/api/seriesDetail', authCheck, persons.getSeriesDetailInfo);
  app.get('/api/seriesRequest', authCheck, persons.getAllOpenSeriesRequests);
  app.get('/api/mySeriesRequests', authCheck, persons.getMySeriesRequests);
  app.get('/api/nextAired', authCheck, persons.getNextAiredInfo);

  app.post('/api/addToMyShows', authCheck, persons.addToMyShows);
  app.post('/api/removeFromMyShows', authCheck, persons.removeFromMyShows);
  app.post('/api/updateMyShow', authCheck, persons.updateMyShow);
  app.post('/api/rateMyShow', authCheck, persons.rateMyShow);
  app.post('/api/rateMyEpisode', authCheck, persons.rateMyEpisode);
  app.post('/api/markMyPastWatched', authCheck, persons.markAllPastEpisodesAsWatched);
  app.post('/api/increaseYear', authCheck, persons.increaseYear);
  app.post('/api/revertYear', authCheck, persons.revertYear);
  app.post('/api/seriesRequest', authCheck, persons.seriesRequest);
  app.post('/api/markEpisodesWatched', authCheck, persons.markEpisodesWatched);
  app.post('/api/pinToDashboard', authCheck, persons.pinToDashboard);

  // GROUPS
  app.get('/api/myGroups', authCheck, groups.getMyGroups);
  app.get('/api/groupPersons', authCheck, groups.getGroupPersons);
  app.get('/api/groupShows', authCheck, groups.getGroupShows);
  app.get('/api/groupEpisodes', authCheck, groups.getGroupEpisodes);
  app.get('/api/notGroupShows', authCheck, groups.getNotGroupShows);

  app.post('/api/createGroup', authCheck, groups.createGroup);
  app.post('/api/groupWatchEpisode', authCheck, groups.markEpisodeWatchedByGroup);
  app.post('/api/watchPastGroupEpisodes', authCheck, groups.markAllPastEpisodesAsGroupWatched);
  app.post('/api/addGroupShow', authCheck, groups.addToGroupShows);
  app.post('/api/removeGroupShow', authCheck, groups.removeFromGroupShows);
  app.post('/api/votes', authCheck, groups.submitVote);
  app.post('/api/ballots', authCheck, groups.addBallot);

  app.patch('/api/ballots', authCheck, groups.editBallot);

  // error handlers

  // development error handler
  // will print stacktrace
  if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
      console.log(err.message);
      console.log(err.stack);
      console.log("Status: " + err.status);
      res.status(err.status || 500).json({
        message: err.message,
        error: err
      });
    });
  }

  // production error handler
  // no stacktraces leaked to user
  app.use(function (err, req, res, next) {
    console.log(err.message);
    console.log(err.stack);
    console.log("Status: " + err.status);
    res.status(err.status || 500).json({
      message: err.message,
      error: err
    });
  });

};
Example #28
0
      req.validateUserJwtForLoginRecord = {
        mobile: payload.mobile,
        appUserId: payload.appUserId,
        clientId: payload.clientId,
        actionType: 'validateUserJwt',
        ownerId: doc.ownerId
      }

      var secret = doc.clientSecret;
      done(null, secret);
    });
  }
};

var validateJwt = expressJwt({
  secret: secretCallback
});

module.exports = {

  /**
   * Middleware for checking for valid authentication
   * @see {auth:service~isAuthenticated}
   */
  isAuthenticated: isAuthenticated,

  /**
   * Middleware for checking for a minimum role
   * @see {auth:service~hasRole}
   */
  hasRole: hasRole,
Example #29
0
  next();
});

app.use(morgan('dev'));

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));
app.use(favicon(__dirname + '/public/assets/img/table-tome-logo.png'));

mongoose.connect(process.env.MONGOLAB_URI);

// AUTHENTICATION
// --------------
var authenticate = jwt({
  secret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
  audience: process.env.AUTH0_CLIENT_ID
});

// AUTH0 MANAGEMENT
// ----------------
var ManagementClient = require('auth0').ManagementClient;
var auth0Manager = new ManagementClient({
  token: process.env.AUTH0_API_TOKEN,
  domain: process.env.AUTH0_DOMAIN
});

// ROUTES
// ======

// API ROUTES
// ----------
Example #30
0
/**
 * @apiGroup Project
 * @api {get} /project          Query projects
 * @apiDescription              Query projects registered
 *
 * @apiParam {Object} find      Optional Mongo find query - defaults to {}
 * @apiParam {Object} sort      Optional Mongo sort object - defaults to {}
 * @apiParam {String} select    Optional Fields to load - defaults to 'logical_id'
 * @apiParam {Number} limit     Optional Maximum number of records to return - defaults to 100
 * @apiParam {Number} skip      Optional Record offset for pagination
 *
 * @apiHeader {String} authorization 
 *                              A valid JWT token "Bearer: xxxxx"
 */
router.get('/', jwt({secret: config.auth.pubkey}), function(req, res, next) {
    var find = {};
    if(req.query.find) find = JSON.parse(req.query.find);
    logger.debug(find);

    db.Projects.find(find)
    .select(req.query.select || 'create_date')
    .limit(req.query.limit || 100)
    .skip(req.query.skip || 0)
    .sort(req.query.sort || '_id')
    .exec(function(err, recs) {
        if(err) return next(err);
        db.Projects.count(find).exec(function(err, count) {
            if(err) return next(err);
            res.json({projects: recs, count: count});
        });