-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
96 lines (82 loc) · 2.42 KB
/
index.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
import type { ADWebAuthConfig } from './types.js'
export class AdWebAuthConnector {
readonly #config: ADWebAuthConfig
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
readonly #maxRetries = 3
constructor(defaultConfig: ADWebAuthConfig) {
this.#config = defaultConfig
if (!this.#config.url.endsWith('/auth')) {
this.#config.url += '/auth'
}
}
async #authenticate(
userName: string,
passwordPlain: string,
remainingRetries: number
): Promise<boolean> {
if (remainingRetries <= 0) {
return false
}
try {
let response: Response
switch (this.#config.method) {
case 'get': {
response = await fetch(
`${this.#config.url}/byGet?${
this.#config.userNameField
}=${encodeURIComponent(userName)}&${
this.#config.passwordField
}=${encodeURIComponent(passwordPlain)}`,
{
method: 'get'
}
)
break
}
case 'post': {
response = await fetch(`${this.#config.url}/byPost`, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
[this.#config.userNameField]: userName,
[this.#config.passwordField]: passwordPlain
})
})
break
}
case 'headers': {
response = await fetch(`${this.#config.url}/byHeaders`, {
method: 'get',
headers: {
[this.#config.userNameField]: userName,
[this.#config.passwordField]: passwordPlain
}
})
break
}
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
default: {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`Invalid method: ${this.#config.method}`)
}
}
return (await response.json()) as boolean
} catch (error) {
console.log(error)
return await this.#authenticate(
userName,
passwordPlain,
remainingRetries - 1
)
}
}
async authenticate(
userName: string,
passwordPlain: string
): Promise<boolean> {
return await this.#authenticate(userName, passwordPlain, this.#maxRetries)
}
}
export type { ADWebAuthConfig } from './types.js'