UNPKG

935 Btext/coffeescriptView Raw
1check = require("validator").check
2HAPINode = require("hapilib").HAPINode
3
4class CodeExchanger
5
6 constructor: ->
7 @client = new HAPINode
8 @routes =
9 "/exchangeCode": (req, res) => @exchangeCodeForToken(req, res)
10
11 init: (@hapiEndPoint, @clientId, @secret) ->
12 check(@hapiEndPoint).isUrl()
13 @client.setBaseUrl @hapiEndPoint
14
15 requestsHandler: ->
16 return (req, res, next) =>
17 handler = @routes[req.url]
18 return next() unless handler
19 handler(req, res)
20
21 exchangeCodeForToken: (req, res) ->
22 return res.send 400, "Bad Request" unless req.body?.code?
23 code = req.body.code
24 @client.post "/auth/code/exchange?authCode=#{code}", clientSecret: @secret, (err, tokenData) ->
25 if err?
26 return res.send err.statusCode, err.message
27 res.send 200, tokenData
28
29module?.exports = CodeExchanger