added basic auth

This commit is contained in:
2022-05-12 23:37:59 +02:00
parent 6f693d48c1
commit 2ae7923efc
4 changed files with 37 additions and 4 deletions

View File

@@ -2,6 +2,7 @@ package web
import (
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
@@ -20,7 +21,11 @@ type deleteShare struct {
Slug string `json:"slug"`
}
func StartWebserver(addr string, client client.Client) error {
func StartWebserver(addr string, client client.Client, username, password string) error {
if username == "" || password == "" {
return errors.New("API username and password must be set")
}
r := mux.NewRouter()
r.HandleFunc("/{slug:[a-zA-Z0-9]{6}}", func(w http.ResponseWriter, r *http.Request) {
@@ -53,11 +58,16 @@ func StartWebserver(addr string, client client.Client) error {
}).Methods("HEAD")
r.HandleFunc("/api/share", func(w http.ResponseWriter, r *http.Request) {
if !checkAuth(w, r, username, password) {
return
}
}).Methods("GET")
r.HandleFunc("/api/share", func(w http.ResponseWriter, r *http.Request) {
// TODO: check auth
if !checkAuth(w, r, username, password) {
return
}
var shareParams createShare
err := json.NewDecoder(r.Body).Decode(&shareParams)
@@ -81,7 +91,9 @@ func StartWebserver(addr string, client client.Client) error {
}).Methods("POST")
r.HandleFunc("/api/share", func(w http.ResponseWriter, r *http.Request) {
//TODO: check auth
if !checkAuth(w, r, username, password) {
return
}
var shareParams deleteShare
err := json.NewDecoder(r.Body).Decode(&shareParams)
@@ -136,3 +148,18 @@ func getShareHead(client client.Client, w http.ResponseWriter, r *http.Request)
return share
}
func checkAuth(w http.ResponseWriter, r *http.Request, username, password string) bool {
username, password, ok := r.BasicAuth()
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return false
}
if username != username || password != password {
w.WriteHeader(http.StatusUnauthorized)
return false
}
return true
}