Guest User

Untitled

a guest
May 3rd, 2022
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * @param {string} USERNAME User name to access the page
  3.  * @param {string} PASSWORD Password to access the page
  4.  * @param {string} REALM A name of an area (a page or a group of pages) to protect.
  5.  * Some browsers may show "Enter user name and password to access REALM"
  6.  */
  7. const USERNAME = 'demouser'
  8. const PASSWORD = 'demopassword'
  9. const REALM = 'Secure Area'
  10.  
  11. addEventListener('fetch', (event) => {
  12.   event.respondWith(handleRequest(event.request))
  13. })
  14.  
  15. async function handleRequest(request) {
  16.   const authorization = request.headers.get('authorization')
  17.   if (!request.headers.has('authorization')) {
  18.     return getUnauthorizedResponse(
  19.       'Provide User Name and Password to access this page.',
  20.     )
  21.   }
  22.   const credentials = parseCredentials(authorization)
  23.   if (credentials[0] !== USERNAME || credentials[1] !== PASSWORD) {
  24.     return getUnauthorizedResponse(
  25.       'The User Name and Password combination you have entered is invalid.',
  26.     )
  27.   }
  28.   return await fetch(request)
  29. }
  30.  
  31. /**
  32.  * Break down base64 encoded authorization string into plain-text username and password
  33.  * @param {string} authorization
  34.  * @returns {string[]}
  35.  */
  36. function parseCredentials(authorization) {
  37.   const parts = authorization.split(' ')
  38.   const plainAuth = atob(parts[1])
  39.   const credentials = plainAuth.split(':')
  40.   return credentials
  41. }
  42.  
  43. /**
  44.  * Helper funtion to generate Response object
  45.  * @param {string} message
  46.  * @returns {Response}
  47.  */
  48. function getUnauthorizedResponse(message) {
  49.   let response = new Response(message, {
  50.     status: 401,
  51.   })
  52.   response.headers.set('WWW-Authenticate', `Basic realm="${REALM}"`)
  53.   return response
  54. }
Add Comment
Please, Sign In to add comment