2025-09-15 18:47:39 +00:00
|
|
|
|
package handler
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2026-05-13 15:07:18 +00:00
|
|
|
|
"context"
|
2026-04-11 04:47:17 +00:00
|
|
|
|
"crypto/rand"
|
2026-03-30 03:13:44 +00:00
|
|
|
|
"encoding/base64"
|
|
|
|
|
|
"encoding/json"
|
2026-08-07 07:12:05 +00:00
|
|
|
|
stderrors "errors"
|
2026-04-11 04:47:17 +00:00
|
|
|
|
"fmt"
|
2025-09-15 18:47:39 +00:00
|
|
|
|
"net/http"
|
|
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
|
|
2026-08-07 07:12:05 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/application/service"
|
2025-12-03 03:11:57 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/config"
|
2025-09-15 18:47:39 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/errors"
|
2026-07-02 04:31:57 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/handler/dto"
|
2025-09-15 18:47:39 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/logger"
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/types"
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
2025-11-25 16:57:33 +00:00
|
|
|
|
secutils "github.com/Tencent/WeKnora/internal/utils"
|
2025-09-15 18:47:39 +00:00
|
|
|
|
)
|
|
|
|
|
|
|
2026-07-02 06:49:27 +00:00
|
|
|
|
const oidcNonceCookieName = "weknora_oidc_nonce"
|
|
|
|
|
|
const oidcNonceCookieMaxAge = 600
|
|
|
|
|
|
|
2025-09-15 18:47:39 +00:00
|
|
|
|
// AuthHandler implements HTTP request handlers for user authentication
|
|
|
|
|
|
// Provides functionality for user registration, login, logout, and token management
|
|
|
|
|
|
// through the REST API endpoints
|
|
|
|
|
|
type AuthHandler struct {
|
2026-05-24 13:38:05 +00:00
|
|
|
|
userService interfaces.UserService
|
|
|
|
|
|
tenantService interfaces.TenantService
|
|
|
|
|
|
configInfo *config.Config
|
|
|
|
|
|
systemSettingSvc interfaces.SystemSettingService
|
feat(rbac): add multi-use share-link invitations for invite_only mode (#1504)
* feat(rbac): add multi-use share-link invitations for invite_only mode
When the auth.registration_mode toggle flips to invite_only, the public
/auth/register endpoint returns 403 — but until now there was no
channel for unregistered users to actually join a tenant. The existing
invitation table required a registered invitee, so new emails could
not enter the system at all.
This change introduces a share-link model:
- Owner generates a multi-use registration link with a per-tenant role
- Recipient opens the link, registers with their own email, and is
added to the tenant on the same request
- Token is stored in plaintext (not hashed) so the management UI can
re-display the URL on demand without a "copy now or revoke" trap.
Threat model is bounded by 7-day TTL, revocability, and the fact
that all the link grants is membership in one tenant.
- accepted_count tracks how many users joined through the link so the
Owner can tell whether a link is fresh or has already been spread
Per-user invitations (registered email -> in-app inbox accept) are
unchanged. Share-link rows use empty invitee_user_id as discriminator;
the partial unique index on (tenant_id, invitee_user_id) was relaxed
to skip empty values so multiple share links can coexist per tenant.
Frontend reuses Login.vue for /register?token=xxx instead of a
parallel page, and adds icon-only revoke / remove actions plus a
distinct "active" status tag for share-link rows.
Migration 000054 adds the token column, the accepted_count column,
and the relaxed pending unique index in a single step.
* feat(auth): update invitation token handling and add rate limiting
- Refactor the invitation token retrieval to use POST instead of GET, enhancing security by preventing the plaintext token from appearing in logs and browser history.
- Update the API endpoint from `/auth/invitations/:token` to `/auth/invitations/lookup` to reflect the new method.
- Introduce a rate limiter for unauthenticated share-link endpoints to mitigate brute-force attacks and abuse, ensuring a maximum of 30 requests per minute per IP.
- Adjust the registration flow to maintain user experience while securing the invitation process.
2026-05-27 11:42:01 +00:00
|
|
|
|
// invitationSvc is required for the share-link registration path
|
|
|
|
|
|
// (POST /auth/register-by-invite). When nil — e.g. legacy test
|
|
|
|
|
|
// fixtures — the share-link endpoints respond 503 rather than
|
|
|
|
|
|
// blocking the rest of the auth surface.
|
|
|
|
|
|
invitationSvc interfaces.TenantInvitationService
|
2025-09-15 18:47:39 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-16 07:39:34 +00:00
|
|
|
|
// NewAuthHandler creates a new auth handler instance with the provided services
|
2025-09-15 18:47:39 +00:00
|
|
|
|
// Parameters:
|
|
|
|
|
|
// - userService: An implementation of the UserService interface for business logic
|
2025-09-16 07:39:34 +00:00
|
|
|
|
// - tenantService: An implementation of the TenantService interface for tenant management
|
2026-05-24 13:38:05 +00:00
|
|
|
|
// - systemSettingSvc: 3-tier resolver for runtime-tunable settings such as
|
|
|
|
|
|
// auth.registration_mode (P3). When DB has a row, it overrides cfg's
|
|
|
|
|
|
// startup value; otherwise we fall back to cfg.Auth.RegistrationMode
|
|
|
|
|
|
// (which already accounted for the legacy DISABLE_REGISTRATION env coerce
|
|
|
|
|
|
// during config load). Mismatch impossible by construction since the
|
|
|
|
|
|
// handler always passes cfg's value as the def parameter to GetString.
|
2025-09-15 18:47:39 +00:00
|
|
|
|
//
|
|
|
|
|
|
// Returns a pointer to the newly created AuthHandler
|
2025-12-03 03:11:57 +00:00
|
|
|
|
func NewAuthHandler(configInfo *config.Config,
|
2026-05-24 13:38:05 +00:00
|
|
|
|
userService interfaces.UserService, tenantService interfaces.TenantService,
|
|
|
|
|
|
systemSettingSvc interfaces.SystemSettingService,
|
feat(rbac): add multi-use share-link invitations for invite_only mode (#1504)
* feat(rbac): add multi-use share-link invitations for invite_only mode
When the auth.registration_mode toggle flips to invite_only, the public
/auth/register endpoint returns 403 — but until now there was no
channel for unregistered users to actually join a tenant. The existing
invitation table required a registered invitee, so new emails could
not enter the system at all.
This change introduces a share-link model:
- Owner generates a multi-use registration link with a per-tenant role
- Recipient opens the link, registers with their own email, and is
added to the tenant on the same request
- Token is stored in plaintext (not hashed) so the management UI can
re-display the URL on demand without a "copy now or revoke" trap.
Threat model is bounded by 7-day TTL, revocability, and the fact
that all the link grants is membership in one tenant.
- accepted_count tracks how many users joined through the link so the
Owner can tell whether a link is fresh or has already been spread
Per-user invitations (registered email -> in-app inbox accept) are
unchanged. Share-link rows use empty invitee_user_id as discriminator;
the partial unique index on (tenant_id, invitee_user_id) was relaxed
to skip empty values so multiple share links can coexist per tenant.
Frontend reuses Login.vue for /register?token=xxx instead of a
parallel page, and adds icon-only revoke / remove actions plus a
distinct "active" status tag for share-link rows.
Migration 000054 adds the token column, the accepted_count column,
and the relaxed pending unique index in a single step.
* feat(auth): update invitation token handling and add rate limiting
- Refactor the invitation token retrieval to use POST instead of GET, enhancing security by preventing the plaintext token from appearing in logs and browser history.
- Update the API endpoint from `/auth/invitations/:token` to `/auth/invitations/lookup` to reflect the new method.
- Introduce a rate limiter for unauthenticated share-link endpoints to mitigate brute-force attacks and abuse, ensuring a maximum of 30 requests per minute per IP.
- Adjust the registration flow to maintain user experience while securing the invitation process.
2026-05-27 11:42:01 +00:00
|
|
|
|
invitationSvc interfaces.TenantInvitationService,
|
2026-05-24 13:38:05 +00:00
|
|
|
|
) *AuthHandler {
|
2026-05-13 15:07:18 +00:00
|
|
|
|
// Boot-time guard: a nil-or-empty Auth section silently disables the
|
|
|
|
|
|
// invite_only gate (see Register below). Emit a loud one-shot log
|
|
|
|
|
|
// pointing at the misconfiguration so operators notice on startup
|
|
|
|
|
|
// instead of discovering it the day someone hits /auth/register.
|
|
|
|
|
|
if configInfo == nil || configInfo.Auth == nil {
|
|
|
|
|
|
logger.Errorf(context.Background(),
|
|
|
|
|
|
"[auth] AuthHandler constructed with nil/incomplete config (cfg=%v); "+
|
|
|
|
|
|
"registration_mode enforcement is disabled. This is almost certainly a wiring bug.",
|
|
|
|
|
|
configInfo)
|
|
|
|
|
|
}
|
2025-09-15 18:47:39 +00:00
|
|
|
|
return &AuthHandler{
|
2026-05-24 13:38:05 +00:00
|
|
|
|
configInfo: configInfo,
|
|
|
|
|
|
userService: userService,
|
|
|
|
|
|
tenantService: tenantService,
|
|
|
|
|
|
systemSettingSvc: systemSettingSvc,
|
feat(rbac): add multi-use share-link invitations for invite_only mode (#1504)
* feat(rbac): add multi-use share-link invitations for invite_only mode
When the auth.registration_mode toggle flips to invite_only, the public
/auth/register endpoint returns 403 — but until now there was no
channel for unregistered users to actually join a tenant. The existing
invitation table required a registered invitee, so new emails could
not enter the system at all.
This change introduces a share-link model:
- Owner generates a multi-use registration link with a per-tenant role
- Recipient opens the link, registers with their own email, and is
added to the tenant on the same request
- Token is stored in plaintext (not hashed) so the management UI can
re-display the URL on demand without a "copy now or revoke" trap.
Threat model is bounded by 7-day TTL, revocability, and the fact
that all the link grants is membership in one tenant.
- accepted_count tracks how many users joined through the link so the
Owner can tell whether a link is fresh or has already been spread
Per-user invitations (registered email -> in-app inbox accept) are
unchanged. Share-link rows use empty invitee_user_id as discriminator;
the partial unique index on (tenant_id, invitee_user_id) was relaxed
to skip empty values so multiple share links can coexist per tenant.
Frontend reuses Login.vue for /register?token=xxx instead of a
parallel page, and adds icon-only revoke / remove actions plus a
distinct "active" status tag for share-link rows.
Migration 000054 adds the token column, the accepted_count column,
and the relaxed pending unique index in a single step.
* feat(auth): update invitation token handling and add rate limiting
- Refactor the invitation token retrieval to use POST instead of GET, enhancing security by preventing the plaintext token from appearing in logs and browser history.
- Update the API endpoint from `/auth/invitations/:token` to `/auth/invitations/lookup` to reflect the new method.
- Introduce a rate limiter for unauthenticated share-link endpoints to mitigate brute-force attacks and abuse, ensuring a maximum of 30 requests per minute per IP.
- Adjust the registration flow to maintain user experience while securing the invitation process.
2026-05-27 11:42:01 +00:00
|
|
|
|
invitationSvc: invitationSvc,
|
2025-09-15 18:47:39 +00:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-24 13:38:05 +00:00
|
|
|
|
// resolveRegistrationMode returns the currently active registration mode.
|
|
|
|
|
|
// Priority: DB system_settings > cfg (which already absorbed the legacy
|
|
|
|
|
|
// DISABLE_REGISTRATION env coerce at startup) > "self_serve" hard default.
|
|
|
|
|
|
//
|
|
|
|
|
|
// Centralised here so /auth/register and /auth/config stay in lock-step —
|
|
|
|
|
|
// otherwise a SystemAdmin's UI edit could affect one path and not the other.
|
|
|
|
|
|
func (h *AuthHandler) resolveRegistrationMode(ctx context.Context) string {
|
|
|
|
|
|
// cfg-derived default: empty is impossible after applyAuthAndTenantDefaults,
|
|
|
|
|
|
// but be defensive in case AuthHandler was constructed before that ran
|
|
|
|
|
|
// (the NewAuthHandler guard already logged in that case).
|
|
|
|
|
|
def := config.AuthRegistrationModeSelfServe
|
|
|
|
|
|
if h.configInfo != nil && h.configInfo.Auth != nil {
|
|
|
|
|
|
if m := strings.TrimSpace(h.configInfo.Auth.RegistrationMode); m != "" {
|
|
|
|
|
|
def = m
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
if h.systemSettingSvc == nil {
|
|
|
|
|
|
return def
|
|
|
|
|
|
}
|
|
|
|
|
|
// envName = "" because DISABLE_REGISTRATION is a boolean and
|
|
|
|
|
|
// auth.registration_mode is a string — the legacy env was already
|
|
|
|
|
|
// coerced into `def` above. Mixing the two semantics at the resolver
|
|
|
|
|
|
// layer would mean a UI delete (DB row absent) silently flipped to
|
|
|
|
|
|
// the legacy boolean read again, which is surprising.
|
|
|
|
|
|
return h.systemSettingSvc.GetString(ctx, "auth.registration_mode", "", def)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-13 10:04:14 +00:00
|
|
|
|
// resolveDefaultTenantMode returns the provisioning policy for ordinary
|
|
|
|
|
|
// public password registrations. Invitation registration never uses this
|
|
|
|
|
|
// value: the invitation itself supplies the target tenant.
|
|
|
|
|
|
func (h *AuthHandler) resolveDefaultTenantMode(ctx context.Context) types.TenantProvisioningMode {
|
|
|
|
|
|
def := config.AuthDefaultTenantModeCreatePersonal
|
|
|
|
|
|
if h.configInfo != nil && h.configInfo.Auth != nil {
|
|
|
|
|
|
if mode := strings.TrimSpace(h.configInfo.Auth.DefaultTenantMode); mode != "" {
|
|
|
|
|
|
def = mode
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
mode := def
|
|
|
|
|
|
if h.systemSettingSvc != nil {
|
|
|
|
|
|
mode = h.systemSettingSvc.GetString(
|
|
|
|
|
|
ctx,
|
|
|
|
|
|
"auth.default_tenant_mode",
|
|
|
|
|
|
"WEKNORA_AUTH_DEFAULT_TENANT_MODE",
|
|
|
|
|
|
def,
|
|
|
|
|
|
)
|
|
|
|
|
|
}
|
|
|
|
|
|
if mode == config.AuthDefaultTenantModeTenantless {
|
|
|
|
|
|
return types.TenantProvisioningTenantless
|
|
|
|
|
|
}
|
|
|
|
|
|
return types.TenantProvisioningCreatePersonal
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// Register godoc
|
|
|
|
|
|
// @Summary 用户注册
|
|
|
|
|
|
// @Description 注册新用户账号
|
|
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Param request body types.RegisterRequest true "注册请求参数"
|
|
|
|
|
|
// @Success 201 {object} types.RegisterResponse
|
|
|
|
|
|
// @Failure 400 {object} errors.AppError "请求参数错误"
|
2025-12-22 06:41:11 +00:00
|
|
|
|
// @Failure 403 {object} errors.AppError "注册功能已禁用"
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// @Router /auth/register [post]
|
2025-09-15 18:47:39 +00:00
|
|
|
|
func (h *AuthHandler) Register(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
|
|
|
|
|
|
logger.Info(ctx, "Start user registration")
|
|
|
|
|
|
|
feat(rbac): tenant member management + invite_only gate (PR 3 of 3, #1303)
Wire the human-facing surface for the tenant-RBAC system that PR 1
introduced and PR 2 enforced: REST endpoints + UI for managing tenant
members, plus the long-pending invite_only registration gate.
Backend
- internal/handler/auth.go: Register now rejects with 403 when
auth.registration_mode=invite_only. PR 1 already exposes the mode via
/auth/config so the frontend hides the sign-up link; this is the
server-side enforcement for direct API calls.
- internal/handler/tenant_member.go: new TenantMemberHandler with
ListMembers / AddMember / UpdateMemberRole / RemoveMember. Maps
service-layer sentinels onto HTTP semantics (ErrLastOwner -> 409,
ErrMembershipAlreadyExists -> 409, ErrUserNotFound on AddMember -> 404,
ErrInvalidTenantRole -> 400). AddMember requires the invitee to
already have an account; SMTP-driven email invites are deferred.
- internal/types/tenant_member.go: new TenantMemberResponse projection
carrying the fields the management UI renders (email, username,
avatar, role, joined_at).
- internal/router/router.go: four routes under /tenants/:id/members
gated per the matrix (Viewer+ for list, Owner+ for every mutation).
- internal/container/container.go: dig provider for the new handler.
Tests
- handler/tenant_member_test.go: 12 table-driven cases covering happy
path, dangling-user tolerance, ErrLastOwner -> 409, ErrMembershipNotFound
-> 404, ErrMembershipAlreadyExists -> 409, unknown email -> 404,
invalid role rejected before user lookup, bad tenant id -> 400.
- handler/auth_register_invite_only_test.go: invite_only -> 403,
self_serve -> 201, nil Auth config falls through.
Frontend
- src/api/tenant/members.ts: typed client (TenantRole/TenantMember/...)
for the four endpoints.
- src/views/settings/TenantMembers.vue: members table with add dialog,
inline role select, confirm-remove modal. All mutation widgets gated
behind currentTenantRole === 'owner'; server still enforces.
- src/views/settings/Settings.vue: register the Members tab; show only
when currentTenantRole is loaded (avoids tab flash on cold nav).
- i18n in en-US/zh-CN/ko-KR/ru-RU: new tenantMember namespace covering
all UI strings and structured error messages (lastOwner / userNotFound
/ alreadyMember / invalidRole etc).
This completes the #1303 RBAC rollout. With cfg.Tenant.EnableRBAC=true
operators now have a full management surface; with EnableRBAC=false
the routes still exist but mutations log-and-pass per PR 2 contract.
2026-05-13 14:23:59 +00:00
|
|
|
|
// 当 auth.registration_mode=invite_only 时,public 注册被关闭。
|
2026-05-24 13:38:05 +00:00
|
|
|
|
// 优先级:DB system_settings > cfg.Auth.RegistrationMode > "self_serve"。
|
|
|
|
|
|
// SystemAdmin 通过「全局设置」UI 实时切换 self_serve / invite_only,立即
|
|
|
|
|
|
// 生效,不需要重启服务。历史变量 DISABLE_REGISTRATION=true 仍在 config
|
|
|
|
|
|
// 启动阶段被等价提升为 invite_only(applyAuthAndTenantDefaults),
|
|
|
|
|
|
// 作为 cfg-default 进入 resolveRegistrationMode。
|
|
|
|
|
|
if h.resolveRegistrationMode(ctx) == config.AuthRegistrationModeInviteOnly {
|
feat(rbac): tenant member management + invite_only gate (PR 3 of 3, #1303)
Wire the human-facing surface for the tenant-RBAC system that PR 1
introduced and PR 2 enforced: REST endpoints + UI for managing tenant
members, plus the long-pending invite_only registration gate.
Backend
- internal/handler/auth.go: Register now rejects with 403 when
auth.registration_mode=invite_only. PR 1 already exposes the mode via
/auth/config so the frontend hides the sign-up link; this is the
server-side enforcement for direct API calls.
- internal/handler/tenant_member.go: new TenantMemberHandler with
ListMembers / AddMember / UpdateMemberRole / RemoveMember. Maps
service-layer sentinels onto HTTP semantics (ErrLastOwner -> 409,
ErrMembershipAlreadyExists -> 409, ErrUserNotFound on AddMember -> 404,
ErrInvalidTenantRole -> 400). AddMember requires the invitee to
already have an account; SMTP-driven email invites are deferred.
- internal/types/tenant_member.go: new TenantMemberResponse projection
carrying the fields the management UI renders (email, username,
avatar, role, joined_at).
- internal/router/router.go: four routes under /tenants/:id/members
gated per the matrix (Viewer+ for list, Owner+ for every mutation).
- internal/container/container.go: dig provider for the new handler.
Tests
- handler/tenant_member_test.go: 12 table-driven cases covering happy
path, dangling-user tolerance, ErrLastOwner -> 409, ErrMembershipNotFound
-> 404, ErrMembershipAlreadyExists -> 409, unknown email -> 404,
invalid role rejected before user lookup, bad tenant id -> 400.
- handler/auth_register_invite_only_test.go: invite_only -> 403,
self_serve -> 201, nil Auth config falls through.
Frontend
- src/api/tenant/members.ts: typed client (TenantRole/TenantMember/...)
for the four endpoints.
- src/views/settings/TenantMembers.vue: members table with add dialog,
inline role select, confirm-remove modal. All mutation widgets gated
behind currentTenantRole === 'owner'; server still enforces.
- src/views/settings/Settings.vue: register the Members tab; show only
when currentTenantRole is loaded (avoids tab flash on cold nav).
- i18n in en-US/zh-CN/ko-KR/ru-RU: new tenantMember namespace covering
all UI strings and structured error messages (lastOwner / userNotFound
/ alreadyMember / invalidRole etc).
This completes the #1303 RBAC rollout. With cfg.Tenant.EnableRBAC=true
operators now have a full management surface; with EnableRBAC=false
the routes still exist but mutations log-and-pass per PR 2 contract.
2026-05-13 14:23:59 +00:00
|
|
|
|
logger.Warn(ctx, "Registration rejected: auth.registration_mode=invite_only")
|
|
|
|
|
|
appErr := errors.NewForbiddenError("Registration is invite-only")
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-15 18:47:39 +00:00
|
|
|
|
var req types.RegisterRequest
|
|
|
|
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
|
|
|
|
logger.Error(ctx, "Failed to parse registration request parameters", err)
|
|
|
|
|
|
appErr := errors.NewValidationError("Invalid registration parameters").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-11-26 02:50:53 +00:00
|
|
|
|
req.Username = secutils.SanitizeForLog(req.Username)
|
|
|
|
|
|
req.Email = secutils.SanitizeForLog(req.Email)
|
2026-08-06 10:07:02 +00:00
|
|
|
|
// Password is intentionally NOT sanitized: SanitizeForLog replaces
|
|
|
|
|
|
// \n, \r, \t and strips other control characters so a string is safe
|
|
|
|
|
|
// to write into a log line. Applying it to a real password would
|
|
|
|
|
|
// silently rewrite the credential before hashing, so registration
|
|
|
|
|
|
// would succeed but login with the original password would fail.
|
|
|
|
|
|
// Passwords must never be logged, so they don't need that defence.
|
2025-09-15 18:47:39 +00:00
|
|
|
|
|
|
|
|
|
|
// Validate required fields
|
|
|
|
|
|
if req.Username == "" || req.Email == "" || req.Password == "" {
|
|
|
|
|
|
logger.Error(ctx, "Missing required registration fields")
|
|
|
|
|
|
appErr := errors.NewValidationError("Username, email and password are required")
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-11-25 16:57:33 +00:00
|
|
|
|
req.Username = secutils.SanitizeForLog(req.Username)
|
|
|
|
|
|
req.Email = secutils.SanitizeForLog(req.Email)
|
2026-07-13 10:04:14 +00:00
|
|
|
|
req.TenantProvisioning = h.resolveDefaultTenantMode(ctx)
|
2025-09-15 18:47:39 +00:00
|
|
|
|
// Call service to register user
|
|
|
|
|
|
user, err := h.userService.Register(ctx, &req)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to register user: %v", err)
|
2026-03-15 03:09:20 +00:00
|
|
|
|
appErr := errors.NewBadRequestError(err.Error())
|
2025-09-15 18:47:39 +00:00
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Return success response
|
|
|
|
|
|
response := &types.RegisterResponse{
|
|
|
|
|
|
Success: true,
|
|
|
|
|
|
Message: "Registration successful",
|
|
|
|
|
|
User: user,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-11-26 02:50:53 +00:00
|
|
|
|
logger.Infof(ctx, "User registered successfully: %s", secutils.SanitizeForLog(user.Email))
|
2025-09-15 18:47:39 +00:00
|
|
|
|
c.JSON(http.StatusCreated, response)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// Login godoc
|
|
|
|
|
|
// @Summary 用户登录
|
|
|
|
|
|
// @Description 用户登录并获取访问令牌
|
|
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Param request body types.LoginRequest true "登录请求参数"
|
|
|
|
|
|
// @Success 200 {object} types.LoginResponse
|
|
|
|
|
|
// @Failure 401 {object} errors.AppError "认证失败"
|
|
|
|
|
|
// @Router /auth/login [post]
|
2025-09-15 18:47:39 +00:00
|
|
|
|
func (h *AuthHandler) Login(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
|
|
|
|
|
|
logger.Info(ctx, "Start user login")
|
|
|
|
|
|
|
|
|
|
|
|
var req types.LoginRequest
|
|
|
|
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
|
|
|
|
logger.Error(ctx, "Failed to parse login request parameters", err)
|
|
|
|
|
|
appErr := errors.NewValidationError("Invalid login parameters").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-11-26 03:27:48 +00:00
|
|
|
|
email := secutils.SanitizeForLog(req.Email)
|
2025-09-15 18:47:39 +00:00
|
|
|
|
|
|
|
|
|
|
// Validate required fields
|
|
|
|
|
|
if req.Email == "" || req.Password == "" {
|
|
|
|
|
|
logger.Error(ctx, "Missing required login fields")
|
|
|
|
|
|
appErr := errors.NewValidationError("Email and password are required")
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Call service to authenticate user
|
|
|
|
|
|
response, err := h.userService.Login(ctx, &req)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to login user: %v", err)
|
|
|
|
|
|
appErr := errors.NewUnauthorizedError("Login failed").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Check if login was successful
|
|
|
|
|
|
if !response.Success {
|
|
|
|
|
|
logger.Warnf(ctx, "Login failed: %s", response.Message)
|
2026-07-02 04:34:33 +00:00
|
|
|
|
c.JSON(http.StatusUnauthorized, dto.NewAuthLoginResponse(response))
|
2025-09-15 18:47:39 +00:00
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// User is already in the correct format from service
|
|
|
|
|
|
|
2025-11-26 03:27:48 +00:00
|
|
|
|
logger.Infof(ctx, "User logged in successfully, email: %s", email)
|
2026-07-02 04:34:33 +00:00
|
|
|
|
c.JSON(http.StatusOK, dto.NewAuthLoginResponse(response))
|
2025-09-15 18:47:39 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-30 03:13:44 +00:00
|
|
|
|
// GetOIDCAuthorizationURL godoc
|
|
|
|
|
|
// @Summary 获取OIDC授权地址
|
|
|
|
|
|
// @Description 根据后端OIDC配置生成第三方登录跳转地址
|
|
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Param redirect_uri query string true "OIDC回调地址"
|
|
|
|
|
|
// @Success 200 {object} types.OIDCAuthURLResponse
|
|
|
|
|
|
// @Failure 400 {object} errors.AppError "请求参数错误"
|
|
|
|
|
|
// @Failure 403 {object} errors.AppError "OIDC未启用"
|
|
|
|
|
|
// @Router /auth/oidc/url [get]
|
|
|
|
|
|
func (h *AuthHandler) GetOIDCAuthorizationURL(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
redirectURI := strings.TrimSpace(c.Query("redirect_uri"))
|
|
|
|
|
|
if redirectURI == "" {
|
|
|
|
|
|
appErr := errors.NewValidationError("redirect_uri is required")
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
resp, err := h.userService.GetOIDCAuthorizationURL(ctx, redirectURI)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to generate OIDC authorization URL: %v", err)
|
|
|
|
|
|
appErr := errors.NewForbiddenError("OIDC authorization unavailable").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-02 06:49:27 +00:00
|
|
|
|
// Bind the state nonce to this browser so an attacker cannot replay
|
|
|
|
|
|
// their own authorization code into a victim's callback.
|
2026-07-28 07:47:26 +00:00
|
|
|
|
setOIDCNonceCookie(c, resp.Nonce)
|
2026-07-02 06:49:27 +00:00
|
|
|
|
|
2026-03-30 03:13:44 +00:00
|
|
|
|
c.JSON(http.StatusOK, resp)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-28 07:47:26 +00:00
|
|
|
|
// setOIDCNonceCookie binds the OIDC state nonce to this browser so an
|
|
|
|
|
|
// attacker cannot replay their own authorization code into a victim's
|
|
|
|
|
|
// callback. Shared by /auth/oidc/url (JSON) and /auth/oidc/start (302).
|
|
|
|
|
|
func setOIDCNonceCookie(c *gin.Context, nonce string) {
|
|
|
|
|
|
if nonce == "" {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
secure := c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https")
|
|
|
|
|
|
c.SetSameSite(http.SameSiteLaxMode)
|
|
|
|
|
|
c.SetCookie(oidcNonceCookieName, nonce, oidcNonceCookieMaxAge, "/", "", secure, true)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// oidcCallbackURL derives the absolute /auth/oidc/callback URL from the
|
|
|
|
|
|
// request's own origin (scheme + host), so external platforms can deep-link
|
|
|
|
|
|
// to /auth/oidc/start without supplying a redirect_uri.
|
|
|
|
|
|
func oidcCallbackURL(c *gin.Context) string {
|
|
|
|
|
|
scheme := "http"
|
|
|
|
|
|
if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
|
|
|
|
|
|
scheme = "https"
|
|
|
|
|
|
}
|
|
|
|
|
|
return scheme + "://" + c.Request.Host + "/api/v1/auth/oidc/callback"
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// OIDCStart godoc
|
|
|
|
|
|
// @Summary 发起 OIDC 登录(直接 302)
|
|
|
|
|
|
// @Description 与 /auth/oidc/url 不同,此端点直接 302 重定向到 OIDC Provider 的授权页,
|
|
|
|
|
|
// @Description 无需前端 JS 介入。适用于外部平台(如企业门户)直接给出一个链接即可
|
|
|
|
|
|
// @Description 触发 OIDC 授权码流程,借助 IdP 的 SSO session 实现免再次输密码。
|
|
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Success 302
|
|
|
|
|
|
// @Router /auth/oidc/start [get]
|
|
|
|
|
|
func (h *AuthHandler) OIDCStart(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
resp, err := h.userService.GetOIDCAuthorizationURL(ctx, oidcCallbackURL(c))
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to generate OIDC authorization URL: %v", err)
|
|
|
|
|
|
appErr := errors.NewForbiddenError("OIDC authorization unavailable").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
setOIDCNonceCookie(c, resp.Nonce)
|
|
|
|
|
|
c.Redirect(http.StatusFound, resp.AuthorizationURL)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-30 03:13:44 +00:00
|
|
|
|
// GetOIDCConfig godoc
|
|
|
|
|
|
// @Summary 获取OIDC登录配置
|
|
|
|
|
|
// @Description 返回OIDC是否启用以及provider展示名称,供前端决定是否展示OIDC登录入口
|
|
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Success 200 {object} types.OIDCConfigResponse
|
|
|
|
|
|
// @Router /auth/oidc/config [get]
|
|
|
|
|
|
func (h *AuthHandler) GetOIDCConfig(c *gin.Context) {
|
|
|
|
|
|
providerDisplayName := ""
|
|
|
|
|
|
enabled := false
|
|
|
|
|
|
|
|
|
|
|
|
if h.configInfo != nil && h.configInfo.OIDCAuth != nil {
|
|
|
|
|
|
enabled = h.configInfo.OIDCAuth.Enable
|
|
|
|
|
|
providerDisplayName = strings.TrimSpace(h.configInfo.OIDCAuth.ProviderDisplayName)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
c.JSON(http.StatusOK, &types.OIDCConfigResponse{
|
|
|
|
|
|
Success: true,
|
|
|
|
|
|
Enabled: enabled,
|
|
|
|
|
|
ProviderDisplayName: providerDisplayName,
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// OIDCRedirectCallback godoc
|
|
|
|
|
|
// @Summary OIDC登录重定向回调
|
|
|
|
|
|
// @Description 接收OIDC provider回调并由后端完成code交换,随后重定向回前端登录页
|
|
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Param code query string false "OIDC授权码"
|
|
|
|
|
|
// @Param state query string false "OIDC状态"
|
|
|
|
|
|
// @Param error query string false "OIDC错误码"
|
|
|
|
|
|
// @Success 302
|
|
|
|
|
|
// @Router /auth/oidc/callback [get]
|
|
|
|
|
|
func (h *AuthHandler) OIDCRedirectCallback(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
frontendRedirectURI := "/"
|
|
|
|
|
|
|
|
|
|
|
|
if providerError := strings.TrimSpace(c.Query("error")); providerError != "" {
|
|
|
|
|
|
redirectURL := frontendRedirectURI + "#oidc_error=" + urlQueryEscape(providerError)
|
|
|
|
|
|
if description := strings.TrimSpace(c.Query("error_description")); description != "" {
|
|
|
|
|
|
redirectURL += "&oidc_error_description=" + urlQueryEscape(description)
|
|
|
|
|
|
}
|
|
|
|
|
|
c.Redirect(http.StatusFound, redirectURL)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
state := strings.TrimSpace(c.Query("state"))
|
2026-07-02 06:49:27 +00:00
|
|
|
|
decodedState, err := decodeOIDCState(state, c.Request)
|
2026-03-30 03:13:44 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to decode OIDC state: %v", err)
|
|
|
|
|
|
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("invalid_state"))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2026-07-02 06:49:27 +00:00
|
|
|
|
// One-time use: clear the binding cookie as soon as it is checked.
|
|
|
|
|
|
c.SetCookie(oidcNonceCookieName, "", -1, "/", "", false, true)
|
2026-03-30 03:13:44 +00:00
|
|
|
|
|
|
|
|
|
|
code := strings.TrimSpace(c.Query("code"))
|
|
|
|
|
|
if code == "" {
|
|
|
|
|
|
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("missing_code"))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-13 10:26:18 +00:00
|
|
|
|
resp, err := h.userService.LoginWithOIDC(ctx, code, strings.TrimSpace(decodedState.RedirectURI), h.resolveDefaultTenantMode(ctx))
|
2026-03-30 03:13:44 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to complete OIDC login via redirect callback: %v", err)
|
|
|
|
|
|
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("login_failed")+"&oidc_error_description="+urlQueryEscape(err.Error()))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
if !resp.Success {
|
|
|
|
|
|
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("login_failed")+"&oidc_error_description="+urlQueryEscape(resp.Message))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
payload, err := encodeOIDCCallbackPayload(resp)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to encode OIDC callback payload: %v", err)
|
|
|
|
|
|
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("payload_encode_failed"))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_result="+urlQueryEscape(payload))
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func encodeOIDCCallbackPayload(resp *types.OIDCCallbackResponse) (string, error) {
|
2026-07-02 04:34:33 +00:00
|
|
|
|
payload, err := json.Marshal(dto.NewAuthOIDCCallbackResponse(resp))
|
2026-03-30 03:13:44 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return "", err
|
|
|
|
|
|
}
|
|
|
|
|
|
return base64.RawURLEncoding.EncodeToString(payload), nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
type oidcStatePayload struct {
|
2026-07-02 06:49:27 +00:00
|
|
|
|
Nonce string
|
|
|
|
|
|
RedirectURI string
|
2026-03-30 03:13:44 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-02 06:49:27 +00:00
|
|
|
|
func decodeOIDCState(raw string, req *http.Request) (*oidcStatePayload, error) {
|
|
|
|
|
|
payload, err := secutils.VerifyOIDCState(raw)
|
2026-03-30 03:13:44 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
}
|
2026-07-02 06:49:27 +00:00
|
|
|
|
cookieNonce, err := req.Cookie(oidcNonceCookieName)
|
|
|
|
|
|
if err != nil || cookieNonce == nil || strings.TrimSpace(cookieNonce.Value) == "" {
|
|
|
|
|
|
return nil, errors.NewValidationError("oidc nonce cookie missing")
|
2026-03-30 03:13:44 +00:00
|
|
|
|
}
|
2026-07-02 06:49:27 +00:00
|
|
|
|
if cookieNonce.Value != payload.Nonce {
|
|
|
|
|
|
return nil, errors.NewValidationError("oidc nonce mismatch")
|
2026-03-30 03:13:44 +00:00
|
|
|
|
}
|
2026-07-02 06:49:27 +00:00
|
|
|
|
return &oidcStatePayload{
|
|
|
|
|
|
Nonce: payload.Nonce,
|
|
|
|
|
|
RedirectURI: strings.TrimSpace(payload.RedirectURI),
|
|
|
|
|
|
}, nil
|
2026-03-30 03:13:44 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func urlQueryEscape(value string) string {
|
|
|
|
|
|
replacer := strings.NewReplacer(
|
|
|
|
|
|
"%", "%25",
|
|
|
|
|
|
" ", "%20",
|
|
|
|
|
|
"#", "%23",
|
|
|
|
|
|
"&", "%26",
|
|
|
|
|
|
"+", "%2B",
|
|
|
|
|
|
"=", "%3D",
|
|
|
|
|
|
"?", "%3F",
|
|
|
|
|
|
)
|
|
|
|
|
|
return replacer.Replace(value)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// Logout godoc
|
|
|
|
|
|
// @Summary 用户登出
|
|
|
|
|
|
// @Description 撤销当前访问令牌并登出
|
|
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Success 200 {object} map[string]interface{} "登出成功"
|
|
|
|
|
|
// @Failure 400 {object} errors.AppError "请求参数错误"
|
|
|
|
|
|
// @Security Bearer
|
|
|
|
|
|
// @Router /auth/logout [post]
|
2025-09-15 18:47:39 +00:00
|
|
|
|
func (h *AuthHandler) Logout(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
|
|
|
|
|
|
logger.Info(ctx, "Start user logout")
|
|
|
|
|
|
|
|
|
|
|
|
// Extract token from Authorization header
|
|
|
|
|
|
authHeader := c.GetHeader("Authorization")
|
|
|
|
|
|
if authHeader == "" {
|
|
|
|
|
|
logger.Error(ctx, "Missing Authorization header")
|
|
|
|
|
|
appErr := errors.NewValidationError("Authorization header is required")
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Parse Bearer token
|
|
|
|
|
|
tokenParts := strings.Split(authHeader, " ")
|
|
|
|
|
|
if len(tokenParts) != 2 || tokenParts[0] != "Bearer" {
|
|
|
|
|
|
logger.Error(ctx, "Invalid Authorization header format")
|
|
|
|
|
|
appErr := errors.NewValidationError("Invalid Authorization header format")
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
token := tokenParts[1]
|
|
|
|
|
|
|
2026-07-02 07:26:43 +00:00
|
|
|
|
// Revoke every outstanding session for this user so refresh tokens
|
|
|
|
|
|
// cannot keep working after logout.
|
|
|
|
|
|
err := h.userService.Logout(ctx, token)
|
2025-09-15 18:47:39 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to revoke token: %v", err)
|
|
|
|
|
|
appErr := errors.NewInternalServerError("Logout failed").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
logger.Info(ctx, "User logged out successfully")
|
|
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
|
|
|
|
"success": true,
|
|
|
|
|
|
"message": "Logout successful",
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// RefreshToken godoc
|
|
|
|
|
|
// @Summary 刷新令牌
|
|
|
|
|
|
// @Description 使用刷新令牌获取新的访问令牌
|
|
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Param request body object{refreshToken=string} true "刷新令牌"
|
|
|
|
|
|
// @Success 200 {object} map[string]interface{} "新令牌"
|
|
|
|
|
|
// @Failure 401 {object} errors.AppError "令牌无效"
|
|
|
|
|
|
// @Router /auth/refresh [post]
|
2025-09-15 18:47:39 +00:00
|
|
|
|
func (h *AuthHandler) RefreshToken(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
|
|
|
|
|
|
logger.Info(ctx, "Start token refresh")
|
|
|
|
|
|
|
|
|
|
|
|
var req struct {
|
|
|
|
|
|
RefreshToken string `json:"refreshToken" binding:"required"`
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
|
|
|
|
logger.Error(ctx, "Failed to parse refresh token request", err)
|
|
|
|
|
|
appErr := errors.NewValidationError("Invalid refresh token request").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Call service to refresh token
|
|
|
|
|
|
accessToken, newRefreshToken, err := h.userService.RefreshToken(ctx, req.RefreshToken)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to refresh token: %v", err)
|
|
|
|
|
|
appErr := errors.NewUnauthorizedError("Token refresh failed").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
logger.Info(ctx, "Token refreshed successfully")
|
|
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
|
|
|
|
"success": true,
|
|
|
|
|
|
"message": "Token refreshed successfully",
|
|
|
|
|
|
"access_token": accessToken,
|
|
|
|
|
|
"refresh_token": newRefreshToken,
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// GetCurrentUser godoc
|
|
|
|
|
|
// @Summary 获取当前用户信息
|
|
|
|
|
|
// @Description 获取当前登录用户的详细信息
|
|
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Success 200 {object} map[string]interface{} "用户信息"
|
|
|
|
|
|
// @Failure 401 {object} errors.AppError "未授权"
|
|
|
|
|
|
// @Security Bearer
|
|
|
|
|
|
// @Router /auth/me [get]
|
2025-09-15 18:47:39 +00:00
|
|
|
|
func (h *AuthHandler) GetCurrentUser(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
|
|
|
|
|
|
// Get current user from service (which extracts from context)
|
|
|
|
|
|
user, err := h.userService.GetCurrentUser(ctx)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to get current user: %v", err)
|
|
|
|
|
|
appErr := errors.NewUnauthorizedError("Failed to get user information").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
fix(rbac): role-aware UI gates leaked write affordances after tenant switch
When an Owner of tenant A invited user B as a Viewer, B could log in,
switch the active tenant from B's home to A via the user menu, and
still see every write button — Create KB, Upload Document, Edit/Delete
agent — because the role-gate plumbing on the client was wired to the
wrong tenant. The server's RBAC enforcement (PR 2 / PR 5) still blocked
the actual mutations with 403, so no data leaked, but the UI presented
authority the user did not have, which is a confusing and embarrassing
defect.
Five distinct root causes, all on the client / server boundary:
1. `currentTenantRole` (frontend/src/stores/auth.ts) read
`tenant.value.id` — the user's *home* tenant — instead of the active
tenant id. After switching to A, the helper still returned B's home
role (Owner), so every `hasRole(...)` gate in the codebase silently
short-circuited. Fix: read `selectedTenantId` first, fall back to
`tenant.id`.
2. `setMemberships` was only called once, on /auth/login. Hard reloads
(which the tenant switcher triggers) re-ran `getCurrentUser()` via
`App.vue` and `router/index.ts`, but those callers discarded the
`memberships` field of the response, so the auth store kept the
login-time snapshot forever. Role changes between sessions stayed
invisible. Fix: extract memberships in both /auth/me consumers and
feed them into `setMemberships`.
3. `KnowledgeBase.vue`'s `isOwner` compared `kb.tenant_id` to the
active tenant id, so any KB inside the current tenant was treated
as "owned by the caller" — bypassing every role gate below. Fix:
compare against `kb.creator_id` (the field PR 5 introduced) and
require an actual creator match. `canEdit` / `canManage` now layer
`hasRole('admin')` on top so a non-creator with sufficient role can
still manage.
4. `KnowledgeBaseList.vue` and `AgentList.vue` rendered the per-card
more-menu (Settings, Delete, Edit) unconditionally. With the
ownership column from PR 5 this is straightforward to gate on the
client: Settings/Delete now require creator-match or `hasRole('admin')`
per the server's `OwnedKBOrAdmin` / `OwnedAgentOrAdmin` matrix.
5. The axios interceptor (frontend/src/utils/request.ts) had a
"selectedTenantId === defaultTenantId → don't attach X-Tenant-ID"
short-circuit. Any code that wrote the active tenant into
`weknora_tenant` (UserMenu's loadUserInfo, OIDC sync, router
hydrate) made the two values equal, after which the header silently
stopped attaching and subsequent navigation requests landed on the
home tenant. Fix: drop the short-circuit; always attach when
selectedTenantId is set.
Server-side, /auth/me read `user.TenantID` (the immutable home tenant
id stamped at signup) when fetching the tenant for the response, so
the `tenant` field always pointed at home even after the auth
middleware had already resolved an active tenant from X-Tenant-ID.
The frontend then re-keyed `authStore.tenant` to the home tenant on
every refresh, undoing the switch. Fix: read the active tenant id from
context (`types.TenantIDFromContext(ctx)`) and only fall back to
user.TenantID when context is unset.
The server-side enforcement was correct throughout — every fix here is
purely about not lying to the user with the rendered UI.
2026-05-14 13:55:22 +00:00
|
|
|
|
// Get tenant information for the *active* tenant (the one the
|
|
|
|
|
|
// auth middleware resolved against the X-Tenant-ID header), not
|
|
|
|
|
|
// the user's home tenant. user.TenantID is the row stored on the
|
|
|
|
|
|
// users table at signup time and never changes; reading it here
|
|
|
|
|
|
// would make /auth/me always return the home tenant even after
|
|
|
|
|
|
// the user switched into a peer tenant. The frontend then re-keys
|
|
|
|
|
|
// `authStore.tenant.id` to the home tenant, and every UI gate
|
|
|
|
|
|
// computed against it (currentTenantRole, isOwner, ...) leaks
|
|
|
|
|
|
// the wrong role. Pull the active tenant id from context instead.
|
2025-09-16 07:39:34 +00:00
|
|
|
|
var tenant *types.Tenant
|
fix(rbac): role-aware UI gates leaked write affordances after tenant switch
When an Owner of tenant A invited user B as a Viewer, B could log in,
switch the active tenant from B's home to A via the user menu, and
still see every write button — Create KB, Upload Document, Edit/Delete
agent — because the role-gate plumbing on the client was wired to the
wrong tenant. The server's RBAC enforcement (PR 2 / PR 5) still blocked
the actual mutations with 403, so no data leaked, but the UI presented
authority the user did not have, which is a confusing and embarrassing
defect.
Five distinct root causes, all on the client / server boundary:
1. `currentTenantRole` (frontend/src/stores/auth.ts) read
`tenant.value.id` — the user's *home* tenant — instead of the active
tenant id. After switching to A, the helper still returned B's home
role (Owner), so every `hasRole(...)` gate in the codebase silently
short-circuited. Fix: read `selectedTenantId` first, fall back to
`tenant.id`.
2. `setMemberships` was only called once, on /auth/login. Hard reloads
(which the tenant switcher triggers) re-ran `getCurrentUser()` via
`App.vue` and `router/index.ts`, but those callers discarded the
`memberships` field of the response, so the auth store kept the
login-time snapshot forever. Role changes between sessions stayed
invisible. Fix: extract memberships in both /auth/me consumers and
feed them into `setMemberships`.
3. `KnowledgeBase.vue`'s `isOwner` compared `kb.tenant_id` to the
active tenant id, so any KB inside the current tenant was treated
as "owned by the caller" — bypassing every role gate below. Fix:
compare against `kb.creator_id` (the field PR 5 introduced) and
require an actual creator match. `canEdit` / `canManage` now layer
`hasRole('admin')` on top so a non-creator with sufficient role can
still manage.
4. `KnowledgeBaseList.vue` and `AgentList.vue` rendered the per-card
more-menu (Settings, Delete, Edit) unconditionally. With the
ownership column from PR 5 this is straightforward to gate on the
client: Settings/Delete now require creator-match or `hasRole('admin')`
per the server's `OwnedKBOrAdmin` / `OwnedAgentOrAdmin` matrix.
5. The axios interceptor (frontend/src/utils/request.ts) had a
"selectedTenantId === defaultTenantId → don't attach X-Tenant-ID"
short-circuit. Any code that wrote the active tenant into
`weknora_tenant` (UserMenu's loadUserInfo, OIDC sync, router
hydrate) made the two values equal, after which the header silently
stopped attaching and subsequent navigation requests landed on the
home tenant. Fix: drop the short-circuit; always attach when
selectedTenantId is set.
Server-side, /auth/me read `user.TenantID` (the immutable home tenant
id stamped at signup) when fetching the tenant for the response, so
the `tenant` field always pointed at home even after the auth
middleware had already resolved an active tenant from X-Tenant-ID.
The frontend then re-keyed `authStore.tenant` to the home tenant on
every refresh, undoing the switch. Fix: read the active tenant id from
context (`types.TenantIDFromContext(ctx)`) and only fall back to
user.TenantID when context is unset.
The server-side enforcement was correct throughout — every fix here is
purely about not lying to the user with the rendered UI.
2026-05-14 13:55:22 +00:00
|
|
|
|
activeTenantID, _ := types.TenantIDFromContext(ctx)
|
|
|
|
|
|
if activeTenantID == 0 {
|
|
|
|
|
|
activeTenantID = user.TenantID
|
|
|
|
|
|
}
|
|
|
|
|
|
if activeTenantID > 0 {
|
|
|
|
|
|
tenant, err = h.tenantService.GetTenantByID(ctx, activeTenantID)
|
2025-09-16 07:39:34 +00:00
|
|
|
|
if err != nil {
|
fix(rbac): role-aware UI gates leaked write affordances after tenant switch
When an Owner of tenant A invited user B as a Viewer, B could log in,
switch the active tenant from B's home to A via the user menu, and
still see every write button — Create KB, Upload Document, Edit/Delete
agent — because the role-gate plumbing on the client was wired to the
wrong tenant. The server's RBAC enforcement (PR 2 / PR 5) still blocked
the actual mutations with 403, so no data leaked, but the UI presented
authority the user did not have, which is a confusing and embarrassing
defect.
Five distinct root causes, all on the client / server boundary:
1. `currentTenantRole` (frontend/src/stores/auth.ts) read
`tenant.value.id` — the user's *home* tenant — instead of the active
tenant id. After switching to A, the helper still returned B's home
role (Owner), so every `hasRole(...)` gate in the codebase silently
short-circuited. Fix: read `selectedTenantId` first, fall back to
`tenant.id`.
2. `setMemberships` was only called once, on /auth/login. Hard reloads
(which the tenant switcher triggers) re-ran `getCurrentUser()` via
`App.vue` and `router/index.ts`, but those callers discarded the
`memberships` field of the response, so the auth store kept the
login-time snapshot forever. Role changes between sessions stayed
invisible. Fix: extract memberships in both /auth/me consumers and
feed them into `setMemberships`.
3. `KnowledgeBase.vue`'s `isOwner` compared `kb.tenant_id` to the
active tenant id, so any KB inside the current tenant was treated
as "owned by the caller" — bypassing every role gate below. Fix:
compare against `kb.creator_id` (the field PR 5 introduced) and
require an actual creator match. `canEdit` / `canManage` now layer
`hasRole('admin')` on top so a non-creator with sufficient role can
still manage.
4. `KnowledgeBaseList.vue` and `AgentList.vue` rendered the per-card
more-menu (Settings, Delete, Edit) unconditionally. With the
ownership column from PR 5 this is straightforward to gate on the
client: Settings/Delete now require creator-match or `hasRole('admin')`
per the server's `OwnedKBOrAdmin` / `OwnedAgentOrAdmin` matrix.
5. The axios interceptor (frontend/src/utils/request.ts) had a
"selectedTenantId === defaultTenantId → don't attach X-Tenant-ID"
short-circuit. Any code that wrote the active tenant into
`weknora_tenant` (UserMenu's loadUserInfo, OIDC sync, router
hydrate) made the two values equal, after which the header silently
stopped attaching and subsequent navigation requests landed on the
home tenant. Fix: drop the short-circuit; always attach when
selectedTenantId is set.
Server-side, /auth/me read `user.TenantID` (the immutable home tenant
id stamped at signup) when fetching the tenant for the response, so
the `tenant` field always pointed at home even after the auth
middleware had already resolved an active tenant from X-Tenant-ID.
The frontend then re-keyed `authStore.tenant` to the home tenant on
every refresh, undoing the switch. Fix: read the active tenant id from
context (`types.TenantIDFromContext(ctx)`) and only fall back to
user.TenantID when context is unset.
The server-side enforcement was correct throughout — every fix here is
purely about not lying to the user with the rendered UI.
2026-05-14 13:55:22 +00:00
|
|
|
|
logger.Warnf(ctx, "Failed to get tenant info for user %s, tenant ID %d: %v", user.Email, activeTenantID, err)
|
2025-09-16 07:39:34 +00:00
|
|
|
|
// Don't fail the request if tenant info is not available
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-12-03 03:11:57 +00:00
|
|
|
|
userInfo := user.ToUserInfo()
|
|
|
|
|
|
userInfo.CanAccessAllTenants = user.CanAccessAllTenants && h.configInfo.Tenant.EnableCrossTenantAccess
|
refactor(rbac): address PR 1 review feedback
Tighten correctness, security and observability of the tenant RBAC
foundation introduced in 3c4cdd70 in response to internal review.
Bugfixes
- custom_agents.runnable_by_viewer: drop the GORM `default:true` tag.
GORM treats a plain bool's zero value as "unspecified" and silently
rewrites it to the column default on insert, which would prevent
admins from ever creating an agent with viewer-runtime disabled. The
column-level DEFAULT TRUE on the database side still backstops rows
inserted by raw SQL / migrations.
- TenantMemberRepository.HasAnyMembers: replace `Limit(1).Count(&n)`
with `Take(&probe)`. GORM's Count ignores Limit and scans the whole
table, which matters because this runs on the auth middleware's
hot path for users without a cached membership.
- service/user.LoginWithOIDC: include User, Tenant and Memberships in
the OIDCCallbackResponse so the OIDC flow returns the same shape as
password login (previously User and friends were left nil).
Security
- middleware/auth.resolveTenantRole: restrict orphan-tenant
auto-promotion to the caller's home tenant. Cross-tenant superuser
visits and JWTs minted for foreign tenants no longer trigger silent
Owner grants. Two regression tests pin the new behaviour.
- service/user.synthFallbackMembership: default the synthesised role
to Viewer instead of Owner. The login response only feeds UI; the
backend re-derives the real role from tenant_members on every
request, so showing a Viewer UI is preferable to a misleading Owner
UI that would surface admin controls the backend will then 403.
- migrations/versioned/000043_tenant_rbac.down.sql: gate the destructive
drop behind a `weknora.allow_destructive_migration` GUC so an
accidental `migrate down` cannot wipe role data in production.
- frontend/src/stores/auth.ts: comment currentTenantRole as
rendering-only so future PRs cannot mistake the localStorage-backed
value for an authorisation signal.
API contract
- Memberships in LoginResponse and OIDCCallbackResponse now serialises
without omitempty, and buildMembershipsForUser / synthFallbackMembership
always return a non-nil slice — frontend can rely on JSON `[]`.
- handler/auth.GetCurrentUser includes memberships so /auth/me refreshes
recover currentTenantRole after a page reload.
Performance
- Add TenantService.GetTenantsByIDs (with the matching repo method) and
use it inside buildMembershipsForUser to batch tenant-name lookups
instead of issuing one query per membership.
Observability
- Replace the remaining `log.Printf` calls in middleware/auth with
contextual logger.Warnf / logger.Infof so role resolution events ride
the standard request-id / Langfuse trace plumbing. The successful
auto-promote line is tagged `[audit]` for log mining.
Tests
- internal/application/service/tenant_member_test.go: hand-rolled
fakeTenantMemberRepo plus 11 cases covering AddMember validation,
EnsureOwner idempotence, "cannot demote/remove the last Owner",
same-role no-op, ErrInvalidTenantRole / ErrMembershipNotFound, and
the TenantRole.HasPermission lattice.
- internal/middleware/auth_role_test.go: fakeMemberService plus 8 cases
pinning every branch of resolveTenantRole, including the two H1
regressions (cross-tenant superuser must not auto-promote; orphan
auto-promote requires the home tenant).
2026-05-13 12:24:55 +00:00
|
|
|
|
// 同步返回当前用户的 memberships,让前端在页面刷新(仅命中 /auth/me)
|
|
|
|
|
|
// 后也能恢复 currentTenantRole,避免角色信息只在 login 那一刻可用。
|
|
|
|
|
|
memberships := h.userService.BuildLoginMemberships(ctx, user, tenant)
|
2026-07-13 10:04:14 +00:00
|
|
|
|
canCreateTenant := user.CanAccessAllTenants ||
|
|
|
|
|
|
resolveTenantSelfServiceCreationEnabled(ctx, h.configInfo, h.systemSettingSvc)
|
feat(invitation): add auto-accept switch for inviting registered users
Add a global tenant switch (tenant.auto_accept_invitation /
WEKNORA_TENANT_AUTO_ACCEPT_INVITATION, default false). When enabled,
inviting an already-registered user adds them to the tenant as an
active member immediately, instead of creating a pending invitation
the invitee must accept from their inbox.
Backend:
- CreateInvitation reads the switch and, when on, calls the new shared
addMemberAndRespond helper (extracted from TenantMemberHandler.AddMember)
to persist the member and write the HTTP response. Both call sites
share it so the sentinel->status mapping can't drift apart.
- Register the setting in the system_setting registry (bool, default
false).
- Expose the switch as capabilities.auto_accept_invitation on
GET /auth/me, so the SPA can adapt the invite popup without calling
the super-admin settings API.
- Cover enabled/disabled, already-a-member, unknown email, owner role
rejection, and nil member service with unit tests.
Frontend:
- The invite popup adapts to the mode. With auto-accept, the form
submits directly (button reads "Send", no "confirm invitation" step)
and refreshes the member roster silently (no toast; the new row is
the feedback). The classic two-step flow is unchanged when off.
- Fix capabilities hydration: refreshFromAuthMe (the only reader of
/auth/me capabilities) was invoked solely from the invitation-token
flow, so on page reload can_create_tenant and auto_accept_invitation
stayed at their initial false. Trigger it from initFromStorage once a
token is restored so deployment switches are reconciled with the live
server.
2026-08-10 05:45:02 +00:00
|
|
|
|
autoAcceptInvitation := h.systemSettingSvc != nil &&
|
|
|
|
|
|
h.systemSettingSvc.GetBool(ctx, "tenant.auto_accept_invitation", "WEKNORA_TENANT_AUTO_ACCEPT_INVITATION", false)
|
2025-09-15 18:47:39 +00:00
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
|
|
|
|
"success": true,
|
2025-09-16 07:39:34 +00:00
|
|
|
|
"data": gin.H{
|
2026-07-13 10:04:14 +00:00
|
|
|
|
"user": userInfo,
|
|
|
|
|
|
"tenant": dto.NewTenantResponse(ctx, tenant),
|
|
|
|
|
|
"memberships": memberships,
|
|
|
|
|
|
"tenant_required": tenant == nil,
|
|
|
|
|
|
"capabilities": gin.H{
|
feat(invitation): add auto-accept switch for inviting registered users
Add a global tenant switch (tenant.auto_accept_invitation /
WEKNORA_TENANT_AUTO_ACCEPT_INVITATION, default false). When enabled,
inviting an already-registered user adds them to the tenant as an
active member immediately, instead of creating a pending invitation
the invitee must accept from their inbox.
Backend:
- CreateInvitation reads the switch and, when on, calls the new shared
addMemberAndRespond helper (extracted from TenantMemberHandler.AddMember)
to persist the member and write the HTTP response. Both call sites
share it so the sentinel->status mapping can't drift apart.
- Register the setting in the system_setting registry (bool, default
false).
- Expose the switch as capabilities.auto_accept_invitation on
GET /auth/me, so the SPA can adapt the invite popup without calling
the super-admin settings API.
- Cover enabled/disabled, already-a-member, unknown email, owner role
rejection, and nil member service with unit tests.
Frontend:
- The invite popup adapts to the mode. With auto-accept, the form
submits directly (button reads "Send", no "confirm invitation" step)
and refreshes the member roster silently (no toast; the new row is
the feedback). The classic two-step flow is unchanged when off.
- Fix capabilities hydration: refreshFromAuthMe (the only reader of
/auth/me capabilities) was invoked solely from the invitation-token
flow, so on page reload can_create_tenant and auto_accept_invitation
stayed at their initial false. Trigger it from initFromStorage once a
token is restored so deployment switches are reconciled with the live
server.
2026-08-10 05:45:02 +00:00
|
|
|
|
"can_create_tenant": canCreateTenant,
|
|
|
|
|
|
"auto_accept_invitation": autoAcceptInvitation,
|
2026-07-13 10:04:14 +00:00
|
|
|
|
},
|
2025-09-16 07:39:34 +00:00
|
|
|
|
},
|
2025-09-15 18:47:39 +00:00
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-18 03:21:55 +00:00
|
|
|
|
// updateMyPreferencesRequest is the body for PUT /auth/me/preferences.
|
|
|
|
|
|
// Fields are pointers so the handler can distinguish "key not present"
|
|
|
|
|
|
// (preserve existing value) from "explicit false". See
|
|
|
|
|
|
// types.UserPreferences for the persistence-layer counterpart.
|
|
|
|
|
|
type updateMyPreferencesRequest struct {
|
feat(tenant): remember user's last-active workspace across logins
Until now a fresh login (new device, expired refresh token, cleared
browser) always dropped the user into their home tenant, even if they
spend most of their time in a peer workspace. The session-local
X-Tenant-ID override in localStorage gave a "same browser sticky"
effect, but never crossed devices or new sessions.
This adds a small server-side preference, `users.preferences.
last_active_tenant_id`, persisted in the existing jsonb column (no
new migration), and threads it through:
* Backend
* `UserPreferences` gains `LastActiveTenantID *uint64` with sentinel
semantics (`*0` from the PATCH endpoint = clear preference).
* `resolveLoginTenantID` validates the stored id (tenant still
exists + active membership, or CanAccessAllTenants) and falls
back to home on any failure, best-effort clearing the stale
preference so subsequent logins don't pay for it again.
* `Login` and `LoginWithOIDC` resolve once and use the result for
both the JWT `tenant_id` claim and the returned `active_tenant`,
keeping the two in sync. `RefreshToken` rides through
`GenerateTokens` so refresh rotations also land the user back in
their preferred tenant instead of bouncing to home.
* `UpdateUserPreferences` learns to merge the new key.
* `PUT /auth/me/preferences` accepts the new field.
* Frontend
* `Login.vue` now writes the user's HOME tenant id into
`user.tenant_id` (matching the field's documented semantics) and
expresses any active-vs-home divergence via `setSelectedTenant`,
so `useHomeTenant` and the "current"/"home" badges stay correct
after the backend honours a remembered preference. `App.vue`'s
OIDC sync does the same reconciliation.
* `TenantSelector`, `UserMenu` and the post-tenant-create handlers
fire `persistLastActiveTenantPreference` after every successful
user-initiated switch (switching to home sends `0` to clear).
The call is raced against the existing reload-grace window so
most writes finish before the page tears down; lost writes are
recoverable on the next switch.
No new UI. Users will simply notice that, after re-logging in on
another device, they land back in the workspace they were last
using rather than always in their home tenant.
Note: `make docs` is unrelated-broken on `main` (audit_log.go
references `errors.AppError` which swag can't resolve), so the
Swagger artifacts under docs/ are intentionally not regenerated
in this PR. The handler code is the source of truth.
2026-05-18 11:48:59 +00:00
|
|
|
|
// LastActiveTenantID lets the SPA persist "after a fresh login,
|
|
|
|
|
|
// drop me back into this workspace" across devices. Send a positive
|
2026-07-14 08:13:49 +00:00
|
|
|
|
// workspace id to set / replace, or 0 to clear. Membership is validated
|
feat(tenant): remember user's last-active workspace across logins
Until now a fresh login (new device, expired refresh token, cleared
browser) always dropped the user into their home tenant, even if they
spend most of their time in a peer workspace. The session-local
X-Tenant-ID override in localStorage gave a "same browser sticky"
effect, but never crossed devices or new sessions.
This adds a small server-side preference, `users.preferences.
last_active_tenant_id`, persisted in the existing jsonb column (no
new migration), and threads it through:
* Backend
* `UserPreferences` gains `LastActiveTenantID *uint64` with sentinel
semantics (`*0` from the PATCH endpoint = clear preference).
* `resolveLoginTenantID` validates the stored id (tenant still
exists + active membership, or CanAccessAllTenants) and falls
back to home on any failure, best-effort clearing the stale
preference so subsequent logins don't pay for it again.
* `Login` and `LoginWithOIDC` resolve once and use the result for
both the JWT `tenant_id` claim and the returned `active_tenant`,
keeping the two in sync. `RefreshToken` rides through
`GenerateTokens` so refresh rotations also land the user back in
their preferred tenant instead of bouncing to home.
* `UpdateUserPreferences` learns to merge the new key.
* `PUT /auth/me/preferences` accepts the new field.
* Frontend
* `Login.vue` now writes the user's HOME tenant id into
`user.tenant_id` (matching the field's documented semantics) and
expresses any active-vs-home divergence via `setSelectedTenant`,
so `useHomeTenant` and the "current"/"home" badges stay correct
after the backend honours a remembered preference. `App.vue`'s
OIDC sync does the same reconciliation.
* `TenantSelector`, `UserMenu` and the post-tenant-create handlers
fire `persistLastActiveTenantPreference` after every successful
user-initiated switch (switching to home sends `0` to clear).
The call is raced against the existing reload-grace window so
most writes finish before the page tears down; lost writes are
recoverable on the next switch.
No new UI. Users will simply notice that, after re-logging in on
another device, they land back in the workspace they were last
using rather than always in their home tenant.
Note: `make docs` is unrelated-broken on `main` (audit_log.go
references `errors.AppError` which swag can't resolve), so the
Swagger artifacts under docs/ are intentionally not regenerated
in this PR. The handler code is the source of truth.
2026-05-18 11:48:59 +00:00
|
|
|
|
// at next login, not here. Nil = field omitted from the PATCH and
|
|
|
|
|
|
// stays untouched.
|
|
|
|
|
|
LastActiveTenantID *uint64 `json:"last_active_tenant_id"`
|
2026-05-18 03:21:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// UpdateMyPreferences godoc
|
|
|
|
|
|
// @Summary 更新当前用户的个性化设置
|
|
|
|
|
|
// @Description 按 PATCH 语义合并用户偏好(仅覆盖请求体里出现的字段,其余字段保持不变),
|
|
|
|
|
|
// @Description 数据存放在 users.preferences (JSON),跨设备/浏览器自动同步。
|
|
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Param request body updateMyPreferencesRequest true "Preferences patch"
|
|
|
|
|
|
// @Success 200 {object} map[string]interface{} "更新后的偏好"
|
|
|
|
|
|
// @Failure 400 {object} errors.AppError "请求参数错误"
|
|
|
|
|
|
// @Failure 401 {object} errors.AppError "未授权"
|
|
|
|
|
|
// @Security Bearer
|
|
|
|
|
|
// @Router /auth/me/preferences [put]
|
|
|
|
|
|
func (h *AuthHandler) UpdateMyPreferences(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
|
|
|
|
|
|
user, err := h.userService.GetCurrentUser(ctx)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
appErr := errors.NewUnauthorizedError("Failed to get user information").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
var req updateMyPreferencesRequest
|
|
|
|
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
|
|
|
|
appErr := errors.NewValidationError("Invalid preferences request").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
patch := types.UserPreferences{
|
feat(tenant): remember user's last-active workspace across logins
Until now a fresh login (new device, expired refresh token, cleared
browser) always dropped the user into their home tenant, even if they
spend most of their time in a peer workspace. The session-local
X-Tenant-ID override in localStorage gave a "same browser sticky"
effect, but never crossed devices or new sessions.
This adds a small server-side preference, `users.preferences.
last_active_tenant_id`, persisted in the existing jsonb column (no
new migration), and threads it through:
* Backend
* `UserPreferences` gains `LastActiveTenantID *uint64` with sentinel
semantics (`*0` from the PATCH endpoint = clear preference).
* `resolveLoginTenantID` validates the stored id (tenant still
exists + active membership, or CanAccessAllTenants) and falls
back to home on any failure, best-effort clearing the stale
preference so subsequent logins don't pay for it again.
* `Login` and `LoginWithOIDC` resolve once and use the result for
both the JWT `tenant_id` claim and the returned `active_tenant`,
keeping the two in sync. `RefreshToken` rides through
`GenerateTokens` so refresh rotations also land the user back in
their preferred tenant instead of bouncing to home.
* `UpdateUserPreferences` learns to merge the new key.
* `PUT /auth/me/preferences` accepts the new field.
* Frontend
* `Login.vue` now writes the user's HOME tenant id into
`user.tenant_id` (matching the field's documented semantics) and
expresses any active-vs-home divergence via `setSelectedTenant`,
so `useHomeTenant` and the "current"/"home" badges stay correct
after the backend honours a remembered preference. `App.vue`'s
OIDC sync does the same reconciliation.
* `TenantSelector`, `UserMenu` and the post-tenant-create handlers
fire `persistLastActiveTenantPreference` after every successful
user-initiated switch (switching to home sends `0` to clear).
The call is raced against the existing reload-grace window so
most writes finish before the page tears down; lost writes are
recoverable on the next switch.
No new UI. Users will simply notice that, after re-logging in on
another device, they land back in the workspace they were last
using rather than always in their home tenant.
Note: `make docs` is unrelated-broken on `main` (audit_log.go
references `errors.AppError` which swag can't resolve), so the
Swagger artifacts under docs/ are intentionally not regenerated
in this PR. The handler code is the source of truth.
2026-05-18 11:48:59 +00:00
|
|
|
|
LastActiveTenantID: req.LastActiveTenantID,
|
2026-05-18 03:21:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
prefs, err := h.userService.UpdateUserPreferences(ctx, user.ID, patch)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to update preferences for user %s: %v", user.Email, err)
|
|
|
|
|
|
appErr := errors.NewBadRequestError("Failed to update preferences").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
|
|
|
|
"success": true,
|
|
|
|
|
|
"data": prefs,
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// ChangePassword godoc
|
|
|
|
|
|
// @Summary 修改密码
|
2026-08-07 07:12:05 +00:00
|
|
|
|
// @Description 修改当前用户的登录密码。新密码须满足 8–32 位且同时包含字母与数字;成功后所有会话被撤销,需重新登录。
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Param request body object{old_password=string,new_password=string} true "密码修改请求"
|
|
|
|
|
|
// @Success 200 {object} map[string]interface{} "修改成功"
|
|
|
|
|
|
// @Failure 400 {object} errors.AppError "请求参数错误"
|
|
|
|
|
|
// @Security Bearer
|
|
|
|
|
|
// @Router /auth/change-password [post]
|
2025-09-15 18:47:39 +00:00
|
|
|
|
func (h *AuthHandler) ChangePassword(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
|
|
|
|
|
|
logger.Info(ctx, "Start password change")
|
|
|
|
|
|
|
|
|
|
|
|
var req struct {
|
|
|
|
|
|
OldPassword string `json:"old_password" binding:"required"`
|
2026-08-07 07:12:05 +00:00
|
|
|
|
NewPassword string `json:"new_password" binding:"required"`
|
2025-09-15 18:47:39 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
|
|
|
|
logger.Error(ctx, "Failed to parse password change request", err)
|
|
|
|
|
|
appErr := errors.NewValidationError("Invalid password change request").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Get current user
|
|
|
|
|
|
user, err := h.userService.GetCurrentUser(ctx)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to get current user: %v", err)
|
|
|
|
|
|
appErr := errors.NewUnauthorizedError("Failed to get user information").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Change password
|
|
|
|
|
|
err = h.userService.ChangePassword(ctx, user.ID, req.OldPassword, req.NewPassword)
|
|
|
|
|
|
if err != nil {
|
2026-08-07 07:12:05 +00:00
|
|
|
|
switch {
|
|
|
|
|
|
case stderrors.Is(err, service.ErrPasswordPolicy):
|
2026-08-07 07:46:43 +00:00
|
|
|
|
appErr := errors.NewValidationError("Password policy violation").
|
|
|
|
|
|
WithDetails(service.DetailPasswordPolicy)
|
2026-08-07 07:12:05 +00:00
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
case stderrors.Is(err, service.ErrInvalidOldPassword):
|
2026-08-07 07:46:43 +00:00
|
|
|
|
appErr := errors.NewBadRequestError("Current password is incorrect").
|
|
|
|
|
|
WithDetails(service.DetailInvalidOldPassword)
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
case stderrors.Is(err, service.ErrSamePassword):
|
|
|
|
|
|
appErr := errors.NewValidationError("New password must differ from current password").
|
|
|
|
|
|
WithDetails(service.DetailSamePassword)
|
2026-08-07 07:12:05 +00:00
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
default:
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to change password: %v", err)
|
|
|
|
|
|
appErr := errors.NewBadRequestError("Password change failed").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-09-15 18:47:39 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "Password changed successfully for user: %s", user.Email)
|
|
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
|
|
|
|
"success": true,
|
|
|
|
|
|
"message": "Password changed successfully",
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-13 11:47:48 +00:00
|
|
|
|
// GetAuthConfig godoc
|
|
|
|
|
|
// @Summary 获取认证配置
|
|
|
|
|
|
// @Description 返回当前部署的注册模式等公开认证配置,供前端决定是否展示注册入口
|
|
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Success 200 {object} map[string]interface{} "认证配置"
|
|
|
|
|
|
// @Router /auth/config [get]
|
|
|
|
|
|
//
|
|
|
|
|
|
// GetAuthConfig is intentionally a no-auth endpoint: the frontend reads
|
|
|
|
|
|
// it on app load to decide whether to show the Register tab. We expose
|
|
|
|
|
|
// only what the UI strictly needs (registration_mode); other config
|
|
|
|
|
|
// stays internal.
|
|
|
|
|
|
func (h *AuthHandler) GetAuthConfig(c *gin.Context) {
|
2026-05-24 13:38:05 +00:00
|
|
|
|
// Same source-of-truth as Register's gate, so the UI hide-the-button
|
|
|
|
|
|
// signal can never disagree with the API enforcement signal.
|
|
|
|
|
|
mode := h.resolveRegistrationMode(c.Request.Context())
|
2026-05-13 11:47:48 +00:00
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
|
|
|
|
"success": true,
|
|
|
|
|
|
"registration_mode": mode,
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// SwitchTenant godoc
|
2026-07-14 08:13:49 +00:00
|
|
|
|
// @Summary 切换激活空间
|
|
|
|
|
|
// @Description 为当前用户在目标空间重新签发访问令牌;要求该用户在目标空间存在 active 成员关系
|
2026-05-13 11:47:48 +00:00
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Param request body object{tenant_id=integer,refresh_token=string} true "切换请求"
|
|
|
|
|
|
// @Success 200 {object} types.LoginResponse
|
|
|
|
|
|
// @Failure 400 {object} errors.AppError "参数错误"
|
2026-07-14 08:13:49 +00:00
|
|
|
|
// @Failure 403 {object} errors.AppError "无该空间成员关系"
|
2026-05-13 11:47:48 +00:00
|
|
|
|
// @Security Bearer
|
|
|
|
|
|
// @Router /auth/switch-tenant [post]
|
|
|
|
|
|
//
|
|
|
|
|
|
// SwitchTenant is the v1 backend hook for the tenant-switcher UI added
|
|
|
|
|
|
// in PR 3. The current PR ships the endpoint so multi-tenant tests can
|
|
|
|
|
|
// exercise the membership flow end-to-end before the frontend lands.
|
|
|
|
|
|
func (h *AuthHandler) SwitchTenant(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
|
|
|
|
|
|
var req struct {
|
|
|
|
|
|
TenantID uint64 `json:"tenant_id" binding:"required"`
|
|
|
|
|
|
RefreshToken string `json:"refresh_token"`
|
|
|
|
|
|
}
|
|
|
|
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
2026-07-14 08:13:49 +00:00
|
|
|
|
appErr := errors.NewValidationError("Invalid workspace switch request").WithDetails(err.Error())
|
2026-05-13 11:47:48 +00:00
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
user, err := h.userService.GetCurrentUser(ctx)
|
|
|
|
|
|
if err != nil || user == nil {
|
|
|
|
|
|
appErr := errors.NewUnauthorizedError("not authenticated")
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
resp, err := h.userService.SwitchTenant(ctx, user, req.TenantID, req.RefreshToken)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "SwitchTenant failed user=%s target=%d: %v", user.ID, req.TenantID, err)
|
2026-07-14 08:13:49 +00:00
|
|
|
|
appErr := errors.NewForbiddenError("workspace switch failed").WithDetails(err.Error())
|
2026-05-13 11:47:48 +00:00
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-02 04:34:33 +00:00
|
|
|
|
c.JSON(http.StatusOK, dto.NewAuthLoginResponse(resp))
|
2026-05-13 11:47:48 +00:00
|
|
|
|
}
|
2026-07-02 06:49:27 +00:00
|
|
|
|
|
2026-04-11 04:47:17 +00:00
|
|
|
|
// @Summary 自动初始化(Lite 桌面版)
|
2026-07-14 08:13:49 +00:00
|
|
|
|
// @Description Lite 版专用:首次启动时自动创建默认用户和空间并返回令牌,后续启动直接签发令牌,免除手动注册/登录流程
|
2026-04-11 04:47:17 +00:00
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Success 200 {object} types.LoginResponse
|
|
|
|
|
|
// @Failure 403 {object} errors.AppError "非 Lite 版本"
|
|
|
|
|
|
// @Router /auth/auto-setup [post]
|
|
|
|
|
|
func (h *AuthHandler) AutoSetup(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
|
|
|
|
|
|
if Edition != "lite" {
|
|
|
|
|
|
appErr := errors.NewForbiddenError("auto-setup is only available in lite edition")
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
const defaultEmail = "admin@weknora.local"
|
|
|
|
|
|
|
|
|
|
|
|
user, _ := h.userService.GetUserByEmail(ctx, defaultEmail)
|
|
|
|
|
|
if user == nil {
|
|
|
|
|
|
logger.Info(ctx, "Auto-setup: creating default user and tenant for lite edition")
|
|
|
|
|
|
|
|
|
|
|
|
randomBytes := make([]byte, 24)
|
|
|
|
|
|
if _, err := rand.Read(randomBytes); err != nil {
|
|
|
|
|
|
appErr := errors.NewInternalServerError("auto-setup failed: unable to generate credentials")
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
randomPassword := base64.RawURLEncoding.EncodeToString(randomBytes)
|
|
|
|
|
|
randomUsername := fmt.Sprintf("user_%s", base64.RawURLEncoding.EncodeToString(randomBytes[:6]))
|
|
|
|
|
|
|
|
|
|
|
|
_, err := h.userService.Register(ctx, &types.RegisterRequest{
|
|
|
|
|
|
Username: randomUsername,
|
|
|
|
|
|
Email: defaultEmail,
|
|
|
|
|
|
Password: randomPassword,
|
|
|
|
|
|
})
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Auto-setup: failed to register default user: %v", err)
|
|
|
|
|
|
appErr := errors.NewInternalServerError("auto-setup failed").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
user, _ = h.userService.GetUserByEmail(ctx, defaultEmail)
|
|
|
|
|
|
if user == nil {
|
|
|
|
|
|
appErr := errors.NewInternalServerError("auto-setup failed: user not found after registration")
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
accessToken, refreshToken, err := h.userService.GenerateTokens(ctx, user)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Auto-setup: failed to generate tokens: %v", err)
|
|
|
|
|
|
appErr := errors.NewInternalServerError("auto-setup failed").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
tenant, _ := h.tenantService.GetTenantByID(ctx, user.TenantID)
|
|
|
|
|
|
|
|
|
|
|
|
logger.Info(ctx, "Auto-setup: completed successfully")
|
2026-07-02 04:34:33 +00:00
|
|
|
|
c.JSON(http.StatusOK, dto.NewAuthLoginResponse(&types.LoginResponse{
|
2026-04-11 04:47:17 +00:00
|
|
|
|
Success: true,
|
|
|
|
|
|
Message: "Auto-setup successful",
|
|
|
|
|
|
User: user,
|
2026-05-13 11:47:48 +00:00
|
|
|
|
ActiveTenant: tenant,
|
|
|
|
|
|
Memberships: []types.Membership{{
|
|
|
|
|
|
TenantID: user.TenantID,
|
|
|
|
|
|
TenantName: tenantNameOrEmpty(tenant),
|
|
|
|
|
|
Role: types.TenantRoleOwner,
|
|
|
|
|
|
}},
|
2026-04-11 04:47:17 +00:00
|
|
|
|
Token: accessToken,
|
|
|
|
|
|
RefreshToken: refreshToken,
|
2026-07-02 04:34:33 +00:00
|
|
|
|
}))
|
2026-04-11 04:47:17 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-13 11:47:48 +00:00
|
|
|
|
// tenantNameOrEmpty returns t.Name when t is non-nil, "" otherwise.
|
|
|
|
|
|
// Used by AutoSetup to populate Membership.TenantName without crashing
|
|
|
|
|
|
// if the tenant lookup failed.
|
|
|
|
|
|
func tenantNameOrEmpty(t *types.Tenant) string {
|
|
|
|
|
|
if t == nil {
|
|
|
|
|
|
return ""
|
|
|
|
|
|
}
|
|
|
|
|
|
return t.Name
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-16 08:40:13 +00:00
|
|
|
|
// ValidateToken godoc
|
|
|
|
|
|
// @Summary 验证令牌
|
|
|
|
|
|
// @Description 验证访问令牌是否有效
|
|
|
|
|
|
// @Tags 认证
|
|
|
|
|
|
// @Accept json
|
|
|
|
|
|
// @Produce json
|
|
|
|
|
|
// @Success 200 {object} map[string]interface{} "令牌有效"
|
|
|
|
|
|
// @Failure 401 {object} errors.AppError "令牌无效"
|
|
|
|
|
|
// @Security Bearer
|
|
|
|
|
|
// @Router /auth/validate [get]
|
2025-09-15 18:47:39 +00:00
|
|
|
|
func (h *AuthHandler) ValidateToken(c *gin.Context) {
|
|
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
|
|
|
|
|
|
|
|
logger.Info(ctx, "Start token validation")
|
|
|
|
|
|
|
|
|
|
|
|
// Extract token from Authorization header
|
|
|
|
|
|
authHeader := c.GetHeader("Authorization")
|
|
|
|
|
|
if authHeader == "" {
|
|
|
|
|
|
logger.Error(ctx, "Missing Authorization header")
|
|
|
|
|
|
appErr := errors.NewValidationError("Authorization header is required")
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Parse Bearer token
|
|
|
|
|
|
tokenParts := strings.Split(authHeader, " ")
|
|
|
|
|
|
if len(tokenParts) != 2 || tokenParts[0] != "Bearer" {
|
|
|
|
|
|
logger.Error(ctx, "Invalid Authorization header format")
|
|
|
|
|
|
appErr := errors.NewValidationError("Invalid Authorization header format")
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
token := tokenParts[1]
|
|
|
|
|
|
|
|
|
|
|
|
// Validate token
|
fix(auth): honour JWT tenant_id claim in middleware
POST /auth/switch-tenant mints an access token whose `tenant_id` claim
points to the target tenant, but the middleware previously discarded
that claim entirely:
user, err := userService.ValidateToken(ctx, token) // returned only *User
targetTenantID := user.TenantID // always the home tenant
The session therefore stayed scoped to the user's home tenant despite
the supposedly fresh token, making the new endpoint a no-op once
the request hit any tenant-scoped query.
This change widens the contract:
- UserService.ValidateToken now returns (user, activeTenantID, error)
where activeTenantID is the JWT's `tenant_id` claim, falling back to
user.TenantID when the claim is absent (backward compatibility with
pre-RBAC tokens still in the wild).
- middleware/auth.go uses activeTenantID as the default target before
applying any X-Tenant-ID header override, and recomputes
crossTenantSwitch from `activeTenantID != user.TenantID` so the
resolveTenantRole branches stay correct for switch-tenant sessions.
- The non-middleware /auth/validate handler in handler/auth.go absorbs
the new return value (it only cares about user identity).
Tests:
- internal/application/service/user_jwt_test.go pins the JWT->tenant-id
projection (`tenantIDFromClaims`) — claim present beats fallback,
zero/negative/string claims fall back, int64/uint64 are accepted for
test-built tokens.
Required for PR 2 multi-tenant integration tests, where a single user
needs to switch between Owner-in-A and Viewer-in-B sessions and observe
distinct authority on each side.
2026-05-13 12:40:17 +00:00
|
|
|
|
user, _, err := h.userService.ValidateToken(ctx, token)
|
2025-09-15 18:47:39 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
logger.Errorf(ctx, "Failed to validate token: %v", err)
|
|
|
|
|
|
appErr := errors.NewUnauthorizedError("Token validation failed").WithDetails(err.Error())
|
|
|
|
|
|
c.Error(appErr)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
logger.Infof(ctx, "Token validated successfully for user: %s", user.Email)
|
|
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
|
|
|
|
"success": true,
|
|
|
|
|
|
"message": "Token is valid",
|
|
|
|
|
|
"user": user.ToUserInfo(),
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|