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;
|
||||
|
||||
Reference in New Issue
Block a user