-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
64 lines (63 loc) · 2.26 KB
/
index.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
var request = require('request');
var querystring = require('querystring');
var sharepoint = require('./SharePoint');
var util=require('util');
module.exports = {
getSharePointAppOnlyAccessToken: function (siteUrl, clientId, clientSecret, callback) {
//first get the site realm
getRealm(siteUrl, function (response) {
//read realm from header
realm = extractRealmId(response.headers[sharepoint.wwwauthenticate]);
var body = {};
body.grant_type = 'client_credentials';
body.client_id = util.format('%s@%s', clientId, realm);
body.resource = util.format('%s/%s@%s', sharepoint.sharePointPrinciple, siteUrl, realm).replace('https://','');
body.client_secret = clientSecret;
var formData = querystring.stringify(body);
var contentLength = formData.length;
//get app only access token
request(
{
url: util.format(sharepoint.authenticationUrl, realm),
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': contentLength
},
body: formData,
json:true
},
function(error,response,body){
if(error || response.statusCode!=200){
throw 'can\'t get access token'
}
callback(body);
}
);
})
}
}
function getRealm(siteUrl, callback) {
request(
{
url: siteUrl + sharepoint.clientSvcUrl,
method: 'GET',
headers: {
'Authorization': 'Bearer ',
'Content-Type': 'application/json'
},
json: true
})
.on('error', function (error) {
throw 'can\t get site realm';
})
.on('response', function (response) {
callback(response);
})
}
function extractRealmId(header) {
if (header == null) {
throw 'fail to get realm from supplied site Url'
}
return header.substring(header.indexOf('realm="') + 7, header.indexOf('",'));
}