forked from davidoram/kratos-selfservice-ui-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
217 lines (186 loc) · 6.2 KB
/
Copy pathmain.go
File metadata and controls
217 lines (186 loc) · 6.2 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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package main
import (
"context"
"embed"
"encoding/gob"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"time"
"github.com/davidoram/kratos-selfservice-ui-go/api_client"
"github.com/davidoram/kratos-selfservice-ui-go/handlers"
"github.com/davidoram/kratos-selfservice-ui-go/middleware"
"github.com/davidoram/kratos-selfservice-ui-go/options"
"github.com/davidoram/kratos-selfservice-ui-go/session"
"github.com/benbjohnson/hashfs"
kratos "github.com/ory/kratos-client-go"
gh "github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
)
// staticFS holds the static files, CSS images etc.
// Its baked into the application executable using the embed API - see https://golang.org/pkg/embed/
//go:embed static
var staticFS embed.FS
func main() {
opt := options.NewOptions().SetFromCommandLine()
if err := opt.Validate(); err != nil {
log.Fatalf("Error parsing command line: %v", err)
}
log.Printf("KratosAdminURL: %s", opt.KratosAdminURL.String())
log.Printf("KratosPublicURL: %s", opt.KratosPublicURL.String())
log.Printf("KratosBrowserURL: %s", opt.KratosBrowserURL.String())
log.Printf("BaseURL: %s", opt.BaseURL.String())
log.Printf("Address: %s", opt.Address())
log.Printf("Port: %v", opt.Port)
log.Printf("Number of Cookie store keys: %d", len(opt.CookieStoreKeyPairs))
// Init API clients
if _, err := api_client.InitPublicClient(opt); err != nil {
log.Fatalf("Error initializing public API client failed with error: %v", err)
}
if _, err := api_client.InitAdminClient(opt); err != nil {
log.Fatalf("Error initializing admin API client failed with error: %v", err)
}
// Setup sesssion store in cookies
var store = sessions.NewCookieStore(opt.CookieStoreKeyPairs...)
// Register kratos session type with gob
gob.Register(kratos.Session{})
gob.Register(make(map[string]interface{}))
// Create router
r := mux.NewRouter()
// Static assets are wrapped in a hash fs that allows for aggesive http caching
var fsys = hashfs.NewFS(staticFS)
r.PathPrefix("/static/").Handler(hashfs.FileServer(fsys))
// Public Routes
r.Use(gh.RecoveryHandler(gh.PrintRecoveryStack(true)), middleware.NoCacheMiddleware)
// Health/readiness probe endpoints
r.HandleFunc("/health/alive", handlers.Health)
r.HandleFunc("/health/ready", handlers.Health)
// Redirect from / to /welcome
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/welcome", http.StatusMovedPermanently)
})
// Login page
loginP := handlers.LoginParams{
FlowRedirectURL: opt.LoginFlowURL(),
RegistrationURL: opt.RegistrationURL(),
FS: fsys,
}
r.HandleFunc("/login", loginP.Login).Name("login")
// Registration page
regP := handlers.RegistrationParams{
FlowRedirectURL: opt.RegistrationURL(),
LoginURL: opt.LoginURL(),
FS: fsys,
}
r.HandleFunc("/registration", regP.Registration)
// Verification page
verificationP := handlers.VerificationParams{
FlowRedirectURL: opt.VerificationURL(),
FS: fsys,
}
r.HandleFunc("/verification", verificationP.Verification)
// Recovery page
recoverP := handlers.RecoveryParams{
FlowRedirectURL: opt.RecoveryFlowURL(),
FS: fsys,
}
r.HandleFunc("/recovery", recoverP.Recovery)
// Error page
errorP := handlers.KratosErrorParams{
RedirectURL: opt.GetBaseURL(),
HomeURL: opt.GetBaseURL(),
FS: fsys,
}
r.HandleFunc("/error", errorP.Error)
// 404 route
pageNotFoundP := handlers.PageNotFoundParams{
HomeURL: opt.GetBaseURL(),
FS: fsys,
}
r.NotFoundHandler = http.HandlerFunc(pageNotFoundP.PageNotFound)
// Routes with authentication middleware
authP := middleware.KratosAuthParams{
SessionStore: session.SessionStore{Store: store},
RedirectUnauthURL: MustURL(r.Get("login")).String(),
Redirect2FA: opt.TwoFAURL(),
}
// Welcome page (authentication optional)
welcomeP := handlers.WelcomeParams{
SessionStore: session.SessionStore{Store: store},
FS: fsys,
}
r.Handle("/welcome", Middleware(
http.HandlerFunc(welcomeP.Welcome),
authP.SetSession,
))
// Settings page (authentication required)
settingsP := handlers.SettingsParams{
FlowRedirectURL: opt.SettingsURL(),
FS: fsys,
}
r.Handle("/settings", Middleware(
http.HandlerFunc(settingsP.Settings),
authP.KratoAuthMiddleware,
))
// Wrap everything in a logger
logR := gh.LoggingHandler(os.Stdout, r)
// Start server
srv := &http.Server{
Addr: opt.Address(),
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: logR, // Pass our instance of gorilla/mux in.
}
// Run our server in a goroutine so that it doesn't block.
go func() {
if opt.TLSCertPath != "" {
log.Printf("Serving TLS")
if err := srv.ListenAndServeTLS(opt.TLSCertPath, opt.TLSKeyPath); err != nil {
log.Println(err)
}
} else {
log.Printf("Serving")
if err := srv.ListenAndServe(); err != nil {
log.Println(err)
}
}
}()
c := make(chan os.Signal, 1)
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
signal.Notify(c, os.Interrupt)
// Block until we receive our signal.
<-c
// Create a deadline to wait for.
ctx, cancel := context.WithTimeout(context.Background(), opt.ShutdownWait)
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
srv.Shutdown(ctx)
// Optionally, you could run srv.Shutdown in a goroutine and block on
// <-ctx.Done() if your application should wait for other services
// to finalize based on context cancellation.
log.Println("shutting down")
os.Exit(0)
}
// MustURL returns a 'named' URL or panics
func MustURL(r *mux.Route, pairs ...string) *url.URL {
url, err := r.URL(pairs...)
if err != nil {
log.Fatalf("Error r.URL failed with error: %v", err)
}
return url
}
// Middleware (this function) makes adding more than one layer of middleware easy
// by specifying them as a list. It will run the last specified handler first.
func Middleware(h http.Handler, middleware ...func(http.Handler) http.Handler) http.Handler {
for _, mw := range middleware {
h = mw(h)
}
return h
}