-
Notifications
You must be signed in to change notification settings - Fork 43
/
handlers.go
184 lines (151 loc) · 5.66 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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package handlers
import (
"github.com/justinas/alice"
"log"
"net/http"
"time"
"strings"
"github.com/adam-hanna/jwt-auth/examples/detailed/server/templates"
"github.com/adam-hanna/jwt-auth/examples/detailed/db"
jwt "github.com/adam-hanna/jwt-auth/src"
)
var restrictedRoute jwt.Auth
func InitHandlers() error {
newRouteError := 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: 72 * time.Hour,
AuthTokenValidTime: 15 * time.Minute,
Debug: true,
})
if newRouteError != nil {
return newRouteError
}
restrictedRoute.SetUnauthorizedHandler(MyUnauthorizedHandler)
restrictedRoute.SetErrorHandler(myErrorHandler)
restrictedRoute.SetRevokeTokenFunction(db.DeleteRefreshToken)
restrictedRoute.SetCheckTokenIdFunction(db.CheckRefreshToken)
http.Handle("/", alice.New(recoverHandler).ThenFunc(loginHandler))
http.Handle("/register", alice.New(recoverHandler).ThenFunc(registerHandler))
http.Handle("/restricted", alice.New(restrictedRoute.Handler, recoverHandler).ThenFunc(restrictedHandler))
http.Handle("/logout", alice.New(restrictedRoute.Handler, recoverHandler).ThenFunc(logoutHandler))
http.Handle("/deleteUser", alice.New(restrictedRoute.Handler, recoverHandler).ThenFunc(deleteUserHandler))
return nil
}
var MyUnauthorizedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "I pitty the fool who is unauthorized", 401)
})
var myErrorHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "I pitty the fool who has a 500 internal server error", 500)
})
func recoverHandler(next http.Handler) http.Handler {
// this catches any errors and returns an internal server error to the client
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Panic("Recovered! Panic: %+v", err)
http.Error(w, http.StatusText(500), 500)
}
}()
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
var restrictedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
csrfSecret := w.Header().Get("X-CSRF-Token")
templates.RenderTemplate(w, "restricted", &templates.RestrictedPage{ csrfSecret, "Stoofs!" })
})
var loginHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
templates.RenderTemplate(w, "login", &templates.LoginPage{ false, "" })
case "POST":
r.ParseForm()
log.Println(r.Form)
user, uuid, loginErr := db.LogUserIn(strings.Join(r.Form["username"], ""), strings.Join(r.Form["password"], ""))
log.Println(user, uuid, loginErr)
if loginErr != nil {
// login err
// templates.RenderTemplate(w, "login", &templates.LoginPage{ true, "Login failed\n\nIncorrect username or password" })
w.WriteHeader(http.StatusUnauthorized)
} else {
// no login err
// now generate credentials for this user
claimsId, idErr := db.StoreRefreshToken()
if idErr != nil {
http.Error(w, http.StatusText(500), 500)
}
claims := jwt.ClaimsType{}
claims.StandardClaims.Subject = uuid
claims.StandardClaims.Id = claimsId
claims.CustomClaims = make(map[string]interface{})
claims.CustomClaims["Role"] = user.Role
err := restrictedRoute.IssueNewTokens(w, claims)
if err != nil {
http.Error(w, "Internal Server Error", 500)
}
w.WriteHeader(http.StatusOK)
}
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
})
var registerHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
templates.RenderTemplate(w, "register", &templates.RegisterPage{ false, "" })
case "POST":
r.ParseForm()
log.Println(r.Form)
// check to see if the username is already taken
_, uuid, err := db.FetchUserByUsername(strings.Join(r.Form["username"], ""))
if err == nil {
templates.RenderTemplate(w, "register", &templates.RegisterPage{ true, "Username not available!" })
// w.WriteHeader(http.StatusUnauthorized)
} else {
// nope, now create this user
role := "user"
uuid, err = db.StoreUser(strings.Join(r.Form["username"], ""), strings.Join(r.Form["password"], ""), role)
if err != nil {
http.Error(w, http.StatusText(500), 500)
}
log.Println("uuid: " + uuid)
// now generate cookies for this user
claimsId, idErr := db.StoreRefreshToken()
if idErr != nil {
http.Error(w, http.StatusText(500), 500)
}
claims := jwt.ClaimsType{}
claims.StandardClaims.Subject = uuid
claims.StandardClaims.Id = claimsId
claims.CustomClaims = make(map[string]interface{})
claims.CustomClaims["Role"] = role
err := restrictedRoute.IssueNewTokens(w, claims)
if err != nil {
http.Error(w, "Internal Server Error", 500)
}
w.WriteHeader(http.StatusOK)
}
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
})
var logoutHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// remove this user's ability to make requests
restrictedRoute.NullifyTokenCookies(&w, r)
// use 302 to force browser to do GET request
http.Redirect(w, r, "/", 302)
})
var deleteUserHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Deleting user")
claims, claimsErr := restrictedRoute.GrabTokenClaims(w, r)
if claimsErr != nil {
http.Error(w, http.StatusText(500), 500)
} else {
db.DeleteUser(claims.StandardClaims.Subject)
// remove this user's ability to make requests
restrictedRoute.NullifyTokenCookies(&w, r)
// use 302 to force browser to do GET request
http.Redirect(w, r, "/register", 302)
}
})