-
Notifications
You must be signed in to change notification settings - Fork 43
/
main.go
91 lines (72 loc) · 2.47 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
package main
import (
"log"
"net/http"
"strings"
"time"
"github.com/adam-hanna/jwt-auth/examples/login_logout/templates"
jwt "github.com/adam-hanna/jwt-auth/src"
)
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(w, 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":
restrictedRoute.NullifyTokenCookies(&w, r)
http.Redirect(w, r, "/login", 302)
default:
http.Error(w, "Method Not Allowed", 405)
}
})
func main() {
authErr := jwt.New(&restrictedRoute, jwt.Options{
PrivateKeyLocation: "keys/app.rsa", // `$ openssl genrsa -out app.rsa 2048`
PublicKeyLocation: "keys/app.rsa.pub", // `$ openssl rsa -in app.rsa -pubout > app.rsa.pub`
RefreshTokenValidTime: 5 * time.Second,
AuthTokenValidTime: 1 * time.Second,
})
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)
}