-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathcredentials.ts
53 lines (46 loc) · 1.43 KB
/
credentials.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
import { BasicAuthResult } from './auth.js'
import { safeCompare } from './compare.js'
// This contains all the logic for parsing and checking credentials
type AuthCredentialsObject = {
name: string
password: string
}
export type AuthCredentials = AuthCredentialsObject[]
export const parseCredentials = (credentials: string): AuthCredentials => {
const authCredentials: AuthCredentials = []
credentials.split('|').forEach((item) => {
if (item.length < 3) {
throw new Error(
`Received incorrect basic auth syntax, use <username>:<password>, received ${item}`
)
}
const parsedCredentials = item.split(':')
if (
parsedCredentials.length !== 2 ||
parsedCredentials[0].length === 0 ||
parsedCredentials[1].length === 0
) {
throw new Error(
`Received incorrect basic auth syntax, use <username>:<password>, received ${item}`
)
}
authCredentials.push({
name: parsedCredentials[0],
password: parsedCredentials[1],
})
})
return authCredentials
}
/**
* Compares the basic auth credentials with the configured user and password
* @param credentials Basic Auth credentials object from `basic-auth`
*/
export const compareCredentials = (
input: BasicAuthResult,
requiredCredentials: AuthCredentials
): boolean =>
requiredCredentials.some(
(item) =>
safeCompare(input.user, item.name) &&
safeCompare(input.pass, item.password)
)