simov / grant

OAuth Proxy
MIT License
4.08k stars 257 forks source link

Missing 'node' documentation and example #241

Open AaronNGray opened 3 years ago

AaronNGray commented 3 years ago

Is it possile to provide example usage and brief documentation for the 'node' https://github.com/simov/grant/blob/master/lib/handler/node.js handler please.

simov commented 3 years ago

It's very similar to some of the serverless handlers, and in fact all of them were based on it:

var http = require('http')
var grant = require('grant').node({
  config: {/*configuration - see below*/}, session: {secret: 'grant'}
})

var server = http.createServer()
server.on('request', async (req, res) => {
  var {response} = await grant(req, res)
  if (response) {
    res.setHeader('content-type', 'application/json')
    res.end(JSON.stringify(response))
  }
})
server.listen(3000)

The above example assumes that you are handling the Grant routes only, but in case you want to handle other routes you can simply check the contents of req.url.

You can see what the session expects here, and what the handler signature is here. You can also take a look at the four main examples, because that's how the node handler behaves as well.

The redirect key is being returned when Grant is about to do internal redirect. So in case Grant does not return response or redirect, and your request handler does not match any other path that you may have, then you just have to respond with something like:

res.statusCode = 404
res.end('Not Found')

I should definitely document this somewhere, but I was not sure if anyone will be interested in using that handler in case you have four other options to use HTTP framework instead.

Lets keep this issue open for now, it might be useful to someone else as well.

Let me know if you have any questions.

AaronNGray commented 3 years ago

Thanks, I will have to look at Grant properly I have came in at top level and not totally sure of what I am doing yet. I intending to use it with GraphQL DGraph, so was try to work out how to look at putting the two together.