forked from mtusi2026/mtusi2026lab2
This commit is contained in:
@@ -3,7 +3,6 @@ package messenger
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
@@ -12,7 +11,6 @@ import (
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/postgres"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/session"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
@@ -34,7 +32,7 @@ func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := s.repository.Ping(ctx); err != nil {
|
||||
if err := s.messengerStore.Ping(ctx); err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if err := s.sessions.Ping(ctx); err != nil {
|
||||
@@ -63,7 +61,7 @@ func (s *Server) users(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
user, err := s.repository.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
|
||||
user, err := s.messengerStore.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
|
||||
if errors.Is(err, postgres.ErrConflict) {
|
||||
return &apiError{http.StatusConflict, errorCodeConflict, "username already exists"}
|
||||
}
|
||||
@@ -79,73 +77,6 @@ func validPassword(value string) bool {
|
||||
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && length >= 12 && length <= 128
|
||||
}
|
||||
|
||||
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost {
|
||||
return methodNotAllowed(w, http.MethodPost)
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1))
|
||||
if err != nil || len(body) != 0 {
|
||||
return invalidRequest()
|
||||
}
|
||||
username, passwordValue, ok := singleBasicAuth(r)
|
||||
if !ok {
|
||||
return unauthorized()
|
||||
}
|
||||
credentials, err := s.repository.UserByUsername(r.Context(), username)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
|
||||
return internalError()
|
||||
}
|
||||
return unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
verified, err := s.passwords.Verify(passwordValue, credentials.PasswordHash)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
if !verified {
|
||||
return unauthorized()
|
||||
}
|
||||
token, expiresAt, err := s.sessions.Create(r.Context(), credentials.ID, s.sessionTTL)
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}{token, "Bearer", model.FormatTime(expiresAt), credentials.User})
|
||||
return nil
|
||||
}
|
||||
|
||||
func singleBasicAuth(r *http.Request) (string, string, bool) {
|
||||
if len(r.Header.Values("Authorization")) != 1 {
|
||||
return "", "", false
|
||||
}
|
||||
username, passwordValue, ok := r.BasicAuth()
|
||||
return username, passwordValue, ok && username != ""
|
||||
}
|
||||
|
||||
func (s *Server) revokeSession(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodDelete {
|
||||
return methodNotAllowed(w, http.MethodDelete)
|
||||
}
|
||||
_, token, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
if err := s.sessions.Delete(r.Context(), token); errors.Is(err, session.ErrNotFound) {
|
||||
return unauthorized()
|
||||
} else if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) me(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
@@ -194,7 +125,7 @@ func (s *Server) chats(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if _, included := members[user.ID]; !included {
|
||||
return invalidRequest()
|
||||
}
|
||||
chat, err := s.repository.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
|
||||
chat, err := s.messengerStore.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
|
||||
if errors.Is(err, postgres.ErrInvalidMembers) {
|
||||
return invalidRequest()
|
||||
}
|
||||
@@ -210,7 +141,7 @@ func (s *Server) listChats(w http.ResponseWriter, r *http.Request, user User) *a
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, hasNext, listErr := s.repository.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
|
||||
items, hasNext, listErr := s.messengerStore.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, postgres.ErrInvalidCursor) {
|
||||
return invalidRequest()
|
||||
}
|
||||
@@ -245,7 +176,7 @@ func (s *Server) chat(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
chat, err := s.repository.ChatForUser(r.Context(), chatID, user.ID)
|
||||
chat, err := s.messengerStore.ChatForUser(r.Context(), chatID, user.ID)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
@@ -280,7 +211,7 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if !validText(input.Text, 4000) {
|
||||
return invalidRequest()
|
||||
}
|
||||
message, err := s.repository.CreateMessage(r.Context(), chatID, user.ID, input.Text)
|
||||
message, err := s.messengerStore.CreateMessage(r.Context(), chatID, user.ID, input.Text)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
@@ -296,7 +227,7 @@ func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, user User,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, hasNext, listErr := s.repository.ListMessages(r.Context(), chatID, user.ID, cursorPosition(cursor), limit)
|
||||
items, hasNext, listErr := s.messengerStore.ListMessages(r.Context(), chatID, user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
@@ -328,30 +259,3 @@ func cursorPosition(cursor *pageCursor) *model.Position {
|
||||
}
|
||||
return &model.Position{CreatedAt: cursor.Time, ID: cursor.ID}
|
||||
}
|
||||
|
||||
func (s *Server) authenticate(r *http.Request) (User, string, *apiError) {
|
||||
values := r.Header.Values("Authorization")
|
||||
if len(values) != 1 {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
scheme, token, found := strings.Cut(values[0], " ")
|
||||
if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t\r\n") {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
userID, err := s.sessions.UserID(r.Context(), token)
|
||||
if errors.Is(err, session.ErrNotFound) || errors.Is(err, session.ErrInvalidToken) {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, "", unavailable()
|
||||
}
|
||||
user, err := s.repository.UserByID(r.Context(), userID)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
_ = s.sessions.Delete(r.Context(), token)
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, "", unavailable()
|
||||
}
|
||||
return user, token, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user