1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| func (r *userRepo) ListUser(ctx context.Context, pageNum, pageSize int) ([]*biz.User, int, error) { var users []User result := r.data.db.Find(&users) if result.Error != nil { return nil, 0, result.Error } total := int(result.RowsAffected) r.data.db.Scopes(paginate(pageNum, pageSize)).Find(&users) rv := make([]*biz.User, 0) for _, u := range users { rv = append(rv, &biz.User{ ID: u.ID, Mobile: u.Mobile, Password: u.Password, NickName: u.NickName, Gender: u.Gender, Role: u.Role, Birthday: u.Birthday, }) } return rv, total, nil }
func paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { if page == 0 { page = 1 }
switch { case pageSize > 100: pageSize = 100 case pageSize <= 0: pageSize = 10 }
offset := (page - 1) * pageSize return db.Offset(offset).Limit(pageSize) } }
func (r *userRepo) UserByMobile(ctx context.Context, mobile string) (*biz.User, error) { var user User result := r.data.db.Where(&User{Mobile: mobile}).First(&user) if result.Error != nil { return nil, result.Error }
if result.RowsAffected == 0 { return nil, status.Errorf(codes.NotFound, "用户不存在") } re := modelToResponse(user) return &re, nil }
func (r *userRepo) UpdateUser(ctx context.Context, user *biz.User) (bool, error) { var userInfo User result := r.data.db.Where(&User{ID: user.ID}).First(&userInfo) if result.RowsAffected == 0 { return false, status.Errorf(codes.NotFound, "用户不存在") }
userInfo.NickName = user.NickName userInfo.Birthday = user.Birthday userInfo.Gender = user.Gender
res := r.data.db.Save(&userInfo) if res.Error != nil { return false, status.Errorf(codes.Internal, res.Error.Error()) }
return true, nil }
func (r *userRepo) CheckPassword(ctx context.Context, psd, encryptedPassword string) (bool, error) { options := &password.Options{SaltLen: 16, Iterations: 10000, KeyLen: 32, HashFunction: sha512.New} passwordInfo := strings.Split(encryptedPassword, "$") check := password.Verify(psd, passwordInfo[2], passwordInfo[3], options) return check, nil }
func (r *userRepo) GetUserById(ctx context.Context, Id int64) (*biz.User, error) { var user User result := r.data.db.Where(&User{ID: Id}).First(&user) if result.Error != nil { return nil, result.Error }
if result.RowsAffected == 0 { return nil, status.Errorf(codes.NotFound, "用户不存在") } re := modelToResponse(user) return &re, nil }
|