Browse Source

Add basic auth middleware

William Petit 3 months ago
parent
commit
d237f3ff0d
3 changed files with 37 additions and 0 deletions
  1. 3
    0
      Dockerfile
  2. 29
    0
      auth.go
  3. 5
    0
      main.go

+ 3
- 0
Dockerfile View File

@@ -46,6 +46,9 @@ EXPOSE 3000
46 46
 VOLUME /tiff
47 47
 VOLUME /data
48 48
 
49
+ENV FIELDNOTES_USERNAME=
50
+ENV FIELDNOTES_PASSWORD=
51
+
49 52
 WORKDIR /app
50 53
 
51 54
 CMD ["./bin/server", "-tiff", "/tiff", "-nomenclature", "/data/nomenclatures.json"]

+ 29
- 0
auth.go View File

@@ -0,0 +1,29 @@
1
+package main
2
+
3
+import (
4
+	"fmt"
5
+	"net/http"
6
+)
7
+
8
+func BasicAuth(username, password string) func(http.Handler) http.Handler {
9
+	return func(next http.Handler) http.Handler {
10
+		fn := func(w http.ResponseWriter, r *http.Request) {
11
+			reqUsername, reqPassword, ok := r.BasicAuth()
12
+			if !ok {
13
+				unauthorized(w)
14
+				return
15
+			}
16
+			if reqUsername != username || password != reqPassword {
17
+				unauthorized(w)
18
+				return
19
+			}
20
+			next.ServeHTTP(w, r)
21
+		}
22
+		return http.HandlerFunc(fn)
23
+	}
24
+}
25
+
26
+func unauthorized(w http.ResponseWriter) {
27
+	w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="fieldnotes-server"`))
28
+	http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
29
+}

+ 5
- 0
main.go View File

@@ -50,6 +50,11 @@ func main() {
50 50
 
51 51
 	r.Group(func(r chi.Router) {
52 52
 
53
+		username := os.Getenv("FIELDNOTES_USERNAME")
54
+		password := os.Getenv("FIELDNOTES_PASSWORD")
55
+
56
+		r.Use(BasicAuth(username, password))
57
+
53 58
 		r.Get("/", showHomePage)
54 59
 
55 60
 		r.Get("/geotiff-explorer", showGeoTiffExplorerPage)