databag/net/server/internal/api_getChannelTopic.go

117 lines
2.8 KiB
Go
Raw Normal View History

2022-02-18 20:21:15 +00:00
package databag
import (
"errors"
"net/http"
"gorm.io/gorm"
"github.com/gorilla/mux"
"databag/internal/store"
)
func GetChannelTopic(w http.ResponseWriter, r *http.Request) {
// scan parameters
params := mux.Vars(r)
topicId := params["topicId"]
channelSlot, _, err, code := getChannelSlot(r, false)
if err != nil {
ErrResponse(w, code, err)
return
}
// load topic
var topicSlot store.TopicSlot
2022-03-08 21:31:04 +00:00
if err = store.DB.Preload("Topic.Assets").Where("channel_id = ? AND topic_slot_id = ?", channelSlot.Channel.ID, topicId).First(&topicSlot).Error; err != nil {
2022-02-18 20:21:15 +00:00
if errors.Is(err, gorm.ErrRecordNotFound) {
code = http.StatusNotFound
} else {
code = http.StatusInternalServerError
}
return
}
WriteResponse(w, getTopicModel(&topicSlot))
}
func isMember(guid string, cards []store.Card) bool {
for _, card := range cards {
if guid == card.Guid {
return true
}
}
return false
}
func isViewer(guid string, groups []store.Group) bool {
for _, group := range groups {
for _, card := range group.Cards {
if guid == card.Guid {
return true
}
}
}
return false
}
func getChannelSlot(r *http.Request, member bool) (slot store.ChannelSlot, guid string, err error, code int) {
// scan parameters
params := mux.Vars(r)
channelId := params["channelId"]
// validate contact access
var account *store.Account
2022-04-14 21:13:08 +00:00
tokenType := ParamTokenType(r);
if tokenType == APP_TOKENAGENT {
2022-04-14 21:13:08 +00:00
account, code, err = ParamAgentToken(r, false);
2022-02-18 20:21:15 +00:00
if err != nil {
return
}
guid = account.Guid
} else if tokenType == APP_TOKENCONTACT {
var card *store.Card
2022-04-14 21:13:08 +00:00
card, code, err = ParamContactToken(r, true)
2022-02-18 20:21:15 +00:00
if err != nil {
return
}
account = &card.Account
guid = card.Guid
} else {
err = errors.New("unknown token type")
code = http.StatusBadRequest
return
}
// load channel
if err = store.DB.Preload("Account").Preload("Channel.Cards").Preload("Channel.Groups.Cards").Where("account_id = ? AND channel_slot_id = ?", account.ID, channelId).First(&slot).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
code = http.StatusNotFound
} else {
code = http.StatusInternalServerError
}
return
}
if slot.Channel == nil {
err = errors.New("referenced empty channel")
code = http.StatusNotFound
return
}
// validate access to channel
if tokenType == APP_TOKENCONTACT {
if member && !isMember(guid, slot.Channel.Cards) {
err = errors.New("contact is not a channel member")
code = http.StatusUnauthorized
return
} else if !isViewer(guid, slot.Channel.Groups) && !isMember(guid, slot.Channel.Cards) {
err = errors.New("contact is not a channel viewer")
code = http.StatusUnauthorized
return
}
}
return
}