package handlers import ( "crypto/rand" "database/sql" "encoding/hex" "encoding/json" "net/http" "strconv" "strings" "git.eeqj.de/sneak/chat/internal/db" "github.com/go-chi/chi" ) // authUser extracts the user from the Authorization header (Bearer token). func (s *Handlers) authUser(r *http.Request) (string, string, error) { auth := r.Header.Get("Authorization") if !strings.HasPrefix(auth, "Bearer ") { return "", "", sql.ErrNoRows } token := strings.TrimPrefix(auth, "Bearer ") u, err := s.params.Database.GetUserByToken(r.Context(), token) if err != nil { return "", "", err } return u.ID, u.Nick, nil } func (s *Handlers) requireAuth(w http.ResponseWriter, r *http.Request) (string, string, bool) { uid, nick, err := s.authUser(r) if err != nil { s.respondJSON(w, r, map[string]string{"error": "unauthorized"}, http.StatusUnauthorized) return "", "", false } return uid, nick, true } const idBytes = 16 func generateID() string { b := make([]byte, idBytes) _, _ = rand.Read(b) return hex.EncodeToString(b) } // 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 string `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) > 32 { s.respondJSON(w, r, map[string]string{"error": "nick must be 1-32 characters"}, http.StatusBadRequest) return } id := generateID() u, err := s.params.Database.CreateUser(r.Context(), id, 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 } tokenStr := generateID() _, err = s.params.Database.CreateAuthToken(r.Context(), tokenStr, u.ID) if err != nil { s.log.Error("create auth token failed", "error", err) s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) return } s.respondJSON(w, r, &response{ID: u.ID, Nick: req.Nick, Token: tokenStr}, http.StatusCreated) } } // HandleState returns the current user's info and joined channels. func (s *Handlers) HandleState() http.HandlerFunc { type response struct { ID string `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") var chID string err := s.params.Database.GetDB().QueryRowContext(r.Context(), "SELECT id FROM channels WHERE name = ?", name).Scan(&chID) 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 } afterTS := r.URL.Query().Get("after") limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) msgs, err := s.params.Database.PollMessages(r.Context(), uid, afterTS, 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 { type request struct { Command string `json:"command"` To string `json:"to"` Params []string `json:"params,omitempty"` Body any `json:"body,omitempty"` } return func(w http.ResponseWriter, r *http.Request) { uid, nick, ok := s.requireAuth(w, r) if !ok { return } 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.Command = strings.ToUpper(strings.TrimSpace(req.Command)) req.To = strings.TrimSpace(req.To) // Helper to extract body as string lines. bodyLines := func() []string { switch v := req.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 } } switch req.Command { case "PRIVMSG", "NOTICE": s.handlePrivmsg(w, r, uid, nick, req.To, bodyLines()) case "JOIN": s.handleJoin(w, r, uid, req.To) case "PART": s.handlePart(w, r, uid, req.To) case "NICK": s.handleNick(w, r, uid, bodyLines()) case "TOPIC": s.handleTopic(w, r, uid, req.To, bodyLines()) 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: " + req.Command}, http.StatusBadRequest) } } } func (s *Handlers) handlePrivmsg(w http.ResponseWriter, r *http.Request, uid, nick, to string, lines []string) { if to == "" { s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest) return } 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(to, "#") { // Channel message. var chID string err := s.params.Database.GetDB().QueryRowContext(r.Context(), "SELECT id FROM channels WHERE name = ?", to).Scan(&chID) 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, nick, 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) } else { // DM. targetUser, err := s.params.Database.GetUserByNick(r.Context(), to) 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, nick, targetUser.ID, 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) handleJoin(w http.ResponseWriter, r *http.Request, uid, to string) { if to == "" { s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest) return } channel := 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) handlePart(w http.ResponseWriter, r *http.Request, uid, to string) { if to == "" { s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest) return } channel := to if !strings.HasPrefix(channel, "#") { channel = "#" + channel } var chID string err := s.params.Database.GetDB().QueryRowContext(r.Context(), "SELECT id FROM channels WHERE name = ?", channel).Scan(&chID) 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) handleNick(w http.ResponseWriter, r *http.Request, uid string, lines []string) { 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) > 32 { 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) handleTopic(w http.ResponseWriter, r *http.Request, uid, to string, lines []string) { if to == "" { s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest) return } if len(lines) == 0 { s.respondJSON(w, r, map[string]string{"error": "body required (topic text)"}, http.StatusBadRequest) return } topic := strings.Join(lines, " ") channel := to if !strings.HasPrefix(channel, "#") { channel = "#" + channel } err := s.params.Database.SetTopic(r.Context(), channel, uid, 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 } beforeTS := r.URL.Query().Get("before") limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) if limit <= 0 { limit = 50 } if strings.HasPrefix(target, "#") { // Channel history — look up channel by name to get its ID for target matching. var chID string err := s.params.Database.GetDB().QueryRowContext(r.Context(), "SELECT id FROM channels WHERE name = ?", target).Scan(&chID) 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, beforeTS, 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) } else { // DM history. targetUser, err := s.params.Database.GetUserByNick(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, targetUser.ID, beforeTS, 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) } } } // 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) } }