From 945695f1482e4eb40aa66471db2fe092361e65c0 Mon Sep 17 00:00:00 2001 From: Joren Schipman Date: Sat, 4 May 2024 01:51:52 +0200 Subject: [PATCH] add some auth --- loothandler.go | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/loothandler.go b/loothandler.go index ccafe24..e1fc124 100644 --- a/loothandler.go +++ b/loothandler.go @@ -11,8 +11,9 @@ import ( ) var ( - password = "hardcodedpassword" - lootPath = "Loot" + password = "hardcodedpassword" + lootPath = "Loot" + sessionCookieName = "auth_session" ) type PageData struct { @@ -44,6 +45,12 @@ func loginHandler(w http.ResponseWriter, r *http.Request) { } if r.FormValue("password") == password { + http.SetCookie(w, &http.Cookie{ + Name: sessionCookieName, + Value: "authenticated", + Path: "/", + MaxAge: 3600, + }) http.Redirect(w, r, "/loot", http.StatusSeeOther) return } @@ -52,10 +59,7 @@ func loginHandler(w http.ResponseWriter, r *http.Request) { } func lootHandler(w http.ResponseWriter, r *http.Request) { - if !isAuthenticated(r) { - http.Redirect(w, r, "/", http.StatusSeeOther) - return - } + checkAuth(w, r) uids, err := getDeviceUIDs() if err != nil { @@ -68,12 +72,20 @@ func lootHandler(w http.ResponseWriter, r *http.Request) { } func fileHandler(w http.ResponseWriter, r *http.Request) { + checkAuth(w, r) + requestedPath := strings.TrimPrefix(r.URL.Path, "/files/") filePath := filepath.Join(lootPath, requestedPath) http.ServeFile(w, r, filePath) } func logoutHandler(w http.ResponseWriter, r *http.Request) { + http.SetCookie(w, &http.Cookie{ + Name: sessionCookieName, + Value: "", + Path: "/", + MaxAge: -1, + }) http.Redirect(w, r, "/", http.StatusSeeOther) } @@ -87,6 +99,10 @@ func renderTemplate(w http.ResponseWriter, tmpl string, data interface{}) { } func isAuthenticated(r *http.Request) bool { + sessionCookie, err := r.Cookie(sessionCookieName) + if err != nil || sessionCookie.Value != "authenticated" { + return false + } return true } @@ -104,3 +120,10 @@ func getDeviceUIDs() ([]string, error) { return uids, nil } +func checkAuth(w http.ResponseWriter, r *http.Request) { + if !isAuthenticated(r) { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } +} +