This repository has been archived by the owner on Oct 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.js
106 lines (99 loc) · 2.81 KB
/
auth.js
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
var _req = require('request-promise'),
Promise = require('bluebird');
module.exports = function(){
var buildUrl = () => {
var scopes;
if (typeof this.scopes === 'object'){
scopes = '' + this.scopes.join(' ');
} else {
scopes = this.scopes;
}
return `${this.api}oauth/authorize?scope=${scopes}&client_id=${this.client_id}`
+ `&redirect_uri=${this.redirect_url}&response_type=code`;
};
var authorize = (req, res, next) => {
console.log('auth.authorize');
console.log(this);
this.test_thing = 123456;
if (req.query.code){
// action the response from Tanda.
token(req, next, req.query.code)
.then(() => {
// save the refresh_token into the database for that user.
next();
})
.catch((err) => {
next(err);
})
} else {
// send the client to Tanda to authorize
res.redirect(buildUrl());
}
};
/**
* refresh the user's token if it expires
* @param {string} refresh_token - The user's refresh token
*/
var refresh = (refresh_token) => {
return new Promise((resolve, reject) => {
// build the request object
var options = {
method: 'POST',
uri: this.api + 'oauth/token',
form: {
client_id : this.client_id,
client_secret : this.client_secret,
refresh_token,
redirect_uri : buildUrl(),
grant_type : 'refresh_token'
},
json: true
};
_req(options)
.then((body) => {
// update the token into the DB/whatever user is doing with it
this.refreshToken(body.refresh_token);
// TODO: figure out neatest way of attaching access_token + expires to req.tanda
// Maybe just attach it to the session, and pull it out + attach it in the express function
})
.catch((err) => {
reject(err);
})
});
};
var token = (req, next, code) => {
return new Promise((resolve, reject) => {
// build the object to send
var options = {
method: 'POST',
uri: this.api + 'oauth/token',
form: {
client_id : this.client_id,
client_secret : this.client_secret,
code,
redirect_uri : this.redirect_url,
grant_type : 'authorization_code'
},
json: true
};
console.log(options);
_req(options)
.then((res) => {
req.tanda = {
access_token : res.access_token,
expires : res.created_at + res.expires_in,
refresh_token : res.refresh_token
};
this.access_token = res.access_token;
resolve();
})
.catch((err) => {
reject(err);
});
});
};
return {
authorize,
refresh
}
};