feat: establish AIOA identity and organization baseline

This commit is contained in:
selfrelease
2026-07-18 08:05:45 +08:00
commit bbb09ed56f
42 changed files with 2473 additions and 0 deletions
@@ -0,0 +1,11 @@
package com.all8ai.aioa
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class AioaApplication
fun main(args: Array<String>) {
runApplication<AioaApplication>(*args)
}
@@ -0,0 +1,46 @@
package com.all8ai.aioa.identity.api
import com.all8ai.aioa.identity.application.CurrentUserService
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.util.UUID
@RestController
@RequestMapping("/api/v1/me")
class CurrentUserController(
private val currentUserService: CurrentUserService,
) {
@GetMapping
fun currentUser(@AuthenticationPrincipal jwt: Jwt): CurrentUserResponse {
val currentUser = currentUserService.get(jwt.subject, jwt.getClaimAsString("tenant_id"))
return CurrentUserResponse(
id = currentUser.id,
tenantId = currentUser.tenantId,
username = currentUser.username,
displayName = currentUser.displayName,
email = currentUser.email,
department = currentUser.department?.let { OrganizationRef(it.id, it.name) },
position = currentUser.position?.let { OrganizationRef(it.id, it.name) },
roles = currentUser.roles,
)
}
}
data class CurrentUserResponse(
val id: UUID,
val tenantId: UUID,
val username: String,
val displayName: String,
val email: String?,
val department: OrganizationRef?,
val position: OrganizationRef?,
val roles: Set<String>,
)
data class OrganizationRef(
val id: UUID,
val name: String,
)
@@ -0,0 +1,27 @@
package com.all8ai.aioa.identity.application
import com.all8ai.aioa.identity.domain.CurrentUser
import com.all8ai.aioa.identity.domain.CurrentUserRepository
import com.all8ai.aioa.shared.web.ApiException
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import java.util.UUID
@Service
class CurrentUserService(
private val repository: CurrentUserRepository,
) {
fun get(subject: String, tenantClaim: String?): CurrentUser {
val tenantId = tenantClaim?.let(::parseTenantId)
?: throw ApiException(HttpStatus.FORBIDDEN, "TENANT_CLAIM_MISSING", "登录身份缺少租户信息")
return repository.findActiveBySubject(tenantId, subject)
?: throw ApiException(HttpStatus.FORBIDDEN, "USER_NOT_PROVISIONED", "当前用户尚未同步到 OA 系统")
}
private fun parseTenantId(value: String): UUID = try {
UUID.fromString(value)
} catch (_: IllegalArgumentException) {
throw ApiException(HttpStatus.FORBIDDEN, "TENANT_CLAIM_INVALID", "登录身份中的租户信息无效")
}
}
@@ -0,0 +1,23 @@
package com.all8ai.aioa.identity.domain
import java.util.UUID
data class CurrentUser(
val id: UUID,
val tenantId: UUID,
val username: String,
val displayName: String,
val email: String?,
val department: OrganizationRef?,
val position: OrganizationRef?,
val roles: Set<String>,
)
data class OrganizationRef(
val id: UUID,
val name: String,
)
fun interface CurrentUserRepository {
fun findActiveBySubject(tenantId: UUID, subject: String): CurrentUser?
}
@@ -0,0 +1,77 @@
package com.all8ai.aioa.identity.infrastructure
import com.all8ai.aioa.identity.domain.CurrentUser
import com.all8ai.aioa.identity.domain.CurrentUserRepository
import com.all8ai.aioa.identity.domain.OrganizationRef
import org.jooq.DSLContext
import org.springframework.stereotype.Repository
import java.util.UUID
@Repository
class JooqCurrentUserRepository(
private val dsl: DSLContext,
) : CurrentUserRepository {
override fun findActiveBySubject(tenantId: UUID, subject: String): CurrentUser? {
val record = dsl.fetchOne(
"""
SELECT
u.id,
u.tenant_id,
u.username,
u.display_name,
u.email,
d.id AS department_id,
d.name AS department_name,
p.id AS position_id,
p.name AS position_name
FROM identity.user_account u
LEFT JOIN organization.user_assignment a
ON a.tenant_id = u.tenant_id
AND a.user_id = u.id
AND a.is_primary = TRUE
AND a.effective_from <= CURRENT_TIMESTAMP
AND (a.effective_until IS NULL OR a.effective_until > CURRENT_TIMESTAMP)
LEFT JOIN organization.department d ON d.id = a.department_id
LEFT JOIN organization.position p ON p.id = a.position_id
WHERE u.tenant_id = ?
AND u.keycloak_subject = ?
AND u.status = 'ACTIVE'
""".trimIndent(),
tenantId,
subject,
) ?: return null
val userId = record.get("id", UUID::class.java)!!
val roles = dsl.fetch(
"""
SELECT r.code
FROM authz.user_role ur
JOIN authz.role r
ON r.tenant_id = ur.tenant_id
AND r.id = ur.role_id
WHERE ur.tenant_id = ?
AND ur.user_id = ?
AND ur.effective_from <= CURRENT_TIMESTAMP
AND (ur.effective_until IS NULL OR ur.effective_until > CURRENT_TIMESTAMP)
AND r.status = 'ACTIVE'
ORDER BY r.code
""".trimIndent(),
tenantId,
userId,
).mapNotNull { it.get("code", String::class.java) }.toSortedSet()
return CurrentUser(
id = userId,
tenantId = record.get("tenant_id", UUID::class.java)!!,
username = record.get("username", String::class.java)!!,
displayName = record.get("display_name", String::class.java)!!,
email = record.get("email", String::class.java),
department = ref(record.get("department_id", UUID::class.java), record.get("department_name", String::class.java)),
position = ref(record.get("position_id", UUID::class.java), record.get("position_name", String::class.java)),
roles = roles,
)
}
private fun ref(id: UUID?, name: String?): OrganizationRef? =
if (id != null && name != null) OrganizationRef(id, name) else null
}
@@ -0,0 +1,20 @@
package com.all8ai.aioa.shared.security
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.Customizer.withDefaults
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.web.SecurityFilterChain
@Configuration
class SecurityConfiguration {
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain = http
.csrf { it.disable() }
.authorizeHttpRequests {
it.requestMatchers("/actuator/health", "/actuator/info").permitAll()
.anyRequest().authenticated()
}
.oauth2ResourceServer { it.jwt(withDefaults()) }
.build()
}
@@ -0,0 +1,9 @@
package com.all8ai.aioa.shared.web
import org.springframework.http.HttpStatus
class ApiException(
val status: HttpStatus,
val code: String,
override val message: String,
) : RuntimeException(message)
@@ -0,0 +1,48 @@
package com.all8ai.aioa.shared.web
import jakarta.servlet.http.HttpServletRequest
import jakarta.validation.ConstraintViolationException
import org.slf4j.LoggerFactory
import org.slf4j.MDC
import org.springframework.http.HttpStatus
import org.springframework.http.ProblemDetail
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import java.net.URI
@RestControllerAdvice
class GlobalExceptionHandler {
private val logger = LoggerFactory.getLogger(javaClass)
@ExceptionHandler(ApiException::class)
fun handleApiException(exception: ApiException, request: HttpServletRequest): ResponseEntity<ProblemDetail> =
response(exception.status, exception.code, exception.message, request)
@ExceptionHandler(MethodArgumentNotValidException::class, ConstraintViolationException::class)
fun handleValidation(exception: Exception, request: HttpServletRequest): ResponseEntity<ProblemDetail> =
response(HttpStatus.BAD_REQUEST, "REQUEST_INVALID", exception.message ?: "请求参数无效", request)
@ExceptionHandler(Exception::class)
fun handleUnexpected(exception: Exception, request: HttpServletRequest): ResponseEntity<ProblemDetail> {
logger.error("Unhandled request error", exception)
return response(HttpStatus.INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "服务器处理请求失败", request)
}
private fun response(
status: HttpStatus,
code: String,
detail: String,
request: HttpServletRequest,
): ResponseEntity<ProblemDetail> {
val problem = ProblemDetail.forStatusAndDetail(status, detail).apply {
type = URI.create("https://aioa.all8ai.com/problems/${code.lowercase().replace('_', '-')}")
title = status.reasonPhrase
instance = URI.create(request.requestURI)
setProperty("code", code)
setProperty("traceId", MDC.get(TraceIdFilter.MDC_TRACE_ID) ?: "unknown")
}
return ResponseEntity.status(status).body(problem)
}
}
@@ -0,0 +1,39 @@
package com.all8ai.aioa.shared.web
import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.MDC
import org.springframework.core.Ordered
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import java.util.UUID
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
class TraceIdFilter : OncePerRequestFilter() {
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain,
) {
val traceId = request.getHeader(TRACE_ID_HEADER)
?.takeIf { TRACE_ID_PATTERN.matches(it) }
?: UUID.randomUUID().toString()
MDC.put(MDC_TRACE_ID, traceId)
response.setHeader(TRACE_ID_HEADER, traceId)
try {
filterChain.doFilter(request, response)
} finally {
MDC.remove(MDC_TRACE_ID)
}
}
companion object {
const val TRACE_ID_HEADER = "X-Trace-Id"
const val MDC_TRACE_ID = "traceId"
private val TRACE_ID_PATTERN = Regex("[A-Za-z0-9._:-]{8,128}")
}
}