fix(SSO登录):身份判定只按工号唯一校验,邮箱降级为属性同步
deploy-hxtesting / build-and-deploy (push) Successful in 1m18s

工号相同即同一人:OIDC 登录先按 username(工号)精确命中本地账号并认回,
邮箱不同(员工改邮箱/测试 IdP 随意填写)不再分裂出 26040006-1、22030265-1
式重复账号。email 仅作工号未命中时的兜底匹配;收编后 IdP 邮箱跟随同步为
账号属性(兜底域占位邮箱不覆盖本地真实邮箱)。停用账号同样被工号命中并
由登录守卫拒绝,避免停用员工绕道拿到 -1 新号。
This commit is contained in:
runny committed 2026-11-27 15:20:33 +08:00
1 parent 043e0485e2
commit 4f77907a8a
2 files changed
+222 -169

No files matched your search

+59 -78
View File
@@ -573,24 +573,19 @@ func (s *userService) finishOIDCLogin(
return nil, errors.New("OIDC provider did not return email")
}
user, err := s.userRepo.GetUserByEmail(ctx, userInfo.Email)
if err != nil && !isUserLookupNotFound(err) {
return nil, fmt.Errorf("failed to query user by email: %w", err)
// 身份判定只看工号:username(工号)精确命中即认回老账号,邮箱不同
// 不另开户;email 仅作工号未命中时的兜底匹配。见 resolveOIDCLoginUser。
user, err := s.resolveOIDCLoginUser(ctx, userInfo)
if err != nil {
return nil, err
}
isNewUser := false
if isUserLookupNotFound(err) || user == nil {
// 老账号自愈:按 email 查不到时(占位邮箱规则变更,或导入/手建
// 账号与 IdP 邮箱前缀不一致),先按 username(工号)收编活跃老
// 账号并归一邮箱,避免重复开户分裂出 26040006-1 式账号。收编
// 条件见 adoptOIDCUserByUsername。
user = s.adoptOIDCUserByUsername(ctx, userInfo)
if user == nil {
user, err = s.provisionOIDCUser(ctx, userInfo, provisioning)
if err != nil {
return nil, err
}
isNewUser = true
if user == nil {
user, err = s.provisionOIDCUser(ctx, userInfo, provisioning)
if err != nil {
return nil, err
}
isNewUser = true
}
// 姓名随登录刷新:IdP 侧改名后下一次登录生效(失败仅告警)。
@@ -2187,79 +2182,65 @@ func (s *userService) provisionOIDCUser(
return user, nil
}
// adoptOIDCUserByUsername 工号收编:按 email 查不到时(占位邮箱规则变更,
// 或导入/手建账号与 IdP 邮箱前缀不一致),按 username(工号)找回本地老
// 账号,根治同一工号分裂出 "26040006-1" 式重复账号——OIDC 首登自动开户
// 撞上已占用工号后会顺延 -1/-2 后缀。收编条件全部满足才生效:
// 1. username 精确命中本地账号且账号活跃;
// 2. 本地邮箱可信:是同兜底域的占位邮箱,或与 IdP 邮箱同域(同一企业
// 的两种邮箱形态,如 26040006@corp ↔ sun.kai@corp);完全无关的
// 外部邮箱不收编;
// 3. 新邮箱(本次登录 IdP 返回/合成,finishOIDCLogin 已查询未命中)必然
// 未被占用,直接改写本地邮箱完成归一。
//
// 收编不再要求账号是 OIDC 开户(OidcOnlyLogin):导入开户与手工开户的
// 工号账号同样认回。返回 nil 表示无可收编账号,调用方按新用户正常开户。
// 失败仅告警,不阻塞登录。
func (s *userService) adoptOIDCUserByUsername(ctx context.Context, info *types.OIDCUserInfo) *types.User {
// resolveOIDCLoginUser 以工号为唯一身份键解析 SSO 登录对应的本地账号:
// 工号相同即同一人,邮箱不参与身份判定(员工改邮箱 / 测试 IdP 随意填写
// 邮箱,都不允许分裂出 "26040006-1" 式重复账号——OIDC 首登自动开户撞上
// 已占用工号后会顺延 -1/-2 后缀)。解析顺序:
// 1. username(工号)精确命中 → 认回,并把 IdP 邮箱同步为账号属性
// (syncAdoptedOIDCEmail)。停用账号同样命中:交由调用方的停用检查
// 拒绝登录,避免停用员工绕道拿到 -1 新号;
// 2. email 精确命中 → 认回(工号 claim 异常 / 历史账号 username 非工号
// 时的兜底,不改动该账号);
// 3. 都未命中 → 返回 nil,调用方按新用户自动开户。
func (s *userService) resolveOIDCLoginUser(ctx context.Context, info *types.OIDCUserInfo) (*types.User, error) {
if s.userRepo == nil {
return nil
return nil, nil
}
candidate := sanitizeUsernameCandidate(info.Username)
if candidate == "" {
return nil
if candidate := sanitizeUsernameCandidate(info.Username); candidate != "" {
user, err := s.userRepo.GetUserByUsername(ctx, candidate)
if err != nil && !isUserLookupNotFound(err) {
return nil, fmt.Errorf("failed to query user by username: %w", err)
}
if user != nil {
s.syncAdoptedOIDCEmail(ctx, user, info)
return user, nil
}
}
existing, err := s.userRepo.GetUserByUsername(ctx, candidate)
if err != nil || existing == nil || !existing.IsActive {
return nil
user, err := s.userRepo.GetUserByEmail(ctx, info.Email)
if err != nil && !isUserLookupNotFound(err) {
return nil, fmt.Errorf("failed to query user by email: %w", err)
}
if !isUserLookupNotFound(err) && user != nil {
return user, nil
}
return nil, nil
}
// syncAdoptedOIDCEmail 工号收编后把 IdP 邮箱同步为账号属性(身份已由工号
// 锁定,邮箱只跟随 IdP)。唯一例外:IdP 侧是兜底域合成的占位邮箱而本地是
// 真实邮箱时不覆盖,避免真实邮箱被占位值冲掉。best-effort:失败仅告警,
// 不阻塞登录(下次登录重试)。
func (s *userService) syncAdoptedOIDCEmail(ctx context.Context, user *types.User, info *types.OIDCUserInfo) {
if user == nil || info.Email == "" || info.Email == user.Email {
return
}
fallbackDomain := ""
if s.config != nil && s.config.OIDCAuth != nil {
fallbackDomain = strings.ToLower(strings.TrimPrefix(strings.TrimSpace(s.config.OIDCAuth.EmailFallbackDomain), "@"))
}
if !adoptableOIDCEmail(existing.Email, info.Email, fallbackDomain) {
return nil
idpIsPlaceholder := fallbackDomain != "" &&
strings.HasSuffix(strings.ToLower(info.Email), "@"+fallbackDomain)
localIsPlaceholder := fallbackDomain != "" &&
strings.HasSuffix(strings.ToLower(user.Email), "@"+fallbackDomain)
if idpIsPlaceholder && !localIsPlaceholder {
return
}
if info.Email == "" || info.Email == existing.Email {
// 没有需要改写的邮箱(或新邮箱恰好与现值一致)。
return existing
user.Email = info.Email
if err := s.userRepo.UpdateUser(ctx, user); err != nil {
logger.Warnf(ctx, "OIDC adopted-account email sync failed for user %s: %v", user.ID, err)
return
}
existing.Email = info.Email
if displayName := strings.TrimSpace(info.DisplayName); displayName != "" && existing.DisplayName == "" {
existing.DisplayName = displayName
}
if err := s.userRepo.UpdateUser(ctx, existing); err != nil {
logger.Warnf(ctx, "OIDC username adoption failed for user %s: %v", existing.ID, err)
return nil
}
logger.Infof(ctx, "OIDC account adopted by username: user %s email → %s", existing.ID, existing.Email)
return existing
}
// adoptableOIDCEmail 判断本地账号邮箱是否可信、可被 OIDC 工号收编:
// - 同兜底域的占位邮箱(OIDC/导入开户按 <工号>@兜底域 合成);或
// - 与 IdP 邮箱同域。
//
// 其余(无关外部邮箱)不收编,避免把陌生账号错认给登录者。
func adoptableOIDCEmail(existingEmail, idpEmail, fallbackDomain string) bool {
existingDomain := emailDomain(existingEmail)
if existingDomain == "" {
return false
}
if fallbackDomain != "" && existingDomain == fallbackDomain {
return true
}
return existingDomain == emailDomain(idpEmail)
}
// emailDomain 取小写域名;无 @、@ 顶头/收尾视为畸形,返回空串。
func emailDomain(value string) string {
value = strings.ToLower(strings.TrimSpace(value))
at := strings.LastIndex(value, "@")
if at <= 0 || at == len(value)-1 {
return ""
}
return value[at+1:]
logger.Infof(ctx, "OIDC adopted-account email synced: user %s email → %s", user.ID, user.Email)
}
// refreshOIDCDisplayName 让姓名跟随 IdP:登录时若 claim 姓名变化则更新。
@@ -503,112 +503,184 @@ func TestFinishOIDCLoginAdoptsImportedAccountWithSameDomainEmail(t *testing.T) {
}
}
func TestAdoptOIDCUserByUsernamePlaceholderWithoutOidcMark(t *testing.T) {
// 占位邮箱但从未标过 OidcOnlyLogin(早期手工开户):工号命中即可收编。
existing := &types.User{
ID: "26040006", Username: "26040006",
Email: "26040006@casdoor.local", IsActive: true,
// Regression for the second 192 duplicate (蔡国梅 / 22030265-1): the IdP email
// lives on a completely unrelated domain (12.com) while the local account holds
// the fallback-domain placeholder. 工号 match must win — identity is the
// employee number, email is just an attribute that follows the IdP.
func TestFinishOIDCLoginAdoptsAccountWithCompletelyDifferentEmailDomain(t *testing.T) {
local := &types.User{
ID: "22030265",
Username: "22030265",
Email: "22030265@casdoor.local", // 本地占位邮箱
TenantID: 6,
IsActive: true,
}
repo := &sharedSpaceUserRepo{
byUsername: map[string]*types.User{"26040006": existing},
}
svc := &userService{userRepo: repo, config: oidcTestConfig()}
adopted := svc.adoptOIDCUserByUsername(context.Background(), &types.OIDCUserInfo{
Username: "26040006",
Email: "sun.kai@hxzh.com",
})
if adopted == nil || adopted.ID != "26040006" {
t.Fatalf("expected adoption, got %+v", adopted)
repo := &sharedSpaceUserRepo{
byUsername: map[string]*types.User{"22030265": local},
}
if len(repo.updated) != 1 || repo.updated[0].Email != "sun.kai@hxzh.com" {
t.Fatalf("email rewrite not persisted: %+v", repo.updated)
memberSvc := &sharedSpaceMemberSvc{membersByUser: []*types.TenantMember{
{UserID: "22030265", TenantID: 6, Role: types.TenantRoleOwner, Status: types.TenantMemberStatusActive},
}}
svc := newSharedSpaceService(t, false, repo, memberSvc, &sharedSpaceInvitationSvc{}, &sharedSpaceTenantSvc{})
svc.config = oidcTestConfig()
svc.tokenRepo = &stubAuthTokenRepo{}
resp, err := svc.finishOIDCLogin(context.Background(), &types.OIDCUserInfo{
Username: "22030265",
Email: "22030265@12.com", // IdP 真实邮箱,与本地完全不同域
}, types.TenantProvisioningCreatePersonal)
if err != nil {
t.Fatalf("finishOIDCLogin: %v", err)
}
if !resp.Success || resp.User == nil || resp.User.ID != "22030265" {
t.Fatalf("expected adoption by 工号, got resp=%+v", resp)
}
if resp.IsNewUser {
t.Fatal("same 工号 with different email must not create 22030265-1")
}
if resp.User.Email != "22030265@12.com" {
t.Fatalf("email attribute not synced from IdP: %s", resp.User.Email)
}
if len(repo.updated) == 0 {
t.Fatal("email sync must be persisted")
}
}
func TestAdoptOIDCUserByUsernameRejectsUnrelatedEmail(t *testing.T) {
// 本地邮箱是完全无关的外部邮箱(不同域、非占位):不收编,避免把
// 陌生账号错认给登录者。
existing := &types.User{
ID: "26040006", Username: "26040006",
Email: "someone@gmail.com", IsActive: true,
// 工号命中但账号已停用:认回停用账号并被登录守卫拒绝,绝不绕道新建 -1 号
// (停用员工重新拿到可用账号比拒绝登录严重得多)。
func TestFinishOIDCLoginAdoptedInactiveAccountIsDisabled(t *testing.T) {
local := &types.User{
ID: "22030265",
Username: "22030265",
Email: "22030265@casdoor.local",
TenantID: 6,
IsActive: false,
}
repo := &sharedSpaceUserRepo{
byUsername: map[string]*types.User{"26040006": existing},
}
svc := &userService{userRepo: repo, config: oidcTestConfig()}
adopted := svc.adoptOIDCUserByUsername(context.Background(), &types.OIDCUserInfo{
Username: "26040006",
Email: "sun.kai@hxzh.com",
})
if adopted != nil {
t.Fatalf("unrelated email must not be adopted, got %+v", adopted)
repo := &sharedSpaceUserRepo{
byUsername: map[string]*types.User{"22030265": local},
}
memberSvc := &sharedSpaceMemberSvc{}
svc := newSharedSpaceService(t, false, repo, memberSvc, &sharedSpaceInvitationSvc{}, &sharedSpaceTenantSvc{})
svc.config = oidcTestConfig()
svc.tokenRepo = &stubAuthTokenRepo{}
resp, err := svc.finishOIDCLogin(context.Background(), &types.OIDCUserInfo{
Username: "22030265",
Email: "22030265@12.com",
}, types.TenantProvisioningCreatePersonal)
if err != nil {
t.Fatalf("finishOIDCLogin: %v", err)
}
if resp.Success {
t.Fatal("disabled account must not log in")
}
if resp.Message != "Account is disabled" {
t.Fatalf("message = %q, want disabled", resp.Message)
}
if resp.IsNewUser {
t.Fatal("disabled account must not be re-provisioned as a fresh -1 account")
}
if len(memberSvc.adds) != 0 {
t.Fatalf("disabled account must not join any space: %+v", memberSvc.adds)
}
}
// 工号未命中(历史账号 username 不是工号)时回退按 email 命中,不另开户。
func TestFinishOIDCLoginFallsBackToEmailMatchWhenUsernameMisses(t *testing.T) {
legacy := &types.User{
ID: "legacy-zhangsan",
Username: "zhangsan", // 与工号 claim 不同
Email: "22030265@casdoor.local",
TenantID: 6,
IsActive: true,
}
repo := &sharedSpaceUserRepo{getUserByEmail: legacy}
memberSvc := &sharedSpaceMemberSvc{membersByUser: []*types.TenantMember{
{UserID: "legacy-zhangsan", TenantID: 6, Role: types.TenantRoleOwner, Status: types.TenantMemberStatusActive},
}}
svc := newSharedSpaceService(t, false, repo, memberSvc, &sharedSpaceInvitationSvc{}, &sharedSpaceTenantSvc{})
svc.config = oidcTestConfig()
svc.tokenRepo = &stubAuthTokenRepo{}
resp, err := svc.finishOIDCLogin(context.Background(), &types.OIDCUserInfo{
Username: "22030265",
Email: "22030265@casdoor.local",
}, types.TenantProvisioningCreatePersonal)
if err != nil {
t.Fatalf("finishOIDCLogin: %v", err)
}
if !resp.Success || resp.User == nil || resp.User.ID != "legacy-zhangsan" {
t.Fatalf("expected email fallback match, got resp=%+v", resp)
}
if resp.IsNewUser {
t.Fatal("email fallback match must not create a new user")
}
if len(repo.updated) != 0 {
t.Fatalf("no writes expected, got %+v", repo.updated)
t.Fatalf("email-path match must not rewrite the account, got %+v", repo.updated)
}
}
func TestAdoptOIDCUserByUsernameRejectsInactiveAccount(t *testing.T) {
existing := &types.User{
ID: "26040006", Username: "26040006",
Email: "26040006@hxzh.com", IsActive: false,
func TestSyncAdoptedOIDCEmail(t *testing.T) {
mk := func(localEmail string) (*sharedSpaceUserRepo, *types.User) {
user := &types.User{ID: "22030265", Username: "22030265", Email: localEmail, IsActive: true}
repo := &sharedSpaceUserRepo{byUsername: map[string]*types.User{"22030265": user}}
return repo, user
}
repo := &sharedSpaceUserRepo{
byUsername: map[string]*types.User{"26040006": existing},
svcWithCfg := func(repo *sharedSpaceUserRepo) *userService {
return &userService{userRepo: repo, config: oidcTestConfig()} // 兜底域 casdoor.local
}
svc := &userService{userRepo: repo, config: oidcTestConfig()}
adopted := svc.adoptOIDCUserByUsername(context.Background(), &types.OIDCUserInfo{
Username: "26040006",
Email: "sun.kai@hxzh.com",
})
if adopted != nil {
t.Fatalf("inactive account must not be adopted, got %+v", adopted)
}
}
func TestAdoptOIDCUserByUsernameSameDomainWithoutFallbackDomain(t *testing.T) {
// 未配置兜底域时占位邮箱分支不可用,但同域收编仍然生效。
existing := &types.User{
ID: "26040006", Username: "26040006",
Email: "26040006@hxzh.com", IsActive: true,
}
repo := &sharedSpaceUserRepo{
byUsername: map[string]*types.User{"26040006": existing},
}
svc := &userService{userRepo: repo} // config 为 nil
adopted := svc.adoptOIDCUserByUsername(context.Background(), &types.OIDCUserInfo{
Username: "26040006",
Email: "sun.kai@hxzh.com",
})
if adopted == nil || adopted.ID != "26040006" {
t.Fatalf("same-domain adoption must work without fallback domain, got %+v", adopted)
}
}
func TestAdoptableOIDCEmail(t *testing.T) {
cases := []struct {
name string
existingEmail string
idpEmail string
fallback string
want bool
}{
{"placeholder in fallback domain", "26040006@casdoor.local", "sun.kai@hxzh.com", "casdoor.local", true},
{"same domain as idp", "26040006@hxzh.com", "sun.kai@hxzh.com", "casdoor.local", true},
{"same domain without fallback config", "26040006@hxzh.com", "sun.kai@hxzh.com", "", true},
{"unrelated external email", "someone@gmail.com", "sun.kai@hxzh.com", "casdoor.local", false},
{"malformed existing email", "not-an-email", "sun.kai@hxzh.com", "casdoor.local", false},
{"empty existing email", "", "sun.kai@hxzh.com", "casdoor.local", false},
{"case-insensitive domain match", "26040006@HXZH.com", "sun.kai@hxzh.com", "", true},
}
for _, tc := range cases {
if got := adoptableOIDCEmail(tc.existingEmail, tc.idpEmail, tc.fallback); got != tc.want {
t.Errorf("%s: adoptableOIDCEmail(%q, %q, %q) = %v, want %v",
tc.name, tc.existingEmail, tc.idpEmail, tc.fallback, got, tc.want)
t.Run("IdP placeholder never clobbers local real email", func(t *testing.T) {
repo, user := mk("zhang.san@hxzh.com")
svcWithCfg(repo).syncAdoptedOIDCEmail(context.Background(), user, &types.OIDCUserInfo{
Username: "22030265", Email: "22030265@casdoor.local",
})
if user.Email != "zhang.san@hxzh.com" || len(repo.updated) != 0 {
t.Fatalf("real email clobbered: email=%s updated=%v", user.Email, repo.updated)
}
}
})
t.Run("IdP real email replaces local placeholder", func(t *testing.T) {
repo, user := mk("22030265@casdoor.local")
svcWithCfg(repo).syncAdoptedOIDCEmail(context.Background(), user, &types.OIDCUserInfo{
Username: "22030265", Email: "22030265@12.com",
})
if user.Email != "22030265@12.com" || len(repo.updated) != 1 {
t.Fatalf("email not synced: email=%s updated=%v", user.Email, repo.updated)
}
})
t.Run("IdP real email replaces local real email", func(t *testing.T) {
repo, user := mk("old@hxzh.com")
svcWithCfg(repo).syncAdoptedOIDCEmail(context.Background(), user, &types.OIDCUserInfo{
Username: "22030265", Email: "new@hxzh.com",
})
if user.Email != "new@hxzh.com" || len(repo.updated) != 1 {
t.Fatalf("email rename not synced: email=%s updated=%v", user.Email, repo.updated)
}
})
t.Run("same email writes nothing", func(t *testing.T) {
repo, user := mk("22030265@12.com")
svcWithCfg(repo).syncAdoptedOIDCEmail(context.Background(), user, &types.OIDCUserInfo{
Username: "22030265", Email: "22030265@12.com",
})
if len(repo.updated) != 0 {
t.Fatalf("unexpected writes: %+v", repo.updated)
}
})
t.Run("no fallback domain config still syncs", func(t *testing.T) {
repo, user := mk("22030265@casdoor.local")
svc := &userService{userRepo: repo} // config 为 nil
svc.syncAdoptedOIDCEmail(context.Background(), user, &types.OIDCUserInfo{
Username: "22030265", Email: "22030265@12.com",
})
if user.Email != "22030265@12.com" || len(repo.updated) != 1 {
t.Fatalf("email not synced without fallback domain: email=%s updated=%v", user.Email, repo.updated)
}
})
}