linstrom/server/server.go
mStar 1bb6cd8a70 bleh
More API stuff. Lots of bleh. Really boring

Also need to figure out a somewhat generic way for "requires ownership"
permission and then a combinator for permissions
2024-11-04 16:25:39 +01:00

76 lines
1.9 KiB
Go

package server
import (
"io/fs"
"net/http"
"github.com/mstarongithub/passkey"
"github.com/rs/zerolog/log"
"gitlab.com/mstarongitlab/goutils/other"
"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{
ContextKeyStorage: store,
}))
return &Server{
store: store,
router: handler,
}
}
func buildRootHandler(pkey *passkey.Passkey, reactiveFS, staticFS fs.FS) http.Handler {
mux := http.NewServeMux()
mux.Handle(
"/webauthn/",
http.StripPrefix(
"/webauthn",
forceCorrectPasskeyAuthFlowMiddleware(buildPasskeyAuthRouter(pkey)),
),
)
mux.Handle("/", setupFrontendRouter(reactiveFS, staticFS))
mux.Handle("/pk/", http.StripPrefix("/pk", http.FileServer(http.Dir("pk-auth"))))
mux.HandleFunc("/alive", isAliveHandler)
mux.Handle("/api/", http.StripPrefix("/api", checkSessionMiddleware(setupApiRouter())))
mux.Handle(
"/profiling/",
http.StripPrefix("/profiling", profilingAuthenticationMiddleware(setupProfilingHandler())),
)
// temporary until proper route structure exists
mux.Handle(
"/authonly/",
pkey.Auth(
ContextKeyPasskeyUsername,
nil,
func(w http.ResponseWriter, r *http.Request) {
other.HttpErr(
w,
HttpErrIdNotAuthenticated,
"Not authenticated",
http.StatusUnauthorized,
)
},
)(ChainMiddlewares(setupTestEndpoints(), passkeyIdToAccountIdTransformerMiddleware)),
)
return mux
}
func buildPasskeyAuthRouter(pkey *passkey.Passkey) http.Handler {
router := http.NewServeMux()
pkey.MountRoutes(router, "/")
return router
}
func (s *Server) Start(addr string) error {
log.Info().Str("addr", addr).Msg("Starting server")
return http.ListenAndServe(addr, s.router)
}