const fs = require('fs')
const http = require('http')
const path = require('path')

// The map of usernames to their passwords.
// Don't ever store raw passwords in a real application!
const passwords = new Map()
  .set('alice', '123456')
  .set('bob', 'supersecretpassword')

http.createServer((req, res) => {
  // Check the provided `user` and `password` headers
  const password = passwords.get(req.headers.user)
  if (password === undefined || password !== req.headers.password) {
    res.statusCode = 403 // Forbidden
    res.end()
    return
  }

  // If the login is valid, send the file
  const readStream = fs.createReadStream(path.join('files', req.url))
  readStream.on('error', _ => {
    res.write('File not found')
    res.end()
  })
  readStream.pipe(res)
}).listen(80)