All checks were successful
check / check (push) Successful in 2m19s
Security: - Add channel membership check before PRIVMSG (prevents non-members from sending) - Add membership check on history endpoint (channels require membership, DMs scoped to own nick) - Enforce MaxBytesReader on all POST request bodies - Fix rand.Read error being silently ignored in token generation Data integrity: - Fix TOCTOU race in GetOrCreateChannel using INSERT OR IGNORE + SELECT Build: - Add CGO_ENABLED=0 to golangci-lint install in Dockerfile (fixes alpine build) Linting: - Strict .golangci.yml: only wsl disabled (deprecated in v2) - Re-enable exhaustruct, depguard, godot, wrapcheck, varnamelen - Fix linters-settings -> linters.settings for v2 config format - Fix ALL lint findings in actual code (no linter config weakening) - Wrap all external package errors (wrapcheck) - Fill struct fields or add targeted nolint:exhaustruct where appropriate - Rename short variables (ts->timestamp, n->bufIndex, etc.) - Add depguard deny policy for io/ioutil and math/rand - Exclude G704 (SSRF) in gosec config (CLI client takes user-configured URLs) Tests: - Add security tests (TestNonMemberCannotSend, TestHistoryNonMember) - Split TestInsertAndPollMessages for reduced complexity - Fix parallel test safety (viper global state prevents parallelism) - Use t.Context() instead of context.Background() in tests Docker build verified passing locally.
1290 lines
23 KiB
Go
1290 lines
23 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi"
|
|
)
|
|
|
|
var validNickRe = regexp.MustCompile(
|
|
`^[a-zA-Z_][a-zA-Z0-9_\-\[\]\\^{}|` + "`" + `]{0,31}$`,
|
|
)
|
|
|
|
var validChannelRe = regexp.MustCompile(
|
|
`^#[a-zA-Z0-9_\-]{1,63}$`,
|
|
)
|
|
|
|
const (
|
|
maxLongPollTimeout = 30
|
|
pollMessageLimit = 100
|
|
defaultMaxBodySize = 4096
|
|
defaultHistLimit = 50
|
|
maxHistLimit = 500
|
|
cmdPrivmsg = "PRIVMSG"
|
|
)
|
|
|
|
func (hdlr *Handlers) maxBodySize() int64 {
|
|
if hdlr.params.Config.MaxMessageSize > 0 {
|
|
return int64(hdlr.params.Config.MaxMessageSize)
|
|
}
|
|
|
|
return defaultMaxBodySize
|
|
}
|
|
|
|
// authUser extracts the user from the Authorization header.
|
|
func (hdlr *Handlers) authUser(
|
|
request *http.Request,
|
|
) (int64, string, error) {
|
|
auth := request.Header.Get("Authorization")
|
|
if !strings.HasPrefix(auth, "Bearer ") {
|
|
return 0, "", errUnauthorized
|
|
}
|
|
|
|
token := strings.TrimPrefix(auth, "Bearer ")
|
|
if token == "" {
|
|
return 0, "", errUnauthorized
|
|
}
|
|
|
|
uid, nick, err := hdlr.params.Database.GetUserByToken(
|
|
request.Context(), token,
|
|
)
|
|
if err != nil {
|
|
return 0, "", fmt.Errorf("auth: %w", err)
|
|
}
|
|
|
|
return uid, nick, nil
|
|
}
|
|
|
|
func (hdlr *Handlers) requireAuth(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
) (int64, string, bool) {
|
|
uid, nick, err := hdlr.authUser(request)
|
|
if err != nil {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"unauthorized",
|
|
http.StatusUnauthorized,
|
|
)
|
|
|
|
return 0, "", false
|
|
}
|
|
|
|
return uid, nick, true
|
|
}
|
|
|
|
// fanOut stores a message and enqueues it to all specified
|
|
// user IDs, then notifies them.
|
|
func (hdlr *Handlers) fanOut(
|
|
request *http.Request,
|
|
command, from, target string,
|
|
body json.RawMessage,
|
|
userIDs []int64,
|
|
) (string, error) {
|
|
dbID, msgUUID, err := hdlr.params.Database.InsertMessage(
|
|
request.Context(), command, from, target, body, nil,
|
|
)
|
|
if err != nil {
|
|
return "", fmt.Errorf("insert message: %w", err)
|
|
}
|
|
|
|
for _, uid := range userIDs {
|
|
enqErr := hdlr.params.Database.EnqueueMessage(
|
|
request.Context(), uid, dbID,
|
|
)
|
|
if enqErr != nil {
|
|
hdlr.log.Error("enqueue failed",
|
|
"error", enqErr, "user_id", uid)
|
|
}
|
|
|
|
hdlr.broker.Notify(uid)
|
|
}
|
|
|
|
return msgUUID, nil
|
|
}
|
|
|
|
// fanOutSilent calls fanOut and discards the UUID.
|
|
func (hdlr *Handlers) fanOutSilent(
|
|
request *http.Request,
|
|
command, from, target string,
|
|
body json.RawMessage,
|
|
userIDs []int64,
|
|
) error {
|
|
_, err := hdlr.fanOut(
|
|
request, command, from, target, body, userIDs,
|
|
)
|
|
|
|
return err
|
|
}
|
|
|
|
// HandleCreateSession creates a new user session.
|
|
func (hdlr *Handlers) HandleCreateSession() http.HandlerFunc {
|
|
type createRequest struct {
|
|
Nick string `json:"nick"`
|
|
}
|
|
|
|
type createResponse struct {
|
|
ID int64 `json:"id"`
|
|
Nick string `json:"nick"`
|
|
Token string `json:"token"`
|
|
}
|
|
|
|
return func(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
) {
|
|
request.Body = http.MaxBytesReader(
|
|
writer, request.Body, hdlr.maxBodySize(),
|
|
)
|
|
|
|
var payload createRequest
|
|
|
|
err := json.NewDecoder(request.Body).Decode(&payload)
|
|
if err != nil {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"invalid request body",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
payload.Nick = strings.TrimSpace(payload.Nick)
|
|
|
|
if !validNickRe.MatchString(payload.Nick) {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"invalid nick format",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
userID, token, err := hdlr.params.Database.CreateUser(
|
|
request.Context(), payload.Nick,
|
|
)
|
|
if err != nil {
|
|
if strings.Contains(err.Error(), "UNIQUE") {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"nick already taken",
|
|
http.StatusConflict,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.log.Error(
|
|
"create user failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.respondJSON(
|
|
writer, request,
|
|
&createResponse{
|
|
ID: userID,
|
|
Nick: payload.Nick,
|
|
Token: token,
|
|
},
|
|
http.StatusCreated,
|
|
)
|
|
}
|
|
}
|
|
|
|
// HandleState returns the current user's info and channels.
|
|
func (hdlr *Handlers) HandleState() http.HandlerFunc {
|
|
return func(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
) {
|
|
uid, nick, ok := hdlr.requireAuth(writer, request)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
channels, err := hdlr.params.Database.ListChannels(
|
|
request.Context(), uid,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"list channels failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.respondJSON(writer, request, map[string]any{
|
|
"id": uid,
|
|
"nick": nick,
|
|
"channels": channels,
|
|
}, http.StatusOK)
|
|
}
|
|
}
|
|
|
|
// HandleListAllChannels returns all channels on the server.
|
|
func (hdlr *Handlers) HandleListAllChannels() http.HandlerFunc {
|
|
return func(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
) {
|
|
_, _, ok := hdlr.requireAuth(writer, request)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
channels, err := hdlr.params.Database.ListAllChannels(
|
|
request.Context(),
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"list all channels failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.respondJSON(
|
|
writer, request, channels, http.StatusOK,
|
|
)
|
|
}
|
|
}
|
|
|
|
// HandleChannelMembers returns members of a channel.
|
|
func (hdlr *Handlers) HandleChannelMembers() http.HandlerFunc {
|
|
return func(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
) {
|
|
_, _, ok := hdlr.requireAuth(writer, request)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
name := "#" + chi.URLParam(request, "channel")
|
|
|
|
chID, err := hdlr.params.Database.GetChannelByName(
|
|
request.Context(), name,
|
|
)
|
|
if err != nil {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"channel not found",
|
|
http.StatusNotFound,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
members, err := hdlr.params.Database.ChannelMembers(
|
|
request.Context(), chID,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"channel members failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.respondJSON(
|
|
writer, request, members, http.StatusOK,
|
|
)
|
|
}
|
|
}
|
|
|
|
// HandleGetMessages returns messages via long-polling.
|
|
func (hdlr *Handlers) HandleGetMessages() http.HandlerFunc {
|
|
return func(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
) {
|
|
uid, _, ok := hdlr.requireAuth(writer, request)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
afterID, _ := strconv.ParseInt(
|
|
request.URL.Query().Get("after"), 10, 64,
|
|
)
|
|
|
|
timeout, _ := strconv.Atoi(
|
|
request.URL.Query().Get("timeout"),
|
|
)
|
|
if timeout < 0 {
|
|
timeout = 0
|
|
}
|
|
|
|
if timeout > maxLongPollTimeout {
|
|
timeout = maxLongPollTimeout
|
|
}
|
|
|
|
msgs, lastQID, err := hdlr.params.Database.PollMessages(
|
|
request.Context(), uid,
|
|
afterID, pollMessageLimit,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"poll messages failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
if len(msgs) > 0 || timeout == 0 {
|
|
hdlr.respondJSON(writer, request, map[string]any{
|
|
"messages": msgs,
|
|
"last_id": lastQID,
|
|
}, http.StatusOK)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.longPoll(writer, request, uid, afterID, timeout)
|
|
}
|
|
}
|
|
|
|
func (hdlr *Handlers) longPoll(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
uid, afterID int64,
|
|
timeout int,
|
|
) {
|
|
waitCh := hdlr.broker.Wait(uid)
|
|
|
|
timer := time.NewTimer(
|
|
time.Duration(timeout) * time.Second,
|
|
)
|
|
|
|
defer timer.Stop()
|
|
|
|
select {
|
|
case <-waitCh:
|
|
case <-timer.C:
|
|
case <-request.Context().Done():
|
|
hdlr.broker.Remove(uid, waitCh)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.broker.Remove(uid, waitCh)
|
|
|
|
msgs, lastQID, err := hdlr.params.Database.PollMessages(
|
|
request.Context(), uid,
|
|
afterID, pollMessageLimit,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"poll messages failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.respondJSON(writer, request, map[string]any{
|
|
"messages": msgs,
|
|
"last_id": lastQID,
|
|
}, http.StatusOK)
|
|
}
|
|
|
|
// HandleSendCommand handles all C2S commands.
|
|
func (hdlr *Handlers) HandleSendCommand() http.HandlerFunc {
|
|
type commandRequest struct {
|
|
Command string `json:"command"`
|
|
To string `json:"to"`
|
|
Body json.RawMessage `json:"body,omitempty"`
|
|
Meta json.RawMessage `json:"meta,omitempty"`
|
|
}
|
|
|
|
return func(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
) {
|
|
request.Body = http.MaxBytesReader(
|
|
writer, request.Body, hdlr.maxBodySize(),
|
|
)
|
|
|
|
uid, nick, ok := hdlr.requireAuth(writer, request)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
var payload commandRequest
|
|
|
|
err := json.NewDecoder(request.Body).Decode(&payload)
|
|
if err != nil {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"invalid request body",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
payload.Command = strings.ToUpper(
|
|
strings.TrimSpace(payload.Command),
|
|
)
|
|
payload.To = strings.TrimSpace(payload.To)
|
|
|
|
if payload.Command == "" {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"command required",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
bodyLines := func() []string {
|
|
if payload.Body == nil {
|
|
return nil
|
|
}
|
|
|
|
var lines []string
|
|
|
|
decErr := json.Unmarshal(payload.Body, &lines)
|
|
if decErr != nil {
|
|
return nil
|
|
}
|
|
|
|
return lines
|
|
}
|
|
|
|
hdlr.dispatchCommand(
|
|
writer, request, uid, nick,
|
|
payload.Command, payload.To,
|
|
payload.Body, bodyLines,
|
|
)
|
|
}
|
|
}
|
|
|
|
func (hdlr *Handlers) dispatchCommand(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
uid int64,
|
|
nick, command, target string,
|
|
body json.RawMessage,
|
|
bodyLines func() []string,
|
|
) {
|
|
switch command {
|
|
case cmdPrivmsg, "NOTICE":
|
|
hdlr.handlePrivmsg(
|
|
writer, request, uid, nick,
|
|
command, target, body, bodyLines,
|
|
)
|
|
case "JOIN":
|
|
hdlr.handleJoin(
|
|
writer, request, uid, nick, target,
|
|
)
|
|
case "PART":
|
|
hdlr.handlePart(
|
|
writer, request, uid, nick, target, body,
|
|
)
|
|
case "NICK":
|
|
hdlr.handleNick(
|
|
writer, request, uid, nick, bodyLines,
|
|
)
|
|
case "TOPIC":
|
|
hdlr.handleTopic(
|
|
writer, request, nick, target, body, bodyLines,
|
|
)
|
|
case "QUIT":
|
|
hdlr.handleQuit(
|
|
writer, request, uid, nick, body,
|
|
)
|
|
case "PING":
|
|
hdlr.respondJSON(writer, request,
|
|
map[string]string{
|
|
"command": "PONG",
|
|
"from": hdlr.params.Config.ServerName,
|
|
},
|
|
http.StatusOK)
|
|
default:
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"unknown command: "+command,
|
|
http.StatusBadRequest,
|
|
)
|
|
}
|
|
}
|
|
|
|
func (hdlr *Handlers) handlePrivmsg(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
uid int64,
|
|
nick, command, target string,
|
|
body json.RawMessage,
|
|
bodyLines func() []string,
|
|
) {
|
|
if target == "" {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"to field required",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
lines := bodyLines()
|
|
if len(lines) == 0 {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"body required",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
if strings.HasPrefix(target, "#") {
|
|
hdlr.handleChannelMsg(
|
|
writer, request, uid, nick,
|
|
command, target, body,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.handleDirectMsg(
|
|
writer, request, uid, nick,
|
|
command, target, body,
|
|
)
|
|
}
|
|
|
|
func (hdlr *Handlers) handleChannelMsg(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
uid int64,
|
|
nick, command, target string,
|
|
body json.RawMessage,
|
|
) {
|
|
chID, err := hdlr.params.Database.GetChannelByName(
|
|
request.Context(), target,
|
|
)
|
|
if err != nil {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"channel not found",
|
|
http.StatusNotFound,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
isMember, err := hdlr.params.Database.IsChannelMember(
|
|
request.Context(), chID, uid,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"check membership failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
if !isMember {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"not a member of this channel",
|
|
http.StatusForbidden,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
memberIDs, err := hdlr.params.Database.GetChannelMemberIDs(
|
|
request.Context(), chID,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"get channel members failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
msgUUID, err := hdlr.fanOut(
|
|
request, command, nick, target, body, memberIDs,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error("send message failed", "error", err)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.respondJSON(writer, request,
|
|
map[string]string{"id": msgUUID, "status": "sent"},
|
|
http.StatusCreated)
|
|
}
|
|
|
|
func (hdlr *Handlers) handleDirectMsg(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
uid int64,
|
|
nick, command, target string,
|
|
body json.RawMessage,
|
|
) {
|
|
targetUID, err := hdlr.params.Database.GetUserByNick(
|
|
request.Context(), target,
|
|
)
|
|
if err != nil {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"user not found",
|
|
http.StatusNotFound,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
recipients := []int64{targetUID}
|
|
if targetUID != uid {
|
|
recipients = append(recipients, uid)
|
|
}
|
|
|
|
msgUUID, err := hdlr.fanOut(
|
|
request, command, nick, target, body, recipients,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error("send dm failed", "error", err)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.respondJSON(writer, request,
|
|
map[string]string{"id": msgUUID, "status": "sent"},
|
|
http.StatusCreated)
|
|
}
|
|
|
|
func (hdlr *Handlers) handleJoin(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
uid int64,
|
|
nick, target string,
|
|
) {
|
|
if target == "" {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"to field required",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
channel := target
|
|
if !strings.HasPrefix(channel, "#") {
|
|
channel = "#" + channel
|
|
}
|
|
|
|
if !validChannelRe.MatchString(channel) {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"invalid channel name",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
chID, err := hdlr.params.Database.GetOrCreateChannel(
|
|
request.Context(), channel,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"get/create channel failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
err = hdlr.params.Database.JoinChannel(
|
|
request.Context(), chID, uid,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"join channel failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
memberIDs, _ := hdlr.params.Database.GetChannelMemberIDs(
|
|
request.Context(), chID,
|
|
)
|
|
|
|
_ = hdlr.fanOutSilent(
|
|
request, "JOIN", nick, channel, nil, memberIDs,
|
|
)
|
|
|
|
hdlr.respondJSON(writer, request,
|
|
map[string]string{
|
|
"status": "joined",
|
|
"channel": channel,
|
|
},
|
|
http.StatusOK)
|
|
}
|
|
|
|
func (hdlr *Handlers) handlePart(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
uid int64,
|
|
nick, target string,
|
|
body json.RawMessage,
|
|
) {
|
|
if target == "" {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"to field required",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
channel := target
|
|
if !strings.HasPrefix(channel, "#") {
|
|
channel = "#" + channel
|
|
}
|
|
|
|
chID, err := hdlr.params.Database.GetChannelByName(
|
|
request.Context(), channel,
|
|
)
|
|
if err != nil {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"channel not found",
|
|
http.StatusNotFound,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
memberIDs, _ := hdlr.params.Database.GetChannelMemberIDs(
|
|
request.Context(), chID,
|
|
)
|
|
|
|
_ = hdlr.fanOutSilent(
|
|
request, "PART", nick, channel, body, memberIDs,
|
|
)
|
|
|
|
err = hdlr.params.Database.PartChannel(
|
|
request.Context(), chID, uid,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"part channel failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
_ = hdlr.params.Database.DeleteChannelIfEmpty(
|
|
request.Context(), chID,
|
|
)
|
|
|
|
hdlr.respondJSON(writer, request,
|
|
map[string]string{
|
|
"status": "parted",
|
|
"channel": channel,
|
|
},
|
|
http.StatusOK)
|
|
}
|
|
|
|
func (hdlr *Handlers) handleNick(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
uid int64,
|
|
nick string,
|
|
bodyLines func() []string,
|
|
) {
|
|
lines := bodyLines()
|
|
if len(lines) == 0 {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"body required (new nick)",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
newNick := strings.TrimSpace(lines[0])
|
|
|
|
if !validNickRe.MatchString(newNick) {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"invalid nick",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
if newNick == nick {
|
|
hdlr.respondJSON(writer, request,
|
|
map[string]string{
|
|
"status": "ok", "nick": newNick,
|
|
},
|
|
http.StatusOK)
|
|
|
|
return
|
|
}
|
|
|
|
err := hdlr.params.Database.ChangeNick(
|
|
request.Context(), uid, newNick,
|
|
)
|
|
if err != nil {
|
|
if strings.Contains(err.Error(), "UNIQUE") {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"nick already in use",
|
|
http.StatusConflict,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.log.Error(
|
|
"change nick failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.broadcastNick(request, uid, nick, newNick)
|
|
|
|
hdlr.respondJSON(writer, request,
|
|
map[string]string{
|
|
"status": "ok", "nick": newNick,
|
|
},
|
|
http.StatusOK)
|
|
}
|
|
|
|
func (hdlr *Handlers) broadcastNick(
|
|
request *http.Request,
|
|
uid int64,
|
|
oldNick, newNick string,
|
|
) {
|
|
channels, _ := hdlr.params.Database.
|
|
GetAllChannelMembershipsForUser(
|
|
request.Context(), uid,
|
|
)
|
|
|
|
notified := map[int64]bool{uid: true}
|
|
|
|
nickBody, err := json.Marshal([]string{newNick})
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"marshal nick body", "error", err,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
dbID, _, _ := hdlr.params.Database.InsertMessage(
|
|
request.Context(), "NICK", oldNick, "",
|
|
json.RawMessage(nickBody), nil,
|
|
)
|
|
|
|
_ = hdlr.params.Database.EnqueueMessage(
|
|
request.Context(), uid, dbID,
|
|
)
|
|
|
|
hdlr.broker.Notify(uid)
|
|
|
|
for _, chanInfo := range channels {
|
|
memberIDs, _ := hdlr.params.Database.
|
|
GetChannelMemberIDs(
|
|
request.Context(), chanInfo.ID,
|
|
)
|
|
|
|
for _, mid := range memberIDs {
|
|
if !notified[mid] {
|
|
notified[mid] = true
|
|
|
|
_ = hdlr.params.Database.EnqueueMessage(
|
|
request.Context(), mid, dbID,
|
|
)
|
|
|
|
hdlr.broker.Notify(mid)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (hdlr *Handlers) handleTopic(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
nick, target string,
|
|
body json.RawMessage,
|
|
bodyLines func() []string,
|
|
) {
|
|
if target == "" {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"to field required",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
lines := bodyLines()
|
|
if len(lines) == 0 {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"body required (topic text)",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
topic := strings.Join(lines, " ")
|
|
|
|
channel := target
|
|
if !strings.HasPrefix(channel, "#") {
|
|
channel = "#" + channel
|
|
}
|
|
|
|
err := hdlr.params.Database.SetTopic(
|
|
request.Context(), channel, topic,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"set topic failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
chID, err := hdlr.params.Database.GetChannelByName(
|
|
request.Context(), channel,
|
|
)
|
|
if err != nil {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"channel not found",
|
|
http.StatusNotFound,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
memberIDs, _ := hdlr.params.Database.GetChannelMemberIDs(
|
|
request.Context(), chID,
|
|
)
|
|
|
|
_ = hdlr.fanOutSilent(
|
|
request, "TOPIC", nick, channel, body, memberIDs,
|
|
)
|
|
|
|
hdlr.respondJSON(writer, request,
|
|
map[string]string{
|
|
"status": "ok", "topic": topic,
|
|
},
|
|
http.StatusOK)
|
|
}
|
|
|
|
func (hdlr *Handlers) handleQuit(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
uid int64,
|
|
nick string,
|
|
body json.RawMessage,
|
|
) {
|
|
channels, _ := hdlr.params.Database.
|
|
GetAllChannelMembershipsForUser(
|
|
request.Context(), uid,
|
|
)
|
|
|
|
notified := map[int64]bool{}
|
|
|
|
var dbID int64
|
|
|
|
if len(channels) > 0 {
|
|
dbID, _, _ = hdlr.params.Database.InsertMessage(
|
|
request.Context(), "QUIT", nick, "", body, nil,
|
|
)
|
|
}
|
|
|
|
for _, chanInfo := range channels {
|
|
memberIDs, _ := hdlr.params.Database.
|
|
GetChannelMemberIDs(
|
|
request.Context(), chanInfo.ID,
|
|
)
|
|
|
|
for _, mid := range memberIDs {
|
|
if mid != uid && !notified[mid] {
|
|
notified[mid] = true
|
|
|
|
_ = hdlr.params.Database.EnqueueMessage(
|
|
request.Context(), mid, dbID,
|
|
)
|
|
|
|
hdlr.broker.Notify(mid)
|
|
}
|
|
}
|
|
|
|
_ = hdlr.params.Database.PartChannel(
|
|
request.Context(), chanInfo.ID, uid,
|
|
)
|
|
|
|
_ = hdlr.params.Database.DeleteChannelIfEmpty(
|
|
request.Context(), chanInfo.ID,
|
|
)
|
|
}
|
|
|
|
_ = hdlr.params.Database.DeleteUser(
|
|
request.Context(), uid,
|
|
)
|
|
|
|
hdlr.respondJSON(writer, request,
|
|
map[string]string{"status": "quit"},
|
|
http.StatusOK)
|
|
}
|
|
|
|
// HandleGetHistory returns message history for a target.
|
|
func (hdlr *Handlers) HandleGetHistory() http.HandlerFunc {
|
|
return func(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
) {
|
|
uid, nick, ok := hdlr.requireAuth(writer, request)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
target := request.URL.Query().Get("target")
|
|
if target == "" {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"target required",
|
|
http.StatusBadRequest,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
if !hdlr.canAccessHistory(
|
|
writer, request, uid, nick, target,
|
|
) {
|
|
return
|
|
}
|
|
|
|
beforeID, _ := strconv.ParseInt(
|
|
request.URL.Query().Get("before"), 10, 64,
|
|
)
|
|
|
|
limit, _ := strconv.Atoi(
|
|
request.URL.Query().Get("limit"),
|
|
)
|
|
if limit <= 0 || limit > maxHistLimit {
|
|
limit = defaultHistLimit
|
|
}
|
|
|
|
msgs, err := hdlr.params.Database.GetHistory(
|
|
request.Context(), target, beforeID, limit,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"get history failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return
|
|
}
|
|
|
|
hdlr.respondJSON(
|
|
writer, request, msgs, http.StatusOK,
|
|
)
|
|
}
|
|
}
|
|
|
|
// canAccessHistory verifies the user can read history
|
|
// for the given target (channel or DM participant).
|
|
func (hdlr *Handlers) canAccessHistory(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
uid int64,
|
|
nick, target string,
|
|
) bool {
|
|
if strings.HasPrefix(target, "#") {
|
|
return hdlr.canAccessChannelHistory(
|
|
writer, request, uid, target,
|
|
)
|
|
}
|
|
|
|
// DM history: only allow if the target is the
|
|
// requester's own nick (messages sent to them).
|
|
if target != nick {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"forbidden",
|
|
http.StatusForbidden,
|
|
)
|
|
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
func (hdlr *Handlers) canAccessChannelHistory(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
uid int64,
|
|
target string,
|
|
) bool {
|
|
chID, err := hdlr.params.Database.GetChannelByName(
|
|
request.Context(), target,
|
|
)
|
|
if err != nil {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"channel not found",
|
|
http.StatusNotFound,
|
|
)
|
|
|
|
return false
|
|
}
|
|
|
|
isMember, err := hdlr.params.Database.IsChannelMember(
|
|
request.Context(), chID, uid,
|
|
)
|
|
if err != nil {
|
|
hdlr.log.Error(
|
|
"check membership failed", "error", err,
|
|
)
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"internal error",
|
|
http.StatusInternalServerError,
|
|
)
|
|
|
|
return false
|
|
}
|
|
|
|
if !isMember {
|
|
hdlr.respondError(
|
|
writer, request,
|
|
"not a member of this channel",
|
|
http.StatusForbidden,
|
|
)
|
|
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
// HandleServerInfo returns server metadata.
|
|
func (hdlr *Handlers) HandleServerInfo() http.HandlerFunc {
|
|
type infoResponse struct {
|
|
Name string `json:"name"`
|
|
MOTD string `json:"motd"`
|
|
}
|
|
|
|
return func(
|
|
writer http.ResponseWriter,
|
|
request *http.Request,
|
|
) {
|
|
hdlr.respondJSON(writer, request, &infoResponse{
|
|
Name: hdlr.params.Config.ServerName,
|
|
MOTD: hdlr.params.Config.MOTD,
|
|
}, http.StatusOK)
|
|
}
|
|
}
|