-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandlers.go
62 lines (56 loc) · 1.74 KB
/
handlers.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
package main
import (
"net/http"
"strings"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/garyburd/redigo/redis"
)
func Health(w http.ResponseWriter, r *http.Request) {
response(w, http.StatusOK, "UP")
}
func Token(w http.ResponseWriter, r *http.Request) {
if apikey := r.Header.Get(APIKEY_HEADER); len(apikey) == 0 {
response(w, http.StatusBadRequest, "APIKEY header is required!")
} else if val, ok := APIKEYS["apikey:"+apikey]; ok {
secret := []byte(AUTH_SECRET)
issuer := jwt.New(jwt.SigningMethodHS256)
issuer.Claims = jwt.MapClaims{
"sub": val.Name,
"exp": time.Now().Add(time.Hour * 72).Unix(),
"roles": strings.Split(val.Roles, ","),
}
if token, err := issuer.SignedString(secret); err != nil {
response(w, http.StatusInternalServerError, err.Error())
} else {
responseObject(w, http.StatusOK, JWT{Token: token})
}
} else {
response(w, http.StatusUnauthorized, "APIKEY is unauthorized!")
}
}
func Cache(w http.ResponseWriter, r *http.Request) {
if c, err := redis.Dial("tcp", REDIS_HOST+":"+REDIS_PORT); err != nil {
response(w, http.StatusInternalServerError, err.Error())
} else {
defer c.Close()
if keys, err := redis.Strings(c.Do("KEYS", "apikey:*")); err != nil {
response(w, http.StatusInternalServerError, err.Error())
} else {
APIKEYS = make(map[string]ApiKey)
var a ApiKey
for _, key := range keys {
if v, err := redis.Values(c.Do("HGETALL", key)); err != nil {
response(w, http.StatusInternalServerError, "key : "+key+" "+err.Error())
return
} else if err := redis.ScanStruct(v, &a); err != nil {
response(w, http.StatusInternalServerError, err.Error())
return
} else {
APIKEYS[key] = a
}
}
response(w, http.StatusOK, "OK")
}
}
}