follow sql schema
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
|
||||
"mediarr/ident"
|
||||
"mediarr/identity"
|
||||
)
|
||||
|
||||
type AuthenticatedUser struct {
|
||||
Principal identity.Principal
|
||||
Account Account
|
||||
}
|
||||
|
||||
type Account struct {
|
||||
PrincipalID ident.UUID
|
||||
Login string
|
||||
State string
|
||||
MustChangePassword bool
|
||||
FailedAttempts int64
|
||||
LockedUntil sql.NullInt64
|
||||
LastLoginAt sql.NullInt64
|
||||
CreatedAt int64
|
||||
}
|
||||
|
||||
var (
|
||||
ErrInvalidCredentials = errors.New("identifiants invalides")
|
||||
ErrAccountLocked = errors.New("compte verrouillé")
|
||||
ErrAccountDisabled = errors.New("compte désactivé")
|
||||
ErrLoginTaken = errors.New("login déjà utilisé")
|
||||
ErrInvalidLogin = errors.New("login invalide")
|
||||
ErrWeakPassword = errors.New("mot de passe trop faible")
|
||||
ErrInvalidSession = errors.New("session invalide")
|
||||
)
|
||||
@@ -0,0 +1,42 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"mediarr/database"
|
||||
)
|
||||
|
||||
func newTestService(t *testing.T) *Service {
|
||||
t.Helper()
|
||||
|
||||
t.Chdir(t.TempDir())
|
||||
|
||||
err, db := database.NewDatabase(database.NewDatabaseParams{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewDatabase : %v", err)
|
||||
}
|
||||
|
||||
t.Cleanup(func() {
|
||||
if err := db.Close(); err != nil {
|
||||
t.Errorf("Close : %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
return NewService(*db)
|
||||
}
|
||||
|
||||
func mustCreateUser(t *testing.T, service *Service, login, password, role string) *AuthenticatedUser {
|
||||
t.Helper()
|
||||
|
||||
created, err := service.CreateUser(context.Background(), CreateUserParams{
|
||||
Login: login,
|
||||
Password: password,
|
||||
Role: role,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser(%q) : %v", login, err)
|
||||
}
|
||||
|
||||
return created
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
const (
|
||||
minPasswordLen = 8
|
||||
maxPasswordLen = 1024
|
||||
maxLoginLen = 255
|
||||
)
|
||||
|
||||
func normalizeLogin(login string) (string, string, error) {
|
||||
display := strings.TrimSpace(login)
|
||||
if display == "" {
|
||||
return "", "", fmt.Errorf("%w: vide", ErrInvalidLogin)
|
||||
}
|
||||
if len(display) > maxLoginLen {
|
||||
return "", "", fmt.Errorf("%w: maximum %d caractères", ErrInvalidLogin, maxLoginLen)
|
||||
}
|
||||
if strings.IndexFunc(display, unicode.IsSpace) >= 0 {
|
||||
return "", "", fmt.Errorf("%w: espaces interdits", ErrInvalidLogin)
|
||||
}
|
||||
if strings.ContainsRune(display, 0) {
|
||||
return "", "", fmt.Errorf("%w: caractère nul interdit", ErrInvalidLogin)
|
||||
}
|
||||
|
||||
return display, strings.ToLower(display), nil
|
||||
}
|
||||
|
||||
func validatePassword(password string) error {
|
||||
if len(password) < minPasswordLen {
|
||||
return fmt.Errorf("%w: minimum %d caractères", ErrWeakPassword, minPasswordLen)
|
||||
}
|
||||
if len(password) > maxPasswordLen {
|
||||
return fmt.Errorf("%w: maximum %d octets", ErrWeakPassword, maxPasswordLen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argon2Memory uint32 = 19 * 1024
|
||||
argon2Time uint32 = 2
|
||||
argon2Threads uint8 = 1
|
||||
argon2KeyLen uint32 = 32
|
||||
argon2SaltLen = 16
|
||||
)
|
||||
|
||||
type argon2Params struct {
|
||||
memory uint32
|
||||
time uint32
|
||||
threads uint8
|
||||
}
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
if err := validatePassword(password); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
salt := make([]byte, argon2SaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("auth: génération du sel : %w", err)
|
||||
}
|
||||
|
||||
key := argon2.IDKey([]byte(password), salt, argon2Time, argon2Memory, argon2Threads, argon2KeyLen)
|
||||
|
||||
return fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
argon2Memory,
|
||||
argon2Time,
|
||||
argon2Threads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(key),
|
||||
), nil
|
||||
}
|
||||
|
||||
func VerifyPassword(password, encoded string) (bool, error) {
|
||||
params, salt, key, err := decodePasswordHash(encoded)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
candidate := argon2.IDKey([]byte(password), salt, params.time, params.memory, params.threads, uint32(len(key)))
|
||||
|
||||
return subtle.ConstantTimeCompare(candidate, key) == 1, nil
|
||||
}
|
||||
|
||||
func decodePasswordHash(encoded string) (argon2Params, []byte, []byte, error) {
|
||||
var params argon2Params
|
||||
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
|
||||
return params, nil, nil, errors.New("auth: hash Argon2id invalide")
|
||||
}
|
||||
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
|
||||
return params, nil, nil, errors.New("auth: version Argon2id invalide")
|
||||
}
|
||||
|
||||
var memory, iterations, threads uint32
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, &threads); err != nil {
|
||||
return params, nil, nil, errors.New("auth: paramètres Argon2id invalides")
|
||||
}
|
||||
|
||||
if memory < 8*1024 || memory > 1024*1024 ||
|
||||
iterations < 1 || iterations > 10 ||
|
||||
threads < 1 || threads > 16 {
|
||||
return params, nil, nil, errors.New("auth: paramètres Argon2id hors limites")
|
||||
}
|
||||
|
||||
params = argon2Params{
|
||||
memory: memory,
|
||||
time: iterations,
|
||||
threads: uint8(threads),
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil || len(salt) < 8 || len(salt) > 64 {
|
||||
return params, nil, nil, errors.New("auth: sel Argon2id invalide")
|
||||
}
|
||||
|
||||
key, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(key) < 16 || len(key) > 64 {
|
||||
return params, nil, nil, errors.New("auth: clé Argon2id invalide")
|
||||
}
|
||||
|
||||
return params, salt, key, nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHashPasswordAndVerify(t *testing.T) {
|
||||
password := "correct horse battery staple"
|
||||
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword : %v", err)
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(hash, "$argon2id$v=19$") {
|
||||
t.Fatalf("hash inattendu : %q", hash)
|
||||
}
|
||||
|
||||
valid, err := VerifyPassword(password, hash)
|
||||
if err != nil {
|
||||
t.Fatalf("VerifyPassword : %v", err)
|
||||
}
|
||||
if !valid {
|
||||
t.Fatal("le mot de passe correct a été refusé")
|
||||
}
|
||||
|
||||
valid, err = VerifyPassword("mauvais mot de passe", hash)
|
||||
if err != nil {
|
||||
t.Fatalf("VerifyPassword (mauvais) : %v", err)
|
||||
}
|
||||
if valid {
|
||||
t.Fatal("un mauvais mot de passe a été accepté")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashPasswordUsesRandomSalt(t *testing.T) {
|
||||
password := "correct horse battery staple"
|
||||
|
||||
first, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword : %v", err)
|
||||
}
|
||||
|
||||
second, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword : %v", err)
|
||||
}
|
||||
|
||||
if first == second {
|
||||
t.Fatal("deux hashes du même mot de passe sont identiques")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashPasswordRejectsWeakPassword(t *testing.T) {
|
||||
_, err := HashPassword("court")
|
||||
if !errors.Is(err, ErrWeakPassword) {
|
||||
t.Fatalf("erreur = %v, attendu ErrWeakPassword", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyPasswordRejectsMalformedHash(t *testing.T) {
|
||||
cases := []string{
|
||||
"",
|
||||
"plaintext",
|
||||
"$argon2id$v=19$m=19456,t=2,p=1$sel$hash",
|
||||
"$argon2id$v=19$m=19456,t=2,p=1$!!!$!!!",
|
||||
"$argon2id$v=18$m=19456,t=2,p=1$c2Vs$c2Vs",
|
||||
}
|
||||
|
||||
for _, encoded := range cases {
|
||||
if _, err := VerifyPassword("correct horse battery staple", encoded); err == nil {
|
||||
t.Fatalf("hash %q accepté", encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"mediarr/database"
|
||||
"mediarr/identity"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
db database.DatabaseClient
|
||||
identity *identity.Service
|
||||
}
|
||||
|
||||
func NewService(db database.DatabaseClient) *Service {
|
||||
return &Service{
|
||||
db: db,
|
||||
identity: identity.NewService(db),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) withTx(ctx context.Context, fn func(*database.Queries) error) error {
|
||||
tx, err := s.db.WriteDB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = tx.Rollback()
|
||||
}()
|
||||
|
||||
if err := fn(s.db.WriteQueries.WithTx(tx)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
return err != nil && strings.Contains(strings.ToLower(err.Error()), "unique constraint failed")
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mediarr/database"
|
||||
"mediarr/ident"
|
||||
)
|
||||
|
||||
const (
|
||||
sessionTokenBytes = 32
|
||||
defaultSessionTTL = 30 * 24 * time.Hour
|
||||
defaultIdleTTL = 7 * 24 * time.Hour
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
ID ident.UUID
|
||||
PrincipalID ident.UUID
|
||||
Kind string
|
||||
Label string
|
||||
CreatedAt int64
|
||||
LastSeenAt int64
|
||||
ExpiresAt int64
|
||||
IdleExpiresAt int64
|
||||
}
|
||||
|
||||
type CreateSessionParams struct {
|
||||
PrincipalID ident.UUID
|
||||
Kind string
|
||||
Label string
|
||||
UserAgent string
|
||||
IPPrefix string
|
||||
TTL time.Duration
|
||||
IdleTTL time.Duration
|
||||
}
|
||||
|
||||
func (s *Service) CreateSession(ctx context.Context, params CreateSessionParams) (*Session, string, error) {
|
||||
kind := params.Kind
|
||||
if kind == "" {
|
||||
kind = "web"
|
||||
}
|
||||
if kind != "web" && kind != "api" {
|
||||
return nil, "", fmt.Errorf("%w: type de session %q", ErrInvalidSession, kind)
|
||||
}
|
||||
|
||||
principal, err := s.db.Queries.GetPrincipal(ctx, params.PrincipalID)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, "", ErrInvalidSession
|
||||
}
|
||||
return nil, "", err
|
||||
}
|
||||
if principal.Status != "active" {
|
||||
return nil, "", ErrInvalidSession
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
|
||||
account, err := s.db.Queries.GetAccount(ctx, params.PrincipalID)
|
||||
switch {
|
||||
case err == nil:
|
||||
switch account.State {
|
||||
case "active":
|
||||
case "disabled":
|
||||
return nil, "", ErrAccountDisabled
|
||||
case "locked":
|
||||
if !account.LockedUntil.Valid || account.LockedUntil.Int64 > now {
|
||||
return nil, "", ErrAccountLocked
|
||||
}
|
||||
}
|
||||
case !errors.Is(err, sql.ErrNoRows):
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
ttl := params.TTL
|
||||
if ttl <= 0 {
|
||||
ttl = defaultSessionTTL
|
||||
}
|
||||
idleTTL := params.IdleTTL
|
||||
if idleTTL <= 0 {
|
||||
idleTTL = defaultIdleTTL
|
||||
}
|
||||
|
||||
tokenBytes := make([]byte, sessionTokenBytes)
|
||||
if _, err := rand.Read(tokenBytes); err != nil {
|
||||
return nil, "", fmt.Errorf("auth: génération du token de session : %w", err)
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(tokenBytes)
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
|
||||
expiresAt := now + ttl.Milliseconds()
|
||||
idleExpiresAt := now + idleTTL.Milliseconds()
|
||||
if idleExpiresAt > expiresAt {
|
||||
idleExpiresAt = expiresAt
|
||||
}
|
||||
|
||||
sessionID, err := ident.NewV7()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
session, err := s.db.WriteQueries.CreateSession(ctx, database.CreateSessionParams{
|
||||
ID: sessionID,
|
||||
TokenHash: tokenHash[:],
|
||||
PrincipalID: params.PrincipalID,
|
||||
Kind: kind,
|
||||
Label: nullableString(params.Label),
|
||||
UserAgent: nullableString(params.UserAgent),
|
||||
IpPrefix: nullableString(params.IPPrefix),
|
||||
CreatedAt: now,
|
||||
LastSeenAt: now,
|
||||
ExpiresAt: expiresAt,
|
||||
IdleExpiresAt: idleExpiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
return sessionFromDB(session), token, nil
|
||||
}
|
||||
|
||||
func (s *Service) ValidateSession(ctx context.Context, token string) (*Session, *AuthenticatedUser, error) {
|
||||
if token == "" {
|
||||
return nil, nil, ErrInvalidSession
|
||||
}
|
||||
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
session, err := s.db.Queries.GetSessionByTokenHash(ctx, tokenHash[:])
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil, ErrInvalidSession
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
if session.RevokedAt.Valid || session.ExpiresAt <= now || session.IdleExpiresAt <= now {
|
||||
return nil, nil, ErrInvalidSession
|
||||
}
|
||||
|
||||
user, err := s.loadAuthenticatedUser(ctx, session.PrincipalID)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil, ErrInvalidSession
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
if user.Principal.Status != "active" || user.Account.State == "disabled" {
|
||||
return nil, nil, ErrInvalidSession
|
||||
}
|
||||
|
||||
idleTTL := session.IdleExpiresAt - session.LastSeenAt
|
||||
if idleTTL <= 0 {
|
||||
idleTTL = defaultIdleTTL.Milliseconds()
|
||||
}
|
||||
idleExpiresAt := now + idleTTL
|
||||
if idleExpiresAt > session.ExpiresAt {
|
||||
idleExpiresAt = session.ExpiresAt
|
||||
}
|
||||
|
||||
updated, err := s.db.WriteQueries.TouchSession(ctx, database.TouchSessionParams{
|
||||
LastSeenAt: now,
|
||||
IdleExpiresAt: idleExpiresAt,
|
||||
ID: session.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return sessionFromDB(updated), user, nil
|
||||
}
|
||||
|
||||
func (s *Service) RevokeSession(ctx context.Context, sessionID ident.UUID) error {
|
||||
_, err := s.db.WriteQueries.RevokeSession(ctx, database.RevokeSessionParams{
|
||||
RevokedAt: sql.NullInt64{
|
||||
Int64: time.Now().UnixMilli(),
|
||||
Valid: true,
|
||||
},
|
||||
ID: sessionID,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrInvalidSession
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) RevokeSessionByToken(ctx context.Context, token string) error {
|
||||
if token == "" {
|
||||
return ErrInvalidSession
|
||||
}
|
||||
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
|
||||
_, err := s.db.WriteQueries.RevokeSessionByTokenHash(ctx, database.RevokeSessionByTokenHashParams{
|
||||
RevokedAt: sql.NullInt64{
|
||||
Int64: time.Now().UnixMilli(),
|
||||
Valid: true,
|
||||
},
|
||||
TokenHash: tokenHash[:],
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrInvalidSession
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) ListSessions(ctx context.Context, principalID ident.UUID) ([]Session, error) {
|
||||
rows, err := s.db.Queries.ListSessionsByPrincipal(ctx, principalID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sessions := make([]Session, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
sessions = append(sessions, *sessionFromDB(row))
|
||||
}
|
||||
|
||||
return sessions, nil
|
||||
}
|
||||
|
||||
func (s *Service) DeleteExpiredSessions(ctx context.Context) (int64, error) {
|
||||
return s.db.WriteQueries.DeleteExpiredSessions(ctx, time.Now().UnixMilli())
|
||||
}
|
||||
|
||||
func sessionFromDB(session database.Session) *Session {
|
||||
return &Session{
|
||||
ID: session.ID,
|
||||
PrincipalID: session.PrincipalID,
|
||||
Kind: session.Kind,
|
||||
Label: session.Label.String,
|
||||
CreatedAt: session.CreatedAt,
|
||||
LastSeenAt: session.LastSeenAt,
|
||||
ExpiresAt: session.ExpiresAt,
|
||||
IdleExpiresAt: session.IdleExpiresAt,
|
||||
}
|
||||
}
|
||||
|
||||
func nullableString(value string) sql.NullString {
|
||||
if value == "" {
|
||||
return sql.NullString{}
|
||||
}
|
||||
return sql.NullString{String: value, Valid: true}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mediarr/database"
|
||||
"mediarr/identity"
|
||||
)
|
||||
|
||||
func TestCreateAndValidateSession(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", identity.RoleMember)
|
||||
|
||||
session, token, err := service.CreateSession(ctx, CreateSessionParams{
|
||||
PrincipalID: created.Principal.ID,
|
||||
Label: "test",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession : %v", err)
|
||||
}
|
||||
if token == "" {
|
||||
t.Fatal("token vide")
|
||||
}
|
||||
|
||||
validated, authenticated, err := service.ValidateSession(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatalf("ValidateSession : %v", err)
|
||||
}
|
||||
if validated.ID != session.ID {
|
||||
t.Fatalf("id = %s, attendu %s", validated.ID, session.ID)
|
||||
}
|
||||
if authenticated.Principal.ID != created.Principal.ID {
|
||||
t.Fatalf("principal = %s, attendu %s", authenticated.Principal.ID, created.Principal.ID)
|
||||
}
|
||||
|
||||
_, _, err = service.ValidateSession(ctx, "mauvais-token")
|
||||
if !errors.Is(err, ErrInvalidSession) {
|
||||
t.Fatalf("erreur = %v, attendu ErrInvalidSession", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevokeSession(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", identity.RoleMember)
|
||||
|
||||
session, token, err := service.CreateSession(ctx, CreateSessionParams{
|
||||
PrincipalID: created.Principal.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession : %v", err)
|
||||
}
|
||||
|
||||
if err := service.RevokeSession(ctx, session.ID); err != nil {
|
||||
t.Fatalf("RevokeSession : %v", err)
|
||||
}
|
||||
|
||||
_, _, err = service.ValidateSession(ctx, token)
|
||||
if !errors.Is(err, ErrInvalidSession) {
|
||||
t.Fatalf("erreur = %v, attendu ErrInvalidSession", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevokeSessionByToken(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", identity.RoleMember)
|
||||
|
||||
_, token, err := service.CreateSession(ctx, CreateSessionParams{
|
||||
PrincipalID: created.Principal.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession : %v", err)
|
||||
}
|
||||
|
||||
if err := service.RevokeSessionByToken(ctx, token); err != nil {
|
||||
t.Fatalf("RevokeSessionByToken : %v", err)
|
||||
}
|
||||
|
||||
_, _, err = service.ValidateSession(ctx, token)
|
||||
if !errors.Is(err, ErrInvalidSession) {
|
||||
t.Fatalf("erreur = %v, attendu ErrInvalidSession", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListAndDeleteExpiredSessions(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", identity.RoleMember)
|
||||
|
||||
if _, _, err := service.CreateSession(ctx, CreateSessionParams{
|
||||
PrincipalID: created.Principal.ID,
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateSession : %v", err)
|
||||
}
|
||||
|
||||
sessions, err := service.ListSessions(ctx, created.Principal.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSessions : %v", err)
|
||||
}
|
||||
if len(sessions) != 1 {
|
||||
t.Fatalf("sessions = %d, attendu 1", len(sessions))
|
||||
}
|
||||
|
||||
deleted, err := service.DeleteExpiredSessions(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("DeleteExpiredSessions : %v", err)
|
||||
}
|
||||
if deleted != 0 {
|
||||
t.Fatalf("supprimées = %d, attendu 0", deleted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuestSession(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
guest, err := identity.NewService(service.db).CreateGuest(ctx, "jean")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateGuest : %v", err)
|
||||
}
|
||||
|
||||
session, token, err := service.CreateSession(ctx, CreateSessionParams{
|
||||
PrincipalID: guest.ID,
|
||||
Kind: "api",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession : %v", err)
|
||||
}
|
||||
if session.Kind != "api" {
|
||||
t.Fatalf("kind = %q, attendu api", session.Kind)
|
||||
}
|
||||
|
||||
_, authenticated, err := service.ValidateSession(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatalf("ValidateSession : %v", err)
|
||||
}
|
||||
if authenticated.Principal.ID != guest.ID {
|
||||
t.Fatalf("principal = %s, attendu %s", authenticated.Principal.ID, guest.ID)
|
||||
}
|
||||
if authenticated.Account.Login != "jean" {
|
||||
t.Fatalf("login = %q, attendu jean", authenticated.Account.Login)
|
||||
}
|
||||
if authenticated.Account.State != "active" {
|
||||
t.Fatalf("state = %q, attendu active", authenticated.Account.State)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSessionRejectsInactivePrincipal(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", identity.RoleMember)
|
||||
|
||||
_, err := service.db.WriteQueries.UpdatePrincipalStatus(ctx, database.UpdatePrincipalStatusParams{
|
||||
Status: "disabled",
|
||||
ID: created.Principal.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("UpdatePrincipalStatus : %v", err)
|
||||
}
|
||||
|
||||
_, _, err = service.CreateSession(ctx, CreateSessionParams{
|
||||
PrincipalID: created.Principal.ID,
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidSession) {
|
||||
t.Fatalf("erreur = %v, attendu ErrInvalidSession", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionExpiration(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", identity.RoleMember)
|
||||
|
||||
_, token, err := service.CreateSession(ctx, CreateSessionParams{
|
||||
PrincipalID: created.Principal.ID,
|
||||
TTL: time.Millisecond,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession : %v", err)
|
||||
}
|
||||
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
|
||||
_, _, err = service.ValidateSession(ctx, token)
|
||||
if !errors.Is(err, ErrInvalidSession) {
|
||||
t.Fatalf("erreur = %v, attendu ErrInvalidSession", err)
|
||||
}
|
||||
}
|
||||
+263
@@ -0,0 +1,263 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mediarr/database"
|
||||
"mediarr/ident"
|
||||
"mediarr/identity"
|
||||
)
|
||||
|
||||
const (
|
||||
maxFailedAttempts = 5
|
||||
lockDuration = 15 * time.Minute
|
||||
)
|
||||
|
||||
type CreateUserParams struct {
|
||||
Login string
|
||||
Password string
|
||||
Role string
|
||||
}
|
||||
|
||||
func (s *Service) CreateUser(ctx context.Context, params CreateUserParams) (*AuthenticatedUser, error) {
|
||||
display, key, err := normalizeLogin(params.Login)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validatePassword(params.Password); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
role := params.Role
|
||||
if role == "" {
|
||||
role = identity.RoleMember
|
||||
}
|
||||
|
||||
groupName, err := identity.GroupNameForRole(role)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
group, err := s.db.Queries.GetPrincipalByNameAndKind(ctx, database.GetPrincipalByNameAndKindParams{
|
||||
Kind: identity.KindGroup,
|
||||
Name: groupName,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, fmt.Errorf("%w: %s", identity.ErrGroupNotFound, groupName)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
passwordHash, err := HashPassword(params.Password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userID, err := ident.NewV7()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
|
||||
err = s.withTx(ctx, func(q *database.Queries) error {
|
||||
if _, err := q.CreatePrincipal(ctx, database.CreatePrincipalParams{
|
||||
ID: userID,
|
||||
Kind: identity.KindUser,
|
||||
Name: display,
|
||||
Status: "active",
|
||||
CreatedAt: now,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := q.CreateAccount(ctx, database.CreateAccountParams{
|
||||
PrincipalID: userID,
|
||||
Login: display,
|
||||
LoginKey: key,
|
||||
PasswordHash: sql.NullString{
|
||||
String: passwordHash,
|
||||
Valid: true,
|
||||
},
|
||||
PasswordChangedAt: sql.NullInt64{
|
||||
Int64: now,
|
||||
Valid: true,
|
||||
},
|
||||
MustChangePassword: 0,
|
||||
State: "active",
|
||||
FailedAttempts: 0,
|
||||
CreatedAt: now,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := q.CreateMembership(ctx, database.CreateMembershipParams{
|
||||
GroupID: group.ID,
|
||||
MemberID: userID,
|
||||
Role: identity.RoleMember,
|
||||
CreatedAt: now,
|
||||
})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return nil, fmt.Errorf("%w: %s", ErrLoginTaken, display)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.loadAuthenticatedUser(ctx, userID)
|
||||
}
|
||||
|
||||
func (s *Service) Authenticate(ctx context.Context, login, password string) (*AuthenticatedUser, error) {
|
||||
_, key, err := normalizeLogin(login)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
account, err := s.db.Queries.GetAccountByLoginKey(ctx, key)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
principal, err := s.db.Queries.GetPrincipal(ctx, account.PrincipalID)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if principal.Status != "active" {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
|
||||
switch account.State {
|
||||
case "disabled":
|
||||
return nil, ErrAccountDisabled
|
||||
case "locked":
|
||||
if !account.LockedUntil.Valid || account.LockedUntil.Int64 > now {
|
||||
return nil, ErrAccountLocked
|
||||
}
|
||||
if _, err := s.db.WriteQueries.UnlockAccount(ctx, account.PrincipalID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
account.State = "active"
|
||||
account.FailedAttempts = 0
|
||||
account.LockedUntil = sql.NullInt64{}
|
||||
}
|
||||
|
||||
if !account.PasswordHash.Valid {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
valid, err := VerifyPassword(password, account.PasswordHash.String)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
if !valid {
|
||||
updated, err := s.db.WriteQueries.RegisterFailedLogin(ctx, database.RegisterFailedLoginParams{
|
||||
MaxAttempts: maxFailedAttempts,
|
||||
LockedUntil: sql.NullInt64{
|
||||
Int64: now + lockDuration.Milliseconds(),
|
||||
Valid: true,
|
||||
},
|
||||
PrincipalID: account.PrincipalID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if updated.State == "locked" {
|
||||
return nil, ErrAccountLocked
|
||||
}
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
if _, err := s.db.WriteQueries.RecordLogin(ctx, database.RecordLoginParams{
|
||||
LastLoginAt: sql.NullInt64{
|
||||
Int64: now,
|
||||
Valid: true,
|
||||
},
|
||||
PrincipalID: account.PrincipalID,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.loadAuthenticatedUser(ctx, account.PrincipalID)
|
||||
}
|
||||
|
||||
func (s *Service) SetPassword(ctx context.Context, principalID ident.UUID, password string) error {
|
||||
if err := validatePassword(password); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
passwordHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
|
||||
_, err = s.db.WriteQueries.UpdatePassword(ctx, database.UpdatePasswordParams{
|
||||
PasswordHash: sql.NullString{
|
||||
String: passwordHash,
|
||||
Valid: true,
|
||||
},
|
||||
PasswordChangedAt: sql.NullInt64{
|
||||
Int64: now,
|
||||
Valid: true,
|
||||
},
|
||||
PrincipalID: principalID,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Service) loadAuthenticatedUser(ctx context.Context, id ident.UUID) (*AuthenticatedUser, error) {
|
||||
principal, err := s.identity.GetPrincipal(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
account, err := s.db.Queries.GetAccount(ctx, id)
|
||||
switch {
|
||||
case err == nil:
|
||||
return &AuthenticatedUser{
|
||||
Principal: *principal,
|
||||
Account: accountFromDB(account),
|
||||
}, nil
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return &AuthenticatedUser{
|
||||
Principal: *principal,
|
||||
Account: Account{
|
||||
PrincipalID: id,
|
||||
Login: principal.Name,
|
||||
State: "active",
|
||||
},
|
||||
}, nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func accountFromDB(account database.Account) Account {
|
||||
return Account{
|
||||
PrincipalID: account.PrincipalID,
|
||||
Login: account.Login,
|
||||
State: account.State,
|
||||
MustChangePassword: account.MustChangePassword != 0,
|
||||
FailedAttempts: account.FailedAttempts,
|
||||
LockedUntil: account.LockedUntil,
|
||||
LastLoginAt: account.LastLoginAt,
|
||||
CreatedAt: account.CreatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mediarr/database"
|
||||
"mediarr/identity"
|
||||
)
|
||||
|
||||
func TestCreateUser(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created, err := service.CreateUser(ctx, CreateUserParams{
|
||||
Login: "Alice",
|
||||
Password: "correct horse battery staple",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser : %v", err)
|
||||
}
|
||||
|
||||
if created.Principal.ID.IsZero() {
|
||||
t.Fatal("identifiant utilisateur vide")
|
||||
}
|
||||
if created.Account.Login != "Alice" {
|
||||
t.Fatalf("login = %q, attendu Alice", created.Account.Login)
|
||||
}
|
||||
if created.Principal.Name != "Alice" {
|
||||
t.Fatalf("name = %q, attendu Alice", created.Principal.Name)
|
||||
}
|
||||
if created.Principal.Status != "active" {
|
||||
t.Fatalf("status = %q, attendu active", created.Principal.Status)
|
||||
}
|
||||
if created.Account.State != "active" {
|
||||
t.Fatalf("état du compte = %q, attendu active", created.Account.State)
|
||||
}
|
||||
if len(created.Principal.Groups) != 1 || created.Principal.Groups[0].Name != "members" {
|
||||
t.Fatalf("groupes = %+v, attendu members", created.Principal.Groups)
|
||||
}
|
||||
|
||||
principal, err := service.db.Queries.GetPrincipal(ctx, created.Principal.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetPrincipal : %v", err)
|
||||
}
|
||||
if principal.Kind != identity.KindUser {
|
||||
t.Fatalf("kind = %q, attendu user", principal.Kind)
|
||||
}
|
||||
|
||||
account, err := service.db.Queries.GetAccountByLoginKey(ctx, "alice")
|
||||
if err != nil {
|
||||
t.Fatalf("GetAccountByLoginKey : %v", err)
|
||||
}
|
||||
if !account.PasswordHash.Valid {
|
||||
t.Fatal("hash du mot de passe absent")
|
||||
}
|
||||
if account.PasswordHash.String == "correct horse battery staple" {
|
||||
t.Fatal("le mot de passe est stocké en clair")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateUserRejectsDuplicateLogin(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
mustCreateUser(t, service, "alice", "correct horse battery staple", identity.RoleMember)
|
||||
|
||||
_, err := service.CreateUser(ctx, CreateUserParams{
|
||||
Login: "ALICE",
|
||||
Password: "another correct horse battery staple",
|
||||
})
|
||||
if !errors.Is(err, ErrLoginTaken) {
|
||||
t.Fatalf("erreur = %v, attendu ErrLoginTaken", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateUserRejectsInvalidInput(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := service.CreateUser(ctx, CreateUserParams{
|
||||
Login: " ",
|
||||
Password: "correct horse battery staple",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidLogin) {
|
||||
t.Fatalf("login vide : erreur = %v, attendu ErrInvalidLogin", err)
|
||||
}
|
||||
|
||||
_, err = service.CreateUser(ctx, CreateUserParams{
|
||||
Login: "alice",
|
||||
Password: "court",
|
||||
})
|
||||
if !errors.Is(err, ErrWeakPassword) {
|
||||
t.Fatalf("mot de passe faible : erreur = %v, attendu ErrWeakPassword", err)
|
||||
}
|
||||
|
||||
_, err = service.CreateUser(ctx, CreateUserParams{
|
||||
Login: "alice",
|
||||
Password: "correct horse battery staple",
|
||||
Role: "super-admin",
|
||||
})
|
||||
if !errors.Is(err, identity.ErrInvalidRole) {
|
||||
t.Fatalf("rôle invalide : erreur = %v, attendu ErrInvalidRole", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateUserAdmin(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
|
||||
created := mustCreateUser(t, service, "root", "correct horse battery staple", identity.RoleAdmin)
|
||||
|
||||
if len(created.Principal.Groups) != 1 || created.Principal.Groups[0].Name != "admins" {
|
||||
t.Fatalf("groupes = %+v, attendu admins", created.Principal.Groups)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticate(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", identity.RoleMember)
|
||||
|
||||
authenticated, err := service.Authenticate(ctx, "ALICE", "correct horse battery staple")
|
||||
if err != nil {
|
||||
t.Fatalf("Authenticate : %v", err)
|
||||
}
|
||||
if authenticated.Principal.ID != created.Principal.ID {
|
||||
t.Fatalf("id = %s, attendu %s", authenticated.Principal.ID, created.Principal.ID)
|
||||
}
|
||||
|
||||
account, err := service.db.Queries.GetAccount(ctx, created.Principal.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAccount : %v", err)
|
||||
}
|
||||
if !account.LastLoginAt.Valid {
|
||||
t.Fatal("last_login_at non renseigné")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticateRejectsUnknownLogin(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
|
||||
_, err := service.Authenticate(context.Background(), "inconnu", "correct horse battery staple")
|
||||
if !errors.Is(err, ErrInvalidCredentials) {
|
||||
t.Fatalf("erreur = %v, attendu ErrInvalidCredentials", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticateRejectsWrongPassword(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", identity.RoleMember)
|
||||
|
||||
_, err := service.Authenticate(ctx, "alice", "mauvais mot de passe")
|
||||
if !errors.Is(err, ErrInvalidCredentials) {
|
||||
t.Fatalf("erreur = %v, attendu ErrInvalidCredentials", err)
|
||||
}
|
||||
|
||||
account, err := service.db.Queries.GetAccount(ctx, created.Principal.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAccount : %v", err)
|
||||
}
|
||||
if account.FailedAttempts != 1 {
|
||||
t.Fatalf("failed_attempts = %d, attendu 1", account.FailedAttempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticateLocksAccountAfterTooManyFailures(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", identity.RoleMember)
|
||||
|
||||
for attempt := 1; attempt <= maxFailedAttempts; attempt++ {
|
||||
_, err := service.Authenticate(ctx, "alice", "mauvais mot de passe")
|
||||
if attempt < maxFailedAttempts {
|
||||
if !errors.Is(err, ErrInvalidCredentials) {
|
||||
t.Fatalf("tentative %d : erreur = %v, attendu ErrInvalidCredentials", attempt, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if !errors.Is(err, ErrAccountLocked) {
|
||||
t.Fatalf("tentative %d : erreur = %v, attendu ErrAccountLocked", attempt, err)
|
||||
}
|
||||
}
|
||||
|
||||
_, err := service.Authenticate(ctx, "alice", "correct horse battery staple")
|
||||
if !errors.Is(err, ErrAccountLocked) {
|
||||
t.Fatalf("erreur = %v, attendu ErrAccountLocked", err)
|
||||
}
|
||||
|
||||
account, err := service.db.Queries.GetAccount(ctx, created.Principal.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAccount : %v", err)
|
||||
}
|
||||
if account.State != "locked" {
|
||||
t.Fatalf("state = %q, attendu locked", account.State)
|
||||
}
|
||||
if !account.LockedUntil.Valid || account.LockedUntil.Int64 <= time.Now().UnixMilli() {
|
||||
t.Fatalf("locked_until = %+v, attendu dans le futur", account.LockedUntil)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticateUnlocksExpiredAccount(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", identity.RoleMember)
|
||||
|
||||
_, err := service.db.WriteQueries.LockAccount(ctx, database.LockAccountParams{
|
||||
LockedUntil: sql.NullInt64{
|
||||
Int64: time.Now().Add(-time.Minute).UnixMilli(),
|
||||
Valid: true,
|
||||
},
|
||||
PrincipalID: created.Principal.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("LockAccount : %v", err)
|
||||
}
|
||||
|
||||
_, err = service.Authenticate(ctx, "alice", "correct horse battery staple")
|
||||
if err != nil {
|
||||
t.Fatalf("Authenticate : %v", err)
|
||||
}
|
||||
|
||||
account, err := service.db.Queries.GetAccount(ctx, created.Principal.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAccount : %v", err)
|
||||
}
|
||||
if account.State != "active" {
|
||||
t.Fatalf("state = %q, attendu active", account.State)
|
||||
}
|
||||
if account.FailedAttempts != 0 {
|
||||
t.Fatalf("failed_attempts = %d, attendu 0", account.FailedAttempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticateRejectsDisabledAccount(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", identity.RoleMember)
|
||||
|
||||
_, err := service.db.WriteQueries.UpdateAccountState(ctx, database.UpdateAccountStateParams{
|
||||
State: "disabled",
|
||||
PrincipalID: created.Principal.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("UpdateAccountState : %v", err)
|
||||
}
|
||||
|
||||
_, err = service.Authenticate(ctx, "alice", "correct horse battery staple")
|
||||
if !errors.Is(err, ErrAccountDisabled) {
|
||||
t.Fatalf("erreur = %v, attendu ErrAccountDisabled", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetPassword(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", identity.RoleMember)
|
||||
|
||||
if err := service.SetPassword(ctx, created.Principal.ID, "nouveau correct horse battery staple"); err != nil {
|
||||
t.Fatalf("SetPassword : %v", err)
|
||||
}
|
||||
|
||||
_, err := service.Authenticate(ctx, "alice", "correct horse battery staple")
|
||||
if !errors.Is(err, ErrInvalidCredentials) {
|
||||
t.Fatalf("ancien mot de passe : erreur = %v, attendu ErrInvalidCredentials", err)
|
||||
}
|
||||
|
||||
_, err = service.Authenticate(ctx, "alice", "nouveau correct horse battery staple")
|
||||
if err != nil {
|
||||
t.Fatalf("nouveau mot de passe : %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user