create account + create session
This commit is contained in:
@@ -196,6 +196,85 @@ func (q *Queries) CreatePrincipal(ctx context.Context, arg CreatePrincipalParams
|
||||
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
|
||||
DELETE FROM account
|
||||
WHERE principal_id = ?1
|
||||
@@ -206,6 +285,20 @@ func (q *Queries) DeleteAccount(ctx context.Context, principalID ident.UUID) 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
|
||||
DELETE FROM membership
|
||||
WHERE group_id = ?1
|
||||
@@ -401,6 +494,58 @@ func (q *Queries) GetPrincipalByNameAndKind(ctx context.Context, arg GetPrincipa
|
||||
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
|
||||
UPDATE account
|
||||
SET failed_attempts = failed_attempts + 1
|
||||
@@ -506,6 +651,49 @@ func (q *Queries) ListGroupMembers(ctx context.Context, groupID ident.UUID) ([]P
|
||||
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
|
||||
SELECT p.id, p.kind, p.name, p.public_key, p.status, p.successor_id, p.created_at, p.disabled_at
|
||||
FROM membership m
|
||||
@@ -546,6 +734,43 @@ func (q *Queries) ListMemberGroups(ctx context.Context, memberID ident.UUID) ([]
|
||||
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
|
||||
SELECT group_id, member_id, role, created_at
|
||||
FROM membership
|
||||
@@ -693,6 +918,49 @@ func (q *Queries) ListPrincipalsByKind(ctx context.Context, kind string) ([]Prin
|
||||
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
|
||||
UPDATE account
|
||||
SET state = 'locked',
|
||||
@@ -758,6 +1026,46 @@ func (q *Queries) RecordLogin(ctx context.Context, arg RecordLoginParams) (Accou
|
||||
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
|
||||
UPDATE account
|
||||
SET failed_attempts = 0,
|
||||
@@ -785,6 +1093,104 @@ func (q *Queries) ResetFailedAttempts(ctx context.Context, principalID ident.UUI
|
||||
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
|
||||
UPDATE account
|
||||
SET state = 'active',
|
||||
|
||||
@@ -154,6 +154,20 @@ DELETE FROM membership
|
||||
WHERE group_id = sqlc.arg(group_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
|
||||
-- ============================================================================
|
||||
@@ -251,3 +265,89 @@ RETURNING *;
|
||||
-- name: DeleteAccount :exec
|
||||
DELETE FROM account
|
||||
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 (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/pressly/goose/v3 v3.30.1
|
||||
golang.org/x/crypto v0.59.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.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=
|
||||
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/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
|
||||
@@ -3,6 +3,7 @@ package node
|
||||
import (
|
||||
"mediarr/cluster"
|
||||
"mediarr/database"
|
||||
"mediarr/user"
|
||||
)
|
||||
|
||||
type Node struct {
|
||||
@@ -49,3 +50,7 @@ func (n *Node) Close() error {
|
||||
func (n *Node) ClusterIdentity() cluster.Identity {
|
||||
return n.cluster
|
||||
}
|
||||
|
||||
func (n *Node) Users() *user.Service {
|
||||
return user.NewService(n.db)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"mediarr/user"
|
||||
)
|
||||
|
||||
func TestNodeUsers(t *testing.T) {
|
||||
t.Chdir(t.TempDir())
|
||||
|
||||
err, node := NewNode(NewNodeParams{DatabaseName: "users"})
|
||||
if err != nil {
|
||||
t.Fatalf("NewNode : %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = node.Close() })
|
||||
|
||||
if err := node.Up(); err != nil {
|
||||
t.Fatalf("Up : %v", err)
|
||||
}
|
||||
|
||||
created, err := node.Users().CreateUser(context.Background(), user.CreateUserParams{
|
||||
Login: "alice",
|
||||
Password: "correct horse battery staple",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser : %v", err)
|
||||
}
|
||||
if created.Login != "alice" {
|
||||
t.Fatalf("login = %q, attendu alice", created.Login)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package user
|
||||
|
||||
import "errors"
|
||||
|
||||
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")
|
||||
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")
|
||||
)
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mediarr/database"
|
||||
"mediarr/ident"
|
||||
)
|
||||
|
||||
type Member struct {
|
||||
ID ident.UUID
|
||||
Name string
|
||||
Kind string
|
||||
Role string
|
||||
}
|
||||
|
||||
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 = "member"
|
||||
}
|
||||
if role != "member" && role != "admin" {
|
||||
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 != "group" {
|
||||
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 != "user" && member.Kind != "guest" {
|
||||
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,83 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAddAndRemoveMember(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", RoleMember)
|
||||
admins := mustGroup(t, service, "admins")
|
||||
|
||||
if err := service.AddMember(ctx, admins.ID, created.ID, "admin"); err != nil {
|
||||
t.Fatalf("AddMember : %v", err)
|
||||
}
|
||||
|
||||
groups, err := service.ListGroups(ctx, created.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("ListGroups : %v", err)
|
||||
}
|
||||
if !hasGroup(groups, "admins") || !hasGroup(groups, "members") {
|
||||
t.Fatalf("groupes = %+v, attendu admins et members", groups)
|
||||
}
|
||||
|
||||
members, err := service.ListGroupMembers(ctx, admins.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("ListGroupMembers : %v", err)
|
||||
}
|
||||
if len(members) != 1 || members[0].ID != created.ID || members[0].Role != "admin" {
|
||||
t.Fatalf("membres = %+v, attendu alice admin", members)
|
||||
}
|
||||
|
||||
if err := service.RemoveMember(ctx, admins.ID, created.ID); err != nil {
|
||||
t.Fatalf("RemoveMember : %v", err)
|
||||
}
|
||||
|
||||
if err := service.RemoveMember(ctx, admins.ID, created.ID); !errors.Is(err, ErrNotMember) {
|
||||
t.Fatalf("erreur = %v, attendu ErrNotMember", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddMemberRejectsDuplicate(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", RoleMember)
|
||||
members := mustGroup(t, service, "members")
|
||||
|
||||
err := service.AddMember(ctx, members.ID, created.ID, "member")
|
||||
if !errors.Is(err, ErrAlreadyMember) {
|
||||
t.Fatalf("erreur = %v, attendu ErrAlreadyMember", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddMemberRejectsInvalidMember(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", RoleMember)
|
||||
members := mustGroup(t, service, "members")
|
||||
|
||||
err := service.AddMember(ctx, members.ID, members.ID, "member")
|
||||
if !errors.Is(err, ErrInvalidMember) {
|
||||
t.Fatalf("erreur = %v, attendu ErrInvalidMember", err)
|
||||
}
|
||||
|
||||
err = service.AddMember(ctx, created.ID, created.ID, "member")
|
||||
if !errors.Is(err, ErrInvalidGroup) {
|
||||
t.Fatalf("erreur = %v, attendu ErrInvalidGroup", err)
|
||||
}
|
||||
}
|
||||
|
||||
func hasGroup(groups []Group, name string) bool {
|
||||
for _, group := range groups {
|
||||
if group.Name == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package user
|
||||
|
||||
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) *User {
|
||||
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
|
||||
}
|
||||
|
||||
func mustGroup(t *testing.T, service *Service, name string) database.Principal {
|
||||
t.Helper()
|
||||
|
||||
group, err := service.db.Queries.GetPrincipalByNameAndKind(context.Background(), database.GetPrincipalByNameAndKindParams{
|
||||
Kind: "group",
|
||||
Name: name,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("groupe %q : %v", name, err)
|
||||
}
|
||||
|
||||
return group
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package user
|
||||
|
||||
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 user
|
||||
|
||||
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("user: 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("user: 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("user: 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("user: 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("user: 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("user: 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("user: clé Argon2id invalide")
|
||||
}
|
||||
|
||||
return params, salt, key, nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package user
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package user
|
||||
|
||||
const (
|
||||
ADMIN = "admin"
|
||||
MEMBER = "member"
|
||||
RoleAdmin = "admin"
|
||||
RoleMember = "member"
|
||||
RoleGuest = "guest"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package user
|
||||
|
||||
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: "group",
|
||||
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
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
package user
|
||||
|
||||
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("user: 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, *User, 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.loadUser(ctx, session.PrincipalID)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil, ErrInvalidSession
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
if user.Status != "active" || user.AccountState == "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,307 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mediarr/database"
|
||||
"mediarr/ident"
|
||||
)
|
||||
|
||||
func TestCreateAndValidateSession(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", RoleMember)
|
||||
|
||||
session, token, err := service.CreateSession(ctx, CreateSessionParams{
|
||||
PrincipalID: created.ID,
|
||||
Kind: "web",
|
||||
Label: "test",
|
||||
UserAgent: "go-test",
|
||||
IPPrefix: "127.0.0.",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession : %v", err)
|
||||
}
|
||||
if token == "" {
|
||||
t.Fatal("token vide")
|
||||
}
|
||||
if session.ID.IsZero() {
|
||||
t.Fatal("identifiant de session vide")
|
||||
}
|
||||
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
stored, err := service.db.Queries.GetSessionByTokenHash(ctx, tokenHash[:])
|
||||
if err != nil {
|
||||
t.Fatalf("GetSessionByTokenHash : %v", err)
|
||||
}
|
||||
if len(stored.TokenHash) != 32 {
|
||||
t.Fatalf("token_hash de %d octets, attendu 32", len(stored.TokenHash))
|
||||
}
|
||||
|
||||
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.ID != created.ID {
|
||||
t.Fatalf("utilisateur = %s, attendu %s", authenticated.ID, created.ID)
|
||||
}
|
||||
if validated.LastSeenAt < session.LastSeenAt {
|
||||
t.Fatalf("last_seen_at = %d, attendu >= %d", validated.LastSeenAt, session.LastSeenAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSessionRejectsUnknownToken(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
|
||||
_, _, err := service.ValidateSession(context.Background(), "inconnu")
|
||||
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", RoleMember)
|
||||
|
||||
session, token, err := service.CreateSession(ctx, CreateSessionParams{PrincipalID: created.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", RoleMember)
|
||||
|
||||
_, token, err := service.CreateSession(ctx, CreateSessionParams{PrincipalID: created.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 TestValidateSessionRejectsExpiredSession(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", RoleMember)
|
||||
|
||||
token := "session-expiree"
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
now := time.Now().UnixMilli()
|
||||
|
||||
sessionID, err := ident.NewV7()
|
||||
if err != nil {
|
||||
t.Fatalf("NewV7 : %v", err)
|
||||
}
|
||||
|
||||
_, err = service.db.WriteQueries.CreateSession(ctx, database.CreateSessionParams{
|
||||
ID: sessionID,
|
||||
TokenHash: tokenHash[:],
|
||||
PrincipalID: created.ID,
|
||||
Kind: "web",
|
||||
CreatedAt: now - 2000,
|
||||
LastSeenAt: now - 2000,
|
||||
ExpiresAt: now - 1,
|
||||
IdleExpiresAt: now + 60_000,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession : %v", err)
|
||||
}
|
||||
|
||||
_, _, err = service.ValidateSession(ctx, token)
|
||||
if !errors.Is(err, ErrInvalidSession) {
|
||||
t.Fatalf("erreur = %v, attendu ErrInvalidSession", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSessionRejectsIdleExpiredSession(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", RoleMember)
|
||||
|
||||
token := "session-inactive"
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
now := time.Now().UnixMilli()
|
||||
|
||||
sessionID, err := ident.NewV7()
|
||||
if err != nil {
|
||||
t.Fatalf("NewV7 : %v", err)
|
||||
}
|
||||
|
||||
_, err = service.db.WriteQueries.CreateSession(ctx, database.CreateSessionParams{
|
||||
ID: sessionID,
|
||||
TokenHash: tokenHash[:],
|
||||
PrincipalID: created.ID,
|
||||
Kind: "web",
|
||||
CreatedAt: now - 2000,
|
||||
LastSeenAt: now - 2000,
|
||||
ExpiresAt: now + 60_000,
|
||||
IdleExpiresAt: now - 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession : %v", err)
|
||||
}
|
||||
|
||||
_, _, err = service.ValidateSession(ctx, token)
|
||||
if !errors.Is(err, ErrInvalidSession) {
|
||||
t.Fatalf("erreur = %v, attendu ErrInvalidSession", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSessionRejectsInactivePrincipal(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", RoleMember)
|
||||
|
||||
_, err := service.db.WriteQueries.UpdatePrincipalStatus(ctx, database.UpdatePrincipalStatusParams{
|
||||
Status: "disabled",
|
||||
DisabledAt: sql.NullInt64{
|
||||
Int64: time.Now().UnixMilli(),
|
||||
Valid: true,
|
||||
},
|
||||
ID: created.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("UpdatePrincipalStatus : %v", err)
|
||||
}
|
||||
|
||||
_, _, err = service.CreateSession(ctx, CreateSessionParams{PrincipalID: created.ID})
|
||||
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", RoleMember)
|
||||
|
||||
_, _, err := service.CreateSession(ctx, CreateSessionParams{PrincipalID: created.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession : %v", err)
|
||||
}
|
||||
|
||||
token := "session-expiree-liste"
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
now := time.Now().UnixMilli()
|
||||
|
||||
sessionID, err := ident.NewV7()
|
||||
if err != nil {
|
||||
t.Fatalf("NewV7 : %v", err)
|
||||
}
|
||||
|
||||
_, err = service.db.WriteQueries.CreateSession(ctx, database.CreateSessionParams{
|
||||
ID: sessionID,
|
||||
TokenHash: tokenHash[:],
|
||||
PrincipalID: created.ID,
|
||||
Kind: "web",
|
||||
CreatedAt: now - 2000,
|
||||
LastSeenAt: now - 2000,
|
||||
ExpiresAt: now - 1,
|
||||
IdleExpiresAt: now - 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession : %v", err)
|
||||
}
|
||||
|
||||
sessions, err := service.ListSessions(ctx, created.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSessions : %v", err)
|
||||
}
|
||||
if len(sessions) != 2 {
|
||||
t.Fatalf("sessions = %d, attendu 2", len(sessions))
|
||||
}
|
||||
|
||||
deleted, err := service.DeleteExpiredSessions(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("DeleteExpiredSessions : %v", err)
|
||||
}
|
||||
if deleted != 1 {
|
||||
t.Fatalf("sessions supprimées = %d, attendu 1", deleted)
|
||||
}
|
||||
|
||||
sessions, err = service.ListSessions(ctx, created.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSessions : %v", err)
|
||||
}
|
||||
if len(sessions) != 1 {
|
||||
t.Fatalf("sessions = %d, attendu 1", len(sessions))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuestSession(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
guestID, err := ident.NewV7()
|
||||
if err != nil {
|
||||
t.Fatalf("NewV7 : %v", err)
|
||||
}
|
||||
|
||||
_, err = service.db.WriteQueries.CreatePrincipal(ctx, database.CreatePrincipalParams{
|
||||
ID: guestID,
|
||||
Kind: "guest",
|
||||
Name: "jean",
|
||||
Status: "active",
|
||||
CreatedAt: time.Now().UnixMilli(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreatePrincipal : %v", err)
|
||||
}
|
||||
|
||||
session, token, err := service.CreateSession(ctx, CreateSessionParams{PrincipalID: guestID})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession : %v", err)
|
||||
}
|
||||
|
||||
validated, guest, 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 guest.ID != guestID {
|
||||
t.Fatalf("id invité = %s, attendu %s", guest.ID, guestID)
|
||||
}
|
||||
if guest.Login != "jean" {
|
||||
t.Fatalf("login = %q, attendu jean", guest.Login)
|
||||
}
|
||||
if guest.AccountState != "active" {
|
||||
t.Fatalf("état = %q, attendu active", guest.AccountState)
|
||||
}
|
||||
}
|
||||
+258
-14
@@ -1,26 +1,270 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mediarr/database"
|
||||
"mediarr/ident"
|
||||
)
|
||||
|
||||
const (
|
||||
maxFailedAttempts = 5
|
||||
lockDuration = 15 * time.Minute
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Username string
|
||||
ID ident.UUID
|
||||
Login string
|
||||
Name string
|
||||
Status string
|
||||
AccountState string
|
||||
MustChangePassword bool
|
||||
CreatedAt int64
|
||||
Groups []Group
|
||||
}
|
||||
|
||||
type Group struct {
|
||||
ID ident.UUID
|
||||
Name string
|
||||
Role string
|
||||
}
|
||||
|
||||
type CreateUserParams struct {
|
||||
Login 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 (s *Service) CreateUser(ctx context.Context, params CreateUserParams) (*User, 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 = RoleMember
|
||||
}
|
||||
|
||||
groupName, err := groupNameForRole(role)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
group, err := s.groupByName(ctx, groupName)
|
||||
if err != nil {
|
||||
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: "user",
|
||||
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: "member",
|
||||
CreatedAt: now,
|
||||
})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return nil, fmt.Errorf("%w: %s", ErrLoginTaken, display)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.loadUser(ctx, userID)
|
||||
}
|
||||
|
||||
func (u *User) Is(role string) bool {
|
||||
return role == u.Role
|
||||
func (s *Service) Authenticate(ctx context.Context, login, password string) (*User, 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.loadUser(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) loadUser(ctx context.Context, id ident.UUID) (*User, error) {
|
||||
principal, err := s.db.Queries.GetPrincipal(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
login := principal.Name
|
||||
accountState := "active"
|
||||
mustChangePassword := false
|
||||
|
||||
account, err := s.db.Queries.GetAccount(ctx, id)
|
||||
switch {
|
||||
case err == nil:
|
||||
login = account.Login
|
||||
accountState = account.State
|
||||
mustChangePassword = account.MustChangePassword != 0
|
||||
case !errors.Is(err, sql.ErrNoRows):
|
||||
return nil, err
|
||||
}
|
||||
|
||||
groups, err := s.ListGroups(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &User{
|
||||
ID: principal.ID,
|
||||
Login: login,
|
||||
Name: principal.Name,
|
||||
Status: principal.Status,
|
||||
AccountState: accountState,
|
||||
MustChangePassword: mustChangePassword,
|
||||
CreatedAt: principal.CreatedAt,
|
||||
Groups: groups,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mediarr/database"
|
||||
)
|
||||
|
||||
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.ID.IsZero() {
|
||||
t.Fatal("identifiant utilisateur vide")
|
||||
}
|
||||
if created.Login != "Alice" {
|
||||
t.Fatalf("login = %q, attendu Alice", created.Login)
|
||||
}
|
||||
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 created.AccountState != "active" {
|
||||
t.Fatalf("état du compte = %q, attendu active", created.AccountState)
|
||||
}
|
||||
if len(created.Groups) != 1 || created.Groups[0].Name != "members" {
|
||||
t.Fatalf("groupes = %+v, attendu members", created.Groups)
|
||||
}
|
||||
|
||||
principal, err := service.db.Queries.GetPrincipal(ctx, created.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetPrincipal : %v", err)
|
||||
}
|
||||
if principal.Kind != "user" {
|
||||
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", 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, 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", RoleAdmin)
|
||||
|
||||
if len(created.Groups) != 1 || created.Groups[0].Name != "admins" {
|
||||
t.Fatalf("groupes = %+v, attendu admins", created.Groups)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticate(t *testing.T) {
|
||||
service := newTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
created := mustCreateUser(t, service, "alice", "correct horse battery staple", RoleMember)
|
||||
|
||||
authenticated, err := service.Authenticate(ctx, "ALICE", "correct horse battery staple")
|
||||
if err != nil {
|
||||
t.Fatalf("Authenticate : %v", err)
|
||||
}
|
||||
if authenticated.ID != created.ID {
|
||||
t.Fatalf("id = %s, attendu %s", authenticated.ID, created.ID)
|
||||
}
|
||||
|
||||
account, err := service.db.Queries.GetAccount(ctx, created.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", 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.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", 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.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", RoleMember)
|
||||
|
||||
_, err := service.db.WriteQueries.LockAccount(ctx, database.LockAccountParams{
|
||||
LockedUntil: sql.NullInt64{
|
||||
Int64: time.Now().Add(-time.Minute).UnixMilli(),
|
||||
Valid: true,
|
||||
},
|
||||
PrincipalID: created.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.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", RoleMember)
|
||||
|
||||
_, err := service.db.WriteQueries.UpdateAccountState(ctx, database.UpdateAccountStateParams{
|
||||
State: "disabled",
|
||||
PrincipalID: created.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", RoleMember)
|
||||
|
||||
if err := service.SetPassword(ctx, created.ID, "nouveau correct horse battery staple"); err != nil {
|
||||
t.Fatalf("SetPassword : %v", err)
|
||||
}
|
||||
|
||||
_, err := service.Authenticate(ctx, "alice", "correct horse battery staple")
|
||||
if !errors.Is(err, ErrInvalidCredentials) {
|
||||
t.Fatalf("ancien mot de passe : erreur = %v, attendu ErrInvalidCredentials", err)
|
||||
}
|
||||
|
||||
_, err = service.Authenticate(ctx, "alice", "nouveau correct horse battery staple")
|
||||
if err != nil {
|
||||
t.Fatalf("nouveau mot de passe : %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user