{"size": 1829, "ext": "js", "max_stars_repo_path": "index.js", "max_stars_repo_name": "mn-tech/wechat-oauth2-proxy", "max_stars_repo_stars_event_min_datetime": "2017-03-27T05:27:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-27T05:27:17.000Z", "max_issues_repo_path": "index.js", "max_issues_repo_name": "mn-tech/wechat-oauth2-proxy", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "index.js", "max_forks_repo_name": "mn-tech/wechat-oauth2-proxy", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 17.931372549, "max_line_length": 68, "alphanum_fraction": 0.6610169492}
/**
 * module dependencies
 */

const url = require('url')
const path = require('path')
const throng = require('throng')
const Koa = require('koa')
const koaBunyanLogger = require('koa-bunyan-logger')
const koaStatic = require('koa-static')
const config = require('./config')

const meta = require('./package.json')

const app = new Koa()

/**
 * trust proxy related header or not
 */

app.proxy = config.proxy

/**
 * normal logger
 */

const bunyan = koaBunyanLogger.bunyan
const logger = bunyan.createLogger({
  name: meta.name
})

/**
 * request logger
 */

app.use(koaBunyanLogger({
  name: meta.name
}))
app.use(koaBunyanLogger.requestIdContext())
app.use(koaBunyanLogger.requestLogger())

/**
 * static file serving
 */

const staticRoot = path.join(__dirname, 'public')
app.use(koaStatic(staticRoot))

/**
 * oauth2 proxy
 */

app.use((ctx, next) => {
  const { redirect } = ctx.query

  if (!redirect) {
    ctx.body = {
      message: `Hello from ${meta.name}.`
    }

    return
  }

  delete ctx.query.redirect
  const query = ctx.query

  const redirectURI = composeRedirectURI(redirect, query)
  ctx.redirect(redirectURI)
})

throng(listen)

function listen () {
  const { host, port } = config.listen
  app.listen(port, () => {
    const baseMsg = `listening on ${host}:${port}`
    let msg
    if (app.proxy) {
      msg = `${baseMsg} in proxy mode`
    } else {
      msg = `${baseMsg}`
    }

    logger.info(msg)
  })
}

function composeRedirectURI (redirect, query) {
  const redirectURI = decodeURIComponent(redirect)

  /**
   * when urObject.search is undefined, `url.format()` will generate
   * search string from urlObject.query.
   */
  const urlObject = url.parse(redirectURI, true)
  delete urlObject.search
  Object.assign(urlObject.query, query)

  const uri = url.format(urlObject)
  return uri
}
