mirror of
https://github.com/getAlby/lndhub.go.git
synced 2025-12-18 13:14:56 +01:00
Soft delete users (#476)
* Update Makefile * Optionally load test DB from env variable * Add option to soft-delete a user This allows users to be marked as deleted. An additional middleware checks if a user is deleted or deactivated and rejects requests for those as StatusUnauthorized. note: the middelware adds an additional DB query to load the user.
This commit is contained in:
5
Makefile
5
Makefile
@@ -2,4 +2,7 @@
|
|||||||
cp .env_example .env
|
cp .env_example .env
|
||||||
|
|
||||||
build:
|
build:
|
||||||
CGO_ENABLED=0 go build -o lndhub
|
CGO_ENABLED=0 go build -o lndhub ./cmd/server
|
||||||
|
|
||||||
|
test:
|
||||||
|
go test -p 1 -v -covermode=atomic -coverprofile=coverage.out -cover -coverpkg=./... ./...
|
||||||
|
|||||||
@@ -153,8 +153,8 @@ func main() {
|
|||||||
logMw := transport.CreateLoggingMiddleware(logger)
|
logMw := transport.CreateLoggingMiddleware(logger)
|
||||||
// strict rate limit for requests for sending payments
|
// strict rate limit for requests for sending payments
|
||||||
strictRateLimitMiddleware := transport.CreateRateLimitMiddleware(c.StrictRateLimit, c.BurstRateLimit)
|
strictRateLimitMiddleware := transport.CreateRateLimitMiddleware(c.StrictRateLimit, c.BurstRateLimit)
|
||||||
secured := e.Group("", tokens.Middleware(c.JWTSecret), logMw)
|
secured := e.Group("", tokens.Middleware(c.JWTSecret), svc.ValidateUserMiddleware(), logMw)
|
||||||
securedWithStrictRateLimit := e.Group("", tokens.Middleware(c.JWTSecret), strictRateLimitMiddleware, logMw)
|
securedWithStrictRateLimit := e.Group("", tokens.Middleware(c.JWTSecret), svc.ValidateUserMiddleware(), strictRateLimitMiddleware, logMw)
|
||||||
|
|
||||||
transport.RegisterLegacyEndpoints(svc, e, secured, securedWithStrictRateLimit, strictRateLimitMiddleware, tokens.AdminTokenMiddleware(c.AdminToken), logMw)
|
transport.RegisterLegacyEndpoints(svc, e, secured, securedWithStrictRateLimit, strictRateLimitMiddleware, tokens.AdminTokenMiddleware(c.AdminToken), logMw)
|
||||||
transport.RegisterV2Endpoints(svc, e, secured, securedWithStrictRateLimit, strictRateLimitMiddleware, tokens.AdminTokenMiddleware(c.AdminToken), logMw)
|
transport.RegisterV2Endpoints(svc, e, secured, securedWithStrictRateLimit, strictRateLimitMiddleware, tokens.AdminTokenMiddleware(c.AdminToken), logMw)
|
||||||
|
|||||||
@@ -20,12 +20,14 @@ func NewUpdateUserController(svc *service.LndhubService) *UpdateUserController {
|
|||||||
type UpdateUserResponseBody struct {
|
type UpdateUserResponseBody struct {
|
||||||
Login string `json:"login"`
|
Login string `json:"login"`
|
||||||
Deactivated bool `json:"deactivated"`
|
Deactivated bool `json:"deactivated"`
|
||||||
|
Deleted bool `json:"deleted"`
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
}
|
}
|
||||||
type UpdateUserRequestBody struct {
|
type UpdateUserRequestBody struct {
|
||||||
Login *string `json:"login,omitempty"`
|
Login *string `json:"login,omitempty"`
|
||||||
Password *string `json:"password,omitempty"`
|
Password *string `json:"password,omitempty"`
|
||||||
Deactivated *bool `json:"deactivated,omitempty"`
|
Deactivated *bool `json:"deactivated,omitempty"`
|
||||||
|
Deleted *bool `json:"deleted,omitempty"`
|
||||||
ID int64 `json:"id" validate:"required"`
|
ID int64 `json:"id" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,7 +54,7 @@ func (controller *UpdateUserController) UpdateUser(c echo.Context) error {
|
|||||||
c.Logger().Errorf("Invalid update user request body error: %v", err)
|
c.Logger().Errorf("Invalid update user request body error: %v", err)
|
||||||
return c.JSON(http.StatusBadRequest, responses.BadArgumentsError)
|
return c.JSON(http.StatusBadRequest, responses.BadArgumentsError)
|
||||||
}
|
}
|
||||||
user, err := controller.svc.UpdateUser(c.Request().Context(), body.ID, body.Login, body.Password, body.Deactivated)
|
user, err := controller.svc.UpdateUser(c.Request().Context(), body.ID, body.Login, body.Password, body.Deactivated, body.Deleted)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.Logger().Errorf("Failed to update user: %v", err)
|
c.Logger().Errorf("Failed to update user: %v", err)
|
||||||
return c.JSON(http.StatusBadRequest, responses.BadArgumentsError)
|
return c.JSON(http.StatusBadRequest, responses.BadArgumentsError)
|
||||||
@@ -61,6 +63,7 @@ func (controller *UpdateUserController) UpdateUser(c echo.Context) error {
|
|||||||
var ResponseBody UpdateUserResponseBody
|
var ResponseBody UpdateUserResponseBody
|
||||||
ResponseBody.Login = user.Login
|
ResponseBody.Login = user.Login
|
||||||
ResponseBody.Deactivated = user.Deactivated
|
ResponseBody.Deactivated = user.Deactivated
|
||||||
|
ResponseBody.Deleted = user.Deleted
|
||||||
ResponseBody.ID = user.ID
|
ResponseBody.ID = user.ID
|
||||||
|
|
||||||
return c.JSON(http.StatusOK, &ResponseBody)
|
return c.JSON(http.StatusOK, &ResponseBody)
|
||||||
|
|||||||
1
db/migrations/20240103130000_add_deleted_to_users.up.sql
Normal file
1
db/migrations/20240103130000_add_deleted_to_users.up.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
alter table users add column deleted boolean default false;
|
||||||
@@ -19,6 +19,7 @@ type User struct {
|
|||||||
Invoices []*Invoice `bun:"rel:has-many,join:id=user_id"`
|
Invoices []*Invoice `bun:"rel:has-many,join:id=user_id"`
|
||||||
Accounts []*Account `bun:"rel:has-many,join:id=user_id"`
|
Accounts []*Account `bun:"rel:has-many,join:id=user_id"`
|
||||||
Deactivated bool
|
Deactivated bool
|
||||||
|
Deleted bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *User) BeforeAppendModel(ctx context.Context, query bun.Query) error {
|
func (u *User) BeforeAppendModel(ctx context.Context, query bun.Query) error {
|
||||||
|
|||||||
101
integration_tests/deactivated_deleted_test.go
Normal file
101
integration_tests/deactivated_deleted_test.go
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
package integration_tests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/getAlby/lndhub.go/controllers"
|
||||||
|
"github.com/getAlby/lndhub.go/lib"
|
||||||
|
"github.com/getAlby/lndhub.go/lib/responses"
|
||||||
|
"github.com/getAlby/lndhub.go/lib/service"
|
||||||
|
"github.com/getAlby/lndhub.go/lib/tokens"
|
||||||
|
"github.com/go-playground/validator/v10"
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/suite"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ValidateUserSuite struct {
|
||||||
|
TestSuite
|
||||||
|
Service *service.LndhubService
|
||||||
|
userLogin ExpectedCreateUserResponseBody
|
||||||
|
userToken string
|
||||||
|
mockLND *MockLND
|
||||||
|
invoiceUpdateSubCancelFn context.CancelFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (suite *ValidateUserSuite) SetupSuite() {
|
||||||
|
mockLND := newDefaultMockLND()
|
||||||
|
svc, err := LndHubTestServiceInit(mockLND)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Error initializing test service: %v", err)
|
||||||
|
}
|
||||||
|
users, userTokens, err := createUsers(svc, 1)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Error creating test users %v", err)
|
||||||
|
}
|
||||||
|
suite.Service = svc
|
||||||
|
suite.mockLND = mockLND
|
||||||
|
e := echo.New()
|
||||||
|
|
||||||
|
e.HTTPErrorHandler = responses.HTTPErrorHandler
|
||||||
|
e.Validator = &lib.CustomValidator{Validator: validator.New()}
|
||||||
|
suite.echo = e
|
||||||
|
suite.echo.Use(tokens.Middleware([]byte(suite.Service.Config.JWTSecret)))
|
||||||
|
suite.echo.Use(svc.ValidateUserMiddleware())
|
||||||
|
suite.echo.GET("/gettxs", controllers.NewGetTXSController(suite.Service).GetTXS)
|
||||||
|
suite.echo.GET("/getuserinvoices", controllers.NewGetTXSController(svc).GetUserInvoices)
|
||||||
|
suite.echo.POST("/addinvoice", controllers.NewAddInvoiceController(suite.Service).AddInvoice)
|
||||||
|
suite.echo.POST("/payinvoice", controllers.NewPayInvoiceController(suite.Service).PayInvoice)
|
||||||
|
|
||||||
|
assert.Equal(suite.T(), 1, len(users))
|
||||||
|
suite.userLogin = users[0]
|
||||||
|
suite.userToken = userTokens[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (suite *ValidateUserSuite) TearDownSuite() {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (suite *ValidateUserSuite) TestDeletedUserValidation() {
|
||||||
|
_, err := suite.Service.DB.NewUpdate().Table("users").Set("deleted = ?", true).Where("login = ?", suite.userLogin.Login).Exec(context.TODO())
|
||||||
|
assert.NoError(suite.T(), err)
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/gettxs", nil)
|
||||||
|
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", suite.userToken))
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
suite.echo.ServeHTTP(rec, req)
|
||||||
|
assert.Equal(suite.T(), http.StatusUnauthorized, rec.Code)
|
||||||
|
|
||||||
|
_, err = suite.Service.DB.NewUpdate().Table("users").Set("deleted = ?", false).Where("login = ?", suite.userLogin.Login).Exec(context.TODO())
|
||||||
|
assert.NoError(suite.T(), err)
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/gettxs", nil)
|
||||||
|
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", suite.userToken))
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
suite.echo.ServeHTTP(rec, req)
|
||||||
|
assert.Equal(suite.T(), http.StatusOK, rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (suite *ValidateUserSuite) TestDeactivatedUserValidation() {
|
||||||
|
_, err := suite.Service.DB.NewUpdate().Table("users").Set("deactivated = ?, deleted = false", true).Where("login = ?", suite.userLogin.Login).Exec(context.TODO())
|
||||||
|
assert.NoError(suite.T(), err)
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/gettxs", nil)
|
||||||
|
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", suite.userToken))
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
suite.echo.ServeHTTP(rec, req)
|
||||||
|
assert.Equal(suite.T(), http.StatusUnauthorized, rec.Code)
|
||||||
|
|
||||||
|
_, err = suite.Service.DB.NewUpdate().Table("users").Set("deactivated = ?, deleted = false", false).Where("login = ?", suite.userLogin.Login).Exec(context.TODO())
|
||||||
|
assert.NoError(suite.T(), err)
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/gettxs", nil)
|
||||||
|
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", suite.userToken))
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
suite.echo.ServeHTTP(rec, req)
|
||||||
|
assert.Equal(suite.T(), http.StatusOK, rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateUserSuite(t *testing.T) {
|
||||||
|
suite.Run(t, new(ValidateUserSuite))
|
||||||
|
}
|
||||||
@@ -47,7 +47,10 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func LndHubTestServiceInit(lndClientMock lnd.LightningClientWrapper) (svc *service.LndhubService, err error) {
|
func LndHubTestServiceInit(lndClientMock lnd.LightningClientWrapper) (svc *service.LndhubService, err error) {
|
||||||
dbUri := "postgresql://user:password@localhost/lndhub?sslmode=disable"
|
dbUri, ok := os.LookupEnv("DATABASE_URI")
|
||||||
|
if !ok {
|
||||||
|
dbUri = "postgresql://user:password@localhost/lndhub?sslmode=disable"
|
||||||
|
}
|
||||||
c := &service.Config{
|
c := &service.Config{
|
||||||
DatabaseUri: dbUri,
|
DatabaseUri: dbUri,
|
||||||
DatabaseMaxConns: 1,
|
DatabaseMaxConns: 1,
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package service
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/getAlby/lndhub.go/rabbitmq"
|
"github.com/getAlby/lndhub.go/rabbitmq"
|
||||||
@@ -11,6 +12,7 @@ import (
|
|||||||
"github.com/getAlby/lndhub.go/lib/responses"
|
"github.com/getAlby/lndhub.go/lib/responses"
|
||||||
"github.com/getAlby/lndhub.go/lib/tokens"
|
"github.com/getAlby/lndhub.go/lib/tokens"
|
||||||
"github.com/getAlby/lndhub.go/lnd"
|
"github.com/getAlby/lndhub.go/lnd"
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
"github.com/labstack/gommon/random"
|
"github.com/labstack/gommon/random"
|
||||||
"github.com/uptrace/bun"
|
"github.com/uptrace/bun"
|
||||||
"github.com/ziflex/lecho/v3"
|
"github.com/ziflex/lecho/v3"
|
||||||
@@ -58,7 +60,7 @@ func (svc *LndhubService) GenerateToken(ctx context.Context, login, password, in
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.Deactivated {
|
if user.Deactivated || user.Deleted {
|
||||||
return "", "", fmt.Errorf(responses.AccountDeactivatedError.Message)
|
return "", "", fmt.Errorf(responses.AccountDeactivatedError.Message)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,3 +90,30 @@ func (svc *LndhubService) ParseInt(value interface{}) (int64, error) {
|
|||||||
return 0, fmt.Errorf("conversion to int from %T not supported", v)
|
return 0, fmt.Errorf("conversion to int from %T not supported", v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (svc *LndhubService) ValidateUserMiddleware() echo.MiddlewareFunc {
|
||||||
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||||
|
return func(c echo.Context) error {
|
||||||
|
userId := c.Get("UserID").(int64)
|
||||||
|
if userId == 0 {
|
||||||
|
return echo.ErrUnauthorized
|
||||||
|
}
|
||||||
|
user, err := svc.FindUser(c.Request().Context(), userId)
|
||||||
|
if err != nil {
|
||||||
|
return echo.NewHTTPError(http.StatusUnauthorized, echo.Map{
|
||||||
|
"error": true,
|
||||||
|
"code": 1,
|
||||||
|
"message": "bad auth",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if user.Deactivated || user.Deleted {
|
||||||
|
return echo.NewHTTPError(http.StatusUnauthorized, echo.Map{
|
||||||
|
"error": true,
|
||||||
|
"code": 1,
|
||||||
|
"message": "bad auth",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return next(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ func (svc *LndhubService) CreateUser(ctx context.Context, login string, password
|
|||||||
return user, err
|
return user, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (svc *LndhubService) UpdateUser(ctx context.Context, userId int64, login *string, password *string, deactivated *bool) (user *models.User, err error) {
|
func (svc *LndhubService) UpdateUser(ctx context.Context, userId int64, login *string, password *string, deactivated *bool, deleted *bool) (user *models.User, err error) {
|
||||||
user, err = svc.FindUser(ctx, userId)
|
user, err = svc.FindUser(ctx, userId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -99,6 +99,14 @@ func (svc *LndhubService) UpdateUser(ctx context.Context, userId int64, login *s
|
|||||||
if deactivated != nil {
|
if deactivated != nil {
|
||||||
user.Deactivated = *deactivated
|
user.Deactivated = *deactivated
|
||||||
}
|
}
|
||||||
|
// if a user gets deleted we mark it as deactivated and deleted
|
||||||
|
// un-deleting it is not supported currently
|
||||||
|
if deleted != nil {
|
||||||
|
if *deleted == true {
|
||||||
|
user.Deactivated = true
|
||||||
|
user.Deleted = true
|
||||||
|
}
|
||||||
|
}
|
||||||
_, err = svc.DB.NewUpdate().Model(user).WherePK().Exec(ctx)
|
_, err = svc.DB.NewUpdate().Model(user).WherePK().Exec(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -15,13 +15,13 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type jwtCustomClaims struct {
|
type jwtCustomClaims struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
IsRefresh bool `json:"isRefresh"`
|
IsRefresh bool `json:"isRefresh"`
|
||||||
MaxSendVolume int64 `json:"maxSendVolume"`
|
MaxSendVolume int64 `json:"maxSendVolume"`
|
||||||
MaxSendAmount int64 `json:"maxSendAmount"`
|
MaxSendAmount int64 `json:"maxSendAmount"`
|
||||||
MaxReceiveVolume int64 `json:"maxReceiveVolume"`
|
MaxReceiveVolume int64 `json:"maxReceiveVolume"`
|
||||||
MaxReceiveAmount int64 `json:"maxReceiveAmount"`
|
MaxReceiveAmount int64 `json:"maxReceiveAmount"`
|
||||||
MaxAccountBalance int64 `json:"maxAccountBalance"`
|
MaxAccountBalance int64 `json:"maxAccountBalance"`
|
||||||
jwt.StandardClaims
|
jwt.StandardClaims
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user