Compare commits
2
Commits
7ebe8962dd
...
276a9fe320
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
276a9fe320 | ||
|
|
f7649f24ef |
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -196,6 +196,85 @@ func (q *Queries) CreatePrincipal(ctx context.Context, arg CreatePrincipalParams
|
|||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const createSession = `-- name: CreateSession :one
|
||||||
|
|
||||||
|
INSERT INTO session (
|
||||||
|
id,
|
||||||
|
token_hash,
|
||||||
|
principal_id,
|
||||||
|
kind,
|
||||||
|
label,
|
||||||
|
user_agent,
|
||||||
|
ip_prefix,
|
||||||
|
created_at,
|
||||||
|
last_seen_at,
|
||||||
|
expires_at,
|
||||||
|
idle_expires_at
|
||||||
|
) VALUES (
|
||||||
|
?1,
|
||||||
|
?2,
|
||||||
|
?3,
|
||||||
|
?4,
|
||||||
|
?5,
|
||||||
|
?6,
|
||||||
|
?7,
|
||||||
|
?8,
|
||||||
|
?9,
|
||||||
|
?10,
|
||||||
|
?11
|
||||||
|
)
|
||||||
|
RETURNING id, token_hash, principal_id, kind, label, user_agent, ip_prefix, created_at, last_seen_at, expires_at, idle_expires_at, revoked_at
|
||||||
|
`
|
||||||
|
|
||||||
|
type CreateSessionParams struct {
|
||||||
|
ID ident.UUID
|
||||||
|
TokenHash []byte
|
||||||
|
PrincipalID ident.UUID
|
||||||
|
Kind string
|
||||||
|
Label sql.NullString
|
||||||
|
UserAgent sql.NullString
|
||||||
|
IpPrefix sql.NullString
|
||||||
|
CreatedAt int64
|
||||||
|
LastSeenAt int64
|
||||||
|
ExpiresAt int64
|
||||||
|
IdleExpiresAt int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// session
|
||||||
|
// ============================================================================
|
||||||
|
func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (Session, error) {
|
||||||
|
row := q.db.QueryRowContext(ctx, createSession,
|
||||||
|
arg.ID,
|
||||||
|
arg.TokenHash,
|
||||||
|
arg.PrincipalID,
|
||||||
|
arg.Kind,
|
||||||
|
arg.Label,
|
||||||
|
arg.UserAgent,
|
||||||
|
arg.IpPrefix,
|
||||||
|
arg.CreatedAt,
|
||||||
|
arg.LastSeenAt,
|
||||||
|
arg.ExpiresAt,
|
||||||
|
arg.IdleExpiresAt,
|
||||||
|
)
|
||||||
|
var i Session
|
||||||
|
err := row.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.TokenHash,
|
||||||
|
&i.PrincipalID,
|
||||||
|
&i.Kind,
|
||||||
|
&i.Label,
|
||||||
|
&i.UserAgent,
|
||||||
|
&i.IpPrefix,
|
||||||
|
&i.CreatedAt,
|
||||||
|
&i.LastSeenAt,
|
||||||
|
&i.ExpiresAt,
|
||||||
|
&i.IdleExpiresAt,
|
||||||
|
&i.RevokedAt,
|
||||||
|
)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|
||||||
const deleteAccount = `-- name: DeleteAccount :exec
|
const deleteAccount = `-- name: DeleteAccount :exec
|
||||||
DELETE FROM account
|
DELETE FROM account
|
||||||
WHERE principal_id = ?1
|
WHERE principal_id = ?1
|
||||||
@@ -206,6 +285,20 @@ func (q *Queries) DeleteAccount(ctx context.Context, principalID ident.UUID) err
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const deleteExpiredSessions = `-- name: DeleteExpiredSessions :execrows
|
||||||
|
DELETE FROM session
|
||||||
|
WHERE expires_at <= ?1
|
||||||
|
OR idle_expires_at <= ?1
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) DeleteExpiredSessions(ctx context.Context, now int64) (int64, error) {
|
||||||
|
result, err := q.db.ExecContext(ctx, deleteExpiredSessions, now)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return result.RowsAffected()
|
||||||
|
}
|
||||||
|
|
||||||
const deleteMembership = `-- name: DeleteMembership :exec
|
const deleteMembership = `-- name: DeleteMembership :exec
|
||||||
DELETE FROM membership
|
DELETE FROM membership
|
||||||
WHERE group_id = ?1
|
WHERE group_id = ?1
|
||||||
@@ -401,6 +494,58 @@ func (q *Queries) GetPrincipalByNameAndKind(ctx context.Context, arg GetPrincipa
|
|||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const getSession = `-- name: GetSession :one
|
||||||
|
SELECT id, token_hash, principal_id, kind, label, user_agent, ip_prefix, created_at, last_seen_at, expires_at, idle_expires_at, revoked_at
|
||||||
|
FROM session
|
||||||
|
WHERE id = ?1
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) GetSession(ctx context.Context, id ident.UUID) (Session, error) {
|
||||||
|
row := q.db.QueryRowContext(ctx, getSession, id)
|
||||||
|
var i Session
|
||||||
|
err := row.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.TokenHash,
|
||||||
|
&i.PrincipalID,
|
||||||
|
&i.Kind,
|
||||||
|
&i.Label,
|
||||||
|
&i.UserAgent,
|
||||||
|
&i.IpPrefix,
|
||||||
|
&i.CreatedAt,
|
||||||
|
&i.LastSeenAt,
|
||||||
|
&i.ExpiresAt,
|
||||||
|
&i.IdleExpiresAt,
|
||||||
|
&i.RevokedAt,
|
||||||
|
)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|
||||||
|
const getSessionByTokenHash = `-- name: GetSessionByTokenHash :one
|
||||||
|
SELECT id, token_hash, principal_id, kind, label, user_agent, ip_prefix, created_at, last_seen_at, expires_at, idle_expires_at, revoked_at
|
||||||
|
FROM session
|
||||||
|
WHERE token_hash = ?1
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) GetSessionByTokenHash(ctx context.Context, tokenHash []byte) (Session, error) {
|
||||||
|
row := q.db.QueryRowContext(ctx, getSessionByTokenHash, tokenHash)
|
||||||
|
var i Session
|
||||||
|
err := row.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.TokenHash,
|
||||||
|
&i.PrincipalID,
|
||||||
|
&i.Kind,
|
||||||
|
&i.Label,
|
||||||
|
&i.UserAgent,
|
||||||
|
&i.IpPrefix,
|
||||||
|
&i.CreatedAt,
|
||||||
|
&i.LastSeenAt,
|
||||||
|
&i.ExpiresAt,
|
||||||
|
&i.IdleExpiresAt,
|
||||||
|
&i.RevokedAt,
|
||||||
|
)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|
||||||
const incrementFailedAttempts = `-- name: IncrementFailedAttempts :one
|
const incrementFailedAttempts = `-- name: IncrementFailedAttempts :one
|
||||||
UPDATE account
|
UPDATE account
|
||||||
SET failed_attempts = failed_attempts + 1
|
SET failed_attempts = failed_attempts + 1
|
||||||
@@ -506,6 +651,49 @@ func (q *Queries) ListGroupMembers(ctx context.Context, groupID ident.UUID) ([]P
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const listGroupMembersWithRole = `-- name: ListGroupMembersWithRole :many
|
||||||
|
SELECT p.id, p.name, p.kind, m.role
|
||||||
|
FROM membership m
|
||||||
|
JOIN principal p ON p.id = m.member_id
|
||||||
|
WHERE m.group_id = ?1
|
||||||
|
ORDER BY p.name
|
||||||
|
`
|
||||||
|
|
||||||
|
type ListGroupMembersWithRoleRow struct {
|
||||||
|
ID ident.UUID
|
||||||
|
Name string
|
||||||
|
Kind string
|
||||||
|
Role string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) ListGroupMembersWithRole(ctx context.Context, groupID ident.UUID) ([]ListGroupMembersWithRoleRow, error) {
|
||||||
|
rows, err := q.db.QueryContext(ctx, listGroupMembersWithRole, groupID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var items []ListGroupMembersWithRoleRow
|
||||||
|
for rows.Next() {
|
||||||
|
var i ListGroupMembersWithRoleRow
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.Name,
|
||||||
|
&i.Kind,
|
||||||
|
&i.Role,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Close(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
const listMemberGroups = `-- name: ListMemberGroups :many
|
const listMemberGroups = `-- name: ListMemberGroups :many
|
||||||
SELECT p.id, p.kind, p.name, p.public_key, p.status, p.successor_id, p.created_at, p.disabled_at
|
SELECT p.id, p.kind, p.name, p.public_key, p.status, p.successor_id, p.created_at, p.disabled_at
|
||||||
FROM membership m
|
FROM membership m
|
||||||
@@ -546,6 +734,43 @@ func (q *Queries) ListMemberGroups(ctx context.Context, memberID ident.UUID) ([]
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const listMemberGroupsWithRole = `-- name: ListMemberGroupsWithRole :many
|
||||||
|
SELECT p.id, p.name, m.role
|
||||||
|
FROM membership m
|
||||||
|
JOIN principal p ON p.id = m.group_id
|
||||||
|
WHERE m.member_id = ?1
|
||||||
|
ORDER BY p.name
|
||||||
|
`
|
||||||
|
|
||||||
|
type ListMemberGroupsWithRoleRow struct {
|
||||||
|
ID ident.UUID
|
||||||
|
Name string
|
||||||
|
Role string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) ListMemberGroupsWithRole(ctx context.Context, memberID ident.UUID) ([]ListMemberGroupsWithRoleRow, error) {
|
||||||
|
rows, err := q.db.QueryContext(ctx, listMemberGroupsWithRole, memberID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var items []ListMemberGroupsWithRoleRow
|
||||||
|
for rows.Next() {
|
||||||
|
var i ListMemberGroupsWithRoleRow
|
||||||
|
if err := rows.Scan(&i.ID, &i.Name, &i.Role); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Close(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
const listMembershipsByGroup = `-- name: ListMembershipsByGroup :many
|
const listMembershipsByGroup = `-- name: ListMembershipsByGroup :many
|
||||||
SELECT group_id, member_id, role, created_at
|
SELECT group_id, member_id, role, created_at
|
||||||
FROM membership
|
FROM membership
|
||||||
@@ -693,6 +918,49 @@ func (q *Queries) ListPrincipalsByKind(ctx context.Context, kind string) ([]Prin
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const listSessionsByPrincipal = `-- name: ListSessionsByPrincipal :many
|
||||||
|
SELECT id, token_hash, principal_id, kind, label, user_agent, ip_prefix, created_at, last_seen_at, expires_at, idle_expires_at, revoked_at
|
||||||
|
FROM session
|
||||||
|
WHERE principal_id = ?1
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) ListSessionsByPrincipal(ctx context.Context, principalID ident.UUID) ([]Session, error) {
|
||||||
|
rows, err := q.db.QueryContext(ctx, listSessionsByPrincipal, principalID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var items []Session
|
||||||
|
for rows.Next() {
|
||||||
|
var i Session
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.TokenHash,
|
||||||
|
&i.PrincipalID,
|
||||||
|
&i.Kind,
|
||||||
|
&i.Label,
|
||||||
|
&i.UserAgent,
|
||||||
|
&i.IpPrefix,
|
||||||
|
&i.CreatedAt,
|
||||||
|
&i.LastSeenAt,
|
||||||
|
&i.ExpiresAt,
|
||||||
|
&i.IdleExpiresAt,
|
||||||
|
&i.RevokedAt,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Close(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
const lockAccount = `-- name: LockAccount :one
|
const lockAccount = `-- name: LockAccount :one
|
||||||
UPDATE account
|
UPDATE account
|
||||||
SET state = 'locked',
|
SET state = 'locked',
|
||||||
@@ -758,6 +1026,46 @@ func (q *Queries) RecordLogin(ctx context.Context, arg RecordLoginParams) (Accou
|
|||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const registerFailedLogin = `-- name: RegisterFailedLogin :one
|
||||||
|
UPDATE account
|
||||||
|
SET failed_attempts = failed_attempts + 1,
|
||||||
|
state = CASE
|
||||||
|
WHEN failed_attempts + 1 >= ?1 THEN 'locked'
|
||||||
|
ELSE state
|
||||||
|
END,
|
||||||
|
locked_until = CASE
|
||||||
|
WHEN failed_attempts + 1 >= ?1 THEN ?2
|
||||||
|
ELSE locked_until
|
||||||
|
END
|
||||||
|
WHERE principal_id = ?3
|
||||||
|
RETURNING principal_id, login, login_key, password_hash, password_changed_at, must_change_password, state, failed_attempts, locked_until, last_login_at, created_at
|
||||||
|
`
|
||||||
|
|
||||||
|
type RegisterFailedLoginParams struct {
|
||||||
|
MaxAttempts int64
|
||||||
|
LockedUntil sql.NullInt64
|
||||||
|
PrincipalID ident.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) RegisterFailedLogin(ctx context.Context, arg RegisterFailedLoginParams) (Account, error) {
|
||||||
|
row := q.db.QueryRowContext(ctx, registerFailedLogin, arg.MaxAttempts, arg.LockedUntil, arg.PrincipalID)
|
||||||
|
var i Account
|
||||||
|
err := row.Scan(
|
||||||
|
&i.PrincipalID,
|
||||||
|
&i.Login,
|
||||||
|
&i.LoginKey,
|
||||||
|
&i.PasswordHash,
|
||||||
|
&i.PasswordChangedAt,
|
||||||
|
&i.MustChangePassword,
|
||||||
|
&i.State,
|
||||||
|
&i.FailedAttempts,
|
||||||
|
&i.LockedUntil,
|
||||||
|
&i.LastLoginAt,
|
||||||
|
&i.CreatedAt,
|
||||||
|
)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|
||||||
const resetFailedAttempts = `-- name: ResetFailedAttempts :one
|
const resetFailedAttempts = `-- name: ResetFailedAttempts :one
|
||||||
UPDATE account
|
UPDATE account
|
||||||
SET failed_attempts = 0,
|
SET failed_attempts = 0,
|
||||||
@@ -785,6 +1093,104 @@ func (q *Queries) ResetFailedAttempts(ctx context.Context, principalID ident.UUI
|
|||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const revokeSession = `-- name: RevokeSession :one
|
||||||
|
UPDATE session
|
||||||
|
SET revoked_at = ?1
|
||||||
|
WHERE id = ?2
|
||||||
|
RETURNING id, token_hash, principal_id, kind, label, user_agent, ip_prefix, created_at, last_seen_at, expires_at, idle_expires_at, revoked_at
|
||||||
|
`
|
||||||
|
|
||||||
|
type RevokeSessionParams struct {
|
||||||
|
RevokedAt sql.NullInt64
|
||||||
|
ID ident.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) RevokeSession(ctx context.Context, arg RevokeSessionParams) (Session, error) {
|
||||||
|
row := q.db.QueryRowContext(ctx, revokeSession, arg.RevokedAt, arg.ID)
|
||||||
|
var i Session
|
||||||
|
err := row.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.TokenHash,
|
||||||
|
&i.PrincipalID,
|
||||||
|
&i.Kind,
|
||||||
|
&i.Label,
|
||||||
|
&i.UserAgent,
|
||||||
|
&i.IpPrefix,
|
||||||
|
&i.CreatedAt,
|
||||||
|
&i.LastSeenAt,
|
||||||
|
&i.ExpiresAt,
|
||||||
|
&i.IdleExpiresAt,
|
||||||
|
&i.RevokedAt,
|
||||||
|
)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|
||||||
|
const revokeSessionByTokenHash = `-- name: RevokeSessionByTokenHash :one
|
||||||
|
UPDATE session
|
||||||
|
SET revoked_at = ?1
|
||||||
|
WHERE token_hash = ?2
|
||||||
|
RETURNING id, token_hash, principal_id, kind, label, user_agent, ip_prefix, created_at, last_seen_at, expires_at, idle_expires_at, revoked_at
|
||||||
|
`
|
||||||
|
|
||||||
|
type RevokeSessionByTokenHashParams struct {
|
||||||
|
RevokedAt sql.NullInt64
|
||||||
|
TokenHash []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) RevokeSessionByTokenHash(ctx context.Context, arg RevokeSessionByTokenHashParams) (Session, error) {
|
||||||
|
row := q.db.QueryRowContext(ctx, revokeSessionByTokenHash, arg.RevokedAt, arg.TokenHash)
|
||||||
|
var i Session
|
||||||
|
err := row.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.TokenHash,
|
||||||
|
&i.PrincipalID,
|
||||||
|
&i.Kind,
|
||||||
|
&i.Label,
|
||||||
|
&i.UserAgent,
|
||||||
|
&i.IpPrefix,
|
||||||
|
&i.CreatedAt,
|
||||||
|
&i.LastSeenAt,
|
||||||
|
&i.ExpiresAt,
|
||||||
|
&i.IdleExpiresAt,
|
||||||
|
&i.RevokedAt,
|
||||||
|
)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|
||||||
|
const touchSession = `-- name: TouchSession :one
|
||||||
|
UPDATE session
|
||||||
|
SET last_seen_at = ?1,
|
||||||
|
idle_expires_at = ?2
|
||||||
|
WHERE id = ?3
|
||||||
|
RETURNING id, token_hash, principal_id, kind, label, user_agent, ip_prefix, created_at, last_seen_at, expires_at, idle_expires_at, revoked_at
|
||||||
|
`
|
||||||
|
|
||||||
|
type TouchSessionParams struct {
|
||||||
|
LastSeenAt int64
|
||||||
|
IdleExpiresAt int64
|
||||||
|
ID ident.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) TouchSession(ctx context.Context, arg TouchSessionParams) (Session, error) {
|
||||||
|
row := q.db.QueryRowContext(ctx, touchSession, arg.LastSeenAt, arg.IdleExpiresAt, arg.ID)
|
||||||
|
var i Session
|
||||||
|
err := row.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.TokenHash,
|
||||||
|
&i.PrincipalID,
|
||||||
|
&i.Kind,
|
||||||
|
&i.Label,
|
||||||
|
&i.UserAgent,
|
||||||
|
&i.IpPrefix,
|
||||||
|
&i.CreatedAt,
|
||||||
|
&i.LastSeenAt,
|
||||||
|
&i.ExpiresAt,
|
||||||
|
&i.IdleExpiresAt,
|
||||||
|
&i.RevokedAt,
|
||||||
|
)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|
||||||
const unlockAccount = `-- name: UnlockAccount :one
|
const unlockAccount = `-- name: UnlockAccount :one
|
||||||
UPDATE account
|
UPDATE account
|
||||||
SET state = 'active',
|
SET state = 'active',
|
||||||
|
|||||||
@@ -154,6 +154,20 @@ DELETE FROM membership
|
|||||||
WHERE group_id = sqlc.arg(group_id)
|
WHERE group_id = sqlc.arg(group_id)
|
||||||
AND member_id = sqlc.arg(member_id);
|
AND member_id = sqlc.arg(member_id);
|
||||||
|
|
||||||
|
-- name: ListMemberGroupsWithRole :many
|
||||||
|
SELECT p.id, p.name, m.role
|
||||||
|
FROM membership m
|
||||||
|
JOIN principal p ON p.id = m.group_id
|
||||||
|
WHERE m.member_id = sqlc.arg(member_id)
|
||||||
|
ORDER BY p.name;
|
||||||
|
|
||||||
|
-- name: ListGroupMembersWithRole :many
|
||||||
|
SELECT p.id, p.name, p.kind, m.role
|
||||||
|
FROM membership m
|
||||||
|
JOIN principal p ON p.id = m.member_id
|
||||||
|
WHERE m.group_id = sqlc.arg(group_id)
|
||||||
|
ORDER BY p.name;
|
||||||
|
|
||||||
-- ============================================================================
|
-- ============================================================================
|
||||||
-- account
|
-- account
|
||||||
-- ============================================================================
|
-- ============================================================================
|
||||||
@@ -251,3 +265,89 @@ RETURNING *;
|
|||||||
-- name: DeleteAccount :exec
|
-- name: DeleteAccount :exec
|
||||||
DELETE FROM account
|
DELETE FROM account
|
||||||
WHERE principal_id = sqlc.arg(principal_id);
|
WHERE principal_id = sqlc.arg(principal_id);
|
||||||
|
|
||||||
|
-- name: RegisterFailedLogin :one
|
||||||
|
UPDATE account
|
||||||
|
SET failed_attempts = failed_attempts + 1,
|
||||||
|
state = CASE
|
||||||
|
WHEN failed_attempts + 1 >= sqlc.arg(max_attempts) THEN 'locked'
|
||||||
|
ELSE state
|
||||||
|
END,
|
||||||
|
locked_until = CASE
|
||||||
|
WHEN failed_attempts + 1 >= sqlc.arg(max_attempts) THEN sqlc.arg(locked_until)
|
||||||
|
ELSE locked_until
|
||||||
|
END
|
||||||
|
WHERE principal_id = sqlc.arg(principal_id)
|
||||||
|
RETURNING *;
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- session
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
-- name: CreateSession :one
|
||||||
|
INSERT INTO session (
|
||||||
|
id,
|
||||||
|
token_hash,
|
||||||
|
principal_id,
|
||||||
|
kind,
|
||||||
|
label,
|
||||||
|
user_agent,
|
||||||
|
ip_prefix,
|
||||||
|
created_at,
|
||||||
|
last_seen_at,
|
||||||
|
expires_at,
|
||||||
|
idle_expires_at
|
||||||
|
) VALUES (
|
||||||
|
sqlc.arg(id),
|
||||||
|
sqlc.arg(token_hash),
|
||||||
|
sqlc.arg(principal_id),
|
||||||
|
sqlc.arg(kind),
|
||||||
|
sqlc.narg(label),
|
||||||
|
sqlc.narg(user_agent),
|
||||||
|
sqlc.narg(ip_prefix),
|
||||||
|
sqlc.arg(created_at),
|
||||||
|
sqlc.arg(last_seen_at),
|
||||||
|
sqlc.arg(expires_at),
|
||||||
|
sqlc.arg(idle_expires_at)
|
||||||
|
)
|
||||||
|
RETURNING *;
|
||||||
|
|
||||||
|
-- name: GetSession :one
|
||||||
|
SELECT *
|
||||||
|
FROM session
|
||||||
|
WHERE id = sqlc.arg(id);
|
||||||
|
|
||||||
|
-- name: GetSessionByTokenHash :one
|
||||||
|
SELECT *
|
||||||
|
FROM session
|
||||||
|
WHERE token_hash = sqlc.arg(token_hash);
|
||||||
|
|
||||||
|
-- name: TouchSession :one
|
||||||
|
UPDATE session
|
||||||
|
SET last_seen_at = sqlc.arg(last_seen_at),
|
||||||
|
idle_expires_at = sqlc.arg(idle_expires_at)
|
||||||
|
WHERE id = sqlc.arg(id)
|
||||||
|
RETURNING *;
|
||||||
|
|
||||||
|
-- name: RevokeSession :one
|
||||||
|
UPDATE session
|
||||||
|
SET revoked_at = sqlc.arg(revoked_at)
|
||||||
|
WHERE id = sqlc.arg(id)
|
||||||
|
RETURNING *;
|
||||||
|
|
||||||
|
-- name: RevokeSessionByTokenHash :one
|
||||||
|
UPDATE session
|
||||||
|
SET revoked_at = sqlc.arg(revoked_at)
|
||||||
|
WHERE token_hash = sqlc.arg(token_hash)
|
||||||
|
RETURNING *;
|
||||||
|
|
||||||
|
-- name: ListSessionsByPrincipal :many
|
||||||
|
SELECT *
|
||||||
|
FROM session
|
||||||
|
WHERE principal_id = sqlc.arg(principal_id)
|
||||||
|
ORDER BY created_at DESC;
|
||||||
|
|
||||||
|
-- name: DeleteExpiredSessions :execrows
|
||||||
|
DELETE FROM session
|
||||||
|
WHERE expires_at <= sqlc.arg(now)
|
||||||
|
OR idle_expires_at <= sqlc.arg(now);
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ go 1.26.7
|
|||||||
require (
|
require (
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
github.com/pressly/goose/v3 v3.30.1
|
github.com/pressly/goose/v3 v3.30.1
|
||||||
|
golang.org/x/crypto v0.59.0
|
||||||
modernc.org/sqlite v1.62.0
|
modernc.org/sqlite v1.62.0
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
|||||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||||
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
|
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
|
||||||
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||||
|
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||||
|
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||||
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
|
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
|
||||||
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
|
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
|
||||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
package identity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"mediarr/database"
|
||||||
|
"mediarr/ident"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GroupNameForRole(role string) (string, error) {
|
||||||
|
switch role {
|
||||||
|
case RoleAdmin:
|
||||||
|
return "admins", nil
|
||||||
|
case RoleMember:
|
||||||
|
return "members", nil
|
||||||
|
default:
|
||||||
|
return "", fmt.Errorf("%w: %q", ErrInvalidRole, role)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) AddMember(ctx context.Context, groupID, memberID ident.UUID, role string) error {
|
||||||
|
if role == "" {
|
||||||
|
role = RoleMember
|
||||||
|
}
|
||||||
|
if role != RoleAdmin && role != RoleMember {
|
||||||
|
return fmt.Errorf("%w: %q", ErrInvalidRole, role)
|
||||||
|
}
|
||||||
|
|
||||||
|
group, err := s.db.Queries.GetPrincipal(ctx, groupID)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return ErrGroupNotFound
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if group.Kind != KindGroup {
|
||||||
|
return fmt.Errorf("%w: %s", ErrInvalidGroup, group.Kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
member, err := s.db.Queries.GetPrincipal(ctx, memberID)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return ErrInvalidMember
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if member.Kind != KindUser && member.Kind != KindGuest {
|
||||||
|
return fmt.Errorf("%w: %s", ErrInvalidMember, member.Kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = s.db.WriteQueries.CreateMembership(ctx, database.CreateMembershipParams{
|
||||||
|
GroupID: groupID,
|
||||||
|
MemberID: memberID,
|
||||||
|
Role: role,
|
||||||
|
CreatedAt: time.Now().UnixMilli(),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if isUniqueViolation(err) {
|
||||||
|
return fmt.Errorf("%w: %s dans %s", ErrAlreadyMember, member.Name, group.Name)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) RemoveMember(ctx context.Context, groupID, memberID ident.UUID) error {
|
||||||
|
_, err := s.db.Queries.GetMembership(ctx, database.GetMembershipParams{
|
||||||
|
GroupID: groupID,
|
||||||
|
MemberID: memberID,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return ErrNotMember
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.db.WriteQueries.DeleteMembership(ctx, database.DeleteMembershipParams{
|
||||||
|
GroupID: groupID,
|
||||||
|
MemberID: memberID,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ListGroups(ctx context.Context, memberID ident.UUID) ([]Group, error) {
|
||||||
|
rows, err := s.db.Queries.ListMemberGroupsWithRole(ctx, memberID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
groups := make([]Group, 0, len(rows))
|
||||||
|
for _, row := range rows {
|
||||||
|
groups = append(groups, Group{
|
||||||
|
ID: row.ID,
|
||||||
|
Name: row.Name,
|
||||||
|
Role: row.Role,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return groups, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ListGroupMembers(ctx context.Context, groupID ident.UUID) ([]Member, error) {
|
||||||
|
rows, err := s.db.Queries.ListGroupMembersWithRole(ctx, groupID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
members := make([]Member, 0, len(rows))
|
||||||
|
for _, row := range rows {
|
||||||
|
members = append(members, Member{
|
||||||
|
ID: row.ID,
|
||||||
|
Name: row.Name,
|
||||||
|
Kind: row.Kind,
|
||||||
|
Role: row.Role,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return members, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package identity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAddAndRemoveMember(t *testing.T) {
|
||||||
|
service := newTestService(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
user := mustCreatePrincipal(t, service, KindUser, "alice")
|
||||||
|
members := mustGroup(t, service, "members")
|
||||||
|
admins := mustGroup(t, service, "admins")
|
||||||
|
|
||||||
|
if err := service.AddMember(ctx, members.ID, user.ID, RoleMember); err != nil {
|
||||||
|
t.Fatalf("AddMember(members) : %v", err)
|
||||||
|
}
|
||||||
|
if err := service.AddMember(ctx, admins.ID, user.ID, RoleAdmin); err != nil {
|
||||||
|
t.Fatalf("AddMember(admins) : %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
groups, err := service.ListGroups(ctx, user.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ListGroups : %v", err)
|
||||||
|
}
|
||||||
|
if !hasGroup(groups, "members") || !hasGroup(groups, "admins") {
|
||||||
|
t.Fatalf("groupes = %+v, attendu members et admins", groups)
|
||||||
|
}
|
||||||
|
|
||||||
|
list, err := service.ListGroupMembers(ctx, admins.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ListGroupMembers : %v", err)
|
||||||
|
}
|
||||||
|
if len(list) != 1 || list[0].ID != user.ID || list[0].Role != RoleAdmin {
|
||||||
|
t.Fatalf("membres = %+v, attendu alice admin", list)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := service.RemoveMember(ctx, admins.ID, user.ID); err != nil {
|
||||||
|
t.Fatalf("RemoveMember : %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := service.RemoveMember(ctx, admins.ID, user.ID); !errors.Is(err, ErrNotMember) {
|
||||||
|
t.Fatalf("erreur = %v, attendu ErrNotMember", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAddMemberRejectsDuplicate(t *testing.T) {
|
||||||
|
service := newTestService(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
user := mustCreatePrincipal(t, service, KindUser, "alice")
|
||||||
|
members := mustGroup(t, service, "members")
|
||||||
|
|
||||||
|
if err := service.AddMember(ctx, members.ID, user.ID, RoleMember); err != nil {
|
||||||
|
t.Fatalf("AddMember : %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err := service.AddMember(ctx, members.ID, user.ID, RoleMember)
|
||||||
|
if !errors.Is(err, ErrAlreadyMember) {
|
||||||
|
t.Fatalf("erreur = %v, attendu ErrAlreadyMember", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAddMemberRejectsInvalidMember(t *testing.T) {
|
||||||
|
service := newTestService(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
user := mustCreatePrincipal(t, service, KindUser, "alice")
|
||||||
|
members := mustGroup(t, service, "members")
|
||||||
|
|
||||||
|
err := service.AddMember(ctx, members.ID, members.ID, RoleMember)
|
||||||
|
if !errors.Is(err, ErrInvalidMember) {
|
||||||
|
t.Fatalf("erreur = %v, attendu ErrInvalidMember", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = service.AddMember(ctx, user.ID, user.ID, RoleMember)
|
||||||
|
if !errors.Is(err, ErrInvalidGroup) {
|
||||||
|
t.Fatalf("erreur = %v, attendu ErrInvalidGroup", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGroupNameForRole(t *testing.T) {
|
||||||
|
name, err := GroupNameForRole(RoleAdmin)
|
||||||
|
if err != nil || name != "admins" {
|
||||||
|
t.Fatalf("admin : name = %q, err = %v", name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
name, err = GroupNameForRole(RoleMember)
|
||||||
|
if err != nil || name != "members" {
|
||||||
|
t.Fatalf("member : name = %q, err = %v", name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := GroupNameForRole("super-admin"); !errors.Is(err, ErrInvalidRole) {
|
||||||
|
t.Fatalf("erreur = %v, attendu ErrInvalidRole", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasGroup(groups []Group, name string) bool {
|
||||||
|
for _, group := range groups {
|
||||||
|
if group.Name == name {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package identity
|
||||||
|
|
||||||
|
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 mustCreatePrincipal(t *testing.T, service *Service, kind, name string) *Principal {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
created, err := service.CreatePrincipal(context.Background(), CreatePrincipalParams{
|
||||||
|
Kind: kind,
|
||||||
|
Name: name,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreatePrincipal(%q) : %v", name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return created
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustGroup(t *testing.T, service *Service, name string) database.Principal {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
group, err := service.db.Queries.GetPrincipalByNameAndKind(context.Background(), database.GetPrincipalByNameAndKindParams{
|
||||||
|
Kind: KindGroup,
|
||||||
|
Name: name,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("groupe %q : %v", name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return group
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package identity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"mediarr/ident"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
KindCluster = "cluster"
|
||||||
|
KindUser = "user"
|
||||||
|
KindGuest = "guest"
|
||||||
|
KindGroup = "group"
|
||||||
|
KindSystem = "system"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
RoleAdmin = "admin"
|
||||||
|
RoleMember = "member"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Principal struct {
|
||||||
|
ID ident.UUID
|
||||||
|
Kind string
|
||||||
|
Name string
|
||||||
|
Status string
|
||||||
|
CreatedAt int64
|
||||||
|
Groups []Group
|
||||||
|
}
|
||||||
|
|
||||||
|
type Group struct {
|
||||||
|
ID ident.UUID
|
||||||
|
Name string
|
||||||
|
Role string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Member struct {
|
||||||
|
ID ident.UUID
|
||||||
|
Name string
|
||||||
|
Kind string
|
||||||
|
Role string
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrInvalidRole = errors.New("rôle invalide")
|
||||||
|
ErrAlreadyMember = errors.New("membre déjà présent dans le groupe")
|
||||||
|
ErrNotMember = errors.New("membre absent du groupe")
|
||||||
|
ErrInvalidMember = errors.New("membre invalide : utilisateur ou invité attendu")
|
||||||
|
ErrInvalidGroup = errors.New("groupe invalide")
|
||||||
|
ErrGroupNotFound = errors.New("groupe introuvable")
|
||||||
|
ErrNameTaken = errors.New("nom déjà utilisé")
|
||||||
|
ErrInvalidKind = errors.New("type de principal invalide")
|
||||||
|
ErrInvalidName = errors.New("nom invalide")
|
||||||
|
ErrInvalidStatus = errors.New("statut de principal invalide")
|
||||||
|
)
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
package identity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"mediarr/database"
|
||||||
|
"mediarr/ident"
|
||||||
|
)
|
||||||
|
|
||||||
|
const maxNameLen = 255
|
||||||
|
|
||||||
|
type CreatePrincipalParams struct {
|
||||||
|
Kind string
|
||||||
|
Name string
|
||||||
|
PublicKey []byte
|
||||||
|
Status string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) CreatePrincipal(ctx context.Context, params CreatePrincipalParams) (*Principal, error) {
|
||||||
|
if !validKind(params.Kind) {
|
||||||
|
return nil, fmt.Errorf("%w: %q", ErrInvalidKind, params.Kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
name := strings.TrimSpace(params.Name)
|
||||||
|
if name == "" || len(name) > maxNameLen {
|
||||||
|
return nil, fmt.Errorf("%w: %q", ErrInvalidName, params.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
status := params.Status
|
||||||
|
if status == "" {
|
||||||
|
status = "active"
|
||||||
|
}
|
||||||
|
if status != "active" && status != "disabled" && status != "revoked" {
|
||||||
|
return nil, fmt.Errorf("%w: %q", ErrInvalidStatus, status)
|
||||||
|
}
|
||||||
|
|
||||||
|
if params.Kind == KindCluster && len(params.PublicKey) == 0 {
|
||||||
|
return nil, fmt.Errorf("%w: clé publique requise pour un cluster", ErrInvalidKind)
|
||||||
|
}
|
||||||
|
|
||||||
|
id, err := ident.NewV7()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = s.db.WriteQueries.CreatePrincipal(ctx, database.CreatePrincipalParams{
|
||||||
|
ID: id,
|
||||||
|
Kind: params.Kind,
|
||||||
|
Name: name,
|
||||||
|
PublicKey: params.PublicKey,
|
||||||
|
Status: status,
|
||||||
|
CreatedAt: time.Now().UnixMilli(),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if isUniqueViolation(err) {
|
||||||
|
return nil, fmt.Errorf("%w: %s", ErrNameTaken, name)
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.GetPrincipal(ctx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) CreateGuest(ctx context.Context, name string) (*Principal, error) {
|
||||||
|
group, err := s.groupByName(ctx, "guests")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
if name == "" || len(name) > maxNameLen {
|
||||||
|
return nil, fmt.Errorf("%w: %q", ErrInvalidName, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
id, 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: id,
|
||||||
|
Kind: KindGuest,
|
||||||
|
Name: name,
|
||||||
|
Status: "active",
|
||||||
|
CreatedAt: now,
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := q.CreateMembership(ctx, database.CreateMembershipParams{
|
||||||
|
GroupID: group.ID,
|
||||||
|
MemberID: id,
|
||||||
|
Role: RoleMember,
|
||||||
|
CreatedAt: now,
|
||||||
|
})
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if isUniqueViolation(err) {
|
||||||
|
return nil, fmt.Errorf("%w: %s", ErrNameTaken, name)
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.GetPrincipal(ctx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetPrincipal(ctx context.Context, id ident.UUID) (*Principal, error) {
|
||||||
|
principal, err := s.db.Queries.GetPrincipal(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
groups, err := s.ListGroups(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Principal{
|
||||||
|
ID: principal.ID,
|
||||||
|
Kind: principal.Kind,
|
||||||
|
Name: principal.Name,
|
||||||
|
Status: principal.Status,
|
||||||
|
CreatedAt: principal.CreatedAt,
|
||||||
|
Groups: groups,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validKind(kind string) bool {
|
||||||
|
switch kind {
|
||||||
|
case KindCluster, KindUser, KindGuest, KindGroup, KindSystem:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package identity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCreatePrincipal(t *testing.T) {
|
||||||
|
service := newTestService(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
created, err := service.CreatePrincipal(ctx, CreatePrincipalParams{
|
||||||
|
Kind: KindUser,
|
||||||
|
Name: "alice",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreatePrincipal : %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if created.ID.IsZero() {
|
||||||
|
t.Fatal("identifiant vide")
|
||||||
|
}
|
||||||
|
if created.Kind != KindUser {
|
||||||
|
t.Fatalf("kind = %q, attendu %q", created.Kind, KindUser)
|
||||||
|
}
|
||||||
|
if created.Name != "alice" {
|
||||||
|
t.Fatalf("name = %q, attendu alice", created.Name)
|
||||||
|
}
|
||||||
|
if created.Status != "active" {
|
||||||
|
t.Fatalf("status = %q, attendu active", created.Status)
|
||||||
|
}
|
||||||
|
if len(created.Groups) != 0 {
|
||||||
|
t.Fatalf("groupes = %+v, attendu aucun", created.Groups)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreatePrincipalRejectsDuplicateName(t *testing.T) {
|
||||||
|
service := newTestService(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
mustCreatePrincipal(t, service, KindUser, "alice")
|
||||||
|
|
||||||
|
_, err := service.CreatePrincipal(ctx, CreatePrincipalParams{
|
||||||
|
Kind: KindUser,
|
||||||
|
Name: "alice",
|
||||||
|
})
|
||||||
|
if !errors.Is(err, ErrNameTaken) {
|
||||||
|
t.Fatalf("erreur = %v, attendu ErrNameTaken", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreatePrincipalRejectsInvalidKind(t *testing.T) {
|
||||||
|
service := newTestService(t)
|
||||||
|
|
||||||
|
_, err := service.CreatePrincipal(context.Background(), CreatePrincipalParams{
|
||||||
|
Kind: "robot",
|
||||||
|
Name: "r2d2",
|
||||||
|
})
|
||||||
|
if !errors.Is(err, ErrInvalidKind) {
|
||||||
|
t.Fatalf("erreur = %v, attendu ErrInvalidKind", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreatePrincipalRejectsInvalidName(t *testing.T) {
|
||||||
|
service := newTestService(t)
|
||||||
|
|
||||||
|
_, err := service.CreatePrincipal(context.Background(), CreatePrincipalParams{
|
||||||
|
Kind: KindUser,
|
||||||
|
Name: " ",
|
||||||
|
})
|
||||||
|
if !errors.Is(err, ErrInvalidName) {
|
||||||
|
t.Fatalf("erreur = %v, attendu ErrInvalidName", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateGuest(t *testing.T) {
|
||||||
|
service := newTestService(t)
|
||||||
|
|
||||||
|
guest, err := service.CreateGuest(context.Background(), "jean")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreateGuest : %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if guest.Kind != KindGuest {
|
||||||
|
t.Fatalf("kind = %q, attendu %q", guest.Kind, KindGuest)
|
||||||
|
}
|
||||||
|
if guest.Name != "jean" {
|
||||||
|
t.Fatalf("name = %q, attendu jean", guest.Name)
|
||||||
|
}
|
||||||
|
if len(guest.Groups) != 1 || guest.Groups[0].Name != "guests" {
|
||||||
|
t.Fatalf("groupes = %+v, attendu guests", guest.Groups)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateGuestRejectsDuplicateName(t *testing.T) {
|
||||||
|
service := newTestService(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
if _, err := service.CreateGuest(ctx, "jean"); err != nil {
|
||||||
|
t.Fatalf("CreateGuest : %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := service.CreateGuest(ctx, "jean"); !errors.Is(err, ErrNameTaken) {
|
||||||
|
t.Fatalf("erreur = %v, attendu ErrNameTaken", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package identity
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"mediarr/database"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
db database.DatabaseClient
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(db database.DatabaseClient) *Service {
|
||||||
|
return &Service{db: 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")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) groupByName(ctx context.Context, name string) (database.Principal, error) {
|
||||||
|
group, err := s.db.Queries.GetPrincipalByNameAndKind(ctx, database.GetPrincipalByNameAndKindParams{
|
||||||
|
Kind: KindGroup,
|
||||||
|
Name: name,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return database.Principal{}, fmt.Errorf("%w: %s", ErrGroupNotFound, name)
|
||||||
|
}
|
||||||
|
return database.Principal{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return group, nil
|
||||||
|
}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
package node
|
package node
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"mediarr/auth"
|
||||||
"mediarr/cluster"
|
"mediarr/cluster"
|
||||||
"mediarr/database"
|
"mediarr/database"
|
||||||
|
"mediarr/identity"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Node struct {
|
type Node struct {
|
||||||
@@ -49,3 +51,11 @@ func (n *Node) Close() error {
|
|||||||
func (n *Node) ClusterIdentity() cluster.Identity {
|
func (n *Node) ClusterIdentity() cluster.Identity {
|
||||||
return n.cluster
|
return n.cluster
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (n *Node) Identity() *identity.Service {
|
||||||
|
return identity.NewService(n.db)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *Node) Auth() *auth.Service {
|
||||||
|
return auth.NewService(n.db)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package node
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"mediarr/auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNodeAuth(t *testing.T) {
|
||||||
|
t.Chdir(t.TempDir())
|
||||||
|
|
||||||
|
err, node := NewNode(NewNodeParams{DatabaseName: "users"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewNode : %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if err := node.Close(); err != nil {
|
||||||
|
t.Errorf("Close : %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := node.Up(); err != nil {
|
||||||
|
t.Fatalf("Up : %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
created, err := node.Auth().CreateUser(context.Background(), auth.CreateUserParams{
|
||||||
|
Login: "alice",
|
||||||
|
Password: "correct horse battery staple",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreateUser : %v", err)
|
||||||
|
}
|
||||||
|
if created.Account.Login != "alice" {
|
||||||
|
t.Fatalf("login = %q, attendu alice", created.Account.Login)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
const (
|
|
||||||
ADMIN = "admin"
|
|
||||||
MEMBER = "member"
|
|
||||||
)
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
type User struct {
|
|
||||||
Username string
|
|
||||||
Password string
|
|
||||||
Email *string
|
|
||||||
Role string
|
|
||||||
}
|
|
||||||
|
|
||||||
type NewUserParams struct {
|
|
||||||
Username string
|
|
||||||
Password string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUser(params NewUserParams) User {
|
|
||||||
|
|
||||||
return User{
|
|
||||||
Username: params.Username,
|
|
||||||
Password: params.Password,
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *User) Is(role string) bool {
|
|
||||||
return role == u.Role
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user