const Koa = require('koa'); const app = new Koa(); const views = require('koa-views'); const json = require('koa-json'); const onerror = require('koa-onerror'); const bodyparser = require('koa-bodyparser'); const logger = require('koa-logger'); const cors = require('koa2-cors'); const jwt = require('koa-jwt'); const jsonwebtoken = require('jsonwebtoken') const helmet = require('koa-helmet'); const mount = require('koa-mount'); const set = require('lodash/set'); const session = require('koa-session'); const { Provider } = require('oidc-provider'); const consola = require('consola') const { Nuxt, Builder } = require('nuxt') const secret = require('./config/secret.json'); const Account = require('./support/account'); const configuration = require('./support/configuration'); const router = require('./routes/index'); const { PORT = 3000, ISSUER = `http://localhost:${PORT}` } = process.env; // error handler onerror(app); // middlewares app.use(bodyparser({ enableTypes:['json', 'form', 'text'] })); app.keys = ['seec']; const CONFIG = { key: 'SEEC', /** (string) cookie key (default is koa:sess) */ /** (number || 'session') maxAge in ms (default is 1 days) */ /** 'session' will result in a cookie that expires when session/browser is closed */ /** Warning: If a session cookie is stolen, this cookie will never expire */ maxAge: 5 * 60 * 1000, overwrite: true, /** (boolean) can overwrite or not (default true) */ httpOnly: true, /** (boolean) httpOnly or not (default true) */ signed: true, /** (boolean) signed or not (default true) */ rolling: false /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. default is false **/ } app.use(session(CONFIG, app)); app.use(cors({ origin: (ctx)=>{ return "*"; }, // exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'], maxAge: 3600, credentials: true, allowMethods: ['GET', 'POST', 'OPTIONS'], allowHeaders: ['Content-Type', 'Authorization', 'Accept'], })); app.use(json()); app.use(logger()); app.use(require('koa-static')(__dirname + '/public')); app.use(views(__dirname + '/views', { extension: 'ejs' })); // logger app.use(async (ctx, next) => { const start = new Date(); await next(); const ms = new Date() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); }); // Custom 401 handling if you don't want to expose koa-jwt errors to users app.use(function(ctx, next){ return next().catch((err) => { if (401 === err.status) { ctx.status = 401; ctx.body = 'Protected resource, use Authorization header to get access\n'; } else { throw err; } }); }); // // error-handling app.on('error', (err, ctx) => { console.error('server error', err, ctx) }); // SSO // app.use(helmet()); // // if (process.env.NODE_ENV === 'production') { // app.proxy = true; // set(configuration, 'cookies.short.secure', true); // set(configuration, 'cookies.long.secure', true); // // app.use(async (ctx, next) => { // if (ctx.secure) { // await next(); // } else if (ctx.method === 'GET' || ctx.method === 'HEAD') { // ctx.redirect(ctx.href.replace(/^http:\/\//i, 'https://')); // } else { // ctx.body = { // error: 'invalid_request', // error_description: 'do yourself a favor and only use https', // }; // ctx.status = 400; // } // }); // } // // (async () => { // let adapter; // if (process.env.MONGODB_URI) { // adapter = require('./adapters/memory_adapter'); // eslint-disable-line global-require // // await adapter.connect(); // } // // const provider = new Provider(ISSUER, { adapter, ...configuration }); // // provider.use(helmet()); // // app.use(router(provider).routes(), router(provider).allowedMethods()); // app.use(mount(provider.app)); // })().catch((err) => { // console.error(err); // process.exitCode = 1; // }); // Import and Set Nuxt.js options const config = require('../nuxt.config.js') config.dev = app.env !== 'production' async function start () { // Instantiate nuxt.js const nuxt = new Nuxt(config) const { host = process.env.HOST || '127.0.0.1', port = process.env.PORT || 3000 } = nuxt.options.server await nuxt.ready() // Build in development if (config.dev) { const builder = new Builder(nuxt) await builder.build() } app.use(jwt({ secret: 'SEEC-1919810-OIDC-114514' }).unless({ // 设置login、register接口,可以不需要认证访问 path: [ /\/api\/user\/login/, /\/api\/user\/register/,/\/api\/user\/sendMessage/,,/\/api\/user\/resetPassword/, /\/api\/interaction/, /\/api\/receiveIDToken/, /\/api\/authenticate/, /^((?!\/api).)*$/ // 设置除了私有接口外的其它资源,可以不需要认证访问 ] })); // routes app.use(router().routes(), router().allowedMethods()); app.use((ctx) => { ctx.req.session = ctx.session; ctx.status = 200 ctx.respond = false // Bypass Koa's built-in response handling ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash nuxt.render(ctx.req, ctx.res) }) // app.use((ctx, next) => { // console.log("ctx.url", ctx.url); // console.log("ctx.url.match(/^\\/api/)", ctx.url.match(/\/api/)); // if ( // ctx.url.match(/\/api\/user\/login/) || // ctx.url.match(/\/api\/user\/register/)|| // ctx.url.match(/\/api\/receiveIDToken/)|| // ctx.url.match(/\/api\/interaction/)|| // ctx.url.match(/\/api\/authenticate/) // ) { // return next(); // } // if (ctx.url.substr(0, 4) === '/api') { // //路由判断是否以/api开头的url,是则进行鉴权,否则直接输入内容 // let authorization = ctx.headers.authorization, // token; // console.log('authorization', authorization); // if (ctx.headers) { // if (!authorization) { // ctx.status = 401; // return (ctx.body = "Bad permissions"); // } // token = authorization.split(" ")[1]; // try { // jwt.verify(token, 'seec-portal', (err, authData) => { // if(err) { // console.log("err:", err); // ctx.status = 401; // return (ctx.body = "Bad permissions"); // } // }); // // ,refresh; // // //这里写刷新令牌逻辑,refresh是判断是否到达刷新令牌时间结果 // // if (refresh) { // // //在刷新时间范围内请求则刷新令牌 // // try { // // let newToken = jsonwebtoken.sign( // // user, // // SECRET, // // { // // expiresIn: "1h" // // } // // ); // // ctx.cookies.set( // // "authUser", // // JSON.stringify(newToken), // // { // // maxAge: 60000 * 60, // // overwrite: true // // } // // ); // // } catch (err) { // // console.log(err); // // } // // } // } catch (err) { // ctx.status = 401; // return (ctx.body = "Bad permissions"); // } // } // return next(); // } else { // ctx.req.session = ctx.session; // ctx.status = 200 // ctx.respond = false // Bypass Koa's built-in response handling // ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash // nuxt.render(ctx.req, ctx.res); // } // }); app.listen(port, host) consola.ready({ message: `Server listening on http://${host}:${port}`, badge: true }) } start(); // module.exports = app;