Files
hfb_sys/backend/internal/modules/auth/repository.go
T
yml2213 1ba7c1dea1 feat(auth): 新增密码登录注册与改密功能并加固安全
- 后端:新增密码登录/注册/重置/改密接口,users 表新增 password_hash 字段
- 安全加固:注册改为冲突即失败防止"注册即改密",登录用户不存在统一返回密码错误并计失败次数防枚举,改密需校验旧密码,清理登录失败计数中的死代码
- 前端:登录页重构为"登录/注册"两个 tab,登录内可切换密码/短信方式,默认密码登录
- 个人中心新增修改密码入口(PC 弹窗 + 移动端 popup),PC 个人资料页移除买家/卖家服务面板
2026-07-02 19:02:49 +08:00

102 lines
2.6 KiB
Go

package auth
import (
"context"
"errors"
"time"
"hfb_sys/backend/internal/model"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
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
if err := r.db.WithContext(ctx).First(&user, id).Error; err != nil {
return nil, err
}
return &user, nil
}
func (r *UserRepository) UpdateProfile(ctx context.Context, id uint64, nickname string, avatarURL string) (*model.User, error) {
if err := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", id).Updates(map[string]any{
"nickname": nickname,
"avatar_url": avatarURL,
}).Error; err != nil {
return nil, err
}
return r.FindByID(ctx, id)
}
func (r *UserRepository) FindOrCreateByPhone(ctx context.Context, phone string) (*model.User, error) {
now := time.Now()
user := model.User{
Phone: phone,
Nickname: "用户" + phone[len(phone)-4:],
RealnameStatus: "unverified",
RiskStatus: "normal",
CreditScore: 100,
Status: "active",
LastLoginAt: &now,
}
err := r.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "phone"}},
DoUpdates: clause.AssignmentColumns([]string{"last_login_at", "updated_at"}),
}).Create(&user).Error
if err != nil {
return nil, err
}
var found model.User
if err := r.db.WithContext(ctx).Where("phone = ?", phone).First(&found).Error; err != nil {
return nil, err
}
return &found, nil
}
func (r *UserRepository) FindByPhone(ctx context.Context, phone string) (*model.User, error) {
var user model.User
if err := r.db.WithContext(ctx).Where("phone = ?", phone).First(&user).Error; err != nil {
return nil, err
}
return &user, nil
}
func (r *UserRepository) SetPassword(ctx context.Context, userID uint64, hash string) error {
return r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", userID).Update("password_hash", hash).Error
}
func (r *UserRepository) RegisterWithPassword(ctx context.Context, phone string, hash string) (*model.User, error) {
now := time.Now()
user := model.User{
Phone: phone,
PasswordHash: hash,
Nickname: "用户" + phone[len(phone)-4:],
RealnameStatus: "unverified",
RiskStatus: "normal",
CreditScore: 100,
Status: "active",
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)
}