From 17694d398b59fbd2e5e68a71c80413c8fc2a1c33 Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Sun, 1 Dec 2024 02:05:46 +0800 Subject: [PATCH] :bug: Prevent user from adding a user twice into a channel --- pkg/internal/services/channel_members.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/pkg/internal/services/channel_members.go b/pkg/internal/services/channel_members.go index 77a2913..7b835ed 100644 --- a/pkg/internal/services/channel_members.go +++ b/pkg/internal/services/channel_members.go @@ -2,6 +2,7 @@ package services import ( "context" + "errors" "fmt" localCache "git.solsynth.dev/hypernet/messaging/pkg/internal/cache" "git.solsynth.dev/hypernet/messaging/pkg/internal/gap" @@ -10,6 +11,7 @@ import ( "github.com/eko/gocache/lib/v4/cache" "github.com/eko/gocache/lib/v4/marshaler" "github.com/eko/gocache/lib/v4/store" + "gorm.io/gorm" "git.solsynth.dev/hypernet/messaging/pkg/internal/database" "git.solsynth.dev/hypernet/messaging/pkg/internal/models" @@ -66,7 +68,15 @@ func AddChannelMemberWithCheck(user authm.Account, target models.Channel) error } func AddChannelMember(user authm.Account, target models.Channel) error { - member := models.ChannelMember{ + var member models.ChannelMember + if err := database.C.Where(&models.ChannelMember{ + AccountID: user.ID, + ChannelID: target.ID, + }).First(&member).Error; err == nil || errors.Is(err, gorm.ErrRecordNotFound) { + return fmt.Errorf("the user is already in the channel") + } + + member = models.ChannelMember{ ChannelID: target.ID, AccountID: user.ID, }