-
Notifications
You must be signed in to change notification settings - Fork 2
/
ng-ovh.js
557 lines (463 loc) · 17.2 KB
/
ng-ovh.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
/**
* ngOvh: Angular Service for OVH API
*
* @author Jean-Philippe Blary (@blary_jp)
* @url https://github.com/blaryjp/ng-ovh
* @license MIT
*/
angular.module('ngOvh', []);
angular.module('ngOvh').provider('Ovh', function () {
'use strict';
var baseUrl = 'https://api.ovh.com/1.0';
var accessRules = [
{
'method' : 'GET',
'path' : '/*'
}, {
'method' : 'POST',
'path' : '/*'
}, {
'method' : 'PUT',
'path' : '/*'
}, {
'method' : 'DELETE',
'path' : '/*'
}
];
var keys = {
ak: '', // Application Key
as: '', // Application Secret key
ck: '' // Consumer Key
};
var preventReturnData = false;
var apiDiff; // fast patch
/*========== CONF ==========*/
/**
* (Optional) Set the API base URL.
*/
this.setBaseUrl = function (url) {
baseUrl = url;
};
/**
* (Mandatory) Set the Application Key (AK).
*/
this.setAppKey = function (ak) {
keys.ak = ak;
};
/**
* (Mandatory) Set the Application Secret key (AS).
*/
this.setAppSecret = function (as) {
keys.as = as;
};
/**
* (Optional) Set the Consumer Key (CK).
* Useful when you've a token and then don't want to log the user.
*/
this.setConsumerKey = function (ck) {
keys.ck = ck;
localStorage.setItem('ovh-ck', ck);
};
/**
* (Optional) Set the access rules.
* Restrict the requests access (default to "all access").
*/
this.setAccessRules = function (rules) {
accessRules = rules;
};
this.setPreventReturnData = function (_preventReturnData) {
preventReturnData = _preventReturnData;
};
/*========== PROVIDER ==========*/
this.$get = ['$http', '$q', '$cacheFactory', '$window', function ($http, $q, $cacheFactory, $window) {
// Define default cache
var ovhCache = $cacheFactory('OvhProvider');
// At init, get CK if present
keys.ck = localStorage.getItem('ovh-ck');
/**
* Log the user (request a new credential).
* It will redirect the user to the OVH API login page.
*
* @param {string} urlToRedirect (Optional) When logged, redirect user to this URL.
* @return {promise} Success/Error.
*/
function login (urlToRedirect) {
// Delete old CK, if logged
if (isLogged()) {
localStorage.removeItem('ovh-ck');
keys.ck = null;
}
return $http({
method : 'POST',
url : baseUrl + '/auth/credential',
headers : {
'X-Ovh-Application' : keys.ak
},
data : {
accessRules : accessRules,
redirection : urlToRedirect || $window.location.href
}
}).then(function (data) {
// Consumer Key!
keys.ck = data.data.consumerKey;
// Save it to localStorage
localStorage.setItem('ovh-ck', keys.ck);
// Redirect to Auth page
$window.location = data.data.validationUrl;
// Return datas only
return data.data;
}, function (error) {
return $q.reject(error);
});
}
/**
* Log out the user (expire current credential).
*
* @return {promise} Success/Error.
*/
function logout () {
// If we're not logged: reject
if (!isLogged()) {
return $q.reject({ data : { errorCode: 'NOT_CREDENTIAL', message: 'You\'re not logged.' } });
}
return getApiTimeDiff().then(function (diff) {
return $http({
method : 'POST',
url : baseUrl + '/auth/logout',
headers : getHeaders({
method : 'POST',
url : baseUrl + '/auth/logout',
body : '',
diff : diff
})
}).then(function () {
// Delete old CK
localStorage.removeItem('ovh-ck');
keys.ck = null;
}, function (error) {
// Delete old CK
localStorage.removeItem('ovh-ck');
keys.ck = null;
return $q.reject(error);
});
}, function (error) {
return $q.reject(error);
});
}
/**
* Perform a request to the OVH API.
*
* @param {object} config $http configuration object (see Angular docs).
* @return {promise} Success/Error.
*/
function request (config) {
// Only requests with the "noAuthentication" flag can call the API without being logged
if (!isLogged() && !config.noAuthentication) {
return $q.reject({ data : { errorCode: 'NOT_CREDENTIAL', message: 'You\'re not logged.' } });
}
return getApiTimeDiff().then(function (diff) {
// Because we delete params from original object, save a local copy.
var params = config.params;
// User can use an url like "/dedicated/server/{serviceName}" with the corresponding parameters (here, "serviceName"),
// and it will be automatically replaced.
// Based on a great idea of @gierschv
if (config.params && ~config.url.indexOf('{')) {
// Because we delete params from original object, save a local copy.
params = angular.copy(config.params);
// Replace all URL params
angular.forEach(params, function (paramVal, paramKey) {
if ((new RegExp('{' + paramKey + '}')).test(config.url)) {
config.url = config.url.replace('{' + paramKey + '}', encodeURIComponent(paramVal));
delete params[paramKey];
}
});
}
// Get cached params
config.params = params;
var requestUrl = URI(config.url).addSearch(config.params || {}).toString();
// Get headers
config.headers = config.noAuthentication ? getHeaders() : getHeaders({
method : config.method,
url : requestUrl,
body : config.data ? angular.toJson(config.data) : '',
diff : diff
});
// Let's go!
return $http(config).then(function (data) {
// Return datas only
return preventReturnData ? data : data.data;
}, function (error) {
return $q.reject(error);
});
}, function (error) {
return $q.reject(error);
});
}
/**
* Get specific schema from API.
*
* @param {string} schemaPath Path of the schema (like "/me").
* @return {promise} Success/Error.
*/
function getSchema (schemaPath) {
return $http({
method : 'GET',
url : baseUrl + schemaPath + '.json',
cache : ovhCache,
headers : getHeaders()
}).then(function (data) {
// Return datas only
return data.data;
}, function (error) {
return $q.reject(error);
});
}
/**
* Get all or a specific Models from API.
*
* @param {string} schemaPath Path of the schema (like "/me.json").
* @param {string} name (Optional) Models name.
* @return {promise} Success/Error.
*/
function getModels (schemaPath, name) {
return getSchema(schemaPath).then(function (schema) {
// If no "name" param, return all models
if (!name) {
return schema.models;
}
// Return only the requested models (throw an error if not present)
return schema.models[name] ? schema.models[name] : $q.reject({ data : { errorCode: 'NOT_FOUND', message: 'Models not found.' } });
}, function (error) {
return $q.reject(error);
});
}
/*========== COMMON ==========*/
/**
* User is logged ?
*
* @return {boolean} True/False.
*/
function isLogged () {
return !!keys.ck;
}
/**
* Get API time and calculate the difference with system clock.
*
* @return {promise} Success/Error.
*/
function getApiTimeDiff () {
if (apiDiff === undefined) {
return $http({
method : 'GET',
url : baseUrl + '/auth/time',
cache : ovhCache,
headers : getHeaders()
}).then(function (data) {
// Calculate the time lag between system clock and API time
apiDiff = Math.floor(Date.now() / 1000) - data.data;
return apiDiff;
}, function (error) {
return $q.reject(error);
});
} else {
// fast patch
return $q.when(true).then(function () {
return apiDiff;
});
}
}
/**
* Sign the request with SHA-1 encryption.
*
* @param {object} opts Informations required for signature.
* @return {string} Signed request.
*/
function signRequest (opts) {
return '$1$' + SHA1([keys.as, keys.ck, opts.method, opts.url, opts.body, opts.diff].join('+'));
}
/**
* Get request headers.
*
* @param {object} opts (Optional) Informations about authentified request.
* @return {object} The headers.
*/
function getHeaders (opts) {
if (!opts) {
// No authentication
return {
'Content-Type' : 'application/json;charset=utf-8'
};
} else {
var diff = (Math.floor(Date.now() / 1000) - opts.diff).toString();
return {
'Content-Type' : 'application/json;charset=utf-8',
'X-Ovh-Application' : keys.ak,
'X-Ovh-Consumer' : keys.ck,
'X-Ovh-Timestamp' : diff,
'X-Ovh-Signature' : signRequest({
method : opts.method,
url : opts.url,
body : opts.body,
diff : diff
})
};
}
}
/**
* Secure Hash Algorithm (SHA1)
* http://www.webtoolkit.info/
*/
/* jshint ignore:start */
function SHA1 (msg) {
function rotate_left(n,s) {
var t4 = ( n<<s ) | (n>>>(32-s));
return t4;
}
function lsb_hex(val) {
var str='';
var i;
var vh;
var vl;
for( i=0; i<=6; i+=2 ) {
vh = (val>>>(i*4+4))&0x0f;
vl = (val>>>(i*4))&0x0f;
str += vh.toString(16) + vl.toString(16);
}
return str;
}
function cvt_hex(val) {
var str='';
var i;
var v;
for( i=7; i>=0; i-- ) {
v = (val>>>(i*4))&0x0f;
str += v.toString(16);
}
return str;
}
function Utf8Encode(string) {
string = string.replace(/\r\n/g,'\n');
var utftext = '';
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
var blockstart;
var i, j;
var W = new Array(80);
var H0 = 0x67452301;
var H1 = 0xEFCDAB89;
var H2 = 0x98BADCFE;
var H3 = 0x10325476;
var H4 = 0xC3D2E1F0;
var A, B, C, D, E;
var temp;
msg = Utf8Encode(msg);
var msg_len = msg.length;
var word_array = new Array();
for( i=0; i<msg_len-3; i+=4 ) {
j = msg.charCodeAt(i)<<24 | msg.charCodeAt(i+1)<<16 |
msg.charCodeAt(i+2)<<8 | msg.charCodeAt(i+3);
word_array.push( j );
}
switch( msg_len % 4 ) {
case 0:
i = 0x080000000;
break;
case 1:
i = msg.charCodeAt(msg_len-1)<<24 | 0x0800000;
break;
case 2:
i = msg.charCodeAt(msg_len-2)<<24 | msg.charCodeAt(msg_len-1)<<16 | 0x08000;
break;
case 3:
i = msg.charCodeAt(msg_len-3)<<24 | msg.charCodeAt(msg_len-2)<<16 | msg.charCodeAt(msg_len-1)<<8 | 0x80;
break;
}
word_array.push( i );
while( (word_array.length % 16) != 14 ) word_array.push( 0 );
word_array.push( msg_len>>>29 );
word_array.push( (msg_len<<3)&0x0ffffffff );
for ( blockstart=0; blockstart<word_array.length; blockstart+=16 ) {
for( i=0; i<16; i++ ) W[i] = word_array[blockstart+i];
for( i=16; i<=79; i++ ) W[i] = rotate_left(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
A = H0;
B = H1;
C = H2;
D = H3;
E = H4;
for( i= 0; i<=19; i++ ) {
temp = (rotate_left(A,5) + ((B&C) | (~B&D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
for( i=20; i<=39; i++ ) {
temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
for( i=40; i<=59; i++ ) {
temp = (rotate_left(A,5) + ((B&C) | (B&D) | (C&D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
for( i=60; i<=79; i++ ) {
temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
H0 = (H0 + A) & 0x0ffffffff;
H1 = (H1 + B) & 0x0ffffffff;
H2 = (H2 + C) & 0x0ffffffff;
H3 = (H3 + D) & 0x0ffffffff;
H4 = (H4 + E) & 0x0ffffffff;
}
var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
return temp.toLowerCase();
}
/* jshint ignore:end */
// External functions
var fcts = {
login : login,
logout : logout,
isLogged : isLogged,
getSchema : getSchema,
getModels : getModels
};
// Generate all REST requests
angular.forEach(['get', 'put', 'post', 'delete', 'remove', 'del'], function (name) {
fcts[name] = function (url, config) {
return request(angular.extend(config || {}, {
method : ((name === 'remove' || name === 'del') ? 'delete' : name).toUpperCase(),
url : baseUrl + url
}));
};
});
return fcts;
}];
});