Anyone authenticated can still read the shared platform list, but only an
admin may add, rename or delete from it.
- users.is_admin boolean, defaulting to false. The very first account ever
registered becomes an admin automatically (CreateUser's INSERT uses
NOT EXISTS (SELECT 1 FROM users) for is_admin), so there's always at
least one without manual setup; promoting anyone beyond that is a manual
UPDATE for now (documented in the migration's comment on the column).
- GetSessionAndUser, GetUserByEmail and GetUserByID now also select
is_admin, and it flows through to model.User (and so to
/api/auth/{register,login,me}'s response) and to the auth middleware's
authedUser.
- New requireAdminMiddleware + addAdminAuth, layered on top of the existing
auth middleware. Wired onto create/update/delete-platform; list/get stay
on plain addAuth, since reading the list only requires being logged in.
Verified end to end: the first registered user comes back is_admin:true,
the second false; the non-admin gets 403 on create/update/delete-platform
but 200 on list; the admin can do all of it.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
40 lines
1.0 KiB
Go
40 lines
1.0 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"completed/internal/model"
|
|
)
|
|
|
|
// authedUser is what AuthMiddleware stores in the request context after
|
|
// validating a session token. Handlers read it with userFromContext.
|
|
type authedUser struct {
|
|
ID uuid.UUID
|
|
Email string
|
|
Name string
|
|
Bio string
|
|
IsAdmin bool
|
|
}
|
|
|
|
type ctxKey string
|
|
|
|
const userCtxKey ctxKey = "completed.user"
|
|
|
|
func (u authedUser) toModel() model.User {
|
|
return model.User{ID: u.ID.String(), Email: u.Email, Name: u.Name, Bio: u.Bio, IsAdmin: u.IsAdmin}
|
|
}
|
|
|
|
// userFromContext returns the authenticated user set by AuthMiddleware. It
|
|
// panics if called from a route that isn't behind AuthMiddleware, since that
|
|
// is a programming error (a handler trusting a context value that was never
|
|
// guaranteed to be there), not a condition callers should need to check.
|
|
func userFromContext(ctx context.Context) authedUser {
|
|
u, ok := ctx.Value(userCtxKey).(authedUser)
|
|
if !ok {
|
|
panic("api: userFromContext called outside AuthMiddleware")
|
|
}
|
|
return u
|
|
}
|