Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/config/config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import convict from 'convict';
const convict = require('convict');

// this loads the defined variables from .env
require('dotenv').config();
Expand Down Expand Up @@ -152,4 +152,4 @@ const config = convict({
// throws error if config does not conform to schema
config.validate({ allowed: 'strict' });

export default config;
module.exports = config;
37 changes: 20 additions & 17 deletions src/config/express.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
import express from 'express';
import morgan from 'morgan';
import bodyParser from 'body-parser';
import compress from 'compression';
import methodOverride from 'method-override';
import cors from 'cors';
import helmet from 'helmet';
import passport from 'passport';

import strategies from './passport';
import routes from '../routes/v1';
import { logs } from './vars';
import config from '../config/config';

// Express instance
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const compress = require('compression');
const methodOverride = require('method-override');
const cors = require('cors');
const helmet = require('helmet');
const passport = require('passport');

const routes = require('../routes/v1');
const { logs } = require('./vars');
const strategies = require('./passport');
const error = require('../middlewares/error');

/**
* Express instance
* @public
*/
const app = express();

// request logging. dev: console | production: file
app.use(morgan(config.get('env')));
app.use(morgan(logs));

// parse body params and attache them to req.body
app.use(bodyParser.json());
Expand Down Expand Up @@ -53,4 +56,4 @@ app.use(error.notFound);
// error handler, send stacktrace only during development
app.use(error.handler);

export default app;
module.exports = app;
26 changes: 13 additions & 13 deletions src/config/passport.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import BearerStrategy from 'passport-http-bearer';
import { ExtractJwt } from 'passport-jwt';
const JwtStrategy = require('passport-jwt').Strategy;
const BearerStrategy = require('passport-http-bearer');
const { ExtractJwt } = require('passport-jwt');

import { jwtSecret } from './vars';
import authProviders from '../services/authProviders';
import User from '../models/user.model';
import config from '../config/config';
const { jwtSecret } = require('./vars');
const authProviders = require('../services/authProviders');
const User = require('../models/user.model');
const config = require('../config/config');


const JwtStrategy = require('passport-jwt').Strategy;
const getsecret = config.get('authentication.token.secret')
const getSecret = config.get('authentication.token.secret')
const jwtOptions = {
secretOrKey: getsecret,
secretOrKey: getSecret,
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'),
};

const jwts = async (payload, done) => {
const jwt = async (payload, done) => {
try {
const user = await User.findById(payload.sub);
if (user) return done(null, user);
Expand All @@ -34,6 +34,6 @@ const oAuth = service => async (token, done) => {
}
};

export const jwt = new JwtStrategy(jwtOptions, jwts);
export const facebook = new BearerStrategy(oAuth('facebook'));
export const google = new BearerStrategy(oAuth('google'));
exports.jwt = new JwtStrategy(jwtOptions, jwt);
exports.facebook = new BearerStrategy(oAuth('facebook'));
exports.google = new BearerStrategy(oAuth('google'));
14 changes: 6 additions & 8 deletions src/config/persistence/mongodb/connectdb.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,26 @@ import mongoose from 'mongoose';

const config = require('../../config');

let dbURI = 'mongodb://kayak:kayak@kayakcluster-shard-00-00-j61pv.mongodb.net:27017,kayakcluster-shard-00-01-j61pv.mongodb.net:27017,kayakcluster-shard-00-02-j61pv.mongodb.net:27017/kayak?ssl=true&replicaSet=KayakCluster-shard-0&authSource=admin';
if (process.env.NODE_ENV === 'production') {
dbURI = process.env.MONGOLAB_URI;
}
let gracefulShutdown;
let db = `${config.get('mongo.host')}/${config.get('mongo.database')}`;

mongoose.Promise = global.Promise;
// Connecting to Database
mongoose.connect(`${config.get('mongo.host')}/${config.get('mongo.database')}`);
mongoose.connect(db, { useNewUrlParser: true });

// Checking if connection to db was successful
mongoose.connection.on('connected', () => {
console.log('Mongoose successfully connected to database URL: '+config.get('mongo.database'));
console.log('Mongoose successfully connected to database URL: '+db);
});

mongoose.connection.on('error', (err) => {
console.error("Mongoose connection error occurred. Error: " + error);
console.error("Mongoose connection error occurred. Error: " + err);
});

mongoose.connection.on('disconnected', () => {
console.log("Mongoose connection lost...");
});

//
// CAPTURE APP TERMINATION / RESTART EVENTS
// To be called when process is restarted or terminated
gracefulShutdown = function (msg, callback) {
Expand Down
4 changes: 2 additions & 2 deletions src/config/vars.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import path from 'path';
const path = require('path');

// import .env variables
require('dotenv-safe').load({
Expand All @@ -8,7 +8,7 @@ require('dotenv-safe').load({

});

export default {
module.exports = {
env: process.env.NODE_ENV,
port: process.env.PORT,
jwtSecret: process.env.JWT_SECRET,
Expand Down
18 changes: 9 additions & 9 deletions src/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import httpStatus from 'http-status';
import moment from 'moment-timezone';
const httpStatus = require('http-status');
const moment = require('moment-timezone');

import User from '../models/user.model';
import RefreshToken from '../models/refreshToken.model';
import { jwtExpirationInterval } from '../config/vars';
const User = require('../models/user.model');
const RefreshToken = require('../models/refreshToken.model');
const { jwtExpirationInterval } = require('../config/vars');

/**
* Returns a formated object with tokens
Expand All @@ -22,7 +22,7 @@ function generateTokenResponse(user, accessToken) {
* Returns jwt token if registration was successful
* @public
*/
export const register = async (req, res, next) => {
exports.register = async (req, res, next) => {
try {
const user = await (new User(req.body)).save();
const userTransformed = user.transform();
Expand All @@ -38,7 +38,7 @@ export const register = async (req, res, next) => {
* Returns jwt token if valid username and password is provided
* @public
*/
export const login = async (req, res, next) => {
exports.login = async (req, res, next) => {
try {
const { user, accessToken } = await User.findAndGenerateToken(req.body);
const token = generateTokenResponse(user, accessToken);
Expand All @@ -54,7 +54,7 @@ export const login = async (req, res, next) => {
* Returns jwt token
* @public
*/
export const oAuth = async (req, res, next) => {
exports.oAuth = async (req, res, next) => {
try {
const { user } = req;
const accessToken = user.token();
Expand All @@ -70,7 +70,7 @@ export const oAuth = async (req, res, next) => {
* Returns a new jwt when given a valid refresh token
* @public
*/
export const refresh = async (req, res, next) => {
exports.refresh = async (req, res, next) => {
try {
const { email, refreshToken } = req.body;
const refreshObject = await RefreshToken.findOneAndRemove({
Expand Down
24 changes: 12 additions & 12 deletions src/controllers/user.controller.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import httpStatus from 'http-status';
import { omit } from 'lodash';
const httpStatus = require('http-status');
const { omit } = require('lodash');

import User from '../models/user.model';
import { handler as errorHandler } from '../middlewares/error';
const User = require('../models/user.model');
const { handler: errorHandler } = require('../middlewares/error');

/**
* Load user and append to req.
* @public
*/
export const load = async (req, res, next, id) => {
exports.load = async (req, res, next, id) => {
try {
const user = await User.get(id);
req.locals = { user };
Expand All @@ -22,19 +22,19 @@ export const load = async (req, res, next, id) => {
* Get user
* @public
*/
export const get = (req, res) => res.json(req.locals.user.transform());
exports.get = (req, res) => res.json(req.locals.user.transform());

/**
* Get logged in user info
* @public
*/
export const loggedIn = (req, res) => res.json(req.user.transform());
exports.loggedIn = (req, res) => res.json(req.user.transform());

/**
* Create new user
* @public
*/
export const create = async (req, res, next) => {
exports.create = async (req, res, next) => {
try {
const user = new User(req.body);
const savedUser = await user.save();
Expand All @@ -49,7 +49,7 @@ export const create = async (req, res, next) => {
* Replace existing user
* @public
*/
export const replace = async (req, res, next) => {
exports.replace = async (req, res, next) => {
try {
const { user } = req.locals;
const newUser = new User(req.body);
Expand All @@ -69,7 +69,7 @@ export const replace = async (req, res, next) => {
* Update existing user
* @public
*/
export const update = (req, res, next) => {
exports.update = (req, res, next) => {
const ommitRole = req.locals.user.role !== 'admin' ? 'role' : '';
const updatedUser = omit(req.body, ommitRole);
const user = Object.assign(req.locals.user, updatedUser);
Expand All @@ -83,7 +83,7 @@ export const update = (req, res, next) => {
* Get user list
* @public
*/
export const list = async (req, res, next) => {
exports.list = async (req, res, next) => {
try {
const users = await User.list(req.query);
const transformedUsers = users.map(user => user.transform());
Expand All @@ -97,7 +97,7 @@ export const list = async (req, res, next) => {
* Delete user
* @public
*/
export const remove = (req, res, next) => {
exports.remove = (req, res, next) => {
const { user } = req.locals;

user.remove()
Expand Down
15 changes: 9 additions & 6 deletions src/middlewares/auth.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import httpStatus from 'http-status';
import passport from 'passport';
const httpStatus = require('http-status');
const passport = require('passport');

const User = require('../models/user.model');
const APIError = require('../utils/APIError');

export const ADMIN = 'admin';
export const LOGGED_USER = '_loggedUser';
const ADMIN = 'admin';
const LOGGED_USER = '_loggedUser';

const handleJWT = (req, res, next, roles) => async (err, user, info) => {
const error = err || info;
Expand Down Expand Up @@ -42,11 +42,14 @@ const handleJWT = (req, res, next, roles) => async (err, user, info) => {
return next();
};

export const authorize = (roles = User.roles) => (req, res, next) =>
exports.ADMIN = ADMIN;
exports.LOGGED_USER = LOGGED_USER;

exports.authorize = (roles = User.roles) => (req, res, next) =>
passport.authenticate(
'jwt', { session: false },
handleJWT(req, res, next, roles),
)(req, res, next);

export const oAuth = service =>
exports.oAuth = service =>
passport.authenticate(service, { session: false });
17 changes: 9 additions & 8 deletions src/middlewares/error.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import httpStatus from 'http-status';
import expressValidation from 'express-validation';
const httpStatus = require('http-status');
const expressValidation = require('express-validation');

import APIError from '../utils/APIError';
import { env } from '../config/vars';
const APIError = require('../utils/APIError');
const { env } = require('../config/vars');

/**
* Error handler. Send stacktrace only during development
* @public
*/
export const handler = (err, req, res, next) => {
const handler = (err, req, res, next) => {
const response = {
code: err.status,
message: err.message || httpStatus[err.status],
Expand All @@ -24,17 +24,18 @@ export const handler = (err, req, res, next) => {
res.json(response);
res.end();
};
exports.handler = handler;

/**
* If error is not an instanceOf APIError, convert it.
* @public
*/
export const converter = (err, req, res, next) => {
exports.converter = (err, req, res, next) => {
let convertedError = err;

if (err instanceof expressValidation.ValidationError) {
convertedError = new APIError({
message: 'Error in validation',
message: 'Erro de Validação',
errors: err.errors,
status: err.status,
stack: err.stack,
Expand All @@ -54,7 +55,7 @@ export const converter = (err, req, res, next) => {
* Catch 404 and forward to error handler
* @public
*/
export const notFound = (req, res, next) => {
exports.notFound = (req, res, next) => {
const err = new APIError({
message: 'Not found',
status: httpStatus.NOT_FOUND,
Expand Down
9 changes: 4 additions & 5 deletions src/models/refreshToken.model.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import mongoose from 'mongoose';
import crypto from 'crypto';
import moment from 'moment-timezone';
const mongoose = require('mongoose');
const crypto = require('crypto');
const moment = require('moment-timezone');

/**
* Refresh Token Schema
Expand Down Expand Up @@ -51,5 +51,4 @@ refreshTokenSchema.statics = {
* @typedef RefreshToken
*/
const RefreshToken = mongoose.model('RefreshToken', refreshTokenSchema);

export default RefreshToken;
module.exports = RefreshToken;
Loading