forked from ZizzyDizzyMC/linx-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapikeys.go
154 lines (128 loc) · 3.1 KB
/
apikeys.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package apikeys
import (
"bufio"
"encoding/base64"
"fmt"
"log"
"net/http"
"os"
"golang.org/x/crypto/scrypt"
"github.com/zenazn/goji/web"
)
const (
scryptSalt = "linx-server"
scryptN = 16384
scryptr = 8
scryptp = 1
scryptKeyLen = 32
)
type AuthOptions struct {
AuthFile string
UnauthMethods []string
BasicAuth bool
SiteName string
SitePath string
}
type ApiKeysMiddleware struct {
successHandler http.Handler
authKeys []string
o AuthOptions
}
func ReadAuthKeys(authFile string) []string {
var authKeys []string
f, err := os.Open(authFile)
if err != nil {
log.Fatal("Failed to open authfile: ", err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
authKeys = append(authKeys, scanner.Text())
}
err = scanner.Err()
if err != nil {
log.Fatal("Scanner error while reading authfile: ", err)
}
return authKeys
}
func CheckAuth(authKeys []string, key string) (result bool, err error) {
checkKey, err := scrypt.Key([]byte(key), []byte(scryptSalt), scryptN, scryptr, scryptp, scryptKeyLen)
if err != nil {
return
}
encodedKey := base64.StdEncoding.EncodeToString(checkKey)
for _, v := range authKeys {
if encodedKey == v {
result = true
return
}
}
result = false
return
}
func (a ApiKeysMiddleware) getSitePrefix() string {
prefix := a.o.SitePath
if len(prefix) <= 0 || prefix[0] != '/' {
prefix = "/" + prefix
}
return prefix
}
func (a ApiKeysMiddleware) goodAuthorizationHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", a.getSitePrefix())
w.WriteHeader(http.StatusFound)
}
func (a ApiKeysMiddleware) badAuthorizationHandler(w http.ResponseWriter, r *http.Request) {
if a.o.BasicAuth {
rs := ""
if a.o.SiteName != "" {
rs = fmt.Sprintf(` realm="%s"`, a.o.SiteName)
}
w.Header().Set("WWW-Authenticate", `Basic`+rs)
}
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
}
func (a ApiKeysMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var successHandler http.Handler
prefix := a.getSitePrefix()
if r.URL.Path == prefix+"auth" {
successHandler = http.HandlerFunc(a.goodAuthorizationHandler)
} else {
successHandler = a.successHandler
}
if sliceContains(a.o.UnauthMethods, r.Method) && r.URL.Path != prefix+"auth" {
// allow unauthenticated methods
successHandler.ServeHTTP(w, r)
return
}
key := r.Header.Get("Linx-Api-Key")
if key == "" && a.o.BasicAuth {
_, password, ok := r.BasicAuth()
if ok {
key = password
}
}
result, err := CheckAuth(a.authKeys, key)
if err != nil || !result {
http.HandlerFunc(a.badAuthorizationHandler).ServeHTTP(w, r)
return
}
successHandler.ServeHTTP(w, r)
}
func NewApiKeysMiddleware(o AuthOptions) func(*web.C, http.Handler) http.Handler {
fn := func(c *web.C, h http.Handler) http.Handler {
return ApiKeysMiddleware{
successHandler: h,
authKeys: ReadAuthKeys(o.AuthFile),
o: o,
}
}
return fn
}
func sliceContains(slice []string, s string) bool {
for _, v := range slice {
if s == v {
return true
}
}
return false
}