 else
   console.log "config file not found"
   return
+
+# read oauth configuration file
+config.oauth = null
+fs.readFile './oauth-config.json', "utf8", (err, data) ->
+  if err
+    console.log "failed to read OAuth config from file ", err
+    return
+  else
+    config.oauth = JSON.parse(data)
+    config.oauth.states = {}
 
 # nodejs' http cannot deal with a chain in one file ->
 # quickfix according to http://stackoverflow.com/a/31629223/1518225

        code = eresp.statusCode
      cb {}, {errortype: "request", error: "#{err}", code: code}

app.get '/oauthcb', (req, res) ->
  unless config.oauth
    res.send 500, "Github Login is disabled"
    return
  unless req.query.code
    res.send 500, "Github Login failed (missing code)"
    return
  clientaddr = req.headers['x-forwarded-for'] || req.connection.remoteAddress
  unless req.query.state
    res.send 500, "No state configured for #{clientaddr}"
    return
  if req.query.state != config.oauth.states[clientaddr]
    console.log "possible CSRF attempt at #{clientaddr} - #{url}"
    res.end 500, "Github Login failed (state mismatch)"
    return
  delete config.oauth.states[clientaddr]
  code = req.query.code
  # TODO: csrf handling
  #state = req.params.state
  url = 'https://github.com/login/oauth/access_token'
  data = {client_id: config.oauth.id, \

    fs.readSync fd, buf, 0, length, null
    return buf.toString 'hex'

setOAuthState = (req, res) ->
  #client = req.headers['x-forwarded-for'] || req.connection.remoteAddress
  client = newRandomState(32)
  res.cookie 'ctfpad-oauth-state-id', client
  config.oauth.states[client] = newRandomState()
  # FIXME: if this log is removed then somehow the states object becomes empty
  # sometimes o_O
  console.log "current oauth states", config.oauth.states
  return config.oauth.states[client]

app.get '/githublogin', (req, res) ->
  unless config.oauth
    res.send 500, "Github Login is disabled"
    return
  state = setOAuthState req, res
  url = "https://github.com/login/oauth/authorize?client_id="
  url += escape config.oauth.id
  url += "&redirect_uri="
