/
auth.go
42 lines (37 loc) · 1.13 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// SPDX-FileCopyrightText: 2023 Institute for Automation of Complex Power Systems
// SPDX-License-Identifier: Apache-2.0
package main
import (
"flag"
"net/http"
"strings"
)
var (
authUsername = flag.String("api-username", "admin", "Username for API endpoint")
authPassword = flag.String("api-password", "", "Password for API endpoint")
authToken = flag.String("api-token", "", "Bearer token for authentication")
)
func basicAuth(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
valid := true
if *authPassword != "" {
username, password, ok := r.BasicAuth()
valid = ok && username == *authUsername && password == *authPassword
} else if *authToken != "" {
authHeader := r.Header.Get("Authentication")
if authHeader != "" {
tokens := strings.Split(authHeader, " ")
switch tokens[0] {
case "Bearer":
valid = tokens[1] == *authToken
}
}
}
if valid {
next.ServeHTTP(w, r)
} else {
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}
})
}