- Resolve duplicate method declarations (CreateUser, GetUserByToken,
GetUserByNick) between db.go and queries.go by renaming queries.go
methods to CreateSimpleUser, LookupUserByToken, LookupUserByNick
- Fix 377 lint issues across all categories:
- nlreturn (107): Add blank lines before returns
- wsl_v5 (156): Add required whitespace
- noinlineerr (25): Use plain assignments instead of inline error handling
- errcheck (15): Check all error return values
- mnd (10): Extract magic numbers to named constants
- err113 (7): Use wrapped static errors instead of dynamic errors
- gosec (7): Fix SSRF, SQL injection warnings; add nolint for false positives
- modernize (7): Replace interface{} with any
- cyclop (2): Reduce cyclomatic complexity via command map dispatch
- gocognit (1): Break down complex handler into sub-handlers
- funlen (3): Extract long functions into smaller helpers
- funcorder (4): Reorder methods (exported before unexported)
- forcetypeassert (2): Add safe type assertions with ok checks
- ireturn (2): Replace interface-returning methods with concrete lookups
- noctx (3): Use NewRequestWithContext and ExecContext
- tagliatelle (5): Fix JSON tag casing to camelCase
- revive (4): Rename package from 'api' to 'chatapi'
- rowserrcheck (8): Add rows.Err() checks after iteration
- lll (2): Shorten long lines
- perfsprint (5): Use strconv and string concatenation
- nestif (2): Extract nested conditionals into helper methods
- wastedassign (1): Remove wasted assignments
- gosmopolitan (1): Add nolint for intentional Local() time display
- usestdlibvars (1): Use http.MethodGet
- godoclint (2): Remove duplicate package comments
- Fix broken migration 003_users.sql that conflicted with 002_schema.sql
(different column types causing test failures)
- All tests pass, make check reports 0 issues
564 lines
15 KiB
Go
564 lines
15 KiB
Go
package handlers
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"git.eeqj.de/sneak/chat/internal/db"
|
|
"github.com/go-chi/chi"
|
|
)
|
|
|
|
const maxNickLen = 32
|
|
|
|
// authUser extracts the user from the Authorization header (Bearer token).
|
|
func (s *Handlers) authUser(r *http.Request) (int64, string, error) {
|
|
auth := r.Header.Get("Authorization")
|
|
if !strings.HasPrefix(auth, "Bearer ") {
|
|
return 0, "", sql.ErrNoRows
|
|
}
|
|
|
|
token := strings.TrimPrefix(auth, "Bearer ")
|
|
|
|
return s.params.Database.LookupUserByToken(r.Context(), token)
|
|
}
|
|
|
|
func (s *Handlers) requireAuth(w http.ResponseWriter, r *http.Request) (int64, string, bool) {
|
|
uid, nick, err := s.authUser(r)
|
|
if err != nil {
|
|
s.respondJSON(w, r, map[string]string{"error": "unauthorized"}, http.StatusUnauthorized)
|
|
|
|
return 0, "", false
|
|
}
|
|
|
|
return uid, nick, true
|
|
}
|
|
|
|
// HandleCreateSession creates a new user session and returns the auth token.
|
|
func (s *Handlers) HandleCreateSession() http.HandlerFunc {
|
|
type request struct {
|
|
Nick string `json:"nick"`
|
|
}
|
|
|
|
type response struct {
|
|
ID int64 `json:"id"`
|
|
Nick string `json:"nick"`
|
|
Token string `json:"token"`
|
|
}
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
var req request
|
|
|
|
err := json.NewDecoder(r.Body).Decode(&req)
|
|
if err != nil {
|
|
s.respondJSON(w, r, map[string]string{"error": "invalid request"}, http.StatusBadRequest)
|
|
|
|
return
|
|
}
|
|
|
|
req.Nick = strings.TrimSpace(req.Nick)
|
|
|
|
if req.Nick == "" || len(req.Nick) > maxNickLen {
|
|
s.respondJSON(w, r, map[string]string{"error": "nick must be 1-32 characters"}, http.StatusBadRequest)
|
|
|
|
return
|
|
}
|
|
|
|
id, token, err := s.params.Database.CreateSimpleUser(r.Context(), req.Nick)
|
|
if err != nil {
|
|
if strings.Contains(err.Error(), "UNIQUE") {
|
|
s.respondJSON(w, r, map[string]string{"error": "nick already taken"}, http.StatusConflict)
|
|
|
|
return
|
|
}
|
|
|
|
s.log.Error("create user failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
s.respondJSON(w, r, &response{ID: id, Nick: req.Nick, Token: token}, http.StatusCreated)
|
|
}
|
|
}
|
|
|
|
// HandleState returns the current user's info and joined channels.
|
|
func (s *Handlers) HandleState() http.HandlerFunc {
|
|
type response struct {
|
|
ID int64 `json:"id"`
|
|
Nick string `json:"nick"`
|
|
Channels []db.ChannelInfo `json:"channels"`
|
|
}
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
uid, nick, ok := s.requireAuth(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
channels, err := s.params.Database.ListChannels(r.Context(), uid)
|
|
if err != nil {
|
|
s.log.Error("list channels failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
s.respondJSON(w, r, &response{ID: uid, Nick: nick, Channels: channels}, http.StatusOK)
|
|
}
|
|
}
|
|
|
|
// HandleListAllChannels returns all channels on the server.
|
|
func (s *Handlers) HandleListAllChannels() http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
_, _, ok := s.requireAuth(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
channels, err := s.params.Database.ListAllChannels(r.Context())
|
|
if err != nil {
|
|
s.log.Error("list all channels failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
s.respondJSON(w, r, channels, http.StatusOK)
|
|
}
|
|
}
|
|
|
|
// HandleChannelMembers returns members of a channel.
|
|
func (s *Handlers) HandleChannelMembers() http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
_, _, ok := s.requireAuth(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
name := "#" + chi.URLParam(r, "channel")
|
|
|
|
chID, err := s.lookupChannelID(r, name)
|
|
if err != nil {
|
|
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
|
|
|
|
return
|
|
}
|
|
|
|
members, err := s.params.Database.ChannelMembers(r.Context(), chID)
|
|
if err != nil {
|
|
s.log.Error("channel members failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
s.respondJSON(w, r, members, http.StatusOK)
|
|
}
|
|
}
|
|
|
|
// HandleGetMessages returns all new messages (channel + DM) for the user via long-polling.
|
|
// This is the single unified message stream — replaces separate channel/DM/poll endpoints.
|
|
func (s *Handlers) HandleGetMessages() http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
uid, _, ok := s.requireAuth(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
afterID, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
|
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
|
|
|
msgs, err := s.params.Database.PollMessages(r.Context(), uid, afterID, limit)
|
|
if err != nil {
|
|
s.log.Error("get messages failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
s.respondJSON(w, r, msgs, http.StatusOK)
|
|
}
|
|
}
|
|
|
|
// HandleSendCommand handles all C2S commands via POST /messages.
|
|
// The "command" field dispatches to the appropriate logic.
|
|
func (s *Handlers) HandleSendCommand() http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
uid, nick, ok := s.requireAuth(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
cmd, err := s.decodeSendCommand(r)
|
|
if err != nil {
|
|
s.respondJSON(w, r, map[string]string{"error": "invalid request"}, http.StatusBadRequest)
|
|
|
|
return
|
|
}
|
|
|
|
switch cmd.Command {
|
|
case "PRIVMSG", "NOTICE":
|
|
s.handlePrivmsgCommand(w, r, uid, cmd)
|
|
case "JOIN":
|
|
s.handleJoinCommand(w, r, uid, cmd)
|
|
case "PART":
|
|
s.handlePartCommand(w, r, uid, cmd)
|
|
case "NICK":
|
|
s.handleNickCommand(w, r, uid, cmd)
|
|
case "TOPIC":
|
|
s.handleTopicCommand(w, r, cmd)
|
|
case "PING":
|
|
s.respondJSON(w, r, map[string]string{"command": "PONG", "from": s.params.Config.ServerName}, http.StatusOK)
|
|
default:
|
|
_ = nick // suppress unused warning
|
|
|
|
s.respondJSON(w, r, map[string]string{"error": "unknown command: " + cmd.Command}, http.StatusBadRequest)
|
|
}
|
|
}
|
|
}
|
|
|
|
type sendCommand struct {
|
|
Command string `json:"command"`
|
|
To string `json:"to"`
|
|
Params []string `json:"params,omitempty"`
|
|
Body any `json:"body,omitempty"`
|
|
}
|
|
|
|
func (s *Handlers) decodeSendCommand(r *http.Request) (*sendCommand, error) {
|
|
var cmd sendCommand
|
|
|
|
err := json.NewDecoder(r.Body).Decode(&cmd)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
cmd.Command = strings.ToUpper(strings.TrimSpace(cmd.Command))
|
|
cmd.To = strings.TrimSpace(cmd.To)
|
|
|
|
return &cmd, nil
|
|
}
|
|
|
|
func bodyLines(body any) []string {
|
|
switch v := body.(type) {
|
|
case []any:
|
|
lines := make([]string, 0, len(v))
|
|
|
|
for _, item := range v {
|
|
if str, ok := item.(string); ok {
|
|
lines = append(lines, str)
|
|
}
|
|
}
|
|
|
|
return lines
|
|
case []string:
|
|
return v
|
|
default:
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func (s *Handlers) handlePrivmsgCommand(
|
|
w http.ResponseWriter, r *http.Request, uid int64, cmd *sendCommand,
|
|
) {
|
|
if cmd.To == "" {
|
|
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
|
|
|
|
return
|
|
}
|
|
|
|
lines := bodyLines(cmd.Body)
|
|
if len(lines) == 0 {
|
|
s.respondJSON(w, r, map[string]string{"error": "body required"}, http.StatusBadRequest)
|
|
|
|
return
|
|
}
|
|
|
|
content := strings.Join(lines, "\n")
|
|
|
|
if strings.HasPrefix(cmd.To, "#") {
|
|
s.sendChannelMessage(w, r, uid, cmd.To, content)
|
|
} else {
|
|
s.sendDirectMessage(w, r, uid, cmd.To, content)
|
|
}
|
|
}
|
|
|
|
func (s *Handlers) sendChannelMessage(
|
|
w http.ResponseWriter, r *http.Request, uid int64, channel, content string,
|
|
) {
|
|
chID, err := s.lookupChannelID(r, channel)
|
|
if err != nil {
|
|
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
|
|
|
|
return
|
|
}
|
|
|
|
msgID, err := s.params.Database.SendMessage(r.Context(), chID, uid, content)
|
|
if err != nil {
|
|
s.log.Error("send message failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
s.respondJSON(w, r, map[string]any{"id": msgID, "status": "sent"}, http.StatusCreated)
|
|
}
|
|
|
|
func (s *Handlers) sendDirectMessage(
|
|
w http.ResponseWriter, r *http.Request, uid int64, toNick, content string,
|
|
) {
|
|
targetID, err := s.params.Database.LookupUserByNick(r.Context(), toNick)
|
|
if err != nil {
|
|
s.respondJSON(w, r, map[string]string{"error": "user not found"}, http.StatusNotFound)
|
|
|
|
return
|
|
}
|
|
|
|
msgID, err := s.params.Database.SendDM(r.Context(), uid, targetID, content)
|
|
if err != nil {
|
|
s.log.Error("send dm failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
s.respondJSON(w, r, map[string]any{"id": msgID, "status": "sent"}, http.StatusCreated)
|
|
}
|
|
|
|
func (s *Handlers) handleJoinCommand(
|
|
w http.ResponseWriter, r *http.Request, uid int64, cmd *sendCommand,
|
|
) {
|
|
if cmd.To == "" {
|
|
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
|
|
|
|
return
|
|
}
|
|
|
|
channel := cmd.To
|
|
if !strings.HasPrefix(channel, "#") {
|
|
channel = "#" + channel
|
|
}
|
|
|
|
chID, err := s.params.Database.GetOrCreateChannel(r.Context(), channel)
|
|
if err != nil {
|
|
s.log.Error("get/create channel failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
err = s.params.Database.JoinChannel(r.Context(), chID, uid)
|
|
if err != nil {
|
|
s.log.Error("join channel failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
s.respondJSON(w, r, map[string]string{"status": "joined", "channel": channel}, http.StatusOK)
|
|
}
|
|
|
|
func (s *Handlers) handlePartCommand(
|
|
w http.ResponseWriter, r *http.Request, uid int64, cmd *sendCommand,
|
|
) {
|
|
if cmd.To == "" {
|
|
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
|
|
|
|
return
|
|
}
|
|
|
|
channel := cmd.To
|
|
if !strings.HasPrefix(channel, "#") {
|
|
channel = "#" + channel
|
|
}
|
|
|
|
chID, err := s.lookupChannelID(r, channel)
|
|
if err != nil {
|
|
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
|
|
|
|
return
|
|
}
|
|
|
|
err = s.params.Database.PartChannel(r.Context(), chID, uid)
|
|
if err != nil {
|
|
s.log.Error("part channel failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
s.respondJSON(w, r, map[string]string{"status": "parted", "channel": channel}, http.StatusOK)
|
|
}
|
|
|
|
func (s *Handlers) handleNickCommand(
|
|
w http.ResponseWriter, r *http.Request, uid int64, cmd *sendCommand,
|
|
) {
|
|
lines := bodyLines(cmd.Body)
|
|
if len(lines) == 0 {
|
|
s.respondJSON(w, r, map[string]string{"error": "body required (new nick)"}, http.StatusBadRequest)
|
|
|
|
return
|
|
}
|
|
|
|
newNick := strings.TrimSpace(lines[0])
|
|
if newNick == "" || len(newNick) > maxNickLen {
|
|
s.respondJSON(w, r, map[string]string{"error": "nick must be 1-32 characters"}, http.StatusBadRequest)
|
|
|
|
return
|
|
}
|
|
|
|
err := s.params.Database.ChangeNick(r.Context(), uid, newNick)
|
|
if err != nil {
|
|
if strings.Contains(err.Error(), "UNIQUE") {
|
|
s.respondJSON(w, r, map[string]string{"error": "nick already in use"}, http.StatusConflict)
|
|
|
|
return
|
|
}
|
|
|
|
s.log.Error("change nick failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
s.respondJSON(w, r, map[string]string{"status": "ok", "nick": newNick}, http.StatusOK)
|
|
}
|
|
|
|
func (s *Handlers) handleTopicCommand(
|
|
w http.ResponseWriter, r *http.Request, cmd *sendCommand,
|
|
) {
|
|
if cmd.To == "" {
|
|
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
|
|
|
|
return
|
|
}
|
|
|
|
lines := bodyLines(cmd.Body)
|
|
if len(lines) == 0 {
|
|
s.respondJSON(w, r, map[string]string{"error": "body required (topic text)"}, http.StatusBadRequest)
|
|
|
|
return
|
|
}
|
|
|
|
topic := strings.Join(lines, " ")
|
|
|
|
channel := cmd.To
|
|
if !strings.HasPrefix(channel, "#") {
|
|
channel = "#" + channel
|
|
}
|
|
|
|
err := s.params.Database.SetTopic(r.Context(), channel, 0, topic)
|
|
if err != nil {
|
|
s.log.Error("set topic failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
s.respondJSON(w, r, map[string]string{"status": "ok", "topic": topic}, http.StatusOK)
|
|
}
|
|
|
|
// HandleGetHistory returns message history for a specific target (channel or DM).
|
|
func (s *Handlers) HandleGetHistory() http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
uid, _, ok := s.requireAuth(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
target := r.URL.Query().Get("target")
|
|
if target == "" {
|
|
s.respondJSON(w, r, map[string]string{"error": "target required"}, http.StatusBadRequest)
|
|
|
|
return
|
|
}
|
|
|
|
beforeID, _ := strconv.ParseInt(r.URL.Query().Get("before"), 10, 64)
|
|
|
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
|
if limit <= 0 {
|
|
limit = defaultHistoryLimit
|
|
}
|
|
|
|
if strings.HasPrefix(target, "#") {
|
|
s.handleChannelHistory(w, r, target, beforeID, limit)
|
|
} else {
|
|
s.handleDMHistory(w, r, uid, target, beforeID, limit)
|
|
}
|
|
}
|
|
}
|
|
|
|
const defaultHistoryLimit = 50
|
|
|
|
func (s *Handlers) handleChannelHistory(
|
|
w http.ResponseWriter, r *http.Request,
|
|
target string, beforeID int64, limit int,
|
|
) {
|
|
chID, err := s.lookupChannelID(r, target)
|
|
if err != nil {
|
|
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
|
|
|
|
return
|
|
}
|
|
|
|
msgs, err := s.params.Database.GetMessagesBefore(r.Context(), chID, beforeID, limit)
|
|
if err != nil {
|
|
s.log.Error("get history failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
s.respondJSON(w, r, msgs, http.StatusOK)
|
|
}
|
|
|
|
func (s *Handlers) handleDMHistory(
|
|
w http.ResponseWriter, r *http.Request,
|
|
uid int64, target string, beforeID int64, limit int,
|
|
) {
|
|
targetID, err := s.params.Database.LookupUserByNick(r.Context(), target)
|
|
if err != nil {
|
|
s.respondJSON(w, r, map[string]string{"error": "user not found"}, http.StatusNotFound)
|
|
|
|
return
|
|
}
|
|
|
|
msgs, err := s.params.Database.GetDMsBefore(r.Context(), uid, targetID, beforeID, limit)
|
|
if err != nil {
|
|
s.log.Error("get dm history failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
|
|
return
|
|
}
|
|
|
|
s.respondJSON(w, r, msgs, http.StatusOK)
|
|
}
|
|
|
|
// lookupChannelID queries the channel ID by name using a parameterized query.
|
|
func (s *Handlers) lookupChannelID(r *http.Request, name string) (int64, error) {
|
|
var chID int64
|
|
|
|
//nolint:gosec // query uses parameterized placeholder (?), not string interpolation
|
|
err := s.params.Database.GetDB().QueryRowContext(r.Context(),
|
|
"SELECT id FROM channels WHERE name = ?", name).Scan(&chID)
|
|
|
|
return chID, err
|
|
}
|
|
|
|
// HandleServerInfo returns server metadata (MOTD, name).
|
|
func (s *Handlers) HandleServerInfo() http.HandlerFunc {
|
|
type response struct {
|
|
Name string `json:"name"`
|
|
MOTD string `json:"motd"`
|
|
}
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
s.respondJSON(w, r, &response{
|
|
Name: s.params.Config.ServerName,
|
|
MOTD: s.params.Config.MOTD,
|
|
}, http.StatusOK)
|
|
}
|
|
}
|