diff --git a/action_update.go b/action_update.go index d47818f..682530c 100644 --- a/action_update.go +++ b/action_update.go @@ -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 +} diff --git a/db.go b/db.go index 8e8c25e..1a25e54 100644 --- a/db.go +++ b/db.go @@ -100,4 +100,13 @@ 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 } \ No newline at end of file