Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
render(app, {
root: path.join(__dirname, './static'),
layout: 'template',
viewExt: 'html',
cache: false,
debug: true,
})
// 跨域
app.use(cors())
// 请求解析
app.use(koaBody())
// jwt
app.use(koaJwt({
secret: JWT.secret,
passthrough: true
}).unless({
path: [/^\/apidocs/]
}))
app.use(valid()) // 参数验证
app.use(pipe()) // 通讯
// 路由
app
.use(router.base)
// .use(router.v1)
.use(router.admin)
// 404
const engine = new Engine({
engineConfig: { apiKey: 'service:tychota-Bam-Api:1Z3thyxiVF84L4nF97NUmw' },
graphqlPort: 3000, // GraphQL port
endpoint: '/graphql', // GraphQL endpoint suffix - '/graphql' by default
dumpTraffic: true,
});
engine.start();
// configure jwt middleware to connect to auth0, check the token and
const jwtConfig = {
secret: jwksRsa.koaJwtSecret(config.get('Security.jwks')),
...config.get('Security.jwt'),
passthrough: true,
};
app.use(koaJwt(jwtConfig));
app.use(engine.koaMiddleware());
// import the schema and mount it under /graphql
import schema from '../presentation/schema';
import getViewerAndRoles from '../business/utils/auth';
import { formatErrorGenerator } from 'graphql-apollo-errors';
// get the dataloader for each request
import * as business from '../business';
router.post(
'/graphql',
graphqlKoa(async ctx => {
// create error formatter
const formatErrorConfig = {
if (config.ENV === 'production') {
mongoose.connect(`mongodb://${config.MONGODB.USER}:${config.MONGODB.PASSWORD}@${config.MONGODB.HOST}:${config.MONGODB.PORT}/${config.MONGODB.NAME}`)
} else {
mongoose.connect(`mongodb://${config.MONGODB.HOST}:${config.MONGODB.PORT}/${config.MONGODB.NAME}`)
}
app.use(ua())
app.use(cookies())
app.use(normal())
app.use(xsrf())
app.use(handel.routes())
.use(handel.allowedMethods())
// Below needs JWT verfiy
app.use(jwt({
secret: config.APP.JWT_KEY,
algorithm: 'RS256'
}).unless({
path: [/^\/static|css|js|img|fonts|favicon|manifest/]
}))
// API (Protected)
app.use(api.routes())
.use(api.allowedMethods())
app.use(nghtml5())
app.listen(config.PORT)
module.exports = function () {
const routesDir = __dirname // 如果不传参数,扫描目录默认为'routes'
const router = require('koa-router')({prefix: `/api/${System.API_version}`})
router.use(koaJWT({
secret: System.JWT_secret
}).unless({
path: [/^\/api\/v1\/(user|admin|wx|upload|protocol|excel|everyday)\/(signin|auth|signature|image|new|base64|wx|order|type)/,
'/api/v1/area',
'/api/v1/banner',
'/api/v1/district',
// '/api/v1/specialty',
// /^\/api\/v1\/specialty\/\d+/,
'/api/v1/cuisine',
'/api/v1/scene',
'/api/v1/other'
// '/api/v1/user',
]}))
addRoutes(router, routesDir)
return router.routes()
}
// routes
const router = new koaRouter();
loadRoutes(router);
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'development_docker') {
const corsOptions = {
credentials: true,
origin: '*',
};
app.use(cors(corsOptions));
}
app
.use(bodyParser())
.use(
jwt({
secret: process.env.JWT_KEY,
}).unless({
path: ['/', '/login'],
}),
)
.use(logger())
.use(router.routes())
.use(
router.allowedMethods({
throw: true,
notImplemented: () => new Boom.notImplemented(),
methodNotAllowed: () => new Boom.methodNotAllowed(),
}),
)
.use(async context => {
context.body = 'INSIDE API';
import bodyParser from 'koa-bodyparser';
import passport from './passport';
const app = new Koa();
if (process.env.NODE_ENV === 'development') {
app.use(logger());
}
app.use(convert(cors({ credentials: true })));
app.use(bodyParser());
app.use(passport.initialize());
// Parse Authorization Header for JWT tokens, and set ctx.state.user if token is
// valid. Passthrough to middleware to make decisions on whether or not their
// routes require users. See src/middleware/validate-user.js
app.use(jwt({ secret: process.env.APP_SECRET, passthrough: true }));
// Custom API modules that define their own routes.
const modules = require('./modules');
modules(app);
export default app;
setup(app: Readonly) {
Object.assign(app.config, {
enableAuthorization: true,
roleField: this.option.roleField || "role",
globalAuthorizationDecorators: this.option.global
})
app.koa.use(KoaJwt({ cookie: "Authorization", ...this.option, secret: this.option.secret, passthrough: true }))
}
}
this.appLogger = logger.child({ module: 'app' });
this.koa.use(loggerMiddleware(this.appLogger));
this.koa.use(bodyParser({ jsonLimit: '20mb', enableTypes: ['json', 'form', 'text'] }));
this.koa.use(cors());
this.koa.keys = [config.sessionKey];
this.koa.use(session({ maxAge: config.sessionAge, renew: true }, this.koa));
const passport = setupPassport(this.appLogger.child({ module: 'passport' }));
this.koa.use(passport.initialize());
this.koa.use(passport.session());
this.koa.use(koaJwt({ key: 'user', secret: config.sessionKey, passthrough: true }));
const routes = routesMiddleware(this.appLogger);
this.koa.use(routes.publicRouter.routes());
this.koa.use(routes.publicRouter.allowedMethods());
this.koa.use(routeLoggerMiddleware);
this.koa.use(serve('public'));
this.koa.use(
koaSwagger({
routePrefix: '/swagger',
swaggerOptions: {
url: './swagger.yml',
},
}),
);