-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathsessionTokenManager.ts
More file actions
167 lines (157 loc) · 5.44 KB
/
sessionTokenManager.ts
File metadata and controls
167 lines (157 loc) · 5.44 KB
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
/**
* © Copyright IBM Corporation 2020, 2021. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { OutgoingHttpHeaders } from 'node:http';
import {
getCurrentTime,
TokenManager,
UserOptions,
validateInput,
} from 'ibm-cloud-sdk-core';
import { getSdkHeaders } from '../lib/common';
/** Configuration options for CouchDB session token retrieval. */
export interface SessionTokenManagerOptions extends UserOptions {
/** The username portion of CouchDB session authentication. */
username: string;
/** The password portion of CouchDB session authentication. */
password: string;
}
/**
* Token Manager of CouchDB session token.
*
* The Token Manager performs basic auth with username and password
* to acquire session tokens.
*/
export class SessionTokenManager extends TokenManager {
protected requiredOptions: string[] = [
'username',
'password',
'serviceUrl',
'jar',
];
private tokenName: string;
private options: SessionTokenManagerOptions;
/**
* Create a new [[SessionTokenManager]] instance. For internal use by
* CouchdbSessionAuthenticator only.
*
* @param {object} options Configuration options.
* @param {string} options.username The username portion of CouchDB Session authentication.
* @param {string} options.password The password portion of CouchDB Session authentication.
* @param {string} options.serviceUrl The endpoint for session token requests.
* @param {any} options.jar The Cookie jar for session token storage.
* @param {boolean} [options.disableSslVerification] A flag that indicates
* whether verification of the token server's SSL certificate should be
* disabled or not.
* @param {object<string, string>} [options.headers] Headers to be sent with every
* outbound HTTP requests to token services.
* @constructor
*/
constructor(options: SessionTokenManagerOptions) {
super(options);
validateInput(options, this.requiredOptions);
this.options = options;
this.tokenName = 'AuthSession';
}
/**
* Only base service specific headers are in use.
*
* @param {OutgoingHttpHeaders} headers - the new set of headers as an object
* @returns {Error}
*/
public override setHeaders(headers: OutgoingHttpHeaders): void {
const errMsg =
'During CouchDB Session Authentication only `request` service headers are in use';
throw new Error(errMsg);
}
/**
* Request a session token using basic credentials.
*
* @returns {Promise}
*/
protected requestToken(): Promise<any> {
const newHeaders = getSdkHeaders(
'cloudant',
'v1',
'authenticatorPostSession'
);
if (!this.options.headers) {
Object.assign(this.options, { 'headers': newHeaders });
} else {
Object.assign(this.options.headers, newHeaders);
}
// these cannot be overwritten
const parameters = {
options: {
headers: this.options.headers,
url: `${this.options.serviceUrl}/_session`,
method: 'POST',
body: {
username: this.options.username,
password: this.options.password,
},
},
};
return this.requestWrapperInstance.sendRequest(parameters);
}
/**
* From the response parse and save session token into field `accessToken`.
* Calculate expiration and refresh time from the received response
* and store them in fields `expireTime` and `refreshTime`.
*
* @param tokenResponse - Response object from session token request
* @private
* @returns {void}
*/
protected saveTokenInfo(tokenResponse): void {
const sessionCookie = tokenResponse.headers['set-cookie'];
if (!Array.isArray(sessionCookie)) {
const err = 'Set-Cookie header not present in response';
throw new Error(err);
}
let sessionToken = null;
let expireTime = null;
let refreshTime = null;
for (let i = 0; i < sessionCookie.length && sessionToken == null; i += 1) {
sessionToken = /AuthSession=([^;]*);/.exec(sessionCookie[i]);
if (sessionToken != null) {
expireTime = /.*Expires=([^;]*);/.exec(sessionCookie[i]);
refreshTime = /.*Max-Age=([^;]*);/.exec(sessionCookie[i]);
}
}
if (sessionToken == null) {
const err = 'Session token not present in response';
throw new Error(err);
}
[, this.accessToken] = sessionToken;
const fractionOfTtl = 0.8;
if (expireTime == null) {
if (refreshTime == null) {
this.expireTime = 0;
this.refreshTime = 0;
} else {
this.expireTime = Number(refreshTime[1]) + getCurrentTime();
this.refreshTime =
Number(refreshTime[1]) * fractionOfTtl + getCurrentTime();
}
} else {
// Store expire time in seconds
this.expireTime = Date.parse(expireTime[1]) / 1000;
// Set refresh time from the expire time
const timeToLive = this.expireTime - getCurrentTime();
this.refreshTime = this.expireTime - timeToLive * (1.0 - fractionOfTtl);
}
}
}