feat: basic authentication

This commit is contained in:
raf 2023-12-19 00:49:12 +03:00
parent 14a55bd77d
commit 11585b3662
No known key found for this signature in database
GPG key ID: 02D1DD3FA08B6B29
2 changed files with 21 additions and 3 deletions

View file

@ -15,8 +15,8 @@ httpserve -p <PORT> -a <ADDRESS> -f <FILENAME> -c <CONTENT_TYPE>
- `-a <ADDRESS>`: Set the address for the server (default: 0.0.0.0) - `-a <ADDRESS>`: Set the address for the server (default: 0.0.0.0)
- `-f <FILENAME>`: Set the filename header for downloaded content - `-f <FILENAME>`: Set the filename header for downloaded content
- `-c <CONTENT_TYPE>`: Set the content-type header (default: application/octet-stream) - `-c <CONTENT_TYPE>`: Set the content-type header (default: application/octet-stream)
- `-user <USERNAME>`: The user that will be used in authentication prompts
> Replace `<PORT>`, `<ADDRESS>`, `<FILENAME>`, and `<CONTENT_TYPE>` with your preferred values. - `-password <PASSWORD>`: The password required to access served data
### Examples ### Examples

20
main.go
View file

@ -42,12 +42,30 @@ var (
address = flag.String("a", "0.0.0.0", "Address (default: 0.0.0.0)") address = flag.String("a", "0.0.0.0", "Address (default: 0.0.0.0)")
fileName = flag.String("f", "", "Set filename header") fileName = flag.String("f", "", "Set filename header")
contentType = flag.String("c", "application/octet-stream", "Set content-type header (default: application/octet-stream)") contentType = flag.String("c", "application/octet-stream", "Set content-type header (default: application/octet-stream)")
username = flag.String("user", "", "Username for basic authentication")
password = flag.String("password", "", "Password for basic authentication")
) )
func basicAuth(handler http.Handler, username, password string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if username != "" || password != "" {
user, pass, ok := r.BasicAuth()
if !ok || user != username || pass != password {
w.Header().Set("WWW-Authenticate", `Basic realm="Please enter your credentials"`)
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized access"))
return
}
}
handler.ServeHTTP(w, r)
})
}
func main() { func main() {
flag.Parse() flag.Parse()
http.Handle("/", &requestHandler{}) authHandler := basicAuth(&requestHandler{}, *username, *password)
http.Handle("/", authHandler)
addr := fmt.Sprintf("%s:%d", *address, *port) addr := fmt.Sprintf("%s:%d", *address, *port)
log.Printf("Server starting on %s\n", addr) log.Printf("Server starting on %s\n", addr)