1 | 'use strict';
|
2 |
|
3 | const Hoek = require('@hapi/hoek');
|
4 | const querystring = require('querystring');
|
5 | const debug = require('debug')('simple-oauth2:request-options');
|
6 | const { Encoding, encodingModeEnum } = require('./encoding');
|
7 |
|
8 | const JSON_CONTENT_TYPE = 'application/json';
|
9 | const FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded';
|
10 |
|
11 | const authorizationMethodEnum = {
|
12 | HEADER: 'header',
|
13 | BODY: 'body',
|
14 | };
|
15 |
|
16 | const bodyFormatEnum = {
|
17 | FORM: 'form',
|
18 | JSON: 'json',
|
19 | };
|
20 |
|
21 | function getDefaultRequestOptions() {
|
22 | return {
|
23 | headers: {},
|
24 | };
|
25 | }
|
26 |
|
27 | class RequestOptions {
|
28 | #config = null;
|
29 | #requestOptions = null;
|
30 |
|
31 | constructor(config, params) {
|
32 | this.#config = config;
|
33 | this.#requestOptions = this.createOptions(params);
|
34 | }
|
35 |
|
36 | createOptions(params) {
|
37 | const parameters = { ...params };
|
38 | const requestOptions = getDefaultRequestOptions();
|
39 |
|
40 | if (this.#config.options.authorizationMethod === authorizationMethodEnum.HEADER) {
|
41 | const encoding = new Encoding(this.#config.options.credentialsEncodingMode);
|
42 | const credentials = encoding.getAuthorizationHeaderToken(this.#config.client.id, this.#config.client.secret);
|
43 |
|
44 | debug('Using header authentication. Authorization header set to %s', credentials);
|
45 |
|
46 | requestOptions.headers.Authorization = `Basic ${credentials}`;
|
47 | } else {
|
48 | debug('Using body authentication');
|
49 |
|
50 | parameters[this.#config.client.idParamName] = this.#config.client.id;
|
51 | parameters[this.#config.client.secretParamName] = this.#config.client.secret;
|
52 | }
|
53 |
|
54 | if (this.#config.options.bodyFormat === bodyFormatEnum.FORM) {
|
55 | debug('Using form request format');
|
56 |
|
57 | requestOptions.payload = querystring.stringify(parameters);
|
58 | requestOptions.headers['Content-Type'] = FORM_CONTENT_TYPE;
|
59 | } else {
|
60 | debug('Using json request format');
|
61 |
|
62 | requestOptions.payload = parameters;
|
63 | requestOptions.headers['Content-Type'] = JSON_CONTENT_TYPE;
|
64 | }
|
65 |
|
66 | return requestOptions;
|
67 | }
|
68 |
|
69 | toObject(requestOptions = {}) {
|
70 | return Hoek.applyToDefaults(requestOptions, this.#requestOptions);
|
71 | }
|
72 | }
|
73 |
|
74 | module.exports = {
|
75 | RequestOptions,
|
76 | authorizationMethodEnum,
|
77 | bodyFormatEnum,
|
78 | encodingModeEnum,
|
79 | };
|