72 lines
1.7 KiB
Go
72 lines
1.7 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"trankilou.fr/lassistanoque/backend/internal/domain"
|
|
)
|
|
|
|
var (
|
|
ErrRegistrationNotAllowed = errors.New("registration not allowed")
|
|
ErrMethodUnknown = errors.New("auth method unknown")
|
|
ErrUnauthorized = errors.New("unauthorized")
|
|
)
|
|
|
|
type Service struct {
|
|
authenticators map[string]Authenticator // "password" -> ..., "oidc" -> ...
|
|
userRepository domain.UserRepository
|
|
settingsRepository domain.SettingsRepository
|
|
}
|
|
|
|
func NewService(
|
|
settingsRepository domain.SettingsRepository,
|
|
userRepository domain.UserRepository,
|
|
authenticators map[string]Authenticator,
|
|
) *Service {
|
|
return &Service{
|
|
authenticators: authenticators,
|
|
userRepository: userRepository,
|
|
settingsRepository: settingsRepository,
|
|
}
|
|
}
|
|
|
|
func (s *Service) Login(ctx context.Context, creds Credentials) (*Session, error) {
|
|
authn, ok := s.authenticators[creds.Method]
|
|
if !ok {
|
|
return nil, fmt.Errorf("auth method unsupported: %s", creds.Method)
|
|
}
|
|
return authn.Authenticate(ctx, creds)
|
|
}
|
|
|
|
func (s *Service) Register(registration Registration) (*Session, error) {
|
|
settings, err := s.settingsRepository.GetSettings()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !settings.RegisterEnabled {
|
|
return nil, ErrRegistrationNotAllowed
|
|
}
|
|
if authenticator, ok := s.authenticators[registration.Method]; ok {
|
|
session, err := authenticator.Register(context.Background(), registration)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
_, err = s.userRepository.CreateTeam(session.User.ID, &domain.Team{
|
|
Label: "Espace personnel",
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return session, nil
|
|
} else {
|
|
return nil, ErrMethodUnknown
|
|
}
|
|
}
|
|
|
|
func (s *Service) Status(session *Session) (*domain.User, error) {
|
|
return nil, nil
|
|
}
|