forked from mtusi2026/mtusi2026lab2
Implement lab2 messenger API with PostgreSQL Redis and Docker
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
store *storage.ChatStore
|
||||
}
|
||||
|
||||
func NewChatHandler(store *storage.ChatStore) *ChatHandler {
|
||||
return &ChatHandler{store: store}
|
||||
}
|
||||
|
||||
type createChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []uuid.UUID `json:"member_ids"`
|
||||
}
|
||||
|
||||
type chatPage struct {
|
||||
Items []model.Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
var req createChatRequest
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
title := strings.TrimSpace(req.Title)
|
||||
titleLength := utf8.RuneCountInString(title)
|
||||
|
||||
if titleLength < 1 || titleLength > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "title must contain from 1 to 100 characters")
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.MemberIDs) < 1 || len(req.MemberIDs) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member_ids must contain from 1 to 100 users")
|
||||
return
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(req.MemberIDs))
|
||||
currentUserIsMember := false
|
||||
|
||||
for _, memberID := range req.MemberIDs {
|
||||
if _, exists := seen[memberID]; exists {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member_ids must contain unique users")
|
||||
return
|
||||
}
|
||||
seen[memberID] = struct{}{}
|
||||
|
||||
if memberID == currentUser.ID {
|
||||
currentUserIsMember = true
|
||||
}
|
||||
}
|
||||
|
||||
if !currentUserIsMember {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "current user must be a chat member")
|
||||
return
|
||||
}
|
||||
|
||||
for _, memberID := range req.MemberIDs {
|
||||
exists, err := h.store.ExistsUser(r.Context(), memberID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member does not exist")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
chat := model.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: title,
|
||||
MemberIDs: req.MemberIDs,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
err := h.store.CreateChat(r.Context(), chat)
|
||||
if errors.Is(err, storage.ErrInvalidMember) {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member does not exist")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, chat)
|
||||
}
|
||||
|
||||
func (h *ChatHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
chats, err := h.store.ListChatsForUser(r.Context(), currentUser.ID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, chatPage{
|
||||
Items: chats,
|
||||
NextCursor: nil,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.store.GetChatForUser(
|
||||
r.Context(), chatID, currentUser.ID,
|
||||
)
|
||||
if errors.Is(err, storage.ErrChatNotFound) {
|
||||
writeError(w, r, http.StatusNotFound,
|
||||
"not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, chat)
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
type MessageHandler struct {
|
||||
chats *storage.ChatStore
|
||||
messages *storage.MessageStore
|
||||
}
|
||||
|
||||
func NewMessageHandler(
|
||||
chats *storage.ChatStore,
|
||||
messages *storage.MessageStore,
|
||||
) *MessageHandler {
|
||||
return &MessageHandler{
|
||||
chats: chats,
|
||||
messages: messages,
|
||||
}
|
||||
}
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type messagePage struct {
|
||||
Items []model.Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func (h *MessageHandler) accessibleChat(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) (uuid.UUID, bool) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return uuid.Nil, false
|
||||
}
|
||||
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid chat id")
|
||||
return uuid.Nil, false
|
||||
}
|
||||
|
||||
_, err = h.chats.GetChatForUser(
|
||||
r.Context(), chatID, currentUser.ID,
|
||||
)
|
||||
if errors.Is(err, storage.ErrChatNotFound) {
|
||||
writeError(w, r, http.StatusNotFound,
|
||||
"not_found", "chat not found")
|
||||
return uuid.Nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return uuid.Nil, false
|
||||
}
|
||||
|
||||
return chatID, true
|
||||
}
|
||||
|
||||
func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, ok := h.accessibleChat(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
currentUser, _ := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
var req createMessageRequest
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
textLength := utf8.RuneCountInString(req.Text)
|
||||
if textLength < 1 || textLength > 4000 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "text must contain from 1 to 4000 characters")
|
||||
return
|
||||
}
|
||||
|
||||
message := model.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: currentUser.ID,
|
||||
Text: req.Text,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
err := h.messages.CreateMessage(r.Context(), message)
|
||||
if errors.Is(err, storage.ErrMessageMemberNotFound) {
|
||||
writeError(w, r, http.StatusNotFound,
|
||||
"not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
}
|
||||
|
||||
func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, ok := h.accessibleChat(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
limit := 50
|
||||
if raw := r.URL.Query().Get("limit"); raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "limit must be between 1 and 100")
|
||||
return
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
|
||||
var cursorTime *time.Time
|
||||
var cursorID *uuid.UUID
|
||||
|
||||
if raw := r.URL.Query().Get("cursor"); raw != "" {
|
||||
t, id, err := decodeCursor(raw)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
cursorTime = &t
|
||||
cursorID = &id
|
||||
}
|
||||
|
||||
items, hasMore, err := h.messages.ListMessages(
|
||||
r.Context(), chatID, limit, cursorTime, cursorID,
|
||||
)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
var nextCursor *string
|
||||
if hasMore && len(items) > 0 {
|
||||
cursor := encodeCursor(items[len(items)-1])
|
||||
nextCursor = &cursor
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, messagePage{
|
||||
Items: items,
|
||||
NextCursor: nextCursor,
|
||||
})
|
||||
}
|
||||
|
||||
func encodeCursor(message model.Message) string {
|
||||
value := fmt.Sprintf(
|
||||
"%s|%s",
|
||||
message.CreatedAt.Format(time.RFC3339Nano),
|
||||
message.ID.String(),
|
||||
)
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(value))
|
||||
}
|
||||
|
||||
func decodeCursor(cursor string) (time.Time, uuid.UUID, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
|
||||
parts := strings.SplitN(string(data), "|", 2)
|
||||
if len(parts) != 2 {
|
||||
return time.Time{}, uuid.Nil, fmt.Errorf("invalid cursor")
|
||||
}
|
||||
|
||||
createdAt, err := time.Parse(time.RFC3339Nano, parts[0])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
|
||||
id, err := uuid.Parse(parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
|
||||
return createdAt, id, nil
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
)
|
||||
|
||||
type errorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type errorResponse struct {
|
||||
Error errorBody `json:"error"`
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, data any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
_ = json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
func writeError(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
status int,
|
||||
code string,
|
||||
message string,
|
||||
) {
|
||||
writeJSON(w, status, errorResponse{
|
||||
Error: errorBody{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: middleware.GetRequestID(r.Context()),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
type SessionHandler struct {
|
||||
users *storage.AuthStore
|
||||
sessions *storage.SessionService
|
||||
}
|
||||
|
||||
func NewSessionHandler(
|
||||
users *storage.AuthStore,
|
||||
sessions *storage.SessionService,
|
||||
) *SessionHandler {
|
||||
return &SessionHandler{
|
||||
users: users,
|
||||
sessions: sessions,
|
||||
}
|
||||
}
|
||||
|
||||
type sessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User interface{} `json:"user"`
|
||||
}
|
||||
|
||||
func sessionTTL() time.Duration {
|
||||
seconds := 3600
|
||||
|
||||
if raw := os.Getenv("SESSION_TTL_SECONDS"); raw != "" {
|
||||
if n, err := strconv.Atoi(raw); err == nil && n > 0 {
|
||||
seconds = n
|
||||
}
|
||||
}
|
||||
|
||||
return time.Duration(seconds) * time.Second
|
||||
}
|
||||
|
||||
func (h *SessionHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Basic realm="messenger", charset="UTF-8"`,
|
||||
)
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username == "" || password == "" {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
user, passwordHash, err := h.users.GetUserByUsername(
|
||||
r.Context(), username,
|
||||
)
|
||||
|
||||
if errors.Is(err, storage.ErrUserNotFound) {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
if !VerifyPassword(password, passwordHash) {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
randomBytes := make([]byte, 32)
|
||||
if _, err := rand.Read(randomBytes); err != nil {
|
||||
writeError(w, r, http.StatusInternalServerError,
|
||||
"internal_error", "internal server error")
|
||||
return
|
||||
}
|
||||
|
||||
token := base64.RawURLEncoding.EncodeToString(randomBytes)
|
||||
createdAt := time.Now().UTC().Truncate(time.Microsecond)
|
||||
expiresAt := createdAt.Add(sessionTTL())
|
||||
|
||||
err = h.sessions.CreateSession(
|
||||
r.Context(),
|
||||
token,
|
||||
user.ID,
|
||||
createdAt,
|
||||
expiresAt,
|
||||
)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Del("WWW-Authenticate")
|
||||
|
||||
writeJSON(w, http.StatusCreated, sessionResponse{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expiresAt,
|
||||
User: user,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *SessionHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
authorization := r.Header.Get("Authorization")
|
||||
|
||||
if !strings.HasPrefix(authorization, "Bearer ") {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
token := strings.TrimPrefix(authorization, "Bearer ")
|
||||
if token == "" || strings.ContainsAny(token, " \t\r\n") {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
err := h.sessions.RevokeSession(r.Context(), token)
|
||||
|
||||
if errors.Is(err, storage.ErrSessionNotFound) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/argon2"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
var usernameRegexp = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type UserHandler struct {
|
||||
store *storage.AuthStore
|
||||
}
|
||||
|
||||
func NewUserHandler(store *storage.AuthStore) *UserHandler {
|
||||
return &UserHandler{store: store}
|
||||
}
|
||||
|
||||
type createUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, 16)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
hash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
1,
|
||||
64*1024,
|
||||
4,
|
||||
32,
|
||||
)
|
||||
|
||||
return "argon2id$" +
|
||||
base64.RawStdEncoding.EncodeToString(salt) + "$" +
|
||||
base64.RawStdEncoding.EncodeToString(hash), nil
|
||||
}
|
||||
|
||||
func VerifyPassword(password, encoded string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 3 || parts[0] != "argon2id" {
|
||||
return false
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[1])
|
||||
if err != nil || len(salt) != 16 {
|
||||
return false
|
||||
}
|
||||
|
||||
expected, err := base64.RawStdEncoding.DecodeString(parts[2])
|
||||
if err != nil || len(expected) != 32 {
|
||||
return false
|
||||
}
|
||||
|
||||
actual := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
1,
|
||||
64*1024,
|
||||
4,
|
||||
32,
|
||||
)
|
||||
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1
|
||||
}
|
||||
|
||||
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
var req createUserRequest
|
||||
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if !usernameRegexp.MatchString(req.Username) {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid username")
|
||||
return
|
||||
}
|
||||
|
||||
req.DisplayName = strings.TrimSpace(req.DisplayName)
|
||||
nameLength := utf8.RuneCountInString(req.DisplayName)
|
||||
|
||||
if nameLength < 1 || nameLength > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid display_name")
|
||||
return
|
||||
}
|
||||
|
||||
passwordLength := utf8.RuneCountInString(req.Password)
|
||||
if passwordLength < 12 || passwordLength > 128 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request",
|
||||
"password must contain 12 to 128 characters")
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := HashPassword(req.Password)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusInternalServerError,
|
||||
"internal_error", "internal server error")
|
||||
return
|
||||
}
|
||||
|
||||
user := model.User{
|
||||
ID: uuid.New(),
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
err = h.store.CreateUser(r.Context(), user, passwordHash)
|
||||
if errors.Is(err, storage.ErrUsernameTaken) {
|
||||
writeError(w, r, http.StatusConflict,
|
||||
"conflict", "username already exists")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, user)
|
||||
}
|
||||
|
||||
func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
}
|
||||
Reference in New Issue
Block a user