-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathform-service.ts
283 lines (235 loc) · 8.01 KB
/
form-service.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
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
import { PUBLIC_USER, userService } from '@hawtio/react'
import * as fetchIntercept from 'fetch-intercept'
import $ from 'jquery'
import { jwtDecode } from 'jwt-decode'
import { OAuthProtoService, UserProfile } from '../api'
import { OPENSHIFT_MASTER_KIND, log } from '../globals'
import {
FetchOptions,
fetchPath,
getCookie,
joinPaths,
logoutRedirect,
redirect,
relToAbsUrl,
secureDispose,
secureRetrieve,
} from '../utils'
import { FORM_AUTH_PROTOCOL_MODULE, FORM_TOKEN_STORAGE_KEY, FormConfig, ResolveUser } from './globals'
type LoginOptions = {
uri: URL
}
interface Headers {
Authorization: string
'X-XSRF-TOKEN'?: string
}
export class FormService implements OAuthProtoService {
private userProfile: UserProfile
private readonly login: Promise<boolean>
private formConfig: FormConfig | null
private fetchUnregister: (() => void) | null
constructor(formConfig: FormConfig | null, userProfile: UserProfile) {
log.debug('Initialising Form Auth Service')
this.userProfile = userProfile
this.userProfile.setOAuthType(FORM_AUTH_PROTOCOL_MODULE)
this.formConfig = formConfig
this.login = this.createLogin()
this.fetchUnregister = null
}
private async createLogin(): Promise<boolean> {
if (!this.formConfig) {
log.debug('Form auth disabled')
return false
}
if (!this.formConfig.uri) {
log.debug('Invalid config, disabled form auth:', this.formConfig)
return false
}
if (this.userProfile.hasError()) {
log.debug('Cannot login as user profile has an error: ', this.userProfile.getError())
return false
}
if (!this.userProfile.getMasterUri()) {
log.debug('Cannot initialise form authentication as master uri not specified')
return false
}
if (this.userProfile.hasToken()) {
return true // already logged in
}
const token = await this.checkToken()
if (!token) {
this.tryLogin({ uri: new URL(window.location.href) })
return false
}
/* Populate the profile with the new token */
log.debug('Populating user profile with token')
this.userProfile.setToken(token)
// Need fetch for keepalive
this.setupFetch()
this.setupJQueryAjax()
return true
}
private async checkToken(): Promise<string | null> {
// Token has to be provided in local storage
return await secureRetrieve(FORM_TOKEN_STORAGE_KEY)
}
private buildLoginUrl(options: LoginOptions): URL {
if (!this.formConfig) throw new Error('Cannot initiate login as form configuration cannot be derived')
const target = relToAbsUrl(this.formConfig.uri)
const targetUri = new URL(target)
log.debug('Login - form URI: ', target)
log.debug('Login - redirect URI:', options.uri)
const searchParams = new URLSearchParams()
searchParams.set('redirectUri', options.uri.toString())
targetUri.search = searchParams.toString()
return targetUri
}
private tryLogin(options: LoginOptions) {
const targetUri = this.buildLoginUrl(options)
if (targetUri.pathname === options.uri.pathname) {
// We are already in the login form
log.debug('Login - Already in', targetUri)
return
}
redirect(targetUri)
}
private setupFetch() {
if (this.userProfile.hasError()) {
return
}
log.debug('Intercept Fetch API to attach auth token to authorization header')
this.fetchUnregister = fetchIntercept.register({
request: (url, config) => {
log.debug('Fetch intercepted for oAuth authentication')
let headers: Headers = {
Authorization: `Bearer ${this.userProfile.getToken()}`,
}
// For CSRF protection with Spring Security
const token = getCookie('XSRF-TOKEN')
if (token) {
log.debug('Set XSRF token header from cookies')
headers = {
...headers,
'X-XSRF-TOKEN': token,
}
}
return [url, { headers, ...config }]
},
})
}
private setupJQueryAjax() {
if (this.userProfile.hasError()) {
return
}
log.debug('Set authorization header to Openshift auth token for AJAX requests')
const beforeSend = (xhr: JQueryXHR, settings: JQueryAjaxSettings) => {
// Set bearer token is used
xhr.setRequestHeader('Authorization', `Bearer ${this.userProfile.getToken()}`)
// For CSRF protection with Spring Security
const token = getCookie('XSRF-TOKEN')
if (token) {
log.debug('Set XSRF token header from cookies')
xhr.setRequestHeader('X-XSRF-TOKEN', token)
}
return // To suppress ts(7030)
}
$.ajaxSetup({ beforeSend })
}
private clearTokenStorage(): void {
secureDispose(FORM_TOKEN_STORAGE_KEY)
}
private doLogout(): void {
if (this.fetchUnregister) this.fetchUnregister()
const currentURI = new URL(window.location.href)
this.clearTokenStorage()
// Redirect to /auth/logout endpoint if possible
const targetUri = this.buildLoginUrl({ uri: currentURI })
logoutRedirect(targetUri)
}
async isLoggedIn(): Promise<boolean> {
// Use Promise to conform with interface
return await this.login
}
private getSubjectFromToken(token: string): string {
const payload = jwtDecode(token)
return payload.sub?.replace('system:serviceaccount:', '') ?? ''
}
registerUserHooks(): void {
log.debug('Registering oAuth user hooks')
const fetchUser = async (resolve: ResolveUser) => {
if (!this.login || !this.userProfile.hasToken() || this.userProfile.hasError()) {
resolve({ username: PUBLIC_USER, isLogin: false })
return false
}
const masterUri = this.userProfile.getMasterUri()
const isOpenShift = this.userProfile.getMasterKind() === OPENSHIFT_MASTER_KIND
const token = this.userProfile.getToken()
let subject = ''
try {
// Try and extract the subject from the token, if applicable
subject = this.getSubjectFromToken(token)
} catch (err) {
if (err instanceof Error) log.warn(err.message)
else log.error(err)
}
/*
* If subject not assigned and the cluster is OpenShift
* then ask cluster API for user.
*
* NOTE: This is an edge-case that really only affects development
* since form-login is prioritized for authentication of non-OpenShift clusters.
*/
if (subject === '' && isOpenShift) {
// Default to 'user' if there is a failure
subject = (await this.openShiftUser(masterUri, token)) ?? ''
}
// Default to user if subject cannot be established
resolve({ username: subject !== '' ? subject : 'user', isLogin: true })
userService.setToken(token)
return true
}
userService.addFetchUserHook(FORM_AUTH_PROTOCOL_MODULE, fetchUser)
const logout = async () => {
log.debug('Running oAuth logout hook')
const login = await this.login
if (!login || !this.userProfile.hasToken() || this.userProfile.hasError()) return false
log.info('Log out')
try {
this.doLogout()
} catch (error) {
log.error('Error logging out:', error)
}
return true
}
userService.addLogoutHook(FORM_AUTH_PROTOCOL_MODULE, logout)
}
/**
* Fetches the username connected to the token using the Openshift API.
* Only applicable if the cluster is Openshift.
*
* return null
*/
private async openShiftUser(masterUri: string, token: string): Promise<string | null> {
const fetchOptions: FetchOptions = {
headers: { Authorization: `Bearer ${token}` },
}
let userName = null
await fetchPath<void>(
joinPaths(masterUri, 'apis/user.openshift.io/v1/users/~'),
{
success: (data: string) => {
log.debug('Connected to master uri api')
const response = JSON.parse(data)
userName = response?.metadata?.name
return
},
error: err => {
log.debug('Cannot get username from Openshift token', { cause: err })
return
},
},
fetchOptions,
)
return userName
}
}