feat(auth): add BOM-costing-only account access
This commit is contained in:
parent
3ba90b83e0
commit
d264efc2e7
73
furniture-3d-system/src/lib/auth-middleware.test.ts
Normal file
73
furniture-3d-system/src/lib/auth-middleware.test.ts
Normal file
@ -0,0 +1,73 @@
|
||||
import type { NextRequest } from 'next/server'
|
||||
|
||||
const mockValidateToken = jest.fn()
|
||||
const mockGetUserInfo = jest.fn()
|
||||
|
||||
jest.mock('./token-validator', () => ({
|
||||
validateToken: (...args: unknown[]) => mockValidateToken(...args),
|
||||
}))
|
||||
|
||||
jest.mock('./permissions', () => ({
|
||||
getUserInfo: (...args: unknown[]) => mockGetUserInfo(...args),
|
||||
}))
|
||||
|
||||
jest.mock('./jwt', () => ({
|
||||
extractTokenFromHeader: () => null,
|
||||
}))
|
||||
|
||||
const { authenticateRequest } = require('./auth-middleware') as typeof import('./auth-middleware')
|
||||
|
||||
function buildRequest(path: string, method = 'GET') {
|
||||
return {
|
||||
method,
|
||||
nextUrl: new URL(`http://localhost${path}`),
|
||||
headers: new Headers(),
|
||||
cookies: {
|
||||
get: (name: string) => (name === 'auth-token' ? { value: 'signed-token' } : undefined),
|
||||
},
|
||||
} as unknown as NextRequest
|
||||
}
|
||||
|
||||
describe('BOM-only API authentication boundary', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
mockValidateToken.mockResolvedValue({ userId: 'bom-only-user', role: 'USER' })
|
||||
mockGetUserInfo.mockResolvedValue({
|
||||
id: 'bom-only-user',
|
||||
email: 'bom-only@example.com',
|
||||
name: 'BOM Only User',
|
||||
role: 'USER',
|
||||
status: 'ACTIVE',
|
||||
businessRoles: ['EXTERNAL_INTAKE'],
|
||||
loginSource: 'LOCAL_BOM_COSTING_ONLY',
|
||||
})
|
||||
})
|
||||
|
||||
it('allows BOM APIs', async () => {
|
||||
await expect(
|
||||
authenticateRequest(buildRequest('/api/bom-costing/cases')),
|
||||
).resolves.toMatchObject({ success: true })
|
||||
})
|
||||
|
||||
it('blocks other authenticated business APIs', async () => {
|
||||
await expect(
|
||||
authenticateRequest(buildRequest('/api/intake/non-integrated')),
|
||||
).resolves.toEqual({
|
||||
success: false,
|
||||
error: '当前账号仅可访问 BOM 核算',
|
||||
})
|
||||
})
|
||||
|
||||
it('allows only BOM-owned storage objects', async () => {
|
||||
await expect(
|
||||
authenticateRequest(
|
||||
buildRequest('/api/storage/object?key=prod%2Fbom-costing%2Fsources%2Fmain.webp'),
|
||||
),
|
||||
).resolves.toMatchObject({ success: true })
|
||||
await expect(
|
||||
authenticateRequest(
|
||||
buildRequest('/api/storage/object?key=non-integrated-assets%2Fproduct%2Fmain.webp'),
|
||||
),
|
||||
).resolves.toMatchObject({ success: false })
|
||||
})
|
||||
})
|
||||
@ -10,6 +10,10 @@ import { getUserInfo, UserInfo } from './permissions';
|
||||
import { validateToken } from './token-validator';
|
||||
import type { AllowedRole } from './role-scope';
|
||||
import { hasAllowedRole } from './role-scope';
|
||||
import {
|
||||
canBomCostingOnlyUserAccessApi,
|
||||
} from './bom-costing-permissions';
|
||||
import { isBomCostingOnlyUser } from './non-integrated-external-entry-permissions';
|
||||
|
||||
/**
|
||||
* 认证结果
|
||||
@ -78,6 +82,20 @@ export async function authenticateRequest(request: NextRequest): Promise<AuthRes
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
isBomCostingOnlyUser(userInfo) &&
|
||||
!canBomCostingOnlyUserAccessApi(
|
||||
request.nextUrl.pathname,
|
||||
request.method,
|
||||
request.nextUrl.searchParams.get('key'),
|
||||
)
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error: '当前账号仅可访问 BOM 核算',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload,
|
||||
|
||||
@ -1,8 +1,11 @@
|
||||
import {
|
||||
BOM_COSTING_API_PATH,
|
||||
BOM_COSTING_WORKBENCH_PATH,
|
||||
canBomCostingOnlyUserAccessApi,
|
||||
canViewBomCostingWorkbench,
|
||||
} from './bom-costing-permissions'
|
||||
import { canAccessWorkspacePath } from './workspace-route-permissions'
|
||||
import { BOM_COSTING_ONLY_LOGIN_SOURCE } from './non-integrated-external-entry-permissions'
|
||||
|
||||
describe('BOM 核算权限', () => {
|
||||
it.each(['OPERATIONS', 'PLANNING', 'PURCHASING', 'DESIGN'])(
|
||||
@ -47,4 +50,39 @@ describe('BOM 核算权限', () => {
|
||||
}),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('只为带专用登录来源的外部账号开放 BOM 核算', () => {
|
||||
const user = {
|
||||
role: 'USER',
|
||||
businessRoles: ['EXTERNAL_INTAKE'],
|
||||
loginSource: BOM_COSTING_ONLY_LOGIN_SOURCE,
|
||||
}
|
||||
|
||||
expect(canViewBomCostingWorkbench(user)).toBe(true)
|
||||
expect(canAccessWorkspacePath(BOM_COSTING_WORKBENCH_PATH, user)).toBe(true)
|
||||
expect(canAccessWorkspacePath('/intake', user)).toBe(false)
|
||||
})
|
||||
|
||||
it('只放行 BOM 专用账号必需的 API', () => {
|
||||
expect(canBomCostingOnlyUserAccessApi(BOM_COSTING_API_PATH, 'GET')).toBe(true)
|
||||
expect(canBomCostingOnlyUserAccessApi(`${BOM_COSTING_API_PATH}/cases`, 'POST')).toBe(true)
|
||||
expect(canBomCostingOnlyUserAccessApi('/api/auth/me', 'GET')).toBe(true)
|
||||
expect(canBomCostingOnlyUserAccessApi('/api/auth/logout', 'POST')).toBe(true)
|
||||
expect(
|
||||
canBomCostingOnlyUserAccessApi(
|
||||
'/api/storage/object',
|
||||
'GET',
|
||||
'prod/bom-costing/sources/main.webp',
|
||||
),
|
||||
).toBe(true)
|
||||
expect(
|
||||
canBomCostingOnlyUserAccessApi(
|
||||
'/api/storage/object',
|
||||
'GET',
|
||||
'non-integrated-assets/product/main.webp',
|
||||
),
|
||||
).toBe(false)
|
||||
expect(canBomCostingOnlyUserAccessApi('/api/intake/non-integrated', 'GET')).toBe(false)
|
||||
expect(canBomCostingOnlyUserAccessApi('/api/users', 'GET')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,8 +1,12 @@
|
||||
import type { ScopedRoleUser } from './role-scope'
|
||||
import { isExternalIntakeUser } from './non-integrated-external-entry-permissions'
|
||||
import {
|
||||
isBomCostingOnlyUser,
|
||||
isExternalIntakeUser,
|
||||
} from './non-integrated-external-entry-permissions'
|
||||
import { isSupplierAccount } from './supplier-account'
|
||||
|
||||
export const BOM_COSTING_WORKBENCH_PATH = '/bom-costing'
|
||||
export const BOM_COSTING_API_PATH = '/api/bom-costing'
|
||||
|
||||
const BOM_COSTING_BUSINESS_ROLES = new Set([
|
||||
'OPERATIONS',
|
||||
@ -11,12 +15,39 @@ const BOM_COSTING_BUSINESS_ROLES = new Set([
|
||||
'DESIGN',
|
||||
])
|
||||
|
||||
export function canViewBomCostingWorkbench(
|
||||
user: (ScopedRoleUser & { supplierCode?: string | null }) | null | undefined,
|
||||
function matchesPathPrefix(pathname: string, prefix: string) {
|
||||
return pathname === prefix || pathname.startsWith(`${prefix}/`)
|
||||
}
|
||||
|
||||
export function canBomCostingOnlyUserAccessApi(
|
||||
pathname: string,
|
||||
method: string,
|
||||
storageKey?: string | null,
|
||||
) {
|
||||
if (!user || isSupplierAccount(user) || isExternalIntakeUser(user)) {
|
||||
const normalizedMethod = method.trim().toUpperCase()
|
||||
if (matchesPathPrefix(pathname, BOM_COSTING_API_PATH)) return true
|
||||
if (pathname === '/api/auth/me') return normalizedMethod === 'GET'
|
||||
if (pathname === '/api/auth/logout') return normalizedMethod === 'POST'
|
||||
if (pathname === '/api/storage/object' && normalizedMethod === 'GET') {
|
||||
return /(^|\/)bom-costing\//.test(storageKey?.trim() ?? '')
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function canViewBomCostingWorkbench(
|
||||
user:
|
||||
| (ScopedRoleUser & {
|
||||
supplierCode?: string | null
|
||||
loginSource?: string | null
|
||||
})
|
||||
| null
|
||||
| undefined,
|
||||
) {
|
||||
if (!user) {
|
||||
return false
|
||||
}
|
||||
if (isBomCostingOnlyUser(user)) return true
|
||||
if (isSupplierAccount(user) || isExternalIntakeUser(user)) return false
|
||||
if (user.role === 'SUPER_ADMIN' || user.role === 'ADMIN') {
|
||||
return true
|
||||
}
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
import {
|
||||
BOM_COSTING_ONLY_LOGIN_SOURCE,
|
||||
EXTERNAL_INTAKE_BUSINESS_ROLE,
|
||||
canExternalIntakeAccessWorkspace,
|
||||
canExternalIntakeCreateRecord,
|
||||
isExternalIntakeRecordOwner,
|
||||
isExternalIntakeUser,
|
||||
isBomCostingOnlyUser,
|
||||
isExternalIntakeWorkspaceCategory,
|
||||
} from './non-integrated-external-entry-permissions'
|
||||
|
||||
@ -23,6 +25,18 @@ describe('external intake entry permissions', () => {
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('does not grant product-entry permissions to BOM-only external accounts', () => {
|
||||
const user = {
|
||||
id: 'bom-only-user-id',
|
||||
businessRoles: [EXTERNAL_INTAKE_BUSINESS_ROLE],
|
||||
loginSource: BOM_COSTING_ONLY_LOGIN_SOURCE,
|
||||
}
|
||||
|
||||
expect(isBomCostingOnlyUser(user)).toBe(true)
|
||||
expect(isExternalIntakeUser(user)).toBe(false)
|
||||
expect(canExternalIntakeCreateRecord(user)).toBe(false)
|
||||
})
|
||||
|
||||
it('allows external intake users to create records', () => {
|
||||
expect(
|
||||
canExternalIntakeCreateRecord({
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
export const EXTERNAL_INTAKE_BUSINESS_ROLE = 'EXTERNAL_INTAKE'
|
||||
export const BOM_COSTING_ONLY_LOGIN_SOURCE = 'LOCAL_BOM_COSTING_ONLY'
|
||||
|
||||
export type ExternalIntakePermissionUser = {
|
||||
id?: string | null
|
||||
businessRoles?: readonly string[] | null
|
||||
loginSource?: string | null
|
||||
}
|
||||
|
||||
export type ExternalIntakePermissionRecord = {
|
||||
@ -25,8 +27,15 @@ function normalizeText(value: unknown) {
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
}
|
||||
|
||||
export function isBomCostingOnlyUser(
|
||||
user: Pick<ExternalIntakePermissionUser, 'loginSource'> | null | undefined,
|
||||
) {
|
||||
return normalizeText(user?.loginSource) === BOM_COSTING_ONLY_LOGIN_SOURCE
|
||||
}
|
||||
|
||||
export function isExternalIntakeUser(user: ExternalIntakePermissionUser | null | undefined) {
|
||||
return Boolean(
|
||||
!isBomCostingOnlyUser(user) &&
|
||||
user?.businessRoles?.some((role) => role === EXTERNAL_INTAKE_BUSINESS_ROLE),
|
||||
)
|
||||
}
|
||||
|
||||
@ -28,6 +28,7 @@ export interface UserInfo {
|
||||
name: string
|
||||
role: Role
|
||||
businessRoles?: BusinessAccountType[] | string[]
|
||||
loginSource?: string | null
|
||||
supplierCode?: string | null
|
||||
supplierName?: string | null
|
||||
status: UserStatus
|
||||
@ -482,6 +483,7 @@ export async function getUserInfo(userId: string): Promise<UserInfo | null> {
|
||||
name: user.name,
|
||||
role: user.role,
|
||||
businessRoles: user.businessRoles,
|
||||
loginSource: user.loginSource,
|
||||
supplierCode: user.supplierCode,
|
||||
supplierName: user.supplierName,
|
||||
status: user.status,
|
||||
|
||||
@ -8,6 +8,7 @@ import {
|
||||
hasFullWorkspaceAccess,
|
||||
resolveWorkspaceRedirectForUser,
|
||||
} from './workspace-route-permissions'
|
||||
import { BOM_COSTING_ONLY_LOGIN_SOURCE } from './non-integrated-external-entry-permissions'
|
||||
|
||||
describe('workspace route permissions', () => {
|
||||
it('keeps admins as full workspace users', () => {
|
||||
@ -86,6 +87,28 @@ describe('workspace route permissions', () => {
|
||||
expect(canAccessWorkspacePath('/supply-chain', externalAdmin)).toBe(false)
|
||||
})
|
||||
|
||||
it('limits BOM-only external accounts to the BOM costing workspace', () => {
|
||||
const bomOnlyUser = {
|
||||
role: 'USER',
|
||||
businessRoles: ['EXTERNAL_INTAKE'],
|
||||
loginSource: BOM_COSTING_ONLY_LOGIN_SOURCE,
|
||||
}
|
||||
|
||||
expect(getWorkspaceAccessLevel(bomOnlyUser)).toBe('bom-costing-only')
|
||||
expect(canAccessHomePortal(bomOnlyUser)).toBe(false)
|
||||
expect(canAccessSupplyChainWorkspace(bomOnlyUser)).toBe(false)
|
||||
expect(canAccessWorkspacePath('/bom-costing', bomOnlyUser)).toBe(true)
|
||||
expect(canAccessWorkspacePath('/bom-costing/cases/example', bomOnlyUser)).toBe(true)
|
||||
expect(canAccessWorkspacePath('/intake', bomOnlyUser)).toBe(false)
|
||||
expect(canAccessWorkspacePath('/users', bomOnlyUser)).toBe(false)
|
||||
expect(canAccessWorkspacePath('/release-notes', bomOnlyUser)).toBe(false)
|
||||
expect(canAccessWorkspacePathByAccessLevel('/', 'bom-costing-only')).toBe(false)
|
||||
expect(canAccessWorkspacePathByAccessLevel('/bom-costing', 'bom-costing-only')).toBe(true)
|
||||
expect(canAccessWorkspacePathByAccessLevel('/intake', 'bom-costing-only')).toBe(false)
|
||||
expect(resolveWorkspaceRedirectForUser('/', bomOnlyUser)).toBe('/bom-costing')
|
||||
expect(resolveWorkspaceRedirectForUser('/intake', bomOnlyUser)).toBe('/bom-costing')
|
||||
})
|
||||
|
||||
it('keeps product research designers as full workspace users', () => {
|
||||
const productDesigner = {
|
||||
role: 'USER',
|
||||
|
||||
@ -8,7 +8,10 @@ import {
|
||||
BOM_COSTING_WORKBENCH_PATH,
|
||||
canViewBomCostingWorkbench,
|
||||
} from './bom-costing-permissions'
|
||||
import { isExternalIntakeUser } from './non-integrated-external-entry-permissions'
|
||||
import {
|
||||
isBomCostingOnlyUser,
|
||||
isExternalIntakeUser,
|
||||
} from './non-integrated-external-entry-permissions'
|
||||
import { isSupplierAccount } from './supplier-account'
|
||||
|
||||
export const HOME_PORTAL_PATH = '/'
|
||||
@ -27,12 +30,14 @@ const USER_MANAGEMENT_ALLOWED_ROLES: AllowedRole[] = [
|
||||
export type WorkspaceAccessLevel =
|
||||
| 'full'
|
||||
| 'management'
|
||||
| 'bom-costing-only'
|
||||
| 'formal-products-only'
|
||||
| 'supplier-barcode-print-only'
|
||||
|
||||
export interface WorkspacePermissionUser {
|
||||
role?: string | null
|
||||
businessRoles?: readonly string[] | null
|
||||
loginSource?: string | null
|
||||
supplierCode?: string | null
|
||||
department?: { name?: string | null; fullPath?: string | null } | null
|
||||
departmentPaths?: readonly string[] | null
|
||||
@ -58,7 +63,12 @@ export function hasFullWorkspaceAccess(user: WorkspacePermissionUser | null | un
|
||||
}
|
||||
|
||||
export function canAccessHomePortal(user: WorkspacePermissionUser | null | undefined) {
|
||||
return Boolean(user && !isExternalIntakeUser(user) && !isSupplierAccount(user))
|
||||
return Boolean(
|
||||
user &&
|
||||
!isBomCostingOnlyUser(user) &&
|
||||
!isExternalIntakeUser(user) &&
|
||||
!isSupplierAccount(user),
|
||||
)
|
||||
}
|
||||
|
||||
export function canAccessSupplyChainWorkspace(
|
||||
@ -74,6 +84,7 @@ function isSupplyChainPath(pathname: string) {
|
||||
export function getWorkspaceAccessLevel(
|
||||
user: WorkspacePermissionUser | null | undefined,
|
||||
): WorkspaceAccessLevel {
|
||||
if (isBomCostingOnlyUser(user)) return 'bom-costing-only'
|
||||
if (isSupplierAccount(user)) return 'supplier-barcode-print-only'
|
||||
if (isExternalIntakeUser(user)) return 'formal-products-only'
|
||||
if (hasFullWorkspaceAccess(user)) return 'full'
|
||||
@ -150,6 +161,7 @@ export function canAccessWorkspacePath(
|
||||
|
||||
const accessLevel = getWorkspaceAccessLevel(user)
|
||||
if (accessLevel === 'full') return true
|
||||
if (accessLevel === 'bom-costing-only') return false
|
||||
if (isUserManagementPath(pathname) && canAccessUserManagement(user)) return true
|
||||
if (pathname === AI_RENDER_WORKBENCH_PATH || pathname.startsWith(`${AI_RENDER_WORKBENCH_PATH}/`)) {
|
||||
return (
|
||||
@ -173,14 +185,26 @@ export function canAccessWorkspacePathByAccessLevel(
|
||||
_role?: string | null,
|
||||
) {
|
||||
if (pathname === HOME_PORTAL_PATH) {
|
||||
return accessLevel !== 'supplier-barcode-print-only'
|
||||
return (
|
||||
accessLevel !== 'bom-costing-only' &&
|
||||
accessLevel !== 'supplier-barcode-print-only'
|
||||
)
|
||||
}
|
||||
if (isSupplyChainPath(pathname)) {
|
||||
// The Edge proxy has only the signed token. The supply-chain layout loads
|
||||
// current permission settings from the database before rendering a page.
|
||||
return accessLevel !== 'supplier-barcode-print-only'
|
||||
return (
|
||||
accessLevel !== 'bom-costing-only' &&
|
||||
accessLevel !== 'supplier-barcode-print-only'
|
||||
)
|
||||
}
|
||||
if (!accessLevel || accessLevel === 'full') return true
|
||||
if (accessLevel === 'bom-costing-only') {
|
||||
return (
|
||||
pathname === BOM_COSTING_WORKBENCH_PATH ||
|
||||
pathname.startsWith(`${BOM_COSTING_WORKBENCH_PATH}/`)
|
||||
)
|
||||
}
|
||||
if (accessLevel === 'supplier-barcode-print-only') {
|
||||
return pathname === SUPPLIER_BARCODE_PRINT_PATH
|
||||
}
|
||||
@ -207,7 +231,11 @@ export function resolveWorkspaceRedirectForUser(
|
||||
requestedPath: string,
|
||||
user: WorkspacePermissionUser | null | undefined,
|
||||
) {
|
||||
if (getWorkspaceAccessLevel(user) === 'supplier-barcode-print-only') {
|
||||
const accessLevel = getWorkspaceAccessLevel(user)
|
||||
if (accessLevel === 'bom-costing-only') {
|
||||
return BOM_COSTING_WORKBENCH_PATH
|
||||
}
|
||||
if (accessLevel === 'supplier-barcode-print-only') {
|
||||
return SUPPLIER_BARCODE_PRINT_PATH
|
||||
}
|
||||
|
||||
|
||||
@ -9,6 +9,7 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { validateToken } from '@/lib/token-validator'
|
||||
import { BOM_COSTING_WORKBENCH_PATH } from '@/lib/bom-costing-permissions'
|
||||
import {
|
||||
FORMAL_PRODUCTS_HOME_PATH,
|
||||
HOME_PORTAL_PATH,
|
||||
@ -134,7 +135,9 @@ export async function proxy(request: NextRequest) {
|
||||
)
|
||||
) {
|
||||
const fallbackPath =
|
||||
payload.workspaceAccess === 'supplier-barcode-print-only'
|
||||
payload.workspaceAccess === 'bom-costing-only'
|
||||
? BOM_COSTING_WORKBENCH_PATH
|
||||
: payload.workspaceAccess === 'supplier-barcode-print-only'
|
||||
? FORMAL_PRODUCTS_HOME_PATH
|
||||
: HOME_PORTAL_PATH
|
||||
return NextResponse.redirect(new URL(fallbackPath, request.url))
|
||||
|
||||
@ -26,6 +26,7 @@ import {
|
||||
isSupplierAllowedApiRequest,
|
||||
handleRequest,
|
||||
jsonSuccess,
|
||||
mapAuthenticatedUserInfo,
|
||||
success,
|
||||
successWithPagination,
|
||||
} from './response'
|
||||
@ -192,6 +193,20 @@ describe('request business-role authorization', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves the login source in the authenticated API context', () => {
|
||||
const user = mapAuthenticatedUserInfo({
|
||||
id: 'bom-only-user',
|
||||
email: 'bom-only@example.com',
|
||||
name: 'BOM Only User',
|
||||
role: 'USER',
|
||||
status: 'ACTIVE',
|
||||
businessRoles: ['EXTERNAL_INTAKE'],
|
||||
loginSource: 'LOCAL_BOM_COSTING_ONLY',
|
||||
})
|
||||
|
||||
expect(user.loginSource).toBe('LOCAL_BOM_COSTING_ONLY')
|
||||
})
|
||||
|
||||
it('keeps an ordinary user out of a management-only read scope', async () => {
|
||||
mockAuthenticateRequest.mockResolvedValue({
|
||||
success: true,
|
||||
|
||||
@ -10,6 +10,7 @@ import type { ApiResponse, PaginationMeta, ResponseMeta, AuthUser, RequestContex
|
||||
import { AppError, ErrorCode, ERROR_MESSAGES, isAppError } from './errors'
|
||||
import { HTTP_STATUS, ENV } from './constants'
|
||||
import type { AllowedRole } from '@/lib/role-scope'
|
||||
import type { UserInfo } from '@/lib/permissions'
|
||||
import { canCreateContent, canOperateDesignWorkspace, hasAllowedRole, hasBusinessRole } from '@/lib/role-scope'
|
||||
import type { BusinessAccountType } from '@prisma/client'
|
||||
import { resolveObjectStorageUrlForClientAccess } from '@/lib/storage'
|
||||
@ -395,6 +396,26 @@ export async function handleRequest<T>(
|
||||
* 从请求中获取用户信息
|
||||
* 通过 auth-middleware 验证 JWT Token 并返回用户信息
|
||||
*/
|
||||
export function mapAuthenticatedUserInfo(userInfo: UserInfo): AuthUser {
|
||||
return {
|
||||
id: userInfo.id,
|
||||
email: userInfo.email,
|
||||
name: userInfo.name,
|
||||
role: userInfo.role as AuthUser['role'],
|
||||
status: userInfo.status as AuthUser['status'],
|
||||
businessRoles: userInfo.businessRoles,
|
||||
loginSource: userInfo.loginSource,
|
||||
supplierCode: userInfo.supplierCode,
|
||||
supplierName: userInfo.supplierName,
|
||||
department: userInfo.department,
|
||||
departmentPaths: userInfo.departmentPaths,
|
||||
departmentId: userInfo.departmentId,
|
||||
teamId: userInfo.teamId,
|
||||
managedDepartmentId: userInfo.managedDepartmentId,
|
||||
managedTeamId: userInfo.managedTeamId,
|
||||
}
|
||||
}
|
||||
|
||||
async function getUserFromRequest(request: NextRequest): Promise<AuthUser | undefined> {
|
||||
// 从现有的认证中间件获取用户信息
|
||||
try {
|
||||
@ -406,22 +427,7 @@ async function getUserFromRequest(request: NextRequest): Promise<AuthUser | unde
|
||||
return undefined
|
||||
}
|
||||
|
||||
return {
|
||||
id: result.userInfo.id,
|
||||
email: result.userInfo.email,
|
||||
name: result.userInfo.name,
|
||||
role: result.userInfo.role as AuthUser['role'],
|
||||
status: result.userInfo.status as AuthUser['status'],
|
||||
businessRoles: result.userInfo.businessRoles,
|
||||
supplierCode: result.userInfo.supplierCode,
|
||||
supplierName: result.userInfo.supplierName,
|
||||
department: result.userInfo.department,
|
||||
departmentPaths: result.userInfo.departmentPaths,
|
||||
departmentId: result.userInfo.departmentId,
|
||||
teamId: result.userInfo.teamId,
|
||||
managedDepartmentId: result.userInfo.managedDepartmentId,
|
||||
managedTeamId: result.userInfo.managedTeamId,
|
||||
}
|
||||
return mapAuthenticatedUserInfo(result.userInfo)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
|
||||
@ -70,6 +70,7 @@ export interface AuthUser {
|
||||
role: UserRole
|
||||
status: 'ACTIVE' | 'PENDING' | 'INACTIVE' | 'SUSPENDED'
|
||||
businessRoles?: BusinessAccountType[] | string[]
|
||||
loginSource?: string | null
|
||||
supplierCode?: string | null
|
||||
supplierName?: string | null
|
||||
department?: { id?: string; name?: string; fullPath?: string } | null
|
||||
|
||||
@ -299,6 +299,7 @@ class UserRepositoryClass extends BaseRepository<
|
||||
name: true,
|
||||
role: true,
|
||||
businessRoles: true,
|
||||
loginSource: true,
|
||||
status: true,
|
||||
supplierCode: true,
|
||||
supplierName: true,
|
||||
|
||||
@ -169,6 +169,40 @@ describe('authService employee auto activation', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('BOM 专用账号的登录令牌只包含 BOM 工作台权限', async () => {
|
||||
const bomOnlyUser = buildAuthUser({
|
||||
name: 'BOM 测试账号',
|
||||
status: 'ACTIVE',
|
||||
businessRoles: ['EXTERNAL_INTAKE'],
|
||||
loginSource: 'LOCAL_BOM_COSTING_ONLY',
|
||||
employeeDirectoryId: null,
|
||||
departmentId: null,
|
||||
department: null,
|
||||
})
|
||||
mockAuthRepository.findByIdentifier.mockResolvedValue(bomOnlyUser as never)
|
||||
mockAuthRepository.getEmployeeAutoActivationContext.mockResolvedValue(null as never)
|
||||
mockAuthRepository.findByIdWithRelations.mockResolvedValue(bomOnlyUser as never)
|
||||
mockGetWorkspaceAccessLevel.mockReturnValue('bom-costing-only' as never)
|
||||
|
||||
const result = await authService.login({
|
||||
identifier: 'BOM 测试账号',
|
||||
password: 'password-1',
|
||||
})
|
||||
|
||||
expect(mockGetWorkspaceAccessLevel).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ loginSource: 'LOCAL_BOM_COSTING_ONLY' }),
|
||||
)
|
||||
expect(mockGetIntakeNodePermissionSettings).not.toHaveBeenCalled()
|
||||
expect(result.user.workspaceAccess).toBe('bom-costing-only')
|
||||
expect(result.user.workspaceAllowedPathPrefixes).toEqual(['/bom-costing'])
|
||||
expect(mockGenerateToken).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
workspaceAccess: 'bom-costing-only',
|
||||
workspaceAllowedPathPrefixes: ['/bom-costing'],
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('密码登录时,业务支持/快递/供应商/龙晨品牌中心不自动激活为内部可用账号', async () => {
|
||||
const pendingUser = buildAuthUser({
|
||||
name: '供应商甲',
|
||||
|
||||
@ -125,6 +125,7 @@ function isEmail(identifier: string): boolean {
|
||||
type WorkspaceTokenPermissionUser = {
|
||||
role?: string | null
|
||||
businessRoles?: readonly string[] | null
|
||||
loginSource?: string | null
|
||||
department?: { name?: string | null; fullPath?: string | null } | null
|
||||
departmentPaths?: readonly string[] | null
|
||||
departmentId?: string | null
|
||||
@ -138,6 +139,12 @@ async function buildWorkspaceTokenPermissions(user: WorkspaceTokenPermissionUser
|
||||
if (workspaceAccess === 'full') {
|
||||
return { workspaceAccess }
|
||||
}
|
||||
if (workspaceAccess === 'bom-costing-only') {
|
||||
return {
|
||||
workspaceAccess,
|
||||
workspaceAllowedPathPrefixes: [BOM_COSTING_WORKBENCH_PATH],
|
||||
}
|
||||
}
|
||||
|
||||
const { overrides } = await intakeNodePermissionSettingsService.getSettings()
|
||||
const allowedPathPrefixes = resolveIntakeTopEntryAllowedPathPrefixes(
|
||||
@ -173,6 +180,7 @@ async function buildAuthUserDTO(
|
||||
const workspacePermissions = await buildWorkspaceTokenPermissions({
|
||||
role: user.role,
|
||||
businessRoles: user.businessRoles,
|
||||
loginSource: user.loginSource,
|
||||
department: user.department,
|
||||
departmentPaths,
|
||||
departmentId: user.departmentId,
|
||||
@ -348,6 +356,7 @@ class AuthService {
|
||||
const workspacePermissions = await buildWorkspaceTokenPermissions({
|
||||
role: effectiveUser.role,
|
||||
businessRoles: effectiveUser.businessRoles,
|
||||
loginSource: effectiveUser.loginSource,
|
||||
department: effectiveUser.department,
|
||||
departmentPaths: await getUserDepartmentPathsById(effectiveUser.id),
|
||||
departmentId: effectiveUser.departmentId,
|
||||
@ -544,6 +553,7 @@ class AuthService {
|
||||
const workspacePermissions = await buildWorkspaceTokenPermissions({
|
||||
role: user.role,
|
||||
businessRoles: user.businessRoles,
|
||||
loginSource: user.loginSource,
|
||||
department: user.department,
|
||||
departmentPaths,
|
||||
departmentId: user.departmentId,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user