Files

35 lines
1.2 KiB
Go
Raw Permalink Normal View History

package auth
import (
"encoding/json"
"net/http"
"github.com/go-chi/chi/v5"
)
// MountAccountRoutes mounts the signed-in account routes onto r: the TOTP enrollment and
// verification routes, which require a session, and GET /profile, which reports the session's
// user or null. A project that signs users in through AuthGuard mounts these alongside its own
// routes.
func (s *Service) MountAccountRoutes(r chi.Router) {
r.With(s.Require).Get("/security/totp/status", s.TOTPStatus)
r.With(s.Require).Get("/security/totp/initiate", s.TOTPInitiate)
r.With(s.Require).Post("/security/totp/verify", s.TOTPVerify)
r.With(s.Require).Post("/security/totp/disable", s.TOTPDisable)
r.With(s.Optional).Get("/profile", profile)
}
func profile(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil {
writeAccountJSON(w, http.StatusOK, map[string]any{"user": nil})
return
}
writeAccountJSON(w, http.StatusOK, map[string]any{"user": user})
}
func writeAccountJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}