-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
84 lines (69 loc) · 1.96 KB
/
handler.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
package auth
import (
"context"
"crypto/ecdsa"
"fmt"
"log/slog"
"net/http"
"net/url"
"github.com/go-chi/chi/v5"
"github.com/seb-schulz/onegate/internal/usermgr"
)
type Config struct {
IssuerUrl string
PrivateKey *ecdsa.PrivateKey
}
func NewHandler(c *Config) http.Handler {
route := chi.NewRouter()
authorizationRequestHandler := authorizationRequestHandler{
clientByClientID: clientByClientID,
loginUrl: url.URL{Path: "/login"},
createAuthorization: createAuthorization,
}
route.Get("/auth", authorizationRequestHandler.ServeHTTP)
callbackRedirectHandler := &callbackRedirectHandler{
currentAuthorization: func(ctx context.Context) (authorization, error) {
return FirstAuthorization(ctx)
},
currentUser: usermgr.FromContext,
}
route.With(usermgr.Middleware).Get("/callback", callbackRedirectHandler.ServeHTTP)
tokenHandler := &tokenHandler{
issuerUrl: c.IssuerUrl,
privateKey: c.PrivateKey,
clientByClientID: clientByClientID,
authorizationByCode: authorizationByCode,
deleteAuthorization: func(ctx context.Context, a authorization) error {
return a.Delete(ctx)
},
}
route.Post("/token", tokenHandler.ServeHTTP)
return route
}
func RedirectWhenLoggedInAndAssigned(callbackURL string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authReq, err := FirstAuthorization(r.Context())
if authReq == nil {
next.ServeHTTP(w, r)
return
}
if err != nil {
// TODO: Evaluate proper error page
slog.Warn(fmt.Sprintf("oAuth2 callback failed with: %v", err))
http.NotFound(w, r)
return
}
if authReq.InternalUserID != nil {
http.Redirect(w, r, callbackURL, http.StatusSeeOther)
return
}
user := usermgr.FromContext(r.Context())
if user != nil {
http.Redirect(w, r, callbackURL, http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}
}