260 lines
6.1 KiB
Go
260 lines
6.1 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"database/sql"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"mediarr/database"
|
|
"mediarr/ident"
|
|
"mediarr/identity"
|
|
)
|
|
|
|
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 != identity.StatusActive {
|
|
return nil, "", ErrInvalidSession
|
|
}
|
|
|
|
now := time.Now().UnixMilli()
|
|
|
|
account, err := s.db.Queries.GetAccount(ctx, params.PrincipalID)
|
|
switch {
|
|
case err == nil:
|
|
switch account.State {
|
|
case AccountStateActive:
|
|
case AccountStateDisabled:
|
|
return nil, "", ErrAccountDisabled
|
|
case AccountStateLocked:
|
|
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 != identity.StatusActive || user.Account.State == AccountStateDisabled {
|
|
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}
|
|
}
|