identity_repo.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // IdentityRepo 登录身份仓储(t_identity,一人多登录方式,(type,identifier) 唯一)。
  2. //
  3. // 平台级访问(同 user_repo.go 包注释):不继承 scope.BaseRepo,裸 *gorm.DB。
  4. // 登录主链路的核心查询:按 (type, identifier) 唯一定位 → 取 canonical_user_id → 再查 user。
  5. package repository
  6. import (
  7. "context"
  8. "gorm.io/gorm"
  9. "yuansiwei/unified-backend/internal/identity/model"
  10. )
  11. // IdentityRepo 登录身份仓储。
  12. type IdentityRepo struct {
  13. db *gorm.DB
  14. }
  15. // NewIdentityRepo 构造登录身份仓储。
  16. //
  17. // 入参:db *gorm.DB:数据库句柄(必填)。
  18. // 出参:*IdentityRepo:就绪仓储。
  19. func NewIdentityRepo(db *gorm.DB) *IdentityRepo {
  20. return &IdentityRepo{db: db}
  21. }
  22. // GetByTypeIdentifier 按 (type, identifier) 唯一键取登录身份记录。
  23. //
  24. // 入参:
  25. // - ctx context.Context:请求上下文。
  26. // - typ string:身份类型(model.IdentityType* 之一:phone/email/wechat/username/legacy_academic/legacy_teaching)。
  27. // - identifier string:归一后的标识值(phone 11 位 / email 小写 / wechat open_id / username 原值)。
  28. //
  29. // 出参:
  30. // - *model.Identity:身份记录(含 CanonicalUserID,供 Service 再查 user)。
  31. // - error:
  32. // - errors.ErrNotFound:该 (type, identifier) 无身份记录(登录"账号不存在"路径之一,防枚举统一文案);
  33. // - errors.ErrDBError:DB 异常。
  34. //
  35. // 归一纪律(调用方责任):
  36. // - email 必须小写、phone 必须 11 位数字、wechat 必须 open_id 原值——Repository 不做归一,
  37. // 归一发生在 Service 入参处理(与旧系统数据归一规则一致,见 P0-02 盘点)。
  38. //
  39. // 实现说明:用 model(&model.Identity{}) 显式指定实体(GORM 自动映射表名 t_identity,TableName() 已锁定),
  40. // Where 用 (type, identifier) 联合条件 + First 取单条(UNIQUE 键保证最多 1 条,无需 Limit 但 First 自带取一)。
  41. func (r *IdentityRepo) GetByTypeIdentifier(ctx context.Context, typ, identifier string) (*model.Identity, error) {
  42. var it model.Identity
  43. if err := r.db.WithContext(ctx).
  44. Where("type = ? AND identifier = ?", typ, identifier).
  45. First(&it).Error; err != nil {
  46. return nil, mapGormErr(err)
  47. }
  48. return &it, nil
  49. }