server is launchable and passkey support works
This commit is contained in:
Melody Becker 2024-09-27 16:53:22 +02:00
parent ee172d84a8
commit c572066571
21 changed files with 857 additions and 40 deletions

1
server/auth.go Normal file
View file

@ -0,0 +1 @@
package server

53
server/middlewares.go Normal file
View file

@ -0,0 +1,53 @@
package server
import (
"context"
"net/http"
"slices"
"time"
"github.com/rs/zerolog/hlog"
"github.com/rs/zerolog/log"
)
type HandlerBuilder func(http.Handler) http.Handler
func ChainMiddlewares(base http.Handler, links ...HandlerBuilder) http.Handler {
slices.Reverse(links)
for _, f := range links {
base = f(base)
}
return base
}
func ContextValsMiddleware(pairs map[any]any) HandlerBuilder {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
for key, val := range pairs {
ctx = context.WithValue(ctx, key, val)
}
newRequest := r.WithContext(ctx)
h.ServeHTTP(w, newRequest)
})
}
}
func LoggingMiddleware(handler http.Handler) http.Handler {
return ChainMiddlewares(handler,
hlog.NewHandler(log.Logger),
hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {
hlog.FromRequest(r).Info().
Str("method", r.Method).
Stringer("url", r.URL).
Int("status", status).
Int("size", size).
Dur("duration", duration).
Send()
}),
hlog.RemoteAddrHandler("ip"),
hlog.UserAgentHandler("user_agent"),
hlog.RefererHandler("referer"),
hlog.RequestIDHandler("req_id", "Request-Id"),
)
}

41
server/server.go Normal file
View file

@ -0,0 +1,41 @@
package server
import (
"fmt"
"io/fs"
"net/http"
"github.com/mstarongithub/passkey"
"github.com/rs/zerolog/log"
"gitlab.com/mstarongitlab/linstrom/storage"
)
type Server struct {
store *storage.Storage
router http.Handler
}
func NewServer(store *storage.Storage, pkey *passkey.Passkey, reactiveFS, staticFS fs.FS) *Server {
handler := buildRootHandler(pkey, reactiveFS, staticFS)
handler = ChainMiddlewares(handler, LoggingMiddleware, ContextValsMiddleware(map[any]any{}))
return &Server{
store: store,
router: handler,
}
}
func buildRootHandler(pkey *passkey.Passkey, reactiveFS, staticFS fs.FS) http.Handler {
mux := http.NewServeMux()
pkey.MountRoutes(mux, "/webauthn/")
mux.Handle("/", http.FileServerFS(reactiveFS))
mux.Handle("/nojs/", http.StripPrefix("/nojs", http.FileServerFS(staticFS)))
mux.Handle("/pk/", http.StripPrefix("/pk", http.FileServer(http.Dir("pk-auth"))))
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, true) })
return mux
}
func (s *Server) Start(addr string) {
log.Info().Str("addr", addr).Msg("Starting server")
http.ListenAndServe(addr, s.router)
}