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.
This commit is contained in:
@@ -36,6 +36,21 @@ export interface LoginResponse {
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
// active_tenant mirrors `tenant` for endpoints that distinguish home
|
||||
// tenant from current tenant (e.g. /auth/register-by-invite). Only
|
||||
// one of `tenant` / `active_tenant` is populated by any given endpoint.
|
||||
active_tenant?: {
|
||||
id: number
|
||||
name: string
|
||||
description?: string
|
||||
api_key?: string
|
||||
status?: string
|
||||
business?: string
|
||||
storage_quota?: number
|
||||
storage_used?: number
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
token?: string
|
||||
refresh_token?: string
|
||||
}
|
||||
@@ -417,3 +432,59 @@ export async function validateToken(): Promise<{ success: boolean; valid?: boole
|
||||
|
||||
|
||||
|
||||
|
||||
// ---- share-link registration --------------------------------------------
|
||||
|
||||
// InviteLookup is the public projection of a share-link row used by
|
||||
// /register?token=xxx — enough to render the registration page header
|
||||
// ("X invited you to Y") without leaking sensitive inviter fields.
|
||||
export interface InviteLookup {
|
||||
tenant_id: number
|
||||
tenant_name?: string
|
||||
role: string
|
||||
expires_at: string
|
||||
}
|
||||
|
||||
export interface InviteLookupResponse {
|
||||
success: boolean
|
||||
data?: InviteLookup
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface RegisterByInviteRequest {
|
||||
token: string
|
||||
email: string
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a share-link token (no auth) into the context the
|
||||
* registration page needs (tenant name, role, expiry). Returns 410
|
||||
* when the link is invalid / revoked / expired.
|
||||
*
|
||||
* Uses POST + body (rather than GET + path) so the plaintext token
|
||||
* never appears in access logs, browser history, or tracing spans.
|
||||
*/
|
||||
export async function getInvitationByToken(token: string): Promise<InviteLookupResponse> {
|
||||
try {
|
||||
const response = await post(`/api/v1/auth/invitations/lookup`, { token })
|
||||
return response as unknown as InviteLookupResponse
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || '' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete registration via a share-link token. The invitee supplies
|
||||
* their own email — the token is the authorisation, not an identity
|
||||
* lock.
|
||||
*/
|
||||
export async function registerByInvite(data: RegisterByInviteRequest): Promise<LoginResponse> {
|
||||
try {
|
||||
const response = await post('/api/v1/auth/register-by-invite', data)
|
||||
return response as unknown as LoginResponse
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message || t('error.auth.registerFailed') }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,17 @@ export interface TenantInvitation {
|
||||
expires_at: string
|
||||
responded_at?: string | null
|
||||
created_at: string
|
||||
// invite_url is set on share-link rows that are still pending. The
|
||||
// backend re-emits it on every list/get so Owners can copy the
|
||||
// link on demand without "copy now or revoke" pressure.
|
||||
invite_url?: string
|
||||
// is_share_link distinguishes share-link rows (no specific invitee,
|
||||
// multi-use, copyable URL) from per-user invitations.
|
||||
is_share_link?: boolean
|
||||
// accepted_count counts how many users have completed registration
|
||||
// through this invitation. Surfaced in the management UI for
|
||||
// share-link rows ("已加入 N 人").
|
||||
accepted_count?: number
|
||||
}
|
||||
|
||||
export interface ListInvitationsResponse {
|
||||
@@ -191,3 +202,35 @@ export async function declineInvitation(invId: number): Promise<SimpleResponse>
|
||||
`/api/v1/me/invitations/${invId}/decline`,
|
||||
)) as unknown as SimpleResponse
|
||||
}
|
||||
|
||||
// ---- share-link API ----------------------------------------------------
|
||||
|
||||
export interface CreateInviteLinkRequest {
|
||||
role: TenantRole
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface CreateInviteLinkResponse {
|
||||
success: boolean
|
||||
data?: TenantInvitation
|
||||
message?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a multi-use share-link invitation for the tenant. The
|
||||
* returned row carries `invite_url` (composed from the persisted
|
||||
* plaintext token) which the SPA copies into clipboards. The link
|
||||
* stays valid until expiry or revocation; revoking is the same DELETE
|
||||
* as a per-user invitation.
|
||||
*
|
||||
* Backend: POST /api/v1/tenants/:id/invite-links (Owner+).
|
||||
*/
|
||||
export async function createInviteLink(
|
||||
tenantId: number,
|
||||
body: CreateInviteLinkRequest,
|
||||
): Promise<CreateInviteLinkResponse> {
|
||||
return (await post(
|
||||
`/api/v1/tenants/${tenantId}/invite-links`,
|
||||
body,
|
||||
)) as unknown as CreateInviteLinkResponse
|
||||
}
|
||||
|
||||
@@ -1305,6 +1305,32 @@ export default {
|
||||
chunkOverlapDesc: 'Number of characters overlapping between adjacent chunks. Helps maintain context at chunk boundaries.',
|
||||
selectRelationType: 'Select relation type'
|
||||
},
|
||||
inviteRegister: {
|
||||
bannerTitle: 'You have been invited to join "{tenant}"',
|
||||
bannerHint: 'Fill in the details below to register. You will join the team automatically once registration completes.',
|
||||
loading: 'Verifying invitation link…',
|
||||
invalidTitle: 'Invitation link is invalid or revoked',
|
||||
invalidBody: 'Ask your inviter to send a new link, or sign in with an existing account.',
|
||||
backToLogin: 'Back to login',
|
||||
title: 'Complete registration',
|
||||
subtitle: "You've been invited to join “{tenant}”",
|
||||
email: 'Email',
|
||||
emailPlaceholder: 'your@example.com',
|
||||
emailHint: 'Use any email address you control.',
|
||||
emailInvalid: 'Please enter a valid email address',
|
||||
username: 'Display name',
|
||||
usernamePlaceholder: 'Enter your display name',
|
||||
password: 'Set a password',
|
||||
passwordPlaceholder: 'At least 6 characters',
|
||||
confirmPassword: 'Confirm password',
|
||||
submit: 'Complete registration',
|
||||
submitting: 'Submitting…',
|
||||
success: 'Registration successful — entering workspace…',
|
||||
failed: 'Registration failed; please try again later',
|
||||
usernameRequired: 'Display name is required',
|
||||
passwordTooShort: 'Password must be at least 6 characters',
|
||||
passwordMismatch: 'Passwords do not match',
|
||||
},
|
||||
auth: {
|
||||
login: 'Login',
|
||||
logout: 'Logout',
|
||||
@@ -4781,6 +4807,23 @@ export default {
|
||||
confirmInviteBody:
|
||||
'Send an invitation to {email} (role: {role}). They will join the tenant only after accepting.',
|
||||
confirmSend: 'Send',
|
||||
copyLink: 'Copy invite link',
|
||||
copied: 'Copied to clipboard',
|
||||
copyFailed: 'Copy failed; please select the text manually',
|
||||
shareLink: {
|
||||
button: 'Generate share link',
|
||||
label: 'Share link',
|
||||
cellTitle: 'Invite via link',
|
||||
cellAccepted: '{count} joined',
|
||||
cellEmpty: 'No one has joined yet',
|
||||
dialogTitle: 'Generate share invitation link',
|
||||
description:
|
||||
"Generate a multi-use registration link you can drop in a group chat. Anyone who opens it registers with their own email and joins this workspace. Expires in {days} days, or revoke it any time from the list.",
|
||||
generate: 'Generate link',
|
||||
resultTitle: 'Invitation link ready',
|
||||
resultBody: "Copy the link below and share it via any private channel. It's also saved in the list — you can re-copy or revoke it later.",
|
||||
revokeConfirm: "Revoking will block anyone who hasn't registered yet from using this link. Generate a new one to re-share.",
|
||||
},
|
||||
revoke: {
|
||||
button: 'Revoke',
|
||||
confirmTitle: 'Revoke invitation?',
|
||||
@@ -4799,6 +4842,7 @@ export default {
|
||||
},
|
||||
status: {
|
||||
pending: 'Pending',
|
||||
shareLinkActive: 'Active',
|
||||
accepted: 'Accepted',
|
||||
declined: 'Declined',
|
||||
revoked: 'Revoked',
|
||||
|
||||
@@ -1162,6 +1162,32 @@ export default {
|
||||
"인접 청크 간의 중복 문자 수입니다. 청크 경계에서 컨텍스트를 유지하는 데 도움이 됩니다.",
|
||||
selectRelationType: "관계 유형 선택",
|
||||
},
|
||||
inviteRegister: {
|
||||
bannerTitle: "「{tenant}」에 초대되었습니다",
|
||||
bannerHint: "아래 정보를 입력해 가입을 완료하세요. 등록이 끝나면 자동으로 팀에 합류합니다.",
|
||||
loading: "초대 링크를 확인하는 중…",
|
||||
invalidTitle: "초대 링크가 유효하지 않거나 취소되었습니다",
|
||||
invalidBody: "초대한 분께 새 링크를 요청하거나 기존 계정으로 로그인하세요.",
|
||||
backToLogin: "로그인으로 돌아가기",
|
||||
title: "가입 완료",
|
||||
subtitle: "「{tenant}」에 초대되었습니다",
|
||||
email: "이메일",
|
||||
emailPlaceholder: "your@example.com",
|
||||
emailHint: "본인이 사용하는 이메일이면 됩니다.",
|
||||
emailInvalid: "유효한 이메일을 입력해 주세요",
|
||||
username: "표시 이름",
|
||||
usernamePlaceholder: "이름을 입력하세요",
|
||||
password: "비밀번호 설정",
|
||||
passwordPlaceholder: "최소 6자 이상",
|
||||
confirmPassword: "비밀번호 확인",
|
||||
submit: "가입 완료",
|
||||
submitting: "전송 중…",
|
||||
success: "가입 완료, 워크스페이스로 이동합니다…",
|
||||
failed: "가입에 실패했습니다. 잠시 후 다시 시도해 주세요",
|
||||
usernameRequired: "이름을 입력하세요",
|
||||
passwordTooShort: "비밀번호는 최소 6자 이상이어야 합니다",
|
||||
passwordMismatch: "두 비밀번호가 일치하지 않습니다",
|
||||
},
|
||||
auth: {
|
||||
login: "로그인",
|
||||
logout: "로그아웃",
|
||||
@@ -4839,6 +4865,23 @@ export default {
|
||||
confirmInviteTitle: "초대를 보내시겠습니까?",
|
||||
confirmInviteBody: "{email}에게 초대를 보냅니다(역할: {role}). 수락 후 멤버가 됩니다.",
|
||||
confirmSend: "보내기",
|
||||
copyLink: "초대 링크 복사",
|
||||
copied: "클립보드에 복사됨",
|
||||
copyFailed: "복사 실패. 직접 선택해 주세요",
|
||||
shareLink: {
|
||||
button: "공유 링크 생성",
|
||||
label: "공유 링크",
|
||||
cellTitle: "링크로 초대",
|
||||
cellAccepted: "{count}명 가입함",
|
||||
cellEmpty: "아직 가입한 사람이 없습니다",
|
||||
dialogTitle: "공유 초대 링크 생성",
|
||||
description:
|
||||
"여러 명이 사용할 수 있는 가입 링크를 생성합니다. 받은 사람이 자신의 이메일로 가입하고 이 워크스페이스에 합류합니다. {days}일 후 만료되며, 목록에서 언제든지 취소할 수 있습니다.",
|
||||
generate: "링크 생성",
|
||||
resultTitle: "초대 링크가 생성되었습니다",
|
||||
resultBody: "아래 링크를 복사해 비공개 채널로 전달하세요. 목록에도 저장되어 다시 복사하거나 취소할 수 있습니다.",
|
||||
revokeConfirm: "취소 후에는 미가입자가 이 링크를 사용할 수 없습니다. 다시 발급하려면 새 링크를 생성하세요.",
|
||||
},
|
||||
revoke: {
|
||||
button: "취소",
|
||||
confirmTitle: "초대를 취소하시겠습니까?",
|
||||
@@ -4856,6 +4899,7 @@ export default {
|
||||
},
|
||||
status: {
|
||||
pending: "대기 중",
|
||||
shareLinkActive: "활성",
|
||||
accepted: "수락됨",
|
||||
declined: "거절됨",
|
||||
revoked: "취소됨",
|
||||
|
||||
@@ -1157,6 +1157,32 @@ export default {
|
||||
chunkOverlapDesc: "相邻块之间重叠的字符数。有助于保持块边界处的上下文。",
|
||||
selectRelationType: "选择关系类型",
|
||||
},
|
||||
inviteRegister: {
|
||||
bannerTitle: "您被邀请加入「{tenant}」",
|
||||
bannerHint: "填写下方信息完成注册,注册成功后将自动加入该团队。",
|
||||
loading: "正在校验邀请链接…",
|
||||
invalidTitle: "邀请链接无效或已撤销",
|
||||
invalidBody: "请联系邀请人重新发送链接,或前往登录使用现有账号。",
|
||||
backToLogin: "返回登录",
|
||||
title: "完成注册",
|
||||
subtitle: "您被邀请加入「{tenant}」",
|
||||
email: "邮箱",
|
||||
emailPlaceholder: "your@example.com",
|
||||
emailHint: "用您自己的邮箱注册即可。",
|
||||
emailInvalid: "请输入有效的邮箱地址",
|
||||
username: "姓名",
|
||||
usernamePlaceholder: "请输入您的姓名",
|
||||
password: "设置密码",
|
||||
passwordPlaceholder: "至少 6 位",
|
||||
confirmPassword: "确认密码",
|
||||
submit: "完成注册",
|
||||
submitting: "提交中…",
|
||||
success: "注册成功,正在进入工作空间…",
|
||||
failed: "注册失败,请稍后重试",
|
||||
usernameRequired: "请输入姓名",
|
||||
passwordTooShort: "密码至少 6 位",
|
||||
passwordMismatch: "两次输入的密码不一致",
|
||||
},
|
||||
auth: {
|
||||
login: "登录",
|
||||
logout: "退出",
|
||||
@@ -4773,6 +4799,23 @@ export default {
|
||||
confirmInviteBody:
|
||||
"将向 {email} 发出加入邀请(角色:{role})。TA 在站内接受后才会成为成员。",
|
||||
confirmSend: "发送",
|
||||
copyLink: "复制邀请链接",
|
||||
copied: "已复制到剪贴板",
|
||||
copyFailed: "复制失败,请手动选中文本",
|
||||
shareLink: {
|
||||
button: "生成共享链接",
|
||||
label: "共享链接",
|
||||
cellTitle: "通过链接邀请",
|
||||
cellAccepted: "已加入 {count} 人",
|
||||
cellEmpty: "尚无成员加入",
|
||||
dialogTitle: "生成共享邀请链接",
|
||||
description:
|
||||
"生成一条多人可用的注册链接,发到群里就行;谁打开都能用自己的邮箱注册并加入当前空间。链接 {days} 天后过期,或随时可在列表中撤销。",
|
||||
generate: "生成链接",
|
||||
resultTitle: "邀请链接已生成",
|
||||
resultBody: "复制下方链接,通过任意私密渠道发给被邀请人。链接也会保存在下方列表中,随时可以重新复制或撤销。",
|
||||
revokeConfirm: "撤销后,所有还未注册的人都无法再使用此链接;如需重发请生成新链接。",
|
||||
},
|
||||
revoke: {
|
||||
button: "撤销",
|
||||
confirmTitle: "确认撤销邀请?",
|
||||
@@ -4791,6 +4834,7 @@ export default {
|
||||
},
|
||||
status: {
|
||||
pending: "待接受",
|
||||
shareLinkActive: "生效中",
|
||||
accepted: "已接受",
|
||||
declined: "已拒绝",
|
||||
revoked: "已撤销",
|
||||
|
||||
@@ -51,6 +51,17 @@ const router = createRouter({
|
||||
component: () => import("../views/auth/Login.vue"),
|
||||
meta: { requiresAuth: false, requiresInit: false }
|
||||
},
|
||||
{
|
||||
path: "/register",
|
||||
name: "registerByInvite",
|
||||
// Share-link landing page reuses the Login form: the same Vue
|
||||
// component renders both modes and detects ?token=xxx on mount
|
||||
// to switch into invite-register flow. Avoids a parallel page
|
||||
// that would duplicate the OIDC / language-switch / styling
|
||||
// surface for one extra field.
|
||||
component: () => import("../views/auth/Login.vue"),
|
||||
meta: { requiresAuth: false, requiresInit: false }
|
||||
},
|
||||
{
|
||||
path: "/join",
|
||||
name: "joinOrganization",
|
||||
|
||||
@@ -272,8 +272,29 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Register Card -->
|
||||
<div class="form-card" v-if="isRegisterMode && registrationEnabled">
|
||||
<!-- Register Card. Renders when the user is in register mode
|
||||
AND either self-service registration is enabled OR they
|
||||
arrived with a valid share-link token (which bypasses the
|
||||
invite_only gate). -->
|
||||
<div class="form-card" v-if="isRegisterMode && (registrationEnabled || inviteLookup)">
|
||||
<!-- Share-link banner: shown only when ?token= resolved to a
|
||||
real invitation row. Sits above the form header so the
|
||||
invitee instantly sees who invited them and into which
|
||||
workspace, without bumping the existing register UX. -->
|
||||
<div v-if="inviteLookup" class="invite-banner">
|
||||
<t-icon name="link" class="invite-banner__icon" />
|
||||
<div class="invite-banner__text">
|
||||
<div class="invite-banner__title">
|
||||
{{ $t('inviteRegister.bannerTitle', { tenant: inviteLookup.tenant_name || '' }) }}
|
||||
</div>
|
||||
<div class="invite-banner__hint">
|
||||
{{ $t('inviteRegister.bannerHint') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="inviteLookupError" class="invite-banner invite-banner--error">
|
||||
{{ inviteLookupError }}
|
||||
</div>
|
||||
<div class="form-header">
|
||||
<h2 class="form-title">{{ $t('auth.createAccount') }}</h2>
|
||||
<p class="form-subtitle">{{ $t('auth.registerSubtitle') }}</p>
|
||||
@@ -370,7 +391,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, nextTick, onMounted, onBeforeUnmount, computed } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useRoleLabel } from '@/composables/useRoleLabel'
|
||||
import { notifyLoginSuccess } from '@/utils/loginNotify'
|
||||
@@ -379,7 +400,18 @@ import { Autoplay, EffectFade, Pagination } from 'swiper/modules'
|
||||
import 'swiper/css'
|
||||
import 'swiper/css/effect-fade'
|
||||
import 'swiper/css/pagination'
|
||||
import { login, register, getOIDCAuthorizationURL, getOIDCConfig, autoSetup, getAuthConfig, userInfoFromApi } from '@/api/auth'
|
||||
import {
|
||||
login,
|
||||
register,
|
||||
getOIDCAuthorizationURL,
|
||||
getOIDCConfig,
|
||||
autoSetup,
|
||||
getAuthConfig,
|
||||
userInfoFromApi,
|
||||
getInvitationByToken,
|
||||
registerByInvite,
|
||||
type InviteLookup,
|
||||
} from '@/api/auth'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
@@ -389,6 +421,7 @@ import screenshot2 from '@/assets/img/screenshot-2.svg'
|
||||
import screenshot4 from '@/assets/img/screenshot-4.svg'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const authStore = useAuthStore()
|
||||
const { t, tm, locale } = useI18n()
|
||||
const { formatRole, roleIcon } = useRoleLabel()
|
||||
@@ -431,6 +464,17 @@ const oidcProviderName = ref('')
|
||||
// In invite_only mode the link/card are hidden.
|
||||
const registrationEnabled = ref(true)
|
||||
|
||||
// invite-link state. When the URL carries ?token=xxx we resolve it to
|
||||
// the originating tenant + role and switch the form into a "register
|
||||
// via invitation" mode. The token bypasses the normal invite_only
|
||||
// gate — possessing it IS the authorisation. Submitting the register
|
||||
// form with this set hits /auth/register-by-invite (auto-login on
|
||||
// success) instead of /auth/register.
|
||||
const inviteToken = ref('')
|
||||
const inviteLookup = ref<InviteLookup | null>(null)
|
||||
const inviteLookupError = ref('')
|
||||
const inviteLookupLoading = ref(false)
|
||||
|
||||
// Language options
|
||||
const languageOptions = [
|
||||
{ value: 'zh-CN', label: '简体中文', shortLabel: '中文', flag: '🇨🇳' },
|
||||
@@ -668,14 +712,36 @@ const handleLogin = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Handle registration
|
||||
// Handle registration. Dispatches based on whether the user arrived
|
||||
// with a share-link token: with token -> register-by-invite (auto-
|
||||
// login on success); without -> the normal self-service register
|
||||
// (drops back to the login form for the user to sign in).
|
||||
const handleRegister = async () => {
|
||||
try {
|
||||
const valid = await registerFormRef.value?.validate()
|
||||
if (valid !== true) return
|
||||
|
||||
loading.value = true
|
||||
|
||||
|
||||
if (inviteToken.value) {
|
||||
const response = await registerByInvite({
|
||||
token: inviteToken.value,
|
||||
username: registerData.username,
|
||||
email: registerData.email,
|
||||
password: registerData.password,
|
||||
})
|
||||
if (!response.success) {
|
||||
MessagePlugin.error(response.message || t('auth.registerFailed'))
|
||||
return
|
||||
}
|
||||
MessagePlugin.success(t('auth.registerSuccess'))
|
||||
// register-by-invite returns the same shape as login (token +
|
||||
// active_tenant + memberships), so reuse the login persistence
|
||||
// path — same store writes, same redirect target.
|
||||
await persistLoginResponse(response)
|
||||
return
|
||||
}
|
||||
|
||||
const response = await register({
|
||||
username: registerData.username,
|
||||
email: registerData.email,
|
||||
@@ -684,11 +750,11 @@ const handleRegister = async () => {
|
||||
|
||||
if (response.success) {
|
||||
MessagePlugin.success(t('auth.registerSuccess'))
|
||||
|
||||
|
||||
// Switch to login mode and fill in email
|
||||
isRegisterMode.value = false
|
||||
formData.email = registerData.email
|
||||
|
||||
|
||||
// Clear register form
|
||||
Object.keys(registerData).forEach(key => {
|
||||
(registerData as any)[key] = ''
|
||||
@@ -706,6 +772,41 @@ const handleRegister = async () => {
|
||||
|
||||
// Check if already logged in; for lite edition, attempt transparent auto-setup
|
||||
onMounted(async () => {
|
||||
// Share-link landing: ?token=xxx switches the form into invite-
|
||||
// register mode before any other auto-flow (logged-in redirect /
|
||||
// auto-setup / OIDC) gets a chance to redirect. Resolution failure
|
||||
// surfaces inline; the user can still log in normally if they
|
||||
// already have an account. We check this BEFORE the isLoggedIn
|
||||
// redirect so an existing session doesn't bounce the user to
|
||||
// /platform (and possibly back to /login if the session is stale),
|
||||
// dropping the invite token along the way.
|
||||
const tokenFromQuery = String(route.query.token || '').trim()
|
||||
if (tokenFromQuery) {
|
||||
inviteToken.value = tokenFromQuery
|
||||
inviteLookupLoading.value = true
|
||||
try {
|
||||
const resp = await getInvitationByToken(tokenFromQuery)
|
||||
if (resp.success && resp.data) {
|
||||
inviteLookup.value = resp.data
|
||||
// Token bypasses invite_only — show the register card even
|
||||
// when self-service registration is otherwise disabled.
|
||||
registrationEnabled.value = true
|
||||
isRegisterMode.value = true
|
||||
} else {
|
||||
inviteLookupError.value = resp.message || t('inviteRegister.invalidBody')
|
||||
}
|
||||
} catch {
|
||||
inviteLookupError.value = t('inviteRegister.invalidBody')
|
||||
} finally {
|
||||
inviteLookupLoading.value = false
|
||||
}
|
||||
// Don't run auto-setup when the user came in via an invite link —
|
||||
// they're explicitly trying to register, not bootstrap a Lite
|
||||
// single-user instance.
|
||||
loadOIDCConfig()
|
||||
return
|
||||
}
|
||||
|
||||
if (authStore.isLoggedIn) {
|
||||
router.replace('/platform/knowledge-bases')
|
||||
return
|
||||
@@ -1103,6 +1204,57 @@ onMounted(async () => {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Share-link invitation banner. Sits above the register form when the
|
||||
* user arrived via /register?token=xxx; gives them confirmation of who
|
||||
* invited them before they fill anything in. Subtle, neutral card —
|
||||
* the page background is heavily brand-coloured already, so a loud
|
||||
* tinted banner clashes; we lean on the form's own surface tokens. */
|
||||
.invite-banner {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 12px 14px;
|
||||
margin-bottom: 20px;
|
||||
border-radius: 10px;
|
||||
background: var(--td-bg-color-container-hover, rgba(0, 0, 0, 0.03));
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.invite-banner__icon {
|
||||
margin-top: 2px;
|
||||
font-size: 18px;
|
||||
flex-shrink: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.invite-banner__text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.invite-banner__title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.invite-banner__hint {
|
||||
font-size: 12px;
|
||||
color: var(--td-text-color-secondary);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.invite-banner--error {
|
||||
background: var(--td-error-color-1, rgba(220, 38, 38, 0.06));
|
||||
border-color: var(--td-error-color-3, rgba(220, 38, 38, 0.2));
|
||||
color: var(--td-error-color, #b91c1c);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.form-header {
|
||||
text-align: center;
|
||||
margin-bottom: 32px;
|
||||
|
||||
@@ -107,9 +107,22 @@
|
||||
<t-table row-key="id" :data="invitations" :columns="invitationColumns" size="medium" hover>
|
||||
<template #invitee="{ row }">
|
||||
<div class="member-cell">
|
||||
<span class="member-name">{{ inviteePrimary(row) }}</span>
|
||||
<span v-if="row.invitee_email && row.invitee_name" class="member-email">{{ row.invitee_email
|
||||
}}</span>
|
||||
<template v-if="row.is_share_link">
|
||||
<span class="member-name share-link-title">
|
||||
<t-icon name="link" size="14px" />
|
||||
{{ $t('tenantInvitation.shareLink.cellTitle') }}
|
||||
</span>
|
||||
<span class="member-email">
|
||||
{{ (row.accepted_count ?? 0) > 0
|
||||
? $t('tenantInvitation.shareLink.cellAccepted', { count: row.accepted_count })
|
||||
: $t('tenantInvitation.shareLink.cellEmpty') }}
|
||||
</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="member-name">{{ inviteePrimary(row) }}</span>
|
||||
<span v-if="row.invitee_email && row.invitee_name" class="member-email">{{ row.invitee_email
|
||||
}}</span>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
<template #role="{ row }">
|
||||
@@ -123,21 +136,40 @@
|
||||
<template #expires_at="{ row }">{{ formatDate(row.expires_at) }}</template>
|
||||
<template #status="{ row }">
|
||||
<t-tag :theme="invitationStatusTheme(row.status)" size="small">
|
||||
{{ $t('tenantInvitation.status.' + row.status) }}
|
||||
{{ row.is_share_link && row.status === 'pending'
|
||||
? $t('tenantInvitation.status.shareLinkActive')
|
||||
: $t('tenantInvitation.status.' + row.status) }}
|
||||
</t-tag>
|
||||
</template>
|
||||
<template #actions="{ row }">
|
||||
<!-- Per-row "copy link" for active share-link rows.
|
||||
Icon-only with tooltip so two actions ("copy" +
|
||||
"revoke") fit inside the actions column without
|
||||
clipping; the full label was too wide. -->
|
||||
<t-tooltip v-if="row.status === 'pending' && row.invite_url"
|
||||
:content="$t('tenantInvitation.copyLink')" placement="top">
|
||||
<t-button shape="square" variant="text" size="small"
|
||||
@click="copyText(absoluteInviteURL(row.invite_url))">
|
||||
<template #icon><t-icon name="copy" /></template>
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
<!-- Inline popconfirm anchored to the revoke button.
|
||||
Avoids spawning a top-level modal for a simple
|
||||
yes/no decision; the popover stays inside the
|
||||
table cell so the user keeps spatial context. -->
|
||||
<t-popconfirm v-if="row.status === 'pending'" theme="warning" :content="$t('tenantInvitation.revoke.confirmBody', {
|
||||
email: row.invitee_email || row.invitee_user_id,
|
||||
})" :confirm-btn="{ content: $t('tenantInvitation.revoke.confirm'), theme: 'danger' }"
|
||||
<t-popconfirm v-if="row.status === 'pending'" theme="warning"
|
||||
:content="row.is_share_link
|
||||
? $t('tenantInvitation.shareLink.revokeConfirm')
|
||||
: $t('tenantInvitation.revoke.confirmBody', {
|
||||
email: row.invitee_email || row.invitee_user_id,
|
||||
})"
|
||||
:confirm-btn="{ content: $t('tenantInvitation.revoke.confirm'), theme: 'danger' }"
|
||||
:cancel-btn="$t('common.cancel')" placement="left" @confirm="doRevokeInvitation(row)">
|
||||
<t-button theme="danger" variant="text" size="small">
|
||||
{{ $t('tenantInvitation.revoke.button') }}
|
||||
</t-button>
|
||||
<t-tooltip :content="$t('tenantInvitation.revoke.button')" placement="top">
|
||||
<t-button theme="danger" shape="square" variant="text" size="small">
|
||||
<template #icon><t-icon name="close" /></template>
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
</t-popconfirm>
|
||||
</template>
|
||||
</t-table>
|
||||
@@ -211,6 +243,67 @@
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
<!-- Share-link generator. Sits next to the invite-by-email
|
||||
popup so the two flows live side-by-side: "I know who"
|
||||
(email input) vs "I don't" (one link, group chat). -->
|
||||
<t-popup v-if="canManage" v-model="shareLinkPopupVisible" trigger="click" placement="bottom-end"
|
||||
destroy-on-close overlay-class-name="member-invite-popup-overlay">
|
||||
<t-button theme="default" variant="outline" shape="square" size="small" class="members-list-add-btn"
|
||||
:title="$t('tenantInvitation.shareLink.button')"
|
||||
:aria-label="$t('tenantInvitation.shareLink.button')">
|
||||
<template #icon><t-icon name="link" /></template>
|
||||
</t-button>
|
||||
<template #content>
|
||||
<div class="member-invite-popup-inner" @click.stop>
|
||||
<div class="member-invite-popup-title">
|
||||
{{
|
||||
shareLinkResult
|
||||
? $t('tenantInvitation.shareLink.resultTitle')
|
||||
: $t('tenantInvitation.shareLink.dialogTitle')
|
||||
}}
|
||||
</div>
|
||||
<div v-if="!shareLinkResult" class="member-invite-form">
|
||||
<p class="invite-confirm-body">
|
||||
{{ $t('tenantInvitation.shareLink.description', { days: INVITATION_TTL_DAYS }) }}
|
||||
</p>
|
||||
<t-form :data="shareLinkForm" :label-width="80">
|
||||
<t-form-item :label="$t('tenantMember.add.roleLabel')" name="role">
|
||||
<t-select v-model="shareLinkForm.role" :options="roleOptions"
|
||||
:popup-props="roleSelectPopupProps" />
|
||||
</t-form-item>
|
||||
</t-form>
|
||||
</div>
|
||||
<div v-else class="share-link-result">
|
||||
<p class="invite-confirm-body">
|
||||
{{ $t('tenantInvitation.shareLink.resultBody') }}
|
||||
</p>
|
||||
<div class="share-link-row">
|
||||
<input class="share-link-row__input"
|
||||
:value="absoluteInviteURL(shareLinkResult.invite_url || '')"
|
||||
readonly @click="($event.target as HTMLInputElement).select()" />
|
||||
<t-button size="small" theme="primary" variant="outline"
|
||||
@click="copyText(absoluteInviteURL(shareLinkResult.invite_url || ''))">
|
||||
<template #icon><t-icon name="copy" /></template>
|
||||
{{ $t('tenantInvitation.copyLink') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="invite-popup-footer">
|
||||
<t-button v-if="!shareLinkResult" variant="outline" :disabled="creatingShareLink"
|
||||
@click="shareLinkPopupVisible = false">
|
||||
{{ $t('common.cancel') }}
|
||||
</t-button>
|
||||
<t-button v-else variant="outline" @click="shareLinkPopupVisible = false">
|
||||
{{ $t('common.close') }}
|
||||
</t-button>
|
||||
<t-button v-if="!shareLinkResult" theme="primary" :loading="creatingShareLink"
|
||||
@click="submitShareLink">
|
||||
{{ $t('tenantInvitation.shareLink.generate') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="loading && members.length === 0" class="loading-inline">
|
||||
@@ -265,9 +358,11 @@
|
||||
:cancel-btn="{ content: $t('common.cancel') }"
|
||||
placement="left"
|
||||
@confirm="removeRow(row)">
|
||||
<t-button theme="danger" variant="text" size="small" @click.stop>
|
||||
{{ $t('tenantMember.remove.button') }}
|
||||
</t-button>
|
||||
<t-tooltip :content="$t('tenantMember.remove.button')" placement="top">
|
||||
<t-button theme="danger" shape="square" variant="text" size="small" @click.stop>
|
||||
<template #icon><t-icon name="user-clear" /></template>
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
</t-popconfirm>
|
||||
</template>
|
||||
</t-table>
|
||||
@@ -430,6 +525,7 @@ import {
|
||||
import {
|
||||
listTenantInvitations,
|
||||
createInvitation,
|
||||
createInviteLink,
|
||||
revokeInvitation,
|
||||
type TenantInvitation,
|
||||
} from '@/api/tenant/invitations'
|
||||
@@ -460,6 +556,13 @@ const error = ref('')
|
||||
const adding = ref(false)
|
||||
/** 邀请流程:锚在列表头「+」按钮旁的弹出层(非居中模态)。 */
|
||||
const invitePopupVisible = ref(false)
|
||||
// share-link generator state (separate popup next to the email
|
||||
// invite). shareLinkResult is non-null after a successful create —
|
||||
// the popup then switches into "here's your link, copy it" mode.
|
||||
const shareLinkPopupVisible = ref(false)
|
||||
const shareLinkForm = reactive<{ role: TenantRole }>({ role: 'contributor' })
|
||||
const creatingShareLink = ref(false)
|
||||
const shareLinkResult = ref<TenantInvitation | null>(null)
|
||||
// Two-step invite inside the popup: 'form' renders the email/role inputs;
|
||||
// 'confirm' swaps the body for an in-place summary; primary CTA toggles label.
|
||||
const addDialogStep = ref<'form' | 'confirm'>('form')
|
||||
@@ -626,7 +729,7 @@ const columns = computed(() => [
|
||||
{ colKey: 'member', title: t('tenantMember.columns.member'), ellipsis: true, minWidth: 132 },
|
||||
{ colKey: 'role', title: t('tenantMember.columns.role'), width: 128 },
|
||||
{ colKey: 'joined_at', title: t('tenantMember.columns.joinedAt'), width: 154 },
|
||||
{ colKey: 'actions', title: t('tenantMember.columns.operations'), width: 88, align: 'right' },
|
||||
{ colKey: 'actions', title: t('tenantMember.columns.operations'), width: 88, align: 'left' },
|
||||
])
|
||||
|
||||
function memberPrimary(row: { username?: string; email?: string }) {
|
||||
@@ -758,7 +861,7 @@ const invitationColumns = computed(() => [
|
||||
{ colKey: 'expires_at', title: t('tenantInvitation.columns.expiresAt'), width: 160 },
|
||||
{ colKey: 'status', title: t('tenantInvitation.columns.status'), width: 100 },
|
||||
...(canManage.value
|
||||
? [{ colKey: 'actions', title: t('tenantInvitation.columns.operations'), width: 88, align: 'right' as const }]
|
||||
? [{ colKey: 'actions', title: t('tenantInvitation.columns.operations'), width: 120, align: 'left' as const }]
|
||||
: []),
|
||||
])
|
||||
|
||||
@@ -1144,6 +1247,53 @@ watch(invitePopupVisible, (open) => {
|
||||
addDialogStep.value = 'form'
|
||||
})
|
||||
|
||||
// Share-link popup: re-init on every open so the operator never sees
|
||||
// the previous result on a fresh click.
|
||||
watch(shareLinkPopupVisible, (open) => {
|
||||
if (!open) return
|
||||
shareLinkForm.role = 'contributor'
|
||||
shareLinkResult.value = null
|
||||
})
|
||||
|
||||
// absoluteInviteURL turns the backend's potentially-host-relative
|
||||
// invite_url into a copy-friendly absolute URL. The backend returns
|
||||
// "/register?token=…" when FRONTEND_BASE_URL is unset (the typical
|
||||
// case); the SPA is best-positioned to know its own origin.
|
||||
function absoluteInviteURL(raw: string): string {
|
||||
if (!raw) return ''
|
||||
if (/^https?:\/\//i.test(raw)) return raw
|
||||
const origin = (typeof window !== 'undefined' && window.location && window.location.origin) || ''
|
||||
return raw.startsWith('/') ? origin + raw : origin + '/' + raw
|
||||
}
|
||||
|
||||
async function copyText(text: string) {
|
||||
if (!text) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
MessagePlugin.success(t('tenantInvitation.copied'))
|
||||
} catch {
|
||||
MessagePlugin.error(t('tenantInvitation.copyFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
async function submitShareLink() {
|
||||
creatingShareLink.value = true
|
||||
try {
|
||||
const resp = await createInviteLink(activeTenantId.value, { role: shareLinkForm.role })
|
||||
if (!resp.success || !resp.data) {
|
||||
MessagePlugin.error(resp.message || t('tenantInvitation.errors.generic'))
|
||||
return
|
||||
}
|
||||
shareLinkResult.value = resp.data
|
||||
invitationsPage.value = 1
|
||||
await loadInvitations()
|
||||
} catch (err: any) {
|
||||
MessagePlugin.error(err?.message || t('tenantInvitation.errors.generic'))
|
||||
} finally {
|
||||
creatingShareLink.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Live display strings for the in-place confirm step. Recomputed
|
||||
// every time the user goes Back, tweaks the form, and re-advances —
|
||||
// the summary always mirrors the current form state.
|
||||
@@ -1813,6 +1963,48 @@ watch(
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
/* Share-link result panel — single-row layout: input field stretches,
|
||||
* copy button stays fixed-width. Mirrors the rounded card style of
|
||||
* the surrounding popup. */
|
||||
.share-link-result {
|
||||
padding: 4px 0 0;
|
||||
}
|
||||
|
||||
.share-link-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.share-link-row__input {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
padding: 7px 10px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: 6px;
|
||||
background: var(--td-bg-color-page);
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 12px;
|
||||
color: var(--td-text-color-primary);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.share-link-row__input:focus {
|
||||
border-color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
/* Inline tag for share-link rows in the pending invitations list,
|
||||
* so they read as "this row is a share link" instead of looking like
|
||||
* a malformed per-user invitation with a missing email. */
|
||||
.share-link-title {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
color: var(--td-brand-color);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.pending-invitations-section {
|
||||
margin-bottom: 24px;
|
||||
display: flex;
|
||||
|
||||
@@ -38,6 +38,11 @@ func NewTenantInvitationRepository(db *gorm.DB) interfaces.TenantInvitationRepos
|
||||
// service layer treats any insert error containing the index name
|
||||
// (idx_tenant_invitations_unique_pending) as the conflict sentinel —
|
||||
// see invitationService.Create.
|
||||
//
|
||||
// Share-link rows (invitee_user_id == "") skip the pre-check: the
|
||||
// partial unique index on (tenant_id, invitee_user_id) deliberately
|
||||
// excludes empty values so multiple share links can coexist on a
|
||||
// tenant; pre-checking would falsely reject every additional one.
|
||||
func (r *tenantInvitationRepository) Create(
|
||||
ctx context.Context,
|
||||
inv *types.TenantInvitation,
|
||||
@@ -46,18 +51,20 @@ func (r *tenantInvitationRepository) Create(
|
||||
inv.Status = types.TenantInvitationStatusPending
|
||||
}
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var probe types.TenantInvitation
|
||||
err := tx.
|
||||
Where("tenant_id = ? AND invitee_user_id = ? AND status = ?",
|
||||
inv.TenantID, inv.InviteeUserID, types.TenantInvitationStatusPending).
|
||||
First(&probe).Error
|
||||
switch {
|
||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||
// fallthrough — clean to insert.
|
||||
case err != nil:
|
||||
return err
|
||||
default:
|
||||
return ErrPendingInvitationExists
|
||||
if inv.InviteeUserID != "" {
|
||||
var probe types.TenantInvitation
|
||||
err := tx.
|
||||
Where("tenant_id = ? AND invitee_user_id = ? AND status = ?",
|
||||
inv.TenantID, inv.InviteeUserID, types.TenantInvitationStatusPending).
|
||||
First(&probe).Error
|
||||
switch {
|
||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||
// fallthrough — clean to insert.
|
||||
case err != nil:
|
||||
return err
|
||||
default:
|
||||
return ErrPendingInvitationExists
|
||||
}
|
||||
}
|
||||
return tx.Create(inv).Error
|
||||
})
|
||||
@@ -101,6 +108,31 @@ func (r *tenantInvitationRepository) GetPendingByPair(
|
||||
return &inv, nil
|
||||
}
|
||||
|
||||
// GetActiveByToken returns the share-link row matching token, or
|
||||
// (nil, nil) if none. Empty token returns (nil, nil) defensively so
|
||||
// a malformed caller doesn't accidentally match the legacy "" sentinel
|
||||
// rows that have token=”.
|
||||
func (r *tenantInvitationRepository) GetActiveByToken(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (*types.TenantInvitation, error) {
|
||||
if token == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var inv types.TenantInvitation
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("token = ? AND status = ?",
|
||||
token, types.TenantInvitationStatusPending).
|
||||
First(&inv).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &inv, nil
|
||||
}
|
||||
|
||||
// listQuery centralises the "newest-first" ordering and includeTerminal
|
||||
// filter so ListByTenant / ListByInvitee stay short.
|
||||
func (r *tenantInvitationRepository) listQuery(includeTerminal bool) *gorm.DB {
|
||||
@@ -255,3 +287,27 @@ func (r *tenantInvitationRepository) SweepExpired(
|
||||
}
|
||||
return res.RowsAffected, nil
|
||||
}
|
||||
|
||||
// IncrementAcceptedCount bumps accepted_count by 1 for the given row.
|
||||
// Implemented as a single UPDATE expression so concurrent accepts
|
||||
// don't race on a read-modify-write loop. We deliberately don't gate
|
||||
// on status='pending' here: AcceptByToken is the only caller, and
|
||||
// share-link rows stay pending across accepts — so the gate would
|
||||
// reject zero rows in steady state but introduce a subtle ordering
|
||||
// dependency on MarkStatusIfPending for per-user accepts.
|
||||
func (r *tenantInvitationRepository) IncrementAcceptedCount(
|
||||
ctx context.Context,
|
||||
id uint64,
|
||||
) error {
|
||||
res := r.db.WithContext(ctx).
|
||||
Model(&types.TenantInvitation{}).
|
||||
Where("id = ?", id).
|
||||
UpdateColumn("accepted_count", gorm.Expr("accepted_count + 1"))
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -2,10 +2,13 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
|
||||
@@ -43,6 +46,14 @@ var (
|
||||
// caller is not the invitee. Owner-driven Revoke is gated at the
|
||||
// route layer so this error only surfaces on the /me/ paths.
|
||||
ErrInvitationForbidden = errors.New("only the invitee can accept or decline this invitation")
|
||||
|
||||
// ErrInvitationTokenInvalid is returned by LookupByToken /
|
||||
// AcceptByToken when the supplied plaintext token does not match
|
||||
// any active share-link row. The handler maps this to 410 Gone.
|
||||
// We deliberately collapse "unknown" / "expired" / "revoked" into
|
||||
// a single sentinel so an attacker can't probe which slots used
|
||||
// to exist.
|
||||
ErrInvitationTokenInvalid = errors.New("invitation token is invalid or has been revoked")
|
||||
)
|
||||
|
||||
// defaultInvitationTTL is the lifetime of a pending invitation before
|
||||
@@ -74,10 +85,10 @@ func invitationTTL() time.Duration {
|
||||
|
||||
// tenantInvitationService implements interfaces.TenantInvitationService.
|
||||
type tenantInvitationService struct {
|
||||
repo interfaces.TenantInvitationRepository
|
||||
memberSvc interfaces.TenantMemberService
|
||||
audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed
|
||||
now func() time.Time // injection seam for tests
|
||||
repo interfaces.TenantInvitationRepository
|
||||
memberSvc interfaces.TenantMemberService
|
||||
audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed
|
||||
now func() time.Time // injection seam for tests
|
||||
}
|
||||
|
||||
// NewTenantInvitationService wires the dependencies. memberSvc is
|
||||
@@ -428,3 +439,147 @@ func (s *tenantInvitationService) CountPendingByInvitee(
|
||||
s.sweep(ctx)
|
||||
return s.repo.CountPendingByInvitee(ctx, inviteeUserID)
|
||||
}
|
||||
|
||||
// invitationTokenBytes is the raw entropy length for share-link
|
||||
// tokens before base64url encoding. 32 bytes -> 256 bits, well above
|
||||
// the 128-bit floor for unguessable opaque tokens.
|
||||
const invitationTokenBytes = 32
|
||||
|
||||
// generateShareLinkToken returns a freshly-randomised plaintext token
|
||||
// (base64url, no padding) for a new share-link invitation.
|
||||
func generateShareLinkToken() (string, error) {
|
||||
buf := make([]byte, invitationTokenBytes)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
// CreateShareLink issues a multi-use share-link invitation. The token
|
||||
// is generated server-side and persisted plaintext on the row so the
|
||||
// management UI can re-display it on demand. Per-user invitation
|
||||
// constraints (already-member, duplicate-pending) do NOT apply here:
|
||||
// share-link rows have no specific invitee, multiple can coexist on
|
||||
// the same tenant, and consumption is non-destructive (see
|
||||
// AcceptByToken).
|
||||
func (s *tenantInvitationService) CreateShareLink(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
role types.TenantRole,
|
||||
invitedBy *string,
|
||||
message string,
|
||||
) (*types.TenantInvitation, string, error) {
|
||||
if !role.IsValid() {
|
||||
return nil, "", ErrInvalidTenantRole
|
||||
}
|
||||
token, err := generateShareLinkToken()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
now := s.now()
|
||||
inv := &types.TenantInvitation{
|
||||
TenantID: tenantID,
|
||||
InviteeUserID: "", // share-link rows have no specific invitee
|
||||
Token: token,
|
||||
InvitedBy: invitedBy,
|
||||
Role: role,
|
||||
Status: types.TenantInvitationStatusPending,
|
||||
Message: message,
|
||||
ExpiresAt: now.Add(invitationTTL()),
|
||||
}
|
||||
if err := s.repo.Create(ctx, inv); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
s.emitAudit(ctx, &types.AuditLog{
|
||||
TenantID: tenantID,
|
||||
ActorUserID: auditActor(ctx),
|
||||
ActorRole: auditActorRole(ctx),
|
||||
Action: types.AuditActionInvitationSent,
|
||||
TargetType: "tenant_invitation",
|
||||
TargetID: strconv.FormatUint(inv.ID, 10),
|
||||
// TargetUserID intentionally empty — share-link has no invitee yet.
|
||||
Outcome: types.AuditOutcomeSuccess,
|
||||
Details: detailsFor(inv.ID, role),
|
||||
})
|
||||
return inv, token, nil
|
||||
}
|
||||
|
||||
// LookupByToken resolves a plaintext share-link token to its row.
|
||||
// Sweeps overdue rows first so an expired link is reflected as
|
||||
// expired rather than letting the registration page accept it for a
|
||||
// few extra seconds. Multi-use semantics: a successful lookup does
|
||||
// not consume or modify the row.
|
||||
func (s *tenantInvitationService) LookupByToken(
|
||||
ctx context.Context,
|
||||
plainToken string,
|
||||
) (*types.TenantInvitation, error) {
|
||||
plainToken = strings.TrimSpace(plainToken)
|
||||
if plainToken == "" {
|
||||
return nil, ErrInvitationTokenInvalid
|
||||
}
|
||||
s.sweep(ctx)
|
||||
inv, err := s.repo.GetActiveByToken(ctx, plainToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if inv == nil {
|
||||
return nil, ErrInvitationTokenInvalid
|
||||
}
|
||||
if inv.IsExpired(s.now()) {
|
||||
return nil, ErrInvitationTokenInvalid
|
||||
}
|
||||
return inv, nil
|
||||
}
|
||||
|
||||
// AcceptByToken adds newUserID to the share-link's tenant + role.
|
||||
// Unlike Accept, the invitation row itself is NOT mutated — share-link
|
||||
// rows stay pending across uses. Idempotent: an existing membership
|
||||
// is returned untouched (callers shouldn't see role downgrade just
|
||||
// because they clicked the same link twice from different devices).
|
||||
func (s *tenantInvitationService) AcceptByToken(
|
||||
ctx context.Context,
|
||||
plainToken string,
|
||||
newUserID string,
|
||||
) (*types.TenantMember, error) {
|
||||
if newUserID == "" {
|
||||
return nil, errors.New("newUserID is required")
|
||||
}
|
||||
inv, err := s.LookupByToken(ctx, plainToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
member, err := s.memberSvc.AddMember(ctx, newUserID, inv.TenantID, inv.Role, inv.InvitedBy)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrMembershipAlreadyExists) {
|
||||
existing, getErr := s.memberSvc.GetMembership(ctx, newUserID, inv.TenantID)
|
||||
if getErr == nil && existing != nil {
|
||||
return existing, nil
|
||||
}
|
||||
}
|
||||
logger.Errorf(ctx,
|
||||
"share-link %d accept failed for user %s: %v",
|
||||
inv.ID, newUserID, err)
|
||||
return nil, err
|
||||
}
|
||||
// Bump usage counter so the management UI can show "N 人已加入".
|
||||
// Best-effort: a failure here doesn't undo the membership the user
|
||||
// just earned — log and move on. The counter is for display only;
|
||||
// audit log + tenant_members rows are the authoritative trail.
|
||||
if incErr := s.repo.IncrementAcceptedCount(ctx, inv.ID); incErr != nil {
|
||||
logger.Warnf(ctx,
|
||||
"share-link %d accepted_count bump failed (membership still created): %v",
|
||||
inv.ID, incErr)
|
||||
}
|
||||
s.emitAudit(ctx, &types.AuditLog{
|
||||
TenantID: inv.TenantID,
|
||||
ActorUserID: auditActor(ctx),
|
||||
ActorRole: auditActorRole(ctx),
|
||||
Action: types.AuditActionInvitationAccepted,
|
||||
TargetType: "tenant_invitation",
|
||||
TargetID: strconv.FormatUint(inv.ID, 10),
|
||||
TargetUserID: newUserID,
|
||||
Outcome: types.AuditOutcomeSuccess,
|
||||
Details: detailsFor(inv.ID, inv.Role),
|
||||
})
|
||||
return member, nil
|
||||
}
|
||||
|
||||
@@ -66,6 +66,22 @@ func (r *fakeInvitationRepo) GetPendingByPair(
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (r *fakeInvitationRepo) GetActiveByToken(
|
||||
ctx context.Context, token string,
|
||||
) (*types.TenantInvitation, error) {
|
||||
if token == "" {
|
||||
return nil, nil
|
||||
}
|
||||
for _, e := range r.rows {
|
||||
if e.Token == token &&
|
||||
e.Status == types.TenantInvitationStatusPending {
|
||||
cp := *e
|
||||
return &cp, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (r *fakeInvitationRepo) filteredTenantRows(
|
||||
tenantID uint64, includeTerminal bool,
|
||||
) []*types.TenantInvitation {
|
||||
@@ -179,6 +195,19 @@ func (r *fakeInvitationRepo) SweepExpired(
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r *fakeInvitationRepo) IncrementAcceptedCount(
|
||||
ctx context.Context, id uint64,
|
||||
) error {
|
||||
for _, e := range r.rows {
|
||||
if e.ID == id {
|
||||
e.AcceptedCount++
|
||||
e.UpdatedAt = time.Now()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return gormErrRecordNotFound
|
||||
}
|
||||
|
||||
var _ interfaces.TenantInvitationRepository = (*fakeInvitationRepo)(nil)
|
||||
|
||||
// newInvitationSvc returns a service wired against in-memory fakes for
|
||||
@@ -395,3 +424,131 @@ func TestInvitationService_CountPending(t *testing.T) {
|
||||
t.Fatalf("want 1 pending after decline, got %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
// --- share-link tests ---------------------------------------------------
|
||||
|
||||
func TestInvitationService_CreateShareLink_PersistsToken(t *testing.T) {
|
||||
svc, repo, _ := newInvitationSvc()
|
||||
inv, plain, err := svc.CreateShareLink(
|
||||
context.Background(), 1, types.TenantRoleContributor, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("create-share-link: %v", err)
|
||||
}
|
||||
if plain == "" {
|
||||
t.Fatalf("plain token must be returned for the URL")
|
||||
}
|
||||
row, _ := repo.GetByID(context.Background(), inv.ID)
|
||||
if row == nil {
|
||||
t.Fatalf("row missing")
|
||||
}
|
||||
if row.Token != plain {
|
||||
t.Fatalf("DB must store plaintext token (multi-use, short-lived), got %q vs %q", row.Token, plain)
|
||||
}
|
||||
if row.InviteeUserID != "" {
|
||||
t.Fatalf("share-link rows must have empty invitee_user_id, got %q", row.InviteeUserID)
|
||||
}
|
||||
if row.Status != types.TenantInvitationStatusPending {
|
||||
t.Fatalf("status must be pending, got %s", row.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_CreateShareLink_RejectsInvalidRole(t *testing.T) {
|
||||
svc, _, _ := newInvitationSvc()
|
||||
_, _, err := svc.CreateShareLink(
|
||||
context.Background(), 1, types.TenantRole("magician"), nil, "")
|
||||
if !errors.Is(err, ErrInvalidTenantRole) {
|
||||
t.Fatalf("want ErrInvalidTenantRole, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_LookupByToken_RejectsUnknownToken(t *testing.T) {
|
||||
svc, _, _ := newInvitationSvc()
|
||||
if _, err := svc.LookupByToken(context.Background(), "nonexistent"); !errors.Is(err, ErrInvitationTokenInvalid) {
|
||||
t.Fatalf("want ErrInvitationTokenInvalid, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_LookupByToken_RejectsExpired(t *testing.T) {
|
||||
svc, repo, _ := newInvitationSvc()
|
||||
_, plain, err := svc.CreateShareLink(context.Background(), 1, types.TenantRoleViewer, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
for _, r := range repo.rows {
|
||||
r.ExpiresAt = time.Now().Add(-time.Hour)
|
||||
}
|
||||
if _, err := svc.LookupByToken(context.Background(), plain); !errors.Is(err, ErrInvitationTokenInvalid) {
|
||||
t.Fatalf("expired token must reject, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_AcceptByToken_HappyPath(t *testing.T) {
|
||||
svc, repo, memberSvc := newInvitationSvc()
|
||||
ctx := context.Background()
|
||||
_, plain, err := svc.CreateShareLink(ctx, 1, types.TenantRoleAdmin, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
mb, err := svc.AcceptByToken(ctx, plain, "u-alice")
|
||||
if err != nil {
|
||||
t.Fatalf("accept-by-token: %v", err)
|
||||
}
|
||||
if mb == nil || mb.UserID != "u-alice" || mb.Role != types.TenantRoleAdmin {
|
||||
t.Fatalf("unexpected membership: %+v", mb)
|
||||
}
|
||||
if got, _ := memberSvc.GetMembership(ctx, "u-alice", 1); got == nil {
|
||||
t.Fatalf("membership row missing")
|
||||
}
|
||||
// Multi-use: row stays pending.
|
||||
rows, _ := repo.ListByTenant(ctx, 1, true)
|
||||
if len(rows) == 0 || rows[0].Status != types.TenantInvitationStatusPending {
|
||||
t.Fatalf("share-link row must remain pending after accept, got %+v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_AcceptByToken_AllowsMultipleUsers(t *testing.T) {
|
||||
svc, _, memberSvc := newInvitationSvc()
|
||||
ctx := context.Background()
|
||||
_, plain, err := svc.CreateShareLink(ctx, 1, types.TenantRoleViewer, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
if _, err := svc.AcceptByToken(ctx, plain, "u-alice"); err != nil {
|
||||
t.Fatalf("accept alice: %v", err)
|
||||
}
|
||||
if _, err := svc.AcceptByToken(ctx, plain, "u-bob"); err != nil {
|
||||
t.Fatalf("accept bob: %v", err)
|
||||
}
|
||||
a, _ := memberSvc.GetMembership(ctx, "u-alice", 1)
|
||||
b, _ := memberSvc.GetMembership(ctx, "u-bob", 1)
|
||||
if a == nil || b == nil {
|
||||
t.Fatalf("both users should have membership: alice=%v bob=%v", a, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_AcceptByToken_RevokedTokenRejected(t *testing.T) {
|
||||
svc, _, _ := newInvitationSvc()
|
||||
ctx := context.Background()
|
||||
inv, plain, err := svc.CreateShareLink(ctx, 1, types.TenantRoleViewer, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
if err := svc.Revoke(ctx, inv.ID); err != nil {
|
||||
t.Fatalf("revoke: %v", err)
|
||||
}
|
||||
if _, err := svc.AcceptByToken(ctx, plain, "u-alice"); !errors.Is(err, ErrInvitationTokenInvalid) {
|
||||
t.Fatalf("revoked token must reject, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvitationService_AcceptByToken_RequiresUserID(t *testing.T) {
|
||||
svc, _, _ := newInvitationSvc()
|
||||
ctx := context.Background()
|
||||
_, plain, err := svc.CreateShareLink(ctx, 1, types.TenantRoleViewer, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
if _, err := svc.AcceptByToken(ctx, plain, ""); err == nil {
|
||||
t.Fatalf("empty user id must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,12 @@ type Config struct {
|
||||
PromptTemplates *PromptTemplatesConfig `yaml:"prompt_templates" json:"prompt_templates"`
|
||||
IM *IMConfig `yaml:"im" json:"im"`
|
||||
Agent *AgentConfig `yaml:"agent" json:"agent"`
|
||||
// FrontendBaseURL is the externally-visible origin of the SPA, used
|
||||
// to compose absolute share-link URLs. Empty falls back to a host-
|
||||
// relative URL ("/register?token=…") which the SPA then resolves
|
||||
// against window.location.origin — fine for typical single-origin
|
||||
// deployments. Sourced from FRONTEND_BASE_URL env at startup.
|
||||
FrontendBaseURL string `yaml:"frontend_base_url" json:"frontend_base_url"`
|
||||
}
|
||||
|
||||
// AgentConfig represents the global agent settings.
|
||||
|
||||
@@ -27,6 +27,11 @@ type AuthHandler struct {
|
||||
tenantService interfaces.TenantService
|
||||
configInfo *config.Config
|
||||
systemSettingSvc interfaces.SystemSettingService
|
||||
// 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
|
||||
}
|
||||
|
||||
// NewAuthHandler creates a new auth handler instance with the provided services
|
||||
@@ -44,6 +49,7 @@ type AuthHandler struct {
|
||||
func NewAuthHandler(configInfo *config.Config,
|
||||
userService interfaces.UserService, tenantService interfaces.TenantService,
|
||||
systemSettingSvc interfaces.SystemSettingService,
|
||||
invitationSvc interfaces.TenantInvitationService,
|
||||
) *AuthHandler {
|
||||
// Boot-time guard: a nil-or-empty Auth section silently disables the
|
||||
// invite_only gate (see Register below). Emit a loud one-shot log
|
||||
@@ -60,6 +66,7 @@ func NewAuthHandler(configInfo *config.Config,
|
||||
userService: userService,
|
||||
tenantService: tenantService,
|
||||
systemSettingSvc: systemSettingSvc,
|
||||
invitationSvc: invitationSvc,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
// registerByInviteRequest is the body for /auth/register-by-invite.
|
||||
//
|
||||
// Email is collected from the invitee themselves: share-link rows have
|
||||
// no specific invitee, so we cannot pre-bind any address. The token
|
||||
// IS the authorisation; the email is whatever account the invitee
|
||||
// wants to register.
|
||||
type registerByInviteRequest struct {
|
||||
Token string `json:"token" binding:"required"`
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
}
|
||||
|
||||
// invitationLookupResponse is the public projection of a share-link
|
||||
// row returned by /auth/invitations/lookup. Kept narrow on purpose:
|
||||
// just enough for the registration page to render context ("X invited
|
||||
// you to Y") without exposing inviter audit fields.
|
||||
type invitationLookupResponse struct {
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
TenantName string `json:"tenant_name,omitempty"`
|
||||
Role types.TenantRole `json:"role"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
}
|
||||
|
||||
// invitationLookupRequest carries the token in the request body
|
||||
// instead of the URL path: GET /auth/invitations/:token would have
|
||||
// landed the plaintext token in access logs, browser history, and
|
||||
// tracing spans. POST + body keeps the token out of those surfaces
|
||||
// at the cost of "this endpoint reads, why is it POST" — worth it
|
||||
// because the token is the sole authorisation for registration.
|
||||
type invitationLookupRequest struct {
|
||||
Token string `json:"token" binding:"required"`
|
||||
}
|
||||
|
||||
// LookupInvitationByToken godoc
|
||||
// @Summary 解析共享邀请链接 token
|
||||
// @Description 根据邀请链接中的 token 返回邀请上下文(租户名 / 角色 / 过期时间),
|
||||
// @Description 供注册页展示。无认证;token 无效或被撤销返回 410。
|
||||
// @Description 使用 POST + body 而非 GET + path,避免 token 落入访问日志 / 浏览器历史 / tracing。
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body invitationLookupRequest true "邀请 token"
|
||||
// @Success 200 {object} invitationLookupResponse
|
||||
// @Failure 410 {object} errors.AppError "链接无效或已撤销"
|
||||
// @Router /auth/invitations/lookup [post]
|
||||
func (h *AuthHandler) LookupInvitationByToken(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
if h.invitationSvc == nil {
|
||||
c.Error(apperrors.NewInternalServerError("invitation service unavailable"))
|
||||
return
|
||||
}
|
||||
|
||||
var req invitationLookupRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.Error(apperrors.NewValidationError("token is required").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
token := strings.TrimSpace(req.Token)
|
||||
if token == "" {
|
||||
c.Error(apperrors.NewValidationError("token is required"))
|
||||
return
|
||||
}
|
||||
|
||||
inv, err := h.invitationSvc.LookupByToken(ctx, token)
|
||||
if err != nil {
|
||||
// Collapse "unknown / expired / revoked" into 410 to avoid
|
||||
// leaking which slot a stolen token used to occupy.
|
||||
c.Error(&apperrors.AppError{
|
||||
Code: apperrors.ErrNotFound,
|
||||
Message: "invitation link is invalid or has been revoked",
|
||||
HTTPCode: http.StatusGone,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
resp := invitationLookupResponse{
|
||||
TenantID: inv.TenantID,
|
||||
Role: inv.Role,
|
||||
ExpiresAt: inv.ExpiresAt.UTC().Format("2006-01-02T15:04:05Z07:00"),
|
||||
}
|
||||
if tenant, terr := h.tenantService.GetTenantByID(ctx, inv.TenantID); terr == nil && tenant != nil {
|
||||
resp.TenantName = tenant.Name
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": resp,
|
||||
})
|
||||
}
|
||||
|
||||
// RegisterByInvite godoc
|
||||
// @Summary 使用共享链接注册
|
||||
// @Description 通过 Owner 生成的共享邀请链接 token 完成注册,绕过 invite_only 模式拦截。
|
||||
// @Description 注册者自填邮箱(与 token 不绑定);注册成功后自动加入对应租户。
|
||||
// @Tags 认证
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body registerByInviteRequest true "邀请注册请求"
|
||||
// @Success 201 {object} types.LoginResponse
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 409 {object} errors.AppError "邮箱已注册"
|
||||
// @Failure 410 {object} errors.AppError "链接无效或已撤销"
|
||||
// @Router /auth/register-by-invite [post]
|
||||
//
|
||||
// RegisterByInvite is intentionally NOT subject to the invite_only gate:
|
||||
// the gate suppresses public registration, while this endpoint requires
|
||||
// a valid token issued by an Owner. The token IS the authorisation.
|
||||
func (h *AuthHandler) RegisterByInvite(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
if h.invitationSvc == nil {
|
||||
c.Error(apperrors.NewInternalServerError("invitation service unavailable"))
|
||||
return
|
||||
}
|
||||
|
||||
var req registerByInviteRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.Error(apperrors.NewValidationError("Invalid registration parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
req.Token = strings.TrimSpace(req.Token)
|
||||
req.Email = strings.TrimSpace(strings.ToLower(req.Email))
|
||||
req.Username = strings.TrimSpace(req.Username)
|
||||
// Password is intentionally NOT sanitized: SanitizeForLog strips
|
||||
// \n, \r, \t and control chars to make a string safe to write into
|
||||
// a log line — applying it to a real password would silently
|
||||
// rewrite the stored credential and lock the user out. Passwords
|
||||
// must never be logged, so they don't need that defence here.
|
||||
if req.Token == "" || req.Email == "" || req.Username == "" || req.Password == "" {
|
||||
c.Error(apperrors.NewValidationError("token, email, username and password are required"))
|
||||
return
|
||||
}
|
||||
|
||||
inv, err := h.invitationSvc.LookupByToken(ctx, req.Token)
|
||||
if err != nil {
|
||||
c.Error(&apperrors.AppError{
|
||||
Code: apperrors.ErrNotFound,
|
||||
Message: "invitation link is invalid or has been revoked",
|
||||
HTTPCode: http.StatusGone,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// If the email already has an account we shouldn't quietly succeed
|
||||
// here: register would fail with a duplicate-email error, but the
|
||||
// share-link flow is "create new account + join tenant", not "join
|
||||
// my existing account". Surface 409 so the SPA can prompt them to
|
||||
// log in instead, and the invitation can be applied to their
|
||||
// existing account via /me/invitations once we wire that path.
|
||||
if existing, _ := h.userService.GetUserByEmail(ctx, req.Email); existing != nil {
|
||||
c.Error(apperrors.NewConflictError(
|
||||
"this email already has an account; please log in to join the workspace"))
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.userService.Register(ctx, &types.RegisterRequest{
|
||||
Username: req.Username,
|
||||
Email: req.Email,
|
||||
Password: req.Password,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "register-by-invite: user create failed for %s: %v",
|
||||
secutils.SanitizeForLog(req.Email), err)
|
||||
c.Error(apperrors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.invitationSvc.AcceptByToken(ctx, req.Token, user.ID); err != nil {
|
||||
// Race: link was revoked between Lookup and Accept. The user
|
||||
// account is created either way — they can still log in.
|
||||
logger.Errorf(ctx, "register-by-invite: accept failed for user %s: %v", user.ID, err)
|
||||
c.Error(&apperrors.AppError{
|
||||
Code: apperrors.ErrNotFound,
|
||||
Message: "invitation link is no longer valid; please log in to your new account",
|
||||
HTTPCode: http.StatusGone,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
accessToken, refreshToken, err := h.userService.GenerateTokens(ctx, user)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "register-by-invite: token generation failed for user %s: %v", user.ID, err)
|
||||
c.Error(apperrors.NewInternalServerError("token generation failed").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
tenant, _ := h.tenantService.GetTenantByID(ctx, inv.TenantID)
|
||||
c.JSON(http.StatusCreated, &types.LoginResponse{
|
||||
Success: true,
|
||||
Message: "Registration successful",
|
||||
User: user,
|
||||
ActiveTenant: tenant,
|
||||
Memberships: []types.Membership{{
|
||||
TenantID: inv.TenantID,
|
||||
TenantName: tenantNameOrEmpty(tenant),
|
||||
Role: inv.Role,
|
||||
}},
|
||||
Token: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
})
|
||||
}
|
||||
@@ -89,7 +89,7 @@ func TestRegister_InviteOnlyRejects(t *testing.T) {
|
||||
}
|
||||
h := NewAuthHandler(&config.Config{
|
||||
Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeInviteOnly},
|
||||
}, us, nil, nil)
|
||||
}, us, nil, nil, nil)
|
||||
|
||||
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
|
||||
if w.Code != http.StatusForbidden {
|
||||
@@ -114,7 +114,7 @@ func TestRegister_SelfServeAllowsRegistration(t *testing.T) {
|
||||
}
|
||||
h := NewAuthHandler(&config.Config{
|
||||
Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeSelfServe},
|
||||
}, us, nil, nil)
|
||||
}, us, nil, nil, nil)
|
||||
|
||||
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
|
||||
if w.Code != http.StatusCreated {
|
||||
@@ -135,7 +135,7 @@ func TestRegister_NilAuthConfigDoesNotPanic(t *testing.T) {
|
||||
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
|
||||
},
|
||||
}
|
||||
h := NewAuthHandler(&config.Config{}, us, nil, nil)
|
||||
h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)
|
||||
|
||||
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
|
||||
if w.Code != http.StatusCreated {
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
@@ -26,20 +27,24 @@ type TenantInvitationHandler struct {
|
||||
invitationService interfaces.TenantInvitationService
|
||||
userService interfaces.UserService
|
||||
tenantService interfaces.TenantService
|
||||
configInfo *config.Config
|
||||
}
|
||||
|
||||
// NewTenantInvitationHandler wires the dependencies. tenantService is
|
||||
// used to hydrate tenant names in the inbox view so the invitee sees
|
||||
// "join Foo Workspace" instead of a raw numeric tenant id.
|
||||
// "join Foo Workspace" instead of a raw numeric tenant id. configInfo
|
||||
// supplies FrontendBaseURL for share-link URL composition.
|
||||
func NewTenantInvitationHandler(
|
||||
invitationService interfaces.TenantInvitationService,
|
||||
userService interfaces.UserService,
|
||||
tenantService interfaces.TenantService,
|
||||
configInfo *config.Config,
|
||||
) *TenantInvitationHandler {
|
||||
return &TenantInvitationHandler{
|
||||
invitationService: invitationService,
|
||||
userService: userService,
|
||||
tenantService: tenantService,
|
||||
configInfo: configInfo,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +78,11 @@ func parseInvitationIDFromPath(c *gin.Context) (uint64, bool) {
|
||||
// name are filled best-effort: a missing row degrades to the bare id
|
||||
// rather than dropping the response. usersByID and tenantsByID let the
|
||||
// caller batch the lookups when projecting a list.
|
||||
//
|
||||
// Share-link rows (InviteeUserID == "") get the IsShareLink flag set
|
||||
// so the SPA can render them differently. invite_url is NOT populated
|
||||
// here — projectInvitationWithLink layers it on for the management
|
||||
// view that needs the copy-link affordance.
|
||||
func projectInvitation(
|
||||
inv *types.TenantInvitation,
|
||||
usersByID map[string]*types.User,
|
||||
@@ -89,6 +99,8 @@ func projectInvitation(
|
||||
ExpiresAt: inv.ExpiresAt,
|
||||
RespondedAt: inv.RespondedAt,
|
||||
CreatedAt: inv.CreatedAt,
|
||||
IsShareLink: inv.InviteeUserID == "",
|
||||
AcceptedCount: inv.AcceptedCount,
|
||||
}
|
||||
if u, ok := usersByID[inv.InviteeUserID]; ok && u != nil {
|
||||
resp.InviteeEmail = u.Email
|
||||
@@ -106,6 +118,26 @@ func projectInvitation(
|
||||
return resp
|
||||
}
|
||||
|
||||
// projectInvitationWithLink layers invite_url on top of projectInvitation
|
||||
// for share-link rows that are still pending. The Owner-facing list and
|
||||
// the create response go through here so a "copy link" button can sit
|
||||
// on every active row — Owners can dispatch the link on demand without
|
||||
// the "copy now or revoke" pressure.
|
||||
//
|
||||
// The /me/invitations inbox path does NOT use this helper: per-user
|
||||
// invitees don't have a token to copy.
|
||||
func (h *TenantInvitationHandler) projectInvitationWithLink(
|
||||
inv *types.TenantInvitation,
|
||||
usersByID map[string]*types.User,
|
||||
tenantsByID map[uint64]*types.Tenant,
|
||||
) types.TenantInvitationResponse {
|
||||
resp := projectInvitation(inv, usersByID, tenantsByID)
|
||||
if inv.Status == types.TenantInvitationStatusPending && inv.Token != "" {
|
||||
resp.InviteURL = buildInviteRegisterURL(h.configInfo, inv.Token)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
// hydrateUsers batches GetUsersByIDs over the (invitee, inviter) pairs.
|
||||
// Best-effort: a transient lookup failure logs and returns an empty
|
||||
// map so the projection falls back to ids.
|
||||
@@ -191,7 +223,9 @@ func (h *TenantInvitationHandler) ListTenantInvitations(c *gin.Context) {
|
||||
for _, inv := range rows {
|
||||
// Within the tenant view we don't bother hydrating tenant name
|
||||
// (the caller already knows the tenant). Pass an empty map.
|
||||
resp = append(resp, projectInvitation(inv, usersByID, nil))
|
||||
// Use ...WithLink so management UI can re-display invite_url
|
||||
// for pending share-link rows (re-copy without revoking).
|
||||
resp = append(resp, h.projectInvitationWithLink(inv, usersByID, nil))
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// frontendBaseURLFor returns the externally-visible SPA origin used to
|
||||
// compose absolute share-link URLs. Lookup order:
|
||||
// 1. config.FrontendBaseURL (set in YAML or via ${FRONTEND_BASE_URL})
|
||||
// 2. FRONTEND_BASE_URL env at request time (so an operator can roll
|
||||
// the value out without restarting the server)
|
||||
// 3. empty — handler emits a host-relative URL ("/register?token=…")
|
||||
// and the SPA resolves it against the current origin.
|
||||
//
|
||||
// Trailing slashes are stripped so callers can append "/register?…"
|
||||
// cleanly.
|
||||
func frontendBaseURLFor(cfg *config.Config) string {
|
||||
candidate := ""
|
||||
if cfg != nil {
|
||||
candidate = strings.TrimSpace(cfg.FrontendBaseURL)
|
||||
}
|
||||
if candidate == "" {
|
||||
candidate = strings.TrimSpace(os.Getenv("FRONTEND_BASE_URL"))
|
||||
}
|
||||
return strings.TrimRight(candidate, "/")
|
||||
}
|
||||
|
||||
// buildInviteRegisterURL composes the registration URL Owners hand
|
||||
// to invitees. Plaintext token is URL-safe by construction (base64url)
|
||||
// so no extra escaping is required.
|
||||
func buildInviteRegisterURL(cfg *config.Config, plainToken string) string {
|
||||
if plainToken == "" {
|
||||
return ""
|
||||
}
|
||||
return frontendBaseURLFor(cfg) + "/register?token=" + plainToken
|
||||
}
|
||||
|
||||
// createInviteLinkRequest is the body for POST /tenants/:id/invite-links.
|
||||
// Only role + optional message — share-link rows have no specific
|
||||
// invitee, so the Owner just picks "what role does the holder get".
|
||||
type createInviteLinkRequest struct {
|
||||
Role types.TenantRole `json:"role" binding:"required"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// CreateInviteLink godoc
|
||||
// @Summary 生成共享邀请链接
|
||||
// @Description 生成一条多次使用的共享邀请链接:谁拿到链接谁就能注册并加入当前租户。
|
||||
// @Description 链接持续有效,直到过期或被撤销。
|
||||
// @Tags 租户邀请
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "租户 ID"
|
||||
// @Param request body createInviteLinkRequest true "共享链接配置"
|
||||
// @Success 201 {object} map[string]interface{}
|
||||
// @Security Bearer
|
||||
// @Router /tenants/{id}/invite-links [post]
|
||||
func (h *TenantInvitationHandler) CreateInviteLink(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
tenantID, ok := parseTenantIDFromPath(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req createInviteLinkRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.Error(apperrors.NewValidationError("invalid request body").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
if !req.Role.IsValid() {
|
||||
c.Error(apperrors.NewValidationError("role must be one of owner/admin/contributor/viewer"))
|
||||
return
|
||||
}
|
||||
|
||||
caller, _ := types.UserIDFromContext(ctx)
|
||||
var invitedBy *string
|
||||
if caller != "" && !types.IsSyntheticUserID(caller) {
|
||||
invitedBy = &caller
|
||||
}
|
||||
|
||||
inv, _, err := h.invitationService.CreateShareLink(ctx, tenantID, req.Role, invitedBy, req.Message)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "CreateShareLink failed: tenant=%d err=%v", tenantID, err)
|
||||
c.Error(apperrors.NewInternalServerError("failed to create share link").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
usersByID := map[string]*types.User{}
|
||||
if invitedBy != nil {
|
||||
if iu, lookupErr := h.userService.GetUserByID(ctx, *invitedBy); lookupErr == nil && iu != nil {
|
||||
usersByID[iu.ID] = iu
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"success": true,
|
||||
"data": h.projectInvitationWithLink(inv, usersByID, nil),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// auth_public_ratelimit.go — sliding-window IP rate limiter for the
|
||||
// unauthenticated share-link endpoints (/auth/invitations/lookup and
|
||||
// /auth/register-by-invite). Both surfaces accept a plaintext token
|
||||
// from the request and either reveal tenant context (lookup) or
|
||||
// create an account (register-by-invite); without a limiter an
|
||||
// attacker can brute-force token guesses and hammer registration.
|
||||
//
|
||||
// The token is 256-bit so guessing the space is infeasible regardless,
|
||||
// but the limiter still narrows the abuse window for partial-token
|
||||
// leaks (e.g. via referrer / clipboard managers / accidental commits)
|
||||
// and bounds the noise this endpoint can add to the user-create path.
|
||||
//
|
||||
// Local in-memory only — fine for typical deployments since both
|
||||
// endpoints handle low absolute volumes; if/when WeKnora horizontally
|
||||
// scales the auth surface, swap to the Redis-backed limiter in
|
||||
// internal/im/ratelimit.go (kept lowercase / package-private today).
|
||||
|
||||
// publicAuthRateLimitWindow is the rolling window length per IP.
|
||||
const publicAuthRateLimitWindow = 60 * time.Second
|
||||
|
||||
// publicAuthRateLimitMax is the request budget per IP per window for
|
||||
// each endpoint instance. 30/min comfortably covers a real user
|
||||
// retrying a failed registration while clamping enumeration
|
||||
// throughput to ~half a request per second.
|
||||
const publicAuthRateLimitMax = 30
|
||||
|
||||
// publicAuthRateLimitCleanupInterval bounds map growth from one-off
|
||||
// IPs that never come back.
|
||||
const publicAuthRateLimitCleanupInterval = 2 * time.Minute
|
||||
|
||||
type ipBucket struct {
|
||||
mu sync.Mutex
|
||||
timestamps []time.Time
|
||||
}
|
||||
|
||||
type ipRateLimiter struct {
|
||||
window time.Duration
|
||||
max int
|
||||
buckets sync.Map // string (IP) -> *ipBucket
|
||||
}
|
||||
|
||||
func newIPRateLimiter(window time.Duration, max int) *ipRateLimiter {
|
||||
l := &ipRateLimiter{window: window, max: max}
|
||||
go l.cleanupLoop()
|
||||
return l
|
||||
}
|
||||
|
||||
// allow returns true if the IP is within budget for the current
|
||||
// window. Empty IP (proxy stripped X-Forwarded-For) is treated as a
|
||||
// shared bucket — slightly over-restrictive vs. dropping the limit
|
||||
// entirely, which would let a misconfigured proxy bypass the gate.
|
||||
func (l *ipRateLimiter) allow(ip string) bool {
|
||||
if ip == "" {
|
||||
ip = "_unknown_"
|
||||
}
|
||||
now := time.Now()
|
||||
cutoff := now.Add(-l.window)
|
||||
|
||||
val, _ := l.buckets.LoadOrStore(ip, &ipBucket{})
|
||||
b := val.(*ipBucket)
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
kept := b.timestamps[:0]
|
||||
for _, t := range b.timestamps {
|
||||
if t.After(cutoff) {
|
||||
kept = append(kept, t)
|
||||
}
|
||||
}
|
||||
b.timestamps = kept
|
||||
if len(b.timestamps) >= l.max {
|
||||
return false
|
||||
}
|
||||
b.timestamps = append(b.timestamps, now)
|
||||
return true
|
||||
}
|
||||
|
||||
func (l *ipRateLimiter) cleanupLoop() {
|
||||
t := time.NewTicker(publicAuthRateLimitCleanupInterval)
|
||||
defer t.Stop()
|
||||
for range t.C {
|
||||
cutoff := time.Now().Add(-l.window)
|
||||
l.buckets.Range(func(k, v any) bool {
|
||||
b := v.(*ipBucket)
|
||||
b.mu.Lock()
|
||||
drop := len(b.timestamps) == 0 ||
|
||||
b.timestamps[len(b.timestamps)-1].Before(cutoff)
|
||||
b.mu.Unlock()
|
||||
if drop {
|
||||
l.buckets.Delete(k)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// publicAuthLimiter — package-singleton so each route registration
|
||||
// shares a single bucket map per process. Each route still gets its
|
||||
// own Gin handler that calls into this same limiter; per-route
|
||||
// isolation isn't important here (real users don't hit both
|
||||
// endpoints in the same window) but the shared state makes total
|
||||
// budget per IP intuitive: 30/min across all share-link surfaces.
|
||||
var publicAuthLimiter = newIPRateLimiter(
|
||||
publicAuthRateLimitWindow, publicAuthRateLimitMax)
|
||||
|
||||
// PublicAuthRateLimit returns a Gin middleware that rate-limits the
|
||||
// unauthenticated share-link endpoints by client IP. 429 is mapped
|
||||
// through the project's AppError type so it flows through the same
|
||||
// error middleware as the rest of the auth surface.
|
||||
func PublicAuthRateLimit() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ip := c.ClientIP()
|
||||
if !publicAuthLimiter.allow(ip) {
|
||||
c.Error(&apperrors.AppError{
|
||||
Code: apperrors.ErrTooManyRequests,
|
||||
Message: "too many requests; please retry shortly",
|
||||
HTTPCode: http.StatusTooManyRequests,
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -565,6 +565,11 @@ func RegisterTenantRoutes(
|
||||
tenantByID.GET("/invitations", g.Viewer(), invitationHandler.ListTenantInvitations)
|
||||
tenantByID.POST("/invitations", g.Owner(), invitationHandler.CreateInvitation)
|
||||
tenantByID.DELETE("/invitations/:inv_id", g.Owner(), invitationHandler.RevokeInvitation)
|
||||
// Share-link create lives under /invite-links so the URL
|
||||
// reads as "create a link" rather than another flavour
|
||||
// of /invitations; the underlying row still lives in the
|
||||
// tenant_invitations table and shows up in the GET above.
|
||||
tenantByID.POST("/invite-links", g.Owner(), invitationHandler.CreateInviteLink)
|
||||
}
|
||||
|
||||
// Audit log feed (PR 6 of #1303). Admin+ so denied-action
|
||||
@@ -650,6 +655,14 @@ func RegisterMyInvitationRoutes(r *gin.RouterGroup, invitationHandler *handler.T
|
||||
// RegisterAuthRoutes registers authentication routes
|
||||
func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
|
||||
r.POST("/auth/register", handler.Register)
|
||||
// Share-link surfaces are unauthenticated and accept a plaintext
|
||||
// token from the caller; rate-limit by IP to bound brute-force /
|
||||
// enumeration / abuse traffic. Limiter is shared across both
|
||||
// endpoints (see middleware/auth_public_ratelimit.go) so total
|
||||
// budget per IP is intuitive.
|
||||
publicAuthRL := middleware.PublicAuthRateLimit()
|
||||
r.POST("/auth/register-by-invite", publicAuthRL, handler.RegisterByInvite)
|
||||
r.POST("/auth/invitations/lookup", publicAuthRL, handler.LookupInvitationByToken)
|
||||
r.POST("/auth/login", handler.Login)
|
||||
r.POST("/auth/auto-setup", handler.AutoSetup)
|
||||
r.GET("/auth/config", handler.GetAuthConfig)
|
||||
|
||||
@@ -26,6 +26,14 @@ type TenantInvitationRepository interface {
|
||||
// they hit the unique index.
|
||||
GetPendingByPair(ctx context.Context, tenantID uint64, inviteeUserID string) (*types.TenantInvitation, error)
|
||||
|
||||
// GetActiveByToken looks up the share-link row matching the
|
||||
// supplied plaintext token. Returns (nil, nil) if no row matches
|
||||
// or the row is no longer pending. "Active" rather than "pending
|
||||
// for a single user" because share-link rows are multi-use:
|
||||
// AcceptByToken does NOT consume them, only Revoke or expiry
|
||||
// removes them from circulation.
|
||||
GetActiveByToken(ctx context.Context, token string) (*types.TenantInvitation, error)
|
||||
|
||||
// ListByTenant returns invitations for the tenant ordered by
|
||||
// id DESC (newest first). includeTerminal controls whether
|
||||
// non-pending rows (accepted/declined/revoked/expired) are
|
||||
@@ -71,4 +79,10 @@ type TenantInvitationRepository interface {
|
||||
// events (we don't — the volume could be high and the audit-log
|
||||
// table already records the original invitation_sent rows).
|
||||
SweepExpired(ctx context.Context, now time.Time) (int64, error)
|
||||
|
||||
// IncrementAcceptedCount atomically bumps accepted_count by 1.
|
||||
// Used by AcceptByToken so the management UI can show "N 人已通过
|
||||
// 此链接加入" for share-link rows. Per-user invitations also call
|
||||
// this on accept; the count just caps at 1 there.
|
||||
IncrementAcceptedCount(ctx context.Context, id uint64) error
|
||||
}
|
||||
|
||||
@@ -64,4 +64,34 @@ type TenantInvitationService interface {
|
||||
// after running the lazy sweep, so the inbox badge can poll a
|
||||
// lightweight endpoint without paginating the full list.
|
||||
CountPendingByInvitee(ctx context.Context, inviteeUserID string) (int64, error)
|
||||
|
||||
// CreateShareLink generates a multi-use share-link invitation for
|
||||
// the tenant. The plaintext token is persisted on the row and also
|
||||
// returned for the handler to compose the registration URL — the
|
||||
// token stays available via list/get for as long as the row is
|
||||
// pending so Owners can re-share without "copy now or lose it"
|
||||
// pressure. Multiple share-link rows can coexist on the same
|
||||
// tenant (different roles, or just multiple campaigns).
|
||||
CreateShareLink(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
role types.TenantRole,
|
||||
invitedBy *string,
|
||||
message string,
|
||||
) (inv *types.TenantInvitation, plainToken string, err error)
|
||||
|
||||
// LookupByToken resolves a plaintext token to its active share-link
|
||||
// row. Returns ErrInvitationTokenInvalid for unknown / expired /
|
||||
// revoked tokens to avoid leaking which tokens used to exist. The
|
||||
// row is NOT consumed; the same token can be looked up arbitrarily
|
||||
// many times until it expires or the Owner revokes it.
|
||||
LookupByToken(ctx context.Context, plainToken string) (*types.TenantInvitation, error)
|
||||
|
||||
// AcceptByToken creates a tenant_members row binding newUserID to
|
||||
// the share-link's tenant + role. Unlike Accept, this does NOT flip
|
||||
// the invitation row into a terminal state — share-link rows stay
|
||||
// pending so subsequent invitees can also register through the
|
||||
// same link. Idempotent: if the user already has membership, the
|
||||
// existing row is returned.
|
||||
AcceptByToken(ctx context.Context, plainToken string, newUserID string) (*types.TenantMember, error)
|
||||
}
|
||||
|
||||
@@ -64,9 +64,22 @@ type TenantInvitation struct {
|
||||
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
// TenantID references tenants.id.
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
// InviteeUserID references users.id (always a registered user; the
|
||||
// handler resolves the email to a User row before insertion).
|
||||
InviteeUserID string `json:"invitee_user_id" gorm:"type:varchar(36);not null;index"`
|
||||
// InviteeUserID references users.id when this row represents a
|
||||
// per-user invitation (Owner picked a registered email). For
|
||||
// share-link rows the field is the empty-string sentinel — there
|
||||
// is no specific invitee yet; whoever holds the link can register.
|
||||
// The (tenant_id, invitee_user_id) partial unique index in
|
||||
// migration 000054 was relaxed to skip empty values so multiple
|
||||
// share-link rows can coexist per tenant.
|
||||
InviteeUserID string `json:"invitee_user_id" gorm:"type:varchar(36);not null;default:'';index"`
|
||||
// Token holds the plaintext registration token for share-link
|
||||
// rows. Empty for per-user invitations (those use the in-app
|
||||
// inbox, not a URL). Stored plaintext so the management UI can
|
||||
// re-display the link on demand — the threat model is bounded by
|
||||
// short TTL, revocability, and the fact that all the link grants
|
||||
// is membership in this one tenant. Excluded from JSON to keep
|
||||
// the wire shape small; handlers emit invite_url instead.
|
||||
Token string `json:"-" gorm:"column:token;type:varchar(64);not null;default:'';index"`
|
||||
// InvitedBy records the user id that issued this invitation. NULL
|
||||
// for invitations created via service-internal / synthetic actors
|
||||
// (mirrors the same treatment TenantMember.InvitedBy gets).
|
||||
@@ -87,6 +100,13 @@ type TenantInvitation struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
|
||||
// AcceptedCount counts how many users have completed registration
|
||||
// through this invitation. Per-user invitations cap out at 1 (and
|
||||
// the row flips to accepted in the same step). Share-link rows can
|
||||
// accumulate many — this is what the management UI surfaces as the
|
||||
// "已加入 N 人" caption so Owners can see whether a link is fresh
|
||||
// or has already been used widely.
|
||||
AcceptedCount int `json:"accepted_count" gorm:"column:accepted_count;not null;default:0"`
|
||||
}
|
||||
|
||||
// TableName binds TenantInvitation to the tenant_invitations table.
|
||||
@@ -122,4 +142,17 @@ type TenantInvitationResponse struct {
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
RespondedAt *time.Time `json:"responded_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// InviteURL is set on share-link rows that are still pending.
|
||||
// Composed by the handler from FrontendBaseURL + the row's plaintext
|
||||
// token, so the management UI can render a "copy link" button per
|
||||
// row without ever exposing the raw token through the JSON wire.
|
||||
InviteURL string `json:"invite_url,omitempty"`
|
||||
// IsShareLink is a convenience flag so the SPA doesn't have to
|
||||
// special-case "invitee_user_id == ''" everywhere when distinguishing
|
||||
// share-link rows from per-user invitations.
|
||||
IsShareLink bool `json:"is_share_link,omitempty"`
|
||||
// AcceptedCount mirrors TenantInvitation.AcceptedCount. Surfaced
|
||||
// for share-link rows so the management UI can show "N 人已通过此
|
||||
// 链接加入"; informational only for per-user invitations.
|
||||
AcceptedCount int `json:"accepted_count,omitempty"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
-- Reverse of 000054_invitation_share_links.
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000054] Reverting share-link columns on tenant_invitations'; END $$;
|
||||
|
||||
DROP INDEX IF EXISTS idx_tenant_invitations_token;
|
||||
DROP INDEX IF EXISTS idx_tenant_invitations_unique_pending;
|
||||
|
||||
-- Share-link rows have invitee_user_id='' and the up migration's index
|
||||
-- explicitly excludes those values; the legacy index does not. If we
|
||||
-- recreate the legacy unique index while multiple share-link rows
|
||||
-- coexist on a tenant, the CREATE will abort with duplicate-key. Drop
|
||||
-- the share-link rows before rebuilding so the rollback is idempotent
|
||||
-- regardless of how many share links the tenant has issued. This is
|
||||
-- intentionally destructive — share-link rows have no per-user state
|
||||
-- worth preserving (no specific invitee, no pending acceptance), and
|
||||
-- the only alternative would be leaving orphaned rows the legacy
|
||||
-- schema can't represent.
|
||||
DELETE FROM tenant_invitations
|
||||
WHERE invitee_user_id = ''
|
||||
AND deleted_at IS NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_tenant_invitations_unique_pending
|
||||
ON tenant_invitations(tenant_id, invitee_user_id)
|
||||
WHERE status = 'pending' AND deleted_at IS NULL;
|
||||
|
||||
ALTER TABLE tenant_invitations
|
||||
DROP COLUMN IF EXISTS accepted_count,
|
||||
DROP COLUMN IF EXISTS token,
|
||||
ALTER COLUMN invitee_user_id DROP DEFAULT;
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000054] tenant_invitations reverted'; END $$;
|
||||
@@ -0,0 +1,48 @@
|
||||
-- Migration: 000054_invitation_share_links
|
||||
-- Extends tenant_invitations with the columns needed for "share link"
|
||||
-- invitations: a multi-use registration link an Owner can drop in a
|
||||
-- group chat. The existing per-user invitation flow (rows with a real
|
||||
-- invitee_user_id) keeps working unchanged.
|
||||
--
|
||||
-- Schema changes:
|
||||
-- * invitee_user_id is given a default empty string. Share-link rows
|
||||
-- start with no specific invitee — whoever holds the link
|
||||
-- registers themselves with their own email. Per-user invitations
|
||||
-- still write the resolved user id at create-time.
|
||||
-- * token holds the plaintext registration token for share-link
|
||||
-- rows. We store plaintext (not a hash) deliberately: the threat
|
||||
-- model is bounded by short TTL, revocability, and the fact that
|
||||
-- consuming the link only grants membership in one tenant.
|
||||
-- Plaintext lets the management UI re-display the link on demand
|
||||
-- so the Owner doesn't have to "copy now or revoke and re-issue".
|
||||
-- * accepted_count counts how many users have completed registration
|
||||
-- through the row. Per-user invitations cap at 1 and flip to
|
||||
-- accepted in the same step; share-link rows accumulate — surfaced
|
||||
-- in the management UI as "N 人已加入" so Owners can tell whether
|
||||
-- a link is fresh or has already been used widely.
|
||||
--
|
||||
-- Index changes:
|
||||
-- * The pending-uniqueness index on (tenant_id, invitee_user_id) is
|
||||
-- relaxed to skip empty values so multiple share-link rows can
|
||||
-- coexist on the same tenant.
|
||||
-- * token gets its own partial unique index for lookup at
|
||||
-- /auth/register-by-invite.
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000054] Extending tenant_invitations for share-link invitations'; END $$;
|
||||
|
||||
ALTER TABLE tenant_invitations
|
||||
ALTER COLUMN invitee_user_id SET DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS token VARCHAR(64) NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS accepted_count INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
DROP INDEX IF EXISTS idx_tenant_invitations_unique_pending;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_tenant_invitations_unique_pending
|
||||
ON tenant_invitations(tenant_id, invitee_user_id)
|
||||
WHERE status = 'pending'
|
||||
AND deleted_at IS NULL
|
||||
AND invitee_user_id <> '';
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_tenant_invitations_token
|
||||
ON tenant_invitations(token)
|
||||
WHERE token <> '' AND deleted_at IS NULL;
|
||||
|
||||
DO $$ BEGIN RAISE NOTICE '[Migration 000054] tenant_invitations extended'; END $$;
|
||||
Reference in New Issue
Block a user