Add embedded web chat client with C2S HTTP API
- New DB schema: users, channel_members, messages tables (migration 003) - Full C2S HTTP API: register, channels, messages, DMs, polling - Preact SPA embedded via embed.FS, served at GET / - IRC-style UI: tab bar, channel messages, user list, DM tabs, /commands - Dark theme, responsive, esbuild-bundled (~19KB) - Polling-based message delivery (1.5s interval) - Commands: /join, /part, /msg, /nick
This commit is contained in:
358
internal/handlers/api.go
Normal file
358
internal/handlers/api.go
Normal file
@@ -0,0 +1,358 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
)
|
||||
|
||||
// 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.GetUserByToken(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
|
||||
}
|
||||
|
||||
// HandleRegister creates a new user and returns the auth token.
|
||||
func (s *Handlers) HandleRegister() 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
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); 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, token, err := s.params.Database.CreateUser(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)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleMe returns the current user's info.
|
||||
func (s *Handlers) HandleMe() http.HandlerFunc {
|
||||
type response struct {
|
||||
ID int64 `json:"id"`
|
||||
Nick string `json:"nick"`
|
||||
}
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, nick, ok := s.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
s.respondJSON(w, r, &response{ID: uid, Nick: nick}, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleListChannels returns channels the user has joined.
|
||||
func (s *Handlers) HandleListChannels() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, _, 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, 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)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleJoinChannel joins a channel (creates it if needed).
|
||||
func (s *Handlers) HandleJoinChannel() http.HandlerFunc {
|
||||
type request struct {
|
||||
Channel string `json:"channel"`
|
||||
}
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, _, ok := s.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req request
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
s.respondJSON(w, r, map[string]string{"error": "invalid request"}, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
req.Channel = strings.TrimSpace(req.Channel)
|
||||
if req.Channel == "" {
|
||||
s.respondJSON(w, r, map[string]string{"error": "channel name required"}, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(req.Channel, "#") {
|
||||
req.Channel = "#" + req.Channel
|
||||
}
|
||||
chID, err := s.params.Database.GetOrCreateChannel(r.Context(), req.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
|
||||
}
|
||||
if err := s.params.Database.JoinChannel(r.Context(), chID, uid); 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": req.Channel}, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
// HandlePartChannel leaves a channel.
|
||||
func (s *Handlers) HandlePartChannel() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, _, ok := s.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
name := "#" + chi.URLParam(r, "channel")
|
||||
var chID int64
|
||||
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
|
||||
}
|
||||
if err := s.params.Database.PartChannel(r.Context(), chID, uid); 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": name}, 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 int64
|
||||
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 messages for a channel.
|
||||
func (s *Handlers) HandleGetMessages() 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 int64
|
||||
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
|
||||
}
|
||||
afterID, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
|
||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
msgs, err := s.params.Database.GetMessages(r.Context(), chID, 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)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleSendMessage sends a message to a channel.
|
||||
func (s *Handlers) HandleSendMessage() http.HandlerFunc {
|
||||
type request struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, _, ok := s.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
name := "#" + chi.URLParam(r, "channel")
|
||||
var chID int64
|
||||
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
|
||||
}
|
||||
var req request
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
s.respondJSON(w, r, map[string]string{"error": "invalid request"}, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.Content) == "" {
|
||||
s.respondJSON(w, r, map[string]string{"error": "content required"}, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
msgID, err := s.params.Database.SendMessage(r.Context(), chID, uid, req.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)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleSendDM sends a direct message to a user.
|
||||
func (s *Handlers) HandleSendDM() http.HandlerFunc {
|
||||
type request struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, _, ok := s.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
targetNick := chi.URLParam(r, "nick")
|
||||
targetID, err := s.params.Database.GetUserByNick(r.Context(), targetNick)
|
||||
if err != nil {
|
||||
s.respondJSON(w, r, map[string]string{"error": "user not found"}, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
var req request
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
s.respondJSON(w, r, map[string]string{"error": "invalid request"}, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.Content) == "" {
|
||||
s.respondJSON(w, r, map[string]string{"error": "content required"}, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
msgID, err := s.params.Database.SendDM(r.Context(), uid, targetID, req.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)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleGetDMs returns direct messages with a user.
|
||||
func (s *Handlers) HandleGetDMs() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, _, ok := s.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
targetNick := chi.URLParam(r, "nick")
|
||||
targetID, err := s.params.Database.GetUserByNick(r.Context(), targetNick)
|
||||
if err != nil {
|
||||
s.respondJSON(w, r, map[string]string{"error": "user not found"}, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
afterID, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
|
||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
msgs, err := s.params.Database.GetDMs(r.Context(), uid, targetID, afterID, limit)
|
||||
if err != nil {
|
||||
s.log.Error("get dms failed", "error", err)
|
||||
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
s.respondJSON(w, r, msgs, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
// HandlePoll returns all new messages (channels + DMs) for the user.
|
||||
func (s *Handlers) HandlePoll() 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("poll messages 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)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"git.eeqj.de/sneak/chat/internal/config"
|
||||
"git.eeqj.de/sneak/chat/internal/db"
|
||||
"git.eeqj.de/sneak/chat/internal/globals"
|
||||
"git.eeqj.de/sneak/chat/internal/healthcheck"
|
||||
@@ -20,6 +21,7 @@ type Params struct {
|
||||
|
||||
Logger *logger.Logger
|
||||
Globals *globals.Globals
|
||||
Config *config.Config
|
||||
Database *db.Database
|
||||
Healthcheck *healthcheck.Healthcheck
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user