Add admin-only private chat messages and message deletion
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:
2026-09-16 15:22:26 +01:00
co-authored by Claude Fable 5.1
parent ebb28532c3
commit 6037729edd
8 changed files with 209 additions and 16 deletions
+37
View File
@@ -118,6 +118,7 @@ type ComplexityRoot struct {
CreatedAt func(childComplexity int) int CreatedAt func(childComplexity int) int
FileURL func(childComplexity int) int FileURL func(childComplexity int) int
ID func(childComplexity int) int ID func(childComplexity int) int
Private func(childComplexity int) int
} }
Mutation struct { Mutation struct {
@@ -641,6 +642,12 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
} }
return e.ComplexityRoot.Message.ID(childComplexity), true 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": case "Mutation.createActivity":
if e.ComplexityRoot.Mutation.CreateActivity == nil { 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) return ec.fieldContext_Message_authorId(ctx, field)
case "fileUrl": case "fileUrl":
return ec.fieldContext_Message_fileUrl(ctx, field) return ec.fieldContext_Message_fileUrl(ctx, field)
case "private":
return ec.fieldContext_Message_private(ctx, field)
case "createdAt": case "createdAt":
return ec.fieldContext_Message_createdAt(ctx, field) 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")) 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) { func (ec *executionContext) _Message_createdAt(ctx context.Context, field graphql.CollectedField, obj *models.Message) (ret graphql.Marshaler) {
return graphql.ResolveField( return graphql.ResolveField(
ctx, ctx,
@@ -8595,6 +8627,11 @@ func (ec *executionContext) _Message(ctx context.Context, sel ast.SelectionSet,
if out.Values[i] == graphql.RequiredNull { if out.Values[i] == graphql.RequiredNull {
atomic.AddUint32(&out.Invalids, 1) 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": case "createdAt":
out.Values[i] = ec._Message_createdAt(ctx, field, obj) out.Values[i] = ec._Message_createdAt(ctx, field, obj)
if out.Values[i] == graphql.Null { if out.Values[i] == graphql.Null {
+5 -1
View File
@@ -24,7 +24,11 @@ func (r *messageResolver) AuthorID(ctx context.Context, obj *models.Message) (in
// Messages is the resolver for the messages field. // Messages is the resolver for the messages field.
func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) { func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) {
var messages []models.Message 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 return nil, err
} }
result := make([]*models.Message, len(messages)) result := make([]*models.Message, len(messages))
+1
View File
@@ -3,6 +3,7 @@ type Message {
content: String! content: String!
authorId: Int! authorId: Int!
fileUrl: String fileUrl: String
private: Boolean!
createdAt: Time! createdAt: Time!
} }
+36 -1
View File
@@ -1,16 +1,51 @@
package handlers package handlers
import ( import (
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services" "adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func (store *Store) ConnectWebSocket(ctx *gin.Context) { 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) conn, err := services.Upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
if err != nil { if err != nil {
// Upgrader already wrote the HTTP error response, so just return // Upgrader already wrote the HTTP error response, so just return
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
} }
+1
View File
@@ -32,6 +32,7 @@ type Message struct {
Content string `json:"text"` Content string `json:"text"`
AuthorID uint `json:"authorId"` AuthorID uint `json:"authorId"`
FileURL string `json:"fileUrl,omitempty"` FileURL string `json:"fileUrl,omitempty"`
Private bool `gorm:"not null;default:false" json:"private"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
} }
+68 -8
View File
@@ -34,6 +34,7 @@ var Upgrader = websocket.Upgrader{
} }
var ( var (
// clients maps each open connection to whether it belongs to an admin.
clients = make(map[*websocket.Conn]bool) clients = make(map[*websocket.Conn]bool)
mu sync.Mutex mu sync.Mutex
wsDB *gorm.DB wsDB *gorm.DB
@@ -45,21 +46,43 @@ const (
rateLimitMaxMsgs = 10 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) { func InitWebSocket(database *gorm.DB, domain string) {
wsDB = database wsDB = database
allowedDomain = domain 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() defer conn.Close()
mu.Lock() mu.Lock()
clients[conn] = true clients[conn] = isAdmin
nextAuthorID++ nextAuthorID++
authorID := nextAuthorID authorID := nextAuthorID
var history []models.Message 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 { for _, msg := range history {
if err := conn.WriteJSON(msg); err != nil { if err := conn.WriteJSON(msg); err != nil {
@@ -73,7 +96,7 @@ func HandleWebSocket(conn *websocket.Conn) {
windowStart := time.Now() windowStart := time.Now()
for { for {
var incoming models.Message var incoming wsIncoming
if err := conn.ReadJSON(&incoming); err != nil { if err := conn.ReadJSON(&incoming); err != nil {
break break
} }
@@ -88,16 +111,32 @@ func HandleWebSocket(conn *websocket.Conn) {
continue 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() mu.Lock()
wsDB.Create(&incoming) wsDB.Create(&msg)
wsDB.Where("id NOT IN (?)", wsDB.Where("id NOT IN (?)",
wsDB.Model(&models.Message{}).Select("id").Order("created_at DESC").Limit(maxMessages), wsDB.Model(&models.Message{}).Select("id").Order("created_at DESC").Limit(maxMessages),
).Delete(&models.Message{}) ).Delete(&models.Message{})
for client := range clients { for client, clientAdmin := range clients {
if err := client.WriteJSON(incoming); err != nil { if msg.Private && !clientAdmin {
continue
}
if err := client.WriteJSON(msg); err != nil {
client.Close() client.Close()
delete(clients, client) delete(clients, client)
} }
@@ -109,3 +148,24 @@ func HandleWebSocket(conn *websocket.Conn) {
delete(clients, conn) delete(clients, conn)
mu.Unlock() 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)
}
}
}
+45 -2
View File
@@ -1,6 +1,7 @@
<script setup> <script setup>
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from "vue"; import { ref, computed, watch, nextTick, onMounted, onUnmounted } from "vue";
import Button from "@/components/input/Button.vue"; import Button from "@/components/input/Button.vue";
import ToggleButton from "@/components/input/ToggleButton.vue";
import { useMessagesStore } from "@/stores/messages"; import { useMessagesStore } from "@/stores/messages";
import { useAuthStore } from "@/stores/auth"; import { useAuthStore } from "@/stores/auth";
import Header from "@/components/text/Header.vue"; import Header from "@/components/text/Header.vue";
@@ -13,6 +14,8 @@ const messageInput = ref("");
const messagesContainer = ref(null); const messagesContainer = ref(null);
const messagesInner = ref(null); const messagesInner = ref(null);
const fileInput = ref(null); const fileInput = ref(null);
const isAdmin = computed(() => !!authStore.user.admin);
const sendPrivate = ref(false);
const isNearBottom = ref(true); const isNearBottom = ref(true);
const SCROLL_THRESHOLD = 100; const SCROLL_THRESHOLD = 100;
@@ -53,15 +56,30 @@ function sendMessage() {
const text = messageInput.value.trim(); const text = messageInput.value.trim();
if (!text) return; if (!text) return;
isNearBottom.value = true; isNearBottom.value = true;
messagesStore.sendMessage(text); messagesStore.sendMessage(text, isAdmin.value && sendPrivate.value);
messageInput.value = ""; messageInput.value = "";
} }
function deleteMessage(id) {
messagesStore.deleteMessage(id);
}
// Admin status is fixed when the socket connects (from the auth cookies), so
// reconnect after a login/logout to pick up or drop private messages.
watch(isAdmin, () => {
if (!messagesStore.isConnected) return;
messagesStore.disconnect();
messagesStore.connect();
});
async function onFileSelected(e) { async function onFileSelected(e) {
const file = e.target.files[0]; const file = e.target.files[0];
if (!file) return; if (!file) return;
isNearBottom.value = true; isNearBottom.value = true;
await messagesStore.uploadAndSendFile(file); await messagesStore.uploadAndSendFile(
file,
isAdmin.value && sendPrivate.value,
);
fileInput.value.value = ""; fileInput.value.value = "";
} }
@@ -142,6 +160,24 @@ onUnmounted(() => {
v-for="message in messages" v-for="message in messages"
:key="message.id" :key="message.id"
class="break-words min-w-0 w-full" class="break-words min-w-0 w-full"
:class="{ 'text-secondary italic': message.private }"
>
<button
v-if="isAdmin && message.id"
type="button"
class="text-tertiary hover:text-primary cursor-pointer mr-1"
aria-label="Delete message"
title="Delete message"
@click="deleteMessage(message.id)"
>
×
</button>
<span
v-if="message.private"
class="text-tertiary"
title="Private: only admins can see this"
aria-label="Private message"
>🔒</span
> >
<span class="text-tertiary">{{ message.authorId }}:</span> <span class="text-tertiary">{{ message.authorId }}:</span>
<template <template
@@ -197,6 +233,13 @@ onUnmounted(() => {
class="hidden" class="hidden"
@change="onFileSelected" @change="onFileSelected"
/> />
<label
v-if="isAdmin"
class="flex items-center gap-2 py-1 text-sm text-secondary cursor-pointer"
>
<ToggleButton v-model="sendPrivate" />
<span>Private (admins only)</span>
</label>
<div class="flex gap-2"> <div class="flex gap-2">
<Button class="flex-1" @click="sendMessage">Send</Button> <Button class="flex-1" @click="sendMessage">Send</Button>
<Button <Button
+16 -4
View File
@@ -34,6 +34,10 @@ export const useMessagesStore = defineStore("messages", () => {
socket.value.onmessage = (event) => { socket.value.onmessage = (event) => {
try { try {
const data = JSON.parse(event.data); const data = JSON.parse(event.data);
if (data.action === "delete") {
messages.value = messages.value.filter((m) => m.id !== data.id);
return;
}
messages.value.push(data); messages.value.push(data);
} catch { } catch {
messages.value.push({ text: event.data }); messages.value.push({ text: event.data });
@@ -65,23 +69,30 @@ export const useMessagesStore = defineStore("messages", () => {
isConnected.value = false; isConnected.value = false;
} }
function sendMessage(text) { function sendMessage(text, isPrivate = false) {
if (!socket.value || !isConnected.value) return; if (!socket.value || !isConnected.value) return;
socket.value.send(JSON.stringify({ text })); socket.value.send(JSON.stringify({ text, private: isPrivate }));
}
function deleteMessage(id) {
if (!socket.value || !isConnected.value) return;
socket.value.send(JSON.stringify({ action: "delete", id }));
} }
function clearMessages() { function clearMessages() {
messages.value = []; messages.value = [];
} }
async function uploadAndSendFile(file) { async function uploadAndSendFile(file, isPrivate = false) {
try { try {
const formData = new FormData(); const formData = new FormData();
formData.append("file", file); formData.append("file", file);
const res = await axios.post("/api/messages/upload", formData); const res = await axios.post("/api/messages/upload", formData);
const { url } = res.data; const { url } = res.data;
if (!socket.value || !isConnected.value) return; if (!socket.value || !isConnected.value) return;
socket.value.send(JSON.stringify({ text: "", fileUrl: url })); socket.value.send(
JSON.stringify({ text: "", fileUrl: url, private: isPrivate }),
);
} catch (err) { } catch (err) {
lastError.value = err; lastError.value = err;
} }
@@ -97,6 +108,7 @@ export const useMessagesStore = defineStore("messages", () => {
connect, connect,
disconnect, disconnect,
sendMessage, sendMessage,
deleteMessage,
clearMessages, clearMessages,
uploadAndSendFile, uploadAndSendFile,
}; };