-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathindex.js
87 lines (69 loc) · 1.68 KB
/
index.js
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
const NAME = "super"
const PASS = "secret"
/**
* RegExp for basic auth credentials
*
* credentials = auth-scheme 1*SP token68
* auth-scheme = "Basic" ; case insensitive
* token68 = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"="
*/
const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/
/**
* RegExp for basic auth user/pass
*
* user-pass = userid ":" password
* userid = *<TEXT excluding ":">
* password = *TEXT
*/
const USER_PASS_REGEXP = /^([^:]*):(.*)$/
/**
* Object to represent user credentials.
*/
const Credentials = function(name, pass) {
this.name = name
this.pass = pass
}
/**
* Parse basic auth to object.
*/
const parseAuthHeader = function(string) {
if (typeof string !== 'string') {
return undefined
}
// parse header
const match = CREDENTIALS_REGEXP.exec(string)
if (!match) {
return undefined
}
// decode user pass
const userPass = USER_PASS_REGEXP.exec(atob(match[1]))
if (!userPass) {
return undefined
}
// return credentials object
return new Credentials(userPass[1], userPass[2])
}
const unauthorizedResponse = function(body) {
return new Response(
body, {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="User Visible Realm"'
}
}
)
}
/**
* Handle request
*/
async function handle(request) {
const credentials = parseAuthHeader(request.headers.get("Authorization"))
if ( !credentials || credentials.name !== NAME || credentials.pass !== PASS) {
return unauthorizedResponse("Unauthorized")
} else {
return fetch(request)
}
}
addEventListener('fetch', event => {
event.respondWith(handle(event.request))
})