forked from mtusi2026/mtusi2026lab3
feat: moved project from lab2
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
type ChatPage struct {
|
||||
Items []repositories.Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type ChatService struct {
|
||||
chats *repositories.ChatStore
|
||||
}
|
||||
|
||||
func NewChatService(chats *repositories.ChatStore) *ChatService {
|
||||
return &ChatService{chats: chats}
|
||||
}
|
||||
|
||||
func ChatHasMember(chat repositories.Chat, userID string) bool {
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == userID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(ctx context.Context, currentUserID, title string, memberIDs []string) (repositories.Chat, error) {
|
||||
if strings.TrimSpace(title) == "" {
|
||||
return repositories.Chat{}, InvalidInput{"title must not be blank"}
|
||||
}
|
||||
if utf8.RuneCountInString(title) > 100 {
|
||||
return repositories.Chat{}, InvalidInput{"title is too long"}
|
||||
}
|
||||
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return repositories.Chat{}, InvalidInput{"member_ids must contain from 1 to 100 users"}
|
||||
}
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
for _, memberID := range memberIDs {
|
||||
if _, err := uuid.Parse(memberID); err != nil {
|
||||
return repositories.Chat{}, InvalidInput{"member_ids must contain valid UUIDs"}
|
||||
}
|
||||
if _, exists := seen[memberID]; exists {
|
||||
return repositories.Chat{}, InvalidInput{"member_ids must not contain duplicates"}
|
||||
}
|
||||
seen[memberID] = struct{}{}
|
||||
}
|
||||
if _, exists := seen[currentUserID]; !exists {
|
||||
return repositories.Chat{}, InvalidInput{"current user must be a chat member"}
|
||||
}
|
||||
chat, err := s.chats.Create(ctx, title, memberIDs)
|
||||
if errors.Is(err, repositories.ErrUnknownMember) {
|
||||
return repositories.Chat{}, InvalidInput{"all members must be existing users"}
|
||||
}
|
||||
return chat, err
|
||||
}
|
||||
|
||||
func (s *ChatService) Get(ctx context.Context, currentUserID, chatID string) (repositories.Chat, error) {
|
||||
chat, err := s.chats.GetByID(ctx, chatID)
|
||||
if repositories.NotFound(err) {
|
||||
return repositories.Chat{}, ErrChatNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return repositories.Chat{}, err
|
||||
}
|
||||
if !ChatHasMember(chat, currentUserID) {
|
||||
return repositories.Chat{}, ErrChatNotFound
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func EncodeChatCursor(cursor repositories.ChatCursor) (string, error) {
|
||||
data, err := json.Marshal(cursor)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(data), nil
|
||||
}
|
||||
|
||||
func DecodeChatCursor(value string) (repositories.ChatCursor, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(value)
|
||||
if err != nil {
|
||||
return repositories.ChatCursor{}, err
|
||||
}
|
||||
var cursor repositories.ChatCursor
|
||||
if err := json.Unmarshal(data, &cursor); err != nil {
|
||||
return repositories.ChatCursor{}, err
|
||||
}
|
||||
if cursor.UserID == "" || cursor.ChatID == "" || cursor.CreatedAt.IsZero() {
|
||||
return repositories.ChatCursor{}, strconv.ErrSyntax
|
||||
}
|
||||
return cursor, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) List(ctx context.Context, userID string, limit int, cursorToken string) (ChatPage, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return ChatPage{}, InvalidInput{"limit must be between 1 and 100"}
|
||||
}
|
||||
var cursor *repositories.ChatCursor
|
||||
if cursorToken != "" {
|
||||
decoded, err := DecodeChatCursor(cursorToken)
|
||||
if err != nil || decoded.UserID != userID {
|
||||
return ChatPage{}, InvalidInput{"invalid cursor"}
|
||||
}
|
||||
cursor = &decoded
|
||||
}
|
||||
items, more, err := s.chats.ListPageForUser(ctx, userID, cursor, limit)
|
||||
if err != nil {
|
||||
return ChatPage{}, err
|
||||
}
|
||||
page := ChatPage{Items: items}
|
||||
if page.Items == nil {
|
||||
page.Items = []repositories.Chat{}
|
||||
}
|
||||
if more {
|
||||
last := items[len(items)-1]
|
||||
next, err := EncodeChatCursor(repositories.ChatCursor{UserID: userID, CreatedAt: last.CreatedAt, ChatID: last.ID})
|
||||
if err != nil {
|
||||
return ChatPage{}, err
|
||||
}
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package services
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrUnknownUser = errors.New("unknown user")
|
||||
ErrChatNotFound = errors.New("chat not found")
|
||||
ErrInvalidSession = errors.New("invalid session")
|
||||
)
|
||||
|
||||
type InvalidInput struct {
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e InvalidInput) Error() string { return e.Message }
|
||||
@@ -0,0 +1,23 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
type HealthService struct {
|
||||
health *repositories.HealthStore
|
||||
sessions *repositories.SessionStore
|
||||
}
|
||||
|
||||
func NewHealthService(health *repositories.HealthStore, sessions *repositories.SessionStore) *HealthService {
|
||||
return &HealthService{health: health, sessions: sessions}
|
||||
}
|
||||
|
||||
func (s *HealthService) Ready(ctx context.Context) error {
|
||||
if err := s.health.Ping(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.sessions.Ping(ctx)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
type MessagePage struct {
|
||||
Items []repositories.Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type MessageService struct {
|
||||
messages *repositories.MessageStore
|
||||
}
|
||||
|
||||
func NewMessageService(messages *repositories.MessageStore) *MessageService {
|
||||
return &MessageService{messages: messages}
|
||||
}
|
||||
|
||||
func (s *MessageService) Create(ctx context.Context, userID string, chat repositories.Chat, text string) (repositories.Message, error) {
|
||||
if !ChatHasMember(chat, userID) {
|
||||
return repositories.Message{}, ErrChatNotFound
|
||||
}
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return repositories.Message{}, InvalidInput{"text must not be blank"}
|
||||
}
|
||||
if utf8.RuneCountInString(text) > 4000 {
|
||||
return repositories.Message{}, InvalidInput{"text is too long"}
|
||||
}
|
||||
return s.messages.Create(ctx, chat.ID, userID, text)
|
||||
}
|
||||
|
||||
func MessageLess(left, right repositories.Message) bool {
|
||||
if left.CreatedAt.Equal(right.CreatedAt) {
|
||||
return left.ID < right.ID
|
||||
}
|
||||
return left.CreatedAt.Before(right.CreatedAt)
|
||||
}
|
||||
|
||||
func MessageAfterCursor(message repositories.Message, cursor repositories.MessageCursor) bool {
|
||||
return message.CreatedAt.After(cursor.CreatedAt) ||
|
||||
(message.CreatedAt.Equal(cursor.CreatedAt) && message.ID > cursor.MessageID)
|
||||
}
|
||||
|
||||
func EncodeMessageCursor(cursor repositories.MessageCursor) (string, error) {
|
||||
data, err := json.Marshal(cursor)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(data), nil
|
||||
}
|
||||
|
||||
func DecodeMessageCursor(value string) (repositories.MessageCursor, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(value)
|
||||
if err != nil {
|
||||
return repositories.MessageCursor{}, err
|
||||
}
|
||||
var cursor repositories.MessageCursor
|
||||
if err := json.Unmarshal(data, &cursor); err != nil {
|
||||
return repositories.MessageCursor{}, err
|
||||
}
|
||||
if cursor.ChatID == "" || cursor.MessageID == "" || cursor.CreatedAt.IsZero() {
|
||||
return repositories.MessageCursor{}, strconv.ErrSyntax
|
||||
}
|
||||
return cursor, nil
|
||||
}
|
||||
|
||||
func (s *MessageService) List(ctx context.Context, userID string, chat repositories.Chat, limit int, cursorToken string) (MessagePage, error) {
|
||||
if !ChatHasMember(chat, userID) {
|
||||
return MessagePage{}, ErrChatNotFound
|
||||
}
|
||||
if limit < 1 || limit > 100 {
|
||||
return MessagePage{}, InvalidInput{"limit must be between 1 and 100"}
|
||||
}
|
||||
var cursor *repositories.MessageCursor
|
||||
if cursorToken != "" {
|
||||
decoded, err := DecodeMessageCursor(cursorToken)
|
||||
if err != nil || decoded.ChatID != chat.ID {
|
||||
return MessagePage{}, InvalidInput{"invalid cursor"}
|
||||
}
|
||||
cursor = &decoded
|
||||
}
|
||||
items, more, err := s.messages.ListPageByChat(ctx, chat.ID, cursor, limit)
|
||||
if err != nil {
|
||||
return MessagePage{}, err
|
||||
}
|
||||
page := MessagePage{Items: items}
|
||||
if page.Items == nil {
|
||||
page.Items = []repositories.Message{}
|
||||
}
|
||||
if more {
|
||||
last := items[len(items)-1]
|
||||
next, err := EncodeMessageCursor(repositories.MessageCursor{ChatID: chat.ID, CreatedAt: last.CreatedAt, MessageID: last.ID})
|
||||
if err != nil {
|
||||
return MessagePage{}, err
|
||||
}
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonMemory uint32 = 64 * 1024
|
||||
argonIterations uint32 = 3
|
||||
argonParallelism uint8 = 2
|
||||
passwordSaltSize = 16
|
||||
passwordHashSize = 32
|
||||
)
|
||||
|
||||
// HashPassword stores the salt and Argon2id parameters in one PHC-encoded value.
|
||||
func HashPassword(password string) ([]byte, error) {
|
||||
salt := make([]byte, passwordSaltSize)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, passwordHashSize)
|
||||
encoded := fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonIterations, argonParallelism,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(hash),
|
||||
)
|
||||
return []byte(encoded), nil
|
||||
}
|
||||
|
||||
func VerifyPassword(password string, encoded []byte) (bool, error) {
|
||||
parts := strings.Split(string(encoded), "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
|
||||
return false, errors.New("invalid password hash format")
|
||||
}
|
||||
var memory, iterations uint32
|
||||
var parallelism uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, ¶llelism); err != nil ||
|
||||
fmt.Sprintf("m=%d,t=%d,p=%d", memory, iterations, parallelism) != parts[3] ||
|
||||
memory < 8*1024 || memory > 128*1024 || iterations < 1 || iterations > 10 || parallelism < 1 || parallelism > 8 {
|
||||
return false, errors.New("invalid password hash parameters")
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[4])
|
||||
if err != nil || len(salt) != passwordSaltSize {
|
||||
return false, errors.New("invalid password salt")
|
||||
}
|
||||
expected, err := base64.RawStdEncoding.Strict().DecodeString(parts[5])
|
||||
if err != nil || len(expected) != passwordHashSize {
|
||||
return false, errors.New("invalid password hash")
|
||||
}
|
||||
actual := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, passwordHashSize)
|
||||
return subtle.ConstantTimeCompare(expected, actual) == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
type SessionService struct {
|
||||
users *UserService
|
||||
sessions *repositories.SessionStore
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func SessionTTL() (time.Duration, error) {
|
||||
value := os.Getenv("SESSION_TTL_SECONDS")
|
||||
if value == "" {
|
||||
return time.Hour, nil
|
||||
}
|
||||
seconds, err := strconv.Atoi(value)
|
||||
if err != nil || seconds < 1 {
|
||||
return 0, errors.New("invalid SESSION_TTL_SECONDS")
|
||||
}
|
||||
return time.Duration(seconds) * time.Second, nil
|
||||
}
|
||||
|
||||
func NewSessionService(users *UserService, sessions *repositories.SessionStore, ttl time.Duration) *SessionService {
|
||||
return &SessionService{users: users, sessions: sessions, ttl: ttl}
|
||||
}
|
||||
|
||||
func (s *SessionService) Login(ctx context.Context, username, password string) (repositories.User, string, time.Time, bool, error) {
|
||||
user, valid, err := s.users.Authenticate(ctx, username, password)
|
||||
if err != nil || !valid {
|
||||
return repositories.User{}, "", time.Time{}, valid, err
|
||||
}
|
||||
token, expires, err := s.CreateForUser(ctx, user.ID)
|
||||
if err != nil {
|
||||
return repositories.User{}, "", time.Time{}, false, err
|
||||
}
|
||||
return user, token, expires, true, nil
|
||||
}
|
||||
|
||||
func (s *SessionService) CreateForUser(ctx context.Context, userID string) (string, time.Time, error) {
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
token := hex.EncodeToString(raw)
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
expires := time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond)
|
||||
if err := s.sessions.Create(ctx, hash[:], userID, expires); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
return token, expires, nil
|
||||
}
|
||||
|
||||
func (s *SessionService) User(ctx context.Context, token string) (repositories.User, error) {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
id, err := s.sessions.UserID(ctx, hash[:])
|
||||
if errors.Is(err, repositories.ErrSessionNotFound) {
|
||||
return repositories.User{}, ErrInvalidSession
|
||||
}
|
||||
if err != nil {
|
||||
return repositories.User{}, err
|
||||
}
|
||||
user, err := s.users.Get(ctx, id)
|
||||
if errors.Is(err, ErrUnknownUser) {
|
||||
return repositories.User{}, ErrInvalidSession
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (s *SessionService) Revoke(ctx context.Context, token string) error {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
return s.sessions.Revoke(ctx, hash[:])
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type UserService struct {
|
||||
users *repositories.UserStore
|
||||
}
|
||||
|
||||
func NewUserService(users *repositories.UserStore) *UserService {
|
||||
return &UserService{users: users}
|
||||
}
|
||||
|
||||
func (s *UserService) Create(ctx context.Context, username, displayName, password string) (repositories.User, error) {
|
||||
if !usernamePattern.MatchString(username) {
|
||||
return repositories.User{}, InvalidInput{"username must contain 3-32 lowercase latin letters, digits or underscores"}
|
||||
}
|
||||
if strings.TrimSpace(displayName) == "" {
|
||||
return repositories.User{}, InvalidInput{"display_name must not be blank"}
|
||||
}
|
||||
if utf8.RuneCountInString(displayName) > 100 {
|
||||
return repositories.User{}, InvalidInput{"display_name is too long"}
|
||||
}
|
||||
if strings.TrimSpace(password) == "" || utf8.RuneCountInString(password) < 12 || utf8.RuneCountInString(password) > 128 {
|
||||
return repositories.User{}, InvalidInput{"password must contain 12-128 characters"}
|
||||
}
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return repositories.User{}, err
|
||||
}
|
||||
user, err := s.users.Create(ctx, username, displayName, hash)
|
||||
if repositories.UniqueViolation(err) {
|
||||
return repositories.User{}, ErrConflict
|
||||
}
|
||||
if repositories.CheckViolation(err) {
|
||||
return repositories.User{}, InvalidInput{"invalid user fields"}
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (s *UserService) Get(ctx context.Context, id string) (repositories.User, error) {
|
||||
user, err := s.users.GetByID(ctx, id)
|
||||
if repositories.NotFound(err) {
|
||||
return repositories.User{}, ErrUnknownUser
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (s *UserService) Authenticate(ctx context.Context, username, password string) (repositories.User, bool, error) {
|
||||
if !usernamePattern.MatchString(username) || utf8.RuneCountInString(password) < 12 || utf8.RuneCountInString(password) > 128 {
|
||||
return repositories.User{}, false, nil
|
||||
}
|
||||
user, packedHash, err := s.users.GetCredentials(ctx, username)
|
||||
if repositories.NotFound(err) {
|
||||
return repositories.User{}, false, nil
|
||||
}
|
||||
if err != nil || packedHash == nil {
|
||||
return repositories.User{}, false, err
|
||||
}
|
||||
valid, err := VerifyPassword(password, packedHash)
|
||||
if err != nil {
|
||||
return repositories.User{}, false, err
|
||||
}
|
||||
return user, valid, nil
|
||||
}
|
||||
Reference in New Issue
Block a user