databag/net/server/internal/api_addCard.go

99 lines
2.5 KiB
Go
Raw Normal View History

2022-01-20 23:19:26 +00:00
package databag
import (
"errors"
"net/http"
"gorm.io/gorm"
"encoding/hex"
2022-01-20 23:19:26 +00:00
"github.com/google/uuid"
"databag/internal/store"
"github.com/theckman/go-securerandom"
2022-01-20 23:19:26 +00:00
)
func AddCard(w http.ResponseWriter, r *http.Request) {
account, code, err := BearerAppToken(r, false)
if err != nil {
ErrResponse(w, code, err)
return
}
var message DataMessage
if err := ParseRequest(r, w, &message); err != nil {
ErrResponse(w, http.StatusBadRequest, err)
return
}
var identity Identity
guid, messageType, _, err := ReadDataMessage(&message, &identity)
if messageType != APP_MSGIDENTITY || err != nil {
ErrResponse(w, http.StatusBadRequest, err)
return
}
var card store.Card
if err := store.DB.Preload("Groups").Where("account_id = ? AND guid = ?", account.ID, guid).First(&card).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
ErrResponse(w, http.StatusInternalServerError, err)
return
}
2022-01-21 07:41:08 +00:00
// populate new record
card.CardId = uuid.New().String()
card.AccountID = account.Guid
2022-01-21 07:41:08 +00:00
card.Guid = guid
card.Username = identity.Handle
card.Name = identity.Name
card.Description = identity.Description
card.Location = identity.Location
card.Image = identity.Image
card.Version = identity.Version
card.Node = identity.Node
card.ProfileRevision = identity.Revision
card.Status = APP_CARDCONFIRMED
2022-01-21 21:18:35 +00:00
card.ViewRevision = 0
data, res := securerandom.Bytes(APP_TOKENSIZE)
if res != nil {
ErrResponse(w, http.StatusInternalServerError, res)
return
}
card.InToken = hex.EncodeToString(data)
2022-01-21 07:41:08 +00:00
2022-01-20 23:19:26 +00:00
} else {
2022-01-21 07:41:08 +00:00
if identity.Revision <= card.ProfileRevision {
WriteResponse(w, getCardModel(&card))
return
2022-01-20 23:19:26 +00:00
}
2022-01-21 07:41:08 +00:00
// update record if revision changed
card.Username = identity.Handle
card.Name = identity.Name
card.Description = identity.Description
card.Location = identity.Location
card.Image = identity.Image
card.Version = identity.Version
card.Node = identity.Node
card.ProfileRevision = identity.Revision
}
2022-01-21 05:48:24 +00:00
2022-01-21 07:41:08 +00:00
// save contact card
2022-01-21 05:48:24 +00:00
err = store.DB.Transaction(func(tx *gorm.DB) error {
if res := store.DB.Save(&card).Error; res != nil {
return res
}
if res := store.DB.Model(&account).Update("card_revision", account.CardRevision + 1).Error; res != nil {
return res
}
return nil
})
if err != nil {
2022-01-20 23:19:26 +00:00
ErrResponse(w, http.StatusInternalServerError, err)
return
}
2022-01-21 05:48:24 +00:00
SetStatus(account)
2022-01-20 23:19:26 +00:00
WriteResponse(w, getCardModel(&card))
}