/
legacy.ts
232 lines (203 loc) · 5.62 KB
/
legacy.ts
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
// Copyright 2020 Cognite AS
import isString from 'lodash/isString';
import isFunction from 'lodash/isFunction';
import { CDFHttpClient } from '../httpClient/cdfHttpClient';
import {
bearerString,
clearParametersFromUrl,
isLocalhost,
isSameProject,
isUsingSSL,
getBaseUrl,
} from '../utils';
import { CogniteLoginError } from '../loginError';
import { AUTHORIZATION_HEADER } from '../constants';
import { HttpCall } from '../httpClient/basicHttpClient';
import { HttpHeaders } from '../httpClient/httpHeaders';
import * as LoginUtils from '../loginUtils';
import {
ACCESS_TOKEN_PARAM,
AuthorizeOptions,
AuthTokens,
ERROR_DESCRIPTION_PARAM,
ERROR_PARAM,
ID_TOKEN_PARAM,
parseTokenQueryParameters,
} from '../loginUtils';
import { createUniversalRetryValidator } from '../httpClient/retryValidator';
export const REDIRECT = 'REDIRECT';
export const POPUP = 'POPUP';
export type OnTokens = (tokens: AuthTokens) => void;
export type OnAuthenticate = (login: OnAuthenticateLoginObject) => void;
export interface AuthOptions {
project: string;
baseUrl?: string;
}
export interface LoginParams {
onAuthenticate?: OnAuthenticate | 'REDIRECT' | 'POPUP';
}
export interface IdInfo {
projectId: number;
project: string;
user: string;
}
export interface OnAuthenticateLoginObject {
redirect: (options: AuthorizeOptions) => void;
popup: (options: AuthorizeOptions) => void;
skip: () => void;
}
/** @hidden */
export interface AuthenticateParams {
project: string;
}
/** @hidden */
export async function getIdInfo(
get: HttpCall,
headers: HttpHeaders
): Promise<null | IdInfo> {
try {
const response = await get<any>('/login/status', { headers });
const { loggedIn, user, project, projectId } = response.data.data;
if (!loggedIn) {
return null;
}
return {
user,
project,
projectId,
};
} catch (err) {
if (err.status === 401) {
return null;
}
throw err;
}
}
export class CogniteAuthentication {
private readonly project: string;
private authTokens?: AuthTokens;
private httpClient: CDFHttpClient;
private baseUrl: string;
constructor({ project, baseUrl }: AuthOptions) {
if (!isString(project)) {
throw Error('options.project is required and must be of type string');
}
this.baseUrl = baseUrl || getBaseUrl(baseUrl);
this.httpClient = new CDFHttpClient(
this.baseUrl,
createUniversalRetryValidator()
);
this.project = project;
}
public login({
onAuthenticate: onAuthMethod,
}: LoginParams): Promise<AuthTokens | null> {
const onAuthenticate =
onAuthMethod === POPUP
? onAuthenticateWithPopup
: isFunction(onAuthMethod)
? onAuthMethod
: onAuthenticateWithRedirect;
return new Promise((resolve, reject) => {
const login: OnAuthenticateLoginObject = {
skip: () => {
resolve(null);
},
redirect: (params) => {
const authorizeParams = {
baseUrl: this.baseUrl,
project: this.project,
...params,
};
LoginUtils.loginWithRedirect(authorizeParams).catch(reject);
},
popup: async (params) => {
const authorizeParams = {
baseUrl: this.baseUrl,
project: this.project,
...params,
};
try {
const tokens = await LoginUtils.loginWithPopup(authorizeParams);
if (tokens) {
this.setTokens(tokens);
resolve(tokens);
} else {
reject(new CogniteLoginError());
}
} catch (error) {
reject(error);
}
},
};
onAuthenticate(login);
});
}
public async getCDFToken(): Promise<AuthTokens | null> {
if (this.authTokens) {
const { accessToken, idToken } = this.authTokens;
const isValid = await isTokensValid(this.httpClient, this.project, {
accessToken,
idToken,
});
if (isValid) {
return { accessToken, idToken };
}
}
return null;
}
public async handleLoginRedirect(): Promise<AuthTokens | null> {
if (!isUsingSSL() && !isLocalhost()) {
return null;
}
const tokens = extractTokensFromUrl();
if (
tokens !== null &&
(await isTokensValid(this.httpClient, this.project, tokens))
) {
clearParametersFromUrl(ACCESS_TOKEN_PARAM, ID_TOKEN_PARAM);
this.setTokens(tokens);
return tokens;
}
return null;
}
private setTokens({ accessToken, idToken }: AuthTokens) {
this.authTokens = { accessToken, idToken };
}
}
function extractTokensFromUrl() {
try {
const tokens = parseTokenQueryParameters(window.location.search);
clearParametersFromUrl(ACCESS_TOKEN_PARAM, ID_TOKEN_PARAM);
return tokens;
} catch (err) {
clearParametersFromUrl(ERROR_PARAM, ERROR_DESCRIPTION_PARAM);
throw err;
}
}
function onAuthenticateWithRedirect(login: OnAuthenticateLoginObject) {
login.redirect({
redirectUrl: window.location.href,
});
}
function onAuthenticateWithPopup(login: OnAuthenticateLoginObject) {
login.popup({
redirectUrl: window.location.href,
});
}
async function isTokensValid(
httpClient: CDFHttpClient,
project: string,
tokens: AuthTokens
) {
const idInfo = await getIdInfoFromAccessToken(httpClient, tokens.accessToken);
return idInfo !== null && isSameProject(idInfo.project, project);
}
function getIdInfoFromAccessToken(
httpClient: CDFHttpClient,
accessToken: string
): Promise<null | IdInfo> {
return getIdInfo(httpClient.get.bind(httpClient), {
[AUTHORIZATION_HEADER]: bearerString(accessToken),
});
}