From b8ad1dd9b94476438f6dd79006f4f5a79e29edb9 Mon Sep 17 00:00:00 2001 From: Lucas Barbieri Date: Mon, 19 Aug 2024 19:47:32 -0300 Subject: [PATCH] feat(): add basic authentication --- .gitignore | 1 + docker-compose.yml | 1 + main.go | 10 ++++++++++ 3 files changed, 12 insertions(+) diff --git a/.gitignore b/.gitignore index a37273b..58ec735 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ files/ +.key diff --git a/docker-compose.yml b/docker-compose.yml index cd46d8d..05b05f9 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,4 +7,5 @@ services: - "58080:8080" volumes: - ./files:/app/files + - ./.key:/app/.key restart: unless-stopped diff --git a/main.go b/main.go index 791facb..8a5b8f1 100644 --- a/main.go +++ b/main.go @@ -42,6 +42,11 @@ func uploadHandler(w http.ResponseWriter, r *http.Request) { return } + if !checkAuth(w, r) { + http.Error(w, "You're not authorized.", http.StatusBadRequest) + return + } + r.Body = http.MaxBytesReader(w, r.Body, maxFileSize) file, _, err := r.FormFile("file") @@ -77,3 +82,8 @@ func uploadHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "http://%s/%d\n", url, time) } } + +func checkAuth(w http.ResponseWriter, r *http.Request) bool { + authKey, _ := os.ReadFile(".key") + return r.Header.Get("X-Auth")+"\n" == string(authKey) +}