-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.go
55 lines (45 loc) · 1.21 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
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"net/http"
"net/url"
"os"
)
// Check if authentication is enabled
func checkAuthEnabled(isEnabled bool) {
authEnabled = isEnabled
// If authentication is disabled
if !isEnabled {
Warn.Println("Authentication is disabled")
return
}
// Gets the key from env variable
key, isValid := os.LookupEnv("TORRENTTPKEY")
// Check if key is empty or unset
if key == "" || !isValid {
Error.Fatalln("Auth flag is enabled but TORRENTTPKEY env variable is empty or unset")
}
// Set the API key to the value of TORRENTTPKEY
apiKey = key
Info.Println("Authentication is enabled")
}
// Check for API key on the HTTP query
func checkAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get API key from HTTP query
key := r.URL.Query().Get("key")
if authEnabled {
// Unescape the API key
unescapedKey, unescapeErr := url.QueryUnescape(key)
if unescapeErr != nil {
errorRes(w, "Error unescaping the API key", http.StatusInternalServerError)
return
}
// Check if API key is valid
if unescapedKey != apiKey {
errorRes(w, "Key is not valid", http.StatusForbidden)
return
}
}
next.ServeHTTP(w, r)
})
}