Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
/* istanbul ignore file */
const Router = require('express').Router;
const getSwaggerSpec = require('../services/swagger');
const swaggerUi = require('swagger-ui-express');
const routes = new Router();
routes.get('/api-docs.json', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(getSwaggerSpec(req));
});
routes.use('/', swaggerUi.serve, (req, res, next) => {
const swaggerUiHandler = swaggerUi.setup(getSwaggerSpec(req));
swaggerUiHandler(req, res, next);
});
module.exports = routes;
// Enable reverse proxy support in Express. This causes the
// the "X-Forwarded-Proto" header field to be trusted so its
// value can be used to determine the protocol. See
// http://expressjs.com/api#app-settings for more details.
app.enable("trust proxy");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
bodyParser.json({
type: () => true // Treat all other content types as application/json
})
);
if (process.env.NODE_ENV === "dev") {
app.use(
"/api-docs",
swaggerUi.serve,
swaggerUi.setup(swaggerSpec, { explorer: true })
);
}
app.use("/api", createApiRouter(context, true));
app.use(handleErrors);
return app;
}
middleware.validateRequest());
// Error handler to display the validation error as HTML
app.use(function (err, req, res, next) {
res.status(err.status);
res.send(
'<h1>' + err.status + ' Error</h1>' +
'<pre>' + err.message + '</pre>'
);
});
routes(app);
});
const swaggerDocument = YAML.load('./server/common/swagger/Api.yaml');
app.use('/swagger', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
}
// log
this.app.use(log4js.connectLogger(this.log.access, { level: 'info' }));
// read pkg
const pkg = require(path.join('..', '..', '..', 'package.json'));
// read api.yml
let api = yaml.safeLoad(fs.readFileSync(path.join(__dirname, '..', '..', '..', 'api.yml'), 'utf-8'));
api.info = {
version: pkg.version,
title: pkg.name,
}
// swagger ui
const swaggerUi = require('swagger-ui-express');
this.app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(api));
this.app.get('/api/debug', (_req, res) => res.redirect('/api-docs/?url=/api/docs'));
// init express-openapi
openapi.initialize({
app: this.app,
apiDoc: api,
paths: path.join(__dirname, 'api'),
consumesMiddleware: {
'application/json': bodyParser.json(),
'text/text': bodyParser.text()
},
errorMiddleware: (err, _req, res, _next) => {
res.status(400);
res.json(err);
},
errorTransformer: (openapi, _jsonschema) => {
const jwt = require('jsonwebtoken');
const basicAuth = require('express-basic-auth');
const swaggerUi = require('swagger-ui-express');
const swaggerJSDoc = require('swagger-jsdoc');
const invalidTokenHandler = require('../middleware/invalidTokenHandler');
const { privateKey, publicKey } = require('../lib/keys');
const { jwtConfig, basicAuthConfig, swaggerConfig } = require('../config/config');
const swaggerSpec = swaggerJSDoc(swaggerConfig);
const router = express.Router();
// Ensure user gets to api docs
router.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
router.get('/', (req, res) => {
res.redirect('/api-docs');
});
router.get('/healthCheck', (req, res) => {
res.sendStatus(200);
});
/**
* @swagger
* /login:
* get:
* summary: Login to the application via basic auth(use admin:admin)
* tags: [Login (Get JWT)]
* security:
import Menu from './models/menu';
import Order from './models/orders';
import OrderItem from './models/orderItem';
import swaggerDocument from './swagger.json';
config();
const app = express();
const PORT = process.env.PORT || 4000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(fileUpload());
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.use('/api/v1', Routes);
User.hasMany(Order, { constraints: true, onDelete: 'CASCADE' });
User.hasMany(OrderItem, { constraints: true, onDelete: 'CASCADE' });
Order.belongsTo(Caterer, { constraints: true, onDelete: 'CASCADE' });
Meal.belongsTo(Caterer, { constraints: true, onDelete: 'CASCADE' });
Menu.belongsTo(Caterer, { constraints: true, onDelete: 'CASCADE' });
OrderItem.belongsTo(Meal, { constraints: true, onDelete: 'CASCADE' });
sequelize
.sync()
.then(() => {
console.log('DB Connection has been established');
app.listen(PORT, null, null, () => {
app.emit('dbConnected');
});
module.exports = ({
config,
db
}) => {
console.info('Init DOCS API module')
const app = Router()
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument))
return app
}
apis: [
'./src/server/entity/**/*.ts',
'./src/server/rest-api/controllers/**/*.ts'
]
})
app.use('/api/**', bodyParser.json())
app.use('/api/**', bodyParser.urlencoded({ extended: false }))
app.get('/api-docs.json', (req, res) => {
res.setHeader('Content-Type', 'application/json')
res.send(swaggerSpec)
})
app.use(
'/api-docs',
swaggerUi.serve,
swaggerUi.setup(swaggerSpec, undefined, {
oauth2RedirectUrl: `${
process.env.SITE_URL
}/api-docs/oauth2-redirect.html`,
oauth: {
clientId: process.env.AUTH0_CLIENT_ID
}
})
)
const getTokenFromAction = (action: Action) => {
const clientAccessToken =
action.request.headers.cookie &&
parse(action.request.headers.cookie as any)[appAuthAccessTokenKey]
const clientIdToken =
action.request.headers.cookie &&
this.app.use(bodyParser.json());
this.app.set('view engine', 'pug');
this.app.set('views', path.join(__dirname, 'views'));
this.app.locals.formatters = {
time: (rawTime) => {
const timeInMS = new Date(rawTime * 1000);
return `${timeInMS.toLocaleString()} - ${timeago().format(timeInMS)}`;
},
hash: (hashString) => {
return hashString != '0' ? `${hashString.substr(0, 5)}...${hashString.substr(hashString.length - 5, 5)}` : '';
},
amount: (amount) => amount.toLocaleString()
};
this.app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
this.app.get('/blockchain', (req, res) => {
if (req.headers['accept'] && req.headers['accept'].includes('text/html'))
res.render('blockchain/index.pug', {
pageTitle: 'Blockchain',
blocks: blockchain.getAllBlocks()
});
else
throw new HTTPError(400, 'Accept content not supported');
});
this.app.get('/blockchain/blocks', (req, res) => {
res.status(200).send(blockchain.getAllBlocks());
});
this.app.get('/blockchain/blocks/latest', (req, res) => {
in: 'header',
name: 'x-api-key',
description:
'All requests must include the `x-api-key` header containing your account ID.',
};
if (this.config.enableApiKeyAuth) {
this.swaggerSpec.addAuthentication(this.spec, auth);
}
this.swaggerSpec.addSchemaDefitions(this.spec, swaggerSchemaDefinitions);
}
this.server.use('/api-spec', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(this.spec);
});
this.server.use('/', swaggerUi.serve, swaggerUi.setup(this.spec));
};
}