Repository navigation
Expand file tree
/
Copy pathhttp_handler.go
More file actions
167 lines (139 loc) · 4.22 KB
/
Copy pathhttp_handler.go
File metadata and controls
167 lines (139 loc) · 4.22 KB
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
package fsa
import (
"encoding/json"
"fmt"
"net/http"
"github.com/didip/tollbooth/v7"
"github.com/didip/tollbooth_chi"
"github.com/go-chi/chi/v5"
)
type Handler struct {
auth *Auth
}
func NewHandler(r chi.Router, auth *Auth) *Handler {
h := &Handler{
auth: auth,
}
h.SetupRoutes(r)
return h
}
func (h *Handler) SetupRoutes(router chi.Router) {
prefix := h.auth.Cfg.resolvedPrefix()
limiter := tollbooth.NewLimiter(float64(h.auth.Cfg.RateLimitPerSecond), nil)
limiter.SetIPLookups([]string{"RemoteAddr", "X-Forwarded-For", "X-Real-IP"})
router.Group(func(r chi.Router) {
if h.auth.Cfg.CORSConfig != nil {
r.Use(NewCORSMiddleware(h.auth.Cfg.CORSConfig))
}
if h.auth.Cfg.RateLimitPerSecond > 0 {
r.Use(tollbooth_chi.LimitHandler(limiter))
}
r.Post(prefix+"/login", h.Login)
r.Post(prefix+"/confirm", h.ConfirmCode)
r.Post(prefix+"/refresh", h.RefreshToken)
r.Post(prefix+"/logout", h.Logout)
// Register OPTIONS handlers so the CORS middleware can short-circuit
// preflight requests — without these, chi returns 405 before the
// middleware fires. The handler body is unreachable in practice.
if h.auth.Cfg.CORSConfig != nil {
noop := func(w http.ResponseWriter, r *http.Request) {}
r.Options(prefix+"/login", noop)
r.Options(prefix+"/confirm", noop)
r.Options(prefix+"/refresh", noop)
r.Options(prefix+"/logout", noop)
}
})
}
func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
var req struct {
Email string `json:"email"`
ReturnUrl string `json:"returnUrl"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
WriteErr(w, fmt.Errorf("invalid request body"), http.StatusBadRequest)
return
}
ctx := r.Context()
if len(req.Email) == 0 {
WriteErr(w, fmt.Errorf("email required"), http.StatusBadRequest)
return
}
if h.auth.emailLimiter != nil && !h.auth.emailLimiter.allow(req.Email) {
WriteErr(w, fmt.Errorf("rate limit exceeded for this email"), http.StatusTooManyRequests)
return
}
if len(req.ReturnUrl) == 0 {
if len(h.auth.Cfg.ReturnUrls) == 0 {
WriteErr(w, fmt.Errorf("returnUrl required and no defaults configured"), http.StatusBadRequest)
return
}
req.ReturnUrl = h.auth.Cfg.ReturnUrls[0]
}
validReturnUrl := false
for _, url := range h.auth.Cfg.ReturnUrls {
if url == req.ReturnUrl {
validReturnUrl = true
break
}
}
if !validReturnUrl {
WriteErr(w, fmt.Errorf("invalid return url"), http.StatusBadRequest)
return
}
err := h.auth.LoginStep1SendVerificationCode(ctx, req.Email, req.ReturnUrl)
if err != nil {
WriteErr(w, err, http.StatusInternalServerError)
return
}
WriteJSON(w, "ok")
}
func (h *Handler) ConfirmCode(w http.ResponseWriter, r *http.Request) {
var req struct {
Code string `json:"code"`
Email string `json:"email"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
WriteErr(w, fmt.Errorf("invalid request body"), http.StatusBadRequest)
return
}
ctx := r.Context()
if len(req.Code) == 0 || len(req.Email) == 0 {
WriteErr(w, fmt.Errorf("code and email required"), http.StatusBadRequest)
return
}
if h.auth.emailLimiter != nil && !h.auth.emailLimiter.allow(req.Email) {
WriteErr(w, fmt.Errorf("rate limit exceeded for this email"), http.StatusTooManyRequests)
return
}
confirmed, tokens, err := h.auth.LoginStep2ConfirmCode(ctx, req.Email, req.Code)
if err != nil {
WriteErr(w, err, http.StatusInternalServerError)
return
}
if !confirmed {
WriteErr(w, fmt.Errorf("error confirming code"), http.StatusBadRequest)
return
}
h.auth.SetTokenCookies(w, tokens)
h.auth.SetCSRFCookie(w)
WriteJSON(w, map[string]string{"status": "authenticated"})
}
func (h *Handler) RefreshToken(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("refresh_token")
if err != nil {
WriteErr(w, fmt.Errorf("refresh token required"), http.StatusUnauthorized)
return
}
ctx := r.Context()
tokens, err := h.auth.RefreshToken(ctx, cookie.Value)
if err != nil {
WriteErr(w, err, http.StatusUnauthorized)
return
}
h.auth.SetTokenCookies(w, tokens)
WriteJSON(w, map[string]string{"status": "refreshed"})
}
func (h *Handler) Logout(w http.ResponseWriter, r *http.Request) {
h.auth.ClearTokenCookies(w)
WriteJSON(w, map[string]string{"status": "logged_out"})
}