Add Go rewrite with Postgres 17 and Dokploy Docker Compose

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
orohi
2026-07-27 08:21:21 +03:00
co-authored by Cursor
parent bac78dd3fc
commit 99a27f00be
67 changed files with 17864 additions and 0 deletions
+168
View File
@@ -0,0 +1,168 @@
// Package auth implements admin authentication: password hashing/verification,
// login, and (single) first-admin self-registration. See oidc.go for the Pocket ID
// SSO flow, which also creates the first admin automatically.
package auth
import (
"context"
"errors"
"fmt"
"regexp"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/bcrypt"
"amnezia-share/internal/models"
)
var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
// BcryptCost is the cost factor used for admin password hashes.
const BcryptCost = bcrypt.DefaultCost
// HashPassword hashes password with bcrypt at BcryptCost.
func HashPassword(password string) (string, error) {
b, err := bcrypt.GenerateFromPassword([]byte(password), BcryptCost)
if err != nil {
return "", fmt.Errorf("хеширование пароля: %w", err)
}
return string(b), nil
}
// VerifyPassword reports whether password matches the bcrypt hash.
func VerifyPassword(hash, password string) bool {
if hash == "" {
return false
}
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
}
// ValidateUsername enforces the admin username policy: 3-64 chars, latin letters,
// digits, dot, dash, underscore only.
func ValidateUsername(username string) error {
if len(username) < 3 || len(username) > 64 {
return errors.New("Логин: от 3 до 64 символов.")
}
if !usernameRe.MatchString(username) {
return errors.New("Логин: только латиница, цифры, точка, дефис, подчёркивание.")
}
return nil
}
// ValidatePassword enforces the admin password policy: at least 10 characters.
func ValidatePassword(password string) error {
if len(password) < 10 {
return errors.New("Пароль не короче 10 символов.")
}
return nil
}
// Repo is the PostgreSQL-backed repository for admin accounts (the "users" table).
type Repo struct {
Pool *pgxpool.Pool
}
// New builds a Repo bound to pool.
func New(pool *pgxpool.Pool) *Repo {
return &Repo{Pool: pool}
}
// AdminCount returns the number of registered admin accounts.
func (r *Repo) AdminCount(ctx context.Context) (int, error) {
var c int
if err := r.Pool.QueryRow(ctx, `SELECT COUNT(*) FROM users`).Scan(&c); err != nil {
return 0, err
}
return c, nil
}
// GetAdminByID loads an admin by id, or (nil, nil) if not found.
func (r *Repo) GetAdminByID(ctx context.Context, id int) (*models.User, error) {
if id <= 0 {
return nil, nil
}
var u models.User
err := r.Pool.QueryRow(ctx, `SELECT id, username, password_hash, role, created_at FROM users WHERE id=$1 LIMIT 1`, id).
Scan(&u.ID, &u.Username, &u.PasswordHash, &u.Role, &u.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &u, nil
}
// GetAdminByUsername loads an admin by exact username match, or (nil, nil) if not
// found.
func (r *Repo) GetAdminByUsername(ctx context.Context, username string) (*models.User, error) {
var u models.User
err := r.Pool.QueryRow(ctx, `SELECT id, username, password_hash, role, created_at FROM users WHERE username=$1 LIMIT 1`, username).
Scan(&u.ID, &u.Username, &u.PasswordHash, &u.Role, &u.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &u, nil
}
// LoginAdmin verifies username/password and returns the matching admin user.
func (r *Repo) LoginAdmin(ctx context.Context, username, password string) (*models.User, error) {
username = strings.TrimSpace(username)
u, err := r.GetAdminByUsername(ctx, username)
if err != nil {
return nil, errors.New("не удалось выполнить вход")
}
if u == nil || !VerifyPassword(u.PasswordHash, password) {
return nil, errors.New("Неверный логин или пароль.")
}
return u, nil
}
// RegisterFirstAdmin creates the single administrator account. It fails if any
// admin already exists (use the login form instead).
func (r *Repo) RegisterFirstAdmin(ctx context.Context, username, password string) (*models.User, error) {
count, err := r.AdminCount(ctx)
if err != nil {
return nil, errors.New("не удалось проверить администраторов")
}
if count > 0 {
return nil, errors.New("Администратор уже зарегистрирован. Войдите через форму входа.")
}
username = strings.TrimSpace(username)
if err := ValidateUsername(username); err != nil {
return nil, err
}
if err := ValidatePassword(password); err != nil {
return nil, err
}
hash, err := HashPassword(password)
if err != nil {
return nil, errors.New("Не удалось сформировать хеш пароля.")
}
var id int
err = r.Pool.QueryRow(ctx, `INSERT INTO users (username, password_hash, role) VALUES ($1,$2,'admin') RETURNING id`, username, hash).Scan(&id)
if err != nil {
return nil, errors.New("Ошибка БД: возможно, логин уже занят.")
}
return r.GetAdminByID(ctx, id)
}
// registerAdminWithHash inserts a new admin with a pre-computed password hash.
// Used by the OIDC auto-provisioning flow (oidc.go) where the local password is
// random and never used to sign in directly.
func (r *Repo) registerAdminWithHash(ctx context.Context, username, passwordHash string) (*models.User, error) {
var id int
err := r.Pool.QueryRow(ctx, `INSERT INTO users (username, password_hash, role) VALUES ($1,$2,'admin') RETURNING id`, username, passwordHash).Scan(&id)
if err != nil {
return nil, fmt.Errorf("создание администратора: %w", err)
}
return r.GetAdminByID(ctx, id)
}
+289
View File
@@ -0,0 +1,289 @@
package auth
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"amnezia-share/internal/models"
)
// OIDCConfig holds the Pocket ID SSO settings (see settings.KeyPocketURL /
// KeyPocketClientID / KeyPocketSecret in internal/settings).
type OIDCConfig struct {
URL string
ClientID string
ClientSecret string
}
// Configured reports whether all three OIDC settings are present.
func (c OIDCConfig) Configured() bool {
return strings.TrimSpace(c.URL) != "" && strings.TrimSpace(c.ClientID) != "" && strings.TrimSpace(c.ClientSecret) != ""
}
func (c OIDCConfig) baseURL() string {
return strings.TrimRight(strings.TrimSpace(c.URL), "/")
}
// GenerateState returns a random hex CSRF state value for the OIDC authorize
// request.
func GenerateState() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return fmt.Sprintf("%x", b), nil
}
// GeneratePKCE returns a PKCE code_verifier and its S256 code_challenge
// (RFC 7636), both base64url-encoded without padding.
func GeneratePKCE() (verifier, challenge string, err error) {
raw := make([]byte, 32)
if _, err = rand.Read(raw); err != nil {
return "", "", err
}
verifier = base64.RawURLEncoding.EncodeToString(raw)
sum := sha256.Sum256([]byte(verifier))
challenge = base64.RawURLEncoding.EncodeToString(sum[:])
return verifier, challenge, nil
}
// AuthURL builds the Pocket ID /authorize URL for the PKCE S256 authorization-code
// flow.
func AuthURL(cfg OIDCConfig, redirectURI, state, codeChallenge string) string {
q := url.Values{}
q.Set("response_type", "code")
q.Set("client_id", cfg.ClientID)
q.Set("redirect_uri", redirectURI)
q.Set("scope", "openid profile email")
q.Set("state", state)
q.Set("code_challenge", codeChallenge)
q.Set("code_challenge_method", "S256")
return cfg.baseURL() + "/authorize?" + q.Encode()
}
// UserInfo is the subset of the OIDC userinfo response we care about.
type UserInfo struct {
PreferredUsername string
Name string
Email string
Sub string
}
// LookupName picks the identifier used to match against the local users table:
// preferred_username, then name, then email, then sub.
func (u UserInfo) LookupName() string {
switch {
case u.PreferredUsername != "":
return u.PreferredUsername
case u.Name != "":
return u.Name
case u.Email != "":
return u.Email
default:
return u.Sub
}
}
var httpClientOIDC = &http.Client{Timeout: 15 * time.Second}
// ExchangeAndUserinfo exchanges an authorization code for an access token and
// fetches the user profile. It mirrors the Pocket ID quirks handled by the PHP
// implementation:
// - token endpoint tried at /api/oidc/token first, then /token,
// - for each endpoint, Basic auth (client_id:client_secret) is tried first, then
// falls back to client_id/client_secret in the POST body,
// - userinfo endpoint tried at /api/oidc/userinfo first, then /userinfo.
func ExchangeAndUserinfo(ctx context.Context, cfg OIDCConfig, code, redirectURI, codeVerifier string) (UserInfo, error) {
base := cfg.baseURL()
tokenEndpoints := []string{base + "/api/oidc/token", base + "/token"}
basicAuth := base64.StdEncoding.EncodeToString([]byte(cfg.ClientID + ":" + cfg.ClientSecret))
var accessToken string
var lastTokenErr error
for _, endpoint := range tokenEndpoints {
fields := url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {redirectURI},
}
if codeVerifier != "" {
fields.Set("code_verifier", codeVerifier)
}
if tok, err := postTokenRequest(ctx, endpoint, fields, map[string]string{"Authorization": "Basic " + basicAuth}); err == nil && tok != "" {
accessToken = tok
break
} else if err != nil {
lastTokenErr = err
}
fieldsSecret := url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {redirectURI},
"client_id": {cfg.ClientID},
"client_secret": {cfg.ClientSecret},
}
if codeVerifier != "" {
fieldsSecret.Set("code_verifier", codeVerifier)
}
if tok, err := postTokenRequest(ctx, endpoint, fieldsSecret, nil); err == nil && tok != "" {
accessToken = tok
break
} else if err != nil {
lastTokenErr = err
}
}
if accessToken == "" {
if lastTokenErr != nil {
return UserInfo{}, fmt.Errorf("Pocket ID не вернул access_token: %w", lastTokenErr)
}
return UserInfo{}, errors.New("Pocket ID не вернул access_token.")
}
userinfoEndpoints := []string{base + "/api/oidc/userinfo", base + "/userinfo"}
var raw map[string]any
var lastErr error
for _, endpoint := range userinfoEndpoints {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
lastErr = err
continue
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Accept", "application/json")
resp, err := httpClientOIDC.Do(req)
if err != nil {
lastErr = err
continue
}
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
_ = resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
lastErr = fmt.Errorf("userinfo HTTP %d", resp.StatusCode)
continue
}
if err := json.Unmarshal(body, &raw); err != nil {
lastErr = err
continue
}
lastErr = nil
break
}
if raw == nil {
if lastErr == nil {
lastErr = errors.New("нет ответа")
}
return UserInfo{}, fmt.Errorf("не удалось получить профиль от Pocket ID: %w", lastErr)
}
info := UserInfo{
PreferredUsername: strings.TrimSpace(stringAny(raw["preferred_username"])),
Name: strings.TrimSpace(stringAny(raw["name"])),
Email: strings.TrimSpace(stringAny(raw["email"])),
Sub: strings.TrimSpace(stringAny(raw["sub"])),
}
if info.Sub == "" && info.PreferredUsername == "" && info.Name == "" && info.Email == "" {
return UserInfo{}, errors.New("Pocket ID не вернул идентификатор пользователя.")
}
return info, nil
}
func stringAny(v any) string {
if s, ok := v.(string); ok {
return s
}
return ""
}
func postTokenRequest(ctx context.Context, endpoint string, fields url.Values, headers map[string]string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(fields.Encode()))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := httpClientOIDC.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return "", fmt.Errorf("token HTTP %d", resp.StatusCode)
}
var dec map[string]any
if err := json.Unmarshal(body, &dec); err != nil {
return "", err
}
tok, _ := dec["access_token"].(string)
tok = strings.TrimSpace(tok)
if tok == "" {
return "", errors.New("нет access_token в ответе")
}
return tok, nil
}
// FindOrCreateAdminFromOIDC matches the Pocket ID profile to an existing admin by
// username (preferred_username/name/email/sub, in that priority) or by e-mail.
// If no admin exists yet at all, the very first successful OIDC login
// auto-provisions the sole admin account (with a random, never-used local
// password). Otherwise, an unmatched profile is rejected.
func (r *Repo) FindOrCreateAdminFromOIDC(ctx context.Context, info UserInfo) (*models.User, error) {
lookupName := info.LookupName()
if lookupName == "" {
return nil, errors.New("Pocket ID не вернул идентификатор пользователя.")
}
admin, err := r.GetAdminByUsername(ctx, lookupName)
if err != nil {
return nil, err
}
if admin == nil && info.Email != "" {
admin, err = r.GetAdminByUsername(ctx, info.Email)
if err != nil {
return nil, err
}
}
if admin == nil {
count, err := r.AdminCount(ctx)
if err != nil {
return nil, err
}
if count != 0 {
return nil, fmt.Errorf("пользователь %q не зарегистрирован как администратор", lookupName)
}
randomPass := make([]byte, 32)
if _, err := rand.Read(randomPass); err != nil {
return nil, err
}
hash, err := HashPassword(fmt.Sprintf("%x", randomPass))
if err != nil {
return nil, err
}
admin, err = r.registerAdminWithHash(ctx, lookupName, hash)
if err != nil {
return nil, err
}
}
if admin.Role != "admin" {
return nil, errors.New("Учётная запись не является администратором.")
}
return admin, nil
}