240 lines
6.8 KiB
Go
240 lines
6.8 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
|
|
"hfb_sys/backend/internal/model"
|
|
"hfb_sys/backend/internal/tenancy"
|
|
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
var trackCodePattern = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`)
|
|
|
|
func sanitizeTrackCode(code string) string {
|
|
s := strings.TrimSpace(code)
|
|
if len(s) == 0 || len(s) > 64 || !trackCodePattern.MatchString(s) {
|
|
return ""
|
|
}
|
|
return s
|
|
}
|
|
|
|
type UserRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewUserRepository(db *gorm.DB) *UserRepository {
|
|
return &UserRepository{db: db}
|
|
}
|
|
|
|
func (r *UserRepository) FindByID(ctx context.Context, id uint64) (*model.User, error) {
|
|
var user model.User
|
|
query := r.db.WithContext(ctx)
|
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
|
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
|
}
|
|
if err := query.First(&user, id).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
// FindActiveForToken 校验用户仍可用且令牌版本未被撤销。
|
|
func (r *UserRepository) FindActiveForToken(ctx context.Context, id uint64, tokenVersion int64) (*model.User, error) {
|
|
if r == nil || r.db == nil {
|
|
return nil, ErrDependencyUnavailable
|
|
}
|
|
var user model.User
|
|
query := r.db.WithContext(ctx)
|
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
|
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
|
}
|
|
if err := query.
|
|
Select("id, phone, status, token_version").
|
|
First(&user, id).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
if user.Status != "active" {
|
|
return nil, ErrUserDisabled
|
|
}
|
|
if user.TokenVersion != tokenVersion {
|
|
return nil, ErrTokenVersionMismatch
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
func (r *UserRepository) UpdateProfile(ctx context.Context, id uint64, nickname string, avatarURL string) (*model.User, error) {
|
|
query := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", id)
|
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
|
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
|
}
|
|
if err := query.Updates(map[string]any{
|
|
"nickname": nickname,
|
|
"avatar_url": avatarURL,
|
|
}).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return r.FindByID(ctx, id)
|
|
}
|
|
|
|
func (r *UserRepository) resolveSiteID(ctx context.Context, siteCode string) uint64 {
|
|
siteCode = strings.TrimSpace(siteCode)
|
|
if siteCode == "" {
|
|
return 0
|
|
}
|
|
var ds model.DistributionSite
|
|
if err := r.db.WithContext(ctx).Where("site_code = ? AND status = 'active'", siteCode).Select("id").First(&ds).Error; err == nil {
|
|
return ds.ID
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func (r *UserRepository) FindOrCreateByPhone(ctx context.Context, phone string, trackCode string, siteCode ...string) (*model.User, error) {
|
|
now := time.Now()
|
|
code := sanitizeTrackCode(trackCode)
|
|
tenantID := tenancy.IDFromContext(ctx)
|
|
var siteID uint64
|
|
if len(siteCode) > 0 {
|
|
siteID = r.resolveSiteID(ctx, siteCode[0])
|
|
}
|
|
if tenantID > 0 {
|
|
siteID = 0
|
|
}
|
|
var existing model.User
|
|
query := r.db.WithContext(ctx).Where("phone = ?", phone)
|
|
if siteID > 0 {
|
|
query = query.Where("distribution_site_id = ?", siteID)
|
|
} else {
|
|
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
|
}
|
|
if err := query.First(&existing).Error; err == nil {
|
|
_ = r.db.WithContext(ctx).Model(&existing).Updates(map[string]any{
|
|
"last_login_at": now,
|
|
"updated_at": now,
|
|
}).Error
|
|
return &existing, nil
|
|
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, err
|
|
}
|
|
user := model.User{
|
|
TenantID: tenantID,
|
|
Phone: phone,
|
|
Nickname: "用户" + phone[len(phone)-4:],
|
|
RealnameStatus: "unverified",
|
|
RiskStatus: "normal",
|
|
CreditScore: 100,
|
|
Status: "active",
|
|
RegisterTrackCode: code,
|
|
DistributionSiteID: siteID,
|
|
LastLoginAt: &now,
|
|
}
|
|
|
|
onConflict := clause.OnConflict{
|
|
DoUpdates: clause.AssignmentColumns([]string{"last_login_at", "updated_at"}),
|
|
Columns: []clause.Column{
|
|
{Name: "tenant_id"},
|
|
{Name: "distribution_site_id"},
|
|
{Name: "phone"},
|
|
},
|
|
}
|
|
err := r.db.WithContext(ctx).Clauses(onConflict).Create(&user).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var found model.User
|
|
query = r.db.WithContext(ctx).Where("phone = ?", phone)
|
|
if siteID > 0 {
|
|
query = query.Where("distribution_site_id = ?", siteID)
|
|
} else {
|
|
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
|
}
|
|
if err := query.First(&found).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &found, nil
|
|
}
|
|
|
|
func (r *UserRepository) FindByPhone(ctx context.Context, phone string, siteCode ...string) (*model.User, error) {
|
|
tenantID := tenancy.IDFromContext(ctx)
|
|
var siteID uint64
|
|
if len(siteCode) > 0 {
|
|
siteID = r.resolveSiteID(ctx, siteCode[0])
|
|
}
|
|
if tenantID > 0 {
|
|
siteID = 0
|
|
}
|
|
var user model.User
|
|
query := r.db.WithContext(ctx).Where("phone = ?", phone)
|
|
if siteID > 0 {
|
|
query = query.Where("distribution_site_id = ?", siteID)
|
|
} else {
|
|
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
|
}
|
|
if err := query.First(&user).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
func (r *UserRepository) SetPassword(ctx context.Context, userID uint64, hash string) error {
|
|
query := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", userID)
|
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
|
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
|
}
|
|
return query.Updates(map[string]any{
|
|
"password_hash": hash,
|
|
"token_version": gorm.Expr("token_version + 1"),
|
|
}).Error
|
|
}
|
|
|
|
// RevokeTokens 使当前用户的所有 access/refresh token 立即失效。
|
|
func (r *UserRepository) RevokeTokens(ctx context.Context, userID uint64) error {
|
|
query := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", userID)
|
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
|
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
|
}
|
|
return query.UpdateColumn("token_version", gorm.Expr("token_version + 1")).Error
|
|
}
|
|
|
|
func (r *UserRepository) RegisterWithPassword(ctx context.Context, phone string, hash string, trackCode string, siteCode ...string) (*model.User, error) {
|
|
now := time.Now()
|
|
code := sanitizeTrackCode(trackCode)
|
|
tenantID := tenancy.IDFromContext(ctx)
|
|
var siteID uint64
|
|
if len(siteCode) > 0 {
|
|
siteID = r.resolveSiteID(ctx, siteCode[0])
|
|
}
|
|
if tenantID > 0 {
|
|
siteID = 0
|
|
}
|
|
user := model.User{
|
|
TenantID: tenantID,
|
|
Phone: phone,
|
|
PasswordHash: hash,
|
|
Nickname: "用户" + phone[len(phone)-4:],
|
|
RealnameStatus: "unverified",
|
|
RiskStatus: "normal",
|
|
CreditScore: 100,
|
|
Status: "active",
|
|
RegisterTrackCode: code,
|
|
DistributionSiteID: siteID,
|
|
LastLoginAt: &now,
|
|
}
|
|
|
|
err := r.db.WithContext(ctx).Create(&user).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
func IsNotFound(err error) bool {
|
|
return errors.Is(err, gorm.ErrRecordNotFound)
|
|
}
|