feat: 实现 Bell 联系人与值班排班 (#183)
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
package contact
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrChannelKeyUnavailable = errors.New("联系人通道加密密钥未配置或格式错误")
|
||||
|
||||
func ParseChannelKey(value string) ([]byte, error) {
|
||||
key, err := base64.StdEncoding.DecodeString(strings.TrimSpace(value))
|
||||
if err != nil || len(key) != 32 {
|
||||
return nil, ErrChannelKeyUnavailable
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
func encryptAddress(key []byte, value string) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, ErrChannelKeyUnavailable
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return gcm.Seal(nonce, nonce, []byte(value), nil), nil
|
||||
}
|
||||
|
||||
func decryptAddress(key, encoded []byte) (string, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", ErrChannelKeyUnavailable
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(encoded) < gcm.NonceSize() {
|
||||
return "", errors.New("通道密文已损坏")
|
||||
}
|
||||
plain, err := gcm.Open(nil, encoded[:gcm.NonceSize()], encoded[gcm.NonceSize():], nil)
|
||||
return string(plain), err
|
||||
}
|
||||
|
||||
func fingerprint(value string) string {
|
||||
sum := sha256.Sum256([]byte(value))
|
||||
return base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package contact
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
)
|
||||
|
||||
type Handler struct{ api.Api }
|
||||
type enabledInput struct {
|
||||
Enabled *bool `json:"enabled" binding:"required"`
|
||||
ExpectedVersion int `json:"expectedVersion" binding:"required"`
|
||||
}
|
||||
type validationInput struct {
|
||||
Status string `json:"status"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
|
||||
func (h Handler) service() (Service, error) {
|
||||
key, err := ParseChannelKey(os.Getenv("BELL_CONTACT_CHANNEL_KEY"))
|
||||
return NewService(h.Orm, key), err
|
||||
}
|
||||
func (h Handler) List(c *gin.Context) {
|
||||
var q PageQuery
|
||||
h.MakeContext(c).MakeOrm().Bind(&q, binding.Form)
|
||||
if h.Errors != nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
items, count, err := NewService(h.Orm, nil).List(c.Request.Context(), q)
|
||||
if err != nil {
|
||||
h.Error(500, errors.New("读取联系人失败"), "读取联系人失败")
|
||||
return
|
||||
}
|
||||
p, s := pageValues(q.PageIndex, q.PageSize)
|
||||
h.PageOK(items, int(count), p, s, "查询成功")
|
||||
}
|
||||
func (h Handler) Create(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可维护联系人"), "仅管理员可维护联系人")
|
||||
return
|
||||
}
|
||||
var input WriteInput
|
||||
h.MakeContext(c).MakeOrm().Bind(&input, binding.JSON)
|
||||
if h.Errors != nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm, nil).Create(c.Request.Context(), input, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) Update(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可维护联系人"), "仅管理员可维护联系人")
|
||||
return
|
||||
}
|
||||
var input WriteInput
|
||||
h.MakeContext(c).MakeOrm().Bind(&input, binding.JSON)
|
||||
if h.Errors != nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm, nil).Update(c.Request.Context(), c.Param("id"), input, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) SetEnabled(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可维护联系人"), "仅管理员可维护联系人")
|
||||
return
|
||||
}
|
||||
var input enabledInput
|
||||
h.MakeContext(c).MakeOrm().Bind(&input, binding.JSON)
|
||||
if h.Errors != nil || input.Enabled == nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm, nil).SetEnabled(c.Request.Context(), c.Param("id"), *input.Enabled, input.ExpectedVersion, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) AddChannel(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可维护通道"), "仅管理员可维护通道")
|
||||
return
|
||||
}
|
||||
if err := restoreChannelBody(c); err != nil {
|
||||
h.MakeContext(c).Error(http.StatusBadRequest, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
var input ChannelInput
|
||||
h.MakeContext(c).MakeOrm().Bind(&input, binding.JSON)
|
||||
if h.Errors != nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
service, keyErr := h.service()
|
||||
if keyErr != nil {
|
||||
h.Error(503, keyErr, keyErr.Error())
|
||||
return
|
||||
}
|
||||
item, err := service.AddChannel(c.Request.Context(), c.Param("id"), input, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) ValidateChannel(c *gin.Context) {
|
||||
if !admin(c) {
|
||||
h.MakeContext(c).Error(403, errors.New("仅管理员可验证通道"), "仅管理员可验证通道")
|
||||
return
|
||||
}
|
||||
var input validationInput
|
||||
h.MakeContext(c).MakeOrm().Bind(&input, binding.JSON)
|
||||
if h.Errors != nil {
|
||||
h.Error(400, ErrInvalid, ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
item, err := NewService(h.Orm, nil).RecordValidation(c.Request.Context(), c.Param("id"), input.Status, input.Detail, user.GetUserId(c))
|
||||
h.result(item, err)
|
||||
}
|
||||
func (h Handler) result(item any, err error) {
|
||||
switch {
|
||||
case err == nil:
|
||||
h.OK(item, "保存成功")
|
||||
case errors.Is(err, ErrInvalid):
|
||||
h.Error(400, err, err.Error())
|
||||
case errors.Is(err, ErrNotFound):
|
||||
h.Error(404, err, err.Error())
|
||||
case errors.Is(err, ErrConflict):
|
||||
h.Error(409, err, err.Error())
|
||||
case errors.Is(err, ErrChannelKeyUnavailable):
|
||||
h.Error(503, err, err.Error())
|
||||
default:
|
||||
h.Logger.Errorf("write Bell contact failed: %v", err)
|
||||
h.Error(409, errors.New("联系人保存失败"), "联系人保存失败")
|
||||
}
|
||||
}
|
||||
func admin(c *gin.Context) bool {
|
||||
claims := jwt.ExtractClaims(c)
|
||||
role, _ := claims[jwt.RoleKey].(string)
|
||||
return role == "admin"
|
||||
}
|
||||
|
||||
var _ = http.StatusOK
|
||||
@@ -0,0 +1,68 @@
|
||||
package contact
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Contact struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
Name string `json:"name" gorm:"size:128;not null"`
|
||||
Role string `json:"role" gorm:"size:128;not null"`
|
||||
Enabled bool `json:"enabled" gorm:"not null;default:true;index"`
|
||||
Version int `json:"version" gorm:"not null;default:1"`
|
||||
CreatedBy int `json:"createdBy" gorm:"not null"`
|
||||
UpdatedBy int `json:"updatedBy" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null"`
|
||||
UpdatedAt time.Time `json:"updatedAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (Contact) TableName() string { return "bell_contacts" }
|
||||
|
||||
type Channel struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
ContactID string `json:"contactId" gorm:"type:uuid;not null;index"`
|
||||
Kind string `json:"kind" gorm:"size:16;not null"`
|
||||
AddressCiphertext []byte `json:"-" gorm:"type:bytea;not null"`
|
||||
AddressFingerprint string `json:"-" gorm:"size:64;not null;index"`
|
||||
AddressMasked string `json:"addressMasked" gorm:"size:64;not null"`
|
||||
CreatedBy int `json:"createdBy" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (Channel) TableName() string { return "bell_contact_channels" }
|
||||
|
||||
type ChannelValidation struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
ChannelID string `json:"channelId" gorm:"type:uuid;not null;index"`
|
||||
Status string `json:"status" gorm:"size:16;not null"`
|
||||
Detail string `json:"detail" gorm:"size:256;not null"`
|
||||
ActorID int `json:"actorId" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null;index"`
|
||||
}
|
||||
|
||||
func (ChannelValidation) TableName() string { return "bell_contact_channel_validations" }
|
||||
|
||||
type AuditFact struct {
|
||||
ID string `json:"id" gorm:"type:uuid;primaryKey"`
|
||||
ContactID string `json:"contactId" gorm:"type:uuid;not null;index"`
|
||||
Action string `json:"action" gorm:"size:32;not null"`
|
||||
Snapshot json.RawMessage `json:"snapshot" gorm:"type:jsonb;not null"`
|
||||
ActorID int `json:"actorId" gorm:"not null"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamptz;not null"`
|
||||
}
|
||||
|
||||
func (AuditFact) TableName() string { return "bell_contact_audit_facts" }
|
||||
|
||||
type ChannelView struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
AddressMasked string `json:"addressMasked"`
|
||||
Status string `json:"status"`
|
||||
ValidatedAt *time.Time `json:"validatedAt,omitempty"`
|
||||
}
|
||||
|
||||
type ContactView struct {
|
||||
Contact
|
||||
Channels []ChannelView `json:"channels"`
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package contact
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const maxChannelRequestBytes = 8 * 1024
|
||||
const channelBodyKey = "bell.contact.channel-body"
|
||||
const channelBodyErrorKey = "bell.contact.channel-body-error"
|
||||
|
||||
var redactedChannelBody = []byte(`{"redacted":true}`)
|
||||
|
||||
// RedactRequestBody must run before GoAdmin's LoggerToFile middleware. The
|
||||
// handler restores the original body from Gin context, while sys_opera_log
|
||||
// only sees a fixed marker and never the contact address.
|
||||
func RedactRequestBody() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if c.Request.Method != http.MethodPost || !isChannelCreatePath(c.Request.URL.Path) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(c.Request.Body, maxChannelRequestBytes+1))
|
||||
if err != nil {
|
||||
c.Set(channelBodyErrorKey, err)
|
||||
} else if len(body) > maxChannelRequestBytes {
|
||||
c.Set(channelBodyErrorKey, errors.New("request body too large"))
|
||||
} else {
|
||||
c.Set(channelBodyKey, body)
|
||||
}
|
||||
_ = c.Request.Body.Close()
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(redactedChannelBody))
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func restoreChannelBody(c *gin.Context) error {
|
||||
if value, ok := c.Get(channelBodyErrorKey); ok {
|
||||
return value.(error)
|
||||
}
|
||||
value, ok := c.Get(channelBodyKey)
|
||||
if !ok {
|
||||
return errors.New("channel request body was not captured")
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(value.([]byte)))
|
||||
return nil
|
||||
}
|
||||
|
||||
func isChannelCreatePath(path string) bool {
|
||||
const prefix = "/api/v1/bell/contacts/"
|
||||
const suffix = "/channels"
|
||||
if !strings.HasPrefix(path, prefix) || !strings.HasSuffix(path, suffix) {
|
||||
return false
|
||||
}
|
||||
id := strings.TrimSuffix(strings.TrimPrefix(path, prefix), suffix)
|
||||
return id != "" && !strings.Contains(id, "/")
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package contact
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type PageQuery struct {
|
||||
PageIndex int `form:"pageIndex"`
|
||||
PageSize int `form:"pageSize"`
|
||||
Name string `form:"name"`
|
||||
Enabled *bool `form:"enabled"`
|
||||
}
|
||||
type Service struct {
|
||||
DB *gorm.DB
|
||||
Key []byte
|
||||
}
|
||||
|
||||
func NewService(db *gorm.DB, key []byte) Service { return Service{DB: db, Key: key} }
|
||||
|
||||
func (s Service) List(ctx context.Context, query PageQuery) ([]ContactView, int64, error) {
|
||||
page, size := pageValues(query.PageIndex, query.PageSize)
|
||||
db := s.DB.WithContext(ctx).Model(&Contact{})
|
||||
if name := strings.TrimSpace(query.Name); name != "" {
|
||||
db = db.Where("name ILIKE ? OR role ILIKE ?", "%"+name+"%", "%"+name+"%")
|
||||
}
|
||||
if query.Enabled != nil {
|
||||
db = db.Where("enabled = ?", *query.Enabled)
|
||||
}
|
||||
var count int64
|
||||
if err := db.Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var contacts []Contact
|
||||
if err := db.Order("created_at DESC,id DESC").Offset((page - 1) * size).Limit(size).Find(&contacts).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
views := make([]ContactView, 0, len(contacts))
|
||||
for _, item := range contacts {
|
||||
view, err := s.view(ctx, item)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
views = append(views, view)
|
||||
}
|
||||
return views, count, nil
|
||||
}
|
||||
|
||||
func (s Service) Create(ctx context.Context, input WriteInput, actor int) (ContactView, error) {
|
||||
input, err := normalizeContact(input)
|
||||
if err != nil {
|
||||
return ContactView{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
item := Contact{ID: uuid.NewString(), Name: input.Name, Role: input.Role, Enabled: true, Version: 1, CreatedBy: actor, UpdatedBy: actor, CreatedAt: now, UpdatedAt: now}
|
||||
err = s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(&item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return appendAudit(tx, item, "created", actor)
|
||||
})
|
||||
if err != nil {
|
||||
return ContactView{}, err
|
||||
}
|
||||
return ContactView{Contact: item, Channels: []ChannelView{}}, nil
|
||||
}
|
||||
|
||||
func (s Service) Update(ctx context.Context, id string, input WriteInput, actor int) (ContactView, error) {
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
return ContactView{}, ErrNotFound
|
||||
}
|
||||
input, err := normalizeContact(input)
|
||||
if err != nil {
|
||||
return ContactView{}, err
|
||||
}
|
||||
if input.ExpectedVersion < 1 {
|
||||
return ContactView{}, ErrInvalid
|
||||
}
|
||||
var item Contact
|
||||
err = s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
result := tx.Model(&Contact{}).Where("id = ? AND version = ?", id, input.ExpectedVersion).Updates(map[string]any{"name": input.Name, "role": input.Role, "version": gorm.Expr("version + 1"), "updated_by": actor, "updated_at": time.Now().UTC()})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
var count int64
|
||||
_ = tx.Model(&Contact{}).Where("id = ?", id).Count(&count).Error
|
||||
if count == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return ErrConflict
|
||||
}
|
||||
if err := tx.First(&item, "id = ?", id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return appendAudit(tx, item, "updated", actor)
|
||||
})
|
||||
if err != nil {
|
||||
return ContactView{}, err
|
||||
}
|
||||
return s.view(ctx, item)
|
||||
}
|
||||
|
||||
func (s Service) SetEnabled(ctx context.Context, id string, enabled bool, expectedVersion, actor int) (ContactView, error) {
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
return ContactView{}, ErrNotFound
|
||||
}
|
||||
if expectedVersion < 1 {
|
||||
return ContactView{}, ErrInvalid
|
||||
}
|
||||
var item Contact
|
||||
err := s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
result := tx.Model(&Contact{}).Where("id = ? AND version = ?", id, expectedVersion).Updates(map[string]any{"enabled": enabled, "version": gorm.Expr("version + 1"), "updated_by": actor, "updated_at": time.Now().UTC()})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return ErrConflict
|
||||
}
|
||||
if err := tx.First(&item, "id = ?", id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return appendAudit(tx, item, map[bool]string{true: "enabled", false: "disabled"}[enabled], actor)
|
||||
})
|
||||
if err != nil {
|
||||
return ContactView{}, err
|
||||
}
|
||||
return s.view(ctx, item)
|
||||
}
|
||||
|
||||
func (s Service) AddChannel(ctx context.Context, contactID string, input ChannelInput, actor int) (ChannelView, error) {
|
||||
if len(s.Key) != 32 {
|
||||
return ChannelView{}, ErrChannelKeyUnavailable
|
||||
}
|
||||
if _, err := uuid.Parse(contactID); err != nil {
|
||||
return ChannelView{}, ErrNotFound
|
||||
}
|
||||
input, err := normalizeChannel(input)
|
||||
if err != nil {
|
||||
return ChannelView{}, err
|
||||
}
|
||||
ciphertext, err := encryptAddress(s.Key, input.Address)
|
||||
if err != nil {
|
||||
return ChannelView{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
item := Channel{ID: uuid.NewString(), ContactID: contactID, Kind: input.Kind, AddressCiphertext: ciphertext, AddressFingerprint: fingerprint(input.Address), AddressMasked: maskAddress(input.Address), CreatedBy: actor, CreatedAt: now}
|
||||
err = s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var contact Contact
|
||||
if err := tx.First(&contact, "id = ?", contactID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := tx.Create(&item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return appendAudit(tx, contact, "channel_added", actor)
|
||||
})
|
||||
if err != nil {
|
||||
return ChannelView{}, err
|
||||
}
|
||||
return ChannelView{ID: item.ID, Kind: item.Kind, AddressMasked: item.AddressMasked, Status: "pending"}, nil
|
||||
}
|
||||
|
||||
func (s Service) RecordValidation(ctx context.Context, channelID, status, detail string, actor int) (ChannelView, error) {
|
||||
status = strings.ToLower(strings.TrimSpace(status))
|
||||
detail = strings.TrimSpace(detail)
|
||||
if status != "verified" && status != "failed" {
|
||||
return ChannelView{}, ErrInvalid
|
||||
}
|
||||
if len([]rune(detail)) > 256 || hasControl(detail) {
|
||||
return ChannelView{}, ErrInvalid
|
||||
}
|
||||
var channel Channel
|
||||
fact := ChannelValidation{ID: uuid.NewString(), ChannelID: channelID, Status: status, Detail: detail, ActorID: actor, CreatedAt: time.Now().UTC()}
|
||||
err := s.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.First(&channel, "id = ?", channelID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := tx.Create(&fact).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
var c Contact
|
||||
if err := tx.First(&c, "id = ?", channel.ContactID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return appendAudit(tx, c, "channel_validation_"+status, actor)
|
||||
})
|
||||
if err != nil {
|
||||
return ChannelView{}, err
|
||||
}
|
||||
return ChannelView{ID: channel.ID, Kind: channel.Kind, AddressMasked: channel.AddressMasked, Status: status, ValidatedAt: &fact.CreatedAt}, nil
|
||||
}
|
||||
|
||||
// DecryptChannelAddress is intentionally server-only. API responses never expose this value.
|
||||
func (s Service) DecryptChannelAddress(ctx context.Context, channelID string) (string, error) {
|
||||
var item Channel
|
||||
if err := s.DB.WithContext(ctx).First(&item, "id = ?", channelID).Error; err != nil {
|
||||
return "", err
|
||||
}
|
||||
return decryptAddress(s.Key, item.AddressCiphertext)
|
||||
}
|
||||
|
||||
func (s Service) view(ctx context.Context, item Contact) (ContactView, error) {
|
||||
var channels []Channel
|
||||
if err := s.DB.WithContext(ctx).Where("contact_id = ?", item.ID).Order("created_at,id").Find(&channels).Error; err != nil {
|
||||
return ContactView{}, err
|
||||
}
|
||||
views := make([]ChannelView, 0, len(channels))
|
||||
for _, ch := range channels {
|
||||
view := ChannelView{ID: ch.ID, Kind: ch.Kind, AddressMasked: ch.AddressMasked, Status: "pending"}
|
||||
var fact ChannelValidation
|
||||
err := s.DB.WithContext(ctx).Where("channel_id = ?", ch.ID).Order("created_at DESC,id DESC").Take(&fact).Error
|
||||
if err == nil {
|
||||
view.Status = fact.Status
|
||||
view.ValidatedAt = &fact.CreatedAt
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ContactView{}, err
|
||||
}
|
||||
views = append(views, view)
|
||||
}
|
||||
return ContactView{Contact: item, Channels: views}, nil
|
||||
}
|
||||
|
||||
func appendAudit(tx *gorm.DB, item Contact, action string, actor int) error {
|
||||
snapshot, err := json.Marshal(map[string]any{"id": item.ID, "name": item.Name, "role": item.Role, "enabled": item.Enabled, "version": item.Version})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&AuditFact{ID: uuid.NewString(), ContactID: item.ID, Action: action, Snapshot: snapshot, ActorID: actor, CreatedAt: time.Now().UTC()}).Error
|
||||
}
|
||||
func pageValues(page, size int) (int, int) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if size < 1 || size > 100 {
|
||||
size = 20
|
||||
}
|
||||
return page, size
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package contact
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalid = errors.New("联系人或通道信息不符合要求")
|
||||
ErrNotFound = errors.New("联系人或通道不存在")
|
||||
ErrConflict = errors.New("数据已被其他人员更新,请刷新后重试")
|
||||
phonePattern = regexp.MustCompile(`^\+?[0-9]{6,20}$`)
|
||||
)
|
||||
|
||||
type WriteInput struct {
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
ExpectedVersion int `json:"expectedVersion"`
|
||||
}
|
||||
|
||||
type ChannelInput struct {
|
||||
Kind string `json:"kind"`
|
||||
Address string `json:"address"`
|
||||
}
|
||||
|
||||
func normalizeContact(input WriteInput) (WriteInput, error) {
|
||||
input.Name = strings.TrimSpace(input.Name)
|
||||
input.Role = strings.TrimSpace(input.Role)
|
||||
if input.Name == "" || len([]rune(input.Name)) > 128 || input.Role == "" || len([]rune(input.Role)) > 128 || hasControl(input.Name+input.Role) {
|
||||
return WriteInput{}, ErrInvalid
|
||||
}
|
||||
return input, nil
|
||||
}
|
||||
|
||||
func normalizeChannel(input ChannelInput) (ChannelInput, error) {
|
||||
input.Kind = strings.ToLower(strings.TrimSpace(input.Kind))
|
||||
input.Address = strings.ReplaceAll(strings.ReplaceAll(strings.TrimSpace(input.Address), " ", ""), "-", "")
|
||||
if (input.Kind != "sms" && input.Kind != "voice") || !phonePattern.MatchString(input.Address) {
|
||||
return ChannelInput{}, ErrInvalid
|
||||
}
|
||||
return input, nil
|
||||
}
|
||||
|
||||
func maskAddress(value string) string {
|
||||
runes := []rune(value)
|
||||
if len(runes) <= 4 {
|
||||
return "****"
|
||||
}
|
||||
return strings.Repeat("*", min(8, len(runes)-4)) + string(runes[len(runes)-4:])
|
||||
}
|
||||
|
||||
func hasControl(value string) bool {
|
||||
for _, r := range value {
|
||||
if r < 32 || r == 127 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user