Add admin-only private chat messages and message deletion
Deploy with Docker Compose / deploy (push) Successful in 58s
Deploy with Docker Compose / deploy (push) Successful in 58s
Admins can flag a chat message as private so only other admin connections receive it, and can delete any message. Admin status is read from the auth cookies on the WebSocket upgrade request. Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
@@ -118,6 +118,7 @@ type ComplexityRoot struct {
|
||||
CreatedAt func(childComplexity int) int
|
||||
FileURL func(childComplexity int) int
|
||||
ID func(childComplexity int) int
|
||||
Private func(childComplexity int) int
|
||||
}
|
||||
|
||||
Mutation struct {
|
||||
@@ -641,6 +642,12 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
|
||||
}
|
||||
|
||||
return e.ComplexityRoot.Message.ID(childComplexity), true
|
||||
case "Message.private":
|
||||
if e.ComplexityRoot.Message.Private == nil {
|
||||
break
|
||||
}
|
||||
|
||||
return e.ComplexityRoot.Message.Private(childComplexity), true
|
||||
|
||||
case "Mutation.createActivity":
|
||||
if e.ComplexityRoot.Mutation.CreateActivity == nil {
|
||||
@@ -1559,6 +1566,8 @@ func (ec *executionContext) childFields_Message(ctx context.Context, field graph
|
||||
return ec.fieldContext_Message_authorId(ctx, field)
|
||||
case "fileUrl":
|
||||
return ec.fieldContext_Message_fileUrl(ctx, field)
|
||||
case "private":
|
||||
return ec.fieldContext_Message_private(ctx, field)
|
||||
case "createdAt":
|
||||
return ec.fieldContext_Message_createdAt(ctx, field)
|
||||
}
|
||||
@@ -3350,6 +3359,29 @@ func (ec *executionContext) fieldContext_Message_fileUrl(_ context.Context, fiel
|
||||
return graphql.NewScalarFieldContext("Message", field, false, false, errors.New("field of type String does not have child fields"))
|
||||
}
|
||||
|
||||
func (ec *executionContext) _Message_private(ctx context.Context, field graphql.CollectedField, obj *models.Message) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
ec.OperationContext,
|
||||
field,
|
||||
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
|
||||
return ec.fieldContext_Message_private(ctx, field)
|
||||
},
|
||||
func(ctx context.Context) (any, error) {
|
||||
return obj.Private, nil
|
||||
},
|
||||
nil,
|
||||
func(ctx context.Context, selections ast.SelectionSet, v bool) graphql.Marshaler {
|
||||
return ec.marshalNBoolean2bool(ctx, selections, v)
|
||||
},
|
||||
true,
|
||||
true,
|
||||
)
|
||||
}
|
||||
func (ec *executionContext) fieldContext_Message_private(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
|
||||
return graphql.NewScalarFieldContext("Message", field, false, false, errors.New("field of type Boolean does not have child fields"))
|
||||
}
|
||||
|
||||
func (ec *executionContext) _Message_createdAt(ctx context.Context, field graphql.CollectedField, obj *models.Message) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
@@ -8595,6 +8627,11 @@ func (ec *executionContext) _Message(ctx context.Context, sel ast.SelectionSet,
|
||||
if out.Values[i] == graphql.RequiredNull {
|
||||
atomic.AddUint32(&out.Invalids, 1)
|
||||
}
|
||||
case "private":
|
||||
out.Values[i] = ec._Message_private(ctx, field, obj)
|
||||
if out.Values[i] == graphql.Null {
|
||||
atomic.AddUint32(&out.Invalids, 1)
|
||||
}
|
||||
case "createdAt":
|
||||
out.Values[i] = ec._Message_createdAt(ctx, field, obj)
|
||||
if out.Values[i] == graphql.Null {
|
||||
|
||||
@@ -24,7 +24,11 @@ func (r *messageResolver) AuthorID(ctx context.Context, obj *models.Message) (in
|
||||
// Messages is the resolver for the messages field.
|
||||
func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) {
|
||||
var messages []models.Message
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&messages).Error; err != nil {
|
||||
query := r.Store.DB.Order("created_at DESC")
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
query = query.Where("private = ?", false)
|
||||
}
|
||||
if err := query.Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.Message, len(messages))
|
||||
|
||||
@@ -3,6 +3,7 @@ type Message {
|
||||
content: String!
|
||||
authorId: Int!
|
||||
fileUrl: String
|
||||
private: Boolean!
|
||||
createdAt: Time!
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,51 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func (store *Store) ConnectWebSocket(ctx *gin.Context) {
|
||||
// Work out admin status before upgrading: the browser sends the auth
|
||||
// cookies with the upgrade request, but they are not available afterwards.
|
||||
isAdmin := store.isAdminRequest(ctx)
|
||||
|
||||
conn, err := services.Upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
|
||||
if err != nil {
|
||||
// Upgrader already wrote the HTTP error response, so just return
|
||||
return
|
||||
}
|
||||
|
||||
services.HandleWebSocket(conn)
|
||||
services.HandleWebSocket(conn, isAdmin)
|
||||
}
|
||||
|
||||
// isAdminRequest reports whether the request carries valid admin credentials.
|
||||
// It prefers the access token and falls back to the refresh token plus a DB
|
||||
// lookup, so an admin whose access token has just expired is still recognised.
|
||||
func (store *Store) isAdminRequest(ctx *gin.Context) bool {
|
||||
if accessToken, err := ctx.Cookie("access_token"); err == nil {
|
||||
if claims, err := store.Auth.VerifyJWT(accessToken); err == nil {
|
||||
admin, ok := (*claims)["admin"].(bool)
|
||||
return ok && admin
|
||||
}
|
||||
}
|
||||
|
||||
refreshToken, err := ctx.Cookie("refresh_token")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
claims, err := store.Auth.VerifyJWT(refreshToken)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
user := models.User{ID: uint(userIDF)}
|
||||
if err := store.DB.First(&user).Error; err != nil {
|
||||
return false
|
||||
}
|
||||
return user.Admin
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ type Message struct {
|
||||
Content string `json:"text"`
|
||||
AuthorID uint `json:"authorId"`
|
||||
FileURL string `json:"fileUrl,omitempty"`
|
||||
Private bool `gorm:"not null;default:false" json:"private"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ var Upgrader = websocket.Upgrader{
|
||||
}
|
||||
|
||||
var (
|
||||
// clients maps each open connection to whether it belongs to an admin.
|
||||
clients = make(map[*websocket.Conn]bool)
|
||||
mu sync.Mutex
|
||||
wsDB *gorm.DB
|
||||
@@ -45,21 +46,43 @@ const (
|
||||
rateLimitMaxMsgs = 10
|
||||
)
|
||||
|
||||
// wsIncoming is the envelope clients send over the socket. A plain chat
|
||||
// message carries text/fileUrl/private; an admin delete carries action+id.
|
||||
type wsIncoming struct {
|
||||
Action string `json:"action,omitempty"`
|
||||
ID uint `json:"id,omitempty"`
|
||||
Text string `json:"text"`
|
||||
FileURL string `json:"fileUrl,omitempty"`
|
||||
Private bool `json:"private,omitempty"`
|
||||
}
|
||||
|
||||
// wsDeleteEvent is broadcast to every client when a message is removed.
|
||||
type wsDeleteEvent struct {
|
||||
Action string `json:"action"`
|
||||
ID uint `json:"id"`
|
||||
}
|
||||
|
||||
func InitWebSocket(database *gorm.DB, domain string) {
|
||||
wsDB = database
|
||||
allowedDomain = domain
|
||||
}
|
||||
|
||||
func HandleWebSocket(conn *websocket.Conn) {
|
||||
// HandleWebSocket serves one chat connection. isAdmin controls whether the
|
||||
// connection may see private messages, send them, and delete messages.
|
||||
func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
|
||||
defer conn.Close()
|
||||
|
||||
mu.Lock()
|
||||
clients[conn] = true
|
||||
clients[conn] = isAdmin
|
||||
nextAuthorID++
|
||||
authorID := nextAuthorID
|
||||
|
||||
var history []models.Message
|
||||
wsDB.Order("created_at ASC").Limit(maxMessages).Find(&history)
|
||||
historyQuery := wsDB.Order("created_at ASC").Limit(maxMessages)
|
||||
if !isAdmin {
|
||||
historyQuery = historyQuery.Where("private = ?", false)
|
||||
}
|
||||
historyQuery.Find(&history)
|
||||
|
||||
for _, msg := range history {
|
||||
if err := conn.WriteJSON(msg); err != nil {
|
||||
@@ -73,7 +96,7 @@ func HandleWebSocket(conn *websocket.Conn) {
|
||||
windowStart := time.Now()
|
||||
|
||||
for {
|
||||
var incoming models.Message
|
||||
var incoming wsIncoming
|
||||
if err := conn.ReadJSON(&incoming); err != nil {
|
||||
break
|
||||
}
|
||||
@@ -88,16 +111,32 @@ func HandleWebSocket(conn *websocket.Conn) {
|
||||
continue
|
||||
}
|
||||
|
||||
incoming.AuthorID = authorID
|
||||
if incoming.Action == "delete" {
|
||||
if isAdmin && incoming.ID != 0 {
|
||||
deleteMessage(incoming.ID)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
msg := models.Message{
|
||||
Content: incoming.Text,
|
||||
FileURL: incoming.FileURL,
|
||||
AuthorID: authorID,
|
||||
// Only admins may mark a message private.
|
||||
Private: incoming.Private && isAdmin,
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
wsDB.Create(&incoming)
|
||||
wsDB.Create(&msg)
|
||||
wsDB.Where("id NOT IN (?)",
|
||||
wsDB.Model(&models.Message{}).Select("id").Order("created_at DESC").Limit(maxMessages),
|
||||
).Delete(&models.Message{})
|
||||
|
||||
for client := range clients {
|
||||
if err := client.WriteJSON(incoming); err != nil {
|
||||
for client, clientAdmin := range clients {
|
||||
if msg.Private && !clientAdmin {
|
||||
continue
|
||||
}
|
||||
if err := client.WriteJSON(msg); err != nil {
|
||||
client.Close()
|
||||
delete(clients, client)
|
||||
}
|
||||
@@ -109,3 +148,24 @@ func HandleWebSocket(conn *websocket.Conn) {
|
||||
delete(clients, conn)
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
// deleteMessage soft-deletes a message and tells every client to drop it.
|
||||
// Clients that never received the message (non-admins for a private one)
|
||||
// simply ignore the unknown id.
|
||||
func deleteMessage(id uint) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
res := wsDB.Delete(&models.Message{}, id)
|
||||
if res.Error != nil || res.RowsAffected == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
event := wsDeleteEvent{Action: "delete", ID: id}
|
||||
for client := range clients {
|
||||
if err := client.WriteJSON(event); err != nil {
|
||||
client.Close()
|
||||
delete(clients, client)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user