This repository has been archived by the owner on Jul 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
auth.go
104 lines (90 loc) · 2.42 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"context"
"encoding/base64"
"errors"
"fmt"
"net/http"
"strings"
"github.com/fiatjaf/lightningd-gjson-rpc/plugin"
)
func defaultAuth(r *http.Request) error {
if accessKey == "" {
return errors.New("no default login credentials set")
}
if r.Header.Get("X-Access") == accessKey {
return nil
}
if r.URL.Query().Get("access-key") == accessKey {
return nil
}
if cookie, err := r.Cookie("user"); err == nil {
var value string
if err = scookie.Decode("user", cookie.Value, &value); err == nil && strings.HasPrefix(login+":", value) {
return nil
}
}
// try to get basic auth
v := r.Header.Get("Authorization")
parts := strings.Split(v, " ")
if len(parts) == 2 {
creds, err := base64.StdEncoding.DecodeString(parts[1])
if err == nil {
if string(creds) == login {
return nil
}
}
}
return fmt.Errorf("Invalid access key.")
}
func authMiddleware(p *plugin.Plugin) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/")
if path == "" || path == "rpc" || path == "stream" {
// default key / login
if err := defaultAuth(r); err == nil {
// set cookie
user := strings.Split(login, ":")[0]
if encoded, err := scookie.Encode("user", user); err == nil {
cookie := &http.Cookie{
Name: "user",
Value: encoded,
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
MaxAge: 2592000,
}
http.SetCookie(w, cookie)
}
next.ServeHTTP(w, r)
return
}
// extra keys -- only access the /rpc and /stream endpoints
if path == "rpc" || path == "stream" {
for key, permissions := range keys {
if r.Header.Get("X-Access") == key ||
r.URL.Query().Get("access-key") == key {
r = r.WithContext(context.WithValue(
r.Context(),
"permissions", permissions,
))
next.ServeHTTP(w, r)
return
}
}
}
p.Logf("auth failed at /%s", path)
w.Header().Set("WWW-Authenticate", `Basic realm="Private Area"`)
w.WriteHeader(401)
return
}
// if you know where the manifest is you can have it
if manifestKey != "" && path == "manifest-"+manifestKey+"/manifest.json" {
r.URL.Path = "/manifest/manifest.json"
}
next.ServeHTTP(w, r)
return
})
}
}