package service import ( "context" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "errors" "time" "messenger/internal/domain" ) const tokenBytes = 32 type AuthService struct { users UserRepository sessions SessionStore ttl time.Duration } func NewAuthService(users UserRepository, sessions SessionStore, ttl time.Duration) *AuthService { return &AuthService{users: users, sessions: sessions, ttl: ttl} } func (s *AuthService) Login(ctx context.Context, username, password string) (domain.Session, error) { user, hash, err := s.users.GetUserByUsername(ctx, username) if errors.Is(err, domain.ErrNotFound) { return domain.Session{}, domain.ErrUnauthorized } if err != nil { return domain.Session{}, err } ok, err := verifyPassword(password, hash) if err != nil { return domain.Session{}, err } if !ok { return domain.Session{}, domain.ErrUnauthorized } raw := make([]byte, tokenBytes) if _, err := rand.Read(raw); err != nil { return domain.Session{}, err } token := base64.RawURLEncoding.EncodeToString(raw) expiresAt := now().Add(s.ttl) if err := s.sessions.Create(ctx, HashToken(token), user.ID, expiresAt); err != nil { return domain.Session{}, err } return domain.Session{Token: token, ExpiresAt: expiresAt, User: user}, nil } func (s *AuthService) Authenticate(ctx context.Context, token string) (domain.User, error) { userID, err := s.sessions.Get(ctx, HashToken(token)) if err != nil { return domain.User{}, err } u, err := s.users.GetUser(ctx, userID) if errors.Is(err, domain.ErrNotFound) { return domain.User{}, domain.ErrUnauthorized } return u, err } func (s *AuthService) Logout(ctx context.Context, token string) error { return s.sessions.Delete(ctx, HashToken(token)) } func HashToken(token string) string { sum := sha256.Sum256([]byte(token)) return hex.EncodeToString(sum[:]) }