UNPKG

1.57 kBJavaScriptView Raw
1'use strict';
2
3const HEADER_ENCODING_FORMAT = 'base64';
4
5const encodingModeEnum = {
6 STRICT: 'strict',
7 LOOSE: 'loose',
8};
9
10
11/**
12 * Encode a single {value} using the application/x-www-form-urlencoded media type
13 * while also applying some additional rules specified by the spec
14 *
15 * @see https://tools.ietf.org/html/rfc6749#appendix-B
16 * @see https://tools.ietf.org/html/rfc6749#section-2.3.1
17 *
18 * @param {String} value
19 */
20function useFormURLEncode(value) {
21 return encodeURIComponent(value).replace(/%20/g, '+');
22}
23
24/**
25 * Get a string representation for the client credentials
26 *
27 * @param {String} clientID
28 * @param {String} clientSecret
29 * @returns {String} credentials
30 */
31function getCredentialsString(clientID, clientSecret) {
32 return `${clientID}:${clientSecret}`;
33}
34
35class Encoding {
36 constructor(encodingMode) {
37 this.encodingMode = encodingMode;
38 }
39
40 /**
41 * Get the authorization header used to request a valid token
42 * @param {String} clientID
43 * @param {String} clientSecret
44 * @return {String} Authorization header string token
45 */
46 getAuthorizationHeaderToken(clientID, clientSecret) {
47 let encodedCredentials;
48
49 if (this.encodingMode === encodingModeEnum.STRICT) {
50 encodedCredentials = getCredentialsString(useFormURLEncode(clientID), useFormURLEncode(clientSecret));
51 } else {
52 encodedCredentials = getCredentialsString(clientID, clientSecret);
53 }
54
55 return Buffer.from(encodedCredentials).toString(HEADER_ENCODING_FORMAT);
56 }
57}
58
59module.exports = {
60 Encoding,
61 encodingModeEnum,
62};