-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
86 lines (67 loc) · 1.94 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
package main
import (
"context"
"fmt"
"net/http"
"os"
"time"
"github.com/golang-jwt/jwt"
)
func auth(w http.ResponseWriter, r *http.Request) {
jwtString := r.URL.Query().Get("jwt")
if jwtString == "" {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, "No JWT")
return
}
// parse the token
token, err := jwt.Parse(jwtString, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return []byte(os.Getenv("MYRADIO_SIGNING_KEY")), nil
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err)
return
}
session, _ := cookiestore.Get(r, AuthRealm)
memberid := claims["uid"].(float64)
name := claims["name"].(string)
myRadioNameCache[int(memberid)] = myRadioNameCacheObject{
name: name,
cacheTime: time.Now(),
}
session.Values["memberid"] = int(memberid)
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
}
func AuthHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/auth" {
h.ServeHTTP(w, r)
return
}
session, _ := cookiestore.Get(r, AuthRealm)
if auth, ok := session.Values["memberid"].(int); !ok || auth == 0 {
// redirect to auth
http.Redirect(w, r, fmt.Sprintf("https://ury.org.uk/myradio/MyRadio/jwt?redirectto=%s/auth", os.Getenv("HOST")), http.StatusFound)
} else {
ctx := context.WithValue(context.Background(), UserCtxKey, auth)
h.ServeHTTP(w, r.WithContext(ctx))
}
})
}
func logout(w http.ResponseWriter, r *http.Request) {
session, _ := cookiestore.Get(r, AuthRealm)
session.Values["memberid"] = 0
session.Save(r, w)
http.Redirect(w, r, "https://ury.org.uk/myradio/MyRadio/logout", http.StatusFound)
}