forked from nylas/nylas-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnylas.coffee
72 lines (59 loc) · 2.59 KB
/
nylas.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
_ = require 'underscore'
request = require 'request'
Promise = require 'bluebird'
NylasConnection = require './nylas-connection'
ManagementAccount = require './models/management-account'
Account = require './models/account'
RestfulModelCollection = require './models/restful-model-collection'
ManagementModelCollection = require './models/management-model-collection'
class Nylas
@appId: null
@appSecret: null
@apiServer: 'https://api.nylas.com'
@config: ({appId, appSecret, apiServer} = {}) ->
throw new Error("Please specify a fully qualified URL for the API Server.") if apiServer?.indexOf('://') == -1
@appId = appId if appId
@appSecret = appSecret if appSecret
@apiServer = apiServer if apiServer
if @hostedAPI()
conn = new NylasConnection @appSecret
@accounts = new ManagementModelCollection ManagementAccount, conn, @appId
else
conn = new NylasConnection @appSecret
@accounts = new RestfulModelCollection Account, conn, @appId
@
@hostedAPI: ->
@appId? and @appSecret?
@with: (accessToken) ->
throw new Error("This function requires an access token") unless accessToken?
new NylasConnection(accessToken, hosted = @hostedAPI)
@exchangeCodeForToken: (code, callback) ->
throw new Error("exchangeCodeForToken() cannot be called until you provide an appId and secret via config()") unless @appId and @appSecret
throw new Error("exchangeCodeForToken() must be called with a code") unless code?
new Promise (resolve, reject) =>
options =
method: 'GET'
json: true
url: "#{@apiServer}/oauth/token"
qs:
'client_id': @appId
'client_secret': @appSecret
'grant_type': 'authorization_code'
'code': code
request options, (error, response, body) ->
if error
reject(error)
callback(error) if callback
else
resolve(body['access_token'])
callback(null, body['access_token']) if callback
@urlForAuthentication: (options = {}) ->
throw new Error("urlForAuthentication() cannot be called until you provide an appId and secret via config()") unless @appId and @appSecret
throw new Error("urlForAuthentication() requires options.redirectURI") unless options.redirectURI?
options.loginHint ?= ''
options.trial ?= false
url = "#{@apiServer}/oauth/authorize?client_id=#{@appId}&trial=#{options.trial}&response_type=code&scope=email&login_hint=#{options.loginHint}&redirect_uri=#{options.redirectURI}"
if options.state?
url += "&state=#{options.state}"
return url
module.exports = Nylas