2026-08-03 18:07:40 +02:00
package main
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"net/http"
2026-08-05 14:58:07 +02:00
"strconv"
2026-08-03 18:07:40 +02:00
"strings"
2026-08-06 09:44:57 +02:00
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
2026-09-01 01:34:48 +02:00
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
2026-09-03 08:24:06 +02:00
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
2026-08-03 18:07:40 +02:00
)
2026-09-01 01:34:48 +02:00
// AuthGuard migration
// ====================
//
// CollabTable used to be a fully self-contained, multi-user auth
// implementation: account and session state lived in this service's own
// PostgreSQL `auth_users`/`auth_sessions` tables (see db.go's schema, which
// is kept but no longer used for this -- see initSchema's doc comment).
// Unlike GameStream (a single-admin tool this migration was first proven
// against), CollabTable is a real multi-user collaboration app: it already
// had full admin user management (list/create/edit/delete other accounts,
// assign roles) before this migration, not just a single local admin
// account. That feature maps directly onto AuthGuard's own
// /api/admin/users endpoints (see AuthGuard/README.md), which enforce the
// exact same rules CollabTable's local implementation did (protected
// superadmin, no self-delete, role-reassignment restricted to superadmin
// actors) -- so handleUsers/handleUser below simply proxy and trust
// AuthGuard's authorization instead of re-checking those rules locally.
//
// It now proxies every browser-session auth operation to AuthGuard
// (Web/Central/AuthGuard), a centralized identity service other projects
// share, via the `authclient` package (Web/Central/shared/backend/
// authclient, vendored here at shared/backend/authclient). CollabTable's own
// /api/auth/... URL paths and JSON response shapes are UNCHANGED -- the
// frontend was not touched -- only what backs them changed.
//
// One CollabTable feature this migration deliberately leaves alone: the
// long-lived per-account API bearer token used by a user's own devices to
// call the sync API (requireAPIToken below, and handleTokenStatus/
// handleTokenRegenerate). That token is a device-pairing credential, not a
// browser session, and AuthGuard has no equivalent concept -- it stays
// entirely local, keyed by whatever numeric id currentUserID resolves to
// (an AuthGuard account id, or the fixed placeholder id when auth is
// disabled; see "Auth-disabled mode" below). Its api_tokens table no longer
// foreign-keys into auth_users; see db.go's comment on that table.
//
// Session cookie / token model
// -----------------------------
// AuthGuard sets its own `auth_session` cookie (authclient.DefaultCookieName)
// on register/login, whose scope (host-only, or a shared parent domain for
// real cross-project SSO) is entirely controlled by AuthGuard's own
// AUTH_COOKIE_DOMAIN setting -- CollabTable has no opinion on it. Rather
// than inventing a second cookie and a mapping between "CollabTable's
// session token" and "AuthGuard's session token", CollabTable forwards
// AuthGuard's Set-Cookie header straight through to the browser on
// register/login/logout (authclient.ForwardCookies), and reads that same
// `auth_session` cookie back off every incoming request to use as the
// bearer token on its server-to-server calls to AuthGuard (sessionToken/
// currentUser below). CollabTable mints no session token of its own at all,
// which is both less code and automatically correct under whatever
// cookie-domain SSO topology AuthGuard is configured with. The frontend
// requires no changes for this -- it never reads the cookie's name or value
// itself, only relies on the browser sending it back.
//
// The pre-migration `collabtable_session` cookie name is retained only as
// something logout additionally clears, so a browser that still holds one
// from before this migration doesn't keep sending a now-meaningless cookie
// forever.
//
// Setup flow
// ----------
// CollabTable's "first launch: create the first (superadmin) account" flow
// doesn't map onto AuthGuard, which is not scoped to a single project and
2026-09-02 10:32:55 +02:00
// has no concept of "this is CollabTable's initial account". CollabTable
2026-09-01 01:34:48 +02:00
// keeps a tiny local flag of its own -- collabtable_setup_state.claimed
// (db.go) -- that means only "has this CollabTable instance completed its
// setup screen once", with no credentials of any kind in it. handleSetup
// atomically claims that flag, registers the account against AuthGuard's
// POST /api/register, and unclaims it again if registration fails (so a bad
2026-09-02 10:32:55 +02:00
// attempt doesn't permanently lock out setup).
//
// The local claim alone would still show this "create account" form to a
// second, third, ... CollabTable instance's own first launch even though
// AuthGuard already has an account from the first one (or from AuthGuard's
// own web UI), since accounts are centralized -- there is no per-instance
// "initial account" once AuthGuard is shared. handleStatus and handleSetup
// both additionally call AuthGuard's GET /api/setup-status
// (authclient.Client.SetupStatus) and treat "AuthGuard already has an
// account" the same as "CollabTable's own setup is already claimed": show
// the login screen, refuse another registration through this flow.
2026-09-01 01:34:48 +02:00
//
// Known gaps versus the pre-migration behavior (AuthGuard was deliberately
// not modified for this migration, so these can only be closed by adding to
// AuthGuard itself later):
// - Self-service profile editing (POST /api/auth/credentials) needs
// AuthGuard's admin/users endpoint, which requires CanManageUsers. A
// plain "user"-role account (not admin/superadmin) has no self-service
// way to change its own username/email/password via AuthGuard today; see
// handleUpdateCredentials. This is a real regression for CollabTable
// specifically (a genuinely multi-user app): a plain collaborator who
// could previously edit their own profile now cannot, until AuthGuard
// grows a true self-service endpoint.
// - AuthGuard has no "is TOTP enabled" read endpoint, only
// enable/verify/disable, so handleTOTPStatus answers from a local
// best-effort cache instead of AuthGuard directly; see its doc comment.
// - The admin user list (GET /api/auth/users) similarly can't ask AuthGuard
// for other accounts' TOTP status, so TotpEnabled on entries other than
// the cache's own observations defaults to false.
// - The TOTP setup QR code's issuer name now comes from AuthGuard's own
// otpauth:// URI rather than being branded "CollabTable" locally, since
// AuthGuard (not CollabTable) generates the secret/URI now.
// - Changing a user's own credentials used to invalidate every session for
// that account (deleteSessionsForUser). AuthGuard has no bulk
// "invalidate every session for this account" call, only single-session
// Logout, so only the session used for the credentials request itself is
// guaranteed revoked; see handleUpdateCredentials.
//
// Auth-disabled mode (AUTHGUARD_URL unset)
// -----------------------------------------
// AUTHGUARD_URL is optional. When it is unset, AuthService.authGuard is nil
// (AuthService.enabled() reports false) and CollabTable runs with
// authentication turned off entirely: every request is treated as already
// authenticated, with no login screen and nothing gated -- this is an
// explicit mode for local development or a standalone deployment that
// doesn't want centralized identity, not an error condition (unlike the
// pre-migration local-Postgres-auth design this replaced, there is no
// degraded/partial fallback state; it is either "AuthGuard" or "no auth" and
// never silently "local auth").
//
// requireSession (gating logout/credentials/users/totp/token/tech-stack/web
// data) simply calls through to next without resolving a session at all in
// this mode. handleStatus/handleSetup/handleLogin each special-case this and
// return a fixed placeholder "authenticated" identity (localProfile) without
// ever touching AuthGuard or the local setup-claim flag, so the frontend
// never shows a login or setup screen. handleLogout is a no-op success.
//
// Features that need a *real* backing identity rather than just an access
// gate -- TOTP (setup/enable/disable; handleTOTPStatus alone still answers
// {enabled: false}), self-service profile editing, and admin user
// management's mutating calls -- have nothing meaningful to do without
// AuthGuard (there is no account to attach a TOTP secret to, no profile to
// edit, no user store to create/update/delete against) and return a clear
// errFeatureRequiresAuthGuard error instead of silently no-opping or faking
// data. GET /api/auth/users is the one exception: consistent with "nothing
// gated", it returns an empty list rather than an error, since listing
// (unlike mutating) has an honest, unsurprising answer when there is no user
// store: there are no managed users to show.
//
// The device-sync API token (handleTokenStatus/handleTokenRegenerate) is
// different from the features above: it has nothing to do with AuthGuard
// accounts even when AuthGuard IS configured (see the top of this comment),
// so it keeps working in disabled mode too, scoped to the fixed placeholder
// identity every request shares -- a real, functional token, not faked data;
// see currentUserID.
2026-08-03 18:07:40 +02:00
const (
2026-09-01 01:34:48 +02:00
// legacySessionCookieName is the cookie CollabTable itself used to mint
// and read before the AuthGuard migration. Nothing sets it anymore; it is
// only referenced so logout can clear a stale copy left over in a browser
// from before the migration.
legacySessionCookieName = "collabtable_session"
2026-08-03 18:07:40 +02:00
minPasswordLength = 8
maxUsernameLength = 64
2026-08-03 20:31:32 +02:00
maxEmailLength = 254
2026-08-03 18:07:40 +02:00
)
var (
errAuthRequired = errors . New ( "Authentication required" )
errSetupComplete = errors . New ( "Setup has already been completed." )
errInvalidCredentials = errors . New ( "Invalid username or password." )
errUsernameRequired = errors . New ( "Username is required." )
2026-08-03 20:31:32 +02:00
errEmailRequired = errors . New ( "Email is required and must be valid." )
2026-08-03 18:07:40 +02:00
errPasswordTooShort = errors . New ( "Password must be at least 8 characters." )
2026-09-01 01:34:48 +02:00
errInvalidAuthInput = errors . New ( "invalid authentication input" )
errSelfServiceProfile = errors . New ( "Self-service profile editing is only available to administrator accounts; ask an administrator to update this account." )
// errFeatureRequiresAuthGuard is returned by the handlers that need a real
// backing identity (not just an access gate) when AUTHGUARD_URL is unset;
// see the top-of-file doc comment's "Auth-disabled mode" section.
errFeatureRequiresAuthGuard = errors . New ( "This feature requires AUTHGUARD_URL to be configured." )
// errAuthGuardUnavailable is returned whenever currentUser/currentProfile
// propagate a non-nil error: by construction (see their doc comments)
// that only happens when AuthGuard could not be reached or gave an
// unusable response -- a real "invalid or expired session" is always
// resolved to (nil, nil) instead, never an error -- so every caller of
// these two can safely report this same, specific message rather than a
// generic "internal error" that would be indistinguishable from any
// other server bug. This matters most for handleStatus/requireSession:
// AUTHGUARD_URL being configured but unreachable must surface as a
// visible, distinct error in the UI rather than ever being confused with
// "please log in" or silently letting the request through unauthenticated.
errAuthGuardUnavailable = errors . New ( "Unable to reach the authentication service. Please try again shortly." )
2026-08-03 18:07:40 +02:00
)
2026-09-01 01:34:48 +02:00
// localProfile is the fixed placeholder identity handleStatus/handleSetup/
// handleLogin report when auth is disabled (AUTHGUARD_URL unset). Role is
// superadmin so CanManageUsers reports true, consistent with "nothing
// gated": the frontend's own admin-only UI sections become visible too, even
// though the underlying admin endpoints have nothing to manage (see
// handleUsers/handleUser). Its ID (0) also doubles as the shared identity
// every request's device-sync API token is scoped to in this mode; see
// currentUserID.
var localProfile = authclient . PublicUser { ID : 0 , Username : "local" , Email : "" , Role : string ( sharedauth . RoleSuperAdmin )}
// AuthService proxies CollabTable's existing /api/auth/... handlers to
// AuthGuard. See this file's top-of-file doc comment for the overall design.
2026-08-03 18:07:40 +02:00
type AuthService struct {
db * DB
2026-09-01 01:34:48 +02:00
authGuard * authclient . Client
2026-08-03 18:07:40 +02:00
secureCookie bool
}
2026-09-01 01:34:48 +02:00
func newAuthService ( authGuard * authclient . Client , db * DB , secureCookie bool ) * AuthService {
2026-09-02 08:51:22 +02:00
return & AuthService { db : db , authGuard : authGuard , secureCookie : secureCookie }
2026-08-03 18:07:40 +02:00
}
func normalizeUsername ( value string ) ( string , error ) {
2026-09-03 08:24:06 +02:00
normalized , ok := authproxy . NormalizeUsername ( value , maxUsernameLength )
if ! ok {
2026-08-03 18:07:40 +02:00
return "" , errUsernameRequired
}
2026-09-03 08:24:06 +02:00
return normalized , nil
2026-08-03 18:07:40 +02:00
}
2026-08-03 20:31:32 +02:00
func normalizeEmail ( value string ) ( string , error ) {
2026-09-03 08:24:06 +02:00
normalized , ok := authproxy . NormalizeEmail ( value , maxEmailLength )
if ! ok {
2026-08-03 20:31:32 +02:00
return "" , errEmailRequired
}
2026-09-03 08:24:06 +02:00
return normalized , nil
2026-08-03 20:31:32 +02:00
}
2026-08-03 18:07:40 +02:00
func validatePassword ( value string ) error {
2026-09-03 08:24:06 +02:00
if ! authproxy . ValidPassword ( value , minPasswordLength ) {
2026-08-03 18:07:40 +02:00
return errPasswordTooShort
}
return nil
}
func randomToken () ( string , error ) {
buffer := make ([] byte , 32 )
if _ , err := rand . Read ( buffer ); err != nil {
return "" , err
}
return base64 . RawURLEncoding . EncodeToString ( buffer ), nil
}
func hashToken ( token string ) string {
sum := sha256 . Sum256 ([] byte ( token ))
return hex . EncodeToString ( sum [:])
}
2026-09-01 01:34:48 +02:00
// enabled reports whether AUTHGUARD_URL was configured. See the top-of-file
// doc comment's "Auth-disabled mode" section.
func ( a * AuthService ) enabled () bool {
return a . authGuard != nil
2026-08-03 18:07:40 +02:00
}
2026-09-01 01:34:48 +02:00
// sessionToken reads the AuthGuard session cookie off the incoming request.
// See the top-of-file doc comment's "Session cookie / token model" section.
func ( a * AuthService ) sessionToken ( r * http . Request ) string {
2026-09-03 08:24:06 +02:00
return authproxy . SessionToken ( r )
2026-09-01 01:34:48 +02:00
}
// clearSessionCookies clears both the AuthGuard cookie (as a fallback --
// normally AuthGuard's own Set-Cookie, forwarded via authclient.ForwardCookies,
// already does this) and the pre-migration CollabTable cookie name.
func ( a * AuthService ) clearSessionCookies ( w http . ResponseWriter ) {
2026-09-03 08:24:06 +02:00
authproxy . ClearSessionCookies ( w , legacySessionCookieName , a . secureCookie )
2026-09-01 01:34:48 +02:00
}
// currentUser resolves the request's AuthGuard session cookie via the
// lightweight GET /api/session/validate call, or nil if the request is
// unauthenticated or the session is invalid/expired. This is intentionally
// the cheap check (no email, no role-derived fields) -- it's what gates
// every request through requireSession.
func ( a * AuthService ) currentUser ( r * http . Request ) ( * authclient . User , error ) {
token := a . sessionToken ( r )
if token == "" {
2026-08-03 18:07:40 +02:00
return nil , nil
}
2026-09-01 01:34:48 +02:00
user , err := a . authGuard . Validate ( r . Context (), token )
if err != nil {
if errors . Is ( err , authclient . ErrInvalidSession ) {
return nil , nil
}
return nil , err
}
return user , nil
2026-08-03 18:07:40 +02:00
}
2026-09-01 01:34:48 +02:00
// currentProfile resolves the full account profile (email included) via
// AuthGuard's GET /api/me, for handlers that need more than currentUser's
// slim shape, alongside the session token itself (so the caller can make a
// further authenticated call to AuthGuard without re-reading the cookie).
func ( a * AuthService ) currentProfile ( r * http . Request ) ( * authclient . PublicUser , string , error ) {
token := a . sessionToken ( r )
if token == "" {
return nil , "" , nil
}
user , err := a . authGuard . Me ( r . Context (), token )
if err != nil {
var apiErr * authclient . APIError
if errors . As ( err , & apiErr ) && apiErr . StatusCode == http . StatusUnauthorized {
return nil , "" , nil
}
return nil , "" , err
}
return user , token , nil
}
// currentUserID resolves the caller's identity to a stable numeric id for
// purely-local, identity-keyed state that has nothing to do with AuthGuard's
// own account data -- currently just the device-sync API token (see
// handleTokenStatus/handleTokenRegenerate). When auth is disabled this is
// the fixed localProfile.ID (0): every request shares the same "local"
// identity, so a device-sync token minted in this mode is real and
// functional, just scoped to that one shared identity rather than a
// per-account AuthGuard identity. ok is false when auth is enabled but the
// caller has no valid session.
func ( a * AuthService ) currentUserID ( r * http . Request ) ( id int64 , ok bool , err error ) {
if ! a . enabled () {
return localProfile . ID , true , nil
}
user , err := a . currentUser ( r )
if err != nil {
return 0 , false , err
}
if user == nil {
return 0 , false , nil
}
return user . ID , true , nil
}
func ( a * AuthService ) requireSession ( next http . Handler ) http . Handler {
2026-08-03 18:07:40 +02:00
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
2026-09-01 01:34:48 +02:00
if ! a . enabled () {
next . ServeHTTP ( w , r )
return
}
2026-08-03 18:07:40 +02:00
user , err := a . currentUser ( r )
if err != nil {
2026-09-01 01:34:48 +02:00
writeJSONError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
2026-08-03 18:07:40 +02:00
return
}
if user == nil {
writeJSONError ( w , http . StatusUnauthorized , errAuthRequired . Error ())
return
}
2026-09-01 01:34:48 +02:00
next . ServeHTTP ( w , r )
2026-08-03 18:07:40 +02:00
})
}
func ( a * AuthService ) requireAPIToken ( next http . Handler ) http . Handler {
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
token := extractBearer ( r )
if token == "" {
writeJSONError ( w , http . StatusUnauthorized , "No bearer token provided" )
return
}
userID , err := a . db . getAPITokenUserID ( r . Context (), hashToken ( token ))
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
return
}
if userID == 0 {
writeJSONError ( w , http . StatusUnauthorized , "Invalid API token" )
return
}
next . ServeHTTP ( w , r )
})
}
func extractBearer ( r * http . Request ) string {
header := r . Header . Get ( "Authorization" )
if ! strings . HasPrefix ( header , "Bearer " ) {
return ""
}
return strings . TrimSpace ( strings . TrimPrefix ( header , "Bearer " ))
}
type authStatusResponse struct {
2026-08-05 14:58:07 +02:00
SetupRequired bool `json:"setupRequired"`
Authenticated bool `json:"authenticated"`
ID int64 `json:"id,omitempty"`
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
Role string `json:"role,omitempty"`
CanManageUsers bool `json:"canManageUsers,omitempty"`
TotpEnabled bool `json:"totpEnabled,omitempty"`
2026-08-03 18:07:40 +02:00
}
type credentialsRequest struct {
2026-08-03 20:31:32 +02:00
Identifier string `json:"identifier"`
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
2026-08-05 14:58:07 +02:00
TotpToken string `json:"totpToken"`
2026-08-03 18:07:40 +02:00
}
2026-09-01 01:34:48 +02:00
func ( a * AuthService ) statusResponse ( ctx context . Context , user authclient . PublicUser ) authStatusResponse {
totpEnabled , err := a . db . GetCachedTOTPEnabled ( ctx , user . ID )
if err != nil {
// Best-effort cache; a read failure just means "assume disabled" rather
// than failing the whole status/login/setup response.
totpEnabled = false
}
return authStatusResponse {
Authenticated : true ,
ID : user . ID ,
Username : user . Username ,
Email : user . Email ,
Role : user . Role ,
CanManageUsers : sharedauth . CanManageUsers ( user . Role ),
TotpEnabled : totpEnabled ,
}
}
2026-08-03 18:07:40 +02:00
func ( a * AuthService ) handleStatus ( w http . ResponseWriter , r * http . Request ) {
2026-09-01 01:34:48 +02:00
if ! a . enabled () {
writeJSON ( w , http . StatusOK , a . statusResponse ( r . Context (), localProfile ))
return
}
claimed , err := a . db . IsSetupClaimed ( r . Context ())
2026-08-03 18:07:40 +02:00
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
return
}
2026-09-01 01:34:48 +02:00
if ! claimed {
2026-09-02 10:32:55 +02:00
// The local claim alone isn't enough to decide this: accounts are
// centralized in AuthGuard now, so another CollabTable instance (or
// AuthGuard's own web UI) may have already created one even though
// this instance's own setup was never claimed. Showing the "create
// your account" form in that case would let someone spin up a
// redundant plain user instead of just logging into the account that
// already exists -- see setupRequired below.
setupRequired , err := a . authGuard . SetupStatus ( r . Context ())
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
return
}
if setupRequired {
writeJSON ( w , http . StatusOK , authStatusResponse { SetupRequired : true })
return
}
// AuthGuard already has an account; fall through to the ordinary
// "not authenticated" response so the frontend shows the login form
// instead of setup.
2026-08-03 18:07:40 +02:00
}
2026-09-01 01:34:48 +02:00
profile , _ , err := a . currentProfile ( r )
2026-08-03 18:07:40 +02:00
if err != nil {
2026-09-01 01:34:48 +02:00
// Reachable-but-invalid-session already resolved to (nil, "", nil)
// inside currentProfile; getting here means AuthGuard itself could not
// be reached or gave an unusable response. This must never be
// conflated with "not authenticated" (which would incorrectly show the
// frontend's login screen with no indication anything is wrong) or
// silently proceed as authenticated -- see errAuthGuardUnavailable.
writeJSONError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
2026-08-03 18:07:40 +02:00
return
}
2026-09-01 01:34:48 +02:00
if profile == nil {
2026-08-03 18:07:40 +02:00
writeJSON ( w , http . StatusOK , authStatusResponse {})
return
}
2026-09-01 01:34:48 +02:00
writeJSON ( w , http . StatusOK , a . statusResponse ( r . Context (), * profile ))
2026-08-05 14:58:07 +02:00
}
2026-09-01 01:34:48 +02:00
// handleSetup registers CollabTable's first account against AuthGuard's
// POST /api/register. See the top-of-file doc comment's "Setup flow" section
// for why this needs a small local claim flag instead of a count-based
// check.
2026-08-03 18:07:40 +02:00
func ( a * AuthService ) handleSetup ( w http . ResponseWriter , r * http . Request ) {
2026-09-01 01:34:48 +02:00
if ! a . enabled () {
writeJSON ( w , http . StatusOK , a . statusResponse ( r . Context (), localProfile ))
return
}
2026-08-03 18:07:40 +02:00
var request credentialsRequest
if err := decodeJSON ( r , & request ); err != nil {
writeJSONError ( w , http . StatusBadRequest , "Invalid JSON body" )
return
}
username , err := normalizeUsername ( request . Username )
if err != nil {
writeJSONError ( w , http . StatusBadRequest , err . Error ())
return
}
2026-08-03 20:31:32 +02:00
email , err := normalizeEmail ( request . Email )
if err != nil {
writeJSONError ( w , http . StatusBadRequest , err . Error ())
return
}
2026-08-03 18:07:40 +02:00
if err := validatePassword ( request . Password ); err != nil {
writeJSONError ( w , http . StatusBadRequest , err . Error ())
return
}
2026-09-01 01:34:48 +02:00
claimed , err := a . db . TryClaimSetup ( r . Context ())
2026-08-03 18:07:40 +02:00
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
return
}
2026-09-01 01:34:48 +02:00
if ! claimed {
writeJSONError ( w , http . StatusConflict , errSetupComplete . Error ())
return
}
2026-09-02 10:32:55 +02:00
// Belt-and-braces: handleStatus already keeps the frontend from ever
// showing this form once AuthGuard has any account (see its own
// SetupStatus check), but a stale page or a direct API call could still
// reach this handler. Reject it the same way as the local claim conflict
// above rather than creating a redundant plain user account.
if setupRequired , err := a . authGuard . SetupStatus ( r . Context ()); err != nil || ! setupRequired {
if unclaimErr := a . db . UnclaimSetup ( r . Context ()); unclaimErr != nil {
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
return
}
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
return
}
writeJSONError ( w , http . StatusConflict , errSetupComplete . Error ())
return
}
2026-09-01 01:34:48 +02:00
result , err := a . authGuard . Register ( r . Context (), username , email , request . Password )
2026-08-03 18:07:40 +02:00
if err != nil {
2026-09-01 01:34:48 +02:00
// The claim slot is only valid once actually backed by a real
// AuthGuard account; reopen it so a corrected retry can proceed.
if unclaimErr := a . db . UnclaimSetup ( r . Context ()); unclaimErr != nil {
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
2026-08-03 18:07:40 +02:00
return
}
2026-09-01 01:34:48 +02:00
writeAuthGuardError ( w , err , "Unable to create account" )
return
}
if err := a . db . SetCachedTOTPEnabled ( r . Context (), result . User . ID , false ); err != nil {
2026-08-03 18:07:40 +02:00
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
return
}
2026-09-01 01:34:48 +02:00
authclient . ForwardCookies ( w , result . Cookies )
writeJSON ( w , http . StatusOK , a . statusResponse ( r . Context (), result . User ))
2026-08-03 18:07:40 +02:00
}
func ( a * AuthService ) handleLogin ( w http . ResponseWriter , r * http . Request ) {
2026-09-01 01:34:48 +02:00
if ! a . enabled () {
writeJSON ( w , http . StatusOK , a . statusResponse ( r . Context (), localProfile ))
return
}
2026-08-03 18:07:40 +02:00
var request credentialsRequest
if err := decodeJSON ( r , & request ); err != nil {
writeJSONError ( w , http . StatusBadRequest , "Invalid JSON body" )
return
}
2026-08-03 20:31:32 +02:00
identifier := strings . TrimSpace ( request . Identifier )
if identifier == "" {
identifier = strings . TrimSpace ( request . Username )
}
2026-09-01 01:34:48 +02:00
if identifier == "" || len ([] rune ( identifier )) > maxEmailLength {
2026-08-03 18:07:40 +02:00
writeJSONError ( w , http . StatusUnauthorized , errInvalidCredentials . Error ())
return
}
2026-09-01 01:34:48 +02:00
result , err := a . authGuard . Login ( r . Context (), identifier , request . Password , request . TotpToken )
if err != nil {
var apiErr * authclient . APIError
if errors . As ( err , & apiErr ) {
if apiErr . TOTPRequired {
writeJSONError ( w , http . StatusUnauthorized , "Two-factor authentication code required." )
return
}
if apiErr . StatusCode == http . StatusUnauthorized {
writeJSONError ( w , http . StatusUnauthorized , errInvalidCredentials . Error ())
return
}
writeAuthGuardError ( w , err , "Unable to sign in" )
return
}
// A non-APIError here means the call to AuthGuard itself failed
// (transport/connectivity), as opposed to AuthGuard giving a real
// answer we didn't like above; see errAuthGuardUnavailable.
writeJSONError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
2026-08-03 20:31:32 +02:00
return
}
2026-09-01 01:34:48 +02:00
// See this file's top-of-file doc comment: a successful login attempted
// WITHOUT a TOTP token is only possible when the account does not have
// TOTP enabled (AuthGuard would otherwise have rejected it), so this is an
// authoritative point to refresh the local cache. A successful login WITH
// a token is not equally conclusive (AuthGuard ignores an unnecessary
// token for an account that doesn't have TOTP enabled), so the cache is
// left as whatever handleTOTPEnable/Disable last set it to rather than
// guessed at here.
if strings . TrimSpace ( request . TotpToken ) == "" {
if err := a . db . SetCachedTOTPEnabled ( r . Context (), result . User . ID , false ); err != nil {
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
return
}
}
authclient . ForwardCookies ( w , result . Cookies )
writeJSON ( w , http . StatusOK , a . statusResponse ( r . Context (), result . User ))
}
func ( a * AuthService ) handleTOTPStatus ( w http . ResponseWriter , r * http . Request ) {
if ! a . enabled () {
writeJSON ( w , http . StatusOK , map [ string ] bool { "enabled" : false })
return
}
user , err := a . currentUser ( r )
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
return
}
if user == nil {
writeJSONError ( w , http . StatusUnauthorized , errAuthRequired . Error ())
return
}
enabled , err := a . db . GetCachedTOTPEnabled ( r . Context (), user . ID )
2026-08-03 18:07:40 +02:00
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
return
}
2026-09-01 01:34:48 +02:00
writeJSON ( w , http . StatusOK , map [ string ] bool { "enabled" : enabled })
}
// handleTOTPSetup provisions a pending TOTP secret via AuthGuard's POST
// /api/totp/enable (AuthGuard's "enable" is CollabTable's "setup" step --
// naming differs, the two-step provision-then-confirm flow is identical).
//
// AuthGuard always (re-)provisions regardless of current state; the
// "already enabled" guard CollabTable had locally is reproduced here from
// the local cache to keep the same user-facing contract (the frontend only
// ever shows this action when it believes TOTP is currently off).
func ( a * AuthService ) handleTOTPSetup ( w http . ResponseWriter , r * http . Request ) {
if ! a . enabled () {
writeJSONError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
2026-08-03 18:07:40 +02:00
return
}
2026-09-01 01:34:48 +02:00
user , err := a . currentUser ( r )
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
2026-08-05 14:58:07 +02:00
return
}
2026-09-01 01:34:48 +02:00
if user == nil {
writeJSONError ( w , http . StatusUnauthorized , errAuthRequired . Error ())
return
}
if enabled , err := a . db . GetCachedTOTPEnabled ( r . Context (), user . ID ); err != nil {
2026-08-03 18:07:40 +02:00
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
return
2026-09-01 01:34:48 +02:00
} else if enabled {
2026-08-05 14:58:07 +02:00
writeJSONError ( w , http . StatusConflict , "disable two-factor authentication before setting up a new secret" )
return
}
2026-09-01 01:34:48 +02:00
result , err := a . authGuard . TOTPEnable ( r . Context (), a . sessionToken ( r ))
2026-08-05 14:58:07 +02:00
if err != nil {
2026-09-01 01:34:48 +02:00
writeAuthGuardError ( w , err , "unable to create two-factor setup" )
2026-08-05 14:58:07 +02:00
return
}
writeJSON ( w , http . StatusOK , map [ string ] any {
2026-09-01 01:34:48 +02:00
"secret" : result . Secret ,
"otpauthUrl" : result . OTPAuthURL ,
"enabled" : result . Enabled ,
2026-08-05 14:58:07 +02:00
})
}
2026-09-01 01:34:48 +02:00
// handleTOTPEnable confirms a generated code via AuthGuard's POST
// /api/totp/verify, activating two-factor authentication (AuthGuard's
// "verify" is CollabTable's "enable" step; see handleTOTPSetup).
func ( a * AuthService ) handleTOTPEnable ( w http . ResponseWriter , r * http . Request ) {
if ! a . enabled () {
writeJSONError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
return
}
user , err := a . currentUser ( r )
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
return
}
if user == nil {
writeJSONError ( w , http . StatusUnauthorized , errAuthRequired . Error ())
return
}
var request struct {
Token string `json:"token"`
}
2026-08-05 14:58:07 +02:00
if err := decodeJSON ( r , & request ); err != nil {
writeJSONError ( w , http . StatusBadRequest , "invalid JSON body" )
return
}
2026-09-01 01:34:48 +02:00
if err := a . authGuard . TOTPVerify ( r . Context (), a . sessionToken ( r ), request . Token ); err != nil {
2026-08-25 19:20:18 +00:00
writeJSONError ( w , http . StatusUnauthorized , "Invalid authenticator code." )
2026-08-05 14:58:07 +02:00
return
}
2026-09-01 01:34:48 +02:00
if err := a . db . SetCachedTOTPEnabled ( r . Context (), user . ID , true ); err != nil {
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
2026-08-05 14:58:07 +02:00
return
}
writeJSON ( w , http . StatusOK , map [ string ] bool { "enabled" : true })
}
2026-09-01 01:34:48 +02:00
func ( a * AuthService ) handleTOTPDisable ( w http . ResponseWriter , r * http . Request ) {
if ! a . enabled () {
writeJSONError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
return
}
user , err := a . currentUser ( r )
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
return
}
if user == nil {
writeJSONError ( w , http . StatusUnauthorized , errAuthRequired . Error ())
return
}
var request struct {
Token string `json:"token"`
}
2026-08-05 14:58:07 +02:00
if err := decodeJSON ( r , & request ); err != nil {
writeJSONError ( w , http . StatusBadRequest , "invalid JSON body" )
return
}
2026-09-01 01:34:48 +02:00
if err := a . authGuard . TOTPDisable ( r . Context (), a . sessionToken ( r ), request . Token ); err != nil {
2026-08-25 19:20:18 +00:00
writeJSONError ( w , http . StatusUnauthorized , "Invalid authenticator code." )
2026-08-05 14:58:07 +02:00
return
}
2026-09-01 01:34:48 +02:00
if err := a . db . SetCachedTOTPEnabled ( r . Context (), user . ID , false ); err != nil {
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
2026-08-05 14:58:07 +02:00
return
}
writeJSON ( w , http . StatusOK , map [ string ] bool { "enabled" : false })
2026-08-03 18:07:40 +02:00
}
2026-09-01 01:34:48 +02:00
func ( a * AuthService ) handleLogout ( w http . ResponseWriter , r * http . Request ) {
if ! a . enabled () {
writeJSON ( w , http . StatusOK , map [ string ] bool { "ok" : true })
return
}
if token := a . sessionToken ( r ); token != "" {
cookies , err := a . authGuard . Logout ( r . Context (), token )
if err != nil {
var apiErr * authclient . APIError
if ! errors . As ( err , & apiErr ) {
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
return
}
// An already-invalid/expired session is fine to treat as "already
// logged out" rather than an error.
} else {
authclient . ForwardCookies ( w , cookies )
2026-08-03 18:07:40 +02:00
}
}
2026-09-01 01:34:48 +02:00
a . clearSessionCookies ( w )
2026-08-03 18:07:40 +02:00
writeJSON ( w , http . StatusOK , map [ string ] bool { "ok" : true })
}
type updateCredentialsRequest struct {
2026-08-03 20:31:32 +02:00
CurrentPassword * string `json:"currentPassword"`
2026-08-03 18:07:40 +02:00
NewUsername * string `json:"newUsername"`
2026-08-03 20:31:32 +02:00
NewEmail * string `json:"newEmail"`
2026-08-03 18:07:40 +02:00
NewPassword * string `json:"newPassword"`
}
2026-09-01 01:34:48 +02:00
// handleUpdateCredentials lets the caller edit their own username/email/
// password. See the top-of-file doc comment's "Known gaps" section:
// AuthGuard only exposes account editing through its admin/users endpoint,
// which requires CanManageUsers, so a plain "user"-role account has no
// AuthGuard-backed way to self-edit today. CollabTable's existing frontend
// never sends CurrentPassword (see lib/api.js's updateCredentials), and
// AuthGuard's admin update endpoint has no notion of it either (an
// authorized caller is trusted without re-proving the current password), so
// that field is accepted for backward compatibility but not acted on.
func ( a * AuthService ) handleUpdateCredentials ( w http . ResponseWriter , r * http . Request ) {
if ! a . enabled () {
writeJSONError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
return
}
current , token , err := a . currentProfile ( r )
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
return
}
if current == nil {
writeJSONError ( w , http . StatusUnauthorized , errAuthRequired . Error ())
return
}
2026-08-03 18:07:40 +02:00
var request updateCredentialsRequest
if err := decodeJSON ( r , & request ); err != nil {
writeJSONError ( w , http . StatusBadRequest , "Invalid JSON body" )
return
}
2026-09-01 01:34:48 +02:00
input := authclient . ManagedUserInput {}
2026-08-03 18:07:40 +02:00
if request . NewUsername != nil {
2026-09-01 01:34:48 +02:00
username , err := normalizeUsername ( * request . NewUsername )
2026-08-03 20:31:32 +02:00
if err != nil {
writeJSONError ( w , http . StatusBadRequest , err . Error ())
return
}
2026-09-01 01:34:48 +02:00
input . Username = username
}
if request . NewEmail != nil {
email , err := normalizeEmail ( * request . NewEmail )
if err != nil {
writeJSONError ( w , http . StatusBadRequest , err . Error ())
return
}
input . Email = email
2026-08-03 20:31:32 +02:00
}
2026-08-03 18:07:40 +02:00
if request . NewPassword != nil && * request . NewPassword != "" {
if err := validatePassword ( * request . NewPassword ); err != nil {
writeJSONError ( w , http . StatusBadRequest , err . Error ())
return
}
2026-09-01 01:34:48 +02:00
input . Password = * request . NewPassword
}
if request . NewUsername == nil && request . NewEmail == nil && input . Password == "" {
writeJSONError ( w , http . StatusBadRequest , errInvalidAuthInput . Error ())
return
}
if ! sharedauth . CanManageUsers ( current . Role ) {
writeJSONError ( w , http . StatusForbidden , errSelfServiceProfile . Error ())
return
}
if err := a . authGuard . UpdateManagedUser ( r . Context (), token , current . ID , input ); err != nil {
writeAuthGuardError ( w , err , "Unable to update account" )
return
}
// Match the pre-migration behavior of forcing re-authentication after a
// credential change. AuthGuard's admin-update endpoint does not itself
// invalidate sessions, and there is no self-service "invalidate all my
// other sessions" call, so only the session used for this request is
// guaranteed to be revoked; see the top-of-file doc comment's "Known
// gaps" section.
if _ , err := a . authGuard . Logout ( r . Context (), token ); err != nil {
var apiErr * authclient . APIError
if ! errors . As ( err , & apiErr ) {
2026-08-03 18:07:40 +02:00
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
return
}
}
2026-09-01 01:34:48 +02:00
a . clearSessionCookies ( w )
2026-08-03 18:07:40 +02:00
writeJSON ( w , http . StatusOK , map [ string ] bool { "ok" : true })
}
2026-09-01 01:34:48 +02:00
func ( a * AuthService ) handleTokenStatus ( w http . ResponseWriter , r * http . Request ) {
userID , ok , err := a . currentUserID ( r )
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
return
}
if ! ok {
writeJSONError ( w , http . StatusUnauthorized , errAuthRequired . Error ())
return
}
hasToken , err := a . db . hasAPIToken ( r . Context (), userID )
2026-08-03 18:07:40 +02:00
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
return
}
writeJSON ( w , http . StatusOK , map [ string ] bool { "hasToken" : hasToken })
}
2026-09-01 01:34:48 +02:00
func ( a * AuthService ) handleTokenRegenerate ( w http . ResponseWriter , r * http . Request ) {
userID , ok , err := a . currentUserID ( r )
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
return
}
if ! ok {
writeJSONError ( w , http . StatusUnauthorized , errAuthRequired . Error ())
return
}
2026-08-03 18:07:40 +02:00
token , err := randomToken ()
if err != nil {
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
return
}
2026-09-01 01:34:48 +02:00
if err := a . db . regenerateAPIToken ( r . Context (), userID , hashToken ( token )); err != nil {
2026-08-03 18:07:40 +02:00
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
return
}
writeJSON ( w , http . StatusOK , map [ string ] string { "token" : token })
}
2026-08-05 14:58:07 +02:00
type managedUserResponse struct {
ID int64 `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Role string `json:"role"`
TotpEnabled bool `json:"totpEnabled"`
}
2026-09-01 01:34:48 +02:00
// managedUserView translates an AuthGuard ManagedUser into CollabTable's
// existing response shape. TotpEnabled reflects only what this CollabTable
// instance's local best-effort cache has observed for that account (see the
// top-of-file doc comment's "Known gaps" section) -- AuthGuard's admin/users
// endpoints do not report TOTP status at all, so an account this instance
// has never toggled 2FA for is reported as false regardless of its real
// state.
func ( a * AuthService ) managedUserView ( ctx context . Context , user authclient . ManagedUser ) managedUserResponse {
enabled , _ := a . db . GetCachedTOTPEnabled ( ctx , user . ID )
return managedUserResponse { ID : user . ID , Username : user . Username , Email : user . Email , Role : user . Role , TotpEnabled : enabled }
2026-08-05 14:58:07 +02:00
}
2026-09-01 01:34:48 +02:00
// writeAuthGuardError translates an authclient error into CollabTable's
// {"error": "...", "message": "..."} response shape. AuthGuard's own
// httpapi handlers were built directly from CollabTable's (and the other
// projects') original local implementations, so their status codes and
// messages already match -- AuthGuard's *APIError is forwarded close to
// verbatim rather than re-mapped by hand. A non-APIError (a transport
// failure actually reaching AuthGuard) falls back to a generic 500 with
// fallbackMessage.
func writeAuthGuardError ( w http . ResponseWriter , err error , fallbackMessage string ) {
2026-09-03 08:24:06 +02:00
if statusCode , message , ok := authproxy . APIErrorResponse ( err ); ok {
writeJSONError ( w , statusCode , message )
2026-09-01 01:34:48 +02:00
return
2026-08-05 14:58:07 +02:00
}
2026-09-01 01:34:48 +02:00
writeJSONError ( w , http . StatusInternalServerError , fallbackMessage )
2026-08-05 14:58:07 +02:00
}
2026-09-01 01:34:48 +02:00
// handleUsers proxies admin user listing/creation to AuthGuard's
// GET/POST /api/admin/users. Authorization (CanManageUsers) is enforced by
// AuthGuard itself from the forwarded session token; CollabTable does not
// re-implement that check locally, so its 401/403 responses come straight
// from AuthGuard via writeAuthGuardError. See the top-of-file doc comment:
// AuthGuard's admin endpoints enforce the exact same rules CollabTable's
// local implementation did.
func ( a * AuthService ) handleUsers ( w http . ResponseWriter , r * http . Request ) {
if ! a . enabled () {
switch r . Method {
case http . MethodGet :
// Nothing is gated in auth-disabled mode, and an empty list is an
// honest answer: there is no user store to list from. See the
// top-of-file doc comment's "Auth-disabled mode" section.
writeJSON ( w , http . StatusOK , [] managedUserResponse {})
case http . MethodPost :
writeJSONError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
default :
w . WriteHeader ( http . StatusMethodNotAllowed )
}
return
}
token := a . sessionToken ( r )
if token == "" {
writeJSONError ( w , http . StatusUnauthorized , errAuthRequired . Error ())
2026-08-05 14:58:07 +02:00
return
}
switch r . Method {
case http . MethodGet :
2026-09-01 01:34:48 +02:00
users , err := a . authGuard . ListManagedUsers ( r . Context (), token )
2026-08-05 14:58:07 +02:00
if err != nil {
2026-09-01 01:34:48 +02:00
writeAuthGuardError ( w , err , "Unable to list users" )
2026-08-05 14:58:07 +02:00
return
}
result := make ([] managedUserResponse , 0 , len ( users ))
for _ , user := range users {
2026-09-01 01:34:48 +02:00
result = append ( result , a . managedUserView ( r . Context (), user ))
2026-08-05 14:58:07 +02:00
}
writeJSON ( w , http . StatusOK , result )
case http . MethodPost :
2026-09-01 01:34:48 +02:00
var input authclient . ManagedUserInput
if err := decodeJSON ( r , & input ); err != nil {
2026-08-05 14:58:07 +02:00
writeJSONError ( w , http . StatusBadRequest , "Invalid JSON body" )
return
}
2026-09-01 01:34:48 +02:00
created , err := a . authGuard . CreateManagedUser ( r . Context (), token , input )
2026-08-05 14:58:07 +02:00
if err != nil {
2026-09-01 01:34:48 +02:00
writeAuthGuardError ( w , err , "Unable to create user" )
2026-08-05 14:58:07 +02:00
return
}
2026-09-01 01:34:48 +02:00
if err := a . db . SetCachedTOTPEnabled ( r . Context (), created . ID , false ); err != nil {
writeJSONError ( w , http . StatusInternalServerError , "Internal server error" )
2026-08-05 14:58:07 +02:00
return
}
2026-09-01 01:34:48 +02:00
writeJSON ( w , http . StatusCreated , a . managedUserView ( r . Context (), * created ))
2026-08-05 14:58:07 +02:00
default :
w . WriteHeader ( http . StatusMethodNotAllowed )
}
}
2026-09-01 01:34:48 +02:00
// handleUser proxies admin user update/delete to AuthGuard's
// PUT/DELETE /api/admin/users/{id}. See handleUsers's doc comment: AuthGuard
// enforces authorization (including the "the superadmin account is
// protected" and "this user cannot be deleted" rules) itself.
func ( a * AuthService ) handleUser ( w http . ResponseWriter , r * http . Request ) {
if ! a . enabled () {
switch r . Method {
case http . MethodPut , http . MethodPatch , http . MethodDelete :
writeJSONError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
default :
w . WriteHeader ( http . StatusMethodNotAllowed )
}
return
}
token := a . sessionToken ( r )
if token == "" {
writeJSONError ( w , http . StatusUnauthorized , errAuthRequired . Error ())
2026-08-05 14:58:07 +02:00
return
}
id , err := strconv . ParseInt ( r . PathValue ( "id" ), 10 , 64 )
if err != nil {
writeJSONError ( w , http . StatusBadRequest , "Invalid user id" )
return
}
switch r . Method {
case http . MethodPut , http . MethodPatch :
2026-09-01 01:34:48 +02:00
var input authclient . ManagedUserInput
if err := decodeJSON ( r , & input ); err != nil {
2026-08-05 14:58:07 +02:00
writeJSONError ( w , http . StatusBadRequest , "Invalid JSON body" )
return
}
2026-09-01 01:34:48 +02:00
if err := a . authGuard . UpdateManagedUser ( r . Context (), token , id , input ); err != nil {
writeAuthGuardError ( w , err , "Unable to update user" )
2026-08-05 14:58:07 +02:00
return
}
writeJSON ( w , http . StatusOK , map [ string ] bool { "ok" : true })
case http . MethodDelete :
2026-09-01 01:34:48 +02:00
if err := a . authGuard . DeleteManagedUser ( r . Context (), token , id ); err != nil {
writeAuthGuardError ( w , err , "Unable to delete user" )
2026-08-05 14:58:07 +02:00
return
}
writeJSON ( w , http . StatusOK , map [ string ] bool { "ok" : true })
default :
w . WriteHeader ( http . StatusMethodNotAllowed )
}
}