Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
}
} else {
require('dotenv').load();
app.use(cors()); // use CORS
app.use(helmet()); // Secure the API with helmet. Readmore: https://expressjs.com/en/advanced/best-practice-security.html
app.enable('trust proxy'); // only if you're behind a reverse proxy (Heroku, Bluemix, AWS if you use an ELB, custom Nginx setup, etc)
// Ratelimiter
var limiter = new RateLimit({
windowMs: 10 * 60 * 1000, // 10 minutes
max: 1000, // limit each IP to 100 requests per windowMs
delayMs: 0 // disable delaying - full speed until the max limit is reached
});
app.use(limiter);
// Set Cache Options
apicache.options({
redisClient: redis.createClient()
}, {
statusCodes: {
exclude: [404, 429, 500],
include: [200, 304]
}
}).middleware;
api = new API({
key: process.env.KEY || null,
region: process.env.REGION || null
});
app.port = process.env.PORT || 3001;
// Default route
ravenClient = new raven.Client(config.sentry.dsn, {
release: manifest.version
});
global.ravenClient = ravenClient;
}
app.use(morgan('common'));
if (ravenClient) {
app.use(raven.middleware.express.requestHandler(ravenClient));
}
// apicache does not cache headers on redirects, so do not cache if configured appropriately
if (config.cacheIgnoreRedirects) {
let cacheOptions = apicache.options();
cacheOptions.statusCodes.exclude = [301, 302];
apicache.options(cacheOptions);
}
const cache = () => {
return apicache.middleware(config.cacheTTL);
};
app.get('/', cache(), asyncHandler(homeCtrl.main));
app.get('/update/darwin', cache(), asyncHandler(updateCtrl.darwin));
app.get('/update/win32/portable', cache(), asyncHandler(updateCtrl.win32_portable));
app.get('/update/win32/:file', cache(), asyncHandler(updateCtrl.win32_file));
app.get('/update/linux', cache(), asyncHandler(updateCtrl.linux));
app.get('/update/:channel/darwin', cache(), asyncHandler(updateCtrl.darwin));
app.get('/update/:channel/win32/portable', cache(), asyncHandler(updateCtrl.win32_portable));
app.get('/update/:channel/win32/:file', cache(), asyncHandler(updateCtrl.win32_file));
app.get('/update/:channel/linux', cache(), asyncHandler(updateCtrl.linux));
app.get('/download/mirror/:mirror/latest', asyncHandler(downloadCtrl.latestMirror));
app.get('/download/:platform/latest', cache(), asyncHandler(downloadCtrl.latest));
if (config.sentry && config.sentry.dsn) {
ravenClient = new raven.Client(config.sentry.dsn, {
release: manifest.version
});
global.ravenClient = ravenClient;
}
app.use(morgan('common'));
if (ravenClient) {
app.use(raven.middleware.express.requestHandler(ravenClient));
}
// apicache does not cache headers on redirects, so do not cache if configured appropriately
if (config.cacheIgnoreRedirects) {
let cacheOptions = apicache.options();
cacheOptions.statusCodes.exclude = [301, 302];
apicache.options(cacheOptions);
}
const cache = () => {
return apicache.middleware(config.cacheTTL);
};
app.get('/', cache(), asyncHandler(homeCtrl.main));
app.get('/update/darwin', cache(), asyncHandler(updateCtrl.darwin));
app.get('/update/win32/portable', cache(), asyncHandler(updateCtrl.win32_portable));
app.get('/update/win32/:file', cache(), asyncHandler(updateCtrl.win32_file));
app.get('/update/linux', cache(), asyncHandler(updateCtrl.linux));
app.get('/update/:channel/darwin', cache(), asyncHandler(updateCtrl.darwin));
app.get('/update/:channel/win32/portable', cache(), asyncHandler(updateCtrl.win32_portable));
app.get('/update/:channel/win32/:file', cache(), asyncHandler(updateCtrl.win32_file));
app.get('/update/:channel/linux', cache(), asyncHandler(updateCtrl.linux));
import superagent from 'superagent';
import * as Settings from 'constants/Settings';
// Cache for the time being until we change this
const apicache = require('apicache')
const cache = apicache.options({ debug: true }).middleware;
import debugLib from 'debug';
const debug = debugLib('quran');
export default function(server) {
server.get('/api/cache/index', function(req, res, next) {
return res.status(200).send(apicache.getIndex());
});
server.get('/api/cache/clear', function(req, res, next) {
return res.send(200, apicache.clear());
});
server.get(/^\/(images|fonts)\/.*/, function(req, res) {
res.redirect(301, '//quran-1f14.kxcdn.com' + req.path);
});
var router = require('express').Router();
var os = require("os");
// Cache options
if (config.cache_enabled.toLowerCase() == "yes"){
if (config.cache_debug.toLowerCase() == "yes")
cache_debug = true;
else
cache_debug = false;
cache_opt = { debug: cache_debug, defaultDuration: parseInt(config.cache_time)};
}
else
cache_opt = { enabled: false };
apicache.options(cache_opt);
// Content-type
router.post("*", function(req, res, next) {
var content_type = req.get('Content-Type');
if (!content_type || !(content_type == 'application/json' || content_type == 'application/x-www-form-urlencoded'
|| content_type == 'application/xml' || content_type == 'application/octet-stream')){
logger.debug(req.connection.remoteAddress + " POST " + req.path);
res_h.bad_request(req, res, "607");
}
else
next();
});
// All requests
router.all("*", function(req, res, next) {
/*
* Data persistence service
* WSP Ltd. 2016
*/
// Libs
// ================================================================
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var http = require('http');
var assert = require('assert');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var apicache = require('apicache').options({ debug: true });
var apimiddleware = apicache.middleware;
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var PubModel = require('./models/pub');
var UserModel = require('./models/user');
require('es6-promise').polyfill();
require('isomorphic-fetch');
var SunCalc = require('../app/lib/suncalc')
var config = require('./config');
app.use('/' + fileName, express.static(staticRoot + fileName));
})
app.use(favicon(path.join(__dirname, 'public', 'favicons', 'favicon.ico')));
app.use(bodyParser.json());
app.use('/graphql', graphqlHTTP({ schema: schema, pretty: systemSetting.enableGraphiql, graphiql: systemSetting.enableGraphiql, }))
//request below will be cache
const redisClient = redis.createClient(systemSetting.redisUrlForApiCache).on("error", err => console.log("Error " + err));
const basicCacheOption = {
debug: true, enabled: systemSetting.isProduction, redisClient,
statusCodes: {
include: [200],
}
};
const basicCache = apicache.options(basicCacheOption).middleware('1 hour');
app.use(basicCache, function (req, res, next) {
global.navigator = { userAgent: req.headers['user-agent'] };
global.document = {
title: "Movie Rater",
meta: {
description: "蒐集了IMDB, YAHOO, PTT的電影評價,一目了然讓你不再踩雷",
image: "/public/favicons/android-chrome-384x384.png"
}
};
const client = new ApolloClient({
ssrMode: true,
networkInterface: createLocalInterface(graphql, schema),
});
const context = {}
const rootFiles = ["robots.txt", "sitemap.xml"];
rootFiles.forEach(fileName => {
app.use('/' + fileName, express.static(staticRoot + fileName));
});
app.use(favicon(path.join(__dirname, 'public', 'favicons', 'favicon.ico')));
app.use(bodyParser.json());
app.use('/graphql', graphqlHTTP({ schema: schema_1.default, pretty: systemSetting_1.systemSetting.enableGraphiql, graphiql: systemSetting_1.systemSetting.enableGraphiql, }));
//request below will be cache
const redisClient = redis.createClient(systemSetting_1.systemSetting.redisUrlForApiCache).on("error", err => console.log("Error " + err));
const basicCacheOption = {
debug: true, enabled: systemSetting_1.systemSetting.isProduction, redisClient,
statusCodes: {
include: [200],
}
};
const basicCache = apicache.options(basicCacheOption).middleware('1 hour');
app.use(basicCache, function (req, res, next) {
global.navigator = { userAgent: req.headers['user-agent'] };
global.document = {
title: "Movie Rater",
meta: {
description: "蒐集了IMDB, YAHOO, PTT的電影評價,一目了然讓你不再踩雷",
image: "/public/favicons/android-chrome-384x384.png"
}
};
const client = new react_apollo_1.ApolloClient({
ssrMode: true,
networkInterface: apollo_local_query_1.createLocalInterface(graphql, schema_1.default),
});
const context = {};
const app = (React.createElement(react_apollo_1.ApolloProvider, { client: client },
React.createElement(react_router_dom_1.StaticRouter, { location: req.url, context: context },
const requestProxy = require('express-http-proxy')
const url = require('url')
const apicache = require('apicache')
const cache = apicache.options({ debug: true }).middleware
const services = (process.env.SERVICES_PORT || 'http://services:8005').replace(/^tcp:\//, 'http:/')
const URI = require('urijs')
const _ = require('underscore')
module.exports = (app) => {
app.use('/search', cache('2 minutes', cacheableRequestsFilter), requestProxy(services, {
forwardPath: (req, res) => {
return '/search' + url.parse(req.url).pathname
},
decorateRequest: (proxyReq, req) => {
proxyReq.headers[ 'Content-Type' ] = 'application/json'
proxyReq.headers[ 'Accept' ] = 'application/json'
return proxyReq
}
}))
module.exports = (env) => {
if (!env.CACHE_SECONDS) {
return (req, res, next) => next();
}
return apicache.options({
debug: env.NODE_ENV === 'development',
appendKey: [ 'sessionID' ],
}).middleware(env.CACHE_SECONDS + ' seconds');
};