Web Variante in Go V0.1
This commit is contained in:
1 parent
f9e3e94629
commit
692b9b6ef8
60 files changed
+13140
No files matched your search
@@ -0,0 +1,424 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"lektorenplan/domain"
|
||||
)
|
||||
|
||||
// UserRole is the application-wide permission level of an account.
|
||||
type UserRole string
|
||||
|
||||
const (
|
||||
RoleAdmin UserRole = "admin"
|
||||
RoleEditor UserRole = "editor"
|
||||
RoleReader UserRole = "reader"
|
||||
)
|
||||
|
||||
// UserRoleTitle returns the German label of a role.
|
||||
func UserRoleTitle(role UserRole) string {
|
||||
switch role {
|
||||
case RoleAdmin:
|
||||
return "Administrator"
|
||||
case RoleEditor:
|
||||
return "Redakteur"
|
||||
default:
|
||||
return "Leser"
|
||||
}
|
||||
}
|
||||
|
||||
// IsValid reports whether the role is known.
|
||||
func (r UserRole) IsValid() bool {
|
||||
return r == RoleAdmin || r == RoleEditor || r == RoleReader
|
||||
}
|
||||
|
||||
// CanEdit reports whether the role may modify planning data.
|
||||
func (r UserRole) CanEdit() bool { return r == RoleAdmin || r == RoleEditor }
|
||||
|
||||
// IsAdmin reports whether the role may manage tenants and accounts.
|
||||
func (r UserRole) IsAdmin() bool { return r == RoleAdmin }
|
||||
|
||||
// User is a login account. Memberships are loaded on demand.
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"displayName"`
|
||||
PasswordHash string `json:"-"`
|
||||
Role UserRole `json:"role"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
TenantIDs []string `json:"tenantIDs,omitempty"`
|
||||
}
|
||||
|
||||
// RoleTitle is a template helper.
|
||||
func (u *User) RoleTitle() string { return UserRoleTitle(u.Role) }
|
||||
|
||||
// Users lists all accounts with their memberships.
|
||||
func (s *Store) Users(ctx context.Context) ([]User, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
"SELECT id, username, display_name, password_hash, role, active, created_at FROM users ORDER BY username COLLATE NOCASE")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []User
|
||||
for rows.Next() {
|
||||
user, err := scanUser(rows)
|
||||
if err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, *user)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
// Close the result set before loading memberships: the pool deliberately
|
||||
// uses a single connection, so nested queries would otherwise block.
|
||||
rows.Close()
|
||||
|
||||
for i := range out {
|
||||
tenantIDs, err := s.Memberships(ctx, out[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[i].TenantIDs = tenantIDs
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// User loads an account by id.
|
||||
func (s *Store) User(ctx context.Context, id string) (*User, error) {
|
||||
row := s.db.QueryRowContext(ctx,
|
||||
"SELECT id, username, display_name, password_hash, role, active, created_at FROM users WHERE id=?", id)
|
||||
user, err := scanUser(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenantIDs, err := s.Memberships(ctx, user.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user.TenantIDs = tenantIDs
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// UserByUsername loads an account by login name.
|
||||
func (s *Store) UserByUsername(ctx context.Context, username string) (*User, error) {
|
||||
row := s.db.QueryRowContext(ctx,
|
||||
"SELECT id, username, display_name, password_hash, role, active, created_at FROM users WHERE username=? COLLATE NOCASE",
|
||||
strings.TrimSpace(username))
|
||||
user, err := scanUser(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenantIDs, err := s.Memberships(ctx, user.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user.TenantIDs = tenantIDs
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanUser(row rowScanner) (*User, error) {
|
||||
var user User
|
||||
var role, created string
|
||||
var active int
|
||||
if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &role, &active, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user.Role = UserRole(role)
|
||||
user.Active = active != 0
|
||||
user.CreatedAt = parseTime(created)
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// HashPassword returns a bcrypt hash suitable for storage.
|
||||
func HashPassword(password string) (string, error) {
|
||||
if len(password) < 6 {
|
||||
return "", errors.New("Das Passwort muss mindestens 6 Zeichen lang sein.")
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(hash), nil
|
||||
}
|
||||
|
||||
// Authenticate validates credentials and returns the active account.
|
||||
func (s *Store) Authenticate(ctx context.Context, username, password string) (*User, error) {
|
||||
user, err := s.UserByUsername(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, errors.New("Benutzername oder Passwort ist falsch.")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !user.Active {
|
||||
return nil, errors.New("Dieses Konto ist deaktiviert.")
|
||||
}
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
|
||||
return nil, errors.New("Benutzername oder Passwort ist falsch.")
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// CreateUser adds an account and its tenant memberships.
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, password string, role UserRole, active bool, tenantIDs []string) (*User, error) {
|
||||
username = strings.TrimSpace(username)
|
||||
displayName = strings.TrimSpace(displayName)
|
||||
if username == "" || displayName == "" {
|
||||
return nil, errors.New("Benutzername und Anzeigename sind erforderlich")
|
||||
}
|
||||
if !role.IsValid() {
|
||||
return nil, errors.New("Unbekannte Rolle")
|
||||
}
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user := &User{
|
||||
ID: domain.NewID(), Username: username, DisplayName: displayName,
|
||||
PasswordHash: hash, Role: role, Active: active, CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
err = s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO users(id, username, display_name, password_hash, role, active, created_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?)`,
|
||||
user.ID, user.Username, user.DisplayName, user.PasswordHash, string(user.Role),
|
||||
boolInt(user.Active), user.CreatedAt.Format(time.RFC3339)); err != nil {
|
||||
return err
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, tenantID := range tenantIDs {
|
||||
if tenantID == "" || seen[tenantID] {
|
||||
continue
|
||||
}
|
||||
seen[tenantID] = true
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"INSERT INTO memberships(user_id, tenant_id) VALUES(?, ?)", user.ID, tenantID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return nil, errors.New("Dieser Benutzername ist bereits vergeben.")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
user.TenantIDs = tenantIDs
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// UpdateUser saves account fields. An empty password keeps the old hash.
|
||||
func (s *Store) UpdateUser(ctx context.Context, id, username, displayName, password string, role UserRole, active bool, tenantIDs []string) error {
|
||||
username = strings.TrimSpace(username)
|
||||
displayName = strings.TrimSpace(displayName)
|
||||
if username == "" || displayName == "" {
|
||||
return errors.New("Benutzername und Anzeigename sind erforderlich")
|
||||
}
|
||||
if !role.IsValid() {
|
||||
return errors.New("Unbekannte Rolle")
|
||||
}
|
||||
return s.transaction(ctx, func(tx *sql.Tx) error {
|
||||
if password != "" {
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"UPDATE users SET username=?, display_name=?, role=?, active=?, password_hash=? WHERE id=?",
|
||||
username, displayName, string(role), boolInt(active), hash, id); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"UPDATE users SET username=?, display_name=?, role=?, active=? WHERE id=?",
|
||||
username, displayName, string(role), boolInt(active), id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM memberships WHERE user_id=?", id); err != nil {
|
||||
return err
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, tenantID := range tenantIDs {
|
||||
if tenantID == "" || seen[tenantID] {
|
||||
continue
|
||||
}
|
||||
seen[tenantID] = true
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"INSERT INTO memberships(user_id, tenant_id) VALUES(?, ?)", id, tenantID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// SetUserPassword updates only the password hash.
|
||||
func (s *Store) SetUserPassword(ctx context.Context, id, password string) error {
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, "UPDATE users SET password_hash=? WHERE id=?", hash, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteUser removes an account and its sessions.
|
||||
func (s *Store) DeleteUser(ctx context.Context, id string) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM users WHERE id=?", id)
|
||||
return err
|
||||
}
|
||||
|
||||
// CountUsers returns the number of accounts.
|
||||
func (s *Store) CountUsers(ctx context.Context) (int, error) {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM users").Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
// EnsureAdmin creates the first administrator when no account exists.
|
||||
// It returns true when a new account was created.
|
||||
func (s *Store) EnsureAdmin(ctx context.Context, username, password string) (bool, error) {
|
||||
count, err := s.CountUsers(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if count > 0 {
|
||||
return false, nil
|
||||
}
|
||||
if strings.TrimSpace(username) == "" {
|
||||
username = "admin"
|
||||
}
|
||||
if strings.TrimSpace(password) == "" {
|
||||
password = "admin123"
|
||||
}
|
||||
_, err = s.CreateUser(ctx, username, "Administrator", password, RoleAdmin, true, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Session is a server-side login session. The cookie holds the raw token;
|
||||
// only its SHA-256 digest is stored here.
|
||||
type Session struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"userID"`
|
||||
CSRFToken string `json:"-"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
}
|
||||
|
||||
func randomToken(bytes int) (string, error) {
|
||||
buf := make([]byte, bytes)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
func tokenDigest(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// CreateSession starts a login session and returns the raw cookie token.
|
||||
func (s *Store) CreateSession(ctx context.Context, userID string, ttl time.Duration) (*Session, string, error) {
|
||||
token, err := randomToken(32)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
csrf, err := randomToken(32)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
session := &Session{
|
||||
ID: tokenDigest(token), UserID: userID, CSRFToken: csrf,
|
||||
CreatedAt: now, ExpiresAt: now.Add(ttl),
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, `
|
||||
INSERT INTO sessions(id, user_id, csrf_token, created_at, expires_at)
|
||||
VALUES(?, ?, ?, ?, ?)`,
|
||||
session.ID, session.UserID, session.CSRFToken,
|
||||
session.CreatedAt.Format(time.RFC3339), session.ExpiresAt.Format(time.RFC3339))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return session, token, nil
|
||||
}
|
||||
|
||||
// SessionUser resolves a cookie token to its session and account.
|
||||
func (s *Store) SessionUser(ctx context.Context, token string) (*Session, *User, error) {
|
||||
if token == "" {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
var session Session
|
||||
var created, expires string
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
"SELECT id, user_id, csrf_token, created_at, expires_at FROM sessions WHERE id=?",
|
||||
tokenDigest(token)).Scan(&session.ID, &session.UserID, &session.CSRFToken, &created, &expires)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
session.CreatedAt = parseTime(created)
|
||||
session.ExpiresAt = parseTime(expires)
|
||||
if time.Now().UTC().After(session.ExpiresAt) {
|
||||
_ = s.DeleteSession(ctx, session.ID)
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
user, err := s.User(ctx, session.UserID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !user.Active {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
return &session, user, nil
|
||||
}
|
||||
|
||||
// DeleteSession invalidates one session by its stored digest.
|
||||
func (s *Store) DeleteSession(ctx context.Context, id string) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM sessions WHERE id=?", id)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteSessionByToken invalidates a session using the raw cookie token.
|
||||
func (s *Store) DeleteSessionByToken(ctx context.Context, token string) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM sessions WHERE id=?", tokenDigest(token))
|
||||
return err
|
||||
}
|
||||
|
||||
// PurgeExpiredSessions removes stale rows.
|
||||
func (s *Store) PurgeExpiredSessions(ctx context.Context) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM sessions WHERE expires_at < ?", time.Now().UTC().Format(time.RFC3339))
|
||||
return err
|
||||
}
|
||||
Reference in new issue
Block a user