feat(accounts): add admin accounts and user preferences
Remove public registration, support administrator-managed accounts, and persist personal preferences. Refs #2 #5 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
103
backend/internal/api/account_lifecycle_test.go
Normal file
103
backend/internal/api/account_lifecycle_test.go
Normal file
@ -0,0 +1,103 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lib/pq"
|
||||
"github.com/tradarr/backend/internal/api"
|
||||
"github.com/tradarr/backend/internal/api/handlers"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
)
|
||||
|
||||
// TEST_DATABASE_URL must identify a disposable PostgreSQL database. All tables
|
||||
// live in a unique schema; no existing application tables are used or removed.
|
||||
func TestAccountLifecyclePostgres(t *testing.T) {
|
||||
dsn := postgresTestURL(t)
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
db.SetMaxOpenConns(1)
|
||||
schema := fmt.Sprintf("account_test_%d", time.Now().UnixNano())
|
||||
if _, err = db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
|
||||
if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
migration, err := os.ReadFile("../database/migrations/000001_init.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Reuse the production users definition without installing extensions or
|
||||
// unrelated ingestion tables. gen_random_uuid is built into PostgreSQL 13+.
|
||||
users := strings.Split(strings.Split(string(migration), "CREATE TABLE users (")[1], "CREATE TABLE user_assets")[0]
|
||||
if _, err = db.Exec("CREATE TABLE users (" + users); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := models.NewRepository(db)
|
||||
hash, _ := auth.HashPassword("secret123")
|
||||
admin, err := repo.CreateUser("admin@example.test", hash, models.RoleAdmin)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, _ := auth.GenerateToken(admin.ID, admin.Email, "admin", "test-secret")
|
||||
router := api.SetupRouter(handlers.New(repo, &config.Config{JWTSecret: "test-secret"}, nil, nil, nil, nil), "test-secret")
|
||||
request := func(method, path, body string, want int) []byte {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, r)
|
||||
if w.Code != want {
|
||||
t.Fatalf("%s %s: got %d want %d: %s", method, path, w.Code, want, w.Body.String())
|
||||
}
|
||||
if bytes.Contains(w.Body.Bytes(), []byte(hash)) || bytes.Contains(w.Body.Bytes(), []byte("password_hash")) || bytes.Contains(w.Body.Bytes(), []byte("secret123")) {
|
||||
t.Fatal("secret leaked")
|
||||
}
|
||||
return w.Body.Bytes()
|
||||
}
|
||||
request("POST", "/api/admin/users", `{"email":"new@example.test","password":"secret123","role":"user"}`, 201)
|
||||
request("POST", "/api/admin/users", `{"email":"new@example.test","password":"secret123","role":"user"}`, 409)
|
||||
request("POST", "/api/admin/users", `{"email":"bad@example.test","password":"secret123","role":"root"}`, 400)
|
||||
request("PUT", "/api/admin/users/"+admin.ID, `{"email":"admin@example.test","role":"user"}`, 400)
|
||||
request("DELETE", "/api/admin/users/"+admin.ID, "", 400)
|
||||
payload := request("POST", "/api/auth/login", `{"email":"new@example.test","password":"secret123"}`, 200)
|
||||
var result struct {
|
||||
Data struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
}
|
||||
if err = json.Unmarshal(payload, &result); err != nil || result.Data.Token == "" {
|
||||
t.Fatal("login missing token", err)
|
||||
}
|
||||
token = result.Data.Token
|
||||
request("POST", "/api/admin/users", `{"email":"blocked@example.test","password":"secret123","role":"user"}`, 403)
|
||||
token, _ = auth.GenerateToken(admin.ID, admin.Email, "admin", "test-secret")
|
||||
request("POST", "/api/admin/users", `{"email":"second@example.test","password":"secret123","role":"admin"}`, 201)
|
||||
request("PUT", "/api/admin/users/"+admin.ID, `{"email":"admin@example.test","role":"user"}`, 200)
|
||||
count, err := repo.CountAdmins()
|
||||
if err != nil || count != 1 {
|
||||
t.Fatal("wrong admin count", count, err)
|
||||
}
|
||||
second, err := repo.GetUserByEmail("second@example.test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = repo.DeleteUser(second.ID); err != models.ErrLastAdmin {
|
||||
t.Fatal("last admin deletion", err)
|
||||
}
|
||||
}
|
||||
93
backend/internal/api/account_security_test.go
Normal file
93
backend/internal/api/account_security_test.go
Normal file
@ -0,0 +1,93 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/api"
|
||||
"github.com/tradarr/backend/internal/api/handlers"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
)
|
||||
|
||||
// These route contract tests deliberately use no database. They establish the
|
||||
// public/authentication boundary; database-backed account lifecycle cases are
|
||||
// covered separately when a disposable PostgreSQL test database is available.
|
||||
func accountRouter() *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
return api.SetupRouter(handlers.New(nil, &config.Config{JWTSecret: "test-secret"}, nil, nil, nil, nil), "test-secret")
|
||||
}
|
||||
|
||||
func TestPublicRegistrationIsUnavailable(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewBufferString(`{"email":"new@example.test","password":"secret123"}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
recorder := httptest.NewRecorder()
|
||||
accountRouter().ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusNotFound && recorder.Code != http.StatusGone && recorder.Code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("public registration must be unavailable; status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountCreationIsAdminOnly(t *testing.T) {
|
||||
token, err := auth.GenerateToken("viewer-id", "viewer@example.test", "user", "test-secret")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/admin/users", bytes.NewBufferString(`{"email":"new@example.test","password":"secret123","role":"user"}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
recorder := httptest.NewRecorder()
|
||||
accountRouter().ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusForbidden {
|
||||
t.Fatalf("viewer must be forbidden from creating accounts; status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserJSONNeverContainsPasswordSecrets(t *testing.T) {
|
||||
user := models.User{ID: "u1", Email: "admin@example.test", Role: models.RoleAdmin, PasswordHash: "$2a$secret"}
|
||||
payload, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, secret := range []string{"password_hash", "$2a$secret", "password"} {
|
||||
if bytes.Contains(payload, []byte(secret)) {
|
||||
t.Fatalf("user payload contains secret %q: %s", secret, payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountCreationRejectsUnauthenticatedAndInvalidInput(t *testing.T) {
|
||||
adminToken, err := auth.GenerateToken("admin-id", "admin@example.test", "admin", "test-secret")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
token, body string
|
||||
want int
|
||||
}{
|
||||
{"", `{"email":"new@example.test","password":"secret123","role":"user"}`, 401},
|
||||
{adminToken, `{"email":"bad","password":"secret123","role":"user"}`, 400},
|
||||
{adminToken, `{"email":"new@example.test","password":"short","role":"user"}`, 400},
|
||||
{adminToken, `{"email":"new@example.test","password":"secret123","role":"root"}`, 400},
|
||||
{adminToken, `{"email":"new@example.test","password":"secret123"}`, 400},
|
||||
} {
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/admin/users", bytes.NewBufferString(tc.body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if tc.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+tc.token)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
accountRouter().ServeHTTP(w, req)
|
||||
if w.Code != tc.want {
|
||||
t.Fatalf("got %d want %d: %s", w.Code, tc.want, w.Body.String())
|
||||
}
|
||||
if bytes.Contains(w.Body.Bytes(), []byte("secret123")) {
|
||||
t.Fatal("password leaked")
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -2,8 +2,12 @@ package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
@ -26,9 +30,9 @@ func (h *Handler) GetCredentials(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
type credResponse struct {
|
||||
SourceID string `json:"source_id"`
|
||||
SourceName string `json:"source_name"`
|
||||
Username string `json:"username"`
|
||||
SourceID string `json:"source_id"`
|
||||
SourceName string `json:"source_name"`
|
||||
Username string `json:"username"`
|
||||
HasPassword bool `json:"has_password"`
|
||||
}
|
||||
var result []credResponse
|
||||
@ -233,7 +237,8 @@ func (h *Handler) ListSources(c *gin.Context) {
|
||||
}
|
||||
|
||||
type updateSourceRequest struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Enabled bool `json:"enabled"`
|
||||
ArticleLimit *int `json:"article_limit" binding:"omitempty,min=1,max=200"`
|
||||
}
|
||||
|
||||
func (h *Handler) UpdateSource(c *gin.Context) {
|
||||
@ -242,7 +247,7 @@ func (h *Handler) UpdateSource(c *gin.Context) {
|
||||
httputil.BadRequest(c, err)
|
||||
return
|
||||
}
|
||||
if err := h.repo.UpdateSource(c.Param("id"), req.Enabled); err != nil {
|
||||
if err := h.repo.UpdateSource(c.Param("id"), req.Enabled, req.ArticleLimit); err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
@ -299,13 +304,22 @@ func (h *Handler) UpdateSettings(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
for _, s := range req.Settings {
|
||||
if err := h.repo.SetSetting(s.Key, s.Value); err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
if s.Key == "summary_max_articles" {
|
||||
limit, err := strconv.Atoi(s.Value)
|
||||
if err != nil || limit < 1 || limit > 500 {
|
||||
httputil.BadRequest(c, fmt.Errorf("summary_max_articles must be between 1 and 500"))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := h.scheduler.Reload(); err != nil {
|
||||
fmt.Printf("settings reload scheduler: %v\n", err)
|
||||
if err := h.repo.SetSettings(req.Settings); err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
if h.scheduler != nil {
|
||||
if err := h.scheduler.Reload(); err != nil {
|
||||
fmt.Printf("settings reload scheduler: %v\n", err)
|
||||
}
|
||||
}
|
||||
httputil.OK(c, gin.H{"ok": true})
|
||||
}
|
||||
@ -494,30 +508,53 @@ func (h *Handler) UpdateAdminUser(c *gin.Context) {
|
||||
}
|
||||
user, err := h.repo.UpdateUser(id, req.Email, models.Role(req.Role))
|
||||
if err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
accountError(c, err)
|
||||
return
|
||||
}
|
||||
httputil.OK(c, user)
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteAdminUser(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
// Empêcher la suppression du dernier admin
|
||||
user, err := h.repo.GetUserByID(id)
|
||||
if err != nil || user == nil {
|
||||
func accountError(c *gin.Context, err error) {
|
||||
switch {
|
||||
case errors.Is(err, models.ErrLastAdmin):
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "cannot remove the last admin"})
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
httputil.NotFound(c)
|
||||
return
|
||||
case models.IsDuplicateEmail(err):
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "email already in use"})
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "account operation failed"})
|
||||
}
|
||||
if user.Role == "admin" {
|
||||
count, _ := h.repo.CountAdmins()
|
||||
if count <= 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "cannot delete the last admin"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := h.repo.DeleteUser(id); err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
}
|
||||
func (h *Handler) DeleteAdminUser(c *gin.Context) {
|
||||
if err := h.repo.DeleteUser(c.Param("id")); err != nil {
|
||||
accountError(c, err)
|
||||
return
|
||||
}
|
||||
httputil.NoContent(c)
|
||||
}
|
||||
|
||||
type createUserRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required,min=6,max=72"`
|
||||
Role string `json:"role" binding:"required,oneof=admin user"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateAdminUser(c *gin.Context) {
|
||||
var req createUserRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid account fields"})
|
||||
return
|
||||
}
|
||||
hash, err := auth.HashPassword(req.Password)
|
||||
if err != nil {
|
||||
accountError(c, err)
|
||||
return
|
||||
}
|
||||
user, err := h.repo.CreateUser(req.Email, hash, models.Role(req.Role))
|
||||
if err != nil {
|
||||
accountError(c, err)
|
||||
return
|
||||
}
|
||||
httputil.Created(c, user)
|
||||
}
|
||||
|
||||
@ -6,7 +6,6 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"github.com/tradarr/backend/internal/httputil"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
)
|
||||
|
||||
type loginRequest struct {
|
||||
@ -14,11 +13,6 @@ type loginRequest struct {
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
type registerRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
}
|
||||
|
||||
func (h *Handler) Login(c *gin.Context) {
|
||||
var req loginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
@ -38,27 +32,4 @@ func (h *Handler) Login(c *gin.Context) {
|
||||
httputil.OK(c, gin.H{"token": token, "user": user})
|
||||
}
|
||||
|
||||
func (h *Handler) Register(c *gin.Context) {
|
||||
var req registerRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
httputil.BadRequest(c, err)
|
||||
return
|
||||
}
|
||||
existing, _ := h.repo.GetUserByEmail(req.Email)
|
||||
if existing != nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "email already in use"})
|
||||
return
|
||||
}
|
||||
hash, err := auth.HashPassword(req.Password)
|
||||
if err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
user, err := h.repo.CreateUser(req.Email, hash, models.RoleUser)
|
||||
if err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
token, _ := auth.GenerateToken(user.ID, user.Email, string(user.Role), h.cfg.JWTSecret)
|
||||
httputil.Created(c, gin.H{"token": token, "user": user})
|
||||
}
|
||||
func (h *Handler) Register(c *gin.Context) { c.Status(http.StatusGone) }
|
||||
|
||||
46
backend/internal/api/handlers/preferences.go
Normal file
46
backend/internal/api/handlers/preferences.go
Normal file
@ -0,0 +1,46 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/httputil"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
)
|
||||
|
||||
func preferencesError(c *gin.Context, err error) {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
httputil.NotFound(c)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "preferences unavailable"})
|
||||
}
|
||||
|
||||
func (h *Handler) GetMyPreferences(c *gin.Context) {
|
||||
if h.repo == nil {
|
||||
preferencesError(c, errors.New("repository unavailable"))
|
||||
return
|
||||
}
|
||||
p, err := h.repo.GetUserPreferences(c.GetString("userID"))
|
||||
if err != nil {
|
||||
preferencesError(c, err)
|
||||
return
|
||||
}
|
||||
httputil.OK(c, p)
|
||||
}
|
||||
|
||||
func (h *Handler) UpdateMyPreferences(c *gin.Context) {
|
||||
var req models.UserPreferences
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid preferences"})
|
||||
return
|
||||
}
|
||||
p, err := h.repo.UpdateUserPreferences(c.GetString("userID"), req)
|
||||
if err != nil {
|
||||
preferencesError(c, err)
|
||||
return
|
||||
}
|
||||
httputil.OK(c, p)
|
||||
}
|
||||
60
backend/internal/api/preferences_contract_test.go
Normal file
60
backend/internal/api/preferences_contract_test.go
Normal file
@ -0,0 +1,60 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/api"
|
||||
"github.com/tradarr/backend/internal/api/handlers"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
)
|
||||
|
||||
func TestPreferencesEndpointsExistAndRejectInvalidValues(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
token, err := auth.GenerateToken("user-1", "person@example.test", "user", "preferences-test-secret")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
router := api.SetupRouter(handlers.New(nil, &config.Config{JWTSecret: "preferences-test-secret"}, nil, nil, nil, nil), "preferences-test-secret")
|
||||
for _, tc := range []struct {
|
||||
method, body string
|
||||
want int
|
||||
}{
|
||||
{http.MethodGet, "", http.StatusOK},
|
||||
{http.MethodPut, `{"language":"de","ranking_mode":"title"}`, http.StatusBadRequest},
|
||||
{http.MethodPut, `{"language":"fr","ranking_mode":"unknown"}`, http.StatusBadRequest},
|
||||
} {
|
||||
req := httptest.NewRequest(tc.method, "/api/me/preferences", bytes.NewBufferString(tc.body))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
if tc.method == http.MethodPut {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
if tc.method == http.MethodGet {
|
||||
if w.Code == http.StatusNotFound {
|
||||
t.Errorf("GET /api/me/preferences is not registered; got status %d; body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
continue
|
||||
}
|
||||
if w.Code != tc.want {
|
||||
t.Errorf("%s /api/me/preferences got status %d, want %d; body=%s", tc.method, w.Code, tc.want, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreferencesRequireAuthentication(t *testing.T) {
|
||||
router := api.SetupRouter(handlers.New(nil, &config.Config{}, nil, nil, nil, nil), "preferences-test-secret")
|
||||
for _, method := range []string{http.MethodGet, http.MethodPut} {
|
||||
req := httptest.NewRequest(method, "/api/me/preferences", bytes.NewBufferString(`{"language":"fr","ranking_mode":"title"}`))
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("%s: status=%d", method, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
138
backend/internal/api/preferences_postgres_test.go
Normal file
138
backend/internal/api/preferences_postgres_test.go
Normal file
@ -0,0 +1,138 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lib/pq"
|
||||
"github.com/tradarr/backend/internal/api"
|
||||
"github.com/tradarr/backend/internal/api/handlers"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
)
|
||||
|
||||
func TestPreferencesPersistPerUserPostgres(t *testing.T) {
|
||||
dsn := postgresTestURL(t)
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
db.SetMaxOpenConns(1)
|
||||
schema := fmt.Sprintf("preferences_test_%d", time.Now().UnixNano())
|
||||
if _, err = db.Exec("CREATE SCHEMA " + pq.QuoteIdentifier(schema)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Exec("DROP SCHEMA " + pq.QuoteIdentifier(schema) + " CASCADE")
|
||||
if _, err = db.Exec("SET search_path TO " + pq.QuoteIdentifier(schema)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(`CREATE TABLE users (
|
||||
id UUID PRIMARY KEY, email TEXT NOT NULL UNIQUE, password_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'user', created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(`INSERT INTO users (id,email,password_hash) VALUES
|
||||
('00000000-0000-0000-0000-000000000001','one@example.test','hash'),
|
||||
('00000000-0000-0000-0000-000000000002','two@example.test','hash')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
migration, err := os.ReadFile("../database/migrations/000011_user_preferences.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(string(migration)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The two accounts predate migration 11: defaults must backfill both,
|
||||
// preserving credentials and identity.
|
||||
var defaults int
|
||||
if err = db.QueryRow(`SELECT COUNT(*) FROM users WHERE language='fr' AND ranking_mode='title' AND password_hash='hash'`).Scan(&defaults); err != nil || defaults != 2 {
|
||||
t.Fatalf("existing accounts were not preserved with defaults: count=%d err=%v", defaults, err)
|
||||
}
|
||||
secret := "preferences-test-secret"
|
||||
tokenFor := func(id, email string) string {
|
||||
t.Helper()
|
||||
token, tokenErr := auth.GenerateToken(id, email, "user", secret)
|
||||
if tokenErr != nil {
|
||||
t.Fatal(tokenErr)
|
||||
}
|
||||
return token
|
||||
}
|
||||
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret)
|
||||
call := func(method, token, body string, want int) map[string]any {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, "/api/me/preferences", bytes.NewBufferString(body))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
if method == http.MethodPut {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
if w.Code != want {
|
||||
t.Fatalf("%s preferences got status %d, want %d: %s", method, w.Code, want, w.Body.String())
|
||||
}
|
||||
var result map[string]any
|
||||
if w.Code == http.StatusOK {
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
firstToken := tokenFor("00000000-0000-0000-0000-000000000001", "one@example.test")
|
||||
secondToken := tokenFor("00000000-0000-0000-0000-000000000002", "two@example.test")
|
||||
first := call(http.MethodGet, firstToken, "", http.StatusOK)
|
||||
assertPreference(t, first, "language", "fr")
|
||||
assertPreference(t, first, "ranking_mode", "title")
|
||||
call(http.MethodPut, firstToken, `{"language":"en","ranking_mode":"title_content","user_id":"00000000-0000-0000-0000-000000000002"}`, http.StatusOK)
|
||||
updated := call(http.MethodGet, firstToken, "", http.StatusOK)
|
||||
assertPreference(t, updated, "language", "en")
|
||||
assertPreference(t, updated, "ranking_mode", "title_content")
|
||||
other := call(http.MethodGet, secondToken, "", http.StatusOK)
|
||||
assertPreference(t, other, "language", "fr")
|
||||
assertPreference(t, other, "ranking_mode", "title")
|
||||
call(http.MethodPut, firstToken, `{"language":"de","ranking_mode":"title"}`, http.StatusBadRequest)
|
||||
call(http.MethodPut, firstToken, `{"language":"fr","ranking_mode":"unknown"}`, http.StatusBadRequest)
|
||||
unchanged := call(http.MethodGet, firstToken, "", http.StatusOK)
|
||||
assertPreference(t, unchanged, "language", "en")
|
||||
assertPreference(t, unchanged, "ranking_mode", "title_content")
|
||||
for _, statement := range []string{
|
||||
`UPDATE users SET language='de'`,
|
||||
`UPDATE users SET ranking_mode='unknown'`,
|
||||
`UPDATE users SET language=NULL`,
|
||||
`UPDATE users SET ranking_mode=NULL`,
|
||||
} {
|
||||
if _, err = db.Exec(statement); err == nil {
|
||||
t.Fatalf("database accepted invalid preferences: %s", statement)
|
||||
}
|
||||
}
|
||||
rollback, err := os.ReadFile("../database/migrations/000011_user_preferences.down.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(string(rollback)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.QueryRow(`SELECT COUNT(*) FROM users WHERE password_hash='hash'`).Scan(&defaults); err != nil || defaults != 2 {
|
||||
t.Fatalf("rollback changed accounts: count=%d err=%v", defaults, err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func assertPreference(t *testing.T, response map[string]any, key, want string) {
|
||||
t.Helper()
|
||||
data, ok := response["data"].(map[string]any)
|
||||
if !ok || data[key] != want {
|
||||
t.Fatalf("preference %s got %v, want %q", key, response["data"], want)
|
||||
}
|
||||
}
|
||||
@ -28,13 +28,14 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
|
||||
|
||||
// Auth public
|
||||
api.POST("/auth/login", h.Login)
|
||||
api.POST("/auth/register", h.Register)
|
||||
|
||||
// Routes authentifiées
|
||||
authed := api.Group("/")
|
||||
authed.Use(auth.Middleware(jwtSecret))
|
||||
|
||||
authed.GET("/me", h.GetMe)
|
||||
authed.GET("/me/preferences", h.GetMyPreferences)
|
||||
authed.PUT("/me/preferences", h.UpdateMyPreferences)
|
||||
authed.GET("/me/assets", h.GetMyAssets)
|
||||
authed.POST("/me/assets", h.AddMyAsset)
|
||||
authed.DELETE("/me/assets/:symbol", h.RemoveMyAsset)
|
||||
@ -81,6 +82,7 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
|
||||
admin.PUT("/schedule", h.UpdateSchedule)
|
||||
|
||||
admin.GET("/users", h.ListUsers)
|
||||
admin.POST("/users", h.CreateAdminUser)
|
||||
admin.PUT("/users/:id", h.UpdateAdminUser)
|
||||
admin.DELETE("/users/:id", h.DeleteAdminUser)
|
||||
|
||||
|
||||
@ -0,0 +1,3 @@
|
||||
ALTER TABLE users
|
||||
DROP COLUMN ranking_mode,
|
||||
DROP COLUMN language;
|
||||
@ -0,0 +1,5 @@
|
||||
ALTER TABLE users
|
||||
ADD COLUMN language TEXT NOT NULL DEFAULT 'fr'
|
||||
CONSTRAINT users_language_check CHECK (language IN ('fr', 'en')),
|
||||
ADD COLUMN ranking_mode TEXT NOT NULL DEFAULT 'title'
|
||||
CONSTRAINT users_ranking_mode_check CHECK (ranking_mode IN ('title', 'title_content'));
|
||||
@ -0,0 +1,34 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUserPreferencesMigrationDefinesExistingAccountDefaults(t *testing.T) {
|
||||
up, err := os.ReadFile("000011_user_preferences.up.sql")
|
||||
if err != nil {
|
||||
t.Fatalf("read preferences migration: %v", err)
|
||||
}
|
||||
down, err := os.ReadFile("000011_user_preferences.down.sql")
|
||||
if err != nil {
|
||||
t.Fatalf("read preferences rollback: %v", err)
|
||||
}
|
||||
upSQL := strings.ToLower(string(up))
|
||||
for _, fragment := range []string{
|
||||
"alter table users",
|
||||
"default 'fr'",
|
||||
"default 'title'",
|
||||
"'en'",
|
||||
"'title_content'",
|
||||
} {
|
||||
if !strings.Contains(upSQL, fragment) {
|
||||
t.Errorf("preferences migration missing %q", fragment)
|
||||
}
|
||||
}
|
||||
downSQL := strings.ToLower(string(down))
|
||||
if !strings.Contains(downSQL, "alter table users") || !strings.Contains(downSQL, "drop column") {
|
||||
t.Errorf("preferences rollback must remove the added user preference columns; got %s", downSQL)
|
||||
}
|
||||
}
|
||||
25
backend/internal/models/account_errors_test.go
Normal file
25
backend/internal/models/account_errors_test.go
Normal file
@ -0,0 +1,25 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/lib/pq"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDuplicateEmailError(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{nil, false}, {errors.New("secret database detail"), false},
|
||||
{&pq.Error{Code: "23505", Constraint: "users_email_key"}, true},
|
||||
{fmt.Errorf("insert: %w", &pq.Error{Code: "23505", Constraint: "users_email_key"}), true},
|
||||
{&pq.Error{Code: "23505", Constraint: "users_pkey"}, false},
|
||||
{&pq.Error{Code: "23514", Constraint: "users_email_key"}, false},
|
||||
} {
|
||||
if got := IsDuplicateEmail(tc.err); got != tc.want {
|
||||
t.Fatalf("got %v want %v", got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -30,23 +30,24 @@ type UserAsset struct {
|
||||
}
|
||||
|
||||
type Source struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ArticleLimit int `json:"article_limit"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Article struct {
|
||||
ID string `json:"id"`
|
||||
SourceID string `json:"source_id"`
|
||||
SourceName string `json:"source_name,omitempty"`
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
URL string `json:"url"`
|
||||
PublishedAt sql.NullTime `json:"published_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Symbols []string `json:"symbols,omitempty"`
|
||||
ID string `json:"id"`
|
||||
SourceID string `json:"source_id"`
|
||||
SourceName string `json:"source_name,omitempty"`
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
URL string `json:"url"`
|
||||
PublishedAt sql.NullTime `json:"published_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Symbols []string `json:"symbols,omitempty"`
|
||||
}
|
||||
|
||||
type ArticleSymbol struct {
|
||||
@ -64,33 +65,33 @@ type ScrapeCredential struct {
|
||||
}
|
||||
|
||||
type ScrapeJob struct {
|
||||
ID string `json:"id"`
|
||||
SourceID string `json:"source_id"`
|
||||
SourceName string `json:"source_name,omitempty"`
|
||||
Status string `json:"status"`
|
||||
StartedAt sql.NullTime `json:"started_at"`
|
||||
FinishedAt sql.NullTime `json:"finished_at"`
|
||||
ArticlesFound int `json:"articles_found"`
|
||||
ErrorMsg string `json:"error_msg"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID string `json:"id"`
|
||||
SourceID string `json:"source_id"`
|
||||
SourceName string `json:"source_name,omitempty"`
|
||||
Status string `json:"status"`
|
||||
StartedAt sql.NullTime `json:"started_at"`
|
||||
FinishedAt sql.NullTime `json:"finished_at"`
|
||||
ArticlesFound int `json:"articles_found"`
|
||||
ErrorMsg string `json:"error_msg"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type AIProvider struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
APIKeyEncrypted string `json:"-"`
|
||||
Model string `json:"model"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
IsActive bool `json:"is_active"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
APIKeyEncrypted string `json:"-"`
|
||||
Model string `json:"model"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
IsActive bool `json:"is_active"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Summary struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
Content string `json:"content"`
|
||||
AIProviderID *string `json:"ai_provider_id"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
Content string `json:"content"`
|
||||
AIProviderID *string `json:"ai_provider_id"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
}
|
||||
|
||||
type Setting struct {
|
||||
@ -99,10 +100,10 @@ type Setting struct {
|
||||
}
|
||||
|
||||
type ScheduleSlot struct {
|
||||
ID string `json:"id"`
|
||||
DayOfWeek int `json:"day_of_week"` // 0=dimanche, 1=lundi ... 6=samedi
|
||||
Hour int `json:"hour"`
|
||||
Minute int `json:"minute"`
|
||||
ID string `json:"id"`
|
||||
DayOfWeek int `json:"day_of_week"` // 0=dimanche, 1=lundi ... 6=samedi
|
||||
Hour int `json:"hour"`
|
||||
Minute int `json:"minute"`
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
|
||||
19
backend/internal/models/preferences.go
Normal file
19
backend/internal/models/preferences.go
Normal file
@ -0,0 +1,19 @@
|
||||
package models
|
||||
|
||||
// UserPreferences is scoped by the authenticated user ID, never by a client field.
|
||||
type UserPreferences struct {
|
||||
Language string `json:"language" binding:"required,oneof=fr en"`
|
||||
RankingMode string `json:"ranking_mode" binding:"required,oneof=title title_content"`
|
||||
}
|
||||
|
||||
func (r *Repository) GetUserPreferences(userID string) (*UserPreferences, error) {
|
||||
p := &UserPreferences{}
|
||||
err := r.db.QueryRow(`SELECT language, ranking_mode FROM users WHERE id=$1`, userID).Scan(&p.Language, &p.RankingMode)
|
||||
return p, err
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateUserPreferences(userID string, preferences UserPreferences) (*UserPreferences, error) {
|
||||
p := &UserPreferences{}
|
||||
err := r.db.QueryRow(`UPDATE users SET language=$1, ranking_mode=$2, updated_at=NOW() WHERE id=$3 RETURNING language, ranking_mode`, preferences.Language, preferences.RankingMode, userID).Scan(&p.Language, &p.RankingMode)
|
||||
return p, err
|
||||
}
|
||||
18
backend/internal/models/preferences_test.go
Normal file
18
backend/internal/models/preferences_test.go
Normal file
@ -0,0 +1,18 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPreferencesValidation(t *testing.T) {
|
||||
for _, language := range []string{"fr", "en", "de", "", "FR"} {
|
||||
for _, mode := range []string{"title", "title_content", "unknown", ""} {
|
||||
p := UserPreferences{Language: language, RankingMode: mode}
|
||||
wantValid := (language == "fr" || language == "en") && (mode == "title" || mode == "title_content")
|
||||
if err := binding.Validator.ValidateStruct(p); (err == nil) != wantValid {
|
||||
t.Fatalf("%+v: valid=%v error=%v", p, wantValid, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -2,7 +2,9 @@ package models
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/lib/pq"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@ -71,21 +73,53 @@ func (r *Repository) ListUsers() ([]User, error) {
|
||||
return users, nil
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateUser(id, email string, role Role) (*User, error) {
|
||||
u := &User{}
|
||||
err := r.db.QueryRow(`
|
||||
UPDATE users SET email=$1, role=$2, updated_at=NOW()
|
||||
WHERE id=$3
|
||||
RETURNING id, email, password_hash, role, created_at, updated_at`,
|
||||
email, role, id,
|
||||
).Scan(&u.ID, &u.Email, &u.PasswordHash, &u.Role, &u.CreatedAt, &u.UpdatedAt)
|
||||
return u, err
|
||||
}
|
||||
var ErrLastAdmin = errors.New("cannot remove the last admin")
|
||||
|
||||
// Lock before counting so concurrent removals cannot both pass the guard.
|
||||
func (r *Repository) mutateUser(id, email string, role Role, remove bool) (*User, error) {
|
||||
tx, err := r.db.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.Exec(`LOCK TABLE users IN SHARE ROW EXCLUSIVE MODE`); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var previous Role
|
||||
if err = tx.QueryRow(`SELECT role FROM users WHERE id=$1`, id).Scan(&previous); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if previous == RoleAdmin && (remove || role != RoleAdmin) {
|
||||
var count int
|
||||
if err = tx.QueryRow(`SELECT COUNT(*) FROM users WHERE role='admin'`).Scan(&count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count <= 1 {
|
||||
return nil, ErrLastAdmin
|
||||
}
|
||||
}
|
||||
u := &User{}
|
||||
if remove {
|
||||
_, err = tx.Exec(`DELETE FROM users WHERE id=$1`, id)
|
||||
} else {
|
||||
err = tx.QueryRow(`UPDATE users SET email=$1, role=$2, updated_at=NOW() WHERE id=$3 RETURNING id, email, password_hash, role, created_at, updated_at`, email, role, id).Scan(&u.ID, &u.Email, &u.PasswordHash, &u.Role, &u.CreatedAt, &u.UpdatedAt)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u, tx.Commit()
|
||||
}
|
||||
func (r *Repository) UpdateUser(id, email string, role Role) (*User, error) {
|
||||
return r.mutateUser(id, email, role, false)
|
||||
}
|
||||
func (r *Repository) DeleteUser(id string) error {
|
||||
_, err := r.db.Exec(`DELETE FROM users WHERE id=$1`, id)
|
||||
_, err := r.mutateUser(id, "", "", true)
|
||||
return err
|
||||
}
|
||||
func IsDuplicateEmail(err error) bool {
|
||||
var pgErr *pq.Error
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.Constraint == "users_email_key"
|
||||
}
|
||||
|
||||
func (r *Repository) CountAdmins() (int, error) {
|
||||
var count int
|
||||
@ -153,7 +187,7 @@ func (r *Repository) GetAllWatchedSymbols() ([]string, error) {
|
||||
// ── Sources ────────────────────────────────────────────────────────────────
|
||||
|
||||
func (r *Repository) ListSources() ([]Source, error) {
|
||||
rows, err := r.db.Query(`SELECT id, name, type, enabled, created_at FROM sources ORDER BY name`)
|
||||
rows, err := r.db.Query(`SELECT id, name, type, enabled, created_at, article_limit FROM sources ORDER BY name`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -161,7 +195,7 @@ func (r *Repository) ListSources() ([]Source, error) {
|
||||
var sources []Source
|
||||
for rows.Next() {
|
||||
var s Source
|
||||
if err := rows.Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt); err != nil {
|
||||
if err := rows.Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sources = append(sources, s)
|
||||
@ -172,16 +206,23 @@ func (r *Repository) ListSources() ([]Source, error) {
|
||||
func (r *Repository) GetSourceByType(sourceType string) (*Source, error) {
|
||||
s := &Source{}
|
||||
err := r.db.QueryRow(`
|
||||
SELECT id, name, type, enabled, created_at FROM sources WHERE type=$1`, sourceType,
|
||||
).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt)
|
||||
SELECT id, name, type, enabled, created_at, article_limit FROM sources WHERE type=$1`, sourceType,
|
||||
).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return s, err
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateSource(id string, enabled bool) error {
|
||||
_, err := r.db.Exec(`UPDATE sources SET enabled=$1 WHERE id=$2`, enabled, id)
|
||||
func (r *Repository) UpdateSource(id string, enabled bool, articleLimit *int) error {
|
||||
result, err := r.db.Exec(`UPDATE sources SET enabled=$1, article_limit=COALESCE($2,article_limit) WHERE id=$3`, enabled, articleLimit, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
count, err := result.RowsAffected()
|
||||
if err == nil && count == 0 {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@ -718,3 +759,18 @@ func (r *Repository) ListReportMessages(reportID string) ([]ReportMessage, error
|
||||
}
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
// SetSettings commits a validated settings request as one unit.
|
||||
func (r *Repository) SetSettings(settings []Setting) error {
|
||||
tx, err := r.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
for _, s := range settings {
|
||||
if _, err = tx.Exec(`INSERT INTO settings (key,value) VALUES ($1,$2) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value`, s.Key, s.Value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user