Files
mtusi2026lab2/internal/auth/service.go
T

65 lines
2.0 KiB
Go

package auth
import (
"context"
"time"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/user"
)
var ErrUnauthenticated = apperr.Unauthorized("a valid bearer token is required")
// Credentials is what this module needs from the users module: the user
// whose password matches, or user.ErrInvalidCredentials.
type Credentials interface {
Authenticate(ctx context.Context, username, password string) (user.User, error)
}
// Issued is a new session as the client sees it; Token is shown only here.
type Issued struct {
Token string
ExpiresAt time.Time
User user.User
}
type Service struct {
users Credentials
sessions Repository
ttl time.Duration
}
func NewService(users Credentials, sessions Repository, ttl time.Duration) *Service {
return &Service{users: users, sessions: sessions, ttl: ttl}
}
// Login checks the credentials first, so a store outage never hands out a
// token without a stored session. The expiry is fixed here and never
// extended; it is truncated to milliseconds, the precision of both the API
// timestamps and the store.
func (s *Service) Login(ctx context.Context, username, password string) (Issued, error) {
u, err := s.users.Authenticate(ctx, username, password)
if err != nil {
return Issued{}, err
}
token := newToken()
expiresAt := time.Now().Add(s.ttl).Truncate(time.Millisecond).UTC()
if err := s.sessions.Create(ctx, Session{TokenHash: HashToken(token), UserID: u.ID, ExpiresAt: expiresAt}); err != nil {
return Issued{}, err
}
return Issued{Token: token, ExpiresAt: expiresAt, User: u}, nil
}
// Authenticate returns the owner of the token's live session or
// ErrUnauthenticated. A store failure stays an unavailability, never
// ErrUnauthenticated: an outage must not look like a bad token to the client.
func (s *Service) Authenticate(ctx context.Context, token string) (uuid.UUID, error) {
return s.sessions.UserID(ctx, HashToken(token))
}
func (s *Service) Logout(ctx context.Context, token string) error {
return s.sessions.Delete(ctx, HashToken(token))
}