Initial commit

This commit is contained in:
Eugenius Naumenko
2026-06-07 22:20:57 +00:00
commit a7d8f72129
357 changed files with 168337 additions and 0 deletions
+163
View File
@@ -0,0 +1,163 @@
package services
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
"speech-learning-api/internal/domain"
"speech-learning-api/internal/store"
)
var ErrInvalidCredentials = errors.New("invalid credentials")
type UserStore interface {
CreateUser(ctx context.Context, email, passwordHash, uiLanguage string) (domain.User, error)
GetPasswordHashByEmail(ctx context.Context, email string) (domain.User, string, error)
GetUser(ctx context.Context, id string) (domain.User, error)
GetPrimaryProfile(ctx context.Context, userID string) (domain.LearnerProfile, error)
CreateLearnerProfile(ctx context.Context, userID, targetLanguage, cefrLevel string, dailyGoalMinutes int) (domain.LearnerProfile, error)
}
type AuthService struct {
store UserStore
jwtSecret []byte
}
type AuthResult struct {
Token string `json:"token"`
User domain.User `json:"user"`
Profile domain.LearnerProfile `json:"profile"`
}
func NewAuthService(store UserStore, jwtSecret string) *AuthService {
return &AuthService{store: store, jwtSecret: []byte(jwtSecret)}
}
func (s *AuthService) Register(ctx context.Context, email, password, uiLanguage, targetLanguage string, dailyGoalMinutes int) (AuthResult, error) {
email = strings.ToLower(strings.TrimSpace(email))
if email == "" || !strings.Contains(email, "@") {
return AuthResult{}, errors.New("valid email is required")
}
if len(password) < 8 {
return AuthResult{}, errors.New("password must be at least 8 characters")
}
if uiLanguage == "" {
uiLanguage = "de-DE"
}
if targetLanguage == "" {
targetLanguage = "en-US"
}
if dailyGoalMinutes <= 0 {
dailyGoalMinutes = 10
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return AuthResult{}, err
}
user, err := s.store.CreateUser(ctx, email, string(hash), uiLanguage)
if err != nil {
return AuthResult{}, err
}
profile, err := s.store.CreateLearnerProfile(ctx, user.ID, targetLanguage, "A1", dailyGoalMinutes)
if err != nil {
return AuthResult{}, err
}
token, err := s.IssueToken(user.ID)
if err != nil {
return AuthResult{}, err
}
return AuthResult{Token: token, User: user, Profile: profile}, nil
}
func (s *AuthService) Login(ctx context.Context, email, password string) (AuthResult, error) {
user, hash, err := s.store.GetPasswordHashByEmail(ctx, email)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
return AuthResult{}, ErrInvalidCredentials
}
return AuthResult{}, err
}
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)); err != nil {
return AuthResult{}, ErrInvalidCredentials
}
profile, err := s.store.GetPrimaryProfile(ctx, user.ID)
if errors.Is(err, store.ErrNotFound) {
profile, err = s.store.CreateLearnerProfile(ctx, user.ID, "en-US", "A1", 10)
}
if err != nil {
return AuthResult{}, err
}
token, err := s.IssueToken(user.ID)
if err != nil {
return AuthResult{}, err
}
return AuthResult{Token: token, User: user, Profile: profile}, nil
}
func (s *AuthService) IssueToken(userID string) (string, error) {
header := map[string]string{"alg": "HS256", "typ": "JWT"}
payload := map[string]any{
"sub": userID,
"exp": time.Now().Add(24 * time.Hour).Unix(),
"iat": time.Now().Unix(),
}
headerJSON, err := json.Marshal(header)
if err != nil {
return "", err
}
payloadJSON, err := json.Marshal(payload)
if err != nil {
return "", err
}
enc := base64.RawURLEncoding
unsigned := enc.EncodeToString(headerJSON) + "." + enc.EncodeToString(payloadJSON)
sig := hmacSHA256(unsigned, s.jwtSecret)
return unsigned + "." + enc.EncodeToString(sig), nil
}
func (s *AuthService) VerifyToken(token string) (string, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return "", errors.New("invalid token")
}
unsigned := parts[0] + "." + parts[1]
expected := hmacSHA256(unsigned, s.jwtSecret)
actual, err := base64.RawURLEncoding.DecodeString(parts[2])
if err != nil {
return "", err
}
if !hmac.Equal(expected, actual) {
return "", errors.New("invalid signature")
}
payloadJSON, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return "", err
}
var claims struct {
Subject string `json:"sub"`
Expiry int64 `json:"exp"`
}
if err := json.Unmarshal(payloadJSON, &claims); err != nil {
return "", err
}
if claims.Subject == "" || time.Now().Unix() > claims.Expiry {
return "", fmt.Errorf("token expired or missing subject")
}
return claims.Subject, nil
}
func hmacSHA256(value string, secret []byte) []byte {
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(value))
return mac.Sum(nil)
}