server

package
v1.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2026 License: Apache-2.0 Imports: 34 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package server 是 usercenter 对外的公开入口包。

背景:usercenter 的启动逻辑(store 注入、bootstrap 迁移与初始化、密钥/常量/种子) 都位于 internal/* 下。Go 的 internal 规则禁止其他模块 import internal 包。 当 usercenter 作为库被另一个独立 Go 模块(如 CapsiFarm 单体二进制)内嵌复用时, 宿主模块无法直接调用 internal/bootstrap。

本包作为薄转发层(thin facade),把宿主需要的启动能力重新导出,转发给 internal/bootstrap 与 internal/store。包内不做业务逻辑,只做参数透传与类型映射, 以便 usercenter 内部演进时仅此一处需同步调整。

典型用法(宿主 main.go):

dbClient := sqlite.NewSqlite("./app.db?_pragma=journal_mode(WAL)", true)
server.SetDB(dbClient)                       // 1. 注入 GORM 客户端
if err := server.RunMigration(); err != nil { // 2. usercenter 全部表迁移
    log.Fatal(err)
}
server.InitKeys(server.Keys{TokenKey: "...", TokenExpired: 1440})
server.InitConstants(server.Constants{PlatformTenantID: "platform", SuperAdminRoleID: "1", EnableTenant: true, LoginLockMaxErr: 5, LoginLockMinutes: 15})
server.SeedAdmin("platform", "1", "")        // 3. 首次部署播种超管(幂等)
// 4. 宿主再做自己业务表的 AutoMigrate、挂业务路由、ListenAndServe

路由注册、鉴权中间件本身在 public 包(usercenter/http、usercenter/utils/middleware), 宿主可直接 import,无需本包转发。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AutoMigrate

func AutoMigrate() error

AutoMigrate 仅迁移 usercenter 域表(不初始化 Casbin)。一般用 RunMigration 即可。

func CheckKeyIsolation

func CheckKeyIsolation(tokenKey, apiKeyEncKey, piiEncKey string)

CheckKeyIsolation 转发 bootstrap.CheckKeyIsolation:检测三套密钥是否被误配为相同, 任意两者相同则 panic。生产部署建议在 InitKeys 后调用。

func CompareAndSwapSystemConfigValue

func CompareAndSwapSystemConfigValue(
	key string,
	expectedValue *string,
	value string,
) (bool, error)

CompareAndSwapSystemConfigValue atomically writes one namespaced value. expectedValue=nil creates only when the key is absent. A non-nil value updates only when the complete stored value still matches, preventing a stale embedded-product settings page from overwriting a newer revision.

func ConsumeReauthProof

func ConsumeReauthProof(principalID, action, proof string) bool

ConsumeReauthProof atomically consumes a short-lived, single-use proof issued by UserCenter for the exact principal and high-risk action.

func CountTenantProjectUsers

func CountTenantProjectUsers(tenantID, projectID string) (int64, error)

func DB

func DB() *gorm.DB

DB 返回当前 GORM DB 句柄。宿主可据此对自己业务表再做 AutoMigrate。

func DeleteTenantProjectRole

func DeleteTenantProjectRole(tenantID, projectID, roleID string) error

DeleteTenantProjectRole validates the exact ownership boundary before using UserCenter's native deletion workflow. Assigned and parent roles remain protected by the native implementation.

func DevAuthRequired

func DevAuthRequired(c *gin.Context)

DevAuthRequired 是开发期鉴权中间件,供宿主(如 CapsiFarm 单体)在全新空库时使用。

背景:生产 utils/middleware.AuthRequired 依赖 Casbin(规则来自 api 表)。全新本地 库 api 表为空,会导致除登录外的所有接口被拦截。开发期目的是验证业务功能, 无需完整权限体系,因此本中间件:

  • 放行静态资源(/web、/swagger、/uploads 等)与免登录公开端点;
  • 其余请求用 token.DecodeToken 真实验签,成功则写 Principal/User 到 context;
  • 不做 Casbin 鉴权——已登录即放行。

生产环境请改用 middleware.AuthRequired 并完成 api 表 + Casbin 规则播种。

func EncryptPassword

func EncryptPassword(password string) (string, error)

EncryptPassword 转发 auth.EncryptedPassword:用 scrypt 对密码哈希。 宿主在播种初始用户时,须先调用本函数得到哈希再写入 users.password。

func InitConstants

func InitConstants(c Constants)

InitConstants 转发 bootstrap.InitConstants:设置全局平台常量。

func InitKeys

func InitKeys(k Keys)

InitKeys 转发 bootstrap.InitKeys:初始化 JWT 缓存、AI Key 加密、PII 加密、OIDC RSA。 进程内须在 DB 就绪后调用一次。

func IsRoleAuthorizationRevisionConflict

func IsRoleAuthorizationRevisionConflict(err error) bool

func NewBackgroundAITransport

func NewBackgroundAITransport(resolve BackgroundAIPrincipalResolver) http.RoundTripper

NewBackgroundAITransport embeds the same UserCenter model routing, encrypted keys, quotas and usage logging used by /v1. It buffers responses for background jobs and exposes only chat completions and model listing. It is not an HTTP authentication middleware and must never be mounted on a network listener. The host must initialize UserCenter and register its AI gateway before use.

func PromptVariables

func PromptVariables(content string) []string

func Prompts

func Prompts(db *gorm.DB, tenantID string) *prompt.Repository

Prompts binds prompt operations to the host's DB/transaction and tenant. The caller supplies its authenticated tenant. Empty tenant explicitly selects platform templates. Tenant callers may read platform templates but not edit them.

func RegisterAdminSPA

func RegisterAdminSPA(router *gin.Engine)

RegisterAdminSPA mounts usercenter's embedded management application under /web/admin. Embedded products should call this on the same Gin engine that serves usercenter's APIs so the SPA and its uc_admin_token remain same-origin.

func RenderPrompt

func RenderPrompt(content string, variables map[string]string) string

func ResetTenantAdministratorPassword

func ResetTenantAdministratorPassword(tenantID, projectID, userID, password string) error

func RoleBelongsToTenantProject

func RoleBelongsToTenantProject(roleID, tenantID, projectID string) bool

RoleBelongsToTenantProject reports whether an enabled role belongs to the exact tenant/project boundary. Embedded products must use this stricter check before accepting a client-supplied role ID; tenant ownership alone is insufficient when one tenant hosts roles for multiple products.

func RunMigration

func RunMigration() error

RunMigration 转发 bootstrap.RunMigration:对所有 usercenter 域表执行 AutoMigrate, 并初始化 Casbin + 刷新免鉴权规则。幂等,可重复执行。

func SeedAdmin

func SeedAdmin(platformTenantID, superAdminRoleID, defaultPwd string)

SeedAdmin 转发 bootstrap.SeedAdmin:首次部署幂等播种平台租户、超管角色与初始管理员。 defaultPwd 为空则随机生成强口令并打印到 stdout,首登强制改密。

func SeedBootstrapAdmin

func SeedBootstrapAdmin(tenantID, superAdminRoleID, pwd string) (seeded bool, generatedPwd string, err error)

SeedBootstrapAdmin 转发 bootstrap.SeedBootstrapAdmin:SeedAdmin 的底层实现, 返回是否实际播种 (seeded) 与生成的随机口令 (generatedPwd)。 已有用户时 seeded=false,为 no-op。

func SetAlertWebhook

func SetAlertWebhook(url string)

SetAlertWebhook 转发 bootstrap.SetAlertWebhook:配置告警 Webhook(飞书/Slack 等)。

func SetDB

func SetDB(client db.DBClientInterface)

SetDB 注入全局 GORM 客户端,供 usercenter 所有 internal 域包使用。 必须在 RunMigration / InitKeys 之前调用。

func SetSocialLogins

func SetSocialLogins(cfgs []SocialLoginConfig)

SetSocialLogins 转发 bootstrap.SetSocialLogins:注册社交登录提供方(GitHub/Google 等)。

func SetTenantAdministratorEnabled

func SetTenantAdministratorEnabled(tenantID, projectID, userID string, enabled bool) error

func SetTenantEnabled

func SetTenantEnabled(id string, enabled bool) error

func ValidPasswordStrength

func ValidPasswordStrength(str string) bool

ValidPasswordStrength 转发 auth.ValidPasswdStrength:校验密码强度 (>=8 位 + 数字 + 小写 + 大写)。首登改密时可用。

Types

type AIModelRouteRevision

type AIModelRouteRevision struct {
	Digest         string
	UpstreamModels []string
}

AIModelRouteRevision is a credential-free snapshot of every configured route the gateway may use for an alias, including global fallback. Embedded products use it to invalidate model-dependent artifacts after routing changes.

func GetAIModelRouteRevision

func GetAIModelRouteRevision(ctx context.Context, tenantID, alias string) (AIModelRouteRevision, error)

GetAIModelRouteRevision is a trusted server composition API, not an HTTP authorization boundary. The host must derive tenantID from its authenticated actor. The digest excludes key material, key rotation, cooldown and transient health, but includes provider endpoints and routing configuration. This is a content digest, not a monotonic revision or proof of immutable model weights.

type BackgroundAIPrincipalResolver

type BackgroundAIPrincipalResolver func(context.Context) (userID, tenantID string)

BackgroundAIPrincipalResolver obtains ownership from an authorized durable job in the host. Never resolve identity from caller-controlled HTTP headers.

type Constants

type Constants = bootstrap.Constants

Constants 转发 bootstrap.Constants:平台租户、超管角色、默认角色、租户开关、 登录锁定策略、默认口令等全局常量。

type CreateTenantAdministratorRequest

type CreateTenantAdministratorRequest struct {
	TenantID  string
	ProjectID string
	UserName  string
	Nickname  string
	Mobile    string
	Email     string
	Password  string
}

type CreateTenantProjectRoleRequest

type CreateTenantProjectRoleRequest struct {
	TenantID      string
	ProjectID     string
	Code          string
	DisplayName   string
	DefaultRouter string
}

CreateTenantProjectRoleRequest deliberately exposes only tenant-safe role fields. Public/system/mandatory flags and cross-tenant parent relations are not accepted through the embedded-product facade.

type CreateTenantRequest

type CreateTenantRequest struct {
	ID        string
	Name      string
	Contact   string
	CellPhone string
	Address   string
	Enabled   bool
	UserLimit int32
	ExpiresAt time.Time
}

type Keys

type Keys = bootstrap.Keys

Keys 转发 bootstrap.Keys:三套独立密钥(JWT/AI Key 加密/PII 加密)+ OIDC RSA 密钥。 留空的密钥槽会从 TokenKey 派生(SHA-256),OIDCSigningKey 留空则自动生成 RSA-2048。

type LoginRequest

type LoginRequest struct {
	UserName   string
	Password   string
	DeviceType int32
	DeviceName string
	ClientIP   string
	UserAgent  string
}

type LoginResult

type LoginResult struct {
	Code        int32
	Message     string
	Token       string
	UserID      string
	UserName    string
	DisplayName string
	TenantID    string
}

func Login

func Login(request LoginRequest) (LoginResult, error)

Login performs UserCenter password authentication and persists a manageable session. Hosts can expose a product-specific response without bypassing UserCenter controls.

type PromptTemplate

type PromptTemplate = prompt.PromptTemplate

PromptTemplate and PromptVersion are UserCenter-owned storage models. Hosts keep references to their IDs, rather than creating competing prompt tables.

type PromptVersion

type PromptVersion = prompt.PromptVersion

type RoleAuthorizationABACPolicy

type RoleAuthorizationABACPolicy = permission.RoleAuthorizationABACPolicy

type RoleAuthorizationDetail

type RoleAuthorizationDetail = permission.RoleAuthorizationDetail

func GetRoleAuthorization

func GetRoleAuthorization(roleID string) (*RoleAuthorizationDetail, error)

type RoleAuthorizationPublishResult

type RoleAuthorizationPublishResult = permission.RoleAuthorizationPublishResult

func PublishRoleAuthorization

func PublishRoleAuthorization(roleID, baseRevision string, selections []RoleAuthorizationSelection) (*RoleAuthorizationPublishResult, error)

func PublishRoleAuthorizationWithABAC

func PublishRoleAuthorizationWithABAC(roleID, baseRevision string, selections []RoleAuthorizationSelection, policy RoleAuthorizationABACPolicy) (*RoleAuthorizationPublishResult, error)

type RoleAuthorizationSelection

type RoleAuthorizationSelection = permission.RoleAuthorizationSelection

RoleAuthorizationSelection and the related result types are aliases of UserCenter's native authorization contract. Embedded products can publish their menu/function selections without writing role_menus or Casbin tables.

type SocialLoginConfig

type SocialLoginConfig = bootstrap.SocialLoginConfig

SocialLoginConfig 转发 bootstrap.SocialLoginConfig:社交登录提供方配置。

type SystemConfigValue

type SystemConfigValue struct {
	Key       string
	Value     string
	UpdatedAt time.Time
}

SystemConfigValue is the narrow public value contract for embedded products. It deliberately exposes neither the UserCenter GORM model nor table details.

func GetSystemConfigValue

func GetSystemConfigValue(key string) (
	value SystemConfigValue,
	found bool,
	err error,
)

GetSystemConfigValue reads one namespaced configuration value. found=false is returned for a missing key so callers do not need to depend on GORM errors.

func ListSystemConfigValues

func ListSystemConfigValues(prefix string) ([]SystemConfigValue, error)

ListSystemConfigValues reads every value in one namespaced key prefix. Embedded products use this to discover their own tenant-scoped settings without depending on UserCenter's GORM model or unfiltered admin APIs.

type TenantAdminRegistration

type TenantAdminRegistration struct {
	TenantID      string
	TenantName    string
	Contact       string
	CellPhone     string
	Address       string
	AdminUserName string
	AdminPassword string
	AdminNickname string
	AdminEmail    string
	AdminMobile   string
	RoleID        string
	ProjectID     string
}

TenantAdminRegistration is the narrow cross-product contract for creating a tenant and its first administrator. Product-specific onboarding data stays in the embedding product and can be written in the same database transaction.

type TenantAdminRegistrationResult

type TenantAdminRegistrationResult struct {
	TenantID string
	UserID   string
	RoleID   string
}

func RegisterTenantAdminInTransaction

func RegisterTenantAdminInTransaction(tx *gorm.DB, request TenantAdminRegistration) (TenantAdminRegistrationResult, error)

RegisterTenantAdminInTransaction writes only UserCenter-owned tenant, principal and role-assignment rows through the caller-owned transaction. The function never commits: an embedding product can atomically roll these rows back when its own onboarding profile fails.

type TenantAdministrator

type TenantAdministrator struct {
	ID        string `json:"id"`
	TenantID  string `json:"tenantId"`
	ProjectID string `json:"projectId"`
	UserName  string `json:"userName"`
	Nickname  string `json:"nickname"`
	Mobile    string `json:"mobile"`
	Email     string `json:"email"`
	Enabled   bool   `json:"enabled"`
	RoleID    string `json:"roleId"`
}

func ListTenantAdministrators

func ListTenantAdministrators(tenantID, projectID string) ([]TenantAdministrator, error)

type TenantProjectRole

type TenantProjectRole struct {
	ID            string `json:"id"`
	TenantID      string `json:"tenantID"`
	ProjectID     string `json:"projectID"`
	Code          string `json:"code"`
	DisplayName   string `json:"displayName"`
	DefaultRouter string `json:"defaultRouter"`
	Enabled       bool   `json:"enabled"`
	Deletable     bool   `json:"deletable"`
}

TenantProjectRole is the stable public view of a tenant-owned role. Code is the machine identifier stored by UserCenter; DisplayName is the product-facing label stored in the native role description field.

func CreateTenantProjectRole

func CreateTenantProjectRole(request CreateTenantProjectRoleRequest) (TenantProjectRole, error)

CreateTenantProjectRole creates a native UserCenter role within one tenant and project. Role limits remain the responsibility of the embedding product; passing zero to UserCenter's limit callback means unlimited.

func ListTenantProjectRoles

func ListTenantProjectRoles(tenantID, projectID string) ([]TenantProjectRole, error)

ListTenantProjectRoles returns only roles owned by the exact tenant and project pair. Public and other-project roles are intentionally excluded.

func RenameTenantProjectRole

func RenameTenantProjectRole(tenantID, projectID, roleID, displayName string) (TenantProjectRole, error)

RenameTenantProjectRole changes only the product-facing display label. The machine code, tenant/project ownership and authorization selections remain immutable through this facade.

type TenantRecord

type TenantRecord struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Contact   string    `json:"contact"`
	CellPhone string    `json:"cellPhone"`
	Address   string    `json:"address"`
	Enabled   bool      `json:"enabled"`
	UserLimit int32     `json:"userLimit"`
	ExpiresAt time.Time `json:"expiresAt"`
}

func CreateTenant

func CreateTenant(request CreateTenantRequest) (TenantRecord, error)

func GetTenant

func GetTenant(id string) (TenantRecord, error)

func UpdateTenant

func UpdateTenant(request UpdateTenantRequest) (TenantRecord, error)

type UpdateTenantRequest

type UpdateTenantRequest struct {
	ID        string
	Name      string
	Contact   string
	CellPhone string
	Address   string
	UserLimit int32
	ExpiresAt time.Time
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL