index.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. const Koa = require('koa');
  2. const app = new Koa();
  3. const views = require('koa-views');
  4. const json = require('koa-json');
  5. const onerror = require('koa-onerror');
  6. const bodyparser = require('koa-bodyparser');
  7. const logger = require('koa-logger');
  8. const cors = require('koa2-cors');
  9. const jwt = require('koa-jwt');
  10. const jsonwebtoken = require('jsonwebtoken')
  11. const helmet = require('koa-helmet');
  12. const mount = require('koa-mount');
  13. const set = require('lodash/set');
  14. const session = require('koa-session');
  15. const { Provider } = require('oidc-provider');
  16. const consola = require('consola')
  17. const { Nuxt, Builder } = require('nuxt')
  18. const secret = require('./config/secret.json');
  19. const Account = require('./support/account');
  20. const configuration = require('./support/configuration');
  21. const router = require('./routes/index');
  22. const { PORT = 3000, ISSUER = `http://localhost:${PORT}` } = process.env;
  23. // error handler
  24. onerror(app);
  25. // middlewares
  26. app.use(bodyparser({
  27. enableTypes:['json', 'form', 'text']
  28. }));
  29. app.keys = ['seec'];
  30. const CONFIG = {
  31. key: 'SEEC', /** (string) cookie key (default is koa:sess) */
  32. /** (number || 'session') maxAge in ms (default is 1 days) */
  33. /** 'session' will result in a cookie that expires when session/browser is closed */
  34. /** Warning: If a session cookie is stolen, this cookie will never expire */
  35. maxAge: 5 * 60 * 1000,
  36. overwrite: true, /** (boolean) can overwrite or not (default true) */
  37. httpOnly: true, /** (boolean) httpOnly or not (default true) */
  38. signed: true, /** (boolean) signed or not (default true) */
  39. 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 **/
  40. }
  41. app.use(session(CONFIG, app));
  42. app.use(cors({
  43. origin: (ctx)=>{
  44. return "*";
  45. },
  46. // exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  47. maxAge: 3600,
  48. credentials: true,
  49. allowMethods: ['GET', 'POST', 'OPTIONS'],
  50. allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
  51. }));
  52. app.use(json());
  53. app.use(logger());
  54. app.use(require('koa-static')(__dirname + '/public'));
  55. app.use(views(__dirname + '/views', {
  56. extension: 'ejs'
  57. }));
  58. // logger
  59. app.use(async (ctx, next) => {
  60. const start = new Date();
  61. await next();
  62. const ms = new Date() - start;
  63. console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
  64. });
  65. // Custom 401 handling if you don't want to expose koa-jwt errors to users
  66. app.use(function(ctx, next){
  67. return next().catch((err) => {
  68. if (401 === err.status) {
  69. ctx.status = 401;
  70. ctx.body = 'Protected resource, use Authorization header to get access\n';
  71. } else {
  72. throw err;
  73. }
  74. });
  75. });
  76. //
  77. // error-handling
  78. app.on('error', (err, ctx) => {
  79. console.error('server error', err, ctx)
  80. });
  81. // SSO
  82. // app.use(helmet());
  83. //
  84. // if (process.env.NODE_ENV === 'production') {
  85. // app.proxy = true;
  86. // set(configuration, 'cookies.short.secure', true);
  87. // set(configuration, 'cookies.long.secure', true);
  88. //
  89. // app.use(async (ctx, next) => {
  90. // if (ctx.secure) {
  91. // await next();
  92. // } else if (ctx.method === 'GET' || ctx.method === 'HEAD') {
  93. // ctx.redirect(ctx.href.replace(/^http:\/\//i, 'https://'));
  94. // } else {
  95. // ctx.body = {
  96. // error: 'invalid_request',
  97. // error_description: 'do yourself a favor and only use https',
  98. // };
  99. // ctx.status = 400;
  100. // }
  101. // });
  102. // }
  103. //
  104. // (async () => {
  105. // let adapter;
  106. // if (process.env.MONGODB_URI) {
  107. // adapter = require('./adapters/memory_adapter'); // eslint-disable-line global-require
  108. // // await adapter.connect();
  109. // }
  110. //
  111. // const provider = new Provider(ISSUER, { adapter, ...configuration });
  112. //
  113. // provider.use(helmet());
  114. //
  115. // app.use(router(provider).routes(), router(provider).allowedMethods());
  116. // app.use(mount(provider.app));
  117. // })().catch((err) => {
  118. // console.error(err);
  119. // process.exitCode = 1;
  120. // });
  121. // Import and Set Nuxt.js options
  122. const config = require('../nuxt.config.js')
  123. config.dev = app.env !== 'production'
  124. async function start () {
  125. // Instantiate nuxt.js
  126. const nuxt = new Nuxt(config)
  127. const {
  128. host = process.env.HOST || '127.0.0.1',
  129. port = process.env.PORT || 3000
  130. } = nuxt.options.server
  131. await nuxt.ready()
  132. // Build in development
  133. if (config.dev) {
  134. const builder = new Builder(nuxt)
  135. await builder.build()
  136. }
  137. app.use(jwt({ secret: 'SEEC-1919810-OIDC-114514' }).unless({
  138. // 设置login、register接口,可以不需要认证访问
  139. path: [
  140. /\/api\/user\/login/, /\/api\/user\/register/,/\/api\/user\/sendMessage/,,/\/api\/user\/resetPassword/, /\/api\/interaction/, /\/api\/receiveIDToken/, /\/api\/authenticate/,
  141. /^((?!\/api).)*$/ // 设置除了私有接口外的其它资源,可以不需要认证访问
  142. ]
  143. }));
  144. // routes
  145. app.use(router().routes(), router().allowedMethods());
  146. app.use((ctx) => {
  147. ctx.req.session = ctx.session;
  148. ctx.status = 200
  149. ctx.respond = false // Bypass Koa's built-in response handling
  150. ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
  151. nuxt.render(ctx.req, ctx.res)
  152. })
  153. // app.use((ctx, next) => {
  154. // console.log("ctx.url", ctx.url);
  155. // console.log("ctx.url.match(/^\\/api/)", ctx.url.match(/\/api/));
  156. // if (
  157. // ctx.url.match(/\/api\/user\/login/) ||
  158. // ctx.url.match(/\/api\/user\/register/)||
  159. // ctx.url.match(/\/api\/receiveIDToken/)||
  160. // ctx.url.match(/\/api\/interaction/)||
  161. // ctx.url.match(/\/api\/authenticate/)
  162. // ) {
  163. // return next();
  164. // }
  165. // if (ctx.url.substr(0, 4) === '/api') {
  166. // //路由判断是否以/api开头的url,是则进行鉴权,否则直接输入内容
  167. // let authorization = ctx.headers.authorization,
  168. // token;
  169. // console.log('authorization', authorization);
  170. // if (ctx.headers) {
  171. // if (!authorization) {
  172. // ctx.status = 401;
  173. // return (ctx.body = "Bad permissions");
  174. // }
  175. // token = authorization.split(" ")[1];
  176. // try {
  177. // jwt.verify(token, 'seec-portal', (err, authData) => {
  178. // if(err) {
  179. // console.log("err:", err);
  180. // ctx.status = 401;
  181. // return (ctx.body = "Bad permissions");
  182. // }
  183. // });
  184. // // ,refresh;
  185. // // //这里写刷新令牌逻辑,refresh是判断是否到达刷新令牌时间结果
  186. // // if (refresh) {
  187. // // //在刷新时间范围内请求则刷新令牌
  188. // // try {
  189. // // let newToken = jsonwebtoken.sign(
  190. // // user,
  191. // // SECRET,
  192. // // {
  193. // // expiresIn: "1h"
  194. // // }
  195. // // );
  196. // // ctx.cookies.set(
  197. // // "authUser",
  198. // // JSON.stringify(newToken),
  199. // // {
  200. // // maxAge: 60000 * 60,
  201. // // overwrite: true
  202. // // }
  203. // // );
  204. // // } catch (err) {
  205. // // console.log(err);
  206. // // }
  207. // // }
  208. // } catch (err) {
  209. // ctx.status = 401;
  210. // return (ctx.body = "Bad permissions");
  211. // }
  212. // }
  213. // return next();
  214. // } else {
  215. // ctx.req.session = ctx.session;
  216. // ctx.status = 200
  217. // ctx.respond = false // Bypass Koa's built-in response handling
  218. // ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
  219. // nuxt.render(ctx.req, ctx.res);
  220. // }
  221. // });
  222. app.listen(port, host)
  223. consola.ready({
  224. message: `Server listening on http://${host}:${port}`,
  225. badge: true
  226. })
  227. }
  228. start();
  229. // module.exports = app;