-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathshotgun_middleware.go
75 lines (62 loc) · 1.69 KB
/
shotgun_middleware.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
package main
import (
"context"
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"fmt"
"net/http"
"strings"
)
var connectionCache map[string]Shotgun
func init() {
connectionCache = make(map[string]Shotgun)
}
func ShotgunAuthMiddleware(config clientConfig) func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
return func(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
s := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
if len(s) != 2 {
rw.Header().Set("WWW-Authenticate", `Basic realm="shotgun-restful"`)
rw.WriteHeader(http.StatusUnauthorized)
rw.Write([]byte("401 Unauthorized\n"))
return
}
if !strings.HasPrefix(s[0], "Basic") {
rw.Header().Set("WWW-Authenticate", `Basic realm="shotgun-restful"`)
rw.WriteHeader(http.StatusUnauthorized)
rw.Write([]byte("401 Unauthorized\n"))
return
}
var isUser bool
if s[0] == "Basic-User" {
isUser = true
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
rw.WriteHeader(http.StatusForbidden)
return
}
name := pair[0]
key := pair[1]
hasher := sha1.New()
hash := hex.EncodeToString(hasher.Sum([]byte(fmt.Sprintf("%s%v%s%s", config.shotgunHost, isUser, name, key))))
conn, ok := connectionCache[hash]
if !ok {
if isUser {
conn = NewUserShotgun(config.shotgunHost, name, key)
} else {
conn = NewShotgun(config.shotgunHost, name, key)
}
}
connectionCache[hash] = conn
conn.Log()
ctx := req.Context()
ctx = context.WithValue(ctx, "sgConn", conn)
next(rw, req.WithContext(ctx))
}
}