-
Notifications
You must be signed in to change notification settings - Fork 43
/
main.go
98 lines (78 loc) · 2.44 KB
/
main.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
package main
import (
"./templates"
"github.com/adam-hanna/jwt-auth/jwt"
"log"
"net/http"
"strings"
"time"
)
var restrictedRoute jwt.Auth
var myUnauthorizedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "I Pitty the fool who is Unauthorized", 401)
})
var restrictedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
csrfSecret := w.Header().Get("X-CSRF-Token")
claims, err := restrictedRoute.GrabTokenClaims(r)
log.Println(claims)
if err != nil {
http.Error(w, "Internal Server Error", 500)
} else {
templates.RenderTemplate(w, "restricted", &templates.RestrictedPage{csrfSecret, claims.CustomClaims["Role"].(string)})
}
})
var loginHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
templates.RenderTemplate(w, "login", &templates.LoginPage{})
case "POST":
r.ParseForm()
if strings.Join(r.Form["username"], "") == "testUser" && strings.Join(r.Form["password"], "") == "testPassword" {
claims := jwt.ClaimsType{}
claims.CustomClaims = make(map[string]interface{})
claims.CustomClaims["Role"] = "user"
err := restrictedRoute.IssueNewTokens(w, &claims)
if err != nil {
http.Error(w, "Internal Server Error", 500)
}
w.WriteHeader(http.StatusOK)
} else {
http.Error(w, "Unauthorized", 401)
}
default:
http.Error(w, "Method Not Allowed", 405)
}
})
var logoutHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
err := restrictedRoute.NullifyTokens(w, r)
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
http.Redirect(w, r, "/login", 302)
default:
http.Error(w, "Method Not Allowed", 405)
}
})
func main() {
authErr := jwt.New(&restrictedRoute, jwt.Options{
SigningMethodString: "HS256",
HMACKey: []byte("My super secret key!"),
RefreshTokenValidTime: 72 * time.Hour,
AuthTokenValidTime: 15 * time.Minute,
Debug: true,
IsDevEnv: true,
})
if authErr != nil {
log.Println("Error initializing the JWT's!")
log.Fatal(authErr)
}
restrictedRoute.SetUnauthorizedHandler(myUnauthorizedHandler)
http.HandleFunc("/", loginHandler)
http.Handle("/restricted", restrictedRoute.Handler(restrictedHandler))
http.Handle("/logout", restrictedRoute.Handler(logoutHandler))
log.Println("Listening on localhost:3000")
http.ListenAndServe("127.0.0.1:3000", nil)
}