Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0fa433ff9 | ||
|
|
142325730d | ||
|
|
1ece778caf | ||
|
|
153fd8719a | ||
|
|
461e93e3b5 | ||
|
|
162fea4afb | ||
|
|
b146dfead7 | ||
|
|
27dadbbfa6 | ||
|
|
6dc47789ef | ||
|
|
65ced64568 | ||
|
|
c40522a09f |
No files matched your search
@@ -38,12 +38,15 @@ type UseCases struct {
|
|||||||
UpdateUserProfileUseCase *useCases.UpdateUserProfileUseCase
|
UpdateUserProfileUseCase *useCases.UpdateUserProfileUseCase
|
||||||
ListUsersUseCase *useCases.ListUsersUseCase
|
ListUsersUseCase *useCases.ListUsersUseCase
|
||||||
CreateInviteUseCase *useCases.CreateInviteUseCase
|
CreateInviteUseCase *useCases.CreateInviteUseCase
|
||||||
|
CancelInviteUseCase *useCases.CancelInviteUseCase
|
||||||
|
RenewInviteUseCase *useCases.RenewInviteUseCase
|
||||||
ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase
|
ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase
|
||||||
GetInviteUseCase *useCases.GetInviteUseCase
|
GetInviteUseCase *useCases.GetInviteUseCase
|
||||||
AcceptInviteUseCase *useCases.AcceptInviteUseCase
|
AcceptInviteUseCase *useCases.AcceptInviteUseCase
|
||||||
SendMailUseCase *useCases.SendMailUseCase
|
SendMailUseCase *useCases.SendMailUseCase
|
||||||
CreateImageUseCase *useCases.CreateImageUseCase
|
CreateImageUseCase *useCases.CreateImageUseCase
|
||||||
DeleteImageUseCase *useCases.DeleteImageUseCase
|
DeleteImageUseCase *useCases.DeleteImageUseCase
|
||||||
|
GetSettingsUseCase *useCases.GetSettingsUseCase
|
||||||
}
|
}
|
||||||
|
|
||||||
type Repositories struct {
|
type Repositories struct {
|
||||||
@@ -73,6 +76,10 @@ func getDb(dbName string) *gorm.DB {
|
|||||||
panic("Failed to migrate database: " + err.Error())
|
panic("Failed to migrate database: " + err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := persistence.BackfillUserRoles(db); err != nil {
|
||||||
|
panic("Failed to backfill user roles: " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
return db
|
return db
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,12 +113,15 @@ func getUseCases(repos *Repositories, settings config.Settings) *UseCases {
|
|||||||
UpdateUserProfileUseCase: useCases.NewUpdateUserProfileUseCase(repos.UserRepo),
|
UpdateUserProfileUseCase: useCases.NewUpdateUserProfileUseCase(repos.UserRepo),
|
||||||
ListUsersUseCase: useCases.NewListUsersUseCase(repos.UserRepo),
|
ListUsersUseCase: useCases.NewListUsersUseCase(repos.UserRepo),
|
||||||
CreateInviteUseCase: useCases.NewCreateInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL),
|
CreateInviteUseCase: useCases.NewCreateInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL),
|
||||||
|
CancelInviteUseCase: useCases.NewCancelInviteUseCase(repos.InviteRepo),
|
||||||
|
RenewInviteUseCase: useCases.NewRenewInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL),
|
||||||
ListUsersAndInvitesUseCase: useCases.NewListUsersAndInvitesUseCase(repos.UserRepo, repos.InviteRepo),
|
ListUsersAndInvitesUseCase: useCases.NewListUsersAndInvitesUseCase(repos.UserRepo, repos.InviteRepo),
|
||||||
GetInviteUseCase: useCases.NewGetInviteUseCase(repos.InviteRepo, hasher),
|
GetInviteUseCase: useCases.NewGetInviteUseCase(repos.InviteRepo, hasher),
|
||||||
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher),
|
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher),
|
||||||
SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo),
|
SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo),
|
||||||
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo),
|
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo),
|
||||||
DeleteImageUseCase: useCases.NewDeleteImageUseCase(repos.ImageRepo),
|
DeleteImageUseCase: useCases.NewDeleteImageUseCase(repos.ImageRepo),
|
||||||
|
GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package settings
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Handler struct {
|
||||||
|
GetSettingsUseCase *useCases.GetSettingsUseCase
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(getSettings *useCases.GetSettingsUseCase) *Handler {
|
||||||
|
return &Handler{GetSettingsUseCase: getSettings}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) GetSettings(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
body, err := json.Marshal(h.GetSettingsUseCase.GetSettings())
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = w.Write(body)
|
||||||
|
}
|
||||||
@@ -10,11 +10,16 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
type InviteHandler struct {
|
type InviteHandler struct {
|
||||||
CreateInviteUseCase *useCases.CreateInviteUseCase
|
CreateInviteUseCase *useCases.CreateInviteUseCase
|
||||||
|
CancelInviteUseCase *useCases.CancelInviteUseCase
|
||||||
|
RenewInviteUseCase *useCases.RenewInviteUseCase
|
||||||
ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase
|
ListUsersAndInvitesUseCase *useCases.ListUsersAndInvitesUseCase
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,13 +49,17 @@ type userListItem struct {
|
|||||||
Kind string `json:"kind"`
|
Kind string `json:"kind"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
DisplayName string `json:"display_name"`
|
DisplayName string `json:"display_name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Role string `json:"role"`
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewInviteHandler(createInvite *useCases.CreateInviteUseCase, listUsersAndInvites *useCases.ListUsersAndInvitesUseCase) *InviteHandler {
|
func NewInviteHandler(createInvite *useCases.CreateInviteUseCase, cancelInvite *useCases.CancelInviteUseCase, renewInvite *useCases.RenewInviteUseCase, listUsersAndInvites *useCases.ListUsersAndInvitesUseCase) *InviteHandler {
|
||||||
return &InviteHandler{
|
return &InviteHandler{
|
||||||
CreateInviteUseCase: createInvite,
|
CreateInviteUseCase: createInvite,
|
||||||
|
CancelInviteUseCase: cancelInvite,
|
||||||
|
RenewInviteUseCase: renewInvite,
|
||||||
ListUsersAndInvitesUseCase: listUsersAndInvites,
|
ListUsersAndInvitesUseCase: listUsersAndInvites,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -82,23 +91,82 @@ func (h *InviteHandler) CreateInvite(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
writeInviteResponse(w, http.StatusCreated, created)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeInviteResponse(w http.ResponseWriter, status int, entry invite.Invite) {
|
||||||
body, err := json.Marshal(inviteResponse{
|
body, err := json.Marshal(inviteResponse{
|
||||||
ID: created.ID,
|
ID: entry.ID,
|
||||||
Kind: useCases.EntryKindInvite,
|
Kind: useCases.EntryKindInvite,
|
||||||
Email: created.Email,
|
Email: entry.Email,
|
||||||
Status: string(created.StatusAt(time.Now())),
|
Status: string(entry.StatusAt(time.Now())),
|
||||||
CreatedAt: created.CreatedAt,
|
CreatedAt: entry.CreatedAt,
|
||||||
ExpiresAt: created.ExpiresAt,
|
ExpiresAt: entry.ExpiresAt,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.Header().Set("Cache-Control", "no-store")
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
w.WriteHeader(http.StatusCreated)
|
w.WriteHeader(status)
|
||||||
_, _ = w.Write(body)
|
_, _ = w.Write(body)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func parseInviteId(r *http.Request) (uint32, error) {
|
||||||
|
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
||||||
|
return uint32(id), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *InviteHandler) CancelInvite(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, err := parseInviteId(r)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.CancelInviteUseCase.CancelInvite(id); err != nil {
|
||||||
|
writeManageInviteError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *InviteHandler) RenewInvite(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, err := parseInviteId(r)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
userId, ok := claims.UserId(r)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
renewed, err := h.RenewInviteUseCase.RenewInvite(useCases.RenewInviteCommand{ID: id, RenewedBy: userId})
|
||||||
|
if err != nil {
|
||||||
|
writeManageInviteError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeInviteResponse(w, http.StatusOK, renewed)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeManageInviteError(w http.ResponseWriter, err error) {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, invite.ErrInviteNotFound):
|
||||||
|
http.Error(w, apperr.InviteNotFoundErrorMessage, http.StatusNotFound)
|
||||||
|
case errors.Is(err, invite.ErrInviteAlreadyAccepted):
|
||||||
|
http.Error(w, apperr.InviteAlreadyAcceptedErrorMessage, http.StatusConflict)
|
||||||
|
case errors.Is(err, invite.ErrInviteEmailNotSent):
|
||||||
|
http.Error(w, apperr.InviteNotSentErrorMessage, http.StatusInternalServerError)
|
||||||
|
case errors.Is(err, user.ErrUserNotFound):
|
||||||
|
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||||
|
default:
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func writeCreateInviteError(w http.ResponseWriter, err error) {
|
func writeCreateInviteError(w http.ResponseWriter, err error) {
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, invite.ErrEmailHasAccount):
|
case errors.Is(err, invite.ErrEmailHasAccount):
|
||||||
@@ -123,7 +191,7 @@ func (h *InviteHandler) ListUsers(w http.ResponseWriter, _ *http.Request) {
|
|||||||
items = append(items, inviteListItem{entry.ID, entry.Kind, entry.Email, entry.Status, entry.CreatedAt})
|
items = append(items, inviteListItem{entry.ID, entry.Kind, entry.Email, entry.Status, entry.CreatedAt})
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
items = append(items, userListItem{entry.ID, entry.Kind, entry.Username, entry.DisplayName, entry.Status, entry.CreatedAt})
|
items = append(items, userListItem{entry.ID, entry.Kind, entry.Username, entry.DisplayName, entry.Email, entry.Role, entry.Status, entry.CreatedAt})
|
||||||
}
|
}
|
||||||
|
|
||||||
body, err := json.Marshal(items)
|
body, err := json.Marshal(items)
|
||||||
|
|||||||
@@ -77,3 +77,21 @@ func RequireVerifiedUser(getUser *useCases.GetUserUseCase) func(http.Handler) ht
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func RequireOwner(getUser *useCases.GetUserUseCase) func(http.Handler) http.Handler {
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
currentUser, ok := resolveCurrentUser(getUser, w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if currentUser.Role != user.RoleOwner {
|
||||||
|
http.Error(w, apperr.OwnerRequiredErrorMessage, http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,6 +19,9 @@ const TooManyRequestsErrorMessage = "Too many requests. Please try again later."
|
|||||||
const EmailHasAccountErrorMessage = "This address already has an account."
|
const EmailHasAccountErrorMessage = "This address already has an account."
|
||||||
const PendingInviteErrorMessage = "There's already a pending invite for this address."
|
const PendingInviteErrorMessage = "There's already a pending invite for this address."
|
||||||
const InviteNotSentErrorMessage = "Couldn't send the invite. Try again in a moment."
|
const InviteNotSentErrorMessage = "Couldn't send the invite. Try again in a moment."
|
||||||
|
const InviteNotFoundErrorMessage = "Invite not found"
|
||||||
|
const InviteAlreadyAcceptedErrorMessage = "This invite has already been accepted."
|
||||||
const InviteInvalidErrorMessage = "This invite link doesn't work."
|
const InviteInvalidErrorMessage = "This invite link doesn't work."
|
||||||
const InviteExpiredErrorMessage = "This invite has expired."
|
const InviteExpiredErrorMessage = "This invite has expired."
|
||||||
|
const OwnerRequiredErrorMessage = "Only the owner can do this."
|
||||||
const UsernameTakenErrorMessage = "That username is taken. Try another."
|
const UsernameTakenErrorMessage = "That username is taken. Try another."
|
||||||
@@ -13,6 +13,7 @@ type PublicUser struct {
|
|||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
DisplayName string `json:"display_name"`
|
DisplayName string `json:"display_name"`
|
||||||
|
Role user.Role `json:"role"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(u user.User) PublicUser {
|
func New(u user.User) PublicUser {
|
||||||
@@ -24,5 +25,6 @@ func New(u user.User) PublicUser {
|
|||||||
CreatedAt: u.CreatedAt,
|
CreatedAt: u.CreatedAt,
|
||||||
UpdatedAt: u.UpdatedAt,
|
UpdatedAt: u.UpdatedAt,
|
||||||
DisplayName: u.DisplayName,
|
DisplayName: u.DisplayName,
|
||||||
|
Role: u.Role,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+19
-1
@@ -5,6 +5,7 @@ import (
|
|||||||
"RenewCMS/api/handlers/auth"
|
"RenewCMS/api/handlers/auth"
|
||||||
"RenewCMS/api/handlers/frontend"
|
"RenewCMS/api/handlers/frontend"
|
||||||
"RenewCMS/api/handlers/image"
|
"RenewCMS/api/handlers/image"
|
||||||
|
"RenewCMS/api/handlers/settings"
|
||||||
"RenewCMS/api/handlers/staticimages"
|
"RenewCMS/api/handlers/staticimages"
|
||||||
"RenewCMS/api/handlers/user"
|
"RenewCMS/api/handlers/user"
|
||||||
"RenewCMS/api/middleware"
|
"RenewCMS/api/middleware"
|
||||||
@@ -99,7 +100,7 @@ func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings,
|
|||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
|
|
||||||
userHandler := user.NewHandler(container.UpdateUserProfileUseCase)
|
userHandler := user.NewHandler(container.UpdateUserProfileUseCase)
|
||||||
inviteHandler := user.NewInviteHandler(container.CreateInviteUseCase, container.ListUsersAndInvitesUseCase)
|
inviteHandler := user.NewInviteHandler(container.CreateInviteUseCase, container.CancelInviteUseCase, container.RenewInviteUseCase, container.ListUsersAndInvitesUseCase)
|
||||||
|
|
||||||
r.Use(jwtauth.Verifier(container.Token))
|
r.Use(jwtauth.Verifier(container.Token))
|
||||||
r.Use(jwtauth.Authenticator(container.Token))
|
r.Use(jwtauth.Authenticator(container.Token))
|
||||||
@@ -108,13 +109,29 @@ func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings,
|
|||||||
r.Patch("/me", userHandler.UpdateMe)
|
r.Patch("/me", userHandler.UpdateMe)
|
||||||
r.Get("/", inviteHandler.ListUsers)
|
r.Get("/", inviteHandler.ListUsers)
|
||||||
r.Group(func(r chi.Router) {
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||||
r.Use(middleware.TrustedProxyRealIP(trustedProxies))
|
r.Use(middleware.TrustedProxyRealIP(trustedProxies))
|
||||||
r.Use(middleware.NewRateLimiter(rateLimit.MaxAttempts, rateLimit.Window))
|
r.Use(middleware.NewRateLimiter(rateLimit.MaxAttempts, rateLimit.Window))
|
||||||
r.Post("/invite", inviteHandler.CreateInvite)
|
r.Post("/invite", inviteHandler.CreateInvite)
|
||||||
|
r.Delete("/invite/{id}", inviteHandler.CancelInvite)
|
||||||
|
r.Post("/invite/{id}/renew", inviteHandler.RenewInvite)
|
||||||
})
|
})
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func NewSettingsRouter(container *UseCases) http.Handler {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
|
||||||
|
settingsHandler := settings.NewHandler(container.GetSettingsUseCase)
|
||||||
|
|
||||||
|
r.Use(jwtauth.Verifier(container.Token))
|
||||||
|
r.Use(jwtauth.Authenticator(container.Token))
|
||||||
|
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||||
|
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||||
|
r.Get("/", settingsHandler.GetSettings)
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
|
func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
|
||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
|
|
||||||
@@ -128,6 +145,7 @@ func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
|
|||||||
r.Mount("/article", NewArticleRouter(container))
|
r.Mount("/article", NewArticleRouter(container))
|
||||||
})
|
})
|
||||||
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
|
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
|
||||||
|
r.Mount("/settings", NewSettingsRouter(container))
|
||||||
r.Mount("/auth", NewAuthRouter(container, settings.IsProduction(), settings.AuthRateLimit, settings.TrustedProxies))
|
r.Mount("/auth", NewAuthRouter(container, settings.IsProduction(), settings.AuthRateLimit, settings.TrustedProxies))
|
||||||
|
|
||||||
return r
|
return r
|
||||||
|
|||||||
@@ -62,6 +62,7 @@ func run() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
settings.Version = version
|
||||||
|
|
||||||
container, closeDb := api.InitContainer(settings)
|
container, closeDb := api.InitContainer(settings)
|
||||||
defer closeDatabase(closeDb)
|
defer closeDatabase(closeDb)
|
||||||
|
|||||||
@@ -30,7 +30,8 @@ The visual spec of record for the back-office SPA and the transactional emails,
|
|||||||
| [New article](screens/new-article.md) | `modal from anywhere · /article/new` | 5 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [New article](screens/new-article.md) | `modal from anywhere · /article/new` | 5 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Editor](screens/editor.md) | `/article/:id/edit` | 22 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Editor](screens/editor.md) | `/article/:id/edit` | 22 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Integration](screens/integration.md) | `/integration` | 2 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Integration](screens/integration.md) | `/integration` | 2 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Users](screens/users.md) | `/users` | 10 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Users](screens/users.md) | `/users` | 17 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
|
| [Settings](screens/settings.md) | `/settings` | 1 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Profile](screens/profile.md) | `/profile` | 13 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Profile](screens/profile.md) | `/profile` | 13 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Accept invite](screens/accept-invite.md) | `/invite/accept?c=CODE` | 9 | `source/RenewCMS Screens Auth.dc.html` |
|
| [Accept invite](screens/accept-invite.md) | `/invite/accept?c=CODE` | 9 | `source/RenewCMS Screens Auth.dc.html` |
|
||||||
| [Global](screens/global.md) | `any route` | 4 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Global](screens/global.md) | `any route` | 4 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
@@ -39,5 +40,5 @@ The visual spec of record for the back-office SPA and the transactional emails,
|
|||||||
|
|
||||||
- `source/RenewCMS Prototype.dc.html`: the clickable flows (first run, edit and publish, password reset, delete, session expiry mid-edit).
|
- `source/RenewCMS Prototype.dc.html`: the clickable flows (first run, edit and publish, password reset, delete, session expiry mid-edit).
|
||||||
- `source/RenewCMS Handoff.dc.html`: the handoff page the first markdown here was generated from. It predates the Users and Profile screens and the invitation email, so it does not list them. Those are written by hand from the Back-office board, `AppFrame.dc.html`, the Prototype and `emails/invitation.html`.
|
- `source/RenewCMS Handoff.dc.html`: the handoff page the first markdown here was generated from. It predates the Users and Profile screens and the invitation email, so it does not list them. Those are written by hand from the Back-office board, `AppFrame.dc.html`, the Prototype and `emails/invitation.html`.
|
||||||
- `source/RenewCMS Components Product.dc.html`: not regenerated for the new screens either. The matching component changes are in `components.md`, under "Added with the Users and Profile screens".
|
- `source/RenewCMS Components Product.dc.html`: not regenerated for the new screens either. The matching component changes are in `components.md`, under "Added with the Users and Profile screens" and "Added with roles, invite actions and Settings".
|
||||||
- `source/RenewCMS Directions.dc.html`: the three brand directions (history only).
|
- `source/RenewCMS Directions.dc.html`: the three brand directions (history only).
|
||||||
+41
-12
@@ -7,8 +7,10 @@
|
|||||||
| AuthShell | UPageCard, UColorModeSelect | title, description? | none | default, notice, footer | All public routes |
|
| AuthShell | UPageCard, UColorModeSelect | title, description? | none | default, notice, footer | All public routes |
|
||||||
| DashboardShell | UDashboardGroup, UDashboardSidebar, UNavigationMenu, UDashboardPanel, UDashboardNavbar, UBreadcrumb | none (reads route.meta and the session store) | none | default, navbar-right | All verified routes |
|
| DashboardShell | UDashboardGroup, UDashboardSidebar, UNavigationMenu, UDashboardPanel, UDashboardNavbar, UBreadcrumb | none (reads route.meta and the session store) | none | default, navbar-right | All verified routes |
|
||||||
| UserMenu | UDropdownMenu, UButton, UAvatar (a bottom sheet below md) | displayName?, username, email | logout | none | DashboardShell |
|
| UserMenu | UDropdownMenu, UButton, UAvatar (a bottom sheet below md) | displayName?, username, email | logout | none | DashboardShell |
|
||||||
| UsersTable | UTable | rows: UserRow[], loading | none | none | Users (md and up) |
|
| UsersTable | UTable | rows: UserRow[], loading, canManage: boolean, busyIds: Set | cancel-invite, renew-invite | none | Users (md and up) |
|
||||||
| UserCardList | custom list | same as UsersTable | none | none | Users (below md) |
|
| UserCardList | custom list | same as UsersTable | same as UsersTable | none | Users (below md) |
|
||||||
|
| RoleBadge | UBadge | role: 'owner'\|'admin' | none | none | Users |
|
||||||
|
| SettingsPage | custom card | none (reads GET /v1/settings) | none | none | Settings |
|
||||||
| InviteStatusBadge | UBadge | status: 'accepted'\|'pending'\|'expired' | none | none | Users |
|
| InviteStatusBadge | UBadge | status: 'accepted'\|'pending'\|'expired' | none | none | Users |
|
||||||
| InviteUserModal | UModal, UForm, UFormField, UInput | none | invited(invite) | none | Users |
|
| InviteUserModal | UModal, UForm, UFormField, UInput | none | invited(invite) | none | Users |
|
||||||
| ProfileCard | custom card (border, padding, optional footer strip) | title, description | none | default, footer | Profile |
|
| ProfileCard | custom card (border, padding, optional footer strip) | title, description | none | default, footer | Profile |
|
||||||
@@ -63,7 +65,7 @@ Responsive 400 px card from sm up, with its top 12 vh from the top. Below sm , t
|
|||||||
|
|
||||||
### DashboardShell
|
### DashboardShell
|
||||||
|
|
||||||
The sidebar has four destinations (Home, Articles, Users, Integration), and the user menu sits at its foot. The top bar carries the breadcrumbs and page title. Collapsing the sidebar leaves a 56 px icon rail. Below lg , the sidebar becomes a slideover.
|
The sidebar has five destinations (Home, Articles, Users, Integration, Settings), and the user menu sits at its foot. The top bar carries the breadcrumbs and page title. Collapsing the sidebar leaves a 56 px icon rail. Below lg , the sidebar becomes a slideover.
|
||||||
|
|
||||||
RenewCMS
|
RenewCMS
|
||||||
|
|
||||||
@@ -97,7 +99,7 @@ Mobile top bar. The menu button opens the sidebar as a left slideover.
|
|||||||
|
|
||||||
Built from UDashboardGroup storage="local" › UDashboardSidebar collapsible :resizable="false" :default-size="16" :collapsed-size="4" with the #header (AppLogo), #default ( UNavigationMenu orientation="vertical" :collapsed ) and #footer (UserMenu) slots. Each page is a UDashboardPanel , with a UDashboardNavbar holding UDashboardSidebarCollapse and UBreadcrumb . On mobile, UDashboardSidebarToggle appears and the sidebar's built-in slideover takes over.
|
Built from UDashboardGroup storage="local" › UDashboardSidebar collapsible :resizable="false" :default-size="16" :collapsed-size="4" with the #header (AppLogo), #default ( UNavigationMenu orientation="vertical" :collapsed ) and #footer (UserMenu) slots. Each page is a UDashboardPanel , with a UDashboardNavbar holding UDashboardSidebarCollapse and UBreadcrumb . On mobile, UDashboardSidebarToggle appears and the sidebar's built-in slideover takes over.
|
||||||
|
|
||||||
UserMenu UDropdownMenu :content="{ side: 'top', align: 'start' }" on a ghost UButton block with a UAvatar and the username. The groups are: the account label; System, Light and Dark as checkbox items; then Log out. There are no profile or password items, because the API doesn't support them. Superseded: see "UserMenu (changed)" under "Added with the Users and Profile screens".
|
UserMenu UDropdownMenu :content="{ side: 'top', align: 'start' }" on a ghost UButton block with a UAvatar and the username. The groups are: the account label; System, Light and Dark as checkbox items; then Log out. There are no profile or password items, because the API doesn't support them. Superseded: see "UserMenu (changed)" under "Added with the Users and Profile screens", which restores the System, Light and Dark items.
|
||||||
|
|
||||||
Props, slots No props, because the shell reads the user from the session Pinia store. The navbar reads route.meta.title and route.meta.breadcrumb . Slots navbar-right (page actions on mobile) and default . It shows the offline banner when navigator.onLine is false.
|
Props, slots No props, because the shell reads the user from the session Pinia store. The navbar reads route.meta.title and route.meta.breadcrumb . Slots navbar-right (page actions on mobile) and default . It shows the offline banner when navigator.onLine is false.
|
||||||
|
|
||||||
@@ -381,24 +383,22 @@ The Product components board was not regenerated for these. They are written fro
|
|||||||
|
|
||||||
### UserMenu (changed)
|
### UserMenu (changed)
|
||||||
|
|
||||||
The chip at the foot of the sidebar no longer logs out on click. It opens the account menu, which lists Profile and Log out.
|
The chip at the foot of the sidebar no longer logs out on click. It opens the account menu, which lists Profile, the theme choice and Log out.
|
||||||
|
|
||||||
- **Chip:** 40 px high, an initials avatar (26 px, sand `#d4c5b0` with ink text), the name, and a chevrons-up-down icon. `aria-haspopup="menu"`, `aria-expanded`, title "Account". While the menu is open, or while `/profile` is the current page, it takes `--rc-sand` with `#111111` text.
|
- **Chip:** 40 px high, an initials avatar (26 px, sand `#d4c5b0` with ink text), the name, and a chevrons-up-down icon. `aria-haspopup="menu"`, `aria-expanded`, title "Account". While the menu is open, or while `/profile` is the current page, it takes `--rc-sand` with `#111111` text.
|
||||||
- **Name:** the display name when there is one, otherwise the username. Initials come from the first letters of the first two words of the display name, uppercased. Without a display name they come from the username.
|
- **Name:** the display name when there is one, otherwise the username. Initials come from the first letters of the first two words of the display name, uppercased. Without a display name they come from the username.
|
||||||
- **Desktop menu:** a 224 px popover anchored above the chip on its left edge, with `--rc-shadow-pop`. Header: the name in semibold, the email below it in muted 12 px, a bottom border. Items are 32 px: Profile (circle-user), a separator, Log out (log-out). The current page's item is highlighted with `--ui-bg-elevated`.
|
- **Desktop menu:** a 224 px popover anchored above the chip on its left edge, with `--rc-shadow-pop`. Header: the name in semibold, the email below it in muted 12 px, a bottom border. Items are 32 px: Profile (circle-user), a separator, System, Light and Dark (14 px text, a check icon at the right edge on the current choice), a separator, Log out (log-out). The current page's item is highlighted with `--ui-bg-elevated`. The theme items are radio-style: choosing one applies at once and keeps the menu open. Nuxt UI: `type: 'checkbox'` items bound to `useColorMode().preference`.
|
||||||
- **Mobile:** the account row in the navigation drawer opens a bottom sheet over an `--rc-overlay` scrim, with a grab handle. Header: 36 px avatar, name in 15 px semibold, email in muted text. Items are 48 px at 15 px text.
|
- **Mobile:** the account row in the navigation drawer opens a bottom sheet over an `--rc-overlay` scrim, with a grab handle. Header: 36 px avatar, name in 15 px semibold, email in muted text. Items are 48 px at 15 px text; the theme items keep the same order and separators.
|
||||||
- **Keyboard:** Escape or a click outside closes it. Arrow keys move between items.
|
- **Keyboard:** Escape or a click outside closes it. Arrow keys move between items.
|
||||||
- **Open question:** the shipped menu also offers System, Light and Dark. The board omits them. See [profile.md](screens/profile.md).
|
- The board now draws the theme items, so the chip, menu and sheet need no visual exception. The board highlights Profile even on Home; the app highlights it only on `/profile`.
|
||||||
|
|
||||||
### DashboardShell (changed)
|
### DashboardShell (changed)
|
||||||
|
|
||||||
The navigation gains **Users** (users icon) between Articles and Integration, in the sidebar and in the mobile drawer. Breadcrumbs for the new pages are "Users" and "Profile".
|
The navigation gains **Users** (users icon) between Articles and Integration, in the sidebar and in the mobile drawer. Breadcrumbs for the new pages are "Users" and "Profile". It later gains **Settings** (settings icon) after Integration, with the breadcrumb "Settings".
|
||||||
|
|
||||||
### UsersTable, UserCardList
|
### UsersTable, UserCardList
|
||||||
|
|
||||||
Columns Username, Invite status, Created (sorted descending, with an arrow-down icon on the header). Grid `minmax(0,1fr) 160px 160px`, 36 px header on `--ui-bg-elevated`, 44 px rows with a top border. Below md the same rows become cards with a 68 px minimum height: the name line, then the badge and "Created {date}". There are no row actions.
|
Superseded by "UsersTable, UserCardList (changed)" below.
|
||||||
|
|
||||||
A row's name cell shows the display name first (medium weight, highlighted), the username beside it in muted text, and a mono "you" tag on the current user's row. Invite rows show the email, regular weight, toned. The row of a just-sent invite has `--ui-bg-elevated`.
|
|
||||||
|
|
||||||
Skeleton rows appear after 150 ms of loading.
|
Skeleton rows appear after 150 ms of loading.
|
||||||
|
|
||||||
@@ -735,3 +735,32 @@ Three choices: System (the default), Light and Dark. The toggle at the top of th
|
|||||||
Nuxt UI In the user menu: a UDropdownMenu group of three type: 'checkbox' items bound to useColorMode().preference . On auth screens: UColorModeSelect in the footer. Nuxt UI's UColorModeButton isn't used because it only toggles between light and dark and hides the system option. colorMode: true in the plugin handles storage and applying the .dark class before first paint.
|
Nuxt UI In the user menu: a UDropdownMenu group of three type: 'checkbox' items bound to useColorMode().preference . On auth screens: UColorModeSelect in the footer. Nuxt UI's UColorModeButton isn't used because it only toggles between light and dark and hides the system option. colorMode: true in the plugin handles storage and applying the .dark class before first paint.
|
||||||
|
|
||||||
ARIA Menu items use menuitemcheckbox , with aria-checked on the current choice. The segmented variant is a radiogroup named "Theme".
|
ARIA Menu items use menuitemcheckbox , with aria-checked on the current choice. The segmented variant is a radiogroup named "Theme".
|
||||||
|
|
||||||
|
## Added with roles, invite actions and Settings
|
||||||
|
|
||||||
|
Written from `source/RenewCMS Screens Back-office.dc.html` and `source/AppFrame.dc.html`. The Product components board was not regenerated for these.
|
||||||
|
|
||||||
|
### UsersTable, UserCardList (changed)
|
||||||
|
|
||||||
|
Columns Email, Display name, Role, Invite status, Created (sorted descending, with an arrow-down icon on the header) and an unlabeled actions column. Grid `minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px`, 12 px gap, 36 px header on `--ui-bg-elevated`, 48 px rows with a top border. Below md the same rows become cards with a 68 px minimum height: the email line, the display name below it when set, then role badge, status badge and "Created {date}" on one line, then the row action as a 44 px button.
|
||||||
|
|
||||||
|
The email cell is medium weight and highlighted, with a mono "you" tag on the current user's row. The display name is highlighted, or a muted `—` when empty. The row of a just-sent or just-renewed invite has `--ui-bg-elevated`. Skeleton rows have one bar per column. The username is not shown.
|
||||||
|
|
||||||
|
### RoleBadge
|
||||||
|
|
||||||
|
A 20 px badge in IBM Plex Mono 11 px medium, 7 px side padding, no icon.
|
||||||
|
|
||||||
|
| Role | Fill | Text | Border |
|
||||||
|
|---|---|---|---|
|
||||||
|
| owner | `--ui-primary` | `--ui-bg` | `--ui-primary` |
|
||||||
|
| admin | transparent | `--ui-text-toned` | `--ui-border-accented` |
|
||||||
|
|
||||||
|
### Row action button (Users)
|
||||||
|
|
||||||
|
A 28 px outline button on desktop (12 px medium text, 13 px icon, 9 px side padding, `--ui-border-accented` border, `--ui-bg` fill, no wrapping), 44 px on mobile (14 px side padding, 14 px icon). Cancel invite: user-x, text `--ui-error`. Renew invite: refresh-cw, text `--ui-text-highlighted`. While busy: the label becomes "Renewing…", the icon loader-circle, opacity 50 %, disabled. Nuxt UI: `UButton variant="outline" size="xs"` with the classes above.
|
||||||
|
|
||||||
|
Cancel goes through `ConfirmDialog` with `tone: 'danger'`: title "Cancel this invite?", the description names the address, the cancel button reads "Keep invite" and the confirm button "Cancel invite", pending label "Cancelling…", and a failure shows a notice inside the dialog.
|
||||||
|
|
||||||
|
### SettingsPage
|
||||||
|
|
||||||
|
A page header (title "Settings", subtitle "Workspace information."), then one card holding a "Version" row. See [screens/settings.md](screens/settings.md).
|
||||||
@@ -16,7 +16,8 @@ A global `router.beforeEach` guard reads `meta.auth`. On the first navigation it
|
|||||||
| `/article/new` | DashboardShell | verified | ArticlesPage + NewArticleModal | POST /v1/article/ |
|
| `/article/new` | DashboardShell | verified | ArticlesPage + NewArticleModal | POST /v1/article/ |
|
||||||
| `/article/:id/edit` | DashboardShell | verified | EditorPage | GET /{id} · PATCH /{id} · PATCH /{id}/publish\|unpublish · POST /{id}/image · DELETE /{id} |
|
| `/article/:id/edit` | DashboardShell | verified | EditorPage | GET /{id} · PATCH /{id} · PATCH /{id}/publish\|unpublish · POST /{id}/image · DELETE /{id} |
|
||||||
| `/integration` | DashboardShell | verified | IntegrationPage | none |
|
| `/integration` | DashboardShell | verified | IntegrationPage | none |
|
||||||
| `/users` | DashboardShell | verified | UsersPage + InviteUserModal | GET /v1/user/ · POST /v1/user/invite |
|
| `/users` | DashboardShell | verified | UsersPage + InviteUserModal | GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id · POST /v1/user/invite/:id/renew |
|
||||||
|
| `/settings` | DashboardShell | verified | SettingsPage | GET /v1/settings |
|
||||||
| `/profile` | DashboardShell | verified | ProfilePage | GET /v1/auth/me · PATCH /v1/user/me · POST /v1/auth/password-reset |
|
| `/profile` | DashboardShell | verified | ProfilePage | GET /v1/auth/me · PATCH /v1/user/me · POST /v1/auth/password-reset |
|
||||||
| `/invite/accept` | AuthShell | public | AcceptInvitePage | GET /v1/auth/invite?c=* · POST /v1/auth/invite/accept* |
|
| `/invite/accept` | AuthShell | public | AcceptInvitePage | GET /v1/auth/invite?c=* · POST /v1/auth/invite/accept* |
|
||||||
| `/:pathMatch(.*)*` | either | any | NotFoundPage | none |
|
| `/:pathMatch(.*)*` | either | any | NotFoundPage | none |
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ Once saved it replaces the username everywhere a person is named:
|
|||||||
|
|
||||||
- the sidebar chip and the account menu (name, and the avatar initials)
|
- the sidebar chip and the account menu (name, and the avatar initials)
|
||||||
- the Home greeting ("Good morning, Marta Alves")
|
- the Home greeting ("Good morning, Marta Alves")
|
||||||
- the Users list, with the username beside it
|
- the Display name column of the Users list
|
||||||
- the emails RenewCMS sends, such as "Marta Alves invited you to RenewCMS"
|
- the emails RenewCMS sends, such as "Marta Alves invited you to RenewCMS"
|
||||||
|
|
||||||
Saving it empty goes back to the username. Logging in still uses the username.
|
Saving it empty goes back to the username. Logging in still uses the username.
|
||||||
@@ -48,11 +48,13 @@ Desktop: a 224 px popover above the chip, aligned to its left. Mobile: the accou
|
|||||||
| Header | The name in semibold (display name, or the username), and the email in muted 12 px (14 px on mobile, with a 36 px initials avatar beside them) |
|
| Header | The name in semibold (display name, or the username), and the email in muted 12 px (14 px on mobile, with a 36 px initials avatar beside them) |
|
||||||
| Item | Profile (circle-user icon), highlighted while on `/profile` |
|
| Item | Profile (circle-user icon), highlighted while on `/profile` |
|
||||||
| Separator | |
|
| Separator | |
|
||||||
|
| Items | System, Light, Dark: a radio-style group, the current choice carries a check icon at the right edge; choosing one applies the theme at once and keeps the menu open |
|
||||||
|
| Separator | |
|
||||||
| Item | Log out (log-out icon) |
|
| Item | Log out (log-out icon) |
|
||||||
|
|
||||||
Avatar initials come from the first letters of the first two words of the display name, uppercased ("Marta Alves" gives MA). Without a display name they come from the username.
|
Avatar initials come from the first letters of the first two words of the display name, uppercased ("Marta Alves" gives MA). Without a display name they come from the username.
|
||||||
|
|
||||||
The board's menu has no System, Light or Dark items, while the shipped UserMenu has them. This is an open question, see the notes below.
|
The board's menu now carries System, Light and Dark, matching the shipped UserMenu. The theme choice stays in the account menu; the Profile page does not repeat it. Items are 32 px on desktop and 48 px in the mobile sheet.
|
||||||
|
|
||||||
## States
|
## States
|
||||||
|
|
||||||
@@ -62,7 +64,7 @@ The board's menu has no System, Light or Dark items, while the shipped UserMenu
|
|||||||
|
|
||||||
- Breadcrumbs: Home (mobile title "Home")
|
- Breadcrumbs: Home (mobile title "Home")
|
||||||
- Page behind the menu: Home, default
|
- Page behind the menu: Home, default
|
||||||
- Menu open, as described above
|
- Menu open, as described above, with the System, Light and Dark group between Profile and Log out. The board shows Light checked
|
||||||
|
|
||||||
### Loading
|
### Loading
|
||||||
|
|
||||||
@@ -161,17 +163,17 @@ The board's menu has no System, Light or Dark items, while the shipped UserMenu
|
|||||||
|
|
||||||
### Display names in the Users list
|
### Display names in the Users list
|
||||||
|
|
||||||
**Trigger:** Accounts with a display name show it first, with the username beside it in grey. Accounts without one show the username. This state needs the Users page ([users.md](users.md)).
|
**Trigger:** The Display name column of the Users list shows the name when one is set and a dash when not. Your own row follows your saved name. This state needs the Users page ([users.md](users.md)).
|
||||||
|
|
||||||
- Breadcrumbs: Users (mobile title "Users")
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
- Signed-in user's display name: "Marta Alves" (sidebar chip shows it too)
|
- Signed-in user's display name: "Marta Alves" (sidebar chip shows it too)
|
||||||
- Row `marta` (you): "Marta Alves", `marta` beside it in muted text, "you" tag, Accepted
|
- Row `marta@renew.example` (you): display name "Marta Alves", role owner, Accepted
|
||||||
- Row `ines`: "Inès Duarte", `ines` beside it in muted text, Accepted
|
- Row `ines.duarte@renew.example`: display name "Inès Duarte", role admin, Accepted
|
||||||
- Row `jonas`: `jonas` alone, Accepted
|
- Row `jonas@renew.example`: display name "—" (muted), role admin, Accepted
|
||||||
|
|
||||||
## Notes for implementation
|
## Notes for implementation
|
||||||
|
|
||||||
- `PATCH /v1/user/me` is marked pending by the design: it does not exist yet. `GET /v1/auth/me` has to start returning the display name.
|
- `PATCH /v1/user/me` is marked pending by the design: it does not exist yet. `GET /v1/auth/me` has to start returning the display name.
|
||||||
- The Password card sends the reset email to the account's own address through the existing `POST /v1/auth/password-reset`. The link ends on the reset confirm screen, and a successful reset invalidates the current session like any other reset.
|
- The Password card sends the reset email to the account's own address through the existing `POST /v1/auth/password-reset`. The link ends on the reset confirm screen, and a successful reset invalidates the current session like any other reset.
|
||||||
- "Disabled for 5 minutes" is the design's number. The real window comes from the `Retry-After` header, as on the login and reset screens.
|
- "Disabled for 5 minutes" is the design's number. The real window comes from the `Retry-After` header, as on the login and reset screens.
|
||||||
- Open question: the shipped UserMenu offers System, Light and Dark, and the redesigned menu does not. Decide whether the theme choice stays in the menu, moves to the Profile page, or is dropped, before building the menu.
|
- Resolved: the theme choice (System, Light, Dark) stays in the account menu, as the board now draws it. The board still draws Profile highlighted on Home; the app highlights it only on `/profile`.
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Settings
|
||||||
|
|
||||||
|
- **Route:** `/settings`
|
||||||
|
- **API:** GET /v1/settings (not drawn, see the notes)
|
||||||
|
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Settings" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
||||||
|
|
||||||
|
Opened from the sidebar (Settings, settings icon, after Integration) and from the mobile drawer. Every verified user sees it, owner and admins alike. For now it holds a single section, Version. Nothing on it can be edited.
|
||||||
|
|
||||||
|
## The page
|
||||||
|
|
||||||
|
Title "Settings" and the subtitle "Workspace information.", 720 px wide at most. Page padding 32 px on desktop and `20px 16px 88px` on mobile, 20 px between the header and the card.
|
||||||
|
|
||||||
|
One card (`--ui-bg`, 1 px `--ui-border`, 20 px padding on desktop and 16 px on mobile), a single row with the label on the left and the value on the right, 16 px apart:
|
||||||
|
|
||||||
|
| Part | Content |
|
||||||
|
|---|---|
|
||||||
|
| Label | "Version", 15 px semibold, `--ui-text-highlighted` |
|
||||||
|
| Value | The running build's version in IBM Plex Mono 14 px, `--ui-text-toned`. The board shows `v2.2.0-beta`. Shown exactly as the server reports it, so the SPA adds no `v` prefix. |
|
||||||
|
|
||||||
|
## States
|
||||||
|
|
||||||
|
### Default
|
||||||
|
|
||||||
|
**Trigger:** Opened from the sidebar.
|
||||||
|
|
||||||
|
- Breadcrumbs: Settings (mobile title "Settings")
|
||||||
|
- Section: Version, `v2.2.0-beta`
|
||||||
|
|
||||||
|
The board draws no loading or error state. Decide them in the spec (see the notes).
|
||||||
|
|
||||||
|
## Notes for implementation
|
||||||
|
|
||||||
|
- The board's API line says "none (static)", but the version lives in the Go binary (`main.version`, set with `-ldflags -X`, `dev` when unset), so the SPA has to ask for it. The recommendation is `GET /v1/settings` returning `{ "version": "..." }` inside the verified group, so later settings have a home. It is read once at startup and never from the environment at request time.
|
||||||
|
- Not drawn: loading (the recommendation is a skeleton for the value only, after 150 ms, like the other pages), and a failed request (an inline error in the card with "Try again", using the global copy "Couldn't reach RenewCMS. Check your connection and try again.").
|
||||||
|
- Keep the page free of actions, toggles and links until a later slice adds a real setting.
|
||||||
+120
-12
@@ -1,24 +1,60 @@
|
|||||||
# Users
|
# Users
|
||||||
|
|
||||||
- **Route:** `/users`
|
- **Route:** `/users`
|
||||||
- **API:** GET /v1/user/ · POST /v1/user/invite
|
- **API:** GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id (pending) · POST /v1/user/invite/:id/renew (pending)
|
||||||
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Users" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Users" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
||||||
|
|
||||||
One shared workspace: every user sees the same articles and this same list. Rows have no actions yet, so nobody can be removed, promoted or have an invite revoked from here. Pending and expired invites show the email address, because a username only exists once the invite is accepted.
|
One shared workspace: every user sees the same articles and this same list. The list shows email, display name, role, invite status and created date. A Pending invite can be cancelled and an Expired one renewed; accepted accounts have no row actions, so nobody can be removed or promoted from here. Only the owner can invite, cancel and renew (see "Roles").
|
||||||
|
|
||||||
An invite is **Pending** until its link is used, **Expired** after 3 days, and **Accepted** once the account is created. The list is sorted by created date, newest first.
|
An invite is **Pending** until its link is used, **Expired** after 3 days, and **Accepted** once the account is created. The list is sorted by created date, newest first.
|
||||||
|
|
||||||
|
## Roles
|
||||||
|
|
||||||
|
There are two roles. They are shown as a badge and are not editable.
|
||||||
|
|
||||||
|
| Role | Who | Can |
|
||||||
|
|---|---|---|
|
||||||
|
| owner | The account that registered first on the workspace. There is exactly one. | Everything an admin can, plus invite users, cancel invites and renew invites. |
|
||||||
|
| admin | Everyone who joined through an invite. Every invite creates an admin. | Read and write articles, see the Users list, edit their own profile, see Settings. |
|
||||||
|
|
||||||
|
The owner is the only difference for now. The role cannot be changed, transferred or removed from the UI.
|
||||||
|
|
||||||
|
**Not drawn by the board** (decide in the spec, cover by Vitest and Go tests only, like the 429 on invite):
|
||||||
|
|
||||||
|
- What a non-owner sees: the recommendation is to hide "Invite user" (desktop and mobile), hide the row actions, and hide the "Invite someone…" hint on the "Only you" state.
|
||||||
|
- The API answer when a non-owner calls an owner-only endpoint: the recommendation is 403 with a plain-text body, and no state change.
|
||||||
|
- The message if the owner's session sees a 403 anyway (role changed under it): the global 403 handling applies.
|
||||||
|
|
||||||
## The list
|
## The list
|
||||||
|
|
||||||
| Column | Content |
|
| Column | Content |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Username | An accepted user: the display name if there is one (medium weight, highlighted) with the username beside it in muted text; otherwise the username alone. A pending or expired invite: the email address, regular weight, toned. The current user's row carries a muted mono "you" tag. |
|
| Email | The account's or invite's email address, medium weight, highlighted. The current user's row carries a muted mono "you" tag after it. |
|
||||||
|
| Display name | The display name when set, highlighted; a muted dash `—` when not. An invite has none, so it shows the dash. Your own row follows your saved name. |
|
||||||
|
| Role | A mono 11 px badge, 20 px high: `owner` (filled, `--ui-primary` with `--ui-bg` text) or `admin` (transparent, toned text, `--ui-border-accented` border). An invite shows the role it will create, `admin`. |
|
||||||
| Invite status | A badge: Accepted (circle-check, success), Pending (mail, warning), Expired (clock-alert, outline, muted). Shown by icon and word as well as color. |
|
| Invite status | A badge: Accepted (circle-check, success), Pending (mail, warning), Expired (clock-alert, outline, muted). Shown by icon and word as well as color. |
|
||||||
| Created | The date as `27 Sep 2026`, or "Today" for the current day. For an invite it is the day the invite was sent, for a user the day the account was created. |
|
| Created | The date as `27 Sep 2026`, or "Today" for the current day. For an invite it is the day the invite was sent (or last renewed), for a user the day the account was created. |
|
||||||
|
| (actions) | Right-aligned, no header text. Pending row: "Cancel invite". Expired row: "Renew invite". Accepted row: empty. |
|
||||||
|
|
||||||
Desktop is a table: 36 px header, 44 px rows, columns `minmax(0,1fr) 160px 160px`. Below md it becomes a card list (68 px minimum row height): the name line, then the badge and "Created {date}". The page header is a title "Users" with the subtitle "Everyone who can sign in and work on your articles." and a primary "Invite user" button (user-plus icon) on its right. On mobile the button becomes a full-width 48 px button pinned to the bottom of the screen.
|
The username is no longer shown in this list.
|
||||||
|
|
||||||
The admin who registered first is always listed, so the list is never empty.
|
Desktop is a table: 36 px header, 48 px rows, columns `minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px` with a 12 px gap. Below md it becomes a card list (68 px minimum row height): the email line (with "you"), the display name below it when there is one, then the role badge, the status badge and "Created {date}" on one line, then the row action, if any, as a 44 px button with 14 px side padding.
|
||||||
|
|
||||||
|
The page header is a title "Users" with the subtitle "Everyone who can sign in and work on your articles." and a primary "Invite user" button (user-plus icon) on its right. On mobile the button becomes a full-width 48 px button pinned to the bottom of the screen.
|
||||||
|
|
||||||
|
The owner is always listed, so the list is never empty.
|
||||||
|
|
||||||
|
### Row actions
|
||||||
|
|
||||||
|
| Action | Shown on | Icon | Look |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Cancel invite | Pending | user-x | Outline button, text in `--ui-error` |
|
||||||
|
| Renew invite | Expired | refresh-cw | Outline button, text `--ui-text-highlighted` |
|
||||||
|
|
||||||
|
Desktop buttons are 28 px high, 12 px medium text, a 13 px icon, 9 px side padding, `--ui-border-accented` border, `--ui-bg` fill. Mobile buttons are 44 px high and 14 px side padding with a 14 px icon.
|
||||||
|
|
||||||
|
- **Cancel invite** asks first with a danger confirmation dialog, since it cannot be undone from here (the address can be invited again).
|
||||||
|
- **Renew invite** asks nothing, since it only sends an email. While the request runs, that row's button reads "Renewing…" with a loader-circle icon at 50 % opacity and is disabled. Only that row is busy.
|
||||||
|
|
||||||
## States
|
## States
|
||||||
|
|
||||||
@@ -27,21 +63,28 @@ The admin who registered first is always listed, so the list is never empty.
|
|||||||
**Trigger:** The list loaded, newest first.
|
**Trigger:** The list loaded, newest first.
|
||||||
|
|
||||||
- Breadcrumbs: Users (mobile title "Users")
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
- Rows: `sam.oliveira@renew.example` Pending, 27 Sep 2026 · `p.huber@gmail.com` Expired, 3 Aug 2026 · `ines` (display name "Inès Duarte") Accepted, 18 Jun 2026 · `jonas` Accepted, 2 Apr 2026 · `marta` (you) Accepted, 12 Mar 2026
|
- Rows:
|
||||||
|
- `sam.oliveira@renew.example`, no display name, admin, Pending, 27 Sep 2026, "Cancel invite"
|
||||||
|
- `p.huber@gmail.com`, display name "Paul Huber", admin, Expired, 3 Aug 2026, "Renew invite"
|
||||||
|
- `ines.duarte@renew.example`, "Inès Duarte", admin, Accepted, 18 Jun 2026
|
||||||
|
- `jonas@renew.example`, no display name, admin, Accepted, 2 Apr 2026
|
||||||
|
- `marta@renew.example` (you), no display name, owner, Accepted, 12 Mar 2026
|
||||||
|
|
||||||
|
The board gives the Expired invite a display name. A real invite has none, so the SPA renders whatever `display_name` the item carries and the dash when it is empty.
|
||||||
|
|
||||||
### Loading
|
### Loading
|
||||||
|
|
||||||
**Trigger:** The first load, or a retry. Skeletons appear after 150 ms.
|
**Trigger:** The first load, or a retry. Skeletons appear after 150 ms.
|
||||||
|
|
||||||
- Breadcrumbs: Users (mobile title "Users")
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
- Five skeleton rows
|
- Five skeleton rows, one bar per column, plus a role-badge and a status-badge placeholder
|
||||||
|
|
||||||
### Only you
|
### Only you
|
||||||
|
|
||||||
**Trigger:** Nobody has been invited yet. The admin who registered is always listed.
|
**Trigger:** Nobody has been invited yet. The owner is always listed.
|
||||||
|
|
||||||
- Breadcrumbs: Users (mobile title "Users")
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
- One row: `marta` (you) Accepted
|
- One row: `marta@renew.example` (you), owner, Accepted
|
||||||
- Hint under the list: "Invite someone so they can sign in with their own account instead of sharing yours."
|
- Hint under the list: "Invite someone so they can sign in with their own account instead of sharing yours."
|
||||||
|
|
||||||
### Error
|
### Error
|
||||||
@@ -111,14 +154,79 @@ The admin who registered first is always listed, so the list is never empty.
|
|||||||
**Trigger:** 201: the dialog closes, the new invite appears at the top as Pending (highlighted row), and a toast confirms.
|
**Trigger:** 201: the dialog closes, the new invite appears at the top as Pending (highlighted row), and a toast confirms.
|
||||||
|
|
||||||
- Breadcrumbs: Users (mobile title "Users")
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
- New first row: `lea.martin@renew.example` Pending, created "Today", row background `--ui-bg-elevated`
|
- New first row: `lea.martin@renew.example`, no display name, admin, Pending, created "Today", row background `--ui-bg-elevated`, with "Cancel invite"
|
||||||
- Toast (success, circle-check): **Invite sent** "lea.martin@renew.example has 3 days to accept."
|
- Toast (success, circle-check): **Invite sent** "lea.martin@renew.example has 3 days to accept."
|
||||||
|
|
||||||
The "Today" label makes this state clock-sensitive, so `task visual:check` skips it.
|
The "Today" label makes this state clock-sensitive, so `task visual:check` skips it.
|
||||||
|
|
||||||
|
### Cancel invite: confirm
|
||||||
|
|
||||||
|
**Trigger:** "Cancel invite" on a Pending row.
|
||||||
|
|
||||||
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
|
- Modal (danger): **Cancel this invite?**
|
||||||
|
- text "The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later."
|
||||||
|
- cancel "Keep invite"
|
||||||
|
- confirm "Cancel invite"
|
||||||
|
|
||||||
|
### Cancel invite: sending
|
||||||
|
|
||||||
|
**Trigger:** Request in flight. Both buttons are disabled and the dialog can't be dismissed.
|
||||||
|
|
||||||
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
|
- Modal (danger): **Cancel this invite?** (same text)
|
||||||
|
- cancel "Keep invite", disabled
|
||||||
|
- confirm "Cancelling…", loading
|
||||||
|
|
||||||
|
### Cancel invite: failed
|
||||||
|
|
||||||
|
**Trigger:** 500 or network failure. The dialog stays open.
|
||||||
|
|
||||||
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
|
- Modal (danger): **Cancel this invite?** (same text)
|
||||||
|
- notice "Couldn't cancel the invite. Try again in a moment."
|
||||||
|
- cancel "Keep invite"
|
||||||
|
- confirm "Cancel invite"
|
||||||
|
|
||||||
|
### Cancel invite: done
|
||||||
|
|
||||||
|
**Trigger:** 204: the row disappears and a toast confirms.
|
||||||
|
|
||||||
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
|
- The Pending row `sam.oliveira@renew.example` is gone; the other four remain
|
||||||
|
- Toast (success, circle-check): **Invite cancelled** "sam.oliveira@renew.example can no longer use the link."
|
||||||
|
|
||||||
|
### Renew invite: sending
|
||||||
|
|
||||||
|
**Trigger:** "Renew invite" on an Expired row. No confirmation, since it only sends an email. The button shows progress and is disabled.
|
||||||
|
|
||||||
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
|
- The Expired row's button reads "Renewing…" with a loader-circle icon, 50 % opacity, disabled
|
||||||
|
|
||||||
|
### Renew invite: done
|
||||||
|
|
||||||
|
**Trigger:** 200: the row becomes Pending with today's date, moves to the top, and the old link stops working.
|
||||||
|
|
||||||
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
|
- First row: `p.huber@gmail.com` Pending, created "Today", row background `--ui-bg-elevated`, now with "Cancel invite"
|
||||||
|
- Toast (success, circle-check): **Invite renewed** "p.huber@gmail.com has 3 days to accept the new link."
|
||||||
|
|
||||||
|
The "Today" label makes this state clock-sensitive, so `task visual:check` skips it.
|
||||||
|
|
||||||
|
### Renew invite: failed
|
||||||
|
|
||||||
|
**Trigger:** 500 or network failure. The row stays Expired and the button can be pressed again.
|
||||||
|
|
||||||
|
- Breadcrumbs: Users (mobile title "Users")
|
||||||
|
- Toast (error, circle-x): **Couldn't renew the invite** "Try again in a moment."
|
||||||
|
|
||||||
## Notes for implementation
|
## Notes for implementation
|
||||||
|
|
||||||
- An accepted user is shown by username and display name only, never by email.
|
- Accepted users are now listed by email, display name and role. This reverses the earlier rule that a user is never listed with an email.
|
||||||
- How display names look in this list is the state "Display names in the Users list" of [profile.md](profile.md). The board draws it in the Profile group, and `task visual:check` finds states by group.
|
- How display names look in this list is the state "Display names in the Users list" of [profile.md](profile.md). The board draws it in the Profile group, and `task visual:check` finds states by group.
|
||||||
|
- The board's API line marks both new endpoints "(pending)", meaning "not built yet". Cancel applies to a Pending invite. Renew is drawn on an Expired one; the recommendation is that the API also accepts a Pending one (it resets the 3 days and replaces the link) and refuses an Accepted one with 409. The SPA only offers Renew on Expired rows.
|
||||||
|
- Renewing replaces the code and expiry, resets the created date to now, and sends the invitation email again. The old link stops working. The email is specified in [emails.md](../emails.md).
|
||||||
|
- A 404 on cancel or renew (the invite was already used or cancelled elsewhere) is not drawn. Decide it in the spec; the recommendation is to drop the row and toast the outcome.
|
||||||
- 429 on the invite request is not drawn. Decide it in the spec before coding.
|
- 429 on the invite request is not drawn. Decide it in the spec before coding.
|
||||||
- The email the invite sends is specified in [emails.md](../emails.md). The screen the link opens is in [accept-invite.md](accept-invite.md).
|
- The email the invite sends is specified in [emails.md](../emails.md). The screen the link opens is in [accept-invite.md](accept-invite.md).
|
||||||
|
- The role rules and what is not drawn are in "Roles" above.
|
||||||
@@ -18,7 +18,7 @@
|
|||||||
<sc-if value="{{ s.boot }}"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px"><span style="width:26px;height:26px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></div></sc-if>
|
<sc-if value="{{ s.boot }}"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px"><span style="width:26px;height:26px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></div></sc-if>
|
||||||
<sc-if value="{{ notBoot }}"><div data-act="usermenu" role="button" aria-haspopup="menu" aria-expanded="{{ menuOpen }}" title="Account" style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;background:{{ chipBg }};color:{{ chipFg }}"><span style="width:26px;height:26px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 11px 'IBM Plex Sans',sans-serif">{{ ini }}</span><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500">{{ who }}</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat"></span></div></sc-if>
|
<sc-if value="{{ notBoot }}"><div data-act="usermenu" role="button" aria-haspopup="menu" aria-expanded="{{ menuOpen }}" title="Account" style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;background:{{ chipBg }};color:{{ chipFg }}"><span style="width:26px;height:26px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 11px 'IBM Plex Sans',sans-serif">{{ ini }}</span><span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500">{{ who }}</span><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevrons-up-down.svg') center / contain no-repeat"></span></div></sc-if>
|
||||||
</div>
|
</div>
|
||||||
<sc-if value="{{ deskMenu }}"><div role="menu" aria-label="Account" style="position:absolute;left:12px;bottom:56px;z-index:40;width:224px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px"><div style="padding:8px 8px 10px;display:flex;flex-direction:column;gap:2px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="font-weight:600;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ who }}</span><span style="font-size:12px;color:var(--ui-text-muted)">marta@renew.example</span></div><div data-act="nav-profile" role="menuitem" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:10px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:10px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></sc-if>
|
<sc-if value="{{ deskMenu }}"><div role="menu" aria-label="Account" style="position:absolute;left:12px;bottom:56px;z-index:40;width:224px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop);padding:4px"><div style="padding:8px 8px 10px;display:flex;flex-direction:column;gap:2px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="font-weight:600;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ who }}</span><span style="font-size:12px;color:var(--ui-text-muted)">marta@renew.example</span></div><div data-act="nav-profile" role="menuitem" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:10px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><sc-for list="{{ themeSeg }}" as="m" hint-placeholder-count="3"><div data-act="{{ m.act }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:32px;padding:0 8px;display:flex;align-items:center;justify-content:space-between;font-size:14px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:32px;padding:0 8px;display:flex;align-items:center;gap:10px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></sc-if>
|
||||||
</sc-if>
|
</sc-if>
|
||||||
<div style="flex:1;min-width:0;min-height:0;display:flex;flex-direction:column">
|
<div style="flex:1;min-width:0;min-height:0;display:flex;flex-direction:column">
|
||||||
<sc-if value="{{ desk }}" hint-placeholder-val="{{ true }}">
|
<sc-if value="{{ desk }}" hint-placeholder-val="{{ true }}">
|
||||||
@@ -202,11 +202,11 @@
|
|||||||
<sc-if value="{{ usError }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><div style="flex:1;display:flex;flex-direction:column;gap:8px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Couldn't load users</span><span style="color:var(--ui-text-toned)">Check your connection and try again.</span></div><span style="align-self:flex-start;height:{{ btnH }};padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;font-size:12px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat"></span>Try again</span></div></div></sc-if>
|
<sc-if value="{{ usError }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><div style="flex:1;display:flex;flex-direction:column;gap:8px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Couldn't load users</span><span style="color:var(--ui-text-toned)">Check your connection and try again.</span></div><span style="align-self:flex-start;height:{{ btnH }};padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;font-size:12px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat"></span>Try again</span></div></div></sc-if>
|
||||||
<sc-if value="{{ usTable }}">
|
<sc-if value="{{ usTable }}">
|
||||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
|
<div style="background:var(--ui-bg);border:1px solid var(--ui-border)">
|
||||||
<div style="display:grid;grid-template-columns:minmax(0,1fr) 160px 160px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Username</span><span>Invite status</span><span style="display:flex;align-items:center;gap:4px;color:var(--ui-text-highlighted)">Created<span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/arrow-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/arrow-down.svg') center / contain no-repeat"></span></span></div>
|
<div style="display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px;gap:12px;height:36px;align-items:center;padding:0 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Email</span><span>Display name</span><span>Role</span><span>Invite status</span><span style="display:flex;align-items:center;gap:4px;color:var(--ui-text-highlighted)">Created<span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/arrow-down.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/arrow-down.svg') center / contain no-repeat"></span></span><span></span></div>
|
||||||
<sc-for list="{{ usRows }}" as="r" hint-placeholder-count="5">
|
<sc-for list="{{ usRows }}" as="r" hint-placeholder-count="5">
|
||||||
<div style="display:grid;grid-template-columns:minmax(0,1fr) 160px 160px;height:44px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:{{ r.bg }}">
|
<div style="display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px;gap:12px;height:48px;align-items:center;padding:0 12px;border-top:1px solid var(--ui-border);background:{{ r.bg }}">
|
||||||
<sc-if value="{{ r.skel }}"><span style="height:12px;width:30%;background:var(--ui-bg-accented)"></span><span style="width:76px;height:20px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></sc-if>
|
<sc-if value="{{ r.skel }}"><span style="height:12px;width:60%;background:var(--ui-bg-accented)"></span><span style="height:12px;width:50%;background:var(--ui-bg-accented)"></span><span style="width:52px;height:20px;background:var(--ui-bg-accented)"></span><span style="width:76px;height:20px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></sc-if>
|
||||||
<sc-if value="{{ r.name }}"><span style="display:flex;align-items:center;gap:8px;min-width:0;padding-right:12px"><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:{{ r.fw }};color:{{ r.fg }}">{{ r.name }}</span><sc-if value="{{ r.sub }}"><span style="flex-shrink:0;color:var(--ui-text-muted)">{{ r.sub }}</span></sc-if><sc-if value="{{ r.you }}"><span style="flex-shrink:0;font:500 11px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">you</span></sc-if></span><span><span style="height:22px;padding:0 7px;display:inline-flex;align-items:center;gap:4px;background:{{ r.b.bg }};color:{{ r.b.fg }};border:1px solid {{ r.b.bd }};font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat"></span>{{ r.b.t }}</span></span><span style="color:var(--ui-text-muted)">{{ r.c }}</span></sc-if>
|
<sc-if value="{{ r.email }}"><span style="display:flex;align-items:center;gap:8px;min-width:0"><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;color:{{ r.fg }}">{{ r.email }}</span><sc-if value="{{ r.you }}"><span style="flex-shrink:0;font:500 11px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">you</span></sc-if></span><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:{{ r.dfg }}">{{ r.dn }}</span><span><span style="height:20px;padding:0 7px;display:inline-flex;align-items:center;background:{{ r.rl.bg }};color:{{ r.rl.fg }};border:1px solid {{ r.rl.bd }};font:500 11px 'IBM Plex Mono',monospace">{{ r.rl.t }}</span></span><span><span style="height:22px;padding:0 7px;display:inline-flex;align-items:center;gap:4px;background:{{ r.b.bg }};color:{{ r.b.fg }};border:1px solid {{ r.b.bd }};font-size:12px;font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat"></span>{{ r.b.t }}</span></span><span style="color:var(--ui-text-muted)">{{ r.c }}</span><span style="display:flex;justify-content:flex-end"><sc-if value="{{ r.act }}"><span data-act="{{ r.act.key }}" style="height:28px;padding:0 9px;white-space:nowrap;flex-shrink:0;display:inline-flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ r.act.fg }};font-weight:500;font-size:12px;opacity:{{ r.act.op }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:13px;height:13px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ r.act.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.act.icon }}.svg') center / contain no-repeat"></span>{{ r.act.t }}</span></sc-if></span></sc-if>
|
||||||
</div>
|
</div>
|
||||||
</sc-for>
|
</sc-for>
|
||||||
</div>
|
</div>
|
||||||
@@ -216,7 +216,7 @@
|
|||||||
<sc-for list="{{ usRows }}" as="r" hint-placeholder-count="5">
|
<sc-for list="{{ usRows }}" as="r" hint-placeholder-count="5">
|
||||||
<div style="display:flex;flex-direction:column;justify-content:center;gap:6px;padding:12px 16px;border-bottom:1px solid var(--ui-border);min-height:68px;background:{{ r.bg }}">
|
<div style="display:flex;flex-direction:column;justify-content:center;gap:6px;padding:12px 16px;border-bottom:1px solid var(--ui-border);min-height:68px;background:{{ r.bg }}">
|
||||||
<sc-if value="{{ r.skel }}"><span style="width:55%;height:14px;background:var(--ui-bg-accented)"></span><span style="width:40%;height:12px;background:var(--ui-bg-accented)"></span></sc-if>
|
<sc-if value="{{ r.skel }}"><span style="width:55%;height:14px;background:var(--ui-bg-accented)"></span><span style="width:40%;height:12px;background:var(--ui-bg-accented)"></span></sc-if>
|
||||||
<sc-if value="{{ r.name }}"><span style="display:flex;align-items:center;gap:8px;min-width:0"><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:15px;line-height:21px;font-weight:{{ r.fw }};color:{{ r.fg }}">{{ r.name }}</span><sc-if value="{{ r.sub }}"><span style="flex-shrink:0;color:var(--ui-text-muted)">{{ r.sub }}</span></sc-if><sc-if value="{{ r.you }}"><span style="flex-shrink:0;font:500 11px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">you</span></sc-if></span><div style="display:flex;align-items:center;gap:10px;font-size:12px;color:var(--ui-text-muted)"><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;background:{{ r.b.bg }};color:{{ r.b.fg }};border:1px solid {{ r.b.bd }};font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat"></span>{{ r.b.t }}</span><span>Created {{ r.c }}</span></div></sc-if>
|
<sc-if value="{{ r.email }}"><span style="display:flex;align-items:center;gap:8px;min-width:0"><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:15px;line-height:21px;font-weight:500;color:{{ r.fg }}">{{ r.email }}</span><sc-if value="{{ r.you }}"><span style="flex-shrink:0;font:500 11px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">you</span></sc-if></span><sc-if value="{{ r.display2 }}"><span style="color:var(--ui-text-toned)">{{ r.dn }}</span></sc-if><div style="display:flex;align-items:center;gap:8px;font-size:12px;color:var(--ui-text-muted)"><span style="height:20px;padding:0 7px;display:inline-flex;align-items:center;background:{{ r.rl.bg }};color:{{ r.rl.fg }};border:1px solid {{ r.rl.bd }};font:500 11px 'IBM Plex Mono',monospace">{{ r.rl.t }}</span><span style="height:20px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;background:{{ r.b.bg }};color:{{ r.b.fg }};border:1px solid {{ r.b.bd }};font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:12px;height:12px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.b.icon }}.svg') center / contain no-repeat"></span>{{ r.b.t }}</span><span>Created {{ r.c }}</span></div><sc-if value="{{ r.act }}"><div style="display:flex;padding-top:4px"><span data-act="{{ r.act.key }}" style="height:44px;padding:0 14px;white-space:nowrap;flex-shrink:0;display:inline-flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ r.act.fg }};font-weight:500;font-size:13px;opacity:{{ r.act.op }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ r.act.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ r.act.icon }}.svg') center / contain no-repeat"></span>{{ r.act.t }}</span></div></sc-if></sc-if>
|
||||||
</div>
|
</div>
|
||||||
</sc-for>
|
</sc-for>
|
||||||
</div>
|
</div>
|
||||||
@@ -226,6 +226,13 @@
|
|||||||
<sc-if value="{{ mob }}"><sc-if value="{{ listFab }}"><div data-act="invite" style="position:absolute;left:16px;right:16px;bottom:16px;height:48px;display:flex;align-items:center;justify-content:center;gap:8px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;font-size:15px;box-shadow:var(--rc-shadow-pop)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/user-plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/user-plus.svg') center / contain no-repeat"></span>Invite user</div></sc-if></sc-if>
|
<sc-if value="{{ mob }}"><sc-if value="{{ listFab }}"><div data-act="invite" style="position:absolute;left:16px;right:16px;bottom:16px;height:48px;display:flex;align-items:center;justify-content:center;gap:8px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;font-size:15px;box-shadow:var(--rc-shadow-pop)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/user-plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/user-plus.svg') center / contain no-repeat"></span>Invite user</div></sc-if></sc-if>
|
||||||
</sc-if>
|
</sc-if>
|
||||||
|
|
||||||
|
<sc-if value="{{ isSettings }}">
|
||||||
|
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:20px;max-width:720px;overflow:hidden">
|
||||||
|
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Settings</span><span style="color:var(--ui-text-muted)">Workspace information.</span></div>
|
||||||
|
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;align-items:center;justify-content:space-between;gap:16px"><span style="font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Version</span><span style="font:400 14px/22px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)">v2.2.0-beta</span></div>
|
||||||
|
</div>
|
||||||
|
</sc-if>
|
||||||
|
|
||||||
<sc-if value="{{ isProfile }}">
|
<sc-if value="{{ isProfile }}">
|
||||||
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:20px;max-width:720px;overflow:hidden">
|
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:20px;max-width:720px;overflow:hidden">
|
||||||
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Profile</span><span style="color:var(--ui-text-muted)">Your account on this RenewCMS workspace.</span></div>
|
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Profile</span><span style="color:var(--ui-text-muted)">Your account on this RenewCMS workspace.</span></div>
|
||||||
@@ -263,7 +270,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<sc-if value="{{ mobMenu }}"><div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="menu" aria-label="Account" style="width:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);padding:8px 0 24px"><div style="margin:0 auto 8px;width:36px;height:4px;background:var(--ui-bg-accented)"></div><div style="padding:8px 16px 14px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="width:36px;height:36px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 13px 'IBM Plex Sans',sans-serif">{{ ini }}</span><div style="display:flex;flex-direction:column;min-width:0"><span style="font-weight:600;font-size:15px;color:var(--ui-text-highlighted)">{{ who }}</span><span style="color:var(--ui-text-muted)">marta@renew.example</span></div></div><div data-act="nav-profile" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></div></sc-if>
|
<sc-if value="{{ mobMenu }}"><div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="menu" aria-label="Account" style="width:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);padding:8px 0 24px"><div style="margin:0 auto 8px;width:36px;height:4px;background:var(--ui-bg-accented)"></div><div style="padding:8px 16px 14px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="width:36px;height:36px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 13px 'IBM Plex Sans',sans-serif">{{ ini }}</span><div style="display:flex;flex-direction:column;min-width:0"><span style="font-weight:600;font-size:15px;color:var(--ui-text-highlighted)">{{ who }}</span><span style="color:var(--ui-text-muted)">marta@renew.example</span></div></div><div data-act="nav-profile" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><sc-for list="{{ themeSeg }}" as="m" hint-placeholder-count="3"><div data-act="{{ m.act }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:48px;padding:0 16px;display:flex;align-items:center;justify-content:space-between;font-size:15px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:18px;height:18px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></div></sc-if>
|
||||||
|
|
||||||
<sc-if value="{{ s.modal }}">
|
<sc-if value="{{ s.modal }}">
|
||||||
<div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:{{ modalAlign }};justify-content:center;padding:{{ modalPad }}">
|
<div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:{{ modalAlign }};justify-content:center;padding:{{ modalPad }}">
|
||||||
@@ -336,7 +343,7 @@ class Component extends DCLogic {
|
|||||||
const s = this.props.s || {}
|
const s = this.props.s || {}
|
||||||
const m = !!this.props.mobile
|
const m = !!this.props.mobile
|
||||||
const k = s.kind || 'home'
|
const k = s.kind || 'home'
|
||||||
const navItems = [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['users', 'users', 'Users'], ['integration', 'plug', 'Integration']]
|
const navItems = [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['users', 'users', 'Users'], ['integration', 'plug', 'Integration'], ['settings', 'settings', 'Settings']]
|
||||||
const nav = navItems.map(([key, icon, t]) => ({ key, icon, t, bg: s.nav === key ? 'var(--rc-sand)' : 'transparent', fg: s.nav === key ? '#111111' : 'var(--ui-text-toned)', fw: s.nav === key ? 500 : 400 }))
|
const nav = navItems.map(([key, icon, t]) => ({ key, icon, t, bg: s.nav === key ? 'var(--rc-sand)' : 'transparent', fg: s.nav === key ? '#111111' : 'var(--ui-text-toned)', fw: s.nav === key ? 500 : 400 }))
|
||||||
const crumbs = (s.crumbs || []).map((t, i, a) => ({ t, sep: i > 0, fg: i === a.length - 1 ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', fw: i === a.length - 1 ? 500 : 400 }))
|
const crumbs = (s.crumbs || []).map((t, i, a) => ({ t, sep: i > 0, fg: i === a.length - 1 ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', fw: i === a.length - 1 ? 500 : 400 }))
|
||||||
const L = s.list || {}
|
const L = s.list || {}
|
||||||
@@ -390,7 +397,9 @@ class Component extends DCLogic {
|
|||||||
}
|
}
|
||||||
const US = s.users || {}
|
const US = s.users || {}
|
||||||
const badges = { accepted: { t: 'Accepted', icon: 'circle-check', bg: 'var(--rc-success-soft)', fg: 'var(--ui-success)', bd: 'var(--rc-success-soft)' }, pending: { t: 'Pending', icon: 'mail', bg: 'var(--rc-warning-soft)', fg: 'var(--ui-warning)', bd: 'var(--rc-warning-soft)' }, expired: { t: 'Expired', icon: 'clock-alert', bg: 'transparent', fg: 'var(--ui-text-muted)', bd: 'var(--ui-border-accented)' } }
|
const badges = { accepted: { t: 'Accepted', icon: 'circle-check', bg: 'var(--rc-success-soft)', fg: 'var(--ui-success)', bd: 'var(--rc-success-soft)' }, pending: { t: 'Pending', icon: 'mail', bg: 'var(--rc-warning-soft)', fg: 'var(--ui-warning)', bd: 'var(--rc-warning-soft)' }, expired: { t: 'Expired', icon: 'clock-alert', bg: 'transparent', fg: 'var(--ui-text-muted)', bd: 'var(--ui-border-accented)' } }
|
||||||
const usRows = (US.loading ? Array.from({ length: 5 }, () => ({ skel: true })) : (US.rows || [])).map(r => r.skel ? r : ({ ...r, name: (r.you && s.display) || r.display || r.u || r.email, sub: r.u && ((r.you && s.display) || r.display) ? r.u : '', fw: r.u ? 500 : 400, fg: r.u ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)', b: badges[r.st] || badges.pending, bg: r.hl ? 'var(--ui-bg-elevated)' : 'transparent' }))
|
const roles = { owner: { t: 'owner', bg: 'var(--ui-primary)', fg: 'var(--ui-bg)', bd: 'var(--ui-primary)' }, admin: { t: 'admin', bg: 'transparent', fg: 'var(--ui-text-toned)', bd: 'var(--ui-border-accented)' } }
|
||||||
|
const acts = { pending: { key: 'cancel-invite', t: 'Cancel invite', icon: 'user-x', fg: 'var(--ui-error)', op: '1' }, expired: { key: 'renew-invite', t: 'Renew invite', icon: 'refresh-cw', fg: 'var(--ui-text-highlighted)', op: '1' } }
|
||||||
|
const usRows = (US.loading ? Array.from({ length: 5 }, () => ({ skel: true })) : (US.rows || [])).map(r => { if (r.skel) return r; const dn = (r.you && s.display) || r.display || ''; const a0 = acts[r.st]; return { ...r, dn: dn || '—', dfg: dn ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', display2: !!dn, fg: 'var(--ui-text-highlighted)', rl: roles[r.role] || roles.admin, b: badges[r.st] || badges.pending, bg: r.hl ? 'var(--ui-bg-elevated)' : 'transparent', act: a0 && (r.busy ? { ...a0, t: r.busy, icon: 'loader-circle', op: '0.5' } : a0) } })
|
||||||
const who = s.display || 'marta'
|
const who = s.display || 'marta'
|
||||||
const ini = s.display ? s.display.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase() : 'MA'
|
const ini = s.display ? s.display.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase() : 'MA'
|
||||||
const pf = s.pf || {}
|
const pf = s.pf || {}
|
||||||
@@ -414,9 +423,9 @@ class Component extends DCLogic {
|
|||||||
const edTitle = e.title || 'How we price a bathroom renovation'
|
const edTitle = e.title || 'How we price a bathroom renovation'
|
||||||
return {
|
return {
|
||||||
cr, s, nav, crumbs, who, ini, pf, dn, dnSave, rsNote, rsBtn,
|
cr, s, nav, crumbs, who, ini, pf, dn, dnSave, rsNote, rsBtn,
|
||||||
menuOpen: !!s.userMenu, deskMenu: !m && !!s.userMenu, mobMenu: m && !!s.userMenu, pfItemBg: 'var(--ui-bg-elevated)',
|
themeSeg: [['system','monitor','System'],['light','sun','Light'],['dark','moon','Dark']].map(([k,icon,tt])=>{const on=(s.mode||'light')===k;return {act:'theme-'+k,icon,t:tt,on,op:on?1:0}}), menuOpen: !!s.userMenu, deskMenu: !m && !!s.userMenu, mobMenu: m && !!s.userMenu, pfItemBg: 'var(--ui-bg-elevated)',
|
||||||
chipBg: s.userMenu || s.nav === 'profile' ? 'var(--rc-sand)' : 'transparent', chipFg: s.userMenu || s.nav === 'profile' ? '#111111' : 'var(--ui-text-highlighted)',
|
chipBg: s.userMenu || s.nav === 'profile' ? 'var(--rc-sand)' : 'transparent', chipFg: s.userMenu || s.nav === 'profile' ? '#111111' : 'var(--ui-text-highlighted)',
|
||||||
isProfile: k === 'profile', pfLoading: k === 'profile' && !!pf.loading, pfReady: k === 'profile' && !pf.loading,
|
isSettings: k === 'settings', isProfile: k === 'profile', pfLoading: k === 'profile' && !!pf.loading, pfReady: k === 'profile' && !pf.loading,
|
||||||
cardPad: m ? '16px' : '20px', cardPadX: m ? '16px' : '20px', inH: m ? '44px' : '40px', pfCols: m ? 'minmax(0,1fr)' : 'minmax(0,1fr) minmax(0,1.4fr)', pwDir: m ? 'column' : 'row', pwAlign: m ? 'stretch' : 'flex-end', edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar,
|
cardPad: m ? '16px' : '20px', cardPadX: m ? '16px' : '20px', inH: m ? '44px' : '40px', pfCols: m ? 'minmax(0,1fr)' : 'minmax(0,1fr) minmax(0,1.4fr)', pwDir: m ? 'column' : 'row', pwAlign: m ? 'stretch' : 'flex-end', edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar,
|
||||||
desk: !m, mob: m, notBoot: !s.boot,
|
desk: !m, mob: m, notBoot: !s.boot,
|
||||||
fw: m ? '390px' : '1440px', fh: m ? '844px' : '900px', dir: m ? 'column' : 'row',
|
fw: m ? '390px' : '1440px', fh: m ? '844px' : '900px', dir: m ? 'column' : 'row',
|
||||||
|
|||||||
@@ -187,6 +187,7 @@ class Component extends DCLogic {
|
|||||||
act(a) {
|
act(a) {
|
||||||
const s = this.state
|
const s = this.state
|
||||||
if (a === 'usermenu') return this.setState({ userMenu: !s.userMenu })
|
if (a === 'usermenu') return this.setState({ userMenu: !s.userMenu })
|
||||||
|
if (a && a.startsWith('theme-')) return this.setState({ mode: a.slice(6) })
|
||||||
if (s.userMenu) this.setState({ userMenu: false })
|
if (s.userMenu) this.setState({ userMenu: false })
|
||||||
if (a === 'pf-reset') return this.setState({ pfReset: 'sent' })
|
if (a === 'pf-reset') return this.setState({ pfReset: 'sent' })
|
||||||
if (a === 'mnav-close') return this.setState({ mnav: false })
|
if (a === 'mnav-close') return this.setState({ mnav: false })
|
||||||
@@ -428,7 +429,7 @@ class Component extends DCLogic {
|
|||||||
devices: devs, modes, flows, hint, tools,
|
devices: devs, modes, flows, hint, tools,
|
||||||
hs: s.hs, hsClass: s.hs ? 'hs' : '', hsJust: s.hs ? 'flex-end' : 'flex-start', hsBg: s.hs ? 'var(--ui-primary)' : 'var(--ui-bg-accented)', toggleHs: () => this.setState({ hs: !s.hs }),
|
hs: s.hs, hsClass: s.hs ? 'hs' : '', hsJust: s.hs ? 'flex-end' : 'flex-start', hsBg: s.hs ? 'var(--ui-primary)' : 'var(--ui-bg-accented)', toggleHs: () => this.setState({ hs: !s.hs }),
|
||||||
mobile, isAuth, isApp, isEmail,
|
mobile, isAuth, isApp, isEmail,
|
||||||
authS: isAuth ? this.authS() : {}, appS: isApp ? { ...this.appS(), userMenu: s.userMenu } : {},
|
authS: isAuth ? this.authS() : {}, appS: isApp ? { ...this.appS(), userMenu: s.userMenu, mode: s.mode } : {},
|
||||||
authBg: mobile ? 'var(--ui-bg)' : 'var(--ui-bg-muted)', authTop: mobile ? '40px' : '108px',
|
authBg: mobile ? 'var(--ui-bg)' : 'var(--ui-bg-muted)', authTop: mobile ? '40px' : '108px',
|
||||||
emailHtml: isEmail ? this.emailHtml() : '', emailSubject: s.email === 'reset' ? 'Reset your RenewCMS password' : 'Verify your RenewCMS account',
|
emailHtml: isEmail ? this.emailHtml() : '', emailSubject: s.email === 'reset' ? 'Reset your RenewCMS password' : 'Verify your RenewCMS account',
|
||||||
devW: dw + 'px', devH: dh + 'px', zoom: s.zoom, boxW: Math.round(dw * s.zoom) + 'px', boxH: Math.round(dh * s.zoom) + 'px',
|
devW: dw + 'px', devH: dh + 'px', zoom: s.zoom, boxW: Math.round(dw * s.zoom) + 'px', boxH: Math.round(dh * s.zoom) + 'px',
|
||||||
|
|||||||
@@ -96,11 +96,11 @@ class Component extends DCLogic {
|
|||||||
const cropM = crop => ({ title: 'Crop and resize', desc: 'north-wall.jpg · 3.9 MB', close: true, crop, cancel: 'Choose another file', confirm: 'Upload image' })
|
const cropM = crop => ({ title: 'Crop and resize', desc: 'north-wall.jpg · 3.9 MB', close: true, crop, cancel: 'Choose another file', confirm: 'Upload image' })
|
||||||
const del = (loading, err) => ({ title: 'Delete this article?', desc: '"Winter checklist for timber windows" and its 3 images will be deleted. This can\'t be undone.', cancel: 'Cancel', confirm: loading ? 'Deleting…' : 'Delete article', tone: 'danger', loading, notice: err })
|
const del = (loading, err) => ({ title: 'Delete this article?', desc: '"Winter checklist for timber windows" and its 3 images will be deleted. This can\'t be undone.', cancel: 'Cancel', confirm: loading ? 'Deleting…' : 'Delete article', tone: 'danger', loading, notice: err })
|
||||||
const people = [
|
const people = [
|
||||||
{ email: 'sam.oliveira@renew.example', st: 'pending', c: '27 Sep 2026' },
|
{ email: 'sam.oliveira@renew.example', role: 'admin', st: 'pending', c: '27 Sep 2026' },
|
||||||
{ email: 'p.huber@gmail.com', st: 'expired', c: '3 Aug 2026' },
|
{ email: 'p.huber@gmail.com', display: 'Paul Huber', role: 'admin', st: 'expired', c: '3 Aug 2026' },
|
||||||
{ u: 'ines', display: 'Inès Duarte', st: 'accepted', c: '18 Jun 2026' },
|
{ email: 'ines.duarte@renew.example', display: 'Inès Duarte', role: 'admin', st: 'accepted', c: '18 Jun 2026' },
|
||||||
{ u: 'jonas', st: 'accepted', c: '2 Apr 2026' },
|
{ email: 'jonas@renew.example', role: 'admin', st: 'accepted', c: '2 Apr 2026' },
|
||||||
{ u: 'marta', st: 'accepted', c: '12 Mar 2026', you: true }
|
{ email: 'marta@renew.example', role: 'owner', st: 'accepted', c: '12 Mar 2026', you: true }
|
||||||
]
|
]
|
||||||
const U = (o = {}) => ({ kind: 'users', nav: 'users', crumbs: ['Users'], mTitle: 'Users', ...o, users: { rows: people, ...(o.users || {}) } })
|
const U = (o = {}) => ({ kind: 'users', nav: 'users', crumbs: ['Users'], mTitle: 'Users', ...o, users: { rows: people, ...(o.users || {}) } })
|
||||||
const inv = (o = {}) => ({ title: 'Invite a user', desc: 'We\'ll email them a link to choose a username and password. The link expires after 3 days.', close: true, cancel: 'Cancel', confirm: 'Send invite', ...o, fields: o.fields || [{ label: 'Email', ph: 'name@example.com', focus: true }] })
|
const inv = (o = {}) => ({ title: 'Invite a user', desc: 'We\'ll email them a link to choose a username and password. The link expires after 3 days.', close: true, cancel: 'Cancel', confirm: 'Send invite', ...o, fields: o.fields || [{ label: 'Email', ph: 'name@example.com', focus: true }] })
|
||||||
@@ -168,7 +168,7 @@ class Component extends DCLogic {
|
|||||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: 'Default', trigger: 'Opened from the sidebar or the Home card.' }),
|
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: 'Default', trigger: 'Opened from the sidebar or the Home card.' }),
|
||||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', copied: true, name: 'Copied', trigger: 'The base URL was copied. The button reads "Copied" for 2 s and this is announced.' })
|
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', copied: true, name: 'Copied', trigger: 'The base URL was copied. The button reads "Copied" for 2 s and this is announced.' })
|
||||||
] },
|
] },
|
||||||
{ label: 'Users', title: 'Users', route: '/users', api: 'GET /v1/user/ · POST /v1/user/invite', note: 'One shared workspace: every user sees the same articles and this same list. Rows have no actions yet. Pending and expired invites show the email address, because a username only exists once the invite is accepted. An invite is Pending until its link is used, Expired after 3 days, and Accepted once the account is created.', states: [
|
{ label: 'Users', title: 'Users', route: '/users', api: 'GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id (pending) · POST /v1/user/invite/:id/renew (pending)', note: 'One shared workspace: every user sees the same articles and this same list. Columns: email, display name, role (owner or admin), invite status and created date. A pending invite can be cancelled and an expired one renewed; accepted accounts have no row actions. An invite is Pending until its link is used, Expired after 3 days, and Accepted once the account is created.', states: [
|
||||||
withM({ ...U(), name: 'Default', trigger: 'The list loaded, newest first.' }),
|
withM({ ...U(), name: 'Default', trigger: 'The list loaded, newest first.' }),
|
||||||
withM({ ...U({ users: { loading: true } }), name: 'Loading', trigger: 'The first load, or a retry. Skeletons appear after 150 ms.' }),
|
withM({ ...U({ users: { loading: true } }), name: 'Loading', trigger: 'The first load, or a retry. Skeletons appear after 150 ms.' }),
|
||||||
withM({ ...U({ users: { rows: people.slice(-1), only: true } }), name: 'Only you', trigger: 'Nobody has been invited yet. The admin who registered is always listed.' }),
|
withM({ ...U({ users: { rows: people.slice(-1), only: true } }), name: 'Only you', trigger: 'Nobody has been invited yet. The admin who registered is always listed.' }),
|
||||||
@@ -178,7 +178,17 @@ class Component extends DCLogic {
|
|||||||
withM({ ...U({ modal: inv({ loading: true, confirm: 'Sending…', fields: invF('lea.martin@renew.example') }) }), name: 'Invite: sending', trigger: 'Request in flight. The field is disabled and the dialog can\'t be dismissed.' }),
|
withM({ ...U({ modal: inv({ loading: true, confirm: 'Sending…', fields: invF('lea.martin@renew.example') }) }), name: 'Invite: sending', trigger: 'Request in flight. The field is disabled and the dialog can\'t be dismissed.' }),
|
||||||
withM({ ...U({ modal: inv({ fields: invF('jonas@renew.example', { err: 'This address already has an account.' }) }) }), name: 'Invite: already a user (409)', trigger: 'The email belongs to an existing user. For a live pending invite the message reads "There\'s already a pending invite for this address." An expired invite can be sent again.' }),
|
withM({ ...U({ modal: inv({ fields: invF('jonas@renew.example', { err: 'This address already has an account.' }) }) }), name: 'Invite: already a user (409)', trigger: 'The email belongs to an existing user. For a live pending invite the message reads "There\'s already a pending invite for this address." An expired invite can be sent again.' }),
|
||||||
withM({ ...U({ modal: inv({ notice: 'Couldn\'t send the invite. Try again in a moment.', fields: invF('lea.martin@renew.example') }) }), name: 'Invite: failed', trigger: '500, network failure, or the email couldn\'t be sent. The address stays in the field.' }),
|
withM({ ...U({ modal: inv({ notice: 'Couldn\'t send the invite. Try again in a moment.', fields: invF('lea.martin@renew.example') }) }), name: 'Invite: failed', trigger: '500, network failure, or the email couldn\'t be sent. The address stays in the field.' }),
|
||||||
withM({ ...U({ users: { rows: [{ email: 'lea.martin@renew.example', st: 'pending', c: 'Today', hl: true }, ...people] } , toasts: [T('success', 'circle-check', 'Invite sent', 'lea.martin@renew.example has 3 days to accept.')] }), name: 'Invite sent', trigger: '201: the dialog closes, the new invite appears at the top as Pending, and a toast confirms.' })
|
withM({ ...U({ modal: { title: 'Cancel this invite?', desc: 'The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later.', cancel: 'Keep invite', confirm: 'Cancel invite', tone: 'danger' } }), name: 'Cancel invite: confirm', trigger: '"Cancel invite" on a Pending row.' }),
|
||||||
|
withM({ ...U({ modal: { title: 'Cancel this invite?', desc: 'The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later.', cancel: 'Keep invite', confirm: 'Cancelling…', tone: 'danger', loading: true } }), name: 'Cancel invite: sending', trigger: 'Request in flight. Both buttons are disabled.' }),
|
||||||
|
withM({ ...U({ modal: { title: 'Cancel this invite?', desc: 'The link sent to sam.oliveira@renew.example will stop working. You can invite the address again later.', cancel: 'Keep invite', confirm: 'Cancel invite', tone: 'danger', notice: 'Couldn\'t cancel the invite. Try again in a moment.' } }), name: 'Cancel invite: failed', trigger: '500 or network failure. The dialog stays open.' }),
|
||||||
|
withM({ ...U({ users: { rows: people.slice(1) }, toasts: [T('success', 'circle-check', 'Invite cancelled', 'sam.oliveira@renew.example can no longer use the link.')] }), name: 'Cancel invite: done', trigger: '204: the row disappears and a toast confirms.' }),
|
||||||
|
withM({ ...U({ users: { rows: people.map(p => p.st === 'expired' ? { ...p, busy: 'Renewing…' } : p) } }), name: 'Renew invite: sending', trigger: '"Renew invite" on an Expired row. No confirmation, since it only sends an email. The button shows progress and is disabled.' }),
|
||||||
|
withM({ ...U({ users: { rows: [{ ...people[1], st: 'pending', c: 'Today', hl: true }, ...people.filter((p, i) => i !== 1)] }, toasts: [T('success', 'circle-check', 'Invite renewed', 'p.huber@gmail.com has 3 days to accept the new link.')] }), name: 'Renew invite: done', trigger: '200: the row becomes Pending with today\'s date, moves to the top, and the old link stops working.' }),
|
||||||
|
withM({ ...U({ toasts: [T('error', 'circle-x', 'Couldn\'t renew the invite', 'Try again in a moment.')] }), name: 'Renew invite: failed', trigger: '500 or network failure. The row stays Expired and the button can be pressed again.' }),
|
||||||
|
withM({ ...U({ users: { rows: [{ email: 'lea.martin@renew.example', role: 'admin', st: 'pending', c: 'Today', hl: true }, ...people] } , toasts: [T('success', 'circle-check', 'Invite sent', 'lea.martin@renew.example has 3 days to accept.')] }), name: 'Invite sent', trigger: '201: the dialog closes, the new invite appears at the top as Pending, and a toast confirms.' })
|
||||||
|
] },
|
||||||
|
{ label: 'Settings', title: 'Settings', route: '/settings', api: 'none (static)', note: 'Opened from the sidebar. For now it holds only the Version section.', states: [
|
||||||
|
withM({ kind: 'settings', nav: 'settings', crumbs: ['Settings'], mTitle: 'Settings', name: 'Default', trigger: 'Opened from the sidebar.' })
|
||||||
] },
|
] },
|
||||||
{ label: 'Profile', title: 'Profile', route: '/profile', api: 'GET /v1/auth/me · PATCH /v1/user/me (pending) · POST /v1/auth/password-reset', note: 'Opened from the account menu at the bottom of the sidebar. Username, email and password are read-only. The display name is optional, trimmed, and up to 60 characters. Once saved it replaces the username everywhere a person is named: the sidebar, the account menu, the Home greeting, the Users list (with the username beside it) and the emails RenewCMS sends, such as "Marta Alves invited you to RenewCMS". Saving it empty goes back to the username. The reset link uses the same flow as "Forgot password" and ends on the auth board\'s "Choose a new password" screen.', states: [
|
{ label: 'Profile', title: 'Profile', route: '/profile', api: 'GET /v1/auth/me · PATCH /v1/user/me (pending) · POST /v1/auth/password-reset', note: 'Opened from the account menu at the bottom of the sidebar. Username, email and password are read-only. The display name is optional, trimmed, and up to 60 characters. Once saved it replaces the username everywhere a person is named: the sidebar, the account menu, the Home greeting, the Users list (with the username beside it) and the emails RenewCMS sends, such as "Marta Alves invited you to RenewCMS". Saving it empty goes back to the username. The reset link uses the same flow as "Forgot password" and ends on the auth board\'s "Choose a new password" screen.', states: [
|
||||||
withM({ ...home, home: { sub: 'Here\'s where things stand on your site.', stats, recent }, userMenu: true, name: 'Account menu', trigger: 'The account chip at the bottom of the sidebar. On mobile, the account row in the navigation drawer opens it as a sheet. Escape or a click outside closes it.' }),
|
withM({ ...home, home: { sub: 'Here\'s where things stand on your site.', stats, recent }, userMenu: true, name: 'Account menu', trigger: 'The account chip at the bottom of the sidebar. On mobile, the account row in the navigation drawer opens it as a sheet. Escape or a click outside closes it.' }),
|
||||||
@@ -193,7 +203,7 @@ class Component extends DCLogic {
|
|||||||
P({ reset: 'sent' }, { display: dname, name: 'Reset: sent', trigger: '200. The message stays until the page is left. "Send again" sends a new link and the old one stops working.' }),
|
P({ reset: 'sent' }, { display: dname, name: 'Reset: sent', trigger: '200. The message stays until the page is left. "Send again" sends a new link and the old one stops working.' }),
|
||||||
P({ reset: 'limited' }, { display: dname, name: 'Reset: too many requests (429)', trigger: 'Rate limited. The button is disabled for 5 minutes.' }),
|
P({ reset: 'limited' }, { display: dname, name: 'Reset: too many requests (429)', trigger: 'Rate limited. The button is disabled for 5 minutes.' }),
|
||||||
P({ reset: 'error' }, { display: dname, name: 'Reset: failed', trigger: '500 or network failure. The button can be pressed again.' }),
|
P({ reset: 'error' }, { display: dname, name: 'Reset: failed', trigger: '500 or network failure. The button can be pressed again.' }),
|
||||||
withM({ ...U(), display: dname, name: 'Display names in the Users list', trigger: 'Accounts with a display name show it first, with the username beside it in grey. Accounts without one show the username.' })
|
withM({ ...U(), display: dname, name: 'Display names in the Users list', trigger: 'The Display name column shows the name when one is set and a dash when not. Your own row follows your saved name.' })
|
||||||
] },
|
] },
|
||||||
{ label: 'Global', title: 'Global states', route: 'any route', api: '', note: 'A 401 on any back-office call redirects to /login?redirect=<path>&reason=expired (see "Session expired" on the auth board). A 403 from an unverified account redirects to /register/pending. A 429 appears only on log in and password reset. Toasts sit bottom right on desktop and bottom center on mobile, at most 3 at once. Success and info last 5 s; errors stay until dismissed.', states: [
|
{ label: 'Global', title: 'Global states', route: 'any route', api: '', note: 'A 401 on any back-office call redirects to /login?redirect=<path>&reason=expired (see "Session expired" on the auth board). A 403 from an unverified account redirects to /register/pending. A 429 appears only on log in and password reset. Toasts sit bottom right on desktop and bottom center on mobile, at most 3 at once. Success and info last 5 s; errors stay until dismissed.', states: [
|
||||||
withM({ kind: 'error', nav: '', crumbs: ['Not found'], mTitle: 'Not found', name: '404 inside the shell', trigger: 'An unknown route while logged in. Logged out, the same content appears inside AuthShell.', err: { code: '404', title: 'Page not found', text: 'The link may be mistyped, or the page may have moved.', primary: 'Go to Home', secondary: 'All articles' } }),
|
withM({ kind: 'error', nav: '', crumbs: ['Not found'], mTitle: 'Not found', name: '404 inside the shell', trigger: 'An unknown route while logged in. Logged out, the same content appears inside AuthShell.', err: { code: '404', title: 'Page not found', text: 'The link may be mistyped, or the page may have moved.', primary: 'Go to Home', secondary: 'All articles' } }),
|
||||||
|
|||||||
+14
-1
@@ -90,6 +90,12 @@ Every state is drawn at desktop and mobile on the screen boards, with final copy
|
|||||||
| Users | `/users` | Invite: already a user | 409 | [users](screens/users.md) |
|
| Users | `/users` | Invite: already a user | 409 | [users](screens/users.md) |
|
||||||
| Users | `/users` | Invite: failed | 500, network or mail failure | [users](screens/users.md) |
|
| Users | `/users` | Invite: failed | 500, network or mail failure | [users](screens/users.md) |
|
||||||
| Users | `/users` | Invite sent | 201: dialog closes, Pending row on top, toast | [users](screens/users.md) |
|
| Users | `/users` | Invite sent | 201: dialog closes, Pending row on top, toast | [users](screens/users.md) |
|
||||||
|
| Users | `/users` | Cancel invite: confirm, sending, failed | "Cancel invite" on a Pending row; DELETE in flight; 500 or network | [users](screens/users.md) |
|
||||||
|
| Users | `/users` | Cancel invite: done | 204: row removed, toast | [users](screens/users.md) |
|
||||||
|
| Users | `/users` | Renew invite: sending | "Renew invite" on an Expired row; POST in flight | [users](screens/users.md) |
|
||||||
|
| Users | `/users` | Renew invite: done | 200: row Pending on top, toast | [users](screens/users.md) |
|
||||||
|
| Users | `/users` | Renew invite: failed | 500 or network: toast, row stays Expired | [users](screens/users.md) |
|
||||||
|
| Settings | `/settings` | Default | Opened from the sidebar | [settings](screens/settings.md) |
|
||||||
| Profile | `/profile` | Account menu | Account chip clicked | [profile](screens/profile.md) |
|
| Profile | `/profile` | Account menu | Account chip clicked | [profile](screens/profile.md) |
|
||||||
| Profile | `/profile` | Loading | Opened by URL before /auth/me returns | [profile](screens/profile.md) |
|
| Profile | `/profile` | Loading | Opened by URL before /auth/me returns | [profile](screens/profile.md) |
|
||||||
| Profile | `/profile` | Default, no display name | First visit | [profile](screens/profile.md) |
|
| Profile | `/profile` | Default, no display name | First visit | [profile](screens/profile.md) |
|
||||||
@@ -131,6 +137,8 @@ Response bodies are plain text and are never shown. `useApi` throws an `ApiError
|
|||||||
| 500 | Save | "Save failed" + Retry. Changes are kept | SaveStatus |
|
| 500 | Save | "Save failed" + Retry. Changes are kept | SaveStatus |
|
||||||
| 500 | Publish / unpublish | "Couldn't publish" / "Couldn't unpublish" + Retry | Toast |
|
| 500 | Publish / unpublish | "Couldn't publish" / "Couldn't unpublish" + Retry | Toast |
|
||||||
| 500 | Load users | "Couldn't load users. Check your connection and try again." + Try again | Alert |
|
| 500 | Load users | "Couldn't load users. Check your connection and try again." + Try again | Alert |
|
||||||
|
| 500 | Cancel invite | "Couldn't cancel the invite. Try again in a moment." The dialog stays open | Notice in dialog |
|
||||||
|
| 500 | Renew invite | "Couldn't renew the invite. Try again in a moment." The row stays Expired | Toast |
|
||||||
| 500 | Invite | "Couldn't send the invite. Try again in a moment." The address stays | Alert in dialog |
|
| 500 | Invite | "Couldn't send the invite. Try again in a moment." The address stays | Alert in dialog |
|
||||||
| 500 | Save display name | "Couldn't save your display name. Your text is still here. Try again in a moment." | Alert in card |
|
| 500 | Save display name | "Couldn't save your display name. Your text is still here. Try again in a moment." | Alert in card |
|
||||||
| 500 | Send reset link (profile) | "Couldn't send the link. Check your connection and try again." | Note |
|
| 500 | Send reset link (profile) | "Couldn't send the link. Check your connection and try again." | Note |
|
||||||
@@ -146,9 +154,14 @@ Added by the Users and Profile screens, none of which exist yet:
|
|||||||
|
|
||||||
- `GET /v1/user/`: the users and their invites, newest first.
|
- `GET /v1/user/`: the users and their invites, newest first.
|
||||||
- `POST /v1/user/invite`: sends an invitation email. 201, 409 for an existing account or a live pending invite.
|
- `POST /v1/user/invite`: sends an invitation email. 201, 409 for an existing account or a live pending invite.
|
||||||
|
- `DELETE /v1/user/invite/:id`: cancels a Pending invite. 204. Owner only.
|
||||||
|
- `POST /v1/user/invite/:id/renew`: replaces the code, resets the 3 days and created date, and resends the email. 200 with the invite. Owner only.
|
||||||
|
- `GET /v1/user/` and `GET /v1/auth/me` gain a `role` ("owner" or "admin"); the list gains `email` on accepted users.
|
||||||
|
- `POST /v1/user/invite` becomes owner only, and always creates an admin.
|
||||||
|
- `GET /v1/settings`: `{ "version": "..." }`.
|
||||||
- `PATCH /v1/user/me`: saves the display name. `GET /v1/auth/me` returns it.
|
- `PATCH /v1/user/me`: saves the display name. `GET /v1/auth/me` returns it.
|
||||||
- `GET /v1/auth/invite?c=CODE`: looks up the invite on load, returns `{ email }`, 404 or 410. `POST /v1/auth/invite/accept` takes `{ code, username, password }` and returns 200 with the session cookie, 409 for a taken username, 404 or 410.
|
- `GET /v1/auth/invite?c=CODE`: looks up the invite on load, returns `{ email }`, 404 or 410. `POST /v1/auth/invite/accept` takes `{ code, username, password }` and returns 200 with the session cookie, 409 for a taken username, 404 or 410.
|
||||||
|
|
||||||
Still not supported, so shown disabled or omitted:
|
Still not supported, so shown disabled or omitted:
|
||||||
|
|
||||||
Renaming a title (shown read-only, with an explanation in Details), resending the verification email (the pending page explains how to start over), changing the email or username, listing or deleting individual images, removing users, revoking invites and any kind of role. Changing the password while logged in works only through the emailed reset link on the Profile page.
|
Renaming a title (shown read-only, with an explanation in Details), resending the verification email (the pending page explains how to start over), changing the email or username, listing or deleting individual images, removing users, promoting or demoting anyone, and any role other than owner and admin. Changing the password while logged in works only through the emailed reset link on the Profile page.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Release notes format
|
||||||
|
|
||||||
|
Name: `vX.Y.Z-beta - Short theme` (theme is 2 to 6 words, sentence case).
|
||||||
|
Tag: `vX.Y.Z-beta`, always with the `v`.
|
||||||
|
|
||||||
|
Body, in this order. Omit a section only when it would be empty, except Upgrading, which is always present.
|
||||||
|
|
||||||
|
1. Intro: one or two plain sentences on what the release is about. No heading.
|
||||||
|
2. `## New`: user-visible features. Group with a bold title line (`**Group name**`) followed by bullets.
|
||||||
|
3. `## Improvements and fixes`: flat bullets.
|
||||||
|
4. `## API`: one bullet per endpoint change, `METHOD /v1/path` in backticks, then behaviour and status codes. Prefix breaking or shape changes with "Changed:".
|
||||||
|
5. `## Under the hood`: dependencies, tests, docs, architecture. Only when relevant to contributors.
|
||||||
|
6. `## Upgrading`: binary replacement, schema/migration changes, new env vars, behaviour changes for existing installs.
|
||||||
|
7. `## Known limitations`: only when there are real ones.
|
||||||
|
|
||||||
|
Rules: bullets are full sentences ending with a period; user-facing wording, no commit prefixes; sentence-case headings; no horizontal rules, no metadata block, no "Pre-1.0" boilerplate (the prerelease flag says it); every release ships all 6 binaries from `task release`.
|
||||||
|
|
||||||
|
## Published releases
|
||||||
|
|
||||||
|
Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create --tag <tag> --title "<name>" --note-file docs/releases/<tag>.md --prerelease --asset <binary>` (one `--asset` per binary), after `task release`.
|
||||||
|
|
||||||
|
| Tag | Name |
|
||||||
|
| --- | --- |
|
||||||
|
| `2.0.0-beta` (legacy tag without the `v`, kept as is) | v2.0.0-beta - Vue 3 SPA and domain-driven backend |
|
||||||
|
| `v2.1.0-beta` | v2.1.0-beta - Image upload in the editor |
|
||||||
|
| `v2.2.0-beta` | v2.2.0-beta - Image crop, image removal & reset screens |
|
||||||
|
| `v2.3.0-beta` | v2.3.0-beta - Multi-user invitations, display names & profile page |
|
||||||
|
| `v2.4.0-beta` | v2.4.0-beta - Owner role, invite management & Settings page |
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
A ground-up rewrite of RenewCMS's backend architecture and frontend. The Go-template UI is replaced by a Vue 3 single-page app embedded in the same binary.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**Vue 3 single-page app**
|
||||||
|
- Built with Vite, Pinia and vue-router, and embedded into the single binary. There is no separate frontend deployment.
|
||||||
|
- The UI uses Nuxt UI (migrated from an initial PrimeVue base) with shared design tokens.
|
||||||
|
- New screens: login, registration, home and navigation, article list, article editor (ProseMirror-based) with a creation modal, image upload, and an account and integration screen.
|
||||||
|
- A typed API client and a session store handle 401, unverified 403, 429 and offline states the same way everywhere.
|
||||||
|
|
||||||
|
**Domain-driven backend**
|
||||||
|
- `internal/domain` (entities, sentinel errors, repository interfaces) is isolated from persistence (GORM), mailer and API concerns, with a strict inward dependency rule.
|
||||||
|
- Business logic moved out of handlers and the persistence layer into use cases: article rules, image validation, password and code hashing, not-found handling, and session invalidation on password reset.
|
||||||
|
- The composition root (`api/dependecyInjection.go`) wires the database, repositories and use cases explicitly. Runtime settings are read once at startup.
|
||||||
|
- The auth handler is split into dedicated registration, login, verification and password-reset handlers, each with per-client rate limiting on the public routes.
|
||||||
|
|
||||||
|
## Improvements and fixes
|
||||||
|
- API responses no longer leak password hashes, verification or reset code hashes, or their expiry dates.
|
||||||
|
- Article read rules now apply the same way to the single-article and list endpoints: the public sees online articles only, verified users also see offline ones.
|
||||||
|
- Registration only opens when no verified account exists, and deleting a user frees its username and email for reuse.
|
||||||
|
- Rate limiting now keys off the real peer IP.
|
||||||
|
|
||||||
|
## Under the hood
|
||||||
|
- Use cases are covered by a full in-memory fake test suite with clean gremlins mutation coverage.
|
||||||
|
- Vitest and Vue Test Utils run the frontend tests, and an automated visual-parity check compares the app to the design source boards.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
- Deployment is unchanged: a single binary, systemd and a reverse proxy. Replace the binary and restart.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
This release adds image upload to the article editor and fixes several rough edges from v2.0.0-beta.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**Image upload in the article editor**
|
||||||
|
- The editor's Image toolbar button, or dropping a file onto the editor, opens an upload dialog.
|
||||||
|
- Choose or drop a PNG, JPEG, WEBP or SVG file up to 10 MB. Progress is shown live, and the image is inserted at the cursor as soon as it is uploaded.
|
||||||
|
- Invalid files (wrong type or too large) are rejected in the browser before anything is sent. The same wording is reused if the server rejects a file the browser let through.
|
||||||
|
- A failed upload leaves the article untouched and offers a retry.
|
||||||
|
|
||||||
|
## Improvements and fixes
|
||||||
|
- Uploaded images now render in the editor and the article body. The dev server proxy was missing a route for the endpoint that serves them.
|
||||||
|
- Clicking a row in the article list now opens the editor. The row-click handler was reading the wrong argument.
|
||||||
|
- The article details panel's copy URL control now copies the link and confirms with a toast.
|
||||||
|
- The user menu's dropdown trigger no longer misrenders when the sidebar is collapsed.
|
||||||
|
- The sidebar's collapsed or expanded state is remembered across reloads.
|
||||||
|
- Smaller styling and layout fixes in the article details panel, editor toolbar and new-article dialog.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
- Replace the binary and restart.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
This release reworks image handling in the article editor and brings the password-reset screens up to the new design.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**Crop and resize before upload**
|
||||||
|
- A Crop and resize step now sits between picking an image and uploading it. It applies to JPEG, PNG and WEBP files. SVG files still upload straight away.
|
||||||
|
- Move or resize the crop frame by dragging it or its handles. Arrow keys nudge it by 1 px, and Shift+arrow resizes it by 1 px.
|
||||||
|
- Aspect ratios: Original, Free, 16:9, 4:3 and 1:1.
|
||||||
|
- Rotate and Reset buttons.
|
||||||
|
- Output width presets: Original, 1600 px (default), 1200 px and 800 px. The output is never wider than the crop frame.
|
||||||
|
- A live line shows the final pixel size and an approximate file size before you upload.
|
||||||
|
|
||||||
|
**Remove images from the editor**
|
||||||
|
- Images in an article can now be removed from the editor. The image file and its database row are both deleted.
|
||||||
|
- The editor renders images as a dedicated image node.
|
||||||
|
|
||||||
|
**Password-reset screens**
|
||||||
|
- The Forgot password and Reset password screens follow the new design and cover every state in the spec.
|
||||||
|
|
||||||
|
## API
|
||||||
|
- `DELETE /v1/article/{id}/image/{imageId}` (authenticated) deletes an image. It returns 204 on success, 404 for an unknown article or image, and 400 for an ID that isn't a valid uint32.
|
||||||
|
- Changed: `POST /v1/article/{id}/image` now returns `{"id": …, "location": …}` instead of `{"location": …}`. The change is additive, but anything parsing the response strictly should be checked.
|
||||||
|
|
||||||
|
## Under the hood
|
||||||
|
- The editor now depends on `@tiptap/extension-image`, `@tiptap/pm` and `@tiptap/vue-3`, all pinned to 3.31.3.
|
||||||
|
- New feature specs and QA procedures cover crop and resize, image removal and both reset screens.
|
||||||
|
- New Go HTTP tests cover image deletion, and Vitest specs were added and updated for the editor and reset views.
|
||||||
|
- The visual-check states cover the new screens, and the design docs are updated to match.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
- No new environment variables and no schema changes.
|
||||||
|
- Replace the binary and restart.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
RenewCMS is no longer a one-person tool. The admin can now invite other people, each with their own account and the exact same access, and everyone can set a display name.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**Invite other users**
|
||||||
|
- A new Users page in the back-office lists everyone who can sign in, plus pending and expired invites, with a status badge for each.
|
||||||
|
- Invite user sends an email with a personal link. The link works once and expires after 3 days.
|
||||||
|
- Invited people choose their own username and password on a new Accept invite screen, and land on Home already logged in.
|
||||||
|
- Everyone shares one workspace: same articles, same images, same access.
|
||||||
|
- Registration stays closed to everyone who wasn't invited.
|
||||||
|
- A new invitation email template supports light and dark mode.
|
||||||
|
|
||||||
|
**Display name and profile**
|
||||||
|
- A new Profile page is opened from the account menu at the bottom of the sidebar.
|
||||||
|
- Set an optional display name (up to 60 characters). It replaces your username in the sidebar, the account menu, the Home greeting, the Users list and the emails RenewCMS sends. Clear it to go back to your username.
|
||||||
|
- Send yourself a password reset link from the Profile page.
|
||||||
|
- The account chip now opens a menu with Profile and Log out, and keeps the System, Light and Dark theme choice.
|
||||||
|
|
||||||
|
## Improvements and fixes
|
||||||
|
- Accepting an invite is atomic: two simultaneous requests with the same link can only create one account.
|
||||||
|
- The Accept invite screen shows a retry option instead of a permanent spinner when the invite can't be loaded.
|
||||||
|
- Invite email validation is now the same in the browser and on the server.
|
||||||
|
- The mobile account sheet reports its open state correctly and returns focus to the account chip when it closes.
|
||||||
|
- A failed password reset email is now logged on the server. The response is unchanged.
|
||||||
|
|
||||||
|
## API
|
||||||
|
- `PATCH /v1/user/me` sets the display name.
|
||||||
|
- `GET /v1/auth/me` and `POST /v1/auth/verify` now return `display_name`.
|
||||||
|
- `GET /v1/user/` lists users and invites.
|
||||||
|
- `POST /v1/user/invite` sends an invite and is rate limited.
|
||||||
|
- `GET /v1/auth/invite` and `POST /v1/auth/invite/accept` power the Accept invite screen.
|
||||||
|
|
||||||
|
## Under the hood
|
||||||
|
- Deleting a user now goes through the persistence model.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
- Download the binary for your platform, replace the old one and restart. Your `.env` and SQLite file stay as they are.
|
||||||
|
- The database migrates itself on startup. It adds a `display_name` column to `users` and a new `invites` table. Existing data is untouched. Back up your SQLite file first as a precaution.
|
||||||
|
- Invitation emails need working SMTP settings, like the verification and reset emails already do. No new environment variables.
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
- Users and invites can't be removed, revoked or resent yet, and there are no roles: everybody is an equal admin.
|
||||||
|
- Invited addresses that already have an account are rejected. An expired invite can be replaced by sending a new one.
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
RenewCMS now knows who owns the workspace. The owner manages invites, including cancelling and renewing them, while every admin keeps the same access to content. A new Settings page shows which build is running.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**Owner and admin roles**
|
||||||
|
- The first registered account is the owner. Everyone who joins through an invite is an admin.
|
||||||
|
- Only the owner can send, cancel or renew invites. Admins keep the same access to articles, images, the Users list, their Profile and Settings.
|
||||||
|
- There is exactly one owner. Roles can't be changed or transferred yet.
|
||||||
|
- Existing installs are migrated automatically: the oldest account becomes the owner and every other account an admin.
|
||||||
|
|
||||||
|
**Invite management**
|
||||||
|
- Pending invites get a Cancel invite action on the Users page. The invite link stops working.
|
||||||
|
- Expired invites get a Renew invite action. It sends a new email with a new personal link valid for 3 days, and the old link stays dead.
|
||||||
|
|
||||||
|
**Users list**
|
||||||
|
- The Users table and the mobile card list now show Email, Display name (a dash when empty), Role, Invite status and Created.
|
||||||
|
- A new role badge tells the owner and admins apart.
|
||||||
|
|
||||||
|
**Settings page**
|
||||||
|
- A new Settings page at `/settings` sits after Integration in the sidebar and the mobile drawer. It shows the version of the running build.
|
||||||
|
|
||||||
|
## Improvements and fixes
|
||||||
|
- The desktop account menu's icons, labels and check mark are now centred in their 32 px rows.
|
||||||
|
- The account menu follows the redesigned board: System, Light and Dark stay in both the menu and the mobile sheet.
|
||||||
|
- The article editor's toolbar scrolls horizontally on mobile instead of overflowing.
|
||||||
|
- The editor's last-saved label now moves from minutes to hours and days instead of counting minutes only.
|
||||||
|
|
||||||
|
## API
|
||||||
|
- `DELETE /v1/user/invite/{id}` cancels a pending invite and returns 204.
|
||||||
|
- `POST /v1/user/invite/{id}/renew` returns 200 with a new code, sets `expires_at` to now plus 3 days and `created_at` to now, and resends the invitation email.
|
||||||
|
- Changed: `POST /v1/user/invite` is now owner-only, like the two endpoints above. Other users get 403 with "Only the owner can do this."
|
||||||
|
- `GET /v1/settings` (authenticated, verified users) returns the running build's version.
|
||||||
|
- Changed: user objects from `GET /v1/user/`, `GET /v1/auth/me` and `POST /v1/auth/verify` now include `role` (`owner` or `admin`).
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
- Replace the binary and restart. Your `.env` and SQLite file stay as they are.
|
||||||
|
- The database migrates itself on startup. It adds a `role` column to `users` and fills it in: the account with the lowest id becomes the owner, every other account an admin. A database that already has roles is left unchanged. Back up your SQLite file first as a precaution.
|
||||||
|
- Behaviour change: admins who joined through a v2.3.0-beta invite can no longer send invites.
|
||||||
|
- No new environment variables.
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
- No endpoint changes or transfers the owner role, and users can't be removed yet.
|
||||||
@@ -26,7 +26,8 @@ Feature: An invited person accepts their invitation and gets a verified account
|
|||||||
And error responses are plain text from http.Error, success responses are JSON
|
And error responses are plain text from http.Error, success responses are JSON
|
||||||
And accepting creates a user with the invite's email (already lower case), the chosen username,
|
And accepting creates a user with the invite's email (already lower case), the chosen username,
|
||||||
the hashed password, is_verified true, an empty verification code, and an empty display name
|
the hashed password, is_verified true, an empty verification code, and an empty display name
|
||||||
And the created user has the same access as any other verified user: no roles, no ownership
|
And the created user is an admin: same access to articles, the users list and Settings, but
|
||||||
|
cannot invite
|
||||||
And the jwt cookie is set exactly as registration sets it: HttpOnly, path "/", 24 hours, with
|
And the jwt cookie is set exactly as registration sets it: HttpOnly, path "/", 24 hours, with
|
||||||
claims user_id and token_version, and Secure in production
|
claims user_id and token_version, and Secure in production
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ Feature: DashboardShell wordmark, sidebar collapse and the UserMenu
|
|||||||
AuthShell uses) followed by the "RenewCMS" wordmark text, not the plain
|
AuthShell uses) followed by the "RenewCMS" wordmark text, not the plain
|
||||||
<span class="font-semibold">RenewCMS</span> the shell renders today
|
<span class="font-semibold">RenewCMS</span> the shell renders today
|
||||||
And the sidebar's #default slot is a UNavigationMenu orientation="vertical" :collapsed bound
|
And the sidebar's #default slot is a UNavigationMenu orientation="vertical" :collapsed bound
|
||||||
to the sidebar's own collapsed state, with items Home, Articles, Users and Integration, in that order
|
to the sidebar's own collapsed state, with items Home, Articles, Users, Integration and Settings, in that order
|
||||||
And the sidebar's #footer slot renders a UserMenu component, not the plain
|
And the sidebar's #footer slot renders a UserMenu component, not the plain
|
||||||
<span>Log out</span> text the shell renders today
|
<span>Log out</span> text the shell renders today
|
||||||
And UserMenu is the account menu specified in features/profile_page.feature, anchored to a
|
And UserMenu is the account menu specified in features/profile_page.feature, anchored to a
|
||||||
|
|||||||
@@ -11,8 +11,8 @@ Feature: A logged-in user fetches their own public profile without triggering th
|
|||||||
Background:
|
Background:
|
||||||
Given the public user struct and its converter, shared by the auth and user handlers from a
|
Given the public user struct and its converter, shared by the auth and user handlers from a
|
||||||
package under api/pkg (features/user_display_name.feature), exactly the JSON shape
|
package under api/pkg (features/user_display_name.feature), exactly the JSON shape
|
||||||
POST /v1/auth/verify returns: id, username, email, is_verified, created_at, updated_at and
|
POST /v1/auth/verify returns: id, username, email, is_verified, created_at, updated_at,
|
||||||
display_name
|
display_name and role
|
||||||
And this slice adds GET /v1/auth/me, handled by a new MeHandler (api/handlers/auth/meHandler.go)
|
And this slice adds GET /v1/auth/me, handled by a new MeHandler (api/handlers/auth/meHandler.go)
|
||||||
built with NewMeHandler(container.GetUserUseCase), the same GetUserUseCase every other
|
built with NewMeHandler(container.GetUserUseCase), the same GetUserUseCase every other
|
||||||
protected handler already gets from api/dependecyInjection.go; no new use case or domain
|
protected handler already gets from api/dependecyInjection.go; no new use case or domain
|
||||||
@@ -43,23 +43,23 @@ Feature: A logged-in user fetches their own public profile without triggering th
|
|||||||
|
|
||||||
Scenario: A verified user fetches their own profile
|
Scenario: A verified user fetches their own profile
|
||||||
Given a user repository containing user id 7, username "alice", email "alice@example.com",
|
Given a user repository containing user id 7, username "alice", email "alice@example.com",
|
||||||
is_verified true, TokenVersion 0
|
is_verified true, role "owner", TokenVersion 0
|
||||||
And a valid jwt cookie for user id 7 encoding token_version 0
|
And a valid jwt cookie for user id 7 encoding token_version 0
|
||||||
When the client sends GET /v1/auth/me with that cookie
|
When the client sends GET /v1/auth/me with that cookie
|
||||||
Then the response status is 200
|
Then the response status is 200
|
||||||
And the response header Cache-Control is "no-store"
|
And the response header Cache-Control is "no-store"
|
||||||
And the response body is the user as JSON with id 7, username "alice", email
|
And the response body is the user as JSON with id 7, username "alice", email
|
||||||
"alice@example.com", is_verified true
|
"alice@example.com", is_verified true, role "owner"
|
||||||
|
|
||||||
Scenario: An unverified user still fetches their own profile, with is_verified false, not a 403
|
Scenario: An unverified user still fetches their own profile, with is_verified false, not a 403
|
||||||
Given a user repository containing user id 8, username "bob", email "bob@example.com",
|
Given a user repository containing user id 8, username "bob", email "bob@example.com",
|
||||||
is_verified false, TokenVersion 0
|
is_verified false, role "owner", TokenVersion 0
|
||||||
And a valid jwt cookie for user id 8 encoding token_version 0
|
And a valid jwt cookie for user id 8 encoding token_version 0
|
||||||
When the client sends GET /v1/auth/me with that cookie
|
When the client sends GET /v1/auth/me with that cookie
|
||||||
Then the response status is 200
|
Then the response status is 200
|
||||||
And the response header Cache-Control is "no-store"
|
And the response header Cache-Control is "no-store"
|
||||||
And the response body is the user as JSON with id 8, username "bob", email "bob@example.com",
|
And the response body is the user as JSON with id 8, username "bob", email "bob@example.com",
|
||||||
is_verified false
|
is_verified false, role "owner"
|
||||||
|
|
||||||
Scenario: No jwt cookie at all is refused
|
Scenario: No jwt cookie at all is refused
|
||||||
Given a user repository containing user id 7, username "alice", is_verified true, TokenVersion 0
|
Given a user repository containing user id 7, username "alice", is_verified true, TokenVersion 0
|
||||||
|
|||||||
@@ -37,13 +37,13 @@ wiring pattern in `test/stale_token_invalidation_http_test.go`.
|
|||||||
## HTTP-level checks
|
## HTTP-level checks
|
||||||
|
|
||||||
8. Seed `mockUserRepo` with user id 7, username "alice", email "alice@example.com",
|
8. Seed `mockUserRepo` with user id 7, username "alice", email "alice@example.com",
|
||||||
`IsVerified: true`, `TokenVersion: 0`. Mint a cookie for user 7 with `token_version: 0`.
|
`IsVerified: true`, `Role: owner`, `TokenVersion: 0`. Mint a cookie for user 7 with
|
||||||
`GET /v1/auth/me` → assert status `200`, `Cache-Control` header equals `"no-store"`, and the
|
`token_version: 0`. `GET /v1/auth/me` → assert status `200`, `Cache-Control` header equals
|
||||||
decoded JSON body has `id: 7`, `username: "alice"`, `email: "alice@example.com"`,
|
`"no-store"`, and the decoded JSON body has `id: 7`, `username: "alice"`,
|
||||||
`is_verified: true`.
|
`email: "alice@example.com"`, `is_verified: true`, `role: "owner"`.
|
||||||
9. Seed user id 8, username "bob", email "bob@example.com", `IsVerified: false`,
|
9. Seed user id 8, username "bob", email "bob@example.com", `IsVerified: false`, `Role: owner`,
|
||||||
`TokenVersion: 0`. Mint a matching cookie. `GET /v1/auth/me` → assert status `200` (not 403),
|
`TokenVersion: 0`. Mint a matching cookie. `GET /v1/auth/me` → assert status `200` (not 403),
|
||||||
`Cache-Control: no-store`, and `is_verified: false` in the body.
|
`Cache-Control: no-store`, `is_verified: false` and `role: "owner"` in the body.
|
||||||
10. No `jwt` cookie at all against the router from step 6 → assert status `401` (produced by
|
10. No `jwt` cookie at all against the router from step 6 → assert status `401` (produced by
|
||||||
`jwtauth.Authenticator` itself; don't assert an exact body for this case, same rationale as
|
`jwtauth.Authenticator` itself; don't assert an exact body for this case, same rationale as
|
||||||
`features/account_verification.qa.md` step 15).
|
`features/account_verification.qa.md` step 15).
|
||||||
|
|||||||
@@ -6,9 +6,13 @@ Feature: A verified user can invite another person by email, and the users list
|
|||||||
registration stays closed to everyone who was not invited
|
registration stays closed to everyone who was not invited
|
||||||
|
|
||||||
Background:
|
Background:
|
||||||
Given the workspace is shared: there are no roles, no ownership and no way to remove a user
|
Given the workspace is shared: every verified user sees the same articles and the same list,
|
||||||
|
roles are owner and admin (features/user_roles.feature), and there is no way to remove a user
|
||||||
And POST /v1/user/invite and GET /v1/user/ are mounted in NewUserRouter, inside the group that
|
And POST /v1/user/invite and GET /v1/user/ are mounted in NewUserRouter, inside the group that
|
||||||
requires a valid jwt cookie, a current token_version and a verified user
|
requires a valid jwt cookie, a current token_version and a verified user
|
||||||
|
And POST /v1/user/invite additionally requires the owner role (403
|
||||||
|
apperr.OwnerRequiredErrorMessage for an admin); GET /v1/user/ is open to every verified user
|
||||||
|
And wherever a scenario has verified user id 7 post an invite, user 7 is the owner
|
||||||
And an invite has an id, an email stored in lower case, a hashed code, an expires_at equal to
|
And an invite has an id, an email stored in lower case, a hashed code, an expires_at equal to
|
||||||
its creation time plus 3 days, an invited_by user id, a nullable accepted_at and a created_at
|
its creation time plus 3 days, an invited_by user id, a nullable accepted_at and a created_at
|
||||||
And the raw invite code is a uuid, hashed with the same hash.Hasher used for verification codes,
|
And the raw invite code is a uuid, hashed with the same hash.Hasher used for verification codes,
|
||||||
@@ -17,8 +21,8 @@ Feature: A verified user can invite another person by email, and the users list
|
|||||||
expires_at is in the future, expired when accepted_at is empty and expires_at is in the past,
|
expires_at is in the future, expired when accepted_at is empty and expires_at is in the past,
|
||||||
accepted when accepted_at is set
|
accepted when accepted_at is set
|
||||||
And the users list item shape is: id, kind ("user" or "invite"), status, created_at, plus
|
And the users list item shape is: id, kind ("user" or "invite"), status, created_at, plus
|
||||||
username and display_name for a user, plus email for an invite; a user is never listed with
|
username, display_name, email and role for a user, plus email for an invite; neither the
|
||||||
an email, and neither the code, its hash, invited_by nor password fields ever appear
|
code, its hash, invited_by nor password fields ever appear
|
||||||
And error responses are plain text from http.Error, success responses are JSON
|
And error responses are plain text from http.Error, success responses are JSON
|
||||||
And the invite email uses the template "invitation" with data Host (the configured PublicURL),
|
And the invite email uses the template "invitation" with data Host (the configured PublicURL),
|
||||||
VerificationCode (the raw code), Email (the invited address) and InvitedBy (the inviter's
|
VerificationCode (the raw code), Email (the invited address) and InvitedBy (the inviter's
|
||||||
@@ -30,7 +34,7 @@ Feature: A verified user can invite another person by email, and the users list
|
|||||||
/login and /password-reset
|
/login and /password-reset
|
||||||
|
|
||||||
Scenario: A verified user invites a new address
|
Scenario: A verified user invites a new address
|
||||||
Given a user repository containing verified user id 7, username "marta", display_name ""
|
Given a user repository containing verified user id 7, who is the owner, username "marta", display_name ""
|
||||||
And an empty invite repository
|
And an empty invite repository
|
||||||
And a valid jwt cookie for user id 7
|
And a valid jwt cookie for user id 7
|
||||||
When the client sends POST /v1/user/invite with body {"email": "Sam.Oliveira@Renew.example"}
|
When the client sends POST /v1/user/invite with body {"email": "Sam.Oliveira@Renew.example"}
|
||||||
@@ -116,6 +120,7 @@ Feature: A verified user can invite another person by email, and the users list
|
|||||||
| with no jwt cookie | POST | /v1/user/invite | 401 |
|
| with no jwt cookie | POST | /v1/user/invite | 401 |
|
||||||
| with a jwt cookie of an unverified user | POST | /v1/user/invite | 403 |
|
| with a jwt cookie of an unverified user | POST | /v1/user/invite | 403 |
|
||||||
| with a jwt cookie whose token_version is stale | POST | /v1/user/invite | 401 |
|
| with a jwt cookie whose token_version is stale | POST | /v1/user/invite | 401 |
|
||||||
|
| with a jwt cookie of a verified admin | POST | /v1/user/invite | 403 |
|
||||||
| with no jwt cookie | GET | /v1/user/ | 401 |
|
| with no jwt cookie | GET | /v1/user/ | 401 |
|
||||||
| with a jwt cookie of an unverified user | GET | /v1/user/ | 403 |
|
| with a jwt cookie of an unverified user | GET | /v1/user/ | 403 |
|
||||||
|
|
||||||
@@ -142,9 +147,10 @@ Feature: A verified user can invite another person by email, and the users list
|
|||||||
And the accepted invite is not listed
|
And the accepted invite is not listed
|
||||||
And the invite items have exactly the keys id, kind, email, status, created_at, with kind
|
And the invite items have exactly the keys id, kind, email, status, created_at, with kind
|
||||||
"invite" and status "pending" or "expired"
|
"invite" and status "pending" or "expired"
|
||||||
And the user items have exactly the keys id, kind, username, display_name, status, created_at,
|
And the user items have exactly the keys id, kind, username, display_name, email, role, status,
|
||||||
with kind "user" and status "accepted"
|
created_at, with kind "user" and status "accepted"
|
||||||
And no user item has an email key, and no item has a key named password, password_reset_code,
|
And each user item has its own email and a role
|
||||||
|
And no item has a key named password, password_reset_code,
|
||||||
verification_code, verification_expiration, password_reset_expiration, token_version,
|
verification_code, verification_expiration, password_reset_expiration, token_version,
|
||||||
code, hashed_code, invited_by or accepted_at
|
code, hashed_code, invited_by or accepted_at
|
||||||
|
|
||||||
|
|||||||
@@ -14,11 +14,13 @@ plus a `fixedClock` only if the use case takes one. Reuse `mockUserRepo` and `st
|
|||||||
3. Handler: `user.NewHandler(updateProfile, createInvite, listUsersAndInvites)` mounted on a fresh
|
3. Handler: `user.NewHandler(updateProfile, createInvite, listUsersAndInvites)` mounted on a fresh
|
||||||
`chi.NewRouter()` mirroring `NewUserRouter`: `jwtauth.Verifier` + `jwtauth.Authenticator` with
|
`chi.NewRouter()` mirroring `NewUserRouter`: `jwtauth.Verifier` + `jwtauth.Authenticator` with
|
||||||
`jwtauth.New("HS256", []byte("test-secret"), nil)`, `RequireCurrentToken(getUser)`,
|
`jwtauth.New("HS256", []byte("test-secret"), nil)`, `RequireCurrentToken(getUser)`,
|
||||||
`RequireVerifiedUser(getUser)`, then `POST /invite` and `GET /`. For the rate-limit case
|
`RequireVerifiedUser(getUser)`, then `POST /invite` and `GET /`. `POST /invite` is also wrapped
|
||||||
wrap only `POST /invite` in `TrustedProxyRealIP(nil)` + `NewRateLimiter(2, time.Minute)`.
|
in `RequireOwner(getUser)`, placed before the limiter. For the rate-limit case
|
||||||
|
wrap only `POST /invite` in `RequireOwner(getUser)` + `TrustedProxyRealIP(nil)` +
|
||||||
|
`NewRateLimiter(2, time.Minute)`.
|
||||||
Requests via `httptest`; jwt cookie built with the `user_id` and `token_version` claims as in
|
Requests via `httptest`; jwt cookie built with the `user_id` and `token_version` claims as in
|
||||||
`test/verified_account_required_http_test.go`. No live server, no real SQLite, no real SMTP.
|
`test/verified_account_required_http_test.go`. No live server, no real SQLite, no real SMTP.
|
||||||
4. Seed users: verified id 7 "marta"; unverified id 8 for the 403 cases. Time is real: build
|
4. Seed users: verified id 7 "marta" with `Role: owner`; unverified id 8 for the 403 cases. Time is real: build
|
||||||
invites with `ExpiresAt`/`CreatedAt` relative to `time.Now()` and compare with a 5 s tolerance.
|
invites with `ExpiresAt`/`CreatedAt` relative to `time.Now()` and compare with a 5 s tolerance.
|
||||||
|
|
||||||
## POST /v1/user/invite
|
## POST /v1/user/invite
|
||||||
@@ -47,7 +49,8 @@ plus a `fixedClock` only if the use case takes one. Reuse `mockUserRepo` and `st
|
|||||||
`inviteRepo` empty. Repeat the same request without re-arming -> `201`. With a seeded expired invite and a
|
`inviteRepo` empty. Repeat the same request without re-arming -> `201`. With a seeded expired invite and a
|
||||||
failing send -> `500` and no invite for that address remains.
|
failing send -> `500` and no invite for that address remains.
|
||||||
13. Auth table (`POST`): no cookie -> `401`; cookie of unverified user 8 -> `403`; cookie with stale
|
13. Auth table (`POST`): no cookie -> `401`; cookie of unverified user 8 -> `403`; cookie with stale
|
||||||
`token_version` -> `401`. Each asserts no invite and no mail.
|
`token_version` -> `401`; cookie of a verified admin (seeded with `Role: admin`) -> `403`, plain
|
||||||
|
text body exactly `apperr.OwnerRequiredErrorMessage`. Each asserts no invite and no mail.
|
||||||
14. Rate limit: limiter of 2 per minute, `RemoteAddr` `203.0.113.20:1234`, three valid POSTs -> `201`,
|
14. Rate limit: limiter of 2 per minute, `RemoteAddr` `203.0.113.20:1234`, three valid POSTs -> `201`,
|
||||||
`201`, `429`; third body is exactly `apperr.TooManyRequestsErrorMessage`, has `Retry-After`, and adds no
|
`201`, `429`; third body is exactly `apperr.TooManyRequestsErrorMessage`, has `Retry-After`, and adds no
|
||||||
invite or mail. `GET /` from the same address afterwards is not `429`.
|
invite or mail. `GET /` from the same address afterwards is not `429`.
|
||||||
@@ -55,9 +58,10 @@ plus a `fixedClock` only if the use case takes one. Reuse `mockUserRepo` and `st
|
|||||||
## GET /v1/user/
|
## GET /v1/user/
|
||||||
15. Seed per the feature scenario (three users, an expired, a pending and an accepted invite, with the
|
15. Seed per the feature scenario (three users, an expired, a pending and an accepted invite, with the
|
||||||
stated `CreatedAt` values). `200`; decode as `[]map[string]json.RawMessage`. Assert length 5, order
|
stated `CreatedAt` values). `200`; decode as `[]map[string]json.RawMessage`. Assert length 5, order
|
||||||
(pending sam, expired p.huber, ines, jonas, marta), key sets exactly as specified for user and invite
|
(pending sam, expired p.huber, ines, jonas, marta), key sets exactly as specified: `id`, `kind`,
|
||||||
items, accepted invite absent, and none of the forbidden keys anywhere. Also assert the raw body string
|
`username`, `display_name`, `email`, `role`, `status`, `created_at` for user items and `id`, `kind`,
|
||||||
contains no user email address.
|
`email`, `status`, `created_at` for invite items, accepted invite absent, and none of the forbidden
|
||||||
|
keys anywhere. Also assert the raw body string contains each accepted user's own email address.
|
||||||
16. Only user 7 -> array with exactly one `kind:"user"` item, status `accepted`.
|
16. Only user 7 -> array with exactly one `kind:"user"` item, status `accepted`.
|
||||||
17. Invite created 3 days + 1 minute ago -> `status:"expired"`; created 2 days ago -> `pending`;
|
17. Invite created 3 days + 1 minute ago -> `status:"expired"`; created 2 days ago -> `pending`;
|
||||||
with `AcceptedAt` set -> not listed.
|
with `AcceptedAt` set -> not listed.
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
Feature: The owner can cancel a pending invite and renew a pending or expired one
|
||||||
|
|
||||||
|
As the owner of the shared RenewCMS workspace
|
||||||
|
I want to cancel an invite I no longer want, or renew one that is stale or expired
|
||||||
|
So that only the people I currently intend to invite can create an account
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given the invite domain, the invitation email and the roles are those of features/invitations.feature
|
||||||
|
and features/user_roles.feature
|
||||||
|
And DELETE /v1/user/invite/{id} and POST /v1/user/invite/{id}/renew are mounted in NewUserRouter,
|
||||||
|
in the same group as POST /v1/user/invite: valid jwt cookie, current token_version, verified user,
|
||||||
|
owner role, trusted-proxy real IP, then the auth rate limiter
|
||||||
|
And the checks run in this order: 401, 403 unverified, 403 not owner, 429, 400 invalid id, 404, 409,
|
||||||
|
then the action
|
||||||
|
And user 7 "marta" is the verified owner and user 9 "jonas" is a verified admin
|
||||||
|
And error responses are plain text from http.Error, and the messages are:
|
||||||
|
| case | status | body |
|
||||||
|
| unknown invite | 404 | Invite not found |
|
||||||
|
| invite already accepted | 409 | This invite has already been accepted. |
|
||||||
|
| id is not a uint32 | 400 | apperr.IdUint32ErrorMessage |
|
||||||
|
| not the owner | 403 | Only the owner can do this. |
|
||||||
|
| no valid session | 401 | apperr.UnauthorizedErrorMessage |
|
||||||
|
| rate limited | 429 | apperr.TooManyRequestsErrorMessage |
|
||||||
|
| renew email not sent | 500 | Couldn't send the invite. Try again in a moment. |
|
||||||
|
And the renew response has the same shape as the create response: exactly the keys id, kind
|
||||||
|
("invite"), email, status, created_at and expires_at
|
||||||
|
|
||||||
|
Rule: Cancelling an invite
|
||||||
|
|
||||||
|
Scenario: The owner cancels a pending invite
|
||||||
|
Given an invite id 3 for "sam.oliveira@renew.example", pending, created by user 7
|
||||||
|
And a valid jwt cookie for user 7
|
||||||
|
When the client sends DELETE /v1/user/invite/3
|
||||||
|
Then the response status is 204
|
||||||
|
And the response body is empty
|
||||||
|
And the invite repository no longer holds invite 3
|
||||||
|
And no email was sent
|
||||||
|
And GET /v1/user/ no longer lists the invite
|
||||||
|
|
||||||
|
Scenario: A cancelled invite's link stops working
|
||||||
|
Given invite 3 was cancelled by the owner
|
||||||
|
When the client sends GET /v1/auth/invite?c=<the code from that invite>
|
||||||
|
Then the response status is 404
|
||||||
|
And the response body is "This invite link doesn't work."
|
||||||
|
And accepting the invite with that code returns 404, creates no user and sets no cookie
|
||||||
|
|
||||||
|
Scenario: A cancelled address can be invited again
|
||||||
|
Given invite 3 for "sam.oliveira@renew.example" was cancelled
|
||||||
|
When the owner sends POST /v1/user/invite for that address
|
||||||
|
Then the response status is 201
|
||||||
|
|
||||||
|
Scenario: The owner cancels an expired invite
|
||||||
|
Given invite 4 is expired
|
||||||
|
When the owner sends DELETE /v1/user/invite/4
|
||||||
|
Then the response status is 204
|
||||||
|
And the invite repository no longer holds invite 4
|
||||||
|
|
||||||
|
Scenario: Other invites and users are untouched
|
||||||
|
Given invites 3 and 4 and users 7 and 9
|
||||||
|
When the owner cancels invite 3
|
||||||
|
Then invite 4 and users 7 and 9 are unchanged
|
||||||
|
|
||||||
|
Scenario: An unknown invite is not found
|
||||||
|
When the owner sends DELETE /v1/user/invite/999
|
||||||
|
Then the response status is 404
|
||||||
|
And the response body is "Invite not found"
|
||||||
|
|
||||||
|
Scenario: Cancelling twice is not found
|
||||||
|
Given the owner cancelled invite 3
|
||||||
|
When the owner sends DELETE /v1/user/invite/3 again
|
||||||
|
Then the response status is 404
|
||||||
|
|
||||||
|
Scenario: An accepted invite cannot be cancelled
|
||||||
|
Given invite 5 was accepted and its user exists
|
||||||
|
When the owner sends DELETE /v1/user/invite/5
|
||||||
|
Then the response status is 409
|
||||||
|
And the response body is "This invite has already been accepted."
|
||||||
|
And invite 5 and its user remain
|
||||||
|
|
||||||
|
Rule: Renewing an invite
|
||||||
|
|
||||||
|
Scenario: The owner renews an expired invite
|
||||||
|
Given invite 4 for "lea.martin@renew.example", created 5 days ago, expired 2 days ago,
|
||||||
|
invited_by 7, stored code hash "hashed:OLD-CODE"
|
||||||
|
And a valid jwt cookie for user 7
|
||||||
|
When the client sends POST /v1/user/invite/4/renew
|
||||||
|
Then the response status is 200
|
||||||
|
And the response has Cache-Control "no-store"
|
||||||
|
And the response id is 4, kind "invite", email "lea.martin@renew.example" and status "pending"
|
||||||
|
And created_at is now and expires_at is 3 days after created_at, each within 5 seconds
|
||||||
|
And the response body has no key named code, hashed_code, invited_by or accepted_at
|
||||||
|
And the invite repository holds exactly one invite for that address, with id 4, a new code hash,
|
||||||
|
invited_by 7 and accepted_at empty
|
||||||
|
|
||||||
|
Scenario: The owner renews a pending invite
|
||||||
|
Given invite 3 is pending
|
||||||
|
When the owner sends POST /v1/user/invite/3/renew
|
||||||
|
Then the response status is 200
|
||||||
|
And invite 3 has a new code hash and created_at now
|
||||||
|
|
||||||
|
Scenario: A renewed invite moves to the top of the users list
|
||||||
|
Given invite 3 is pending and older than invite 6
|
||||||
|
When the owner renews invite 3
|
||||||
|
Then GET /v1/user/ lists invite 3 before invite 6
|
||||||
|
|
||||||
|
Scenario: The old link is dead and the new link works
|
||||||
|
Given invite 4 was renewed and the raw code in the new email is NEW-CODE
|
||||||
|
When the client sends GET /v1/auth/invite?c=<the old code>
|
||||||
|
Then the response status is 404
|
||||||
|
And accepting with the old code returns 404 and creates no user
|
||||||
|
And GET /v1/auth/invite?c=NEW-CODE returns 200 with {"email": "lea.martin@renew.example"}
|
||||||
|
And this holds when the renewed invite was pending as well as expired
|
||||||
|
|
||||||
|
Scenario: Renewing sends the invitation email again
|
||||||
|
When the owner renews invite 4
|
||||||
|
Then exactly one email was sent, with template "invitation"
|
||||||
|
And its Host is the configured PublicURL, its Email is the invited address, its InvitedBy is
|
||||||
|
the acting owner's display name or, when empty, username
|
||||||
|
And its VerificationCode is the new raw code
|
||||||
|
And the link in it is <Host>/invite/accept?c=<new raw code>
|
||||||
|
And the invite's invited_by is unchanged
|
||||||
|
|
||||||
|
Scenario: An unknown or cancelled invite is not found
|
||||||
|
When the owner sends POST /v1/user/invite/999/renew
|
||||||
|
Then the response status is 404
|
||||||
|
And the response body is "Invite not found"
|
||||||
|
And renewing a cancelled invite also returns 404
|
||||||
|
|
||||||
|
Scenario: An accepted invite cannot be renewed
|
||||||
|
Given invite 5 was accepted
|
||||||
|
When the owner sends POST /v1/user/invite/5/renew
|
||||||
|
Then the response status is 409
|
||||||
|
And the response body is "This invite has already been accepted."
|
||||||
|
And invite 5 is unchanged and no email was sent
|
||||||
|
|
||||||
|
Scenario: A failed email leaves the invite as it was
|
||||||
|
Given expired invite 4 and an email repository whose next send fails
|
||||||
|
When the owner sends POST /v1/user/invite/4/renew
|
||||||
|
Then the response status is 500
|
||||||
|
And the response body is "Couldn't send the invite. Try again in a moment."
|
||||||
|
And invite 4 keeps its old code hash, expires_at and created_at, and is still expired
|
||||||
|
And a pending invite whose renew mail fails keeps its old link valid
|
||||||
|
And a retry of the same request returns 200
|
||||||
|
|
||||||
|
Rule: Only the owner can manage invites
|
||||||
|
|
||||||
|
Scenario Outline: Access is checked on both endpoints
|
||||||
|
Given invite 3 is pending
|
||||||
|
When <caller> sends <method> <path>
|
||||||
|
Then the response status is <status>
|
||||||
|
And invite 3 is unchanged
|
||||||
|
And no email was sent
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| caller | method | path | status |
|
||||||
|
| a client with no cookie | DELETE | /v1/user/invite/3 | 401 |
|
||||||
|
| a client with no cookie | POST | /v1/user/invite/3/renew | 401 |
|
||||||
|
| a stale token_version | DELETE | /v1/user/invite/3 | 401 |
|
||||||
|
| a stale token_version | POST | /v1/user/invite/3/renew | 401 |
|
||||||
|
| an unverified user | DELETE | /v1/user/invite/3 | 403 |
|
||||||
|
| an unverified user | POST | /v1/user/invite/3/renew | 403 |
|
||||||
|
| verified admin 9 | DELETE | /v1/user/invite/3 | 403 |
|
||||||
|
| verified admin 9 | POST | /v1/user/invite/3/renew | 403 |
|
||||||
|
|
||||||
|
Scenario: An admin is refused with the owner message, even on an unknown id
|
||||||
|
When admin 9 sends DELETE /v1/user/invite/999
|
||||||
|
Then the response status is 403
|
||||||
|
And the response body is "Only the owner can do this."
|
||||||
|
|
||||||
|
Scenario Outline: An id that is not a uint32 is rejected
|
||||||
|
When the owner sends <method> <path>
|
||||||
|
Then the response status is 400
|
||||||
|
And the response body is apperr.IdUint32ErrorMessage
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| method | path |
|
||||||
|
| DELETE | /v1/user/invite/abc |
|
||||||
|
| DELETE | /v1/user/invite/-1 |
|
||||||
|
| DELETE | /v1/user/invite/4294967296 |
|
||||||
|
| POST | /v1/user/invite/abc/renew |
|
||||||
|
| POST | /v1/user/invite/-1/renew |
|
||||||
|
| POST | /v1/user/invite/4294967296/renew|
|
||||||
|
|
||||||
|
Rule: Rate limiting
|
||||||
|
|
||||||
|
Scenario: Requests over the limit are refused
|
||||||
|
Given the auth rate limiter allows 2 requests per window
|
||||||
|
When the owner sends three valid requests to DELETE or renew from IP 203.0.113.40
|
||||||
|
Then the third response is 429 with apperr.TooManyRequestsErrorMessage and a Retry-After header
|
||||||
|
And the third request changes nothing and sends no email
|
||||||
|
And GET /v1/user/ from the same address is not 429
|
||||||
|
|
||||||
|
Scenario: An admin does not use up the quota
|
||||||
|
When admin 9 sends three requests from one IP
|
||||||
|
Then all three responses are 403, not 429
|
||||||
|
|
||||||
|
Scenario: The counter is shared with inviting
|
||||||
|
Given the auth rate limiter allows 2 requests per window
|
||||||
|
When the owner sends POST /v1/user/invite, then renews an invite, then sends DELETE /v1/user/invite/3
|
||||||
|
Then the DELETE returns 429
|
||||||
|
|
||||||
|
Rule: Existing behaviour is unchanged
|
||||||
|
|
||||||
|
Scenario: The invitation and acceptance features still hold
|
||||||
|
Then every scenario of features/invitations.feature and features/accept_invitation.feature still passes
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# QA procedure: invite management
|
||||||
|
|
||||||
|
Package: `test` (black-box). Reuse `mockUserRepo`, `stubHasher`, `mockMailRepo` and `mockInviteRepo`.
|
||||||
|
Extend `mockInviteRepo` with the new renew method and a `failSwitch` entry for it (unique type names
|
||||||
|
across the package). No live server, no real SQLite (except case 27), no real SMTP.
|
||||||
|
|
||||||
|
## Setup shared by every case
|
||||||
|
1. Call `validator.InitValidator()` once.
|
||||||
|
2. Use cases over domain interfaces only: `CreateInvite`, `ListUsersAndInvites`, `GetInvite`, the accept
|
||||||
|
use case, plus the new cancel and renew use cases (final names are the coder's).
|
||||||
|
3. Handler built with `NewHandler(...)` on a fresh `chi.NewRouter()` mirroring `NewUserRouter`:
|
||||||
|
`jwtauth.Verifier` + `jwtauth.Authenticator` (`jwtauth.New("HS256", []byte("test-secret"), nil)`),
|
||||||
|
`RequireCurrentToken`, `RequireVerifiedUser`, `GET /`, then a group with `RequireOwner`,
|
||||||
|
`TrustedProxyRealIP(nil)` and `NewRateLimiter` containing `POST /invite`, `DELETE /invite/{id}` and
|
||||||
|
`POST /invite/{id}/renew`. Mount `GET /invite` and `POST /invite/accept` from the auth handler for the
|
||||||
|
old-link cases.
|
||||||
|
4. Seed users: owner 7 "marta", unverified 8, admin 9. Invite hashes are `"hashed:"+raw`. Times are
|
||||||
|
relative to `time.Now()`, compared with a 5 s tolerance.
|
||||||
|
|
||||||
|
## DELETE /v1/user/invite/{id}
|
||||||
|
5. Pending invite, owner cookie -> `204`, empty body, invite gone, no mail, absent from `GET /`.
|
||||||
|
6. After cancel: `GET /invite?c=<code>` -> `404`; accept -> `404`, no user, no cookie; re-invite the address -> `201`.
|
||||||
|
7. Expired invite -> `204`.
|
||||||
|
8. Unknown id -> `404` "Invite not found"; second delete -> `404`.
|
||||||
|
9. Accepted invite -> `409` "This invite has already been accepted."; invite and user remain.
|
||||||
|
10. Other invites and users unchanged after a cancel.
|
||||||
|
11. Repository delete failure -> `500`, invite still present.
|
||||||
|
|
||||||
|
## POST /v1/user/invite/{id}/renew
|
||||||
|
12. Expired invite -> `200`, `Cache-Control: no-store`; key set exactly `id`, `kind`, `email`, `status`,
|
||||||
|
`created_at`, `expires_at`; no `code`, `hashed_code`, `invited_by`, `accepted_at`.
|
||||||
|
13. Stored invite: same id, new hash, `invited_by` 7, `accepted_at` nil, `created_at` about now,
|
||||||
|
`expires_at` = `created_at` + 72h.
|
||||||
|
14. Pending invite renews with `200`, new hash.
|
||||||
|
15. Mail: exactly one entry, template `invitation`, `Host`, `Email`, `InvitedBy` by display name or username
|
||||||
|
of the acting owner, `VerificationCode` = raw new code.
|
||||||
|
16. `GET /` lists the renewed invite first.
|
||||||
|
17. Old code: `GET /invite` and accept -> `404`, no user; new code -> `200` with the email. Control checks before
|
||||||
|
the renew show the old code worked. Same for pending.
|
||||||
|
18. Unknown id -> `404`; cancelled id -> `404`.
|
||||||
|
19. Accepted -> `409`, all fields unchanged, no mail.
|
||||||
|
20. `mailRepo.fail.failNext("Send")` -> `500` "Couldn't send the invite. Try again in a moment."; invite hash,
|
||||||
|
expiry and created_at unchanged; retry -> `200`.
|
||||||
|
21. Renew persistence failure -> `500`, no mail, invite unchanged.
|
||||||
|
|
||||||
|
## Access and ids (table over both endpoints)
|
||||||
|
22. No cookie -> `401`; stale `token_version` -> `401`; unverified -> `403`; admin -> `403` with body
|
||||||
|
`apperr.OwnerRequiredErrorMessage`; admin on an unknown id -> `403`. Each: invite unchanged, no mail.
|
||||||
|
23. Ids `abc`, `-1`, `4294967296` -> `400` `apperr.IdUint32ErrorMessage` on both endpoints.
|
||||||
|
|
||||||
|
## Rate limit
|
||||||
|
24. Limiter of 2, `RemoteAddr` `203.0.113.40:1234`: third request -> `429`, `apperr.TooManyRequestsErrorMessage`,
|
||||||
|
`Retry-After`, no change, no mail. `GET /` from the same address is not `429`.
|
||||||
|
25. Admin's three requests -> `403`, `403`, `403`.
|
||||||
|
26. Shared counter: `POST /invite`, renew, then `DELETE` -> `429`.
|
||||||
|
|
||||||
|
## Use case and persistence
|
||||||
|
27. Use case level:
|
||||||
|
- unknown id -> `errors.Is(err, ErrInviteNotFound)`; accepted -> the accepted sentinel (name is the coder's);
|
||||||
|
- success returns the same id, a new hash, `CreatedAt` about now, `ExpiresAt` = `CreatedAt` + `invite.Lifetime`;
|
||||||
|
- mail failure wraps `ErrInviteEmailNotSent` and restores the prior values;
|
||||||
|
- the mail logic is shared with `CreateInvite`.
|
||||||
|
28. Persistence on in-memory SQLite: the renew method updates hash, expiry and created_at by id, returns
|
||||||
|
`ErrInviteNotFound` when the row is missing or already accepted.
|
||||||
|
|
||||||
|
## Manual
|
||||||
|
Renew against a real or sandboxed SMTP server: one mail arrives, the new link works, the old mail's link is dead.
|
||||||
|
Persistence across a restart on a fresh SQLite file. Review layering and that no comments were introduced.
|
||||||
|
|
||||||
|
## Out of scope
|
||||||
|
SPA handling of 404, 409 and 429 on these endpoints: this slice is API-only.
|
||||||
@@ -130,14 +130,14 @@ Feature: Nuxt UI shell foundation and router guards
|
|||||||
Then the alert above the title contains "Your session expired."
|
Then the alert above the title contains "Your session expired."
|
||||||
And the footer area outside the card contains a "Forgot password?" link
|
And the footer area outside the card contains a "Forgot password?" link
|
||||||
|
|
||||||
Scenario: DashboardShell renders the four navigation destinations
|
Scenario: DashboardShell renders the five navigation destinations
|
||||||
Given the current route is /article
|
Given the current route is /article
|
||||||
When DashboardShell mounts
|
When DashboardShell mounts
|
||||||
Then the sidebar navigation lists exactly four destinations in this order: "Home" linking to
|
Then the sidebar navigation lists exactly five destinations in this order: "Home" linking to
|
||||||
/home, "Articles" linking to /article, "Users" linking to /users, and "Integration" linking
|
/home, "Articles" linking to /article, "Users" linking to /users, "Integration" linking
|
||||||
to /integration
|
to /integration, and "Settings" linking to /settings
|
||||||
And the "Articles" destination has aria-current="page"
|
And the "Articles" destination has aria-current="page"
|
||||||
And none of "Home", "Users" and "Integration" has aria-current set
|
And none of "Home", "Users", "Integration" and "Settings" has aria-current set
|
||||||
|
|
||||||
Scenario: DashboardShell shows the offline banner when the browser reports offline
|
Scenario: DashboardShell shows the offline banner when the browser reports offline
|
||||||
Given navigator.onLine is false
|
Given navigator.onLine is false
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ Mock `useApi` / the `/v1/auth/me` call per case; no real backend, no httptest se
|
|||||||
13. **AuthShell notice/footer slots** — mount AuthShell with notice and footer slot content; assert
|
13. **AuthShell notice/footer slots** — mount AuthShell with notice and footer slot content; assert
|
||||||
both render outside/above the card content as specified.
|
both render outside/above the card content as specified.
|
||||||
14. **DashboardShell nav + aria-current** — mount DashboardShell with current route /article; assert
|
14. **DashboardShell nav + aria-current** — mount DashboardShell with current route /article; assert
|
||||||
4 links in order (Home→/home, Articles→/article, Users→/users, Integration→/integration), and only the Articles link
|
5 links in order (Home→/home, Articles→/article, Users→/users, Integration→/integration, Settings→/settings), and only the Articles link
|
||||||
has aria-current="page".
|
has aria-current="page".
|
||||||
15. **DashboardShell offline banner** — mock navigator.onLine false, mount DashboardShell; assert
|
15. **DashboardShell offline banner** — mock navigator.onLine false, mount DashboardShell; assert
|
||||||
the offline banner is visible; set navigator.onLine true and dispatch the 'online' event; assert
|
the offline banner is visible; set navigator.onLine true and dispatch the 'online' event; assert
|
||||||
@@ -57,7 +57,7 @@ plus the components.md AuthShell/DashboardShell sections.
|
|||||||
- [ ] AuthShell below sm: card loses border, 20px padding fills screen, fields/buttons use xl size,
|
- [ ] AuthShell below sm: card loses border, 20px padding fills screen, fields/buttons use xl size,
|
||||||
light and dark.
|
light and dark.
|
||||||
- [ ] AuthShell footer: UColorModeSelect size="sm" plus footer links render outside the card.
|
- [ ] AuthShell footer: UColorModeSelect size="sm" plus footer links render outside the card.
|
||||||
- [ ] DashboardShell desktop: sidebar with RenewCMS logo header, 3 nav items, UserMenu footer;
|
- [ ] DashboardShell desktop: sidebar with RenewCMS logo header, 5 nav items, UserMenu footer;
|
||||||
collapsing the sidebar leaves a 56px icon rail with tooltips on hover/focus.
|
collapsing the sidebar leaves a 56px icon rail with tooltips on hover/focus.
|
||||||
- [ ] DashboardShell mobile (below lg): UDashboardSidebarToggle appears, sidebar becomes a
|
- [ ] DashboardShell mobile (below lg): UDashboardSidebarToggle appears, sidebar becomes a
|
||||||
slideover, closes after navigating.
|
slideover, closes after navigating.
|
||||||
|
|||||||
@@ -18,8 +18,8 @@ Feature: Profile page, display name and the account menu
|
|||||||
display_name in a response is read as ""; the session store gains an action that replaces
|
display_name in a response is read as ""; the session store gains an action that replaces
|
||||||
the session's displayName from the display_name of a PATCH /v1/user/me response
|
the session's displayName from the display_name of a PATCH /v1/user/me response
|
||||||
And the PageHeader shows breadcrumb "Profile" (mobile title "Profile"), the page title
|
And the PageHeader shows breadcrumb "Profile" (mobile title "Profile"), the page title
|
||||||
"Profile" and the subtitle "Your account on this RenewCMS workspace."; none of the four
|
"Profile" and the subtitle "Your account on this RenewCMS workspace."; none of the five
|
||||||
navigation items (Home, Articles, Users, Integration) has aria-current="page" on /profile
|
navigation items (Home, Articles, Users, Integration, Settings) has aria-current="page" on /profile
|
||||||
And the page is at most 720 px wide with three ProfileCards in this order: Display name,
|
And the page is at most 720 px wide with three ProfileCards in this order: Display name,
|
||||||
Account, Password; cards are separated by 20 px, have 20 px padding (16 px on mobile) and
|
Account, Password; cards are separated by 20 px, have 20 px padding (16 px on mobile) and
|
||||||
inputs are 40 px high (44 px on mobile, 16 px text)
|
inputs are 40 px high (44 px on mobile, 16 px text)
|
||||||
@@ -92,7 +92,7 @@ Feature: Profile page, display name and the account menu
|
|||||||
checked (kept from the shipped menu), a separator, and "Log out" (icon log-out); items are
|
checked (kept from the shipped menu), a separator, and "Log out" (icon log-out); items are
|
||||||
32 px on desktop and 48 px at 15 px text on mobile
|
32 px on desktop and 48 px at 15 px text on mobile
|
||||||
And activating "Profile" navigates to /profile and closes the menu (when already on /profile
|
And activating "Profile" navigates to /profile and closes the menu (when already on /profile
|
||||||
it only closes); activating a theme item sets the preference and closes the menu;
|
it only closes); activating a theme item sets the preference and, in the desktop popover, keeps the menu open (the mobile sheet closes);
|
||||||
activating "Log out" behaves as today: POST /v1/auth/logout in a try/finally, then
|
activating "Log out" behaves as today: POST /v1/auth/logout in a try/finally, then
|
||||||
session.clear() and a navigation to /login
|
session.clear() and a navigation to /login
|
||||||
And avatar initials are the uppercased first Unicode character of each of the first two words
|
And avatar initials are the uppercased first Unicode character of each of the first two words
|
||||||
@@ -296,7 +296,10 @@ Feature: Profile page, display name and the account menu
|
|||||||
And its header shows "marta" in semibold and "marta@renew.example" in muted 12 px
|
And its header shows "marta" in semibold and "marta@renew.example" in muted 12 px
|
||||||
And below it are "Profile" (circle-user), a separator, "System", "Light", "Dark" (the
|
And below it are "Profile" (circle-user), a separator, "System", "Light", "Dark" (the
|
||||||
current preference checked), a separator, and "Log out" (log-out)
|
current preference checked), a separator, and "Log out" (log-out)
|
||||||
|
And every item is 32 px high
|
||||||
And "Profile" is not highlighted
|
And "Profile" is not highlighted
|
||||||
|
And "System", "Light" and "Dark" form one group where choosing one applies the theme at once
|
||||||
|
and keeps the menu open
|
||||||
|
|
||||||
Scenario: Account menu — opened from the drawer on mobile
|
Scenario: Account menu — opened from the drawer on mobile
|
||||||
Given the user is on /home on a viewport below lg and the navigation drawer is open
|
Given the user is on /home on a viewport below lg and the navigation drawer is open
|
||||||
@@ -305,8 +308,17 @@ Feature: Profile page, display name and the account menu
|
|||||||
with the Home page behind it
|
with the Home page behind it
|
||||||
And its header shows a 36 px avatar "MA", the name "marta" at 15 px semibold and the email
|
And its header shows a 36 px avatar "MA", the name "marta" at 15 px semibold and the email
|
||||||
"marta@renew.example" muted
|
"marta@renew.example" muted
|
||||||
And its items are 48 px high: "Profile", a separator, "System", "Light", "Dark", a separator,
|
And its items are 48 px high at 15 px text: "Profile", a separator, "System", "Light", "Dark",
|
||||||
"Log out"
|
a separator, "Log out"
|
||||||
|
And the sheet has the same items in the same order as the desktop popover, so it is no taller
|
||||||
|
than the board's sheet
|
||||||
|
|
||||||
|
Scenario: Account menu matches the board with no visual exception
|
||||||
|
Given web/visual/states.ts has no exception on the profile state "Account menu"
|
||||||
|
When `task visual:check -- profile "Account menu"` runs at desktop and mobile, light and dark
|
||||||
|
Then every capture is within 10 %
|
||||||
|
And System, Light and Dark are present in the popover and in the sheet
|
||||||
|
And item heights are 32 px on desktop and 48 px on mobile
|
||||||
|
|
||||||
Scenario Outline: Closing the menu
|
Scenario Outline: Closing the menu
|
||||||
Given the account menu is open
|
Given the account menu is open
|
||||||
|
|||||||
@@ -102,12 +102,17 @@ capture must be within 10 %. Base session mock: GET /v1/auth/me 200 with id 1, u
|
|||||||
"marta", email "marta@renew.example", is_verified true, display_name "" (state-specific
|
"marta", email "marta@renew.example", is_verified true, display_name "" (state-specific
|
||||||
overrides below).
|
overrides below).
|
||||||
|
|
||||||
- [ ] Account menu: /home with `now: boardNow` and the home Default fixtures, session as above,
|
- [ ] Account menu: /home with `now: boardNow` and the home Default fixtures, session as above
|
||||||
menu opened by clicking the chip (on mobile: open the drawer, then the account row). Name
|
(id 1, "marta", "marta@renew.example", display_name ""), menu opened by clicking the chip
|
||||||
"marta", initials "MA", email "marta@renew.example". The theme items kept by user decision
|
(on mobile: open the drawer, then the account row). Name "marta", initials "MA", email
|
||||||
are not drawn on the board, so the mobile capture is expected to exceed 10 %. The user has
|
"marta@renew.example". The board now draws System, Light and Dark, with Light checked in
|
||||||
approved a per-state `exception` for it, to be added with `approvedBy` only after the
|
its sample. The `exception` block is removed from web/visual/states.ts, so the default 10 %
|
||||||
real difference is measured and reported to the user with its cause.
|
gate applies. `task visual:check -- profile "Account menu"` must PASS on all four captures
|
||||||
|
(desktop and mobile, light and dark). If the only remaining diff is the board's Profile
|
||||||
|
highlight on Home (the app highlights Profile only on /profile), do NOT re-add an exception
|
||||||
|
and do NOT highlight Profile on Home. Stop and ask the user.
|
||||||
|
- [ ] Manual: item heights measured 32 px (desktop popover) and 48 px (mobile sheet); arrow keys move
|
||||||
|
between items; Escape and outside click close; choosing a theme keeps the menu open.
|
||||||
- [ ] Loading: /profile with GET /v1/auth/me hanging; three skeleton cards, 16 px apart.
|
- [ ] Loading: /profile with GET /v1/auth/me hanging; three skeleton cards, 16 px apart.
|
||||||
- [ ] Default, no display name: empty field, "0 / 60", the username footer, Save at 40 %.
|
- [ ] Default, no display name: empty field, "0 / 60", the username footer, Save at 40 %.
|
||||||
- [ ] Editing: type "Marta Alves"; field focused; "11 / 60"; "Unsaved changes"; Save enabled.
|
- [ ] Editing: type "Marta Alves"; field focused; "11 / 60"; "Unsaved changes"; Save enabled.
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
Feature: Settings page and GET /v1/settings
|
||||||
|
|
||||||
|
As a verified RenewCMS user in the shared workspace
|
||||||
|
I want a Settings page that shows the version of the RenewCMS build I am running
|
||||||
|
So that I can tell which build is deployed when I report a problem or check an upgrade
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given GET /v1/settings is mounted under /v1 in api/router.go in its own router, behind
|
||||||
|
jwtauth.Verifier, jwtauth.Authenticator, middleware.RequireCurrentToken and
|
||||||
|
middleware.RequireVerifiedUser, the same chain as NewUserRouter
|
||||||
|
And the response of a verified caller is 200 with the JSON body {"version": "<value>"}, one
|
||||||
|
snake_case field and nothing else, built from the domain entity settings.Settings in
|
||||||
|
internal/domain/settings
|
||||||
|
And GetSettingsUseCase (internal/infrastructure/useCases) is built with the version string and
|
||||||
|
depends only on the domain package; the handler in api/handlers/settings receives it
|
||||||
|
through NewHandler and never reads config, os or the environment
|
||||||
|
And config.Settings gains a Version field; cmd/server/main.go sets it from its own
|
||||||
|
main.version variable ("dev" unless set with -ldflags -X main.version) right after
|
||||||
|
config.NewSettingsFromEnv, and api/dependecyInjection.go passes settings.Version to the use
|
||||||
|
case; no os.Getenv or os.LookupEnv for the version appears outside cmd/server/main.go and
|
||||||
|
internal/infrastructure/config, and the version is captured once at startup
|
||||||
|
And /settings is a verified route (meta.auth "verified", meta.title "Settings") rendered as
|
||||||
|
SettingsPage inside DashboardShell, per docs/design/routes.md and docs/design/screens/settings.md
|
||||||
|
And SettingsPage calls GET /v1/settings once per navigation to it
|
||||||
|
And the PageHeader shows breadcrumb "Settings" (mobile title "Settings"), the page title
|
||||||
|
"Settings" and the subtitle "Workspace information."
|
||||||
|
And the page is at most 720 px wide, with padding 32 px on desktop and 20px 16px 88px on
|
||||||
|
mobile, and 20 px between the header and the card
|
||||||
|
And the page holds one card, --ui-bg with a 1 px --ui-border, 20 px padding on desktop and
|
||||||
|
16 px on mobile, containing a single row laid out as the board frame draws it: the label at
|
||||||
|
the left, the value at the right, vertically centred, 16 px apart
|
||||||
|
And the label is "Version" (15 px semibold, --ui-text-highlighted) and the value is the
|
||||||
|
server's version string in IBM Plex Mono 14 px, --ui-text-toned, with no "v" added by the
|
||||||
|
SPA
|
||||||
|
And the page has no action, toggle, link or input; every verified user sees it, owner and
|
||||||
|
admin alike
|
||||||
|
And DashboardShell's navigation gains "Settings" (icon settings, i-lucide-settings, linking to
|
||||||
|
/settings) after "Integration", in the sidebar and in the mobile drawer, so it lists five
|
||||||
|
destinations in this order: Home, Articles, Users, Integration, Settings
|
||||||
|
And skeleton placeholders show only after 150 ms of loading, so a fast response never flashes
|
||||||
|
them
|
||||||
|
And the Loading and Error states are not drawn in docs/design; they are decided in this spec
|
||||||
|
and covered by Vitest only (no visual state)
|
||||||
|
|
||||||
|
Scenario Outline: A verified caller gets the running build's version
|
||||||
|
Given the process was started with a config.Settings whose Version is "<version>"
|
||||||
|
And a verified user is logged in with a valid jwt cookie
|
||||||
|
When the client sends GET /v1/settings
|
||||||
|
Then the response status is 200
|
||||||
|
And the response body is exactly the JSON object {"version": "<version>"}
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| version |
|
||||||
|
| v2.2.0-beta |
|
||||||
|
| dev |
|
||||||
|
|
||||||
|
Scenario: The use case returns the version it was built with
|
||||||
|
Given GetSettingsUseCase is built with the version "v2.2.0-beta"
|
||||||
|
When GetSettings is called
|
||||||
|
Then it returns a settings.Settings whose Version is "v2.2.0-beta"
|
||||||
|
|
||||||
|
Scenario: A request without a jwt cookie is refused
|
||||||
|
When the client sends GET /v1/settings with no jwt cookie
|
||||||
|
Then the response status is 401
|
||||||
|
And the use case is not consulted for the response
|
||||||
|
|
||||||
|
Scenario: A token whose version no longer matches the account is refused
|
||||||
|
Given user id 7 exists with token version 1
|
||||||
|
And the jwt cookie was minted for user 7 with token version 0
|
||||||
|
When the client sends GET /v1/settings with that cookie
|
||||||
|
Then the response status is 401
|
||||||
|
And the response body is apperr.UnauthorizedErrorMessage
|
||||||
|
|
||||||
|
Scenario: An unverified account is refused
|
||||||
|
Given user id 8 exists with is_verified false and a valid jwt cookie
|
||||||
|
When the client sends GET /v1/settings with that cookie
|
||||||
|
Then the response status is 403
|
||||||
|
And the response body is apperr.VerificationRequiredErrorMessage
|
||||||
|
And the response does not contain the version
|
||||||
|
|
||||||
|
Scenario: Default — the Version row shows the server's version
|
||||||
|
Given GET /v1/settings resolves 200 with {"version": "v2.2.0-beta"}
|
||||||
|
When the user navigates to /settings
|
||||||
|
Then the breadcrumb reads "Settings" (mobile title "Settings")
|
||||||
|
And the header shows the title "Settings" and the subtitle "Workspace information."
|
||||||
|
And the card shows one row: the label "Version" and the value "v2.2.0-beta"
|
||||||
|
And the "Settings" nav item has aria-current="page" and no other nav item does
|
||||||
|
|
||||||
|
Scenario: The value is shown exactly as reported, with no prefix added
|
||||||
|
Given GET /v1/settings resolves 200 with {"version": "dev"}
|
||||||
|
When the user navigates to /settings
|
||||||
|
Then the value reads "dev"
|
||||||
|
|
||||||
|
Scenario: Navigation — "Settings" sits after Integration
|
||||||
|
Given the user is on /home
|
||||||
|
When DashboardShell mounts
|
||||||
|
Then the sidebar and the mobile drawer list Home, Articles, Users, Integration, Settings in
|
||||||
|
that order
|
||||||
|
And "Settings" has the settings icon and links to /settings
|
||||||
|
|
||||||
|
Scenario: Loading — the value becomes a skeleton after 150 ms while the request is in flight
|
||||||
|
Given GET /v1/settings has not yet resolved
|
||||||
|
When the user navigates to /settings
|
||||||
|
Then the label "Version" is visible at once, and nothing stands in for the value during the
|
||||||
|
first 150 ms
|
||||||
|
And after 150 ms a skeleton replaces the value only, and the card is aria-busy="true"
|
||||||
|
When GET /v1/settings then resolves 200 with {"version": "v2.2.0-beta"}
|
||||||
|
Then the skeleton is replaced by "v2.2.0-beta" and aria-busy is no longer set
|
||||||
|
|
||||||
|
Scenario Outline: Error — a 500 or a network failure replaces the row with an inline alert and a retry
|
||||||
|
Given GET /v1/settings <failure>
|
||||||
|
When the user navigates to /settings
|
||||||
|
Then the card shows an error alert with no close button and no title, reading "Couldn't reach
|
||||||
|
RenewCMS. Check your connection and try again.", with an action "Try again" (icon rotate-cw)
|
||||||
|
And the "Version" row is not shown
|
||||||
|
And the header (title and subtitle) is still shown
|
||||||
|
When the user activates "Try again"
|
||||||
|
Then the Loading state shows and GET /v1/settings is sent again
|
||||||
|
When it then resolves 200 with {"version": "v2.2.0-beta"}
|
||||||
|
Then the Default state's row replaces the alert
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| resolves with a 500 response |
|
||||||
|
| never reaches the server |
|
||||||
|
|
||||||
|
Scenario: A 401 or an unverified 403 is handled globally, not by the page
|
||||||
|
Given GET /v1/settings resolves 401
|
||||||
|
When the user navigates to /settings
|
||||||
|
Then useApi's global handling redirects to "/login?redirect=/settings&reason=expired"
|
||||||
|
And SettingsPage shows no error alert of its own
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
# QA: Settings page and GET /v1/settings
|
||||||
|
|
||||||
|
## Automated Go (`task test`, package `test`, black-box)
|
||||||
|
|
||||||
|
Files: `test/settings_test.go` (use case) and `test/settings_http_test.go` (HTTP). Fakes: reuse
|
||||||
|
`mockUserRepo` from `test/user_test.go`; no settings repository exists, so none is needed. Name any
|
||||||
|
new fake uniquely, since all fakes share one package.
|
||||||
|
|
||||||
|
Setup shared by the HTTP cases:
|
||||||
|
1. Call `validator.InitValidator()` once.
|
||||||
|
2. Build `token := jwtauth.New("HS256", []byte("test-secret"), nil)`, `getUser :=
|
||||||
|
useCases.NewGetUserUseCase(userRepo)` and `settingsHandler :=
|
||||||
|
settings.NewHandler(useCases.NewGetSettingsUseCase(version))`.
|
||||||
|
3. Mount on a fresh `chi.NewRouter()` mirroring `NewSettingsRouter`:
|
||||||
|
`r.Route("/v1/settings", ...)` with `jwtauth.Verifier(token)`, `jwtauth.Authenticator(token)`,
|
||||||
|
`middleware.RequireCurrentToken(getUser)`, `middleware.RequireVerifiedUser(getUser)`, then
|
||||||
|
`r.Get("/", settingsHandler.GetSettings)`. No live server, no SQLite, no SMTP.
|
||||||
|
4. Mint cookies with `token.Encode(map[string]any{"user_id": uint32(id), "token_version":
|
||||||
|
uint32(v)})`, as in `test/stale_token_invalidation_http_test.go`.
|
||||||
|
|
||||||
|
Cases:
|
||||||
|
5. Use case, table-driven over versions "v2.2.0-beta" and "dev": `NewGetSettingsUseCase(v)
|
||||||
|
.GetSettings().Version == v`. The rule that `internal/domain/settings` and the use case do not
|
||||||
|
import `config`, `os`, `net/http` or `gorm` is a review item, not a Go test.
|
||||||
|
6. Verified user id 7 (`IsVerified: true`, `TokenVersion: 0`), matching cookie, version
|
||||||
|
"v2.2.0-beta": `GET /v1/settings` returns 200 and the body decodes to exactly one key
|
||||||
|
`version` equal to "v2.2.0-beta" (decode into `map[string]any` and assert `len == 1`). Repeat
|
||||||
|
with version "dev".
|
||||||
|
7. No cookie: 401. Do not assert an exact body (it is produced by `jwtauth.Authenticator`).
|
||||||
|
8. User 7 with `TokenVersion: 1`, cookie encoding `token_version: 0`: 401, body exactly
|
||||||
|
`apperr.UnauthorizedErrorMessage`.
|
||||||
|
9. User 8 with `IsVerified: false`, matching cookie: 403, body exactly
|
||||||
|
`apperr.VerificationRequiredErrorMessage`, and the body does not contain the version string.
|
||||||
|
10. After building the router, call `t.Setenv("ENVIRONMENT", "development")` and re-request as in
|
||||||
|
case 6: the response is unchanged (nothing is read from the environment at request time).
|
||||||
|
|
||||||
|
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mock `useApi`'s `request` for `GET /v1/settings`. Mount SettingsPage inside DashboardShell with a
|
||||||
|
resolved verified session and a test router at /settings. Use fake timers for the 150 ms cases. No
|
||||||
|
test freezes the system date.
|
||||||
|
|
||||||
|
1. **Default** — resolve `{ version: 'v2.2.0-beta' }`; assert breadcrumb "Settings", title
|
||||||
|
"Settings", subtitle "Workspace information.", one row with the label "Version" and the value
|
||||||
|
exactly "v2.2.0-beta", `request` called once with `/v1/settings`, and no button, link, switch or
|
||||||
|
input inside the card.
|
||||||
|
2. **No prefix** — resolve `{ version: 'dev' }`; assert the value text is exactly "dev".
|
||||||
|
3. **Navigation** — assert the sidebar and the drawer list Home, Articles, Users, Integration,
|
||||||
|
Settings in that order with the settings icon on the last; on /settings only "Settings" carries
|
||||||
|
`aria-current="page"`.
|
||||||
|
4. **Loading** — unresolved request; at 149 ms assert no skeleton and that "Version" is present; at
|
||||||
|
150 ms assert a skeleton in place of the value and `aria-busy="true"` on the card; resolve and
|
||||||
|
assert the value and no `aria-busy`.
|
||||||
|
5. **Error, Examples-driven** — reject with `ApiError(500)`, then `NetworkError`; assert the alert
|
||||||
|
text "Couldn't reach RenewCMS. Check your connection and try again.", the "Try again" action, no
|
||||||
|
close button, no title and no "Version" row, with the header still shown. Click "Try again";
|
||||||
|
assert Loading and a second `request`; resolve and assert the Default row.
|
||||||
|
6. **401** — reject with `ApiError(401)`; assert the page shows no alert of its own (the redirect
|
||||||
|
itself is covered by `useApi`'s existing tests).
|
||||||
|
7. **Router meta** — assert the `/settings` route has `meta.auth === 'verified'` and
|
||||||
|
`meta.title === 'Settings'`.
|
||||||
|
8. **Amended shell specs** — update the existing Vitest for `nuxt_ui_shell_foundation` case 14,
|
||||||
|
`dashboard_shell_branding`, users_screen and profile_page to five nav items, in the same change.
|
||||||
|
|
||||||
|
## Visual (`task visual:check -- settings`, desktop and mobile, light and dark)
|
||||||
|
|
||||||
|
Reference: `docs/design/screens/settings.md`; board group "Settings" in `docs/design/source/RenewCMS
|
||||||
|
Screens Back-office.dc.html`; exact values from the `isSettings` block of
|
||||||
|
`docs/design/source/AppFrame.dc.html`. Add the mock to `web/visual/states.ts`. The gate is hard:
|
||||||
|
every capture within 10 %.
|
||||||
|
|
||||||
|
- [ ] Default: mock `GET /v1/settings` returning `{ "version": "v2.2.0-beta" }` (the board's
|
||||||
|
sample). Layout as the frame draws it: the header is a 20/28 semibold title with the muted
|
||||||
|
subtitle 2 px below; the card is the header's next sibling, 20 px below; the card is
|
||||||
|
`--ui-bg` with a 1 px `--ui-border` and no drawn radius; the row is a flex row with
|
||||||
|
`justify-content: space-between`, `align-items: center` and a 16 px gap, the label at the
|
||||||
|
left and the mono value at the right; the whole page is at most 720 px wide.
|
||||||
|
- [ ] Not drawn, no visual state: Loading and Error. Do not add them to `web/visual/states.ts`;
|
||||||
|
Vitest cases 4 and 5 cover them.
|
||||||
|
- [ ] Not covered by screenshots: keyboard order (Tab reaches the "Settings" nav item; on Error,
|
||||||
|
Tab reaches "Try again", and Enter and Space activate it); focus after a navigation; the
|
||||||
|
skeleton pulse under reduced motion.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- With a build made through `task build` or `task release` (`-ldflags -X main.version=...`),
|
||||||
|
open /settings and confirm the value equals the injected version. A build without the flag must
|
||||||
|
show `dev`.
|
||||||
|
- Confirm against a running `task dev` API that an unverified account is sent to /register/pending
|
||||||
|
and a logged-out browser to /login?redirect=/settings&reason=expired.
|
||||||
|
- Confirm the embedded SPA (built without `-tags nofrontend`) serves /settings on a hard refresh,
|
||||||
|
since Vitest never exercises the embedded frontend.
|
||||||
@@ -7,8 +7,8 @@ Feature: API responses never expose a user's secret fields
|
|||||||
credential or a still-valid reset/verification secret
|
credential or a still-valid reset/verification secret
|
||||||
|
|
||||||
Background:
|
Background:
|
||||||
Given the public shape of a user in any API response is exactly seven fields: id, username,
|
Given the public shape of a user in any API response is exactly eight fields: id, username,
|
||||||
email, is_verified, created_at, updated_at and display_name
|
email, is_verified, created_at, updated_at, display_name and role
|
||||||
And password, password_reset_code, verification_code, verification_expiration,
|
And password, password_reset_code, verification_code, verification_expiration,
|
||||||
password_reset_expiration and token_version never appear in any response body, under any key
|
password_reset_expiration and token_version never appear in any response body, under any key
|
||||||
name, regardless of their value or whether they are set
|
name, regardless of their value or whether they are set
|
||||||
@@ -21,7 +21,7 @@ Feature: API responses never expose a user's secret fields
|
|||||||
When the client sends POST /v1/auth/verify with body {"code": "abc123"}
|
When the client sends POST /v1/auth/verify with body {"code": "abc123"}
|
||||||
Then the response status is 200
|
Then the response status is 200
|
||||||
And the response body is a JSON object with exactly the keys id, username, email,
|
And the response body is a JSON object with exactly the keys id, username, email,
|
||||||
is_verified, created_at, updated_at and display_name
|
is_verified, created_at, updated_at, display_name and role
|
||||||
And the response body does not contain the keys password, password_reset_code,
|
And the response body does not contain the keys password, password_reset_code,
|
||||||
verification_code, verification_expiration, password_reset_expiration or token_version
|
verification_code, verification_expiration, password_reset_expiration or token_version
|
||||||
And the response body's is_verified is true
|
And the response body's is_verified is true
|
||||||
|
|||||||
@@ -21,11 +21,12 @@ Package: `test` (black-box), extending `test/account_verification_http_test.go`'
|
|||||||
user id 7. Decode the response body into `map[string]json.RawMessage` (not into `user.User`)
|
user id 7. Decode the response body into `map[string]json.RawMessage` (not into `user.User`)
|
||||||
and assert:
|
and assert:
|
||||||
- the key set is exactly `{"id", "username", "email", "is_verified", "created_at",
|
- the key set is exactly `{"id", "username", "email", "is_verified", "created_at",
|
||||||
"updated_at", "display_name"}`;
|
"updated_at", "display_name", "role"}`;
|
||||||
- none of `password`, `password_reset_code`, `verification_code`,
|
- none of `password`, `password_reset_code`, `verification_code`,
|
||||||
`verification_expiration`, `password_reset_expiration`, `token_version` is present;
|
`verification_expiration`, `password_reset_expiration`, `token_version` is present;
|
||||||
- `is_verified` unmarshals to `true`;
|
- `is_verified` unmarshals to `true`;
|
||||||
- `display_name` unmarshals to `""`.
|
- `display_name` unmarshals to `""`;
|
||||||
|
- `role` unmarshals to `"owner"` (seeded user 7 has `Role: owner`).
|
||||||
5. Rejected verify: same seed, `{"code":"wrong-code"}` → assert status `403` and that the raw
|
5. Rejected verify: same seed, `{"code":"wrong-code"}` → assert status `403` and that the raw
|
||||||
response body bytes, treated as a string, contain none of the substrings `password`,
|
response body bytes, treated as a string, contain none of the substrings `password`,
|
||||||
`verification_code`, `password_reset_code`, `verification_expiration`,
|
`verification_code`, `password_reset_code`, `verification_expiration`,
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
Feature: Users have a role, owner or admin, and only the owner can invite
|
||||||
|
|
||||||
|
As the person who registered the workspace
|
||||||
|
I want my account to be the owner and everyone I invite to be an admin
|
||||||
|
So that only I can invite people, while every admin keeps the same access to articles,
|
||||||
|
the users list, their own profile and Settings
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given a user has a role that is exactly "owner" or "admin", stored on the user record and read
|
||||||
|
from the user repository on every request, never from the jwt claims
|
||||||
|
And the first registered user is the owner: CreateUser creates the user with role "owner",
|
||||||
|
and registration is only possible while no verified user exists
|
||||||
|
And every user created by accepting an invite is an admin: AcceptInvite creates the user with
|
||||||
|
role "admin", whatever the inviter's role
|
||||||
|
And there is exactly one owner and no endpoint changes, transfers or removes a role
|
||||||
|
And AutoMigrate adds the role column to existing databases and backfills it: the user with the
|
||||||
|
lowest id becomes "owner" and every other user "admin"; a database that already has roles
|
||||||
|
is left unchanged by a later start
|
||||||
|
And the public user shape (api/pkg/publicuser) is id, username, email, is_verified, created_at,
|
||||||
|
updated_at, display_name and role
|
||||||
|
And the users list user items are id, kind, username, display_name, email, role, status,
|
||||||
|
created_at; invite items are unchanged: id, kind, email, status, created_at
|
||||||
|
And POST /v1/user/invite is owner-only: after the jwt, current-token and verified checks, a
|
||||||
|
RequireOwner check loads the user with GetUserUseCase and refuses any role other than
|
||||||
|
"owner" with 403 and the plain-text body apperr.OwnerRequiredErrorMessage
|
||||||
|
"Only the owner can do this.", before the rate limiter, the body decoding and the validation
|
||||||
|
And GET /v1/user/ stays open to every verified user, owner and admin alike
|
||||||
|
And error responses are plain text from http.Error, success responses are JSON
|
||||||
|
|
||||||
|
Scenario: The first registered user is the owner
|
||||||
|
Given the user repository is empty
|
||||||
|
When the client sends POST /v1/auth/register with username "marta", password "hunter2example12",
|
||||||
|
email "marta@renew.example"
|
||||||
|
Then the response status is 200
|
||||||
|
And the user repository holds one user with username "marta" and role "owner"
|
||||||
|
|
||||||
|
Scenario: A user created by accepting an invite is an admin
|
||||||
|
Given a verified owner "marta" and a pending invite for "lea.martin@renew.example" with a known raw code
|
||||||
|
When the client sends POST /v1/auth/invite/accept with that code, username "lea" and password "limewash2026"
|
||||||
|
Then the response status is 200
|
||||||
|
And the user repository holds user "lea" with role "admin"
|
||||||
|
And user "marta" still has role "owner"
|
||||||
|
|
||||||
|
Scenario Outline: GET /v1/auth/me returns the role of the session user
|
||||||
|
Given a verified user "<username>" with role "<role>" and a valid jwt cookie for that user
|
||||||
|
When the client sends GET /v1/auth/me
|
||||||
|
Then the response status is 200
|
||||||
|
And the response body has the key role with value "<role>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| username | role |
|
||||||
|
| marta | owner |
|
||||||
|
| lea | admin |
|
||||||
|
|
||||||
|
Scenario: An unverified owner sees their role on /auth/me
|
||||||
|
Given an unverified user "bob" with role "owner" and a valid jwt cookie
|
||||||
|
When the client sends GET /v1/auth/me
|
||||||
|
Then the response status is 200
|
||||||
|
And the response body's role is "owner" and is_verified is false
|
||||||
|
|
||||||
|
Scenario: The users list carries email and role on accepted users
|
||||||
|
Given verified owner id 1 "marta" with email "marta@renew.example"
|
||||||
|
And admin id 2 "jonas" with email "jonas@renew.example"
|
||||||
|
And admin id 3 "ines" with display_name "Inès Duarte" and email "ines.duarte@renew.example"
|
||||||
|
And a pending invite for "sam.oliveira@renew.example"
|
||||||
|
When the client sends GET /v1/user/ with a valid jwt cookie for user id 2
|
||||||
|
Then the response status is 200
|
||||||
|
And the user items have exactly the keys id, kind, username, display_name, email, role, status, created_at
|
||||||
|
And user 1 has email "marta@renew.example" and role "owner"; users 2 and 3 have role "admin" and their own email
|
||||||
|
And the invite item has exactly the keys id, kind, email, status, created_at
|
||||||
|
And no item has a key named password, password_reset_code, verification_code,
|
||||||
|
verification_expiration, password_reset_expiration, token_version, code, hashed_code,
|
||||||
|
invited_by or accepted_at
|
||||||
|
|
||||||
|
Scenario: The owner can invite
|
||||||
|
Given a verified owner id 1 "marta" and a valid jwt cookie for user id 1
|
||||||
|
When the client sends POST /v1/user/invite with body {"email": "sam.oliveira@renew.example"}
|
||||||
|
Then the response status is 201
|
||||||
|
And one invite exists and one "invitation" email was sent
|
||||||
|
|
||||||
|
Scenario: An admin cannot invite
|
||||||
|
Given a verified admin id 2 "jonas" and a valid jwt cookie for user id 2
|
||||||
|
When the client sends POST /v1/user/invite with body {"email": "sam.oliveira@renew.example"}
|
||||||
|
Then the response status is 403
|
||||||
|
And the response body is exactly apperr.OwnerRequiredErrorMessage, as plain text
|
||||||
|
And the invite repository is still empty
|
||||||
|
And no email was sent
|
||||||
|
|
||||||
|
Scenario Outline: The owner check comes before validation and the rate limiter
|
||||||
|
Given a verified admin id 2 and a valid jwt cookie for user id 2
|
||||||
|
When the client sends POST /v1/user/invite with body <body>
|
||||||
|
Then the response status is 403
|
||||||
|
And no invite was created and no email was sent
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| body |
|
||||||
|
| {"email": "not-an-email"} |
|
||||||
|
| not json |
|
||||||
|
|
||||||
|
Scenario: An admin's refused invites do not use up the rate limit
|
||||||
|
Given AUTH_RATE_LIMIT_MAX_ATTEMPTS is 2 for a window covering the whole test
|
||||||
|
When an admin at IP "203.0.113.20" sends 3 POST /v1/user/invite requests
|
||||||
|
Then all 3 responses are 403 and none is 429
|
||||||
|
|
||||||
|
Scenario: The role is read on every request, not from the token
|
||||||
|
Given a verified user id 2 whose stored role is "owner", with a valid jwt cookie
|
||||||
|
And the stored role changes to "admin" without the token changing
|
||||||
|
When the client sends POST /v1/user/invite with a valid body
|
||||||
|
Then the response status is 403
|
||||||
|
|
||||||
|
Scenario: An admin can still list users
|
||||||
|
Given a verified admin id 2 and a valid jwt cookie for user id 2
|
||||||
|
When the client sends GET /v1/user/
|
||||||
|
Then the response status is 200
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# QA procedure: user_roles
|
||||||
|
|
||||||
|
Package: `test` (black-box). Reuse `mockUserRepo`, `stubHasher`, `mockMailRepo`, `mockInviteRepo`.
|
||||||
|
No live server, no real SQLite file, no real SMTP.
|
||||||
|
|
||||||
|
## Setup shared by every case
|
||||||
|
1. Call `validator.InitValidator()` once.
|
||||||
|
2. Use cases: `NewGetUserUseCase`, `NewCreateInviteUseCase`, `NewListUsersAndInvitesUseCase`,
|
||||||
|
`NewCreateUserUseCase`, `NewAcceptInviteUseCase` over the fakes.
|
||||||
|
3. Router mirrors `NewUserRouter`: `jwtauth.Verifier` + `Authenticator` with
|
||||||
|
`jwtauth.New("HS256", []byte("test-secret"), nil)`, `RequireCurrentToken`, `RequireVerifiedUser`,
|
||||||
|
`GET /`, and a group with `RequireOwner(getUser)`, `TrustedProxyRealIP(nil)`,
|
||||||
|
`NewRateLimiter(2, time.Minute)`, `POST /invite`. A second router mirrors `NewAuthRouter` for
|
||||||
|
`/register`, `/invite/accept` and `/me`.
|
||||||
|
4. Seed: owner id 1 "marta" (role owner), admin id 2 "jonas" (role admin), both verified.
|
||||||
|
Cookies carry `user_id` and `token_version`, and never a role.
|
||||||
|
|
||||||
|
## Roles at creation
|
||||||
|
5. Empty repo, `POST /v1/auth/register` -> 200, the stored user has `Role == user.RoleOwner`.
|
||||||
|
6. Pending invite with a known code (stubHasher), `POST /v1/auth/invite/accept` -> 200, the stored
|
||||||
|
user has `Role == user.RoleAdmin`, and user 1 is still owner.
|
||||||
|
7. Use-case level: `CreateUser` returns a user with `RoleOwner`; `AcceptInvite` returns `RoleAdmin`.
|
||||||
|
|
||||||
|
## GET /v1/auth/me
|
||||||
|
8. Table over owner and admin: 200, decode into `map[string]json.RawMessage`, key `role` equals the stored role.
|
||||||
|
9. Unverified owner -> 200, `role` "owner", `is_verified` false.
|
||||||
|
10. The key set of the public user is exactly the eight fields, and `POST /v1/auth/verify` returns the same eight.
|
||||||
|
|
||||||
|
## GET /v1/user/
|
||||||
|
11. Seed three users plus a pending invite. 200; user items have exactly the keys id, kind, username,
|
||||||
|
display_name, email, role, status, created_at; email and role match the seed. The invite item has
|
||||||
|
exactly id, kind, email, status, created_at. No forbidden key appears anywhere.
|
||||||
|
12. Cookie of admin 2 -> 200.
|
||||||
|
|
||||||
|
## POST /v1/user/invite
|
||||||
|
13. Owner cookie, valid body -> 201, one invite, one "invitation" mail.
|
||||||
|
14. Admin cookie, valid body -> 403, body exactly `apperr.OwnerRequiredErrorMessage`, `Content-Type`
|
||||||
|
is not JSON-decoded (plain text), no invite, no mail.
|
||||||
|
15. Admin cookie with `{"email":"not-an-email"}` and with `not json` -> 403 both.
|
||||||
|
16. Rate limit 2: admin sends 3 requests -> 403, 403, 403.
|
||||||
|
17. Flip user 2's stored role from owner to admin between two requests with the same cookie ->
|
||||||
|
second request 403.
|
||||||
|
18. Existing auth table from invitations.qa.md (no cookie 401, unverified 403, stale token 401) is
|
||||||
|
unchanged; the unverified 403 body remains `apperr.VerificationRequiredErrorMessage`.
|
||||||
|
|
||||||
|
## Use case level
|
||||||
|
19. `RequireOwner` with a user id that no longer exists -> 401 `apperr.UnauthorizedErrorMessage`;
|
||||||
|
with an unexpected repository error -> 500.
|
||||||
|
|
||||||
|
## Manual verification (not exercised by the Go tests)
|
||||||
|
- Persistence backfill: copy a SQLite file from before this change with 3 users and no role column.
|
||||||
|
Start the app: the column exists, the lowest id is `owner`, the others `admin`. Restart: nothing
|
||||||
|
changes. Start against a fresh file: registering creates an owner.
|
||||||
|
- Layering check by review: `Role` and the sentinel/constants live in `internal/domain/user`; GORM
|
||||||
|
tags only in `persistence/models`, converted by the mapper.
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
Feature: Users row actions: Cancel invite and Renew invite
|
||||||
|
|
||||||
|
As the owner of a RenewCMS workspace
|
||||||
|
I want to cancel a pending invite and renew an expired one from the Users list
|
||||||
|
So that I can correct a wrong address or resend a lapsed link without leaving the page
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given /users is the verified route of features/users_screen.feature, rendered as UsersPage with
|
||||||
|
UsersTable (md and up) or UserCardList (below md), per docs/design/screens/users.md
|
||||||
|
And the backend already exists (features/invite_management.feature) and this slice changes no Go:
|
||||||
|
DELETE /v1/user/invite/{id} answers 204 with an empty body, and POST /v1/user/invite/{id}/renew
|
||||||
|
answers 200 with {id, kind "invite", email, status "pending", created_at, expires_at}
|
||||||
|
And useUsers gains cancelInvite(id), which sends DELETE /v1/user/invite/{id} with no body, and
|
||||||
|
renewInvite(id), which sends POST /v1/user/invite/{id}/renew with no body
|
||||||
|
And the actions are shown only when the session user's role from GET /v1/auth/me is "owner";
|
||||||
|
for "admin", or any other or absent value, no action button is rendered and the sixth column
|
||||||
|
stays empty; this is not drawn in docs/design, so it has no visual state and is covered
|
||||||
|
by Vitest only
|
||||||
|
And the sixth column (desktop) or the last line of the card (below md) holds at most one
|
||||||
|
action: "Cancel invite" on a Pending row, "Renew invite" on an Expired row, nothing on an
|
||||||
|
Accepted row
|
||||||
|
And each action is an outline button: 28 px high on desktop (12 px medium text, 13 px icon,
|
||||||
|
9 px side padding, --ui-border-accented border, --ui-bg fill, no wrapping) and 44 px high
|
||||||
|
below md (14 px side padding, 14 px icon); UButton variant "outline" size "xs"
|
||||||
|
And "Cancel invite" has the icon user-x and text in --ui-error; "Renew invite" has the icon
|
||||||
|
refresh-cw and text --ui-text-highlighted
|
||||||
|
And below md the action is the last line of the card, under the badges line
|
||||||
|
And "Cancel invite" opens ConfirmDialog (tone "danger") through useOverlay: title "Cancel this
|
||||||
|
invite?", description "The link sent to {email} will stop working. You can invite the address
|
||||||
|
again later.", cancel button "Keep invite", confirm button "Cancel invite", pending label
|
||||||
|
"Cancelling…"; the action runs inside the dialog, so the failure notice shows in the dialog
|
||||||
|
And "Renew invite" asks nothing and sends the request at once
|
||||||
|
And a request failure is any 500, any network failure that never reaches the server, and any
|
||||||
|
other status except 401 and 403; 401 and 403 are handled entirely by useApi's global handling
|
||||||
|
(features/api_client_global_error_handling.feature); the response body text is never shown
|
||||||
|
verbatim
|
||||||
|
And the fixture is the Default fixture of features/users_screen.feature: invite id 2
|
||||||
|
"sam.oliveira@renew.example" pending 27 Sep 2026; invite id 1 "p.huber@gmail.com" with
|
||||||
|
display_name "Paul Huber" expired 3 Aug 2026; users 3, 2, 1; the session user is "marta",
|
||||||
|
role "owner"; rows are keyed by kind and id
|
||||||
|
|
||||||
|
Scenario: Default: actions sit on the right of the Pending and Expired rows only
|
||||||
|
Given GET /v1/user/ resolves 200 with the Default fixture
|
||||||
|
When the owner navigates to /users at desktop
|
||||||
|
Then the first row "sam.oliveira@renew.example" ends with "Cancel invite" (icon user-x, text --ui-error)
|
||||||
|
And the second row "p.huber@gmail.com" ends with "Renew invite" (icon refresh-cw)
|
||||||
|
And the three Accepted rows have an empty sixth cell
|
||||||
|
And below md the same two cards end with the same buttons as 44 px buttons
|
||||||
|
|
||||||
|
Scenario Outline: Non-owners see no row actions
|
||||||
|
Given the session user has role "<role>" and GET /v1/user/ resolves 200 with the Default fixture
|
||||||
|
When the user navigates to /users at desktop and at a below-md width
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| role | result |
|
||||||
|
| admin | no "Cancel invite" and no "Renew invite" button exists |
|
||||||
|
| (none) | no "Cancel invite" and no "Renew invite" button exists |
|
||||||
|
| owner | "Cancel invite" and "Renew invite" are present once each |
|
||||||
|
|
||||||
|
Scenario: Cancel invite: confirm
|
||||||
|
Given the Default state has loaded
|
||||||
|
When the owner activates "Cancel invite" on the "sam.oliveira@renew.example" row
|
||||||
|
Then a danger modal opens titled "Cancel this invite?"
|
||||||
|
And its text reads "The link sent to sam.oliveira@renew.example will stop working. You can invite
|
||||||
|
the address again later."
|
||||||
|
And its buttons are "Keep invite" and "Cancel invite" (danger), and no request has been sent
|
||||||
|
|
||||||
|
Scenario: Cancel invite: "Keep invite" closes the dialog and changes nothing
|
||||||
|
Given the "Cancel this invite?" dialog is open for "sam.oliveira@renew.example"
|
||||||
|
When the owner activates "Keep invite"
|
||||||
|
Then the dialog closes, DELETE /v1/user/invite/2 is never sent and all 5 rows remain
|
||||||
|
|
||||||
|
Scenario: Cancel invite: sending
|
||||||
|
Given the "Cancel this invite?" dialog is open for "sam.oliveira@renew.example"
|
||||||
|
When the owner activates "Cancel invite" and DELETE /v1/user/invite/2 has not resolved
|
||||||
|
Then DELETE /v1/user/invite/2 was sent once
|
||||||
|
And the confirm button reads "Cancelling…" with a loading indicator
|
||||||
|
And "Keep invite" is disabled
|
||||||
|
And Esc and a backdrop click do not close the dialog
|
||||||
|
|
||||||
|
Scenario Outline: Cancel invite: failed
|
||||||
|
Given the "Cancel this invite?" dialog is open for "sam.oliveira@renew.example"
|
||||||
|
When the owner activates "Cancel invite" and DELETE /v1/user/invite/2 <failure>
|
||||||
|
Then the dialog stays open, with an error notice inside it reading "Couldn't cancel the invite.
|
||||||
|
Try again in a moment."
|
||||||
|
And "Keep invite" and "Cancel invite" are enabled again
|
||||||
|
And all 5 rows remain and no toast is raised
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| resolves with a 500 response |
|
||||||
|
| resolves with a 500 response whose body is some other text |
|
||||||
|
| never reaches the server |
|
||||||
|
| resolves with a 404 response |
|
||||||
|
|
||||||
|
Scenario: Cancel invite: retrying after a failure
|
||||||
|
Given the dialog shows the failure notice
|
||||||
|
When the owner activates "Cancel invite" again and DELETE /v1/user/invite/2 resolves 204
|
||||||
|
Then DELETE /v1/user/invite/2 was sent a second time
|
||||||
|
And the dialog closes and the row is removed
|
||||||
|
|
||||||
|
Scenario: Cancel invite: done
|
||||||
|
Given the "Cancel this invite?" dialog is open for "sam.oliveira@renew.example"
|
||||||
|
When the owner activates "Cancel invite" and DELETE /v1/user/invite/2 resolves 204
|
||||||
|
Then the dialog closes
|
||||||
|
And the row "sam.oliveira@renew.example" is gone and the other 4 rows remain in their order
|
||||||
|
And GET /v1/user/ is not called again
|
||||||
|
And a toast appears: color success, icon i-lucide-circle-check, id "invite-cancelled-2", title
|
||||||
|
"Invite cancelled", description "sam.oliveira@renew.example can no longer use the link."
|
||||||
|
|
||||||
|
Scenario: Cancel invite: an Expired row can't be cancelled from the list
|
||||||
|
Given the Default state has loaded
|
||||||
|
Then the "p.huber@gmail.com" row offers "Renew invite" and no "Cancel invite"
|
||||||
|
|
||||||
|
Scenario: Renew invite: sending
|
||||||
|
Given the Default state has loaded
|
||||||
|
When the owner activates "Renew invite" on the "p.huber@gmail.com" row and
|
||||||
|
POST /v1/user/invite/1/renew has not resolved
|
||||||
|
Then POST /v1/user/invite/1/renew was sent once with no body and no confirmation was shown
|
||||||
|
And on that row the button reads "Renewing…" with the icon loader-circle at 50 % opacity, disabled
|
||||||
|
And no other row's button changes and the "Cancel invite" button of "sam.oliveira@renew.example" stays enabled
|
||||||
|
And a second activation of the busy button sends nothing
|
||||||
|
|
||||||
|
Scenario: Renew invite: done
|
||||||
|
Given POST /v1/user/invite/1/renew was sent from the "p.huber@gmail.com" row
|
||||||
|
When it resolves 200 with id 1, kind "invite", email "p.huber@gmail.com", status "pending",
|
||||||
|
created_at now and expires_at 3 days later
|
||||||
|
Then the row moves to the top of the list as Pending, created "Today", drawn with the
|
||||||
|
--ui-bg-elevated background, keeping its display name "Paul Huber" and role "admin", and now
|
||||||
|
ends with "Cancel invite"
|
||||||
|
And "sam.oliveira@renew.example" is now the second row and the other rows are unchanged
|
||||||
|
And exactly one row exists for "p.huber@gmail.com" and GET /v1/user/ is not called again
|
||||||
|
And a toast appears: color success, icon i-lucide-circle-check, id "invite-renewed-1", title
|
||||||
|
"Invite renewed", description "p.huber@gmail.com has 3 days to accept the new link."
|
||||||
|
|
||||||
|
Scenario: Renew invite: renewing a Pending row is not offered
|
||||||
|
Given the Default state has loaded
|
||||||
|
Then the "sam.oliveira@renew.example" row offers "Cancel invite" and no "Renew invite"
|
||||||
|
|
||||||
|
Scenario Outline: Renew invite: failed
|
||||||
|
Given the Default state has loaded
|
||||||
|
When the owner activates "Renew invite" on the "p.huber@gmail.com" row and
|
||||||
|
POST /v1/user/invite/1/renew <failure>
|
||||||
|
Then a toast appears: color error, icon i-lucide-circle-x, id "invite-renew-failed-1", title
|
||||||
|
"Couldn't renew the invite", description "Try again in a moment."
|
||||||
|
And the row stays Expired in its place, with "Renew invite" enabled again
|
||||||
|
And the list is otherwise unchanged
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| resolves with a 500 response |
|
||||||
|
| resolves with a 500 response whose body is some other text |
|
||||||
|
| never reaches the server |
|
||||||
|
| resolves with a 404 response |
|
||||||
|
|
||||||
|
Scenario: Renew invite: retrying after a failure
|
||||||
|
Given the failed toast has appeared for "p.huber@gmail.com"
|
||||||
|
When the owner activates "Renew invite" again and POST /v1/user/invite/1/renew resolves 200
|
||||||
|
Then the "Invite renewed" toast is raised and the row is Pending on top
|
||||||
|
|
||||||
|
Scenario: Renew invite: only the busy row is busy
|
||||||
|
Given the fixture also holds Expired invite id 7 "old@renew.example"
|
||||||
|
When the owner activates "Renew invite" on "p.huber@gmail.com" and it has not resolved
|
||||||
|
Then "Renew invite" on "old@renew.example" is still enabled and can be activated
|
||||||
|
|
||||||
|
Scenario: Actions after a new invite is sent
|
||||||
|
Given the Default state has loaded and an invite for "lea.martin@renew.example" was sent (201)
|
||||||
|
Then the new first row ends with "Cancel invite"
|
||||||
|
|
||||||
|
Scenario: Cancelling a just-renewed row
|
||||||
|
Given "p.huber@gmail.com" was renewed and is the first row
|
||||||
|
When the owner confirms "Cancel invite" for it and DELETE /v1/user/invite/1 resolves 204
|
||||||
|
Then the row is gone and the toast "Invite cancelled" is raised
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
# QA: Users row actions (Cancel invite, Renew invite)
|
||||||
|
|
||||||
|
## Implementation note for coder (informational, not a QA assertion)
|
||||||
|
|
||||||
|
No Go change. Toasts use useToast().add({ id, color, icon, title, description }):
|
||||||
|
- cancelled: id "invite-cancelled-{id}", color success, icon i-lucide-circle-check, title "Invite cancelled",
|
||||||
|
description "{email} can no longer use the link."
|
||||||
|
- renewed: id "invite-renewed-{id}", color success, icon i-lucide-circle-check, title "Invite renewed",
|
||||||
|
description "{email} has 3 days to accept the new link."
|
||||||
|
- renew failed: id "invite-renew-failed-{id}", color error, icon i-lucide-circle-x, title "Couldn't renew the invite",
|
||||||
|
description "Try again in a moment."
|
||||||
|
|
||||||
|
Cancel runs through ConfirmDialog (tone "danger", cancelLabel "Keep invite", confirmLabel "Cancel invite",
|
||||||
|
pendingLabel "Cancelling…"); its action throws an Error whose message is "Couldn't cancel the invite. Try again in
|
||||||
|
a moment." for any failure except 401/403 (global handling), so the dialog shows it. Remove the 10.5 % exception
|
||||||
|
from the "users" > Default state in web/visual/states.ts.
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mock useApi's `request` for GET /v1/user/, DELETE /v1/user/invite/{id} and POST /v1/user/invite/{id}/renew. Mount
|
||||||
|
UsersPage inside DashboardShell with a verified owner session (id 1, "marta", role "owner") and a test router at
|
||||||
|
/users. Default fixture as in features/users_screen.qa.md. No test freezes the system date; the renewed row's
|
||||||
|
"Today" label is not asserted. Run layout cases at desktop and below-md widths (mock matchMedia).
|
||||||
|
|
||||||
|
1. Default actions: row 1 has "Cancel invite" (user-x), row 2 "Renew invite" (refresh-cw), Accepted rows have
|
||||||
|
none; at below-md the same buttons sit last in the cards.
|
||||||
|
2. Non-owners, Examples-driven: role "admin", role absent, role "owner"; assert presence or absence of both
|
||||||
|
buttons at both widths.
|
||||||
|
3. Cancel invite: confirm: click "Cancel invite" on row 1; assert dialog title, text with the address, "Keep
|
||||||
|
invite", "Cancel invite", and that `request` was not called with DELETE.
|
||||||
|
4. Keep invite: click it; assert the dialog closed, no DELETE, 5 rows.
|
||||||
|
5. Cancel invite: sending: unresolved DELETE; assert one call to DELETE /v1/user/invite/2 (no body), "Cancelling…",
|
||||||
|
"Keep invite" disabled, Escape and backdrop click do not close.
|
||||||
|
6. Cancel invite: failed, Examples-driven: ApiError(500), ApiError(500) with other text, ApiError(404),
|
||||||
|
NetworkError; assert the dialog stays open with the notice "Couldn't cancel the invite. Try again in a moment."
|
||||||
|
once (never the raw body), buttons re-enabled, 5 rows, no toast.
|
||||||
|
7. Cancel invite: retry: after 6, resolve 204 on the second click; assert two DELETE calls, dialog closed, row gone.
|
||||||
|
8. Cancel invite: done: resolve 204; assert dialog closed, row 1 gone, 4 rows in order, no second GET, toast
|
||||||
|
raised with the id, color, icon, title and description above.
|
||||||
|
9. 401 and 403 on DELETE and on renew: assert the global handling runs and no local notice or toast is added.
|
||||||
|
10. Renew invite: sending: unresolved POST; assert one call to POST /v1/user/invite/1/renew with no body, no
|
||||||
|
dialog, the row-2 button reads "Renewing…", is disabled, has the loader-circle icon and 50 % opacity class; row
|
||||||
|
1's "Cancel invite" is enabled; a second click sends nothing.
|
||||||
|
11. Only the busy row is busy: two Expired rows; renew one, assert the other button is enabled and usable.
|
||||||
|
12. Renew invite: done: resolve 200 with the response shape; assert "p.huber@gmail.com" is first, Pending, has the
|
||||||
|
--ui-bg-elevated class, keeps "Paul Huber", ends with "Cancel invite", "sam.oliveira@renew.example" second, one
|
||||||
|
row for the address, no second GET, and the toast (id, color, icon, title, description).
|
||||||
|
13. Renew invite: failed, Examples-driven: ApiError(500), ApiError(500) with other text, ApiError(404),
|
||||||
|
NetworkError; assert the error toast, the row still Expired in place, the button enabled again with the label
|
||||||
|
"Renew invite".
|
||||||
|
14. Renew retry: after 13, resolve 200; assert the success toast and the row on top.
|
||||||
|
15. Interplay: a row from a fresh invite (201) shows "Cancel invite"; cancelling a just-renewed row removes it and
|
||||||
|
raises "Invite cancelled".
|
||||||
|
16. Invite-only rule: assert no "Renew invite" on a Pending row and no "Cancel invite" on an Expired row.
|
||||||
|
|
||||||
|
## Visual (task visual:check -- users, desktop and mobile, light and dark)
|
||||||
|
|
||||||
|
Reference: docs/design/screens/users.md; board group "Users" in `docs/design/source/RenewCMS Screens
|
||||||
|
Back-office.dc.html`; exact values in `docs/design/source/AppFrame.dc.html`. Layout (button size, position in the
|
||||||
|
sixth column and on the card, dialog geometry) is taken from the board frame, not components.md. The gate is hard:
|
||||||
|
every capture of every non-skipped state must be within 10 %, both viewports, both themes. Use the board's sample
|
||||||
|
data: the existing `usersFixture` (sam.oliveira@renew.example pending 27 Sep 2026; p.huber@gmail.com "Paul Huber"
|
||||||
|
expired 3 Aug 2026), session marta/owner. Add these 7 states to `users` in web/visual/states.ts:
|
||||||
|
|
||||||
|
- [ ] Cancel invite: confirm: steps click "Cancel invite" on the sam.oliveira row; dialog "Cancel this invite?" with
|
||||||
|
text naming sam.oliveira@renew.example, "Keep invite", "Cancel invite".
|
||||||
|
- [ ] Cancel invite: sending: mock `DELETE /v1/user/invite/2` status 204 with `hang: true`; steps open the dialog and
|
||||||
|
click "Cancel invite"; "Cancelling…" loading, "Keep invite" disabled.
|
||||||
|
- [ ] Cancel invite: failed: mock `DELETE /v1/user/invite/2` status 500; steps open the dialog and confirm; the
|
||||||
|
notice "Couldn't cancel the invite. Try again in a moment." inside the dialog, buttons enabled.
|
||||||
|
- [ ] Cancel invite: done: `{ path: '/users', skip: 'clock-sensitive' }` (per the user's request; the design does
|
||||||
|
not mark it clock-sensitive). Prints SKIP, never investigated or date-frozen. Vitest case 8 covers it.
|
||||||
|
- [ ] Renew invite: sending: mock `POST /v1/user/invite/1/renew` status 200 with `hang: true`; steps click "Renew
|
||||||
|
invite" on the p.huber row; only that button shows "Renewing…", loader-circle, 50 % opacity.
|
||||||
|
- [ ] Renew invite: done: `{ path: '/users', skip: 'clock-sensitive' }` ("Today"). Vitest case 12 covers it.
|
||||||
|
- [ ] Renew invite: failed: mock `POST /v1/user/invite/1/renew` status 500; steps click "Renew invite"; the error
|
||||||
|
toast "Couldn't renew the invite" / "Try again in a moment." is visible and the p.huber row is Expired with
|
||||||
|
"Renew invite". Keep the toast on screen for the capture; if the runner can't, stop and ask.
|
||||||
|
- [ ] Default: with the exception removed it passes at 10 % with the drawn buttons; if it fails, stop and ask (no
|
||||||
|
exception without approval).
|
||||||
|
- [ ] Not drawn, no visual state: non-owner rendering and the 404 fallback. Vitest only (cases 2, 6, 13).
|
||||||
|
- [ ] Not covered by screenshots: keyboard order (Tab reaches each row action; in the dialog focus starts on "Keep
|
||||||
|
invite", is trapped, Esc closes it except while Cancelling…, focus return after the dialog closes); hover and
|
||||||
|
active on the buttons; motion (modal 240 ms, toast enter and exit), stopped under reduced motion.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- Real round trips against `task dev`, as owner: cancel a pending invite (row disappears, the old link at
|
||||||
|
/invite/accept?c=... answers "This invite link doesn't work."), renew an expired one (row moves to top with
|
||||||
|
"Today", old link dead, new link works), and reload to confirm the order matches the API.
|
||||||
|
- Real invitation email on renew needs real or sandboxed SMTP (`SMTP_HOST` and related vars): confirm the new mail
|
||||||
|
arrives with the new link and the old one no longer works.
|
||||||
|
- Failure paths with the API stopped or SMTP failing: the renew toast and the cancel dialog notice appear, and a
|
||||||
|
retry succeeds.
|
||||||
|
- Admin session against `task dev`: no row actions are shown.
|
||||||
|
- Toast placement and stacking on desktop (bottom right) and above the pinned "Invite user" button on mobile.
|
||||||
|
- Focus after a successful cancel (the row is gone) lands somewhere sensible.
|
||||||
|
- "Today" and the elevated row on a live app after Renew, since visual:check skips it.
|
||||||
+106
-47
@@ -12,43 +12,63 @@ Feature: Users screen and InviteUserModal
|
|||||||
And UsersPage calls GET /v1/user/ once per navigation, and InviteUserModal sends POST
|
And UsersPage calls GET /v1/user/ once per navigation, and InviteUserModal sends POST
|
||||||
/v1/user/invite; both endpoints already exist (features/invitations.feature) and this slice
|
/v1/user/invite; both endpoints already exist (features/invitations.feature) and this slice
|
||||||
wires the SPA to them unchanged, with no Go change
|
wires the SPA to them unchanged, with no Go change
|
||||||
And the list items keep the API shape: kind "user" (id, username, display_name, status
|
And the list items keep the API shape: user items are kind "user" (id, username, display_name,
|
||||||
"accepted", created_at) or kind "invite" (id, email, status "pending" or "expired",
|
email, role "owner" or "admin", status "accepted", created_at) or kind "invite" (id, email,
|
||||||
created_at); the list is used in the order the API returns it (created date, newest first),
|
status "pending" or "expired", created_at); the list is used in the order the API returns it
|
||||||
and rows are keyed by kind and id, because a user and an invite can share a numeric id
|
(created date, newest first), and rows are keyed by kind and id, because a user and an
|
||||||
|
invite can share a numeric id
|
||||||
And DashboardShell's navigation gains "Users" (icon users, linking to /users) between
|
And DashboardShell's navigation gains "Users" (icon users, linking to /users) between
|
||||||
"Articles" and "Integration", in the sidebar and in the mobile drawer, so it lists Home,
|
"Articles" and "Integration", in the sidebar and in the mobile drawer, so it lists Home,
|
||||||
Articles, Users, Integration in that order; "Users" has aria-current="page" on /users; the
|
Articles, Users, Integration, Settings in that order; "Users" has aria-current="page" on /users; the
|
||||||
"four navigation destinations" scenario of nuxt_ui_shell_foundation.feature and the items of
|
"five navigation destinations" scenario of nuxt_ui_shell_foundation.feature and the items of
|
||||||
dashboard_shell_branding.feature are amended accordingly
|
dashboard_shell_branding.feature are amended accordingly
|
||||||
And the PageHeader shows breadcrumb "Users" (mobile title "Users")
|
And the PageHeader shows breadcrumb "Users" (mobile title "Users")
|
||||||
And the page header is the title "Users" with the subtitle "Everyone who can sign in and work
|
And the page header is the title "Users" with the subtitle "Everyone who can sign in and work
|
||||||
on your articles." and, on desktop (md and up), a primary "Invite user" button (icon
|
on your articles." and, on desktop (md and up) for the owner, a primary "Invite user" button
|
||||||
user-plus) at the right of the header
|
(icon user-plus) at the right of the header
|
||||||
And below md, "Invite user" is instead a full-width 48 px button (icon user-plus) pinned 16 px
|
And below md, for the owner, "Invite user" is instead a full-width 48 px button (icon
|
||||||
from the left, right and bottom of the screen with the popover shadow, and it is hidden
|
user-plus) pinned 16 px from the left, right and bottom of the screen with the popover
|
||||||
while InviteUserModal is open
|
shadow, and it is hidden while InviteUserModal is open
|
||||||
And the list is rendered as UsersTable (desktop, md and up: columns Username, Invite status,
|
And "Invite user" (desktop header button and the mobile pinned button) is shown only when the
|
||||||
Created, grid minmax(0,1fr) 160px 160px, 36 px header, 44 px rows, an arrow-down icon on the
|
session user's role from GET /v1/auth/me is "owner"; for "admin", or any other or absent
|
||||||
Created header) or UserCardList (below md: 68 px minimum row height, the name line, then the
|
value, neither button is rendered, the pinned button's bottom space is not reserved, and
|
||||||
InviteStatusBadge and "Created {date}"), both fed by the same items array; rows have no
|
the "Only you" hint is hidden; this is not drawn in docs/design, so it has no visual state
|
||||||
actions and are not clickable
|
and is covered by Vitest only
|
||||||
And a user row's name cell shows the display name first (medium weight, highlighted) with the
|
And the list is rendered as UsersTable (desktop, md and up) or UserCardList (below md), both
|
||||||
username beside it in muted text when display_name is not empty, otherwise the username
|
fed by the same items array; rows are not clickable; row actions are specified in features/users_row_actions.feature
|
||||||
alone (medium weight, highlighted); an invite row shows the email address in regular weight,
|
And UsersTable has the columns Email, Display name, Role, Invite status and Created, plus an
|
||||||
toned; an accepted user is never shown by email
|
unlabeled, empty actions column kept so the grid matches the board: grid
|
||||||
And the row whose kind is "user" and whose id equals the session user's id (from GET
|
minmax(0,1.3fr) minmax(0,1fr) 84px 120px 110px 150px with a 12 px gap, a 36 px header on
|
||||||
/v1/auth/me) carries a muted mono "you" tag after the name
|
--ui-bg-elevated, 48 px rows with a top border, and an arrow-down icon on the Created header
|
||||||
|
And UserCardList (below md) has a 68 px minimum row height: the email line (with the "you"
|
||||||
|
tag), the display name below it only when there is one, then the RoleBadge, the
|
||||||
|
InviteStatusBadge and "Created {date}" on one line
|
||||||
|
And the username is not shown anywhere in the list
|
||||||
|
And the Email cell shows the account's or invite's email address, medium weight, highlighted;
|
||||||
|
the row whose kind is "user" and whose id equals the session user's id (from GET
|
||||||
|
/v1/auth/me) carries a muted mono "you" tag after it
|
||||||
|
And the Display name cell shows the item's display_name, highlighted, or a muted dash "—" when
|
||||||
|
it is empty or absent; an invite item shows the dash unless it carries a display_name; the
|
||||||
|
current user's row shows their saved name
|
||||||
|
And RoleBadge is a 20 px badge, IBM Plex Mono 11 px medium, 7 px side padding, no icon, showing
|
||||||
|
the word: owner (filled --ui-primary, --ui-bg text, --ui-primary border) or admin
|
||||||
|
(transparent, --ui-text-toned text, --ui-border-accented border); a user row shows its
|
||||||
|
role, and an invite row shows "admin", the role it will create
|
||||||
And InviteStatusBadge shows icon and word, never color alone: Accepted (circle-check, success
|
And InviteStatusBadge shows icon and word, never color alone: Accepted (circle-check, success
|
||||||
soft), Pending (mail, warning soft), Expired (clock-alert, transparent, muted, with an
|
soft), Pending (mail, warning soft), Expired (clock-alert, transparent, muted, with an
|
||||||
accented border)
|
accented border)
|
||||||
And the Created column shows the date as "27 Sep 2026", or "Today" when it is the current day;
|
And the Created column shows the date as "27 Sep 2026", or "Today" when it is the current day;
|
||||||
the fixture below uses absolute dates only
|
the fixture below uses absolute dates only
|
||||||
And skeleton rows (5) show only after 150 ms of loading, so a fast response never flashes them
|
And skeleton rows (5) show only after 150 ms of loading, so a fast response never flashes them,
|
||||||
|
one bar per column plus a RoleBadge placeholder and an InviteStatusBadge placeholder in the
|
||||||
|
table (md and up); the below-md card skeleton keeps the board's two-bar shape
|
||||||
And the Default fixture holds 5 items, newest first: invite id 2 "sam.oliveira@renew.example"
|
And the Default fixture holds 5 items, newest first: invite id 2 "sam.oliveira@renew.example"
|
||||||
pending 27 Sep 2026; invite id 1 "p.huber@gmail.com" expired 3 Aug 2026; user id 3 "ines"
|
pending 27 Sep 2026; invite id 1 "p.huber@gmail.com" with display_name "Paul Huber" expired
|
||||||
with display_name "Inès Duarte" accepted 18 Jun 2026; user id 2 "jonas" accepted 2 Apr 2026;
|
3 Aug 2026; user id 3 "ines" email "ines.duarte@renew.example" display_name "Inès Duarte"
|
||||||
user id 1 "marta" accepted 12 Mar 2026; the session user is id 1 "marta"
|
role admin accepted 18 Jun 2026; user id 2 "jonas" email "jonas@renew.example" no display
|
||||||
|
name, role admin, accepted 2 Apr 2026; user id 1 "marta" email "marta@renew.example" no
|
||||||
|
display name, role owner, accepted 12 Mar 2026; the session user is id 1 "marta", role
|
||||||
|
"owner"
|
||||||
And InviteUserModal is a UModal opened from either "Invite user" button; every time it opens it
|
And InviteUserModal is a UModal opened from either "Invite user" button; every time it opens it
|
||||||
starts in its default state: title "Invite a user", text "We'll email them a link to choose
|
starts in its default state: title "Invite a user", text "We'll email them a link to choose
|
||||||
a username and password. The link expires after 3 days.", an empty, focused Email field
|
a username and password. The link expires after 3 days.", an empty, focused Email field
|
||||||
@@ -86,48 +106,87 @@ Feature: Users screen and InviteUserModal
|
|||||||
form is not disabled by an in-flight request; focus returns to the button that opened it
|
form is not disabled by an in-flight request; focus returns to the button that opened it
|
||||||
And a 401 and a 403 (unverified) on either endpoint are handled entirely by useApi's global
|
And a 401 and a 403 (unverified) on either endpoint are handled entirely by useApi's global
|
||||||
handling (features/api_client_global_error_handling.feature)
|
handling (features/api_client_global_error_handling.feature)
|
||||||
And this slice does not build the accept-invite screen (/invite/accept), does not add row
|
And this slice does not build the accept-invite screen (/invite/accept); the "Display names in the Users list" state of the
|
||||||
actions (remove, promote, revoke or resend), and does not change how display names look in
|
Profile group is drawn by this same list
|
||||||
the Profile group's "Display names in the Users list" state
|
|
||||||
|
|
||||||
Scenario: Default — the list loads newest first, with display name, "you" tag and status badges
|
Scenario: Default — the list loads newest first with email, display name, role, status and created
|
||||||
Given GET /v1/user/ resolves 200 with the 5-item Default fixture and the session user is "marta"
|
Given GET /v1/user/ resolves 200 with the 5-item Default fixture and the session user is
|
||||||
|
"marta" with role "owner"
|
||||||
When the user navigates to /users
|
When the user navigates to /users
|
||||||
Then the breadcrumb reads "Users" (mobile title "Users")
|
Then the breadcrumb reads "Users" (mobile title "Users")
|
||||||
And the header shows the title "Users", the subtitle and, on desktop, "Invite user"
|
And the header shows the title "Users", the subtitle and, on desktop, "Invite user"
|
||||||
And the rows appear in exactly the fixture's order
|
And the table header reads Email, Display name, Role, Invite status, Created, and an empty
|
||||||
And the first row shows "sam.oliveira@renew.example" (toned), a Pending badge and "27 Sep 2026"
|
unlabeled sixth cell
|
||||||
And the second row shows "p.huber@gmail.com", an Expired badge and "3 Aug 2026"
|
And the rows appear in exactly the fixture's order, each 48 px high
|
||||||
And the third row shows "Inès Duarte" first with "ines" beside it in muted text, an Accepted
|
And the first row shows "sam.oliveira@renew.example", "—" (muted), "admin", a Pending badge
|
||||||
|
and "27 Sep 2026"
|
||||||
|
And the second row shows "p.huber@gmail.com", "Paul Huber", "admin", an Expired badge and
|
||||||
|
"3 Aug 2026"
|
||||||
|
And the third row shows "ines.duarte@renew.example", "Inès Duarte", "admin", an Accepted
|
||||||
badge and "18 Jun 2026"
|
badge and "18 Jun 2026"
|
||||||
And the fifth row shows "marta" with the "you" tag, an Accepted badge and "12 Mar 2026"
|
And the fourth row shows "jonas@renew.example", "—", "admin", an Accepted badge and "2 Apr 2026"
|
||||||
And no row shows an email address for an accepted user
|
And the fifth row shows "marta@renew.example" with the "you" tag, "—", "owner" (filled), an
|
||||||
And below md the same rows render as cards, each with the name line, then the badge and
|
Accepted badge and "12 Mar 2026"
|
||||||
"Created {date}"
|
And the username "ines", "jonas" or "marta" appears in no row
|
||||||
|
And below md the same rows render as cards: the email line, the display name below it only
|
||||||
|
for "p.huber@gmail.com" and "ines.duarte@renew.example", then the RoleBadge, the status
|
||||||
|
badge and "Created {date}" on one line
|
||||||
|
|
||||||
Scenario: Navigation — "Users" sits between Articles and Integration
|
Scenario: Navigation — "Users" sits between Articles and Integration
|
||||||
Given the user is on /users
|
Given the user is on /users
|
||||||
When DashboardShell mounts
|
When DashboardShell mounts
|
||||||
Then the sidebar and the mobile drawer list Home, Articles, Users, Integration in that order
|
Then the sidebar and the mobile drawer list Home, Articles, Users, Integration, Settings in that order
|
||||||
And "Users" has the users icon, links to /users and has aria-current="page"
|
And "Users" has the users icon, links to /users and has aria-current="page"
|
||||||
|
|
||||||
Scenario: Loading — skeleton rows after 150 ms while the first request, or a retry, is in flight
|
Scenario: Loading — skeleton rows after 150 ms while the first request, or a retry, is in flight
|
||||||
Given GET /v1/user/ has not yet resolved
|
Given GET /v1/user/ has not yet resolved
|
||||||
When the user navigates to /users
|
When the user navigates to /users
|
||||||
Then nothing is drawn in place of the list for the first 150 ms
|
Then nothing is drawn in place of the list for the first 150 ms
|
||||||
And after 150 ms 5 skeleton rows replace the list, and the list container is aria-busy="true"
|
And after 150 ms 5 skeleton rows replace the list, on desktop each with one bar per column
|
||||||
|
plus a RoleBadge and an InviteStatusBadge placeholder and below md in the board's two-bar
|
||||||
|
card shape, and the list container is aria-busy="true"
|
||||||
When GET /v1/user/ then resolves 200 with the Default fixture
|
When GET /v1/user/ then resolves 200 with the Default fixture
|
||||||
Then the skeleton rows are replaced by the Default state's rows
|
Then the skeleton rows are replaced by the Default state's rows
|
||||||
|
|
||||||
Scenario: Only you — nobody has been invited yet
|
Scenario: Only you — nobody has been invited yet
|
||||||
Given GET /v1/user/ resolves 200 with only user id 1 "marta", accepted 12 Mar 2026, and the
|
Given GET /v1/user/ resolves 200 with only user id 1 "marta" (email "marta@renew.example",
|
||||||
session user is "marta"
|
role "owner"), accepted 12 Mar 2026, and the session user is "marta" with role "owner"
|
||||||
When the user navigates to /users
|
When the user navigates to /users
|
||||||
Then the list has one row: "marta" with the "you" tag, an Accepted badge and "12 Mar 2026"
|
Then the list has one row: "marta@renew.example" with the "you" tag, "—", "owner", an
|
||||||
|
Accepted badge and "12 Mar 2026"
|
||||||
And under the list the hint reads "Invite someone so they can sign in with their own account
|
And under the list the hint reads "Invite someone so they can sign in with their own account
|
||||||
instead of sharing yours."
|
instead of sharing yours."
|
||||||
And "Invite user" is still available
|
And "Invite user" is still available
|
||||||
|
|
||||||
|
Scenario: Display names in the Users list — saved names show, empty ones show a dash
|
||||||
|
Given GET /v1/auth/me resolves 200 for user id 1 with display_name "Marta Alves" and role "owner"
|
||||||
|
And GET /v1/user/ resolves 200 with the Default fixture where user id 1 has display_name
|
||||||
|
"Marta Alves"
|
||||||
|
When the user navigates to /users
|
||||||
|
Then the row "marta@renew.example" (you) shows "Marta Alves", "owner" and an Accepted badge
|
||||||
|
And the row "ines.duarte@renew.example" shows "Inès Duarte", "admin" and an Accepted badge
|
||||||
|
And the row "jonas@renew.example" shows a muted "—", "admin" and an Accepted badge
|
||||||
|
And the sidebar chip also shows "Marta Alves"
|
||||||
|
|
||||||
|
Scenario Outline: Non-owners cannot invite — "Invite user" and the hint are not rendered
|
||||||
|
Given the session user is "<username>" with role "<role>" and GET /v1/user/ resolves 200
|
||||||
|
with <fixture>
|
||||||
|
When the user navigates to /users at desktop and at a below-md width
|
||||||
|
Then <invite>
|
||||||
|
And the list still renders normally
|
||||||
|
And <hint>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| username | role | fixture | invite | hint |
|
||||||
|
| jonas | admin | the Default fixture | no "Invite user" button is rendered, header or pinned | the pinned button's space is not reserved |
|
||||||
|
| jonas | admin | only user id 1 "marta" and user id 2 "jonas" | no "Invite user" button is rendered, header or pinned | the "Invite someone…" hint is not shown |
|
||||||
|
| marta | owner | the Default fixture | "Invite user" is rendered in the header (desktop) and pinned (below md) | the list is unchanged |
|
||||||
|
|
||||||
|
Scenario: An unknown or missing role is treated as non-owner
|
||||||
|
Given GET /v1/auth/me resolves 200 without a role
|
||||||
|
When the user navigates to /users
|
||||||
|
Then no "Invite user" button is rendered
|
||||||
|
|
||||||
Scenario Outline: Error — a 500 or a network failure replaces the list with an alert and a retry
|
Scenario Outline: Error — a 500 or a network failure replaces the list with an alert and a retry
|
||||||
Given GET /v1/user/ <failure>
|
Given GET /v1/user/ <failure>
|
||||||
When the user navigates to /users
|
When the user navigates to /users
|
||||||
@@ -185,8 +244,8 @@ Feature: Users screen and InviteUserModal
|
|||||||
"lea.martin@renew.example", status "pending", created_at now, expires_at 3 days later
|
"lea.martin@renew.example", status "pending", created_at now, expires_at 3 days later
|
||||||
Then the modal closes and focus returns to "Invite user"
|
Then the modal closes and focus returns to "Invite user"
|
||||||
And GET /v1/user/ is not called again
|
And GET /v1/user/ is not called again
|
||||||
And the list has 6 rows, the first being "lea.martin@renew.example" with a Pending badge and
|
And the list has 6 rows, the first being "lea.martin@renew.example" with "—", "admin", a
|
||||||
"Today", drawn with the --ui-bg-elevated background
|
Pending badge and "Today", drawn with the --ui-bg-elevated background
|
||||||
And the other 5 rows are unchanged and follow it in their previous order
|
And the other 5 rows are unchanged and follow it in their previous order
|
||||||
And a toast appears: color success, icon i-lucide-circle-check, id "invite-sent-3", title
|
And a toast appears: color success, icon i-lucide-circle-check, id "invite-sent-3", title
|
||||||
"Invite sent", description "lea.martin@renew.example has 3 days to accept."
|
"Invite sent", description "lea.martin@renew.example has 3 days to accept."
|
||||||
@@ -200,7 +259,7 @@ Feature: Users screen and InviteUserModal
|
|||||||
Scenario: Invite sent into the Only-you state keeps a coherent list
|
Scenario: Invite sent into the Only-you state keeps a coherent list
|
||||||
Given the Only-you state has loaded
|
Given the Only-you state has loaded
|
||||||
When an invite for "lea.martin@renew.example" is sent and resolves 201
|
When an invite for "lea.martin@renew.example" is sent and resolves 201
|
||||||
Then the list shows the new Pending row above the "marta" row
|
Then the list shows the new Pending row above the "marta@renew.example" row
|
||||||
And the Only-you hint is no longer shown
|
And the Only-you hint is no longer shown
|
||||||
|
|
||||||
Scenario Outline: Invite: already a user (409) — the field error depends on the response text
|
Scenario Outline: Invite: already a user (409) — the field error depends on the response text
|
||||||
|
|||||||
+50
-18
@@ -3,9 +3,9 @@
|
|||||||
## Implementation note for coder (informational, not a QA assertion)
|
## Implementation note for coder (informational, not a QA assertion)
|
||||||
|
|
||||||
The invitations API is already built and covered by features/invitations.qa.md: this slice has no
|
The invitations API is already built and covered by features/invitations.qa.md: this slice has no
|
||||||
Go change, so it has no HTTP-level Go section.
|
Go change in this slice; the API shape was extended by user_roles.feature, so it has no HTTP-level Go section.
|
||||||
|
|
||||||
The shell specs were amended to four destinations (Home, Articles, Users, Integration):
|
The shell specs were amended to five destinations (Home, Articles, Users, Integration, Settings):
|
||||||
nuxt_ui_shell_foundation.feature / .qa.md (case 14) and dashboard_shell_branding.feature. Their
|
nuxt_ui_shell_foundation.feature / .qa.md (case 14) and dashboard_shell_branding.feature. Their
|
||||||
Vitest tests must be updated in the same change.
|
Vitest tests must be updated in the same change.
|
||||||
|
|
||||||
@@ -16,20 +16,27 @@ The list items are keyed by `kind` and `id`.
|
|||||||
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
Mock `useApi`'s `request` for `GET /v1/user/` and `POST /v1/user/invite` per case; no real backend.
|
Mock `useApi`'s `request` for `GET /v1/user/` and `POST /v1/user/invite` per case; no real backend.
|
||||||
Mount UsersPage inside DashboardShell with a resolved verified session (id 1, username "marta") and
|
Mount UsersPage inside DashboardShell with a resolved verified session (id 1, username "marta",
|
||||||
a test router at /users. The Default fixture is the Background's 5 items; the invite fixture is
|
role "owner") and a test router at /users; cases 6 to 17 use that owner session. The Default
|
||||||
|
fixture is the Background's 5 items; the invite fixture is
|
||||||
id 3, email "lea.martin@renew.example". No test freezes the system date. The specs only assert on
|
id 3, email "lea.martin@renew.example". No test freezes the system date. The specs only assert on
|
||||||
the fixture's absolute dates; the sent row's "Today" label is not asserted anywhere (see the Visual
|
the fixture's absolute dates; the sent row's "Today" label is not asserted anywhere (see the Visual
|
||||||
part). Run each layout case at a desktop and a below-md width (mock `matchMedia`).
|
part). Run each layout case at a desktop and a below-md width (mock `matchMedia`).
|
||||||
|
|
||||||
1. **Default** — assert breadcrumb "Users", title, subtitle, "Invite user", rows in fixture order,
|
1. **Default** — assert breadcrumb "Users", title, subtitle, "Invite user", the table header
|
||||||
"Inès Duarte" with "ines" beside it, the "you" tag only on the "marta" row, badge words and
|
labels (Email, Display name, Role, Invite status, Created), rows in fixture order, per row the
|
||||||
the fixture's absolute dates; assert no accepted row shows an email.
|
email, the display name or "—", the RoleBadge word and class (owner filled, admin outlined),
|
||||||
2. **Navigation** — assert the sidebar and the drawer list Home, Articles, Users, Integration in
|
the badge word and the absolute date, "Paul Huber" on the invite row, the "you" tag only on
|
||||||
that order, and "Users" carries aria-current="page" on /users.
|
"marta@renew.example", no username text in any row, and the below-md cards (display name line
|
||||||
|
only when set).
|
||||||
|
2. **Navigation** — assert the sidebar and the drawer list Home, Articles, Users, Integration,
|
||||||
|
Settings in that order, and "Users" carries aria-current="page" on /users.
|
||||||
3. **Loading** — unresolved `GET`; with fake timers assert nothing is drawn at 149 ms; at 150 ms
|
3. **Loading** — unresolved `GET`; with fake timers assert nothing is drawn at 149 ms; at 150 ms
|
||||||
assert 5 skeleton rows and `aria-busy="true"`; resolve and assert the Default rows.
|
assert 5 skeleton rows and `aria-busy="true"`, and at desktop that each row has a RoleBadge
|
||||||
4. **Only you** — a single "marta" item; assert the row, the hint text and "Invite user".
|
and a status badge placeholder (below md the cards keep the two-bar shape); resolve and
|
||||||
|
assert the Default rows.
|
||||||
|
4. **Only you** — a single "marta" item (email, role "owner"); assert the row, the hint text and
|
||||||
|
"Invite user".
|
||||||
5. **Error, Examples-driven** — reject with `ApiError(500)`, then `NetworkError`; assert the alert
|
5. **Error, Examples-driven** — reject with `ApiError(500)`, then `NetworkError`; assert the alert
|
||||||
copy, the "Try again" action, no close button and no rows; click "Try again"; assert `request`
|
copy, the "Try again" action, no close button and no rows; click "Try again"; assert `request`
|
||||||
is called again, then resolve the Default fixture and assert its rows.
|
is called again, then resolve the Default fixture and assert its rows.
|
||||||
@@ -45,8 +52,8 @@ part). Run each layout case at a desktop and a below-md width (mock `matchMedia`
|
|||||||
was not called a second time, the list has 6 rows with the new Pending row first and the
|
was not called a second time, the list has 6 rows with the new Pending row first and the
|
||||||
others unchanged, the first row has the `--ui-bg-elevated` background class, and the toast
|
others unchanged, the first row has the `--ui-bg-elevated` background class, and the toast
|
||||||
was raised with id "invite-sent-3", color success, icon "i-lucide-circle-check", title
|
was raised with id "invite-sent-3", color success, icon "i-lucide-circle-check", title
|
||||||
"Invite sent" and description "lea.martin@renew.example has 3 days to accept." Assert nothing
|
"Invite sent" and description "lea.martin@renew.example has 3 days to accept." Assert the new
|
||||||
about the "Today" label.
|
first row shows "—" and "admin", and nothing about the "Today" label.
|
||||||
10. **Replacement of an expired invite** — invite "p.huber@gmail.com", resolve 201; assert exactly
|
10. **Replacement of an expired invite** — invite "p.huber@gmail.com", resolve 201; assert exactly
|
||||||
one row for that address, first and Pending.
|
one row for that address, first and Pending.
|
||||||
11. **Invite sent into Only you** — assert the new row above "marta" and the hint gone.
|
11. **Invite sent into Only you** — assert the new row above "marta" and the hint gone.
|
||||||
@@ -65,6 +72,14 @@ part). Run each layout case at a desktop and a below-md width (mock `matchMedia`
|
|||||||
the same body; resolve 201 and assert the closed modal, the row and the toast.
|
the same body; resolve 201 and assert the closed modal, the row and the toast.
|
||||||
17. **Cancel discards** — type, click "Cancel"; assert immediate close, no `request`, an empty
|
17. **Cancel discards** — type, click "Cancel"; assert immediate close, no `request`, an empty
|
||||||
field on reopening, and focus back on the opening button.
|
field on reopening, and focus back on the opening button.
|
||||||
|
18. **Display names in the Users list** — the Default fixture with user 1 named "Marta Alves"
|
||||||
|
(session `/v1/auth/me` too); assert the "marta@renew.example" row shows "Marta Alves", "owner"
|
||||||
|
and Accepted, the "ines.duarte@renew.example" row "Inès Duarte" and "admin", the
|
||||||
|
"jonas@renew.example" row "—" and "admin", and the sidebar chip "Marta Alves".
|
||||||
|
19. **Non-owners, Examples-driven** — session role "admin", at desktop and below md; assert no
|
||||||
|
"Invite user" button (header or pinned), the list still renders, no reserved space for the
|
||||||
|
pinned button, and the hint absent for a list of only "marta" and "jonas". Also a session with
|
||||||
|
no role (no button) and an owner control (button present in both layouts).
|
||||||
|
|
||||||
## Visual (task visual:check -- users, desktop and mobile, light and dark)
|
## Visual (task visual:check -- users, desktop and mobile, light and dark)
|
||||||
|
|
||||||
@@ -73,11 +88,23 @@ Screens Back-office.dc.html`, exact values in `docs/design/source/AppFrame.dc.ht
|
|||||||
state's mock to `web/visual/states.ts` with the board's own sample data. The gate is hard: every
|
state's mock to `web/visual/states.ts` with the board's own sample data. The gate is hard: every
|
||||||
capture of every non-skipped state must be within 10 %, for both viewports and both themes.
|
capture of every non-skipped state must be within 10 %, for both viewports and both themes.
|
||||||
|
|
||||||
- [ ] Default: the 5 board rows (`sam.oliveira@renew.example`, `p.huber@gmail.com`, `ines` with
|
- [ ] Fixtures: `usersFixture` in `web/visual/states.ts` follows the board data: invite 2
|
||||||
"Inès Duarte", `jonas`, `marta` with "you"), dates 27 Sep 2026, 3 Aug 2026, 18 Jun 2026,
|
`sam.oliveira@renew.example` pending, no name; invite 1 `p.huber@gmail.com` with
|
||||||
2 Apr 2026, 12 Mar 2026; session user `marta`.
|
`display_name: 'Paul Huber'` expired; user 3 `ines.duarte@renew.example` "Inès Duarte" admin;
|
||||||
- [ ] Loading: 5 skeleton rows; the setup must give skeletons time to show (150 ms) before the capture.
|
user 2 `jonas@renew.example` admin, empty name; user 1 `marta@renew.example` owner, empty
|
||||||
- [ ] Only you: the single `marta` row plus the hint.
|
name. `verifiedSession` carries `role: 'owner'`. `profileSession` and `usersWithDisplayNames`
|
||||||
|
are updated so "Display names in the Users list" shows "Marta Alves", owner.
|
||||||
|
- [ ] Default: the 5 board rows by email with display names, roles and status badges, dates
|
||||||
|
27 Sep 2026, 3 Aug 2026, 18 Jun 2026, 2 Apr 2026, 12 Mar 2026; session user `marta`. The
|
||||||
|
Cancel/Renew buttons in the sixth column are specified in features/users_row_actions.feature.
|
||||||
|
- [ ] Loading: 5 skeleton rows, with role and status placeholders on desktop and the board's
|
||||||
|
two-bar cards on mobile; the setup must give skeletons time to show (150 ms) before the
|
||||||
|
capture.
|
||||||
|
- [ ] Only you: the single `marta@renew.example` row (owner) plus the hint.
|
||||||
|
- [ ] Profile "Display names in the Users list" (`task visual:check -- profile "Display names in
|
||||||
|
the Users list"`): Marta Alves / Inès Duarte / dash.
|
||||||
|
- [ ] Not drawn, no visual state: non-owner rendering (no "Invite user", no hint). Covered by
|
||||||
|
Vitest only (case 19); do not add it to `web/visual/states.ts`.
|
||||||
- [ ] Error: the alert and "Try again", no table or cards; the header button is still drawn.
|
- [ ] Error: the alert and "Try again", no table or cards; the header button is still drawn.
|
||||||
- [ ] Invite: default: modal over the Default list, empty focused Email; the mobile pinned button hidden.
|
- [ ] Invite: default: modal over the Default list, empty focused Email; the mobile pinned button hidden.
|
||||||
- [ ] Invite: validation: value `sam.oliveira@renew`, error copy.
|
- [ ] Invite: validation: value `sam.oliveira@renew`, error copy.
|
||||||
@@ -91,6 +118,9 @@ capture of every non-skipped state must be within 10 %, for both viewports and b
|
|||||||
- [ ] Layout, taken from the board frame (`AppFrame.dc.html`), not `components.md`: desktop header
|
- [ ] Layout, taken from the board frame (`AppFrame.dc.html`), not `components.md`: desktop header
|
||||||
row is title block left and the 32 px "Invite user" button right, aligned to the bottom of
|
row is title block left and the 32 px "Invite user" button right, aligned to the bottom of
|
||||||
the row; on mobile the button is 16 px from left, right and bottom, 48 px high, 18 px icon.
|
the row; on mobile the button is 16 px from left, right and bottom, 48 px high, 18 px icon.
|
||||||
|
- [ ] Layout, from `AppFrame.dc.html`: 36 px table header, 48 px rows, sixth 150 px track empty;
|
||||||
|
RoleBadge 20 px high, 7 px side padding, IBM Plex Mono 11 px medium; cards show the email
|
||||||
|
line, then the display name, then the badges line.
|
||||||
- [ ] Not covered by screenshots: keyboard and focus order (Tab reaches "Invite user", the modal
|
- [ ] Not covered by screenshots: keyboard and focus order (Tab reaches "Invite user", the modal
|
||||||
focus starts on Email, then Cancel, then "Send invite", focus is trapped, Esc closes it in
|
focus starts on Email, then Cancel, then "Send invite", focus is trapped, Esc closes it in
|
||||||
every dismissible state and is blocked while Sending, focus returns to the opening button);
|
every dismissible state and is blocked while Sending, focus returns to the opening button);
|
||||||
@@ -106,6 +136,8 @@ capture of every non-skipped state must be within 10 %, for both viewports and b
|
|||||||
- **Real invitation email** — needs real or sandboxed SMTP (`SMTP_HOST` and the related env
|
- **Real invitation email** — needs real or sandboxed SMTP (`SMTP_HOST` and the related env
|
||||||
vars): the mail arrives and its link `{PUBLIC_URL}/invite/accept?c=...` carries the code. The
|
vars): the mail arrives and its link `{PUBLIC_URL}/invite/accept?c=...` carries the code. The
|
||||||
link will not resolve in the SPA, because the accept screen is out of scope.
|
link will not resolve in the SPA, because the accept screen is out of scope.
|
||||||
|
- **Admin session** — sign in once as an admin against `task dev` and confirm there is no
|
||||||
|
"Invite user" button and no "Only you" hint.
|
||||||
- **Toast placement and stacking on a live app** — bottom right on desktop and above the pinned
|
- **Toast placement and stacking on a live app** — bottom right on desktop and above the pinned
|
||||||
button on mobile.
|
button on mobile.
|
||||||
- **"Today" and the elevated row on a live app** — confirm the new row and the "Today" label
|
- **"Today" and the elevated row on a live app** — confirm the new row and the "Today" label
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ var ErrInviteNotFound = errors.New("invite not found")
|
|||||||
var ErrInviteEmailNotSent = errors.New("invite email not sent")
|
var ErrInviteEmailNotSent = errors.New("invite email not sent")
|
||||||
var ErrInviteInvalid = errors.New("invite invalid")
|
var ErrInviteInvalid = errors.New("invite invalid")
|
||||||
var ErrInviteExpired = errors.New("invite expired")
|
var ErrInviteExpired = errors.New("invite expired")
|
||||||
|
var ErrInviteAlreadyAccepted = errors.New("invite already accepted")
|
||||||
|
|
||||||
const Lifetime = 3 * 24 * time.Hour
|
const Lifetime = 3 * 24 * time.Hour
|
||||||
|
|
||||||
|
|||||||
@@ -9,5 +9,6 @@ type Repository interface {
|
|||||||
Create(invite Invite) (Invite, error)
|
Create(invite Invite) (Invite, error)
|
||||||
GetAll() []Invite
|
GetAll() []Invite
|
||||||
Delete(id uint32) error
|
Delete(id uint32) error
|
||||||
|
Renew(id uint32, hashedCode string, expiresAt time.Time, createdAt time.Time) (Invite, error)
|
||||||
AcceptWithUser(inviteID uint32, acceptedAt time.Time, newUser user.User) (user.User, error)
|
AcceptWithUser(inviteID uint32, acceptedAt time.Time, newUser user.User) (user.User, error)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package settings
|
||||||
|
|
||||||
|
type Settings struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
}
|
||||||
@@ -16,6 +16,13 @@ var ErrPasswordResetCodeExpired = errors.New("password reset code expired")
|
|||||||
var ErrInvalidDisplayName = errors.New("invalid display name")
|
var ErrInvalidDisplayName = errors.New("invalid display name")
|
||||||
var ErrUsernameTaken = errors.New("username taken")
|
var ErrUsernameTaken = errors.New("username taken")
|
||||||
|
|
||||||
|
type Role string
|
||||||
|
|
||||||
|
const (
|
||||||
|
RoleOwner Role = "owner"
|
||||||
|
RoleAdmin Role = "admin"
|
||||||
|
)
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
ID uint32 `json:"id"`
|
ID uint32 `json:"id"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
@@ -24,6 +31,7 @@ type User struct {
|
|||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
DisplayName string `json:"display_name"`
|
DisplayName string `json:"display_name"`
|
||||||
IsVerified bool `json:"is_verified"`
|
IsVerified bool `json:"is_verified"`
|
||||||
|
Role Role `json:"role"`
|
||||||
VerificationCode string `json:"verification_code"`
|
VerificationCode string `json:"verification_code"`
|
||||||
VerificationExpiration time.Time `json:"verification_expiration"`
|
VerificationExpiration time.Time `json:"verification_expiration"`
|
||||||
PasswordResetExpiration time.Time `json:"password_reset_expiration"`
|
PasswordResetExpiration time.Time `json:"password_reset_expiration"`
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ type Settings struct {
|
|||||||
Smtp SmtpSettings
|
Smtp SmtpSettings
|
||||||
AuthRateLimit AuthRateLimitSettings
|
AuthRateLimit AuthRateLimitSettings
|
||||||
TrustedProxies []string
|
TrustedProxies []string
|
||||||
|
Version string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Settings) IsProduction() bool {
|
func (s Settings) IsProduction() bool {
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ func UserToDomain(m models.User) user.User {
|
|||||||
Email: m.Email,
|
Email: m.Email,
|
||||||
DisplayName: m.DisplayName,
|
DisplayName: m.DisplayName,
|
||||||
IsVerified: m.IsVerified,
|
IsVerified: m.IsVerified,
|
||||||
|
Role: user.Role(m.Role),
|
||||||
VerificationCode: nullableStringToDomain(m.VerificationCode),
|
VerificationCode: nullableStringToDomain(m.VerificationCode),
|
||||||
VerificationExpiration: m.VerificationExpiration,
|
VerificationExpiration: m.VerificationExpiration,
|
||||||
PasswordResetExpiration: m.PasswordResetExpiration,
|
PasswordResetExpiration: m.PasswordResetExpiration,
|
||||||
@@ -45,6 +46,7 @@ func UserToModel(a user.User) models.User {
|
|||||||
Email: a.Email,
|
Email: a.Email,
|
||||||
DisplayName: a.DisplayName,
|
DisplayName: a.DisplayName,
|
||||||
IsVerified: a.IsVerified,
|
IsVerified: a.IsVerified,
|
||||||
|
Role: string(a.Role),
|
||||||
VerificationCode: DomainToNullableString(a.VerificationCode),
|
VerificationCode: DomainToNullableString(a.VerificationCode),
|
||||||
VerificationExpiration: a.VerificationExpiration,
|
VerificationExpiration: a.VerificationExpiration,
|
||||||
PasswordResetExpiration: a.PasswordResetExpiration,
|
PasswordResetExpiration: a.PasswordResetExpiration,
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ type User struct {
|
|||||||
Email string `gorm:"unique;not null"`
|
Email string `gorm:"unique;not null"`
|
||||||
DisplayName string `gorm:"not null;default:''"`
|
DisplayName string `gorm:"not null;default:''"`
|
||||||
IsVerified bool `gorm:"default=false;not null"`
|
IsVerified bool `gorm:"default=false;not null"`
|
||||||
|
Role string `gorm:"not null;default:''"`
|
||||||
VerificationCode *string `gorm:"unique"`
|
VerificationCode *string `gorm:"unique"`
|
||||||
VerificationExpiration time.Time
|
VerificationExpiration time.Time
|
||||||
PasswordResetExpiration time.Time
|
PasswordResetExpiration time.Time
|
||||||
|
|||||||
@@ -45,6 +45,25 @@ func (i *InviteRepository) Delete(id uint32) error {
|
|||||||
return deleteOrNotFound(result, domainInvite.ErrInviteNotFound)
|
return deleteOrNotFound(result, domainInvite.ErrInviteNotFound)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (i *InviteRepository) Renew(id uint32, hashedCode string, expiresAt time.Time, createdAt time.Time) (domainInvite.Invite, error) {
|
||||||
|
result := i.db.Model(&entity.Invite{}).
|
||||||
|
Where("id = ? AND accepted_at IS NULL", id).
|
||||||
|
Updates(map[string]any{
|
||||||
|
"hashed_code": hashedCode,
|
||||||
|
"expires_at": expiresAt,
|
||||||
|
"created_at": createdAt,
|
||||||
|
})
|
||||||
|
if err := deleteOrNotFound(result, domainInvite.ErrInviteNotFound); err != nil {
|
||||||
|
return domainInvite.Invite{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var model entity.Invite
|
||||||
|
if err := i.db.First(&model, id).Error; err != nil {
|
||||||
|
return domainInvite.Invite{}, err
|
||||||
|
}
|
||||||
|
return mappers.InviteToDomain(model), nil
|
||||||
|
}
|
||||||
|
|
||||||
func (i *InviteRepository) AcceptWithUser(inviteID uint32, acceptedAt time.Time, newUser domainUser.User) (domainUser.User, error) {
|
func (i *InviteRepository) AcceptWithUser(inviteID uint32, acceptedAt time.Time, newUser domainUser.User) (domainUser.User, error) {
|
||||||
createdModel := mappers.UserToModel(newUser)
|
createdModel := mappers.UserToModel(newUser)
|
||||||
err := i.db.Transaction(func(tx *gorm.DB) error {
|
err := i.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ func (u *UserRepository) Create(user domainUser.User) (domainUser.User, error) {
|
|||||||
PasswordResetCode: mappers.DomainToNullableString(user.PasswordResetCode),
|
PasswordResetCode: mappers.DomainToNullableString(user.PasswordResetCode),
|
||||||
Email: user.Email,
|
Email: user.Email,
|
||||||
IsVerified: user.IsVerified,
|
IsVerified: user.IsVerified,
|
||||||
|
Role: string(user.Role),
|
||||||
VerificationCode: mappers.DomainToNullableString(user.VerificationCode),
|
VerificationCode: mappers.DomainToNullableString(user.VerificationCode),
|
||||||
VerificationExpiration: user.VerificationExpiration,
|
VerificationExpiration: user.VerificationExpiration,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package persistence
|
||||||
|
|
||||||
|
import (
|
||||||
|
domainUser "RenewCMS/internal/domain/user"
|
||||||
|
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func BackfillUserRoles(db *gorm.DB) error {
|
||||||
|
return db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
var firstUser entity.User
|
||||||
|
result := tx.Where("role = ''").Order("id asc").Limit(1).Find(&firstUser)
|
||||||
|
if result.Error != nil {
|
||||||
|
return result.Error
|
||||||
|
}
|
||||||
|
if result.RowsAffected == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var lowest entity.User
|
||||||
|
if err := tx.Order("id asc").First(&lowest).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if lowest.Role == "" {
|
||||||
|
if err := tx.Model(&entity.User{}).Where("id = ?", lowest.ID).Update("role", string(domainUser.RoleOwner)).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.Model(&entity.User{}).Where("role = ''").Update("role", string(domainUser.RoleAdmin)).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -54,6 +54,7 @@ func (a *AcceptInviteUseCase) AcceptInvite(command AcceptInviteCommand) (user.Us
|
|||||||
Password: hashedPassword,
|
Password: hashedPassword,
|
||||||
Email: pending.Email,
|
Email: pending.Email,
|
||||||
IsVerified: true,
|
IsVerified: true,
|
||||||
|
Role: user.RoleAdmin,
|
||||||
})
|
})
|
||||||
if errors.Is(err, invite.ErrInviteNotFound) {
|
if errors.Is(err, invite.ErrInviteNotFound) {
|
||||||
return user.User{}, invite.ErrInviteInvalid
|
return user.User{}, invite.ErrInviteInvalid
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package useCases
|
||||||
|
|
||||||
|
import "RenewCMS/internal/domain/invite"
|
||||||
|
|
||||||
|
type CancelInviteUseCase struct {
|
||||||
|
inviteRepository invite.Repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCancelInviteUseCase(inviteRepository invite.Repository) *CancelInviteUseCase {
|
||||||
|
return &CancelInviteUseCase{inviteRepository}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *CancelInviteUseCase) CancelInvite(id uint32) error {
|
||||||
|
if _, err := findManageableInvite(c.inviteRepository, id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return c.inviteRepository.Delete(id)
|
||||||
|
}
|
||||||
@@ -6,21 +6,15 @@ import (
|
|||||||
"RenewCMS/internal/domain/mail"
|
"RenewCMS/internal/domain/mail"
|
||||||
"RenewCMS/internal/domain/user"
|
"RenewCMS/internal/domain/user"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const inviteTemplateName = "invitation"
|
|
||||||
|
|
||||||
type CreateInviteUseCase struct {
|
type CreateInviteUseCase struct {
|
||||||
userRepository user.Repository
|
userRepository user.Repository
|
||||||
inviteRepository invite.Repository
|
inviteRepository invite.Repository
|
||||||
hasher hash.Hasher
|
hasher hash.Hasher
|
||||||
mailRepository mail.Repository
|
mailer inviteMailer
|
||||||
publicURL string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreateInviteCommand struct {
|
type CreateInviteCommand struct {
|
||||||
@@ -28,20 +22,8 @@ type CreateInviteCommand struct {
|
|||||||
InvitedBy uint32
|
InvitedBy uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
type MailInviteData struct {
|
|
||||||
Host string
|
|
||||||
VerificationCode string
|
|
||||||
Email string
|
|
||||||
InvitedBy string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d MailInviteData) Subject() string {
|
|
||||||
inviter := strings.NewReplacer("\r", " ", "\n", " ").Replace(d.InvitedBy)
|
|
||||||
return inviter + " invited you to RenewCMS"
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCreateInviteUseCase(userRepository user.Repository, inviteRepository invite.Repository, hasher hash.Hasher, mailRepository mail.Repository, publicURL string) *CreateInviteUseCase {
|
func NewCreateInviteUseCase(userRepository user.Repository, inviteRepository invite.Repository, hasher hash.Hasher, mailRepository mail.Repository, publicURL string) *CreateInviteUseCase {
|
||||||
return &CreateInviteUseCase{userRepository, inviteRepository, hasher, mailRepository, publicURL}
|
return &CreateInviteUseCase{userRepository, inviteRepository, hasher, inviteMailer{mailRepository, publicURL}}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (g *CreateInviteUseCase) CreateInvite(command CreateInviteCommand) (invite.Invite, error) {
|
func (g *CreateInviteUseCase) CreateInvite(command CreateInviteCommand) (invite.Invite, error) {
|
||||||
@@ -61,8 +43,7 @@ func (g *CreateInviteUseCase) CreateInvite(command CreateInviteCommand) (invite.
|
|||||||
return invite.Invite{}, err
|
return invite.Invite{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
rawCode := uuid.NewString()
|
rawCode, hashedCode, err := newInviteCode(g.hasher)
|
||||||
hashedCode, err := g.hasher.Hash(rawCode)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return invite.Invite{}, err
|
return invite.Invite{}, err
|
||||||
}
|
}
|
||||||
@@ -78,13 +59,7 @@ func (g *CreateInviteUseCase) CreateInvite(command CreateInviteCommand) (invite.
|
|||||||
return invite.Invite{}, err
|
return invite.Invite{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := g.mailRepository.Send(email, inviteTemplateName, MailInviteData{
|
if sendErr := g.mailer.send(email, rawCode, inviter); sendErr != nil {
|
||||||
Host: g.publicURL,
|
|
||||||
VerificationCode: rawCode,
|
|
||||||
Email: email,
|
|
||||||
InvitedBy: inviterName(inviter),
|
|
||||||
}); err != nil {
|
|
||||||
sendErr := fmt.Errorf("%w: %w", invite.ErrInviteEmailNotSent, err)
|
|
||||||
if deleteErr := g.inviteRepository.Delete(createdInvite.ID); deleteErr != nil {
|
if deleteErr := g.inviteRepository.Delete(createdInvite.ID); deleteErr != nil {
|
||||||
return invite.Invite{}, errors.Join(sendErr, deleteErr)
|
return invite.Invite{}, errors.Join(sendErr, deleteErr)
|
||||||
}
|
}
|
||||||
@@ -119,10 +94,3 @@ func (g *CreateInviteUseCase) discardOpenInvite(email string, now time.Time) err
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func inviterName(inviter user.User) string {
|
|
||||||
if inviter.DisplayName != "" {
|
|
||||||
return inviter.DisplayName
|
|
||||||
}
|
|
||||||
return inviter.Username
|
|
||||||
}
|
|
||||||
@@ -56,6 +56,7 @@ func (g *CreateUserUseCase) CreateUser(createUser CreateUserCommand) (user.User,
|
|||||||
PasswordResetCode: "",
|
PasswordResetCode: "",
|
||||||
Email: createUser.Email,
|
Email: createUser.Email,
|
||||||
IsVerified: false,
|
IsVerified: false,
|
||||||
|
Role: user.RoleOwner,
|
||||||
VerificationCode: hashedVerificationCode,
|
VerificationCode: hashedVerificationCode,
|
||||||
VerificationExpiration: time.Now().Add(2 * time.Hour),
|
VerificationExpiration: time.Now().Add(2 * time.Hour),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package useCases
|
||||||
|
|
||||||
|
import "RenewCMS/internal/domain/settings"
|
||||||
|
|
||||||
|
type GetSettingsUseCase struct {
|
||||||
|
version string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewGetSettingsUseCase(version string) *GetSettingsUseCase {
|
||||||
|
return &GetSettingsUseCase{version}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *GetSettingsUseCase) GetSettings() settings.Settings {
|
||||||
|
return settings.Settings{Version: g.version}
|
||||||
|
}
|
||||||
@@ -23,6 +23,7 @@ type DirectoryEntry struct {
|
|||||||
Username string
|
Username string
|
||||||
DisplayName string
|
DisplayName string
|
||||||
Email string
|
Email string
|
||||||
|
Role string
|
||||||
Status string
|
Status string
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
}
|
}
|
||||||
@@ -41,6 +42,8 @@ func (g *ListUsersAndInvitesUseCase) ListUsersAndInvites() []DirectoryEntry {
|
|||||||
Kind: EntryKindUser,
|
Kind: EntryKindUser,
|
||||||
Username: existingUser.Username,
|
Username: existingUser.Username,
|
||||||
DisplayName: existingUser.DisplayName,
|
DisplayName: existingUser.DisplayName,
|
||||||
|
Email: existingUser.Email,
|
||||||
|
Role: string(existingUser.Role),
|
||||||
Status: string(invite.StatusAccepted),
|
Status: string(invite.StatusAccepted),
|
||||||
CreatedAt: existingUser.CreatedAt,
|
CreatedAt: existingUser.CreatedAt,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package useCases
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/internal/domain/hash"
|
||||||
|
"RenewCMS/internal/domain/invite"
|
||||||
|
"RenewCMS/internal/domain/mail"
|
||||||
|
"RenewCMS/internal/domain/user"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RenewInviteUseCase struct {
|
||||||
|
userRepository user.Repository
|
||||||
|
inviteRepository invite.Repository
|
||||||
|
hasher hash.Hasher
|
||||||
|
mailer inviteMailer
|
||||||
|
}
|
||||||
|
|
||||||
|
type RenewInviteCommand struct {
|
||||||
|
ID uint32
|
||||||
|
RenewedBy uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRenewInviteUseCase(userRepository user.Repository, inviteRepository invite.Repository, hasher hash.Hasher, mailRepository mail.Repository, publicURL string) *RenewInviteUseCase {
|
||||||
|
return &RenewInviteUseCase{userRepository, inviteRepository, hasher, inviteMailer{mailRepository, publicURL}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *RenewInviteUseCase) RenewInvite(command RenewInviteCommand) (invite.Invite, error) {
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
renewer, err := u.userRepository.Get(command.RenewedBy)
|
||||||
|
if err != nil {
|
||||||
|
return invite.Invite{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
previous, err := findManageableInvite(u.inviteRepository, command.ID)
|
||||||
|
if err != nil {
|
||||||
|
return invite.Invite{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
rawCode, hashedCode, err := newInviteCode(u.hasher)
|
||||||
|
if err != nil {
|
||||||
|
return invite.Invite{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
renewed, err := u.inviteRepository.Renew(previous.ID, hashedCode, now.Add(invite.Lifetime), now)
|
||||||
|
if err != nil {
|
||||||
|
return invite.Invite{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if sendErr := u.mailer.send(renewed.Email, rawCode, renewer); sendErr != nil {
|
||||||
|
if _, restoreErr := u.inviteRepository.Renew(previous.ID, previous.HashedCode, previous.ExpiresAt, previous.CreatedAt); restoreErr != nil {
|
||||||
|
return invite.Invite{}, errors.Join(sendErr, restoreErr)
|
||||||
|
}
|
||||||
|
return invite.Invite{}, sendErr
|
||||||
|
}
|
||||||
|
|
||||||
|
return renewed, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package useCases
|
||||||
|
|
||||||
|
import "RenewCMS/internal/domain/invite"
|
||||||
|
|
||||||
|
func findManageableInvite(inviteRepository invite.Repository, id uint32) (invite.Invite, error) {
|
||||||
|
for _, existing := range inviteRepository.GetAll() {
|
||||||
|
if existing.ID != id {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if existing.AcceptedAt != nil {
|
||||||
|
return invite.Invite{}, invite.ErrInviteAlreadyAccepted
|
||||||
|
}
|
||||||
|
return existing, nil
|
||||||
|
}
|
||||||
|
return invite.Invite{}, invite.ErrInviteNotFound
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package useCases
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/internal/domain/hash"
|
||||||
|
"RenewCMS/internal/domain/invite"
|
||||||
|
"RenewCMS/internal/domain/mail"
|
||||||
|
"RenewCMS/internal/domain/user"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
const inviteTemplateName = "invitation"
|
||||||
|
|
||||||
|
type MailInviteData struct {
|
||||||
|
Host string
|
||||||
|
VerificationCode string
|
||||||
|
Email string
|
||||||
|
InvitedBy string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d MailInviteData) Subject() string {
|
||||||
|
inviter := strings.NewReplacer("\r", " ", "\n", " ").Replace(d.InvitedBy)
|
||||||
|
return inviter + " invited you to RenewCMS"
|
||||||
|
}
|
||||||
|
|
||||||
|
type inviteMailer struct {
|
||||||
|
mailRepository mail.Repository
|
||||||
|
publicURL string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m inviteMailer) send(email string, rawCode string, inviter user.User) error {
|
||||||
|
if err := m.mailRepository.Send(email, inviteTemplateName, MailInviteData{
|
||||||
|
Host: m.publicURL,
|
||||||
|
VerificationCode: rawCode,
|
||||||
|
Email: email,
|
||||||
|
InvitedBy: inviterName(inviter),
|
||||||
|
}); err != nil {
|
||||||
|
return fmt.Errorf("%w: %w", invite.ErrInviteEmailNotSent, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newInviteCode(hasher hash.Hasher) (string, string, error) {
|
||||||
|
rawCode := uuid.NewString()
|
||||||
|
hashedCode, err := hasher.Hash(rawCode)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
return rawCode, hashedCode, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func inviterName(inviter user.User) string {
|
||||||
|
if inviter.DisplayName != "" {
|
||||||
|
return inviter.DisplayName
|
||||||
|
}
|
||||||
|
return inviter.Username
|
||||||
|
}
|
||||||
@@ -63,6 +63,8 @@ func newAcceptInviteFixture(t *testing.T, maxAttempts int) *acceptInviteFixture
|
|||||||
meHandler := auth.NewMeHandler(getUser)
|
meHandler := auth.NewMeHandler(getUser)
|
||||||
listHandler := userhandler.NewInviteHandler(
|
listHandler := userhandler.NewInviteHandler(
|
||||||
useCases.NewCreateInviteUseCase(f.users, f.invites, f.hasher, f.mail, invitePublicURL),
|
useCases.NewCreateInviteUseCase(f.users, f.invites, f.hasher, f.mail, invitePublicURL),
|
||||||
|
nil,
|
||||||
|
nil,
|
||||||
useCases.NewListUsersAndInvitesUseCase(f.users, f.invites),
|
useCases.NewListUsersAndInvitesUseCase(f.users, f.invites),
|
||||||
)
|
)
|
||||||
registerHandler := auth.NewLoginHandler(
|
registerHandler := auth.NewLoginHandler(
|
||||||
|
|||||||
@@ -99,13 +99,13 @@ func TestInvitationsQaList(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("The list never carries secrets or user emails", func(t *testing.T) {
|
t.Run("The list never carries secrets", func(t *testing.T) {
|
||||||
f := newInviteFixture(t, 100)
|
f := newInviteFixture(t, 100)
|
||||||
f.invites.seed(pendingInvite("sam@renew.example"))
|
f.invites.seed(pendingInvite("sam@renew.example"))
|
||||||
|
|
||||||
body := f.list(t).Body.String()
|
body := f.list(t).Body.String()
|
||||||
|
|
||||||
for _, forbidden := range []string{"\"code\"", "hashed_code", "verification_code", "password", "marta@renew.example"} {
|
for _, forbidden := range []string{"\"code\"", "hashed_code", "verification_code", "password"} {
|
||||||
if strings.Contains(body, forbidden) {
|
if strings.Contains(body, forbidden) {
|
||||||
t.Errorf("list leaks %q", forbidden)
|
t.Errorf("list leaks %q", forbidden)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -76,6 +76,21 @@ func (m *inviteFakeRepo) Delete(id uint32) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *inviteFakeRepo) Renew(id uint32, hashedCode string, expiresAt time.Time, createdAt time.Time) (invite.Invite, error) {
|
||||||
|
if err := m.fail.trigger("Renew"); err != nil {
|
||||||
|
return invite.Invite{}, err
|
||||||
|
}
|
||||||
|
stored, ok := m.invites[id]
|
||||||
|
if !ok || stored.AcceptedAt != nil {
|
||||||
|
return invite.Invite{}, invite.ErrInviteNotFound
|
||||||
|
}
|
||||||
|
stored.HashedCode = hashedCode
|
||||||
|
stored.ExpiresAt = expiresAt
|
||||||
|
stored.CreatedAt = createdAt
|
||||||
|
m.invites[id] = stored
|
||||||
|
return stored, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (m *inviteFakeRepo) AcceptWithUser(id uint32, at time.Time, newUser user.User) (user.User, error) {
|
func (m *inviteFakeRepo) AcceptWithUser(id uint32, at time.Time, newUser user.User) (user.User, error) {
|
||||||
if err := m.fail.trigger("MarkAccepted"); err != nil {
|
if err := m.fail.trigger("MarkAccepted"); err != nil {
|
||||||
return user.User{}, err
|
return user.User{}, err
|
||||||
@@ -111,7 +126,7 @@ func expiredInvite(email string) invite.Invite {
|
|||||||
|
|
||||||
func inviteInviterRepo(displayName string) *mockUserRepo {
|
func inviteInviterRepo(displayName string) *mockUserRepo {
|
||||||
repo := newMockUserRepo()
|
repo := newMockUserRepo()
|
||||||
repo.users[7] = user.User{ID: 7, Username: "marta", DisplayName: displayName, Email: "marta@renew.example", IsVerified: true}
|
repo.users[7] = user.User{ID: 7, Username: "marta", DisplayName: displayName, Email: "marta@renew.example", IsVerified: true, Role: user.RoleOwner}
|
||||||
repo.nextID = 7
|
repo.nextID = 7
|
||||||
return repo
|
return repo
|
||||||
}
|
}
|
||||||
@@ -138,6 +153,8 @@ func newInviteFixture(t *testing.T, maxAttempts int) *inviteFixture {
|
|||||||
getUser := useCases.NewGetUserUseCase(f.users)
|
getUser := useCases.NewGetUserUseCase(f.users)
|
||||||
handler := userhandler.NewInviteHandler(
|
handler := userhandler.NewInviteHandler(
|
||||||
useCases.NewCreateInviteUseCase(f.users, f.invites, f.hasher, f.mail, invitePublicURL),
|
useCases.NewCreateInviteUseCase(f.users, f.invites, f.hasher, f.mail, invitePublicURL),
|
||||||
|
nil,
|
||||||
|
nil,
|
||||||
useCases.NewListUsersAndInvitesUseCase(f.users, f.invites),
|
useCases.NewListUsersAndInvitesUseCase(f.users, f.invites),
|
||||||
)
|
)
|
||||||
f.router = chi.NewRouter()
|
f.router = chi.NewRouter()
|
||||||
@@ -478,14 +495,14 @@ func TestInvitationsHttp(t *testing.T) {
|
|||||||
if want.kind == "invite" {
|
if want.kind == "invite" {
|
||||||
assertExactKeys(t, item, "id", "kind", "email", "status", "created_at")
|
assertExactKeys(t, item, "id", "kind", "email", "status", "created_at")
|
||||||
} else {
|
} else {
|
||||||
assertExactKeys(t, item, "id", "kind", "username", "display_name", "status", "created_at")
|
assertExactKeys(t, item, "id", "kind", "username", "display_name", "email", "role", "status", "created_at")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if decodedString(t, items[2], "display_name") != "Ines Duarte" {
|
if decodedString(t, items[2], "display_name") != "Ines Duarte" {
|
||||||
t.Errorf("expected display name for ines")
|
t.Errorf("expected display name for ines")
|
||||||
}
|
}
|
||||||
if strings.Contains(rec.Body.String(), "jonas@renew.example") || strings.Contains(rec.Body.String(), "marta@renew.example") {
|
if decodedString(t, items[3], "email") != "jonas@renew.example" || decodedString(t, items[4], "email") != "marta@renew.example" {
|
||||||
t.Errorf("user emails and accepted invites must not be listed")
|
t.Errorf("expected user emails in the list")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,591 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/handlers/auth"
|
||||||
|
userhandler "RenewCMS/api/handlers/user"
|
||||||
|
"RenewCMS/api/middleware"
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
validator "RenewCMS/api/pkg/validator"
|
||||||
|
"RenewCMS/internal/domain/invite"
|
||||||
|
"RenewCMS/internal/domain/user"
|
||||||
|
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||||
|
persistence "RenewCMS/internal/infrastructure/persistence/repositories"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/glebarez/sqlite"
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/go-chi/jwtauth/v5"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
const manageClientIP = "203.0.113.40"
|
||||||
|
|
||||||
|
type inviteManagementFixture struct {
|
||||||
|
users *mockUserRepo
|
||||||
|
invites *inviteFakeRepo
|
||||||
|
mail *mockMailRepo
|
||||||
|
hasher *stubHasher
|
||||||
|
router *chi.Mux
|
||||||
|
token *jwtauth.JWTAuth
|
||||||
|
}
|
||||||
|
|
||||||
|
func newInviteManagementFixture(t *testing.T, maxAttempts int) *inviteManagementFixture {
|
||||||
|
t.Helper()
|
||||||
|
validator.InitValidator()
|
||||||
|
f := &inviteManagementFixture{
|
||||||
|
users: inviteInviterRepo(""),
|
||||||
|
invites: newInviteFakeRepo(),
|
||||||
|
mail: newMockMailRepo(),
|
||||||
|
hasher: &stubHasher{},
|
||||||
|
token: jwtauth.New("HS256", []byte("test-secret"), nil),
|
||||||
|
}
|
||||||
|
f.invites.users = f.users
|
||||||
|
f.users.users[9] = user.User{ID: 9, Username: "jonas", Email: "jonas@renew.example", IsVerified: true, Role: user.RoleAdmin}
|
||||||
|
f.users.users[11] = user.User{ID: 11, Username: "unverified", Email: "unverified@renew.example", IsVerified: false, Role: user.RoleAdmin}
|
||||||
|
f.users.users[12] = user.User{ID: 12, Username: "stale", Email: "stale@renew.example", IsVerified: true, Role: user.RoleOwner, TokenVersion: 2}
|
||||||
|
f.users.nextID = 12
|
||||||
|
|
||||||
|
getUser := useCases.NewGetUserUseCase(f.users)
|
||||||
|
handler := userhandler.NewInviteHandler(
|
||||||
|
useCases.NewCreateInviteUseCase(f.users, f.invites, f.hasher, f.mail, invitePublicURL),
|
||||||
|
useCases.NewCancelInviteUseCase(f.invites),
|
||||||
|
useCases.NewRenewInviteUseCase(f.users, f.invites, f.hasher, f.mail, invitePublicURL),
|
||||||
|
useCases.NewListUsersAndInvitesUseCase(f.users, f.invites),
|
||||||
|
)
|
||||||
|
acceptHandler := auth.NewAcceptInviteHandler(
|
||||||
|
useCases.NewGetInviteUseCase(f.invites, f.hasher),
|
||||||
|
useCases.NewAcceptInviteUseCase(f.users, f.invites, f.hasher),
|
||||||
|
f.token,
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
|
||||||
|
f.router = chi.NewRouter()
|
||||||
|
f.router.Get("/v1/auth/invite", acceptHandler.GetInvite)
|
||||||
|
f.router.Post("/v1/auth/invite/accept", acceptHandler.AcceptInvite)
|
||||||
|
f.router.Route("/v1/user", func(r chi.Router) {
|
||||||
|
r.Use(jwtauth.Verifier(f.token))
|
||||||
|
r.Use(jwtauth.Authenticator(f.token))
|
||||||
|
r.Use(middleware.RequireCurrentToken(getUser))
|
||||||
|
r.Use(middleware.RequireVerifiedUser(getUser))
|
||||||
|
r.Get("/", handler.ListUsers)
|
||||||
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(middleware.RequireOwner(getUser))
|
||||||
|
r.Use(middleware.TrustedProxyRealIP(nil))
|
||||||
|
r.Use(middleware.NewRateLimiter(maxAttempts, time.Hour))
|
||||||
|
r.Post("/invite", handler.CreateInvite)
|
||||||
|
r.Delete("/invite/{id}", handler.CancelInvite)
|
||||||
|
r.Post("/invite/{id}/renew", handler.RenewInvite)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *inviteManagementFixture) send(t *testing.T, method, target string, cookie *http.Cookie) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
req := httptest.NewRequest(method, target, strings.NewReader(""))
|
||||||
|
req.RemoteAddr = manageClientIP + ":4321"
|
||||||
|
if cookie != nil {
|
||||||
|
req.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
f.router.ServeHTTP(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *inviteManagementFixture) asOwner(t *testing.T, method, target string) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
return f.send(t, method, target, displayNameCookie(t, f.token, 7, 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *inviteManagementFixture) asUser(t *testing.T, id uint32, version uint32, method, target string) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
return f.send(t, method, target, displayNameCookie(t, f.token, id, version))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *inviteManagementFixture) accepted(email string) invite.Invite {
|
||||||
|
at := time.Now().Add(-time.Hour)
|
||||||
|
seeded := pendingInvite(email)
|
||||||
|
seeded.AcceptedAt = &at
|
||||||
|
return f.invites.seed(seeded)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInviteManagementHttp(t *testing.T) {
|
||||||
|
t.Run("The owner cancels a pending invite", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
f.invites.seed(pendingInvite("sam.oliveira@renew.example"))
|
||||||
|
f.invites.seed(pendingInvite("lea.martin@renew.example"))
|
||||||
|
f.invites.seed(expiredInvite("old@renew.example"))
|
||||||
|
f.invites.seed(pendingInvite("third@renew.example"))
|
||||||
|
before := f.invites.invites[2]
|
||||||
|
ownerBefore, adminBefore := f.users.users[7], f.users.users[9]
|
||||||
|
|
||||||
|
rec := f.asOwner(t, http.MethodDelete, "/v1/user/invite/1")
|
||||||
|
|
||||||
|
if rec.Code != http.StatusNoContent || rec.Body.Len() != 0 || rec.Header().Get("Cache-Control") != "" {
|
||||||
|
t.Fatalf("unexpected response %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if _, ok := f.invites.invites[1]; ok || len(f.invites.invites) != 3 || f.invites.invites[2] != before {
|
||||||
|
t.Errorf("unexpected invite state %+v", f.invites.invites)
|
||||||
|
}
|
||||||
|
if len(f.mail.SentEmails) != 0 || len(f.users.users) != 4 || f.users.users[7] != ownerBefore || f.users.users[9] != adminBefore {
|
||||||
|
t.Errorf("mail or users changed")
|
||||||
|
}
|
||||||
|
if strings.Contains(f.asOwner(t, http.MethodGet, "/v1/user/").Body.String(), "sam.oliveira@renew.example") {
|
||||||
|
t.Errorf("cancelled invite still listed")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A cancelled invite's link stops working and its address can be invited again", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
f.invites.seed(invite.Invite{Email: "sam.oliveira@renew.example", HashedCode: "hashed:OLD-CODE", InvitedBy: 7, CreatedAt: time.Now(), ExpiresAt: time.Now().Add(time.Hour)})
|
||||||
|
f.asOwner(t, http.MethodDelete, "/v1/user/invite/1")
|
||||||
|
|
||||||
|
rec := f.send(t, http.MethodGet, "/v1/auth/invite?c=OLD-CODE", nil)
|
||||||
|
if rec.Code != http.StatusNotFound || rec.Body.String() != inviteInvalidBody {
|
||||||
|
t.Errorf("expected 404 invalid, got %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/v1/user/invite", strings.NewReader(`{"email": "sam.oliveira@renew.example"}`))
|
||||||
|
req.RemoteAddr = manageClientIP + ":4321"
|
||||||
|
req.AddCookie(displayNameCookie(t, f.token, 7, 0))
|
||||||
|
created := httptest.NewRecorder()
|
||||||
|
f.router.ServeHTTP(created, req)
|
||||||
|
if created.Code != http.StatusCreated {
|
||||||
|
t.Errorf("expected 201, got %d", created.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("The owner cancels an expired invite", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
f.invites.seed(expiredInvite("old@renew.example"))
|
||||||
|
|
||||||
|
rec := f.asOwner(t, http.MethodDelete, "/v1/user/invite/1")
|
||||||
|
|
||||||
|
if rec.Code != http.StatusNoContent || len(f.invites.invites) != 0 {
|
||||||
|
t.Errorf("expected 204 and empty repo, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Renewing a cancelled invite is not found", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
f.invites.seed(pendingInvite("sam.oliveira@renew.example"))
|
||||||
|
f.asOwner(t, http.MethodDelete, "/v1/user/invite/1")
|
||||||
|
|
||||||
|
rec := f.asOwner(t, http.MethodPost, "/v1/user/invite/1/renew")
|
||||||
|
|
||||||
|
if rec.Code != http.StatusNotFound || rec.Body.String() != apperr.InviteNotFoundErrorMessage+"\n" || len(f.mail.SentEmails) != 0 {
|
||||||
|
t.Errorf("unexpected %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("An unknown invite is not found, and cancelling twice too", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
f.invites.seed(pendingInvite("sam.oliveira@renew.example"))
|
||||||
|
|
||||||
|
rec := f.asOwner(t, http.MethodDelete, "/v1/user/invite/999")
|
||||||
|
if rec.Code != http.StatusNotFound || rec.Body.String() != apperr.InviteNotFoundErrorMessage+"\n" {
|
||||||
|
t.Errorf("unexpected %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
f.asOwner(t, http.MethodDelete, "/v1/user/invite/1")
|
||||||
|
if again := f.asOwner(t, http.MethodDelete, "/v1/user/invite/1"); again.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("expected 404, got %d", again.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("An accepted invite cannot be cancelled or renewed", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
accepted := f.accepted("lea.martin@renew.example")
|
||||||
|
|
||||||
|
for _, call := range []struct{ method, path string }{
|
||||||
|
{http.MethodDelete, "/v1/user/invite/1"},
|
||||||
|
{http.MethodPost, "/v1/user/invite/1/renew"},
|
||||||
|
} {
|
||||||
|
rec := f.asOwner(t, call.method, call.path)
|
||||||
|
if rec.Code != http.StatusConflict || rec.Body.String() != apperr.InviteAlreadyAcceptedErrorMessage+"\n" {
|
||||||
|
t.Errorf("%s: unexpected %d %q", call.method, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if f.invites.invites[1].HashedCode != accepted.HashedCode || len(f.mail.SentEmails) != 0 {
|
||||||
|
t.Errorf("accepted invite changed or mail sent")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("The owner renews an expired invite", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
now := time.Now()
|
||||||
|
for _, filler := range []string{"a@renew.example", "b@renew.example", "c@renew.example"} {
|
||||||
|
f.invites.seed(pendingInvite(filler))
|
||||||
|
}
|
||||||
|
f.invites.seed(invite.Invite{Email: "lea.martin@renew.example", HashedCode: "hashed:OLD-CODE", InvitedBy: 9, CreatedAt: now.Add(-5 * 24 * time.Hour), ExpiresAt: now.Add(-2 * 24 * time.Hour)})
|
||||||
|
|
||||||
|
rec := f.asOwner(t, http.MethodPost, "/v1/user/invite/4/renew")
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK || rec.Header().Get("Cache-Control") != "no-store" {
|
||||||
|
t.Fatalf("unexpected %d %q", rec.Code, rec.Header().Get("Cache-Control"))
|
||||||
|
}
|
||||||
|
decoded := decodeKeys(t, rec.Body.Bytes())
|
||||||
|
assertExactKeys(t, decoded, "id", "kind", "email", "status", "created_at", "expires_at")
|
||||||
|
if decodedString(t, decoded, "kind") != "invite" || decodedString(t, decoded, "email") != "lea.martin@renew.example" || decodedString(t, decoded, "status") != "pending" {
|
||||||
|
t.Errorf("unexpected body %s", rec.Body.String())
|
||||||
|
}
|
||||||
|
var id uint32
|
||||||
|
if err := json.Unmarshal(decoded["id"], &id); err != nil || id != 4 {
|
||||||
|
t.Errorf("unexpected id %s", decoded["id"])
|
||||||
|
}
|
||||||
|
createdAt, err := time.Parse(time.RFC3339Nano, decodedString(t, decoded, "created_at"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("bad created_at: %v", err)
|
||||||
|
}
|
||||||
|
expiresAt, err := time.Parse(time.RFC3339Nano, decodedString(t, decoded, "expires_at"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("bad expires_at: %v", err)
|
||||||
|
}
|
||||||
|
if time.Since(createdAt) > 5*time.Second || time.Until(createdAt) > 5*time.Second {
|
||||||
|
t.Errorf("unexpected created_at %s", createdAt)
|
||||||
|
}
|
||||||
|
if delta := expiresAt.Sub(createdAt) - invite.Lifetime; delta > 5*time.Second || delta < -5*time.Second {
|
||||||
|
t.Errorf("unexpected expires_at %s", expiresAt)
|
||||||
|
}
|
||||||
|
stored := f.invites.invites[4]
|
||||||
|
data := inviteMailData(t, f.mail)
|
||||||
|
if time.Since(stored.CreatedAt) > 5*time.Second || stored.ExpiresAt.Sub(stored.CreatedAt) != invite.Lifetime {
|
||||||
|
t.Errorf("unexpected dates %+v", stored)
|
||||||
|
}
|
||||||
|
if stored.HashedCode != "hashed:"+data.VerificationCode || stored.HashedCode == "hashed:OLD-CODE" || stored.InvitedBy != 9 || stored.AcceptedAt != nil || len(f.invites.invites) != 4 {
|
||||||
|
t.Errorf("unexpected stored invite %+v", stored)
|
||||||
|
}
|
||||||
|
if data.Host != invitePublicURL || data.Email != "lea.martin@renew.example" || data.InvitedBy != "marta" || f.mail.SentEmails[0].Template != "invitation" || f.mail.SentEmails[0].Address != "lea.martin@renew.example" {
|
||||||
|
t.Errorf("unexpected mail %+v", f.mail.SentEmails[0])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A renewed pending invite moves to the top of the list and the old link dies", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
f.invites.seed(invite.Invite{Email: "lea.martin@renew.example", HashedCode: "hashed:OLD-CODE", InvitedBy: 7, CreatedAt: time.Now().Add(-48 * time.Hour), ExpiresAt: time.Now().Add(24 * time.Hour)})
|
||||||
|
f.invites.seed(invite.Invite{Email: "newer@renew.example", HashedCode: "hashed:OTHER", InvitedBy: 7, CreatedAt: time.Now().Add(-24 * time.Hour), ExpiresAt: time.Now().Add(48 * time.Hour)})
|
||||||
|
|
||||||
|
f.asOwner(t, http.MethodPost, "/v1/user/invite/1/renew")
|
||||||
|
|
||||||
|
list := f.asOwner(t, http.MethodGet, "/v1/user/").Body.String()
|
||||||
|
if strings.Index(list, "lea.martin@renew.example") > strings.Index(list, "newer@renew.example") {
|
||||||
|
t.Errorf("renewed invite not listed first: %s", list)
|
||||||
|
}
|
||||||
|
if old := f.send(t, http.MethodGet, "/v1/auth/invite?c=OLD-CODE", nil); old.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("old link expected 404, got %d", old.Code)
|
||||||
|
}
|
||||||
|
fresh := f.send(t, http.MethodGet, "/v1/auth/invite?c="+inviteMailData(t, f.mail).VerificationCode, nil)
|
||||||
|
if fresh.Code != http.StatusOK || !strings.Contains(fresh.Body.String(), "lea.martin@renew.example") {
|
||||||
|
t.Errorf("new link expected 200, got %d %q", fresh.Code, fresh.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Accepting with a cancelled or replaced code is not found and creates no user", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
f.invites.seed(invite.Invite{Email: "lea.martin@renew.example", HashedCode: "hashed:OLD-CODE", InvitedBy: 7, CreatedAt: time.Now().Add(-time.Hour), ExpiresAt: time.Now().Add(24 * time.Hour)})
|
||||||
|
f.invites.seed(invite.Invite{Email: "sam@renew.example", HashedCode: "hashed:CANCELLED", InvitedBy: 7, CreatedAt: time.Now().Add(-time.Hour), ExpiresAt: time.Now().Add(24 * time.Hour)})
|
||||||
|
f.asOwner(t, http.MethodPost, "/v1/user/invite/1/renew")
|
||||||
|
f.asOwner(t, http.MethodDelete, "/v1/user/invite/2")
|
||||||
|
usersBefore := len(f.users.users)
|
||||||
|
|
||||||
|
for _, code := range []string{"OLD-CODE", "CANCELLED"} {
|
||||||
|
body := `{"code":"` + code + `","username":"newperson","password":"password123"}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/v1/auth/invite/accept", strings.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
f.router.ServeHTTP(rec, req)
|
||||||
|
if rec.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("%s: expected 404, got %d %q", code, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(f.users.users) != usersBefore {
|
||||||
|
t.Errorf("a user was created")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Renewing an unknown invite is not found", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
|
||||||
|
rec := f.asOwner(t, http.MethodPost, "/v1/user/invite/999/renew")
|
||||||
|
|
||||||
|
if rec.Code != http.StatusNotFound || rec.Body.String() != apperr.InviteNotFoundErrorMessage+"\n" {
|
||||||
|
t.Errorf("unexpected %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A failed email leaves the invite as it was", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
seeded := f.invites.seed(expiredInvite("lea.martin@renew.example"))
|
||||||
|
f.mail.fail.failNext("Send")
|
||||||
|
|
||||||
|
rec := f.asOwner(t, http.MethodPost, "/v1/user/invite/1/renew")
|
||||||
|
|
||||||
|
if rec.Code != http.StatusInternalServerError || rec.Body.String() != apperr.InviteNotSentErrorMessage+"\n" {
|
||||||
|
t.Fatalf("unexpected %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if f.invites.invites[1] != seeded {
|
||||||
|
t.Errorf("invite changed: %+v vs %+v", f.invites.invites[1], seeded)
|
||||||
|
}
|
||||||
|
if retry := f.asOwner(t, http.MethodPost, "/v1/user/invite/1/renew"); retry.Code != http.StatusOK {
|
||||||
|
t.Errorf("retry expected 200, got %d", retry.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A repository failure on cancel leaves the invite in place", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
seeded := f.invites.seed(pendingInvite("sam.oliveira@renew.example"))
|
||||||
|
f.invites.fail.failNextWith("Delete", errRepositoryFailure)
|
||||||
|
|
||||||
|
rec := f.asOwner(t, http.MethodDelete, "/v1/user/invite/1")
|
||||||
|
|
||||||
|
if rec.Code != http.StatusInternalServerError || f.invites.invites[1] != seeded {
|
||||||
|
t.Errorf("unexpected %d or invite changed", rec.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A repository failure on renew sends no mail and leaves the invite as it was", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
seeded := f.invites.seed(pendingInvite("sam.oliveira@renew.example"))
|
||||||
|
f.invites.fail.failNextWith("Renew", errRepositoryFailure)
|
||||||
|
|
||||||
|
rec := f.asOwner(t, http.MethodPost, "/v1/user/invite/1/renew")
|
||||||
|
|
||||||
|
if rec.Code != http.StatusInternalServerError || f.invites.invites[1] != seeded || len(f.mail.SentEmails) != 0 {
|
||||||
|
t.Errorf("unexpected %d, invite or mail changed", rec.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("The old code of a pending invite works until it is renewed", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
f.invites.seed(invite.Invite{Email: "lea.martin@renew.example", HashedCode: "hashed:OLD-CODE", InvitedBy: 7, CreatedAt: time.Now().Add(-time.Hour), ExpiresAt: time.Now().Add(24 * time.Hour)})
|
||||||
|
|
||||||
|
if before := f.send(t, http.MethodGet, "/v1/auth/invite?c=OLD-CODE", nil); before.Code != http.StatusOK {
|
||||||
|
t.Fatalf("control expected 200, got %d", before.Code)
|
||||||
|
}
|
||||||
|
f.asOwner(t, http.MethodPost, "/v1/user/invite/1/renew")
|
||||||
|
if after := f.send(t, http.MethodGet, "/v1/auth/invite?c=OLD-CODE", nil); after.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("expected 404, got %d", after.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Access is checked on both endpoints", func(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
cookie func(f *inviteManagementFixture) *http.Cookie
|
||||||
|
wantErr int
|
||||||
|
}{
|
||||||
|
{"no cookie", func(f *inviteManagementFixture) *http.Cookie { return nil }, http.StatusUnauthorized},
|
||||||
|
{"stale token_version", func(f *inviteManagementFixture) *http.Cookie { return displayNameCookie(t, f.token, 12, 1) }, http.StatusUnauthorized},
|
||||||
|
{"unverified user", func(f *inviteManagementFixture) *http.Cookie { return displayNameCookie(t, f.token, 11, 0) }, http.StatusForbidden},
|
||||||
|
{"admin", func(f *inviteManagementFixture) *http.Cookie { return displayNameCookie(t, f.token, 9, 0) }, http.StatusForbidden},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
for _, call := range []struct{ method, path string }{
|
||||||
|
{http.MethodDelete, "/v1/user/invite/1"},
|
||||||
|
{http.MethodPost, "/v1/user/invite/1/renew"},
|
||||||
|
} {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
seeded := f.invites.seed(pendingInvite("sam.oliveira@renew.example"))
|
||||||
|
|
||||||
|
rec := f.send(t, call.method, call.path, tc.cookie(f))
|
||||||
|
|
||||||
|
if rec.Code != tc.wantErr || f.invites.invites[1] != seeded || len(f.mail.SentEmails) != 0 {
|
||||||
|
t.Errorf("%s %s %s: got %d", tc.name, call.method, call.path, rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("An admin is refused with the owner message, even on an unknown id", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
|
||||||
|
rec := f.asUser(t, 9, 0, http.MethodDelete, "/v1/user/invite/999")
|
||||||
|
|
||||||
|
if rec.Code != http.StatusForbidden || rec.Body.String() != apperr.OwnerRequiredErrorMessage+"\n" {
|
||||||
|
t.Errorf("unexpected %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("An id that is not a uint32 is rejected", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 100)
|
||||||
|
for _, ident := range []string{"abc", "-1", "4294967296"} {
|
||||||
|
for _, call := range []struct{ method, suffix string }{{http.MethodDelete, ""}, {http.MethodPost, "/renew"}} {
|
||||||
|
rec := f.asOwner(t, call.method, "/v1/user/invite/"+ident+call.suffix)
|
||||||
|
if rec.Code != http.StatusBadRequest || rec.Body.String() != apperr.IdUint32ErrorMessage+"\n" {
|
||||||
|
t.Errorf("%s %s: unexpected %d %q", call.method, ident, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Requests over the limit are refused and the counter is shared with inviting", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 2)
|
||||||
|
f.invites.seed(pendingInvite("sam.oliveira@renew.example"))
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/v1/user/invite", strings.NewReader(`{"email": "new.person@renew.example"}`))
|
||||||
|
req.RemoteAddr = manageClientIP + ":4321"
|
||||||
|
req.AddCookie(displayNameCookie(t, f.token, 7, 0))
|
||||||
|
created := httptest.NewRecorder()
|
||||||
|
f.router.ServeHTTP(created, req)
|
||||||
|
if created.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("expected 201, got %d", created.Code)
|
||||||
|
}
|
||||||
|
f.asOwner(t, http.MethodPost, "/v1/user/invite/1/renew")
|
||||||
|
rec := f.asOwner(t, http.MethodDelete, "/v1/user/invite/1")
|
||||||
|
|
||||||
|
if rec.Code != http.StatusTooManyRequests || rec.Body.String() != apperr.TooManyRequestsErrorMessage+"\n" || rec.Header().Get("Retry-After") == "" {
|
||||||
|
t.Errorf("unexpected %d %q", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if _, ok := f.invites.invites[1]; !ok || len(f.mail.SentEmails) != 2 {
|
||||||
|
t.Errorf("third request changed something")
|
||||||
|
}
|
||||||
|
if list := f.asOwner(t, http.MethodGet, "/v1/user/"); list.Code != http.StatusOK {
|
||||||
|
t.Errorf("list should not be limited, got %d", list.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("An admin does not use up the quota", func(t *testing.T) {
|
||||||
|
f := newInviteManagementFixture(t, 2)
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
if rec := f.asUser(t, 9, 0, http.MethodDelete, "/v1/user/invite/1"); rec.Code != http.StatusForbidden {
|
||||||
|
t.Errorf("request %d: expected 403, got %d", i, rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type renewRestoreFailRepo struct {
|
||||||
|
*inviteFakeRepo
|
||||||
|
calls int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *renewRestoreFailRepo) Renew(id uint32, hashedCode string, expiresAt time.Time, createdAt time.Time) (invite.Invite, error) {
|
||||||
|
r.calls++
|
||||||
|
if r.calls == 2 {
|
||||||
|
return invite.Invite{}, errRepositoryFailure
|
||||||
|
}
|
||||||
|
return r.inviteFakeRepo.Renew(id, hashedCode, expiresAt, createdAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManageInviteUseCases(t *testing.T) {
|
||||||
|
t.Run("Renew restores the previous values when the mail fails", func(t *testing.T) {
|
||||||
|
users := inviteInviterRepo("Marta")
|
||||||
|
invites := newInviteFakeRepo()
|
||||||
|
mail := newMockMailRepo()
|
||||||
|
seeded := invites.seed(pendingInvite("a@renew.example"))
|
||||||
|
mail.fail.failNextWith("Send", errors.New("smtp down"))
|
||||||
|
renew := useCases.NewRenewInviteUseCase(users, invites, &stubHasher{}, mail, invitePublicURL)
|
||||||
|
|
||||||
|
_, err := renew.RenewInvite(useCases.RenewInviteCommand{ID: 1, RenewedBy: 7})
|
||||||
|
|
||||||
|
if !errors.Is(err, invite.ErrInviteEmailNotSent) || errors.Is(err, errRepositoryFailure) || invites.invites[1] != seeded {
|
||||||
|
t.Errorf("unexpected result %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Renew joins the restore failure with the mail failure", func(t *testing.T) {
|
||||||
|
users := inviteInviterRepo("Marta")
|
||||||
|
invites := newInviteFakeRepo()
|
||||||
|
mail := newMockMailRepo()
|
||||||
|
invites.seed(pendingInvite("a@renew.example"))
|
||||||
|
mail.fail.failNextWith("Send", errors.New("smtp down"))
|
||||||
|
renew := useCases.NewRenewInviteUseCase(users, &renewRestoreFailRepo{inviteFakeRepo: invites}, &stubHasher{}, mail, invitePublicURL)
|
||||||
|
|
||||||
|
_, err := renew.RenewInvite(useCases.RenewInviteCommand{ID: 1, RenewedBy: 7})
|
||||||
|
|
||||||
|
if !errors.Is(err, invite.ErrInviteEmailNotSent) || !errors.Is(err, errRepositoryFailure) {
|
||||||
|
t.Errorf("unexpected result %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Cancel returns the sentinels", func(t *testing.T) {
|
||||||
|
invites := newInviteFakeRepo()
|
||||||
|
invites.seed(pendingInvite("a@renew.example"))
|
||||||
|
accepted := pendingInvite("b@renew.example")
|
||||||
|
at := time.Now()
|
||||||
|
accepted.AcceptedAt = &at
|
||||||
|
invites.seed(accepted)
|
||||||
|
cancel := useCases.NewCancelInviteUseCase(invites)
|
||||||
|
|
||||||
|
if err := cancel.CancelInvite(9); !errors.Is(err, invite.ErrInviteNotFound) {
|
||||||
|
t.Errorf("expected not found, got %v", err)
|
||||||
|
}
|
||||||
|
if err := cancel.CancelInvite(2); !errors.Is(err, invite.ErrInviteAlreadyAccepted) {
|
||||||
|
t.Errorf("expected already accepted, got %v", err)
|
||||||
|
}
|
||||||
|
if err := cancel.CancelInvite(1); err != nil {
|
||||||
|
t.Errorf("unexpected %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Renew sends nothing when persisting fails", func(t *testing.T) {
|
||||||
|
users := inviteInviterRepo("Marta")
|
||||||
|
invites := newInviteFakeRepo()
|
||||||
|
mail := newMockMailRepo()
|
||||||
|
seeded := invites.seed(pendingInvite("a@renew.example"))
|
||||||
|
invites.fail.failNextWith("Renew", errRepositoryFailure)
|
||||||
|
renew := useCases.NewRenewInviteUseCase(users, invites, &stubHasher{}, mail, invitePublicURL)
|
||||||
|
|
||||||
|
_, err := renew.RenewInvite(useCases.RenewInviteCommand{ID: 1, RenewedBy: 7})
|
||||||
|
|
||||||
|
if !errors.Is(err, errRepositoryFailure) || len(mail.SentEmails) != 0 || invites.invites[1] != seeded {
|
||||||
|
t.Errorf("unexpected result %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Renew names the acting owner by display name", func(t *testing.T) {
|
||||||
|
users := inviteInviterRepo("Marta L.")
|
||||||
|
invites := newInviteFakeRepo()
|
||||||
|
mail := newMockMailRepo()
|
||||||
|
invites.seed(pendingInvite("a@renew.example"))
|
||||||
|
renew := useCases.NewRenewInviteUseCase(users, invites, &stubHasher{}, mail, invitePublicURL)
|
||||||
|
|
||||||
|
if _, err := renew.RenewInvite(useCases.RenewInviteCommand{ID: 1, RenewedBy: 7}); err != nil {
|
||||||
|
t.Fatalf("unexpected %v", err)
|
||||||
|
}
|
||||||
|
if inviteMailData(t, mail).InvitedBy != "Marta L." {
|
||||||
|
t.Errorf("unexpected inviter name")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInviteRepositoryRenew(t *testing.T) {
|
||||||
|
db, err := gorm.Open(sqlite.Open("file:inviterenew?mode=memory&cache=private"), &gorm.Config{Logger: logger.Discard})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to open db: %v", err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(&entity.Invite{}); err != nil {
|
||||||
|
t.Fatalf("failed to migrate: %v", err)
|
||||||
|
}
|
||||||
|
repo := persistence.NewInviteRepository(db)
|
||||||
|
now := time.Now().UTC().Truncate(time.Second)
|
||||||
|
created, err := repo.Create(invite.Invite{Email: "a@renew.example", HashedCode: "old", InvitedBy: 7, CreatedAt: now.Add(-96 * time.Hour), ExpiresAt: now.Add(-24 * time.Hour)})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create failed: %v", err)
|
||||||
|
}
|
||||||
|
accepted := now
|
||||||
|
acceptedRow := entity.Invite{Email: "b@renew.example", HashedCode: "x", InvitedBy: 7, AcceptedAt: &accepted}
|
||||||
|
db.Create(&acceptedRow)
|
||||||
|
|
||||||
|
t.Run("Renew replaces code hash and dates and keeps the id", func(t *testing.T) {
|
||||||
|
renewed, err := repo.Renew(created.ID, "new", now.Add(invite.Lifetime), now)
|
||||||
|
if err != nil || renewed.ID != created.ID || renewed.HashedCode != "new" || !renewed.CreatedAt.Equal(now) || !renewed.ExpiresAt.Equal(now.Add(invite.Lifetime)) || renewed.InvitedBy != 7 {
|
||||||
|
t.Errorf("unexpected %+v %v", renewed, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Renew of an unknown or accepted invite is not found", func(t *testing.T) {
|
||||||
|
if _, err := repo.Renew(999, "new", now, now); !errors.Is(err, invite.ErrInviteNotFound) {
|
||||||
|
t.Errorf("expected not found, got %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.Renew(acceptedRow.ID, "new", now, now); !errors.Is(err, invite.ErrInviteNotFound) {
|
||||||
|
t.Errorf("expected not found, got %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/handlers/settings"
|
||||||
|
"RenewCMS/api/middleware"
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
validator "RenewCMS/api/pkg/validator"
|
||||||
|
"RenewCMS/internal/domain/user"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/go-chi/jwtauth/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newSettingsRouter(userRepo *mockUserRepo, token *jwtauth.JWTAuth, version string) *chi.Mux {
|
||||||
|
getUserUseCase := useCases.NewGetUserUseCase(userRepo)
|
||||||
|
settingsHandler := settings.NewHandler(useCases.NewGetSettingsUseCase(version))
|
||||||
|
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Route("/v1/settings", func(r chi.Router) {
|
||||||
|
r.Use(jwtauth.Verifier(token))
|
||||||
|
r.Use(jwtauth.Authenticator(token))
|
||||||
|
r.Use(middleware.RequireCurrentToken(getUserUseCase))
|
||||||
|
r.Use(middleware.RequireVerifiedUser(getUserUseCase))
|
||||||
|
r.Get("/", settingsHandler.GetSettings)
|
||||||
|
})
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSettingsHttp(t *testing.T) {
|
||||||
|
validator.InitValidator()
|
||||||
|
|
||||||
|
for _, version := range []string{"v2.2.0-beta", "dev"} {
|
||||||
|
t.Run("A verified caller gets the running build's version: "+version, func(t *testing.T) {
|
||||||
|
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||||
|
userRepo := newMockUserRepo()
|
||||||
|
userRepo.users[7] = user.User{ID: 7, Username: "alice", IsVerified: true, TokenVersion: 0}
|
||||||
|
router := newSettingsRouter(userRepo, token, version)
|
||||||
|
cookie := mintGetCurrentUserCookie(t, token, 7, 0)
|
||||||
|
|
||||||
|
rec := sendGetCurrentUserRequest(router, http.MethodGet, "/v1/settings", cookie)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status 200, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if rec.Body.String() != `{"version":"`+version+`"}` {
|
||||||
|
t.Errorf("unexpected body: %q", rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("The response does not depend on the environment at request time", func(t *testing.T) {
|
||||||
|
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||||
|
userRepo := newMockUserRepo()
|
||||||
|
userRepo.users[7] = user.User{ID: 7, Username: "alice", IsVerified: true, TokenVersion: 0}
|
||||||
|
router := newSettingsRouter(userRepo, token, "v2.2.0-beta")
|
||||||
|
cookie := mintGetCurrentUserCookie(t, token, 7, 0)
|
||||||
|
t.Setenv("ENVIRONMENT", "development")
|
||||||
|
|
||||||
|
rec := sendGetCurrentUserRequest(router, http.MethodGet, "/v1/settings", cookie)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status 200, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if rec.Body.String() != `{"version":"v2.2.0-beta"}` {
|
||||||
|
t.Errorf("unexpected body: %q", rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A request without a jwt cookie is refused", func(t *testing.T) {
|
||||||
|
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||||
|
router := newSettingsRouter(newMockUserRepo(), token, "v2.2.0-beta")
|
||||||
|
|
||||||
|
rec := sendGetCurrentUserRequest(router, http.MethodGet, "/v1/settings", nil)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("expected status 401, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if strings.Contains(rec.Body.String(), "v2.2.0-beta") {
|
||||||
|
t.Errorf("body leaks the version: %q", rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A token whose version no longer matches the account is refused", func(t *testing.T) {
|
||||||
|
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||||
|
userRepo := newMockUserRepo()
|
||||||
|
userRepo.users[7] = user.User{ID: 7, Username: "alice", IsVerified: true, TokenVersion: 1}
|
||||||
|
router := newSettingsRouter(userRepo, token, "v2.2.0-beta")
|
||||||
|
cookie := mintGetCurrentUserCookie(t, token, 7, 0)
|
||||||
|
|
||||||
|
rec := sendGetCurrentUserRequest(router, http.MethodGet, "/v1/settings", cookie)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("expected status 401, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if rec.Body.String() != apperr.UnauthorizedErrorMessage+"\n" {
|
||||||
|
t.Errorf("unexpected body: %q", rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("An unverified account is refused", func(t *testing.T) {
|
||||||
|
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||||
|
userRepo := newMockUserRepo()
|
||||||
|
userRepo.users[8] = user.User{ID: 8, Username: "bob", IsVerified: false, TokenVersion: 0}
|
||||||
|
router := newSettingsRouter(userRepo, token, "v2.2.0-beta")
|
||||||
|
cookie := mintGetCurrentUserCookie(t, token, 8, 0)
|
||||||
|
|
||||||
|
rec := sendGetCurrentUserRequest(router, http.MethodGet, "/v1/settings", cookie)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("expected status 403, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if rec.Body.String() != apperr.VerificationRequiredErrorMessage+"\n" {
|
||||||
|
t.Errorf("unexpected body: %q", rec.Body.String())
|
||||||
|
}
|
||||||
|
if strings.Contains(rec.Body.String(), "v2.2.0-beta") {
|
||||||
|
t.Errorf("body leaks the version: %q", rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetSettingsUseCase(t *testing.T) {
|
||||||
|
for _, version := range []string{"v2.2.0-beta", "dev"} {
|
||||||
|
t.Run("The use case returns the version it was built with: "+version, func(t *testing.T) {
|
||||||
|
useCase := useCases.NewGetSettingsUseCase(version)
|
||||||
|
|
||||||
|
got := useCase.GetSettings()
|
||||||
|
|
||||||
|
if got.Version != version {
|
||||||
|
t.Errorf("expected version %s, got %q", version, got.Version)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,7 +20,7 @@ import (
|
|||||||
"github.com/go-chi/jwtauth/v5"
|
"github.com/go-chi/jwtauth/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
var displayNameResponseKeys = []string{"id", "username", "email", "is_verified", "created_at", "updated_at", "display_name"}
|
var displayNameResponseKeys = []string{"id", "username", "email", "is_verified", "created_at", "updated_at", "display_name", "role"}
|
||||||
|
|
||||||
func newDisplayNameRouter(userRepo *mockUserRepo, token *jwtauth.JWTAuth) *chi.Mux {
|
func newDisplayNameRouter(userRepo *mockUserRepo, token *jwtauth.JWTAuth) *chi.Mux {
|
||||||
hasher := &stubHasher{}
|
hasher := &stubHasher{}
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ func TestUserResponseFieldHygiene(t *testing.T) {
|
|||||||
t.Fatalf("failed to decode response: %v", err)
|
t.Fatalf("failed to decode response: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedKeys := []string{"id", "username", "email", "is_verified", "created_at", "updated_at", "display_name"}
|
expectedKeys := []string{"id", "username", "email", "is_verified", "created_at", "updated_at", "display_name", "role"}
|
||||||
if len(decoded) != len(expectedKeys) {
|
if len(decoded) != len(expectedKeys) {
|
||||||
t.Errorf("expected exactly %d keys, got %d: %v", len(expectedKeys), len(decoded), decoded)
|
t.Errorf("expected exactly %d keys, got %d: %v", len(expectedKeys), len(decoded), decoded)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,486 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/handlers/auth"
|
||||||
|
userhandler "RenewCMS/api/handlers/user"
|
||||||
|
"RenewCMS/api/middleware"
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
validator "RenewCMS/api/pkg/validator"
|
||||||
|
"RenewCMS/internal/domain/user"
|
||||||
|
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||||
|
persistence "RenewCMS/internal/infrastructure/persistence/repositories"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"bytes"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/glebarez/sqlite"
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/go-chi/jwtauth/v5"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
rolesInviteBody = `{"email": "sam.oliveira@renew.example"}`
|
||||||
|
rolesClientIP = "203.0.113.20"
|
||||||
|
)
|
||||||
|
|
||||||
|
type userRolesFixture struct {
|
||||||
|
users *mockUserRepo
|
||||||
|
invites *inviteFakeRepo
|
||||||
|
mail *mockMailRepo
|
||||||
|
router *chi.Mux
|
||||||
|
token *jwtauth.JWTAuth
|
||||||
|
}
|
||||||
|
|
||||||
|
func newUserRolesFixture(t *testing.T, maxAttempts int) *userRolesFixture {
|
||||||
|
t.Helper()
|
||||||
|
validator.InitValidator()
|
||||||
|
f := &userRolesFixture{
|
||||||
|
users: newMockUserRepo(),
|
||||||
|
invites: newInviteFakeRepo(),
|
||||||
|
mail: newMockMailRepo(),
|
||||||
|
token: jwtauth.New("HS256", []byte("test-secret"), nil),
|
||||||
|
}
|
||||||
|
f.invites.users = f.users
|
||||||
|
hasher := &stubHasher{}
|
||||||
|
getUser := useCases.NewGetUserUseCase(f.users)
|
||||||
|
loginHandler := auth.NewLoginHandler(
|
||||||
|
f.token,
|
||||||
|
useCases.NewCreateUserUseCase(f.users, hasher, f.mail, invitePublicURL),
|
||||||
|
useCases.NewAuthenticateUserUseCase(f.users, hasher),
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
acceptHandler := auth.NewAcceptInviteHandler(
|
||||||
|
useCases.NewGetInviteUseCase(f.invites, hasher),
|
||||||
|
useCases.NewAcceptInviteUseCase(f.users, f.invites, hasher),
|
||||||
|
f.token,
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
meHandler := auth.NewMeHandler(getUser)
|
||||||
|
inviteHandler := userhandler.NewInviteHandler(
|
||||||
|
useCases.NewCreateInviteUseCase(f.users, f.invites, hasher, f.mail, invitePublicURL),
|
||||||
|
nil,
|
||||||
|
nil,
|
||||||
|
useCases.NewListUsersAndInvitesUseCase(f.users, f.invites),
|
||||||
|
)
|
||||||
|
|
||||||
|
f.router = chi.NewRouter()
|
||||||
|
f.router.Route("/v1/auth", func(r chi.Router) {
|
||||||
|
r.Post("/register", loginHandler.Register)
|
||||||
|
r.Post("/invite/accept", acceptHandler.AcceptInvite)
|
||||||
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(jwtauth.Verifier(f.token))
|
||||||
|
r.Use(jwtauth.Authenticator(f.token))
|
||||||
|
r.Use(middleware.RequireCurrentToken(getUser))
|
||||||
|
r.Get("/me", meHandler.Me)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
f.router.Route("/v1/user", func(r chi.Router) {
|
||||||
|
r.Use(jwtauth.Verifier(f.token))
|
||||||
|
r.Use(jwtauth.Authenticator(f.token))
|
||||||
|
r.Use(middleware.RequireCurrentToken(getUser))
|
||||||
|
r.Use(middleware.RequireVerifiedUser(getUser))
|
||||||
|
r.Get("/", inviteHandler.ListUsers)
|
||||||
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(middleware.RequireOwner(getUser))
|
||||||
|
r.Use(middleware.TrustedProxyRealIP(nil))
|
||||||
|
r.Use(middleware.NewRateLimiter(maxAttempts, time.Hour))
|
||||||
|
r.Post("/invite", inviteHandler.CreateInvite)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *userRolesFixture) seedUser(id uint32, username string, role user.Role, verified bool) {
|
||||||
|
f.users.users[id] = user.User{
|
||||||
|
ID: id,
|
||||||
|
Username: username,
|
||||||
|
Email: username + "@renew.example",
|
||||||
|
IsVerified: verified,
|
||||||
|
Role: role,
|
||||||
|
}
|
||||||
|
if id > f.users.nextID {
|
||||||
|
f.users.nextID = id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *userRolesFixture) do(t *testing.T, method, target, body string, cookie *http.Cookie) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
req := httptest.NewRequest(method, target, bytes.NewBufferString(body))
|
||||||
|
req.RemoteAddr = rolesClientIP + ":4321"
|
||||||
|
if cookie != nil {
|
||||||
|
req.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
f.router.ServeHTTP(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *userRolesFixture) as(t *testing.T, userID uint32) *http.Cookie {
|
||||||
|
t.Helper()
|
||||||
|
return displayNameCookie(t, f.token, userID, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertNothingInvited(t *testing.T, f *userRolesFixture) {
|
||||||
|
t.Helper()
|
||||||
|
if len(f.invites.invites) != 0 {
|
||||||
|
t.Errorf("expected no invite, got %d", len(f.invites.invites))
|
||||||
|
}
|
||||||
|
if len(f.mail.SentEmails) != 0 {
|
||||||
|
t.Errorf("expected no email, got %d", len(f.mail.SentEmails))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUserRolesHttp(t *testing.T) {
|
||||||
|
t.Run("The first registered user is the owner", func(t *testing.T) {
|
||||||
|
f := newUserRolesFixture(t, 100)
|
||||||
|
|
||||||
|
rec := f.do(t, http.MethodPost, "/v1/auth/register", `{"username": "marta", "password": "hunter2example12", "email": "marta@renew.example"}`, nil)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if len(f.users.users) != 1 {
|
||||||
|
t.Fatalf("expected one user, got %d", len(f.users.users))
|
||||||
|
}
|
||||||
|
for _, stored := range f.users.users {
|
||||||
|
if stored.Username != "marta" || stored.Role != user.RoleOwner {
|
||||||
|
t.Errorf("unexpected user %+v", stored)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A user created by accepting an invite is an admin", func(t *testing.T) {
|
||||||
|
f := newUserRolesFixture(t, 100)
|
||||||
|
f.seedUser(1, "marta", user.RoleOwner, true)
|
||||||
|
pending := pendingInvite(acceptEmail)
|
||||||
|
pending.HashedCode = "hashed:" + acceptCode
|
||||||
|
f.invites.seed(pending)
|
||||||
|
|
||||||
|
rec := f.do(t, http.MethodPost, "/v1/auth/invite/accept", acceptBody(acceptCode, "lea", acceptPassword), nil)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
roles := map[string]user.Role{}
|
||||||
|
for _, stored := range f.users.users {
|
||||||
|
roles[stored.Username] = stored.Role
|
||||||
|
}
|
||||||
|
if roles["lea"] != user.RoleAdmin {
|
||||||
|
t.Errorf("expected lea admin, got %q", roles["lea"])
|
||||||
|
}
|
||||||
|
if roles["marta"] != user.RoleOwner {
|
||||||
|
t.Errorf("expected marta still owner, got %q", roles["marta"])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
username string
|
||||||
|
role user.Role
|
||||||
|
}{{"marta", user.RoleOwner}, {"lea", user.RoleAdmin}} {
|
||||||
|
t.Run("GET /v1/auth/me returns the role of the session user: "+tc.username, func(t *testing.T) {
|
||||||
|
f := newUserRolesFixture(t, 100)
|
||||||
|
f.seedUser(4, tc.username, tc.role, true)
|
||||||
|
|
||||||
|
rec := f.do(t, http.MethodGet, "/v1/auth/me", "", f.as(t, 4))
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
if got := decodedString(t, decodeKeys(t, rec.Body.Bytes()), "role"); got != string(tc.role) {
|
||||||
|
t.Errorf("expected role %q, got %q", tc.role, got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("An unverified owner sees their role on /auth/me", func(t *testing.T) {
|
||||||
|
f := newUserRolesFixture(t, 100)
|
||||||
|
f.seedUser(5, "bob", user.RoleOwner, false)
|
||||||
|
|
||||||
|
rec := f.do(t, http.MethodGet, "/v1/auth/me", "", f.as(t, 5))
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
decoded := decodeKeys(t, rec.Body.Bytes())
|
||||||
|
if decodedString(t, decoded, "role") != "owner" || string(decoded["is_verified"]) != "false" {
|
||||||
|
t.Errorf("unexpected body %s", rec.Body.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("The users list carries email and role on accepted users", func(t *testing.T) {
|
||||||
|
f := newUserRolesFixture(t, 100)
|
||||||
|
day := func(d int) time.Time { return time.Date(2026, 3, d, 9, 0, 0, 0, time.UTC) }
|
||||||
|
f.users.users[1] = user.User{ID: 1, Username: "marta", Email: "marta@renew.example", IsVerified: true, Role: user.RoleOwner, CreatedAt: day(1)}
|
||||||
|
f.users.users[2] = user.User{ID: 2, Username: "jonas", Email: "jonas@renew.example", IsVerified: true, Role: user.RoleAdmin, CreatedAt: day(2)}
|
||||||
|
f.users.users[3] = user.User{ID: 3, Username: "ines", DisplayName: "Inès Duarte", Email: "ines.duarte@renew.example", IsVerified: true, Role: user.RoleAdmin, CreatedAt: day(3)}
|
||||||
|
f.invites.seed(pendingInvite("sam.oliveira@renew.example"))
|
||||||
|
|
||||||
|
rec := f.do(t, http.MethodGet, "/v1/user/", "", f.as(t, 2))
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
items := decodeList(t, rec.Body.Bytes())
|
||||||
|
if len(items) != 4 {
|
||||||
|
t.Fatalf("expected 4 items, got %d", len(items))
|
||||||
|
}
|
||||||
|
wantRoles := map[string][2]string{
|
||||||
|
"marta": {"marta@renew.example", "owner"},
|
||||||
|
"jonas": {"jonas@renew.example", "admin"},
|
||||||
|
"ines": {"ines.duarte@renew.example", "admin"},
|
||||||
|
}
|
||||||
|
for _, item := range items {
|
||||||
|
if decodedString(t, item, "kind") == "invite" {
|
||||||
|
assertExactKeys(t, item, "id", "kind", "email", "status", "created_at")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
assertExactKeys(t, item, "id", "kind", "username", "display_name", "email", "role", "status", "created_at")
|
||||||
|
want := wantRoles[decodedString(t, item, "username")]
|
||||||
|
if decodedString(t, item, "email") != want[0] || decodedString(t, item, "role") != want[1] {
|
||||||
|
t.Errorf("unexpected user item %v", item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, forbidden := range []string{"password", "password_reset_code", "verification_code", "verification_expiration", "password_reset_expiration", "token_version", "code", "hashed_code", "invited_by", "accepted_at"} {
|
||||||
|
for _, item := range items {
|
||||||
|
if _, present := item[forbidden]; present {
|
||||||
|
t.Errorf("item carries forbidden key %q", forbidden)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("The owner can invite", func(t *testing.T) {
|
||||||
|
f := newUserRolesFixture(t, 100)
|
||||||
|
f.seedUser(1, "marta", user.RoleOwner, true)
|
||||||
|
|
||||||
|
rec := f.do(t, http.MethodPost, "/v1/user/invite", rolesInviteBody, f.as(t, 1))
|
||||||
|
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("expected 201, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if len(f.invites.invites) != 1 || len(f.mail.SentEmails) != 1 || f.mail.SentEmails[0].Template != "invitation" {
|
||||||
|
t.Errorf("expected one invite and one invitation email, got %d and %+v", len(f.invites.invites), f.mail.SentEmails)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("An admin cannot invite", func(t *testing.T) {
|
||||||
|
f := newUserRolesFixture(t, 100)
|
||||||
|
f.seedUser(2, "jonas", user.RoleAdmin, true)
|
||||||
|
|
||||||
|
rec := f.do(t, http.MethodPost, "/v1/user/invite", rolesInviteBody, f.as(t, 2))
|
||||||
|
|
||||||
|
if rec.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("expected 403, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
if rec.Body.String() != apperr.OwnerRequiredErrorMessage+"\n" {
|
||||||
|
t.Errorf("unexpected body %q", rec.Body.String())
|
||||||
|
}
|
||||||
|
assertNothingInvited(t, f)
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, body := range []string{`{"email": "not-an-email"}`, `not json`} {
|
||||||
|
t.Run("The owner check comes before validation and the rate limiter: "+body, func(t *testing.T) {
|
||||||
|
f := newUserRolesFixture(t, 100)
|
||||||
|
f.seedUser(2, "jonas", user.RoleAdmin, true)
|
||||||
|
|
||||||
|
rec := f.do(t, http.MethodPost, "/v1/user/invite", body, f.as(t, 2))
|
||||||
|
|
||||||
|
if rec.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("expected 403, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
assertNothingInvited(t, f)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("An admin's refused invites do not use up the rate limit", func(t *testing.T) {
|
||||||
|
f := newUserRolesFixture(t, 2)
|
||||||
|
f.seedUser(2, "jonas", user.RoleAdmin, true)
|
||||||
|
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
rec := f.do(t, http.MethodPost, "/v1/user/invite", rolesInviteBody, f.as(t, 2))
|
||||||
|
if rec.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("request %d: expected 403, got %d", i, rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("The role is read on every request, not from the token", func(t *testing.T) {
|
||||||
|
f := newUserRolesFixture(t, 100)
|
||||||
|
f.seedUser(2, "jonas", user.RoleOwner, true)
|
||||||
|
cookie := f.as(t, 2)
|
||||||
|
stored := f.users.users[2]
|
||||||
|
stored.Role = user.RoleAdmin
|
||||||
|
f.users.users[2] = stored
|
||||||
|
|
||||||
|
rec := f.do(t, http.MethodPost, "/v1/user/invite", rolesInviteBody, cookie)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("expected 403, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("An admin can still list users", func(t *testing.T) {
|
||||||
|
f := newUserRolesFixture(t, 100)
|
||||||
|
f.seedUser(2, "jonas", user.RoleAdmin, true)
|
||||||
|
|
||||||
|
rec := f.do(t, http.MethodGet, "/v1/user/", "", f.as(t, 2))
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A jwt for a since-deleted account is refused with 401 on invite", func(t *testing.T) {
|
||||||
|
f := newUserRolesFixture(t, 100)
|
||||||
|
f.seedUser(1, "marta", user.RoleOwner, true)
|
||||||
|
cookie := f.as(t, 1)
|
||||||
|
delete(f.users.users, 1)
|
||||||
|
|
||||||
|
rec := f.do(t, http.MethodPost, "/v1/user/invite", rolesInviteBody, cookie)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("expected 401, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUserRolesUseCases(t *testing.T) {
|
||||||
|
t.Run("CreateUser returns an owner", func(t *testing.T) {
|
||||||
|
users := newMockUserRepo()
|
||||||
|
uc := useCases.NewCreateUserUseCase(users, &stubHasher{}, newMockMailRepo(), invitePublicURL)
|
||||||
|
|
||||||
|
created, err := uc.CreateUser(useCases.CreateUserCommand{Username: "marta", Password: "hunter2example12", Email: "marta@renew.example"})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if created.Role != user.RoleOwner {
|
||||||
|
t.Errorf("expected owner, got %q", created.Role)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("AcceptInvite returns an admin", func(t *testing.T) {
|
||||||
|
users := newMockUserRepo()
|
||||||
|
invites := newInviteFakeRepo()
|
||||||
|
invites.users = users
|
||||||
|
pending := pendingInvite(acceptEmail)
|
||||||
|
pending.HashedCode = "hashed:" + acceptCode
|
||||||
|
invites.seed(pending)
|
||||||
|
uc := useCases.NewAcceptInviteUseCase(users, invites, &stubHasher{})
|
||||||
|
|
||||||
|
created, err := uc.AcceptInvite(useCases.AcceptInviteCommand{Code: acceptCode, Username: "lea", Password: acceptPassword})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if created.Role != user.RoleAdmin {
|
||||||
|
t.Errorf("expected admin, got %q", created.Role)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequireOwnerRepositoryFailure(t *testing.T) {
|
||||||
|
t.Run("An unexpected repository error is a 500, not a 403", func(t *testing.T) {
|
||||||
|
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||||
|
repo := newMockUserRepo()
|
||||||
|
repo.users[1] = user.User{ID: 1, Username: "marta", IsVerified: true, Role: user.RoleOwner}
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Use(jwtauth.Verifier(token))
|
||||||
|
r.Use(jwtauth.Authenticator(token))
|
||||||
|
r.Use(middleware.RequireOwner(useCases.NewGetUserUseCase(repo)))
|
||||||
|
r.Post("/", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })
|
||||||
|
repo.fail.failNext("Get")
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/", nil)
|
||||||
|
req.AddCookie(displayNameCookie(t, token, 1, 0))
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusInternalServerError {
|
||||||
|
t.Fatalf("expected 500, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBackfillUserRoles(t *testing.T) {
|
||||||
|
openDB := func(t *testing.T) *gorm.DB {
|
||||||
|
t.Helper()
|
||||||
|
db, err := gorm.Open(sqlite.Open("file:roles?mode=memory&cache=private"), &gorm.Config{Logger: logger.Discard})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open: %v", err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(&entity.User{}); err != nil {
|
||||||
|
t.Fatalf("migrate: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if sqlDB, err := db.DB(); err == nil {
|
||||||
|
_ = sqlDB.Close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
rolesByID := func(t *testing.T, db *gorm.DB) map[uint32]string {
|
||||||
|
t.Helper()
|
||||||
|
var rows []entity.User
|
||||||
|
if err := db.Find(&rows).Error; err != nil {
|
||||||
|
t.Fatalf("find: %v", err)
|
||||||
|
}
|
||||||
|
roles := map[uint32]string{}
|
||||||
|
for _, row := range rows {
|
||||||
|
roles[row.ID] = row.Role
|
||||||
|
}
|
||||||
|
return roles
|
||||||
|
}
|
||||||
|
seed := func(t *testing.T, db *gorm.DB, id uint32, role string) {
|
||||||
|
t.Helper()
|
||||||
|
suffix := string(rune('a' + id))
|
||||||
|
row := entity.User{ID: id, Username: "u" + suffix, Password: "x", Email: "e" + suffix, Role: role}
|
||||||
|
if err := db.Create(&row).Error; err != nil {
|
||||||
|
t.Fatalf("seed: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("The lowest id becomes owner and every other user admin", func(t *testing.T) {
|
||||||
|
db := openDB(t)
|
||||||
|
seed(t, db, 3, "")
|
||||||
|
seed(t, db, 5, "")
|
||||||
|
seed(t, db, 9, "")
|
||||||
|
|
||||||
|
if err := persistence.BackfillUserRoles(db); err != nil {
|
||||||
|
t.Fatalf("backfill: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
roles := rolesByID(t, db)
|
||||||
|
if roles[3] != "owner" || roles[5] != "admin" || roles[9] != "admin" {
|
||||||
|
t.Errorf("unexpected roles %v", roles)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("A later start changes nothing", func(t *testing.T) {
|
||||||
|
db := openDB(t)
|
||||||
|
seed(t, db, 2, "admin")
|
||||||
|
seed(t, db, 4, "owner")
|
||||||
|
|
||||||
|
if err := persistence.BackfillUserRoles(db); err != nil {
|
||||||
|
t.Fatalf("backfill: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
roles := rolesByID(t, db)
|
||||||
|
if roles[2] != "admin" || roles[4] != "owner" {
|
||||||
|
t.Errorf("unexpected roles %v", roles)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("An empty database is left alone", func(t *testing.T) {
|
||||||
|
db := openDB(t)
|
||||||
|
|
||||||
|
if err := persistence.BackfillUserRoles(db); err != nil {
|
||||||
|
t.Fatalf("backfill: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -48,9 +48,7 @@ function formatDetailDate(iso: string, relative = false) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const createdLabel = computed(() => formatDetailDate(props.article.created_at))
|
const createdLabel = computed(() => formatDetailDate(props.article.created_at))
|
||||||
const updatedLabel = computed(() =>
|
const updatedLabel = computed(() => formatDetailDate(props.article.updated_at, true))
|
||||||
formatDetailDate(props.article.updated_at, true),
|
|
||||||
)
|
|
||||||
const publicUrl = computed(() => `/v1/article/${props.article.id}`)
|
const publicUrl = computed(() => `/v1/article/${props.article.id}`)
|
||||||
const imagesCount = computed(() => props.article.images.length)
|
const imagesCount = computed(() => props.article.images.length)
|
||||||
const apiNote = computed(() =>
|
const apiNote = computed(() =>
|
||||||
@@ -94,9 +92,7 @@ async function copyUrl() {
|
|||||||
}"
|
}"
|
||||||
>
|
>
|
||||||
<template #header>
|
<template #header>
|
||||||
<h2 class="text-base font-semibold text-highlighted">
|
<h2 class="text-base font-semibold text-highlighted">Details</h2>
|
||||||
Details
|
|
||||||
</h2>
|
|
||||||
</template>
|
</template>
|
||||||
<dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-2 text-sm">
|
<dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-2 text-sm">
|
||||||
<dt class="text-muted">Created</dt>
|
<dt class="text-muted">Created</dt>
|
||||||
@@ -110,9 +106,7 @@ async function copyUrl() {
|
|||||||
</dl>
|
</dl>
|
||||||
<div class="flex flex-col gap-1.5 text-sm">
|
<div class="flex flex-col gap-1.5 text-sm">
|
||||||
<p class="text-muted">Public API URL</p>
|
<p class="text-muted">Public API URL</p>
|
||||||
<div
|
<div class="flex items-center gap-1.5 bg-elevated px-2 py-1.5 font-mono text-xs">
|
||||||
class="flex items-center gap-1.5 bg-elevated px-2 py-1.5 font-mono text-xs"
|
|
||||||
>
|
|
||||||
<span class="flex-1">{{ publicUrl }}</span>
|
<span class="flex-1">{{ publicUrl }}</span>
|
||||||
<UButton
|
<UButton
|
||||||
icon="i-lucide-copy"
|
icon="i-lucide-copy"
|
||||||
@@ -126,20 +120,13 @@ async function copyUrl() {
|
|||||||
</div>
|
</div>
|
||||||
<p class="text-xs/[18px] text-muted">{{ apiNote }}</p>
|
<p class="text-xs/[18px] text-muted">{{ apiNote }}</p>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div class="flex flex-col gap-1 border-t border-default pt-3 text-sm">
|
||||||
class="flex flex-col gap-1 border-t border-default pt-3 text-sm"
|
|
||||||
>
|
|
||||||
<p class="text-muted">Title</p>
|
<p class="text-muted">Title</p>
|
||||||
<p class="text-xs/[18px] text-toned">{{ TITLE_NOTE }}</p>
|
<p class="text-xs/[18px] text-toned">{{ TITLE_NOTE }}</p>
|
||||||
</div>
|
</div>
|
||||||
</UCard>
|
</UCard>
|
||||||
|
|
||||||
<USlideover
|
<USlideover v-model:open="open" side="right" title="Details" class="lg:hidden">
|
||||||
v-model:open="open"
|
|
||||||
side="right"
|
|
||||||
title="Details"
|
|
||||||
class="lg:hidden"
|
|
||||||
>
|
|
||||||
<template #body>
|
<template #body>
|
||||||
<div class="flex flex-col gap-4 text-sm">
|
<div class="flex flex-col gap-4 text-sm">
|
||||||
<dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-2">
|
<dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-2">
|
||||||
@@ -172,9 +159,7 @@ async function copyUrl() {
|
|||||||
</div>
|
</div>
|
||||||
<p class="text-xs/[18px] text-muted">{{ apiNote }}</p>
|
<p class="text-xs/[18px] text-muted">{{ apiNote }}</p>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div class="flex flex-col gap-1 border-t border-default pt-3">
|
||||||
class="flex flex-col gap-1 border-t border-default pt-3"
|
|
||||||
>
|
|
||||||
<p class="text-muted">Title</p>
|
<p class="text-muted">Title</p>
|
||||||
<p class="text-xs/[18px] text-toned">
|
<p class="text-xs/[18px] text-toned">
|
||||||
{{ TITLE_NOTE }}
|
{{ TITLE_NOTE }}
|
||||||
|
|||||||
@@ -234,7 +234,7 @@ defineExpose({
|
|||||||
content-type="html"
|
content-type="html"
|
||||||
:editable="!props.disabled"
|
:editable="!props.disabled"
|
||||||
:ui="{ base: 'article-content' }"
|
:ui="{ base: 'article-content' }"
|
||||||
class="article-editor grid h-full min-h-0 grid-cols-1 grid-rows-[auto_minmax(0,1fr)_auto] lg:grid-cols-[minmax(0,1fr)_17.5rem]"
|
class="article-editor grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)_auto] grid-cols-[minmax(0,1fr)] lg:grid-cols-[minmax(0,1fr)_17.5rem]"
|
||||||
@update:model-value="onUpdate"
|
@update:model-value="onUpdate"
|
||||||
>
|
>
|
||||||
<span class="hidden">{{ captureEditor(editor) }}</span>
|
<span class="hidden">{{ captureEditor(editor) }}</span>
|
||||||
@@ -243,7 +243,7 @@ defineExpose({
|
|||||||
:editor="editor"
|
:editor="editor"
|
||||||
:items="buildItems(editor)"
|
:items="buildItems(editor)"
|
||||||
layout="fixed"
|
layout="fixed"
|
||||||
class="col-span-full row-start-1 border-b border-default bg-default px-6 py-1.5"
|
class="col-span-full row-start-1 min-w-0 overflow-x-auto border-b border-default bg-default px-6 py-1.5 [&>*]:shrink-0"
|
||||||
/>
|
/>
|
||||||
<div class="col-start-1 row-start-3">
|
<div class="col-start-1 row-start-3">
|
||||||
<slot name="footer" />
|
<slot name="footer" />
|
||||||
|
|||||||
@@ -33,26 +33,18 @@ onUnmounted(() => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
const controlSize = computed(() => (belowSm.value ? 'xl' : undefined))
|
const controlSize = computed(() => (belowSm.value ? 'xl' : undefined))
|
||||||
const controlClass = computed(() =>
|
const controlClass = computed(() => (belowSm.value ? '!h-11 !text-base' : '!h-10 !text-base'))
|
||||||
belowSm.value ? '!h-11 !text-base' : '!h-10 !text-base',
|
const inputClass = computed(() => (belowSm.value ? '!h-11 !text-lg' : '!h-10 !text-base'))
|
||||||
)
|
|
||||||
const inputClass = computed(() =>
|
|
||||||
belowSm.value ? '!h-11 !text-lg' : '!h-10 !text-base',
|
|
||||||
)
|
|
||||||
|
|
||||||
const mainClass = computed(() => [
|
const mainClass = computed(() => [
|
||||||
'flex min-h-screen flex-col items-center gap-5',
|
'flex min-h-screen flex-col items-center gap-5',
|
||||||
belowSm.value ? 'bg-default pt-10' : 'bg-muted pt-[12vh]',
|
belowSm.value ? 'bg-default pt-10' : 'bg-muted pt-[12vh]',
|
||||||
])
|
])
|
||||||
|
|
||||||
const cardClass = computed(() =>
|
const cardClass = computed(() => (belowSm.value ? 'w-full' : 'w-full max-w-[400px]'))
|
||||||
belowSm.value ? 'w-full' : 'w-full max-w-[400px]',
|
|
||||||
)
|
|
||||||
|
|
||||||
const cardUi = computed(() => ({
|
const cardUi = computed(() => ({
|
||||||
root: belowSm.value
|
root: belowSm.value ? 'rounded-none ring-0' : 'rounded-none ring-0 border border-default',
|
||||||
? 'rounded-none ring-0'
|
|
||||||
: 'rounded-none ring-0 border border-default',
|
|
||||||
container: belowSm.value
|
container: belowSm.value
|
||||||
? 'flex flex-col gap-6 px-5 pt-2 pb-0 lg:flex'
|
? 'flex flex-col gap-6 px-5 pt-2 pb-0 lg:flex'
|
||||||
: 'flex flex-col gap-6 p-10 sm:p-10 lg:flex',
|
: 'flex flex-col gap-6 p-10 sm:p-10 lg:flex',
|
||||||
|
|||||||
@@ -25,12 +25,8 @@ const error = ref('')
|
|||||||
const cancelButton = ref<{ $el: HTMLElement } | null>(null)
|
const cancelButton = ref<{ $el: HTMLElement } | null>(null)
|
||||||
let settled = false
|
let settled = false
|
||||||
|
|
||||||
const confirmColor = computed(() =>
|
const confirmColor = computed(() => (props.tone === 'danger' ? 'error' : 'primary'))
|
||||||
props.tone === 'danger' ? 'error' : 'primary',
|
const confirmText = computed(() => (pending.value ? props.pendingLabel : props.confirmLabel))
|
||||||
)
|
|
||||||
const confirmText = computed(() =>
|
|
||||||
pending.value ? props.pendingLabel : props.confirmLabel,
|
|
||||||
)
|
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
await nextTick()
|
await nextTick()
|
||||||
@@ -62,10 +58,7 @@ async function onConfirm() {
|
|||||||
await props.action()
|
await props.action()
|
||||||
settle(true)
|
settle(true)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error.value =
|
error.value = err instanceof Error ? err.message : 'Something went wrong. Try again.'
|
||||||
err instanceof Error
|
|
||||||
? err.message
|
|
||||||
: 'Something went wrong. Try again.'
|
|
||||||
} finally {
|
} finally {
|
||||||
pending.value = false
|
pending.value = false
|
||||||
}
|
}
|
||||||
@@ -92,35 +85,34 @@ function onCancel() {
|
|||||||
}"
|
}"
|
||||||
:ui="{
|
:ui="{
|
||||||
content:
|
content:
|
||||||
'divide-y-0 shadow-(--shadow-modal) ring-0 sm:top-[220px] sm:max-w-110 sm:translate-y-0 max-sm:!inset-x-4 max-sm:!top-auto max-sm:!bottom-4 max-sm:!left-4 max-sm:!w-auto max-sm:!max-w-none max-sm:!translate-x-0 max-sm:!translate-y-0',
|
'divide-y-0 shadow-(--shadow-modal) ring-0 sm:top-35 sm:max-w-115 sm:translate-y-0 max-sm:!inset-x-4 max-sm:!top-auto max-sm:!bottom-4 max-sm:!left-4 max-sm:!w-auto max-sm:!max-w-none max-sm:!translate-x-0 max-sm:!translate-y-0',
|
||||||
header: 'min-h-0 px-6 pt-6 pb-0 sm:px-6 max-sm:px-5 max-sm:pt-5',
|
header: 'min-h-0 px-6 pt-5 pb-0 sm:px-6',
|
||||||
title: 'text-lg max-sm:text-[1.0625rem]/6',
|
title: 'text-lg/6 font-semibold',
|
||||||
description:
|
description: 'mt-1 text-sm text-muted text-pretty',
|
||||||
'mt-2 text-base text-toned max-sm:text-[0.9375rem]/[23px]',
|
body: 'px-6 pt-5 pb-0 sm:px-6 sm:pt-5 sm:pb-0',
|
||||||
body: 'px-6 pt-4 pb-0 sm:px-6 sm:pt-4 sm:pb-0 max-sm:px-5',
|
footer: 'px-6 py-5 sm:px-6',
|
||||||
footer: 'p-6 sm:px-6 max-sm:p-5',
|
|
||||||
}"
|
}"
|
||||||
>
|
>
|
||||||
<template v-if="error" #body>
|
<template #body>
|
||||||
<UAlert
|
<UAlert
|
||||||
|
v-if="error"
|
||||||
color="error"
|
color="error"
|
||||||
icon="i-lucide-circle-x"
|
icon="i-lucide-circle-x"
|
||||||
:description="error"
|
:description="error"
|
||||||
variant="soft"
|
variant="soft"
|
||||||
:close="false"
|
:close="false"
|
||||||
role="alert"
|
role="alert"
|
||||||
|
:ui="{ root: 'gap-2 px-3 py-2.5', description: 'text-sm text-toned' }"
|
||||||
/>
|
/>
|
||||||
</template>
|
</template>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<div
|
<div class="flex w-full flex-col-reverse gap-2 sm:flex-row sm:justify-end">
|
||||||
class="flex w-full flex-col-reverse gap-2 sm:flex-row sm:justify-end"
|
|
||||||
>
|
|
||||||
<UButton
|
<UButton
|
||||||
ref="cancelButton"
|
ref="cancelButton"
|
||||||
color="neutral"
|
color="neutral"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
block
|
block
|
||||||
class="h-11 justify-center text-[0.9375rem] text-highlighted disabled:text-dimmed disabled:opacity-100 sm:h-8 sm:w-auto sm:px-3 sm:text-sm"
|
class="h-11 justify-center text-sm text-highlighted disabled:text-dimmed disabled:opacity-100 sm:h-8 sm:w-auto sm:px-3"
|
||||||
:disabled="pending"
|
:disabled="pending"
|
||||||
@click="onCancel"
|
@click="onCancel"
|
||||||
>
|
>
|
||||||
@@ -131,7 +123,7 @@ function onCancel() {
|
|||||||
:loading="pending"
|
:loading="pending"
|
||||||
:disabled="pending"
|
:disabled="pending"
|
||||||
block
|
block
|
||||||
class="h-11 justify-center text-[0.9375rem] sm:h-8 sm:w-auto sm:px-3 sm:text-sm"
|
class="h-11 justify-center text-sm sm:h-8 sm:w-auto sm:px-3"
|
||||||
@click="onConfirm"
|
@click="onConfirm"
|
||||||
>
|
>
|
||||||
{{ confirmText }}
|
{{ confirmText }}
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ const navItems = computed(() =>
|
|||||||
{ label: 'Articles', to: '/article', icon: 'i-lucide-file-text' },
|
{ label: 'Articles', to: '/article', icon: 'i-lucide-file-text' },
|
||||||
{ label: 'Users', to: '/users', icon: 'i-lucide-users' },
|
{ label: 'Users', to: '/users', icon: 'i-lucide-users' },
|
||||||
{ label: 'Integration', to: '/integration', icon: 'i-lucide-plug' },
|
{ label: 'Integration', to: '/integration', icon: 'i-lucide-plug' },
|
||||||
|
{ label: 'Settings', to: '/settings', icon: 'i-lucide-settings' },
|
||||||
].map((item) => ({
|
].map((item) => ({
|
||||||
...item,
|
...item,
|
||||||
active: route.path === item.to || route.path.startsWith(`${item.to}/`),
|
active: route.path === item.to || route.path.startsWith(`${item.to}/`),
|
||||||
|
|||||||
@@ -44,15 +44,8 @@ const items = computed(() =>
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<ul class="flex flex-col gap-1.5">
|
<ul class="flex flex-col gap-1.5">
|
||||||
<li
|
<li v-for="item in items" :key="item.label" class="flex items-center gap-2 text-xs/[18px]">
|
||||||
v-for="item in items"
|
<UIcon :name="item.icon" :class="['size-3.5 shrink-0', item.iconClass]" />
|
||||||
:key="item.label"
|
|
||||||
class="flex items-center gap-2 text-xs/[18px]"
|
|
||||||
>
|
|
||||||
<UIcon
|
|
||||||
:name="item.icon"
|
|
||||||
:class="['size-3.5 shrink-0', item.iconClass]"
|
|
||||||
/>
|
|
||||||
<span :class="item.textClass">{{ item.label }}</span>
|
<span :class="item.textClass">{{ item.label }}</span>
|
||||||
<span class="sr-only">{{ item.met ? 'met' : 'not met' }}</span>
|
<span class="sr-only">{{ item.met ? 'met' : 'not met' }}</span>
|
||||||
</li>
|
</li>
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
role: 'owner' | 'admin'
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const roleClass = computed(() =>
|
||||||
|
props.role === 'owner'
|
||||||
|
? 'border border-primary bg-primary text-(--ui-bg)'
|
||||||
|
: 'border border-accented bg-transparent text-toned',
|
||||||
|
)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<UBadge
|
||||||
|
color="neutral"
|
||||||
|
variant="soft"
|
||||||
|
:class="roleClass"
|
||||||
|
:ui="{ base: 'h-5 rounded-none px-1.75 py-0 font-mono text-[0.6875rem] font-medium' }"
|
||||||
|
>
|
||||||
|
{{ role }}
|
||||||
|
</UBadge>
|
||||||
|
</template>
|
||||||
@@ -8,7 +8,8 @@ const props = defineProps<{
|
|||||||
|
|
||||||
defineEmits<{ retry: [] }>()
|
defineEmits<{ retry: [] }>()
|
||||||
|
|
||||||
const HOUR_MS = 60 * 60 * 1000
|
const MINUTE_MS = 60 * 1000
|
||||||
|
const HOUR_MS = 60 * MINUTE_MS
|
||||||
const TICK_MS = 15000
|
const TICK_MS = 15000
|
||||||
|
|
||||||
const now = ref(Date.now())
|
const now = ref(Date.now())
|
||||||
@@ -32,6 +33,18 @@ function formatClock(date: Date) {
|
|||||||
return `${hours}:${minutes}`
|
return `${hours}:${minutes}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatElapsed(diffMs: number) {
|
||||||
|
const minutes = Math.floor(diffMs / MINUTE_MS)
|
||||||
|
if (minutes < 60) {
|
||||||
|
return `${minutes} min`
|
||||||
|
}
|
||||||
|
const hours = Math.floor(minutes / 60)
|
||||||
|
if (hours < 24) {
|
||||||
|
return `${hours} h`
|
||||||
|
}
|
||||||
|
return `${Math.floor(hours / 24)} d`
|
||||||
|
}
|
||||||
|
|
||||||
const savedText = computed(() => {
|
const savedText = computed(() => {
|
||||||
if (!props.savedAt) {
|
if (!props.savedAt) {
|
||||||
return 'Saved'
|
return 'Saved'
|
||||||
@@ -40,8 +53,7 @@ const savedText = computed(() => {
|
|||||||
if (diffMs < HOUR_MS) {
|
if (diffMs < HOUR_MS) {
|
||||||
return `Saved at ${formatClock(props.savedAt)}`
|
return `Saved at ${formatClock(props.savedAt)}`
|
||||||
}
|
}
|
||||||
const minutes = Math.floor(diffMs / 60000)
|
return `Saved ${formatElapsed(diffMs)} ago`
|
||||||
return minutes === 1 ? 'Saved 1 min ago' : `Saved ${minutes} min ago`
|
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -64,10 +76,7 @@ const savedText = computed(() => {
|
|||||||
<span>Unsaved changes</span>
|
<span>Unsaved changes</span>
|
||||||
</template>
|
</template>
|
||||||
<template v-else-if="state === 'saving'">
|
<template v-else-if="state === 'saving'">
|
||||||
<UIcon
|
<UIcon name="i-lucide-loader-circle" class="size-3.5 animate-spin" />
|
||||||
name="i-lucide-loader-circle"
|
|
||||||
class="size-3.5 animate-spin"
|
|
||||||
/>
|
|
||||||
<span>Saving…</span>
|
<span>Saving…</span>
|
||||||
</template>
|
</template>
|
||||||
<template v-else-if="state === 'error'">
|
<template v-else-if="state === 'error'">
|
||||||
|
|||||||
@@ -1,14 +1,29 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import InviteStatusBadge from '@/components/InviteStatusBadge.vue'
|
import InviteStatusBadge from '@/components/InviteStatusBadge.vue'
|
||||||
import UserNameCell from '@/components/UserNameCell.vue'
|
import RoleBadge from '@/components/RoleBadge.vue'
|
||||||
|
import UserRowAction from '@/components/UserRowAction.vue'
|
||||||
|
import UserEmailCell from '@/components/UserEmailCell.vue'
|
||||||
import { formatCreatedDate } from '@/lib/relativeDate'
|
import { formatCreatedDate } from '@/lib/relativeDate'
|
||||||
import { USER_SKELETON_ROWS, userRowKey, type UserListItem } from '@/composables/useUsers'
|
import {
|
||||||
|
USER_SKELETON_ROWS,
|
||||||
|
userDisplayName,
|
||||||
|
userRole,
|
||||||
|
userRowKey,
|
||||||
|
type UserListItem,
|
||||||
|
} from '@/composables/useUsers'
|
||||||
|
|
||||||
defineProps<{
|
defineProps<{
|
||||||
items: UserListItem[]
|
items: UserListItem[]
|
||||||
loading: boolean
|
loading: boolean
|
||||||
sessionUserId?: number
|
sessionUserId?: number
|
||||||
highlightedKey?: string
|
highlightedKey?: string
|
||||||
|
canManage?: boolean
|
||||||
|
busyKeys?: string[]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
cancel: [item: UserListItem]
|
||||||
|
renew: [item: UserListItem]
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
function rowKey(item: UserListItem) {
|
function rowKey(item: UserListItem) {
|
||||||
@@ -36,15 +51,28 @@ function rowKey(item: UserListItem) {
|
|||||||
class="flex min-h-17 flex-col justify-center gap-1.5 border-b border-default px-4 py-3"
|
class="flex min-h-17 flex-col justify-center gap-1.5 border-b border-default px-4 py-3"
|
||||||
:class="{ 'bg-elevated': rowKey(item) === highlightedKey }"
|
:class="{ 'bg-elevated': rowKey(item) === highlightedKey }"
|
||||||
>
|
>
|
||||||
<UserNameCell
|
<UserEmailCell
|
||||||
:item="item"
|
:email="item.email"
|
||||||
:is-you="item.kind === 'user' && item.id === sessionUserId"
|
:is-you="item.kind === 'user' && item.id === sessionUserId"
|
||||||
large
|
large
|
||||||
/>
|
/>
|
||||||
<div class="flex items-center gap-2.5 text-xs text-muted">
|
<span v-if="userDisplayName(item)" class="text-toned">{{
|
||||||
|
userDisplayName(item)
|
||||||
|
}}</span>
|
||||||
|
<div class="flex items-center gap-2 text-xs text-muted">
|
||||||
|
<RoleBadge :role="userRole(item)" />
|
||||||
<InviteStatusBadge :status="item.status" size="sm" />
|
<InviteStatusBadge :status="item.status" size="sm" />
|
||||||
<span>Created {{ formatCreatedDate(item.created_at) }}</span>
|
<span>Created {{ formatCreatedDate(item.created_at) }}</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div v-if="canManage && item.kind === 'invite'" class="flex pt-1">
|
||||||
|
<UserRowAction
|
||||||
|
:item="item"
|
||||||
|
large
|
||||||
|
:busy="busyKeys?.includes(rowKey(item))"
|
||||||
|
@cancel="emit('cancel', item)"
|
||||||
|
@renew="emit('renew', item)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</li>
|
</li>
|
||||||
</template>
|
</template>
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
defineProps<{
|
||||||
|
email: string
|
||||||
|
isYou: boolean
|
||||||
|
large?: boolean
|
||||||
|
}>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<span class="flex min-w-0 items-center gap-2">
|
||||||
|
<span
|
||||||
|
class="truncate font-medium text-highlighted"
|
||||||
|
:class="large ? 'text-[0.9375rem]/[21px]' : ''"
|
||||||
|
>{{ email }}</span
|
||||||
|
>
|
||||||
|
<span v-if="isYou" class="shrink-0 font-mono text-[0.6875rem] font-medium text-muted"
|
||||||
|
>you</span
|
||||||
|
>
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
@@ -4,6 +4,7 @@ import { useMediaQuery } from '@vueuse/core'
|
|||||||
import { colorModeOptions, useAccountMenu } from '@/composables/useAccountMenu'
|
import { colorModeOptions, useAccountMenu } from '@/composables/useAccountMenu'
|
||||||
|
|
||||||
const DESKTOP_QUERY = '(min-width: 64rem)'
|
const DESKTOP_QUERY = '(min-width: 64rem)'
|
||||||
|
const ITEM_CLASS = 'h-8 items-center py-0'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
username: string
|
username: string
|
||||||
@@ -60,7 +61,7 @@ const items = computed(() => [
|
|||||||
{
|
{
|
||||||
label: 'Profile',
|
label: 'Profile',
|
||||||
icon: 'i-lucide-circle-user',
|
icon: 'i-lucide-circle-user',
|
||||||
class: onProfile.value ? 'bg-elevated' : undefined,
|
class: onProfile.value ? `${ITEM_CLASS} bg-elevated` : ITEM_CLASS,
|
||||||
onSelect: goToProfile,
|
onSelect: goToProfile,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -68,6 +69,8 @@ const items = computed(() => [
|
|||||||
type: 'checkbox' as const,
|
type: 'checkbox' as const,
|
||||||
label: option.label,
|
label: option.label,
|
||||||
checked: colorMode.preference === option.value,
|
checked: colorMode.preference === option.value,
|
||||||
|
class: ITEM_CLASS,
|
||||||
|
onSelect: (event: Event) => event.preventDefault(),
|
||||||
onUpdateChecked: (checked: boolean) => {
|
onUpdateChecked: (checked: boolean) => {
|
||||||
if (checked) {
|
if (checked) {
|
||||||
colorMode.preference = option.value
|
colorMode.preference = option.value
|
||||||
@@ -78,6 +81,7 @@ const items = computed(() => [
|
|||||||
{
|
{
|
||||||
label: 'Log out',
|
label: 'Log out',
|
||||||
icon: 'i-lucide-log-out',
|
icon: 'i-lucide-log-out',
|
||||||
|
class: ITEM_CLASS,
|
||||||
onSelect: () => emit('logout'),
|
onSelect: () => emit('logout'),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { computed } from 'vue'
|
|
||||||
import type { UserListItem } from '@/composables/useUsers'
|
|
||||||
|
|
||||||
const props = defineProps<{
|
|
||||||
item: UserListItem
|
|
||||||
isYou: boolean
|
|
||||||
large?: boolean
|
|
||||||
}>()
|
|
||||||
|
|
||||||
const primary = computed(() => {
|
|
||||||
if (props.item.kind === 'invite') {
|
|
||||||
return props.item.email
|
|
||||||
}
|
|
||||||
return props.item.display_name || props.item.username
|
|
||||||
})
|
|
||||||
|
|
||||||
const secondary = computed(() =>
|
|
||||||
props.item.kind === 'user' && props.item.display_name ? props.item.username : '',
|
|
||||||
)
|
|
||||||
|
|
||||||
const primaryClass = computed(() => [
|
|
||||||
props.item.kind === 'invite' ? 'text-toned' : 'font-medium text-highlighted',
|
|
||||||
props.large ? 'text-[0.9375rem]/[21px]' : '',
|
|
||||||
])
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<span class="flex min-w-0 items-center gap-2">
|
|
||||||
<span class="truncate" :class="primaryClass">{{ primary }}</span>
|
|
||||||
<span v-if="secondary" class="shrink-0 text-muted">{{ secondary }}</span>
|
|
||||||
<span v-if="isYou" class="shrink-0 font-mono text-[0.6875rem] font-medium text-muted"
|
|
||||||
>you</span
|
|
||||||
>
|
|
||||||
</span>
|
|
||||||
</template>
|
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import type { UserListItem } from '@/composables/useUsers'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
item: UserListItem
|
||||||
|
busy?: boolean
|
||||||
|
large?: boolean
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const emit = defineEmits<{ cancel: []; renew: [] }>()
|
||||||
|
|
||||||
|
const actions = {
|
||||||
|
pending: {
|
||||||
|
label: 'Cancel invite',
|
||||||
|
icon: 'i-lucide-user-x',
|
||||||
|
textClass: 'text-error',
|
||||||
|
event: 'cancel',
|
||||||
|
},
|
||||||
|
expired: {
|
||||||
|
label: 'Renew invite',
|
||||||
|
icon: 'i-lucide-refresh-cw',
|
||||||
|
textClass: 'text-highlighted',
|
||||||
|
event: 'renew',
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
const action = computed(() => {
|
||||||
|
return props.item.kind === 'invite' ? actions[props.item.status] : null
|
||||||
|
})
|
||||||
|
|
||||||
|
const label = computed(() => (props.busy ? 'Renewing…' : (action.value?.label ?? '')))
|
||||||
|
const icon = computed(() => (props.busy ? 'i-lucide-loader-circle' : action.value?.icon))
|
||||||
|
const sizeClass = computed(() =>
|
||||||
|
props.large ? 'h-11 gap-2 px-3.5 text-sm' : 'h-7 gap-1.5 px-2.25 text-xs',
|
||||||
|
)
|
||||||
|
const iconClass = computed(() => (props.large ? 'size-3.5' : 'size-3.25'))
|
||||||
|
|
||||||
|
function onClick() {
|
||||||
|
if (props.busy || !action.value) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (action.value.event === 'cancel') {
|
||||||
|
emit('cancel')
|
||||||
|
} else {
|
||||||
|
emit('renew')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<UButton
|
||||||
|
v-if="action"
|
||||||
|
color="neutral"
|
||||||
|
variant="outline"
|
||||||
|
size="xs"
|
||||||
|
:icon="icon"
|
||||||
|
:disabled="busy"
|
||||||
|
class="shrink-0 border border-accented bg-default font-medium whitespace-nowrap ring-0"
|
||||||
|
:class="[sizeClass, action.textClass, { 'opacity-50': busy }]"
|
||||||
|
:ui="{ leadingIcon: iconClass }"
|
||||||
|
@click="onClick"
|
||||||
|
>
|
||||||
|
{{ label }}
|
||||||
|
</UButton>
|
||||||
|
</template>
|
||||||
@@ -1,16 +1,32 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import InviteStatusBadge from '@/components/InviteStatusBadge.vue'
|
import InviteStatusBadge from '@/components/InviteStatusBadge.vue'
|
||||||
import UserNameCell from '@/components/UserNameCell.vue'
|
import RoleBadge from '@/components/RoleBadge.vue'
|
||||||
|
import UserRowAction from '@/components/UserRowAction.vue'
|
||||||
|
import UserEmailCell from '@/components/UserEmailCell.vue'
|
||||||
import { formatCreatedDate } from '@/lib/relativeDate'
|
import { formatCreatedDate } from '@/lib/relativeDate'
|
||||||
import { USER_SKELETON_ROWS, userRowKey, type UserListItem } from '@/composables/useUsers'
|
import {
|
||||||
|
USER_SKELETON_ROWS,
|
||||||
|
userDisplayName,
|
||||||
|
userRole,
|
||||||
|
userRowKey,
|
||||||
|
type UserListItem,
|
||||||
|
} from '@/composables/useUsers'
|
||||||
|
|
||||||
const ROW_GRID = 'grid grid-cols-[minmax(0,1fr)_160px_160px] items-center px-3'
|
const ROW_GRID =
|
||||||
|
'grid grid-cols-[minmax(0,1.3fr)_minmax(0,1fr)_84px_120px_110px_150px] items-center gap-3 px-3'
|
||||||
|
|
||||||
defineProps<{
|
defineProps<{
|
||||||
items: UserListItem[]
|
items: UserListItem[]
|
||||||
loading: boolean
|
loading: boolean
|
||||||
sessionUserId?: number
|
sessionUserId?: number
|
||||||
highlightedKey?: string
|
highlightedKey?: string
|
||||||
|
canManage?: boolean
|
||||||
|
busyKeys?: string[]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
cancel: [item: UserListItem]
|
||||||
|
renew: [item: UserListItem]
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
function rowKey(item: UserListItem) {
|
function rowKey(item: UserListItem) {
|
||||||
@@ -21,12 +37,15 @@ function rowKey(item: UserListItem) {
|
|||||||
<template>
|
<template>
|
||||||
<div class="border border-default bg-default" :aria-busy="loading ? 'true' : undefined">
|
<div class="border border-default bg-default" :aria-busy="loading ? 'true' : undefined">
|
||||||
<div :class="ROW_GRID" class="h-9 bg-elevated font-medium text-muted">
|
<div :class="ROW_GRID" class="h-9 bg-elevated font-medium text-muted">
|
||||||
<span>Username</span>
|
<span>Email</span>
|
||||||
|
<span>Display name</span>
|
||||||
|
<span>Role</span>
|
||||||
<span>Invite status</span>
|
<span>Invite status</span>
|
||||||
<span class="flex items-center gap-1 text-highlighted">
|
<span class="flex items-center gap-1 text-highlighted">
|
||||||
Created
|
Created
|
||||||
<UIcon name="i-lucide-arrow-down" class="size-3 shrink-0" />
|
<UIcon name="i-lucide-arrow-down" class="size-3 shrink-0" />
|
||||||
</span>
|
</span>
|
||||||
|
<span></span>
|
||||||
</div>
|
</div>
|
||||||
<template v-if="loading">
|
<template v-if="loading">
|
||||||
<span role="status" class="sr-only">Loading users</span>
|
<span role="status" class="sr-only">Loading users</span>
|
||||||
@@ -34,9 +53,11 @@ function rowKey(item: UserListItem) {
|
|||||||
v-for="n in USER_SKELETON_ROWS"
|
v-for="n in USER_SKELETON_ROWS"
|
||||||
:key="n"
|
:key="n"
|
||||||
:class="ROW_GRID"
|
:class="ROW_GRID"
|
||||||
class="h-11 border-t border-default"
|
class="h-12 border-t border-default"
|
||||||
>
|
>
|
||||||
<USkeleton class="h-3 w-[30%] rounded-none bg-accented" />
|
<USkeleton class="h-3 w-[60%] rounded-none bg-accented" />
|
||||||
|
<USkeleton class="h-3 w-[50%] rounded-none bg-accented" />
|
||||||
|
<USkeleton class="h-5 w-13 rounded-none bg-accented" />
|
||||||
<USkeleton class="h-5 w-19 rounded-none bg-accented" />
|
<USkeleton class="h-5 w-19 rounded-none bg-accented" />
|
||||||
<USkeleton class="h-3 w-20 rounded-none bg-accented" />
|
<USkeleton class="h-3 w-20 rounded-none bg-accented" />
|
||||||
</div>
|
</div>
|
||||||
@@ -47,15 +68,29 @@ function rowKey(item: UserListItem) {
|
|||||||
:key="rowKey(item)"
|
:key="rowKey(item)"
|
||||||
data-testid="user-row"
|
data-testid="user-row"
|
||||||
:class="[ROW_GRID, { 'bg-elevated': rowKey(item) === highlightedKey }]"
|
:class="[ROW_GRID, { 'bg-elevated': rowKey(item) === highlightedKey }]"
|
||||||
class="h-11 border-t border-default"
|
class="h-12 border-t border-default"
|
||||||
>
|
>
|
||||||
<UserNameCell
|
<UserEmailCell
|
||||||
:item="item"
|
:email="item.email"
|
||||||
:is-you="item.kind === 'user' && item.id === sessionUserId"
|
:is-you="item.kind === 'user' && item.id === sessionUserId"
|
||||||
class="pr-3"
|
|
||||||
/>
|
/>
|
||||||
|
<span
|
||||||
|
class="truncate"
|
||||||
|
:class="userDisplayName(item) ? 'text-highlighted' : 'text-muted'"
|
||||||
|
>{{ userDisplayName(item) || '—' }}</span
|
||||||
|
>
|
||||||
|
<span><RoleBadge :role="userRole(item)" /></span>
|
||||||
<span><InviteStatusBadge :status="item.status" /></span>
|
<span><InviteStatusBadge :status="item.status" /></span>
|
||||||
<span class="text-muted">{{ formatCreatedDate(item.created_at) }}</span>
|
<span class="text-muted">{{ formatCreatedDate(item.created_at) }}</span>
|
||||||
|
<span class="flex justify-end">
|
||||||
|
<UserRowAction
|
||||||
|
v-if="canManage"
|
||||||
|
:item="item"
|
||||||
|
:busy="busyKeys?.includes(rowKey(item))"
|
||||||
|
@cancel="emit('cancel', item)"
|
||||||
|
@renew="emit('renew', item)"
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { createPinia, setActivePinia } from 'pinia'
|
|||||||
import uiPlugin from '@nuxt/ui/vue-plugin'
|
import uiPlugin from '@nuxt/ui/vue-plugin'
|
||||||
import router from '@/router'
|
import router from '@/router'
|
||||||
import { useApi } from '@/composables/useApi'
|
import { useApi } from '@/composables/useApi'
|
||||||
|
import { useColorMode } from '@/composables/useColorMode'
|
||||||
import DashboardShell from '../DashboardShell.vue'
|
import DashboardShell from '../DashboardShell.vue'
|
||||||
import { DESKTOP_WIDTH, MOBILE_WIDTH, setViewportWidth } from './viewport'
|
import { DESKTOP_WIDTH, MOBILE_WIDTH, setViewportWidth } from './viewport'
|
||||||
|
|
||||||
@@ -57,14 +58,14 @@ afterEach(async () => {
|
|||||||
document.body.innerHTML = ''
|
document.body.innerHTML = ''
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('DashboardShell renders the four navigation destinations', () => {
|
describe('DashboardShell renders the five navigation destinations', () => {
|
||||||
it('lists Home, Articles, Users and Integration in order, with only Articles carrying aria-current', async () => {
|
it('lists Home, Articles, Users, Integration and Settings in order, with only Articles carrying aria-current', async () => {
|
||||||
const wrapper = await mountShell('/article')
|
const wrapper = await mountShell('/article')
|
||||||
|
|
||||||
const hrefs = wrapper
|
const hrefs = wrapper
|
||||||
.findAll('nav[aria-label="Main"] a')
|
.findAll('nav[aria-label="Main"] a')
|
||||||
.map((link) => link.attributes('href'))
|
.map((link) => link.attributes('href'))
|
||||||
expect(hrefs).toEqual(['/home', '/article', '/users', '/integration'])
|
expect(hrefs).toEqual(['/home', '/article', '/users', '/integration', '/settings'])
|
||||||
|
|
||||||
const home = wrapper.find('a[href="/home"]')
|
const home = wrapper.find('a[href="/home"]')
|
||||||
const articles = wrapper.find('a[href="/article"]')
|
const articles = wrapper.find('a[href="/article"]')
|
||||||
@@ -77,6 +78,27 @@ describe('DashboardShell renders the four navigation destinations', () => {
|
|||||||
expect(integration.attributes('aria-current')).toBeUndefined()
|
expect(integration.attributes('aria-current')).toBeUndefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('lists the same five destinations in the mobile drawer and Settings current', async () => {
|
||||||
|
await mountShell('/settings', { width: MOBILE_WIDTH })
|
||||||
|
|
||||||
|
const toggle = document.body.querySelector('[data-slot="toggle"]') as HTMLButtonElement
|
||||||
|
toggle.click()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const links = Array.from(
|
||||||
|
document.body.querySelectorAll('[role="dialog"] nav[aria-label="Main"] a'),
|
||||||
|
)
|
||||||
|
expect(links.map((link) => link.getAttribute('href'))).toEqual([
|
||||||
|
'/home',
|
||||||
|
'/article',
|
||||||
|
'/users',
|
||||||
|
'/integration',
|
||||||
|
'/settings',
|
||||||
|
])
|
||||||
|
expect(links[4].querySelector('[class*="lucide"], svg')).not.toBeNull()
|
||||||
|
expect(links[4].getAttribute('aria-current')).toBe('page')
|
||||||
|
})
|
||||||
|
|
||||||
it('marks Users with aria-current on /users', async () => {
|
it('marks Users with aria-current on /users', async () => {
|
||||||
const wrapper = await mountShell('/users')
|
const wrapper = await mountShell('/users')
|
||||||
|
|
||||||
@@ -210,11 +232,11 @@ describe('The account chip shows the display name and no item is current on /pro
|
|||||||
expect(trigger?.getAttribute('aria-label')).toBe('Marta Alves — account menu')
|
expect(trigger?.getAttribute('aria-label')).toBe('Marta Alves — account menu')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('marks none of the four navigation items current on /profile', async () => {
|
it('marks none of the five navigation items current on /profile', async () => {
|
||||||
const wrapper = await mountShell('/profile')
|
const wrapper = await mountShell('/profile')
|
||||||
|
|
||||||
const links = wrapper.findAll('nav[aria-label="Main"] a')
|
const links = wrapper.findAll('nav[aria-label="Main"] a')
|
||||||
expect(links).toHaveLength(4)
|
expect(links).toHaveLength(5)
|
||||||
links.forEach((link) => expect(link.attributes('aria-current')).toBeUndefined())
|
links.forEach((link) => expect(link.attributes('aria-current')).toBeUndefined())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -272,6 +294,29 @@ describe('Account menu: opened from the drawer on mobile', () => {
|
|||||||
expect(document.body.querySelector('[role="menu"]')).toBeNull()
|
expect(document.body.querySelector('[role="menu"]')).toBeNull()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('applies a theme choice and closes the sheet', async () => {
|
||||||
|
const colorMode = useColorMode()
|
||||||
|
colorMode.preference = 'system'
|
||||||
|
await mountShell('/home', { width: MOBILE_WIDTH })
|
||||||
|
;(document.body.querySelector('[data-slot="toggle"]') as HTMLButtonElement).click()
|
||||||
|
await flushPromises()
|
||||||
|
;(
|
||||||
|
document.body.querySelector(
|
||||||
|
'[role="dialog"] button[aria-haspopup]',
|
||||||
|
) as HTMLButtonElement
|
||||||
|
).click()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const dark = Array.from(
|
||||||
|
document.body.querySelectorAll<HTMLElement>('[role="menu"] [role="menuitemcheckbox"]'),
|
||||||
|
).find((item) => item.textContent?.trim() === 'Dark')!
|
||||||
|
dark.click()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(colorMode.preference).toBe('dark')
|
||||||
|
expect(document.body.querySelector('[role="menu"]')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
it('logs out from the sheet', async () => {
|
it('logs out from the sheet', async () => {
|
||||||
await mountShell('/home', { width: MOBILE_WIDTH })
|
await mountShell('/home', { width: MOBILE_WIDTH })
|
||||||
;(document.body.querySelector('[data-slot="toggle"]') as HTMLButtonElement).click()
|
;(document.body.querySelector('[data-slot="toggle"]') as HTMLButtonElement).click()
|
||||||
|
|||||||
@@ -24,9 +24,15 @@ describe('Saved within the hour', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('Saved over an hour ago', () => {
|
describe('Saved over an hour ago', () => {
|
||||||
it('reads "Saved n min ago"', () => {
|
it.each([
|
||||||
|
['2026-09-26T12:02:00Z', 'Saved 1 h ago'],
|
||||||
|
['2026-09-26T12:32:00Z', 'Saved 1 h ago'],
|
||||||
|
['2026-09-26T23:02:00Z', 'Saved 12 h ago'],
|
||||||
|
['2026-09-27T11:02:00Z', 'Saved 1 d ago'],
|
||||||
|
['2026-09-29T15:00:00Z', 'Saved 3 d ago'],
|
||||||
|
])('at %s reads "%s"', (now, expected) => {
|
||||||
vi.useFakeTimers()
|
vi.useFakeTimers()
|
||||||
vi.setSystemTime(new Date('2026-09-26T12:32:00Z'))
|
vi.setSystemTime(new Date(now))
|
||||||
const wrapper = mount(SaveStatus, {
|
const wrapper = mount(SaveStatus, {
|
||||||
props: {
|
props: {
|
||||||
state: 'saved',
|
state: 'saved',
|
||||||
@@ -35,7 +41,7 @@ describe('Saved over an hour ago', () => {
|
|||||||
global: { plugins: [uiPlugin] },
|
global: { plugins: [uiPlugin] },
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(wrapper.text()).toContain('Saved 90 min ago')
|
expect(wrapper.text()).toContain(expected)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -236,7 +236,7 @@ describe('Menu items', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('Theme choice stays in the menu', () => {
|
describe('Theme choice stays in the menu', () => {
|
||||||
it('checks the current preference, sets Dark, closes, and shows Dark checked on reopening', async () => {
|
it('checks the current preference, sets Dark at once and keeps the menu open', async () => {
|
||||||
const colorMode = useColorMode()
|
const colorMode = useColorMode()
|
||||||
colorMode.preference = 'system'
|
colorMode.preference = 'system'
|
||||||
await mountMenu()
|
await mountMenu()
|
||||||
@@ -248,15 +248,24 @@ describe('Theme choice stays in the menu', () => {
|
|||||||
await flushPromises()
|
await flushPromises()
|
||||||
|
|
||||||
expect(colorMode.preference).toBe('dark')
|
expect(colorMode.preference).toBe('dark')
|
||||||
expect(menu()).toBeNull()
|
expect(menu()).not.toBeNull()
|
||||||
|
|
||||||
await openMenu()
|
|
||||||
|
|
||||||
expect(findItem('Dark').getAttribute('aria-checked')).toBe('true')
|
expect(findItem('Dark').getAttribute('aria-checked')).toBe('true')
|
||||||
expect(findItem('System').getAttribute('aria-checked')).toBe('false')
|
expect(findItem('System').getAttribute('aria-checked')).toBe('false')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('Item heights', () => {
|
||||||
|
it('gives every desktop item 32 px', async () => {
|
||||||
|
await mountMenu()
|
||||||
|
await openMenu()
|
||||||
|
|
||||||
|
for (const item of itemsIn(menu()!)) {
|
||||||
|
expect(item.classList.contains('h-8')).toBe(true)
|
||||||
|
expect(item.classList.contains('items-center')).toBe(true)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('Avatar initials', () => {
|
describe('Avatar initials', () => {
|
||||||
it.each([
|
it.each([
|
||||||
['marta', '', 'MA', 'marta'],
|
['marta', '', 'MA', 'marta'],
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { userRole, type UserListItem } from '@/composables/useUsers'
|
||||||
|
|
||||||
|
describe('userRole', () => {
|
||||||
|
it.each([['owner' as const], ['admin' as const]])('passes a user role %s through', (role) => {
|
||||||
|
const item: UserListItem = {
|
||||||
|
kind: 'user',
|
||||||
|
id: 1,
|
||||||
|
username: 'u',
|
||||||
|
display_name: '',
|
||||||
|
email: 'u@renew.example',
|
||||||
|
role,
|
||||||
|
status: 'accepted',
|
||||||
|
created_at: '2026-03-12T00:00:00Z',
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(userRole(item)).toBe(role)
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each([['pending' as const], ['expired' as const]])(
|
||||||
|
'returns admin for a %s invite',
|
||||||
|
(status) => {
|
||||||
|
const item: UserListItem = {
|
||||||
|
kind: 'invite',
|
||||||
|
id: 2,
|
||||||
|
email: 'i@renew.example',
|
||||||
|
status,
|
||||||
|
created_at: '2026-03-12T00:00:00Z',
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(userRole(item)).toBe('admin')
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
@@ -21,12 +21,15 @@ export class NetworkError extends Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type UserRole = 'owner' | 'admin'
|
||||||
|
|
||||||
export interface MeResult {
|
export interface MeResult {
|
||||||
id?: number
|
id?: number
|
||||||
verified: boolean
|
verified: boolean
|
||||||
username?: string
|
username?: string
|
||||||
email?: string
|
email?: string
|
||||||
displayName: string
|
displayName: string
|
||||||
|
role?: UserRole
|
||||||
}
|
}
|
||||||
|
|
||||||
export type OnUnauthorized = 'redirect' | 'passthrough'
|
export type OnUnauthorized = 'redirect' | 'passthrough'
|
||||||
@@ -135,6 +138,7 @@ export function useApi() {
|
|||||||
username?: string
|
username?: string
|
||||||
email?: string
|
email?: string
|
||||||
display_name?: string | null
|
display_name?: string | null
|
||||||
|
role?: string
|
||||||
}>('/v1/auth/me', { onUnauthorized: 'passthrough' })
|
}>('/v1/auth/me', { onUnauthorized: 'passthrough' })
|
||||||
return {
|
return {
|
||||||
id: body.id,
|
id: body.id,
|
||||||
@@ -142,6 +146,7 @@ export function useApi() {
|
|||||||
username: body.username,
|
username: body.username,
|
||||||
email: body.email,
|
email: body.email,
|
||||||
displayName: body.display_name ?? '',
|
displayName: body.display_name ?? '',
|
||||||
|
role: body.role as UserRole | undefined,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { useApi } from '@/composables/useApi'
|
||||||
|
|
||||||
|
export interface WorkspaceSettings {
|
||||||
|
version: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSettings() {
|
||||||
|
const { request } = useApi()
|
||||||
|
|
||||||
|
function getSettings(): Promise<WorkspaceSettings> {
|
||||||
|
return request<WorkspaceSettings>('/v1/settings/')
|
||||||
|
}
|
||||||
|
|
||||||
|
return { getSettings }
|
||||||
|
}
|
||||||
@@ -6,6 +6,8 @@ export type UserListItem =
|
|||||||
id: number
|
id: number
|
||||||
username: string
|
username: string
|
||||||
display_name: string
|
display_name: string
|
||||||
|
email: string
|
||||||
|
role: 'owner' | 'admin'
|
||||||
status: 'accepted'
|
status: 'accepted'
|
||||||
created_at: string
|
created_at: string
|
||||||
}
|
}
|
||||||
@@ -13,6 +15,7 @@ export type UserListItem =
|
|||||||
kind: 'invite'
|
kind: 'invite'
|
||||||
id: number
|
id: number
|
||||||
email: string
|
email: string
|
||||||
|
display_name?: string
|
||||||
status: 'pending' | 'expired'
|
status: 'pending' | 'expired'
|
||||||
created_at: string
|
created_at: string
|
||||||
}
|
}
|
||||||
@@ -23,6 +26,14 @@ export function userRowKey(kind: UserListItem['kind'], id: number) {
|
|||||||
return `${kind}-${id}`
|
return `${kind}-${id}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function userDisplayName(item: UserListItem) {
|
||||||
|
return item.display_name ?? ''
|
||||||
|
}
|
||||||
|
|
||||||
|
export function userRole(item: UserListItem): 'owner' | 'admin' {
|
||||||
|
return item.kind === 'user' ? item.role : 'admin'
|
||||||
|
}
|
||||||
|
|
||||||
export interface CreatedInvite {
|
export interface CreatedInvite {
|
||||||
id: number
|
id: number
|
||||||
kind: 'invite'
|
kind: 'invite'
|
||||||
@@ -47,5 +58,13 @@ export function useUsers() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return { listUsers, inviteUser }
|
function cancelInvite(id: number): Promise<void> {
|
||||||
|
return request<void>(`/v1/user/invite/${id}`, { method: 'DELETE' })
|
||||||
|
}
|
||||||
|
|
||||||
|
function renewInvite(id: number): Promise<CreatedInvite> {
|
||||||
|
return request<CreatedInvite>(`/v1/user/invite/${id}/renew`, { method: 'POST' })
|
||||||
|
}
|
||||||
|
|
||||||
|
return { listUsers, inviteUser, cancelInvite, renewInvite }
|
||||||
}
|
}
|
||||||
@@ -65,10 +65,7 @@ describe('Nuxt UI shell foundation and router guards', () => {
|
|||||||
it('The first navigation to a non-public route resolves the session and shows AppBoot meanwhile', async () => {
|
it('The first navigation to a non-public route resolves the session and shows AppBoot meanwhile', async () => {
|
||||||
let resolveMe: (value: { verified: boolean }) => void = () => {}
|
let resolveMe: (value: { verified: boolean }) => void = () => {}
|
||||||
const getMe = vi.fn(
|
const getMe = vi.fn(
|
||||||
() =>
|
() => new Promise<{ verified: boolean }>((resolve) => (resolveMe = resolve)),
|
||||||
new Promise<{ verified: boolean }>(
|
|
||||||
(resolve) => (resolveMe = resolve),
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
vi.mocked(useApi).mockReturnValue({ getMe })
|
vi.mocked(useApi).mockReturnValue({ getMe })
|
||||||
setUpSession()
|
setUpSession()
|
||||||
@@ -124,9 +121,7 @@ describe('Nuxt UI shell foundation and router guards', () => {
|
|||||||
await router.push('/article')
|
await router.push('/article')
|
||||||
mountApp()
|
mountApp()
|
||||||
|
|
||||||
await vi.waitFor(() =>
|
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/register/pending'))
|
||||||
expect(router.currentRoute.value.path).toBe('/register/pending'),
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('A session-only route admits an unverified session', async () => {
|
it('A session-only route admits an unverified session', async () => {
|
||||||
@@ -201,9 +196,7 @@ describe('Nuxt UI shell foundation and router guards', () => {
|
|||||||
)
|
)
|
||||||
expect(app.text()).toContain('Home')
|
expect(app.text()).toContain('Home')
|
||||||
|
|
||||||
const primaryButton = app
|
const primaryButton = app.findAll('button').find((button) => button.text() === 'Try again')
|
||||||
.findAll('button')
|
|
||||||
.find((button) => button.text() === 'Try again')
|
|
||||||
await primaryButton?.trigger('click')
|
await primaryButton?.trigger('click')
|
||||||
await flushPromises()
|
await flushPromises()
|
||||||
|
|
||||||
@@ -219,16 +212,12 @@ describe('Nuxt UI shell foundation and router guards', () => {
|
|||||||
const app = mountApp()
|
const app = mountApp()
|
||||||
|
|
||||||
await vi.waitFor(() =>
|
await vi.waitFor(() =>
|
||||||
expect(app.find('[role="alert"] h1').text()).toBe(
|
expect(app.find('[role="alert"] h1').text()).toBe('Something went wrong'),
|
||||||
'Something went wrong',
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
expect(router.currentRoute.value.path).toBe('/article')
|
expect(router.currentRoute.value.path).toBe('/article')
|
||||||
|
|
||||||
const primaryButton = app
|
const primaryButton = app.findAll('button').find((button) => button.text() === 'Try again')
|
||||||
.findAll('button')
|
|
||||||
.find((button) => button.text() === 'Try again')
|
|
||||||
await primaryButton?.trigger('click')
|
await primaryButton?.trigger('click')
|
||||||
await flushPromises()
|
await flushPromises()
|
||||||
|
|
||||||
@@ -239,6 +228,7 @@ describe('Nuxt UI shell foundation and router guards', () => {
|
|||||||
{ path: '/home', title: 'Home' },
|
{ path: '/home', title: 'Home' },
|
||||||
{ path: '/article', title: 'Articles' },
|
{ path: '/article', title: 'Articles' },
|
||||||
{ path: '/integration', title: 'Integration' },
|
{ path: '/integration', title: 'Integration' },
|
||||||
|
{ path: '/settings', title: 'Settings' },
|
||||||
])(
|
])(
|
||||||
'Placeholder verified route $path renders inside DashboardShell with title $title',
|
'Placeholder verified route $path renders inside DashboardShell with title $title',
|
||||||
async ({ path, title }) => {
|
async ({ path, title }) => {
|
||||||
@@ -251,14 +241,10 @@ describe('Nuxt UI shell foundation and router guards', () => {
|
|||||||
await flushPromises()
|
await flushPromises()
|
||||||
|
|
||||||
const headings = app.findAll('h1')
|
const headings = app.findAll('h1')
|
||||||
expect(headings.some((heading) => heading.text() === title)).toBe(
|
expect(headings.some((heading) => heading.text() === title)).toBe(true)
|
||||||
true,
|
|
||||||
)
|
|
||||||
expect(app.find('nav[aria-label="breadcrumb"]').text()).toBe(title)
|
expect(app.find('nav[aria-label="breadcrumb"]').text()).toBe(title)
|
||||||
|
|
||||||
const activeLink = app.find(
|
const activeLink = app.find(`a[href="${path}"][aria-current="page"]`)
|
||||||
`a[href="${path}"][aria-current="page"]`,
|
|
||||||
)
|
|
||||||
expect(activeLink.exists()).toBe(true)
|
expect(activeLink.exists()).toBe(true)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -86,6 +86,11 @@ const router = createRouter({
|
|||||||
component: () => import('@/views/IntegrationView.vue'),
|
component: () => import('@/views/IntegrationView.vue'),
|
||||||
meta: { auth: 'verified', title: 'Integration' },
|
meta: { auth: 'verified', title: 'Integration' },
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: '/settings',
|
||||||
|
component: () => import('@/views/SettingsView.vue'),
|
||||||
|
meta: { auth: 'verified', title: 'Settings' },
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: '/:pathMatch(.*)*',
|
path: '/:pathMatch(.*)*',
|
||||||
component: () => import('@/views/NotFoundView.vue'),
|
component: () => import('@/views/NotFoundView.vue'),
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
import { ref } from 'vue'
|
import { ref } from 'vue'
|
||||||
import { ApiError, useApi } from '@/composables/useApi'
|
import { ApiError, useApi, type UserRole } from '@/composables/useApi'
|
||||||
|
|
||||||
export type SessionStatus = 'idle' | 'checking' | 'ready' | 'error'
|
export type SessionStatus = 'idle' | 'checking' | 'ready' | 'error'
|
||||||
|
|
||||||
@@ -10,6 +10,7 @@ export interface Session {
|
|||||||
username?: string
|
username?: string
|
||||||
email?: string
|
email?: string
|
||||||
displayName: string
|
displayName: string
|
||||||
|
role?: UserRole
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useSessionStore = defineStore('session', () => {
|
export const useSessionStore = defineStore('session', () => {
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
||||||
|
import DashboardShell from '@/components/DashboardShell.vue'
|
||||||
|
import { ApiError } from '@/composables/useApi'
|
||||||
|
import { useSettings } from '@/composables/useSettings'
|
||||||
|
|
||||||
|
const SKELETON_DELAY_MS = 150
|
||||||
|
const UNREACHABLE_COPY = "Couldn't reach RenewCMS. Check your connection and try again."
|
||||||
|
|
||||||
|
type LoadState = 'loading' | 'ready' | 'error'
|
||||||
|
|
||||||
|
const { getSettings } = useSettings()
|
||||||
|
|
||||||
|
const loadState = ref<LoadState>('loading')
|
||||||
|
const version = ref('')
|
||||||
|
const showSkeleton = ref(false)
|
||||||
|
let skeletonTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
|
|
||||||
|
function clearSkeletonTimer() {
|
||||||
|
if (skeletonTimer !== null) {
|
||||||
|
clearTimeout(skeletonTimer)
|
||||||
|
skeletonTimer = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isHandledGlobally(error: unknown) {
|
||||||
|
return error instanceof ApiError && (error.status === 401 || error.status === 403)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadSettings() {
|
||||||
|
loadState.value = 'loading'
|
||||||
|
showSkeleton.value = false
|
||||||
|
clearSkeletonTimer()
|
||||||
|
skeletonTimer = setTimeout(() => {
|
||||||
|
showSkeleton.value = true
|
||||||
|
}, SKELETON_DELAY_MS)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const settings = await getSettings()
|
||||||
|
version.value = settings.version
|
||||||
|
loadState.value = 'ready'
|
||||||
|
} catch (error) {
|
||||||
|
if (!isHandledGlobally(error)) {
|
||||||
|
loadState.value = 'error'
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
clearSkeletonTimer()
|
||||||
|
showSkeleton.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(loadSettings)
|
||||||
|
onBeforeUnmount(clearSkeletonTimer)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<DashboardShell>
|
||||||
|
<div class="flex max-w-180 flex-col gap-5">
|
||||||
|
<div class="flex flex-col gap-0.5">
|
||||||
|
<h1 class="text-xl font-semibold text-highlighted">Settings</h1>
|
||||||
|
<p class="text-muted">Workspace information.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
data-testid="settings-card"
|
||||||
|
:aria-busy="loadState === 'loading' && showSkeleton ? 'true' : undefined"
|
||||||
|
class="border border-default bg-default p-4 lg:p-5"
|
||||||
|
>
|
||||||
|
<UAlert
|
||||||
|
v-if="loadState === 'error'"
|
||||||
|
role="alert"
|
||||||
|
color="error"
|
||||||
|
variant="soft"
|
||||||
|
orientation="vertical"
|
||||||
|
:close="false"
|
||||||
|
icon="i-lucide-circle-x"
|
||||||
|
:description="UNREACHABLE_COPY"
|
||||||
|
:ui="{ actions: 'mt-2' }"
|
||||||
|
>
|
||||||
|
<template #actions>
|
||||||
|
<UButton
|
||||||
|
color="neutral"
|
||||||
|
variant="outline"
|
||||||
|
icon="i-lucide-rotate-cw"
|
||||||
|
class="h-11 gap-1.5 border border-accented bg-default px-2.5 text-xs text-highlighted ring-0 md:h-8"
|
||||||
|
:ui="{ leadingIcon: 'size-3.5' }"
|
||||||
|
@click="loadSettings"
|
||||||
|
>
|
||||||
|
Try again
|
||||||
|
</UButton>
|
||||||
|
</template>
|
||||||
|
</UAlert>
|
||||||
|
|
||||||
|
<div v-else class="flex items-center justify-between gap-4">
|
||||||
|
<span class="text-lg font-semibold text-highlighted">Version</span>
|
||||||
|
<USkeleton
|
||||||
|
v-if="loadState === 'loading' && showSkeleton"
|
||||||
|
data-testid="settings-skeleton"
|
||||||
|
class="h-5 w-24 rounded-none bg-accented"
|
||||||
|
/>
|
||||||
|
<span
|
||||||
|
v-else-if="loadState === 'ready'"
|
||||||
|
data-testid="settings-version"
|
||||||
|
class="font-mono text-base text-toned"
|
||||||
|
>{{ version }}</span
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</DashboardShell>
|
||||||
|
</template>
|
||||||
+108
-5
@@ -1,11 +1,13 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
|
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||||
import { useMediaQuery } from '@vueuse/core'
|
import { useMediaQuery } from '@vueuse/core'
|
||||||
import { useToast } from '@nuxt/ui/composables'
|
import { useOverlay, useToast } from '@nuxt/ui/composables'
|
||||||
|
import ConfirmDialog from '@/components/ConfirmDialog.vue'
|
||||||
import DashboardShell from '@/components/DashboardShell.vue'
|
import DashboardShell from '@/components/DashboardShell.vue'
|
||||||
import InviteUserModal from '@/components/InviteUserModal.vue'
|
import InviteUserModal from '@/components/InviteUserModal.vue'
|
||||||
import UserCardList from '@/components/UserCardList.vue'
|
import UserCardList from '@/components/UserCardList.vue'
|
||||||
import UsersTable from '@/components/UsersTable.vue'
|
import UsersTable from '@/components/UsersTable.vue'
|
||||||
|
import { ApiError } from '@/composables/useApi'
|
||||||
import { useUsers, userRowKey, type CreatedInvite, type UserListItem } from '@/composables/useUsers'
|
import { useUsers, userRowKey, type CreatedInvite, type UserListItem } from '@/composables/useUsers'
|
||||||
import { useSessionStore } from '@/stores/session'
|
import { useSessionStore } from '@/stores/session'
|
||||||
|
|
||||||
@@ -14,9 +16,13 @@ const DESKTOP_QUERY = '(min-width: 48rem)'
|
|||||||
|
|
||||||
type LoadState = 'loading' | 'ready' | 'error'
|
type LoadState = 'loading' | 'ready' | 'error'
|
||||||
|
|
||||||
|
const AUTH_HANDLED_STATUSES = [401, 403]
|
||||||
|
const CANCEL_FAILED_COPY = "Couldn't cancel the invite. Try again in a moment."
|
||||||
|
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
|
const overlay = useOverlay()
|
||||||
const session = useSessionStore()
|
const session = useSessionStore()
|
||||||
const { listUsers } = useUsers()
|
const { listUsers, cancelInvite, renewInvite } = useUsers()
|
||||||
const isDesktop = useMediaQuery(DESKTOP_QUERY)
|
const isDesktop = useMediaQuery(DESKTOP_QUERY)
|
||||||
|
|
||||||
const loadState = ref<LoadState>('loading')
|
const loadState = ref<LoadState>('loading')
|
||||||
@@ -24,14 +30,18 @@ const items = ref<UserListItem[]>([])
|
|||||||
const showSkeleton = ref(false)
|
const showSkeleton = ref(false)
|
||||||
const inviteModalOpen = ref(false)
|
const inviteModalOpen = ref(false)
|
||||||
const highlightedKey = ref('')
|
const highlightedKey = ref('')
|
||||||
|
const busyKeys = ref<string[]>([])
|
||||||
let skeletonTimer: ReturnType<typeof setTimeout> | null = null
|
let skeletonTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
let opener: HTMLElement | null = null
|
let opener: HTMLElement | null = null
|
||||||
|
|
||||||
const sessionUserId = computed(() => session.session?.id)
|
const sessionUserId = computed(() => session.session?.id)
|
||||||
|
const canInvite = computed(() => session.session?.role === 'owner')
|
||||||
const showList = computed(
|
const showList = computed(
|
||||||
() => loadState.value === 'ready' || (loadState.value === 'loading' && showSkeleton.value),
|
() => loadState.value === 'ready' || (loadState.value === 'loading' && showSkeleton.value),
|
||||||
)
|
)
|
||||||
const showOnlyYouHint = computed(() => loadState.value === 'ready' && items.value.length === 1)
|
const showOnlyYouHint = computed(
|
||||||
|
() => loadState.value === 'ready' && items.value.length === 1 && canInvite.value,
|
||||||
|
)
|
||||||
|
|
||||||
function clearSkeletonTimer() {
|
function clearSkeletonTimer() {
|
||||||
if (skeletonTimer !== null) {
|
if (skeletonTimer !== null) {
|
||||||
@@ -84,6 +94,7 @@ function onInvited(invite: CreatedInvite) {
|
|||||||
kind: 'invite',
|
kind: 'invite',
|
||||||
id: invite.id,
|
id: invite.id,
|
||||||
email: invite.email,
|
email: invite.email,
|
||||||
|
display_name: '',
|
||||||
status: 'pending',
|
status: 'pending',
|
||||||
created_at: invite.created_at,
|
created_at: invite.created_at,
|
||||||
}
|
}
|
||||||
@@ -103,6 +114,90 @@ function onInvited(invite: CreatedInvite) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isHandledByApiClient(err: unknown) {
|
||||||
|
return err instanceof ApiError && AUTH_HANDLED_STATUSES.includes(err.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeRow(key: string) {
|
||||||
|
items.value = items.value.filter((item) => userRowKey(item.kind, item.id) !== key)
|
||||||
|
}
|
||||||
|
|
||||||
|
function confirmCancel(invite: UserListItem) {
|
||||||
|
const key = userRowKey(invite.kind, invite.id)
|
||||||
|
overlay
|
||||||
|
.create(ConfirmDialog, {
|
||||||
|
props: {
|
||||||
|
title: 'Cancel this invite?',
|
||||||
|
description: `The link sent to ${invite.email} will stop working. You can invite the address again later.`,
|
||||||
|
confirmLabel: 'Cancel invite',
|
||||||
|
cancelLabel: 'Keep invite',
|
||||||
|
pendingLabel: 'Cancelling…',
|
||||||
|
tone: 'danger',
|
||||||
|
action: async () => {
|
||||||
|
try {
|
||||||
|
await cancelInvite(invite.id)
|
||||||
|
} catch (err) {
|
||||||
|
if (isHandledByApiClient(err)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
throw new Error(CANCEL_FAILED_COPY)
|
||||||
|
}
|
||||||
|
removeRow(key)
|
||||||
|
toast.add({
|
||||||
|
id: `invite-cancelled-${invite.id}`,
|
||||||
|
color: 'success',
|
||||||
|
icon: 'i-lucide-circle-check',
|
||||||
|
title: 'Invite cancelled',
|
||||||
|
description: `${invite.email} can no longer use the link.`,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.open()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function renew(invite: UserListItem) {
|
||||||
|
const key = userRowKey(invite.kind, invite.id)
|
||||||
|
if (busyKeys.value.includes(key)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
busyKeys.value = [...busyKeys.value, key]
|
||||||
|
try {
|
||||||
|
const renewed = await renewInvite(invite.id)
|
||||||
|
items.value = [
|
||||||
|
{
|
||||||
|
kind: 'invite',
|
||||||
|
id: renewed.id,
|
||||||
|
email: renewed.email,
|
||||||
|
display_name: invite.display_name,
|
||||||
|
status: 'pending',
|
||||||
|
created_at: renewed.created_at,
|
||||||
|
},
|
||||||
|
...items.value.filter((item) => userRowKey(item.kind, item.id) !== key),
|
||||||
|
]
|
||||||
|
highlightedKey.value = userRowKey('invite', renewed.id)
|
||||||
|
toast.add({
|
||||||
|
id: `invite-renewed-${renewed.id}`,
|
||||||
|
color: 'success',
|
||||||
|
icon: 'i-lucide-circle-check',
|
||||||
|
title: 'Invite renewed',
|
||||||
|
description: `${renewed.email} has 3 days to accept the new link.`,
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
if (!isHandledByApiClient(err)) {
|
||||||
|
toast.add({
|
||||||
|
id: `invite-renew-failed-${invite.id}`,
|
||||||
|
color: 'error',
|
||||||
|
icon: 'i-lucide-circle-x',
|
||||||
|
title: "Couldn't renew the invite",
|
||||||
|
description: 'Try again in a moment.',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
busyKeys.value = busyKeys.value.filter((busyKey) => busyKey !== key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
onMounted(loadUsers)
|
onMounted(loadUsers)
|
||||||
onBeforeUnmount(clearSkeletonTimer)
|
onBeforeUnmount(clearSkeletonTimer)
|
||||||
</script>
|
</script>
|
||||||
@@ -116,7 +211,7 @@ onBeforeUnmount(clearSkeletonTimer)
|
|||||||
<p class="text-muted">Everyone who can sign in and work on your articles.</p>
|
<p class="text-muted">Everyone who can sign in and work on your articles.</p>
|
||||||
</div>
|
</div>
|
||||||
<UButton
|
<UButton
|
||||||
v-if="isDesktop"
|
v-if="isDesktop && canInvite"
|
||||||
icon="i-lucide-user-plus"
|
icon="i-lucide-user-plus"
|
||||||
class="h-8 px-3"
|
class="h-8 px-3"
|
||||||
@click="openInviteModal"
|
@click="openInviteModal"
|
||||||
@@ -158,6 +253,10 @@ onBeforeUnmount(clearSkeletonTimer)
|
|||||||
:loading="loadState === 'loading'"
|
:loading="loadState === 'loading'"
|
||||||
:session-user-id="sessionUserId"
|
:session-user-id="sessionUserId"
|
||||||
:highlighted-key="highlightedKey"
|
:highlighted-key="highlightedKey"
|
||||||
|
:can-manage="canInvite"
|
||||||
|
:busy-keys="busyKeys"
|
||||||
|
@cancel="confirmCancel"
|
||||||
|
@renew="renew"
|
||||||
/>
|
/>
|
||||||
<UserCardList
|
<UserCardList
|
||||||
v-else
|
v-else
|
||||||
@@ -165,6 +264,10 @@ onBeforeUnmount(clearSkeletonTimer)
|
|||||||
:loading="loadState === 'loading'"
|
:loading="loadState === 'loading'"
|
||||||
:session-user-id="sessionUserId"
|
:session-user-id="sessionUserId"
|
||||||
:highlighted-key="highlightedKey"
|
:highlighted-key="highlightedKey"
|
||||||
|
:can-manage="canInvite"
|
||||||
|
:busy-keys="busyKeys"
|
||||||
|
@cancel="confirmCancel"
|
||||||
|
@renew="renew"
|
||||||
/>
|
/>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -174,7 +277,7 @@ onBeforeUnmount(clearSkeletonTimer)
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<UButton
|
<UButton
|
||||||
v-if="!isDesktop"
|
v-if="!isDesktop && canInvite"
|
||||||
v-show="!inviteModalOpen"
|
v-show="!inviteModalOpen"
|
||||||
icon="i-lucide-user-plus"
|
icon="i-lucide-user-plus"
|
||||||
class="fixed inset-x-4 bottom-4 h-12 justify-center text-[0.9375rem] shadow-(--shadow-popover)"
|
class="fixed inset-x-4 bottom-4 h-12 justify-center text-[0.9375rem] shadow-(--shadow-popover)"
|
||||||
|
|||||||
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user