-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
65 lines (54 loc) · 1.66 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
/**
* @param {string} USERNAME User name to access the page
* @param {string} PASSWORD Password to access the page
* @param {string} PASSWORD A name of an area (a page or a group of pages) to protect.
* Some browsers may show "Enter user name and password to access REALM"
*/
const USERNAME = 'demouser'
const PASSWORD = 'demopassword'
const REALM = 'Secure Area'
/**
* Break down base64 encoded authorization string into plain-text username and password
* @param {string} authorization
* @returns {string[]}
*/
function parseCredentials(authorization) {
const parts = authorization.split(' ')
const plainAuth = atob(parts[1])
const credentials = plainAuth.split(':')
return credentials
}
/**
* Helper funtion to generate Response object
* @param {string} message
* @returns {Response}
*/
function getUnauthorizedResponse(message) {
let response = new Response(message, {
status: 401,
})
response.headers.set('WWW-Authenticate', `Basic realm="${REALM}"`)
return response
}
/**
* @param {Request} request
* @returns {Response}
*/
async function handleRequest(request) {
const authorization = request.headers.get('authorization')
if (!request.headers.has('authorization')) {
return getUnauthorizedResponse(
'Provide User Name and Password to access this page.',
)
}
const credentials = parseCredentials(authorization)
if (credentials[0] !== USERNAME || credentials[1] !== PASSWORD) {
return getUnauthorizedResponse(
'The User Name and Password combination you have entered is invalid.',
)
}
return await fetch(request)
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})