Change status and password method

This commit is contained in:
Hoang 2021-11-09 09:38:24 +07:00
parent a4ae19667f
commit 13b807efd7
2 changed files with 68 additions and 0 deletions

View File

@ -2,6 +2,7 @@ package usermngmt
import (
"context"
"errors"
"github.com/Selly-Modules/mongodb"
"go.mongodb.org/mongo-driver/bson"
@ -55,3 +56,61 @@ func (s Service) UpdateByUserID(userID string, payload UpdateOptions) error {
return nil
}
// ChangePasswordByUserID ...
func (s Service) ChangePasswordByUserID(userID, oldPassword, newPassword string) error {
var (
ctx = context.Background()
id, _ = mongodb.NewIDFromString(userID)
)
if oldPassword == "" || newPassword == "" {
return errors.New("new password and old password cannot be empty")
}
// Find user
user, _ := s.userFindByID(ctx, id)
if user.ID.IsZero() {
return errors.New("user does not exist")
}
// Check old password
isValid := checkPasswordHash(oldPassword, user.HashedPassword)
if !isValid {
return errors.New("the password is incorrect")
}
// Update password
err := s.userUpdateOneByCondition(ctx, bson.M{"_id": user.ID}, bson.M{
"$set": bson.M{
"hashedPassword": hashPassword(newPassword),
"updatedAt": now(),
},
})
if err != nil {
return err
}
return nil
}
// ChangeStatusByUserID ...
func (s Service) ChangeStatusByUserID(userID, newStatus string) error {
var (
ctx = context.Background()
id, _ = mongodb.NewIDFromString(userID)
)
// Update password
err := s.userUpdateOneByCondition(ctx, bson.M{"_id": id}, bson.M{
"$set": bson.M{
"status": newStatus,
"updatedAt": now(),
},
})
if err != nil {
return err
}
return nil
}

9
db.go
View File

@ -101,3 +101,12 @@ func (s Service) userUpdateOneByCondition(ctx context.Context, cond interface{},
return err
}
func (s Service) userFindByID(ctx context.Context, id primitive.ObjectID) (User, error) {
var (
col = s.getUserCollection()
doc User
)
err := col.FindOne(ctx, bson.M{"_id": id}).Decode(&doc)
return doc, err
}