Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

use command bus for service communication (#743)

Guilherme Oenning00c95eea7daa
diff --git a/.circleci/config.yml b/.circleci/config.yml
index 335efffd0..54faf1080 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -1,7 +1,7 @@
version: 2
references:
builder: &builder
- getfider/circleci:0.0.19
+ getfider/circleci:0.0.20
workdir: &workdir
/go/src/github.com/getfider/fider
diff --git a/.test.env b/.test.env
index 5bad92c7a..9f57756eb 100644
--- a/.test.env
+++ b/.test.env
@@ -12,6 +12,8 @@ BLOB_STORAGE_S3_ACCESS_KEY_ID=s3user
BLOB_STORAGE_S3_SECRET_ACCESS_KEY=s3user-s3cr3t
BLOB_STORAGE_S3_BUCKET=test-bucket
+BLOB_STORAGE_FS_PATH=./testdata/tmp/fs_test
+
CDN_HOST=
OAUTH_FACEBOOK_APPID=FB_CL_ID
@@ -25,7 +27,10 @@ OAUTH_GITHUB_SECRET=GH_CL_SECRET
-EMAIL_SMTP_HOST=smtp.random.org
-EMAIL_SMTP_PORT=465
-EMAIL_SMTP_PASSWORD=random
\ No newline at end of file
+EMAIL_SMTP_HOST=localhost
+EMAIL_SMTP_PORT=1234
+EMAIL_SMTP_USERNAME=us3r
+EMAIL_SMTP_PASSWORD=p4ss
+
+EMAIL_MAILGUN_API=mys3cr3tk3y
+EMAIL_MAILGUN_DOMAIN=mydomain.com
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
index de4f84b1e..55e8b7fdb 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -16,4 +16,4 @@ EXPOSE 3000
HEALTHCHECK --timeout=5s CMD ./fider ping
-CMD [ "./fider" ]
\ No newline at end of file
+CMD ./fider migrate && ./fider
\ No newline at end of file
diff --git a/GUIDELINES.md b/GUIDELINES.md
index 548b70163..ba3cbd7a9 100644
--- a/GUIDELINES.md
+++ b/GUIDELINES.md
@@ -1,6 +1,12 @@
# Server Development
-...
+**Models Naming**
+
+* `app/models/action.<something>`: actions are based on user interaction for POST/PUT/PATCH requests. Actions map 1-to-1 with an Command. E.g: `action.CreateNewUser`;
+* `app/models/dto.<something>`: A simple object used for data transfer between various packages/services. E.g: `dto.NewUserInfo`;
+* `app/models/entity.<something>`: An object that is mapped to a database table. E.g: `entity.User`;
+* `app/models/cmd.<something>` something that must be done and potentially return some value. E.g.: `cmd.HttpRequest`, `cmd.LogDebug`, `cmd.SendMail`, `cmd.CreateNewUser`;
+* `app/models/query.<something>` get some information from somewhere. E.g.: `query.GetUserById`, `query.GetBillingStatus`;
# UI Development
diff --git a/app/actions/actions.go b/app/actions/actions.go
index 8905fd00c..24f8798af 100644
--- a/app/actions/actions.go
+++ b/app/actions/actions.go
@@ -1,7 +1,8 @@
package actions
import (
- "github.com/getfider/fider/app"
+ "context"
+
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/validate"
)
@@ -9,6 +10,6 @@ import (
// Actionable is any action that the user can perform using the web app
type Actionable interface {
Initialize() interface{}
- IsAuthorized(user *models.User, services *app.Services) bool
- Validate(user *models.User, services *app.Services) *validate.Result
+ IsAuthorized(ctx context.Context, user *models.User) bool
+ Validate(ctx context.Context, user *models.User) *validate.Result
}
diff --git a/app/actions/actions_test.go b/app/actions/actions_test.go
index 9ffebce51..49ac1d11f 100644
--- a/app/actions/actions_test.go
+++ b/app/actions/actions_test.go
@@ -1,14 +1,9 @@
package actions_test
import (
- "github.com/getfider/fider/app"
. "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/billing"
- "github.com/getfider/fider/app/pkg/blob/fs"
- "github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/validate"
- "github.com/getfider/fider/app/storage/inmemory"
)
var jonSnowToken, _ = jwt.Encode(jwt.OAuthClaims{
@@ -18,16 +13,6 @@ var jonSnowToken, _ = jwt.Encode(jwt.OAuthClaims{
OAuthProvider: "facebook",
})
-var services = &app.Services{
- Tenants: inmemory.NewTenantStorage(),
- Users: &inmemory.UserStorage{},
- Posts: inmemory.NewPostStorage(),
- Tags: inmemory.NewTagStorage(),
- Notifications: inmemory.NewNotificationStorage(),
- Blobs: fs.NewStorage(env.Path("tmp")),
- Billing: billing.NewClient(),
-}
-
func ExpectFailed(result *validate.Result, expectedFields ...string) {
Expect(result.Ok).IsFalse()
Expect(result.Err).IsNil()
diff --git a/app/actions/billing.go b/app/actions/billing.go
index b34c412cb..a1c756277 100644
--- a/app/actions/billing.go
+++ b/app/actions/billing.go
@@ -1,33 +1,40 @@
package actions
import (
+ "context"
"fmt"
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
+
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/log"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/dto"
"github.com/getfider/fider/app/pkg/validate"
"github.com/goenning/vat"
)
// CreateEditBillingPaymentInfo is used to create/edit billing payment info
type CreateEditBillingPaymentInfo struct {
- Model *models.CreateEditBillingPaymentInfo
+ Model *dto.CreateEditBillingPaymentInfo
}
// Initialize the model
func (input *CreateEditBillingPaymentInfo) Initialize() interface{} {
- input.Model = new(models.CreateEditBillingPaymentInfo)
+ input.Model = new(dto.CreateEditBillingPaymentInfo)
return input.Model
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateEditBillingPaymentInfo) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *CreateEditBillingPaymentInfo) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil && user.IsAdministrator()
}
-// Validate is current model is valid
-func (input *CreateEditBillingPaymentInfo) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *CreateEditBillingPaymentInfo) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
if input.Model.Name == "" {
@@ -59,16 +66,17 @@ func (input *CreateEditBillingPaymentInfo) Validate(user *models.User, services
result.AddFieldFailure("addressPostalCode", "Postal Code is required.")
}
- current, err := services.Billing.GetPaymentInfo()
+ getPaymentInfo := &query.GetPaymentInfo{}
+ err := bus.Dispatch(ctx, getPaymentInfo)
+ if err != nil {
+ return validate.Error(err)
+ }
+ current := getPaymentInfo.Result
isNew := current == nil
isUpdate := current != nil && input.Model.Card == nil
isReplacing := current != nil && input.Model.Card != nil
- if err != nil {
- return validate.Error(err)
- }
-
if (isNew || isReplacing) && (input.Model.Card == nil || input.Model.Card.Token == "") {
result.AddFieldFailure("card", "Card information is required.")
}
@@ -76,16 +84,14 @@ func (input *CreateEditBillingPaymentInfo) Validate(user *models.User, services
if input.Model.AddressCountry == "" {
result.AddFieldFailure("addressCountry", "Country is required.")
} else {
- countries := models.GetAllCountries()
- found := false
- for _, c := range countries {
- if c.Code == input.Model.AddressCountry {
- found = true
+ err := bus.Dispatch(ctx, &query.GetCountryByCode{Code: input.Model.AddressCountry})
+ if err != nil {
+ if err == app.ErrNotFound {
+ result.AddFieldFailure("addressCountry", fmt.Sprintf("'%s' is not a valid country code.", input.Model.AddressCountry))
+ } else {
+ return validate.Error(err)
}
}
- if !found {
- result.AddFieldFailure("addressCountry", fmt.Sprintf("'%s' is not a valid country code.", input.Model.AddressCountry))
- }
if (isNew || isReplacing) && input.Model.Card != nil && input.Model.AddressCountry != input.Model.Card.Country {
result.AddFieldFailure("addressCountry", "Country doesn't match with card issue country.")
@@ -114,7 +120,7 @@ func (input *CreateEditBillingPaymentInfo) Validate(user *models.User, services
if err == vat.ErrInvalidVATNumberFormat {
result.AddFieldFailure("vatNumber", "VAT Number is an invalid format.")
} else {
- services.Logger.Error(errors.Wrap(err, "failed to validate VAT Number '%s'", input.Model.VATNumber))
+ log.Error(ctx, errors.Wrap(err, "failed to validate VAT Number '%s'", input.Model.VATNumber))
result.AddFieldFailure("vatNumber", "We couldn't validate your VAT Number right now, please try again soon.")
}
}
diff --git a/app/actions/billing_test.go b/app/actions/billing_test.go
index 192b0cac9..3a0babe05 100644
--- a/app/actions/billing_test.go
+++ b/app/actions/billing_test.go
@@ -1,27 +1,35 @@
package actions_test
import (
+ "context"
"testing"
+ "github.com/getfider/fider/app/services/billing"
+
+ "github.com/getfider/fider/app"
+
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/dto"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
)
func TestCreateEditBillingPaymentInfo_InvalidInput(t *testing.T) {
RegisterT(t)
+ bus.Init(billing.Service{})
testCases := []struct {
expected []string
- input *models.CreateEditBillingPaymentInfo
+ input *dto.CreateEditBillingPaymentInfo
}{
{
expected: []string{"card", "name", "email", "addressLine1", "addressLine2", "addressCity", "addressPostalCode", "addressCountry"},
- input: &models.CreateEditBillingPaymentInfo{},
+ input: &dto.CreateEditBillingPaymentInfo{},
},
{
expected: []string{"card", "email", "addressCity", "addressPostalCode", "addressCountry"},
- input: &models.CreateEditBillingPaymentInfo{
+ input: &dto.CreateEditBillingPaymentInfo{
Name: "John",
AddressLine1: "Street 1",
AddressLine2: "Street 2",
@@ -31,13 +39,13 @@ func TestCreateEditBillingPaymentInfo_InvalidInput(t *testing.T) {
},
{
expected: []string{"card", "email", "addressCity", "addressPostalCode", "addressCountry"},
- input: &models.CreateEditBillingPaymentInfo{
+ input: &dto.CreateEditBillingPaymentInfo{
Name: "John",
AddressLine1: "Street 1",
AddressLine2: "Street 2",
Email: "jo@a",
AddressCountry: "US",
- Card: &models.CreateEditBillingPaymentInfoCard{
+ Card: &dto.CreateEditBillingPaymentInfoCard{
Country: "IE",
},
},
@@ -48,17 +56,18 @@ func TestCreateEditBillingPaymentInfo_InvalidInput(t *testing.T) {
action := &actions.CreateEditBillingPaymentInfo{
Model: testCase.input,
}
- services.Billing.SetCurrentTenant(&models.Tenant{ID: 2})
- result := action.Validate(nil, services)
+ ctx := context.WithValue(context.Background(), app.TenantCtxKey, &models.Tenant{ID: 2})
+ result := action.Validate(ctx, nil)
ExpectFailed(result, testCase.expected...)
}
}
func TestCreateEditBillingPaymentInfo_ValidInput(t *testing.T) {
RegisterT(t)
+ bus.Init(billing.Service{})
action := &actions.CreateEditBillingPaymentInfo{
- Model: &models.CreateEditBillingPaymentInfo{
+ Model: &dto.CreateEditBillingPaymentInfo{
Name: "Jon Snow",
AddressLine1: "Street 1",
AddressLine2: "Street 2",
@@ -67,24 +76,25 @@ func TestCreateEditBillingPaymentInfo_ValidInput(t *testing.T) {
AddressState: "NY",
AddressCountry: "US",
- Card: &models.CreateEditBillingPaymentInfoCard{
+ Card: &dto.CreateEditBillingPaymentInfoCard{
Token: "tok_visa",
Country: "US",
},
},
}
- services.Billing.SetCurrentTenant(&models.Tenant{ID: 2})
- result := action.Validate(nil, services)
+ ctx := context.WithValue(context.Background(), app.TenantCtxKey, &models.Tenant{ID: 2})
+ result := action.Validate(ctx, nil)
ExpectSuccess(result)
}
func TestCreateEditBillingPaymentInfo_VATNumber(t *testing.T) {
RegisterT(t)
+ bus.Init(billing.Service{})
- services.Billing.SetCurrentTenant(&models.Tenant{ID: 2})
+ ctx := context.WithValue(context.Background(), app.TenantCtxKey, &models.Tenant{ID: 2})
action := &actions.CreateEditBillingPaymentInfo{
- Model: &models.CreateEditBillingPaymentInfo{
+ Model: &dto.CreateEditBillingPaymentInfo{
Name: "Jon Snow",
AddressLine1: "Street 1",
AddressLine2: "Street 2",
@@ -94,28 +104,28 @@ func TestCreateEditBillingPaymentInfo_VATNumber(t *testing.T) {
AddressCountry: "IE",
VATNumber: "IE0",
- Card: &models.CreateEditBillingPaymentInfoCard{
+ Card: &dto.CreateEditBillingPaymentInfoCard{
Token: "tok_visa",
Country: "IE",
},
},
}
- result := action.Validate(nil, services)
+ result := action.Validate(ctx, nil)
ExpectFailed(result, "vatNumber")
action.Model.VATNumber = "GB270600730"
- result = action.Validate(nil, services)
+ result = action.Validate(ctx, nil)
ExpectFailed(result, "vatNumber")
action.Model.VATNumber = "IE6388047A"
- result = action.Validate(nil, services)
+ result = action.Validate(ctx, nil)
ExpectFailed(result, "vatNumber")
action.Model.VATNumber = "IE6388047V"
- result = action.Validate(nil, services)
+ result = action.Validate(ctx, nil)
ExpectSuccess(result)
action.Model.VATNumber = ""
- result = action.Validate(nil, services)
+ result = action.Validate(ctx, nil)
ExpectSuccess(result)
}
diff --git a/app/actions/invite.go b/app/actions/invite.go
index 4033bfdee..8a53f4358 100644
--- a/app/actions/invite.go
+++ b/app/actions/invite.go
@@ -1,9 +1,13 @@
package actions
import (
+ "context"
"fmt"
"strings"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/errors"
@@ -24,12 +28,12 @@ func (input *InviteUsers) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *InviteUsers) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *InviteUsers) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil && user.IsCollaborator()
}
-// Validate is current model is valid
-func (input *InviteUsers) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *InviteUsers) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
if input.Model.Subject == "" {
@@ -65,7 +69,7 @@ func (input *InviteUsers) Validate(user *models.User, services *app.Services) *v
input.Invitations = make([]*models.UserInvitation, 0)
for _, email := range input.Model.Recipients {
if email != "" {
- _, err := services.Users.GetByEmail(email)
+ err := bus.Dispatch(ctx, &query.GetUserByEmail{Email: email})
if errors.Cause(err) == app.ErrNotFound {
input.Invitations = append(input.Invitations, &models.UserInvitation{
Email: email,
diff --git a/app/actions/invite_test.go b/app/actions/invite_test.go
index 296330977..38df7b806 100644
--- a/app/actions/invite_test.go
+++ b/app/actions/invite_test.go
@@ -1,19 +1,23 @@
package actions_test
import (
+ "context"
"fmt"
"testing"
+ "github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
)
func TestInviteUsers_Empty(t *testing.T) {
RegisterT(t)
action := &actions.InviteUsers{Model: &models.InviteUsers{}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "subject", "message", "recipients")
Expect(action.Invitations).IsNil()
}
@@ -26,7 +30,7 @@ func TestInviteUsers_Oversized(t *testing.T) {
Message: "Use this link to join %invite%",
Recipients: []string{"[email protected]"},
}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "subject")
Expect(action.Invitations).IsNil()
}
@@ -39,7 +43,7 @@ func TestInviteUsers_MissingInvite(t *testing.T) {
Message: "Please!",
Recipients: []string{"[email protected]"},
}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "message")
Expect(action.Invitations).IsNil()
}
@@ -57,7 +61,7 @@ func TestInviteUsers_TooManyRecipients(t *testing.T) {
Message: "Use this link to join %invite%",
Recipients: recipients,
}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "recipients")
Expect(action.Invitations).IsNil()
}
@@ -73,7 +77,7 @@ func TestInviteUsers_InvalidRecipient(t *testing.T) {
"@got.com",
},
}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "recipients")
Expect(action.Invitations).IsNil()
}
@@ -81,6 +85,10 @@ func TestInviteUsers_InvalidRecipient(t *testing.T) {
func TestInviteUsers_Valid(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ return app.ErrNotFound
+ })
+
action := &actions.InviteUsers{Model: &models.InviteUsers{
Subject: "Share your feedback.",
Message: "Use this link to join our community: %invite%",
@@ -91,7 +99,7 @@ func TestInviteUsers_Valid(t *testing.T) {
},
}}
- ExpectSuccess(action.Validate(nil, services))
+ ExpectSuccess(action.Validate(context.Background(), nil))
Expect(action.Invitations).HasLen(2)
@@ -105,13 +113,14 @@ func TestInviteUsers_Valid(t *testing.T) {
func TestInviteUsers_IgnoreAlreadyRegistered(t *testing.T) {
RegisterT(t)
- theTenant := &models.Tenant{ID: 1, Name: "The Tenant"}
- services.Users.SetCurrentTenant(theTenant)
- services.Users.Register(&models.User{
- Name: "Tony",
- Email: "[email protected]",
- Tenant: theTenant,
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ if q.Email == "[email protected]" {
+ q.Result = &models.User{Email: q.Email}
+ return nil
+ }
+ return app.ErrNotFound
})
+
action := &actions.InviteUsers{Model: &models.InviteUsers{
Subject: "Share your feedback.",
Message: "Use this link to join our community: %invite%",
@@ -122,7 +131,7 @@ func TestInviteUsers_IgnoreAlreadyRegistered(t *testing.T) {
},
}}
- ExpectSuccess(action.Validate(nil, services))
+ ExpectSuccess(action.Validate(context.Background(), nil))
Expect(action.Invitations).HasLen(2)
@@ -136,13 +145,11 @@ func TestInviteUsers_IgnoreAlreadyRegistered(t *testing.T) {
func TestInviteUsers_ShouldFail_WhenAllRecipientsIgnored(t *testing.T) {
RegisterT(t)
- theTenant := &models.Tenant{ID: 1, Name: "The Tenant"}
- services.Users.SetCurrentTenant(theTenant)
- services.Users.Register(&models.User{
- Name: "Tony",
- Email: "[email protected]",
- Tenant: theTenant,
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ q.Result = &models.User{Email: q.Email}
+ return nil
})
+
action := &actions.InviteUsers{Model: &models.InviteUsers{
Subject: "Share your feedback.",
Message: "Use this link to join our community: %invite%",
@@ -151,7 +158,7 @@ func TestInviteUsers_ShouldFail_WhenAllRecipientsIgnored(t *testing.T) {
},
}}
- ExpectFailed(action.Validate(nil, services), "recipients")
+ ExpectFailed(action.Validate(context.Background(), nil), "recipients")
}
func TestInviteUsers_SampleInvite_IgnoreRecipients(t *testing.T) {
@@ -165,5 +172,5 @@ func TestInviteUsers_SampleInvite_IgnoreRecipients(t *testing.T) {
},
}
- ExpectSuccess(action.Validate(nil, services))
+ ExpectSuccess(action.Validate(context.Background(), nil))
}
diff --git a/app/actions/oauth.go b/app/actions/oauth.go
index 3a1d37900..c839f828a 100644
--- a/app/actions/oauth.go
+++ b/app/actions/oauth.go
@@ -1,9 +1,13 @@
package actions
import (
+ "context"
"strings"
- "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/rand"
"github.com/getfider/fider/app/pkg/validate"
@@ -22,24 +26,25 @@ func (input *CreateEditOAuthConfig) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateEditOAuthConfig) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *CreateEditOAuthConfig) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil && user.IsAdministrator()
}
-// Validate is current model is valid
-func (input *CreateEditOAuthConfig) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *CreateEditOAuthConfig) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
if input.Model.Provider != "" {
- config, err := services.Tenants.GetOAuthConfigByProvider(input.Model.Provider)
+ getConfig := &query.GetCustomOAuthConfigByProvider{Provider: input.Model.Provider}
+ err := bus.Dispatch(ctx, getConfig)
if err != nil {
return validate.Error(err)
}
- input.Model.ID = config.ID
- input.Model.Logo.BlobKey = config.LogoBlobKey
+ input.Model.ID = getConfig.Result.ID
+ input.Model.Logo.BlobKey = getConfig.Result.LogoBlobKey
if input.Model.ClientSecret == "" {
- input.Model.ClientSecret = config.ClientSecret
+ input.Model.ClientSecret = getConfig.Result.ClientSecret
}
} else {
input.Model.Provider = "_" + strings.ToLower(rand.String(10))
@@ -57,8 +62,8 @@ func (input *CreateEditOAuthConfig) Validate(user *models.User, services *app.Se
}
result.AddFieldFailure("logo", messages...)
- if input.Model.Status != models.OAuthConfigEnabled &&
- input.Model.Status != models.OAuthConfigDisabled {
+ if input.Model.Status != enum.OAuthConfigEnabled &&
+ input.Model.Status != enum.OAuthConfigDisabled {
result.AddFieldFailure("status", "Invalid status.")
}
diff --git a/app/actions/oauth_test.go b/app/actions/oauth_test.go
index 83df15ed5..45e2439c0 100644
--- a/app/actions/oauth_test.go
+++ b/app/actions/oauth_test.go
@@ -1,12 +1,16 @@
package actions_test
import (
+ "context"
"testing"
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/rand"
)
@@ -43,7 +47,7 @@ func TestCreateEditOAuthConfig_InvalidInput(t *testing.T) {
action := &actions.CreateEditOAuthConfig{
Model: testCase.input,
}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, testCase.expected...)
}
}
@@ -61,7 +65,7 @@ func TestCreateEditOAuthConfig_AddNew_ValidInput(t *testing.T) {
input := &models.CreateEditOAuthConfig{
DisplayName: "My Provider",
- Status: models.OAuthConfigEnabled,
+ Status: enum.OAuthConfigEnabled,
ClientID: "823187ahjjfdha8fds7yfdashfjkdsa",
ClientSecret: "jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij",
AuthorizeURL: "http://provider/oauth/authorize",
@@ -75,7 +79,7 @@ func TestCreateEditOAuthConfig_AddNew_ValidInput(t *testing.T) {
action := &actions.CreateEditOAuthConfig{
Model: input,
}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
Expect(input.ID).Equals(0)
Expect(input.Provider).HasLen(11)
@@ -85,21 +89,23 @@ func TestCreateEditOAuthConfig_AddNew_ValidInput(t *testing.T) {
func TestCreateEditOAuthConfig_EditExisting_NewSecret(t *testing.T) {
RegisterT(t)
- services.Tenants.SaveOAuthConfig(&models.CreateEditOAuthConfig{
- ID: 4,
- Logo: &models.ImageUpload{
- BlobKey: "hello-world.png",
- },
- Provider: "_NAME",
- DisplayName: "My Provider",
- ClientSecret: "MY_OLD_SECRET",
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ if q.Provider == "_NAME" {
+ q.Result = &models.OAuthConfig{
+ ID: 4,
+ Provider: q.Provider,
+ LogoBlobKey: "hello-world.png",
+ }
+ return nil
+ }
+ return app.ErrNotFound
})
action := &actions.CreateEditOAuthConfig{}
action.Initialize()
action.Model.Provider = "_NAME"
action.Model.DisplayName = "My Provider"
- action.Model.Status = models.OAuthConfigDisabled
+ action.Model.Status = enum.OAuthConfigDisabled
action.Model.ClientID = "823187ahjjfdha8fds7yfdashfjkdsa"
action.Model.ClientSecret = "jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij"
action.Model.AuthorizeURL = "http://provider/oauth/authorize"
@@ -110,7 +116,7 @@ func TestCreateEditOAuthConfig_EditExisting_NewSecret(t *testing.T) {
action.Model.JSONUserNamePath = "user.name"
action.Model.JSONUserEmailPath = "user.email"
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
Expect(action.Model.ID).Equals(4)
Expect(action.Model.Logo.BlobKey).Equals("hello-world.png")
@@ -120,19 +126,24 @@ func TestCreateEditOAuthConfig_EditExisting_NewSecret(t *testing.T) {
func TestCreateEditOAuthConfig_EditExisting_OmitSecret(t *testing.T) {
RegisterT(t)
- services.Tenants.SaveOAuthConfig(&models.CreateEditOAuthConfig{
- ID: 5,
- Logo: &models.ImageUpload{},
- Provider: "_NAME2",
- DisplayName: "My Provider",
- ClientSecret: "MY_OLD_SECRET",
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ if q.Provider == "_NAME2" {
+ q.Result = &models.OAuthConfig{
+ ID: 5,
+ Provider: q.Provider,
+ DisplayName: "My Provider",
+ ClientSecret: "MY_OLD_SECRET",
+ }
+ return nil
+ }
+ return app.ErrNotFound
})
action := &actions.CreateEditOAuthConfig{}
action.Initialize()
action.Model.Provider = "_NAME2"
action.Model.DisplayName = "My Provider"
- action.Model.Status = models.OAuthConfigDisabled
+ action.Model.Status = enum.OAuthConfigDisabled
action.Model.ClientID = "823187ahjjfdha8fds7yfdashfjkdsa"
action.Model.AuthorizeURL = "http://provider/oauth/authorize"
action.Model.TokenURL = "http://provider/oauth/token"
@@ -142,7 +153,7 @@ func TestCreateEditOAuthConfig_EditExisting_OmitSecret(t *testing.T) {
action.Model.JSONUserNamePath = "user.name"
action.Model.JSONUserEmailPath = "user.email"
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
Expect(action.Model.ID).Equals(5)
Expect(action.Model.ClientSecret).Equals("MY_OLD_SECRET")
@@ -151,11 +162,15 @@ func TestCreateEditOAuthConfig_EditExisting_OmitSecret(t *testing.T) {
func TestCreateEditOAuthConfig_EditNonExisting(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ return app.ErrNotFound
+ })
+
action := &actions.CreateEditOAuthConfig{}
action.Initialize()
action.Model.Provider = "_MY_NEW_PROVIDER"
action.Model.DisplayName = "My Provider"
- action.Model.Status = models.OAuthConfigDisabled
+ action.Model.Status = enum.OAuthConfigDisabled
action.Model.ClientID = "823187ahjjfdha8fds7yfdashfjkdsa"
action.Model.AuthorizeURL = "http://provider/oauth/authorize"
action.Model.TokenURL = "http://provider/oauth/token"
@@ -164,7 +179,7 @@ func TestCreateEditOAuthConfig_EditNonExisting(t *testing.T) {
action.Model.JSONUserIDPath = "user.id"
action.Model.JSONUserNamePath = "user.name"
action.Model.JSONUserEmailPath = "user.email"
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
Expect(result.Err).Equals(app.ErrNotFound)
Expect(result.Ok).IsFalse()
}
diff --git a/app/actions/post.go b/app/actions/post.go
index cf45994ec..ff981c38f 100644
--- a/app/actions/post.go
+++ b/app/actions/post.go
@@ -1,6 +1,11 @@
package actions
import (
+ "context"
+
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/gosimple/slug"
"github.com/getfider/fider/app"
@@ -21,29 +26,27 @@ func (input *CreateNewPost) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateNewPost) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *CreateNewPost) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil
}
-// Validate is current model is valid
-func (input *CreateNewPost) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *CreateNewPost) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
if input.Model.Title == "" {
result.AddFieldFailure("title", "Title is required.")
} else if len(input.Model.Title) < 10 {
result.AddFieldFailure("title", "Title needs to be more descriptive.")
- }
-
- if len(input.Model.Title) > 100 {
+ } else if len(input.Model.Title) > 100 {
result.AddFieldFailure("title", "Title must have less than 100 characters.")
- }
-
- post, err := services.Posts.GetBySlug(slug.Make(input.Model.Title))
- if err != nil && errors.Cause(err) != app.ErrNotFound {
- return validate.Error(err)
- } else if post != nil {
- result.AddFieldFailure("title", "This has already been posted before.")
+ } else {
+ err := bus.Dispatch(ctx, &query.GetPostBySlug{Slug: slug.Make(input.Model.Title)})
+ if err != nil && errors.Cause(err) != app.ErrNotFound {
+ return validate.Error(err)
+ } else if err == nil {
+ result.AddFieldFailure("title", "This has already been posted before.")
+ }
}
messages, err := validate.MultiImageUpload(nil, input.Model.Attachments, validate.MultiImageUploadOpts{
@@ -72,19 +75,14 @@ func (input *UpdatePost) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *UpdatePost) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *UpdatePost) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil && user.IsCollaborator()
}
-// Validate is current model is valid
-func (input *UpdatePost) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *UpdatePost) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
- post, err := services.Posts.GetByNumber(input.Model.Number)
- if err != nil {
- return validate.Error(err)
- }
-
if input.Model.Title == "" {
result.AddFieldFailure("title", "Title is required.")
} else if len(input.Model.Title) < 10 {
@@ -95,29 +93,38 @@ func (input *UpdatePost) Validate(user *models.User, services *app.Services) *va
result.AddFieldFailure("title", "Title must have less than 100 characters.")
}
- another, err := services.Posts.GetBySlug(slug.Make(input.Model.Title))
- if err != nil && errors.Cause(err) != app.ErrNotFound {
+ postByNumber := &query.GetPostByNumber{Number: input.Model.Number}
+ if err := bus.Dispatch(ctx, postByNumber); err != nil {
return validate.Error(err)
- } else if another != nil && another.ID != post.ID {
- result.AddFieldFailure("title", "This has already been posted before.")
}
- attachments, err := services.Posts.GetAttachments(post, nil)
- if err != nil {
- return validate.Error(err)
- }
+ input.Post = postByNumber.Result
- messages, err := validate.MultiImageUpload(attachments, input.Model.Attachments, validate.MultiImageUploadOpts{
- MaxUploads: 3,
- MaxKilobytes: 5120,
- ExactRatio: false,
- })
- if err != nil {
+ postBySlug := &query.GetPostBySlug{Slug: slug.Make(input.Model.Title)}
+ err := bus.Dispatch(ctx, postBySlug)
+ if err != nil && errors.Cause(err) != app.ErrNotFound {
return validate.Error(err)
+ } else if err == nil && postBySlug.Result.ID != input.Post.ID {
+ result.AddFieldFailure("title", "This has already been posted before.")
}
- result.AddFieldFailure("attachments", messages...)
- input.Post = post
+ if len(input.Model.Attachments) > 0 {
+ getAttachments := &query.GetAttachments{Post: input.Post}
+ err = bus.Dispatch(ctx, getAttachments)
+ if err != nil {
+ return validate.Error(err)
+ }
+
+ messages, err := validate.MultiImageUpload(getAttachments.Result, input.Model.Attachments, validate.MultiImageUploadOpts{
+ MaxUploads: 3,
+ MaxKilobytes: 5120,
+ ExactRatio: false,
+ })
+ if err != nil {
+ return validate.Error(err)
+ }
+ result.AddFieldFailure("attachments", messages...)
+ }
return result
}
@@ -134,12 +141,12 @@ func (input *AddNewComment) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *AddNewComment) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *AddNewComment) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil
}
-// Validate is current model is valid
-func (input *AddNewComment) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *AddNewComment) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
if input.Model.Content == "" {
@@ -172,24 +179,25 @@ func (input *SetResponse) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *SetResponse) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *SetResponse) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil && user.IsCollaborator()
}
-// Validate is current model is valid
-func (input *SetResponse) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *SetResponse) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
- if input.Model.Status < models.PostOpen || input.Model.Status > models.PostDuplicate {
+ if input.Model.Status < enum.PostOpen || input.Model.Status > enum.PostDuplicate {
result.AddFieldFailure("status", "Status is invalid.")
}
- if input.Model.Status == models.PostDuplicate {
+ if input.Model.Status == enum.PostDuplicate {
if input.Model.OriginalNumber == input.Model.Number {
result.AddFieldFailure("originalNumber", "Cannot be a duplicate of itself")
}
- original, err := services.Posts.GetByNumber(input.Model.OriginalNumber)
+ getOriginaPost := &query.GetPostByNumber{Number: input.Model.OriginalNumber}
+ err := bus.Dispatch(ctx, getOriginaPost)
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
result.AddFieldFailure("originalNumber", "Original post not found")
@@ -197,8 +205,9 @@ func (input *SetResponse) Validate(user *models.User, services *app.Services) *v
return validate.Error(err)
}
}
- if original != nil {
- input.Original = original
+
+ if getOriginaPost.Result != nil {
+ input.Original = getOriginaPost.Result
}
}
@@ -218,28 +227,28 @@ func (input *DeletePost) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *DeletePost) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *DeletePost) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil && user.IsAdministrator()
}
// Validate if current model is valid
-func (input *DeletePost) Validate(user *models.User, services *app.Services) *validate.Result {
- post, err := services.Posts.GetByNumber(input.Model.Number)
- if err != nil {
+func (input *DeletePost) Validate(ctx context.Context, user *models.User) *validate.Result {
+ getPost := &query.GetPostByNumber{Number: input.Model.Number}
+ if err := bus.Dispatch(ctx, getPost); err != nil {
return validate.Error(err)
}
- isReferenced, err := services.Posts.IsReferenced(post)
- if err != nil {
+ input.Post = getPost.Result
+
+ isReferencedQuery := &query.PostIsReferenced{PostID: input.Post.ID}
+ if err := bus.Dispatch(ctx, isReferencedQuery); err != nil {
return validate.Error(err)
}
- if isReferenced {
+ if isReferencedQuery.Result {
return validate.Failed("This post cannot be deleted because it's being referenced by a duplicated post.")
}
- input.Post = post
-
return validate.Success()
}
@@ -257,44 +266,43 @@ func (input *EditComment) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *EditComment) IsAuthorized(user *models.User, services *app.Services) bool {
- post, err := services.Posts.GetByNumber(input.Model.PostNumber)
- if err != nil {
- return false
- }
-
- comment, err := services.Posts.GetCommentByID(input.Model.ID)
- if err != nil {
+func (input *EditComment) IsAuthorized(ctx context.Context, user *models.User) bool {
+ postByNumber := &query.GetPostByNumber{Number: input.Model.PostNumber}
+ commentByID := &query.GetCommentByID{CommentID: input.Model.ID}
+ if err := bus.Dispatch(ctx, postByNumber, commentByID); err != nil {
return false
}
- input.Post = post
- input.Comment = comment
- return user.ID == comment.User.ID || user.IsCollaborator()
+ input.Post = postByNumber.Result
+ input.Comment = commentByID.Result
+ return user.ID == input.Comment.User.ID || user.IsCollaborator()
}
// Validate if current model is valid
-func (input *EditComment) Validate(user *models.User, services *app.Services) *validate.Result {
+func (input *EditComment) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
if input.Model.Content == "" {
result.AddFieldFailure("content", "Comment is required.")
}
- attachments, err := services.Posts.GetAttachments(input.Post, input.Comment)
- if err != nil {
- return validate.Error(err)
- }
+ if len(input.Model.Attachments) > 0 {
+ getAttachments := &query.GetAttachments{Post: input.Post, Comment: input.Comment}
+ err := bus.Dispatch(ctx, getAttachments)
+ if err != nil {
+ return validate.Error(err)
+ }
- messages, err := validate.MultiImageUpload(attachments, input.Model.Attachments, validate.MultiImageUploadOpts{
- MaxUploads: 2,
- MaxKilobytes: 5120,
- ExactRatio: false,
- })
- if err != nil {
- return validate.Error(err)
+ messages, err := validate.MultiImageUpload(getAttachments.Result, input.Model.Attachments, validate.MultiImageUploadOpts{
+ MaxUploads: 2,
+ MaxKilobytes: 5120,
+ ExactRatio: false,
+ })
+ if err != nil {
+ return validate.Error(err)
+ }
+ result.AddFieldFailure("attachments", messages...)
}
- result.AddFieldFailure("attachments", messages...)
return result
}
@@ -311,16 +319,16 @@ func (input *DeleteComment) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *DeleteComment) IsAuthorized(user *models.User, services *app.Services) bool {
- comment, err := services.Posts.GetCommentByID(input.Model.CommentID)
- if err != nil {
+func (input *DeleteComment) IsAuthorized(ctx context.Context, user *models.User) bool {
+ commentByID := &query.GetCommentByID{CommentID: input.Model.CommentID}
+ if err := bus.Dispatch(ctx, commentByID); err != nil {
return false
}
- return user.ID == comment.User.ID || user.IsCollaborator()
+ return user.ID == commentByID.Result.User.ID || user.IsCollaborator()
}
// Validate if current model is valid
-func (input *DeleteComment) Validate(user *models.User, services *app.Services) *validate.Result {
+func (input *DeleteComment) Validate(ctx context.Context, user *models.User) *validate.Result {
return validate.Success()
}
diff --git a/app/actions/post_test.go b/app/actions/post_test.go
index 525418d4d..c44b4c2d9 100644
--- a/app/actions/post_test.go
+++ b/app/actions/post_test.go
@@ -1,18 +1,29 @@
package actions_test
import (
+ "context"
"testing"
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
)
func TestCreateNewPost_InvalidPostTitles(t *testing.T) {
RegisterT(t)
- services.SetCurrentUser(&models.User{ID: 1})
- services.Posts.Add("My great post", "With a great description")
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostBySlug) error {
+ if q.Slug == "my-great-post" {
+ q.Result = &models.Post{Slug: q.Slug}
+ return nil
+ }
+ return app.ErrNotFound
+ })
for _, title := range []string{
"me",
@@ -23,7 +34,7 @@ func TestCreateNewPost_InvalidPostTitles(t *testing.T) {
"my GREAT post",
} {
action := &actions.CreateNewPost{Model: &models.NewPost{Title: title}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "title")
}
}
@@ -31,12 +42,16 @@ func TestCreateNewPost_InvalidPostTitles(t *testing.T) {
func TestCreateNewPost_ValidPostTitles(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostBySlug) error {
+ return app.ErrNotFound
+ })
+
for _, title := range []string{
"this is my new post",
"this post is very descriptive",
} {
action := &actions.CreateNewPost{Model: &models.NewPost{Title: title}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
}
}
@@ -45,52 +60,78 @@ func TestSetResponse_InvalidStatus(t *testing.T) {
RegisterT(t)
action := &actions.SetResponse{Model: &models.SetResponse{
- Status: models.PostDeleted,
+ Status: enum.PostDeleted,
Text: "Spam!",
}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "status")
}
func TestDeletePost_WhenIsBeingReferenced(t *testing.T) {
RegisterT(t)
- services.SetCurrentUser(&models.User{ID: 1})
- post1, _ := services.Posts.Add("Post #1", "")
- post2, _ := services.Posts.Add("Post #2", "")
- services.Posts.MarkAsDuplicate(post2, post1)
+ post1 := &models.Post{ID: 1, Number: 1, Title: "Post 1"}
+ post2 := &models.Post{ID: 2, Number: 2, Title: "Post 2"}
- model := &models.DeletePost{
- Number: post2.Number,
- Text: "Spam!",
- }
- action := &actions.DeletePost{Model: model}
- ExpectSuccess(action.Validate(nil, services))
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ if q.Number == post1.Number {
+ q.Result = post1
+ return nil
+ }
+
+ if q.Number == post2.Number {
+ q.Result = post2
+ return nil
+ }
+
+ return app.ErrNotFound
+ })
- model.Number = post1.Number
- ExpectFailed(action.Validate(nil, services))
+ bus.AddHandler(func(ctx context.Context, q *query.PostIsReferenced) error {
+ q.Result = q.PostID == post2.ID
+ return nil
+ })
+
+ action := &actions.DeletePost{Model: &models.DeletePost{}}
+ action.Model.Number = post1.Number
+ ExpectSuccess(action.Validate(context.Background(), nil))
+
+ action.Model.Number = post2.Number
+ ExpectFailed(action.Validate(context.Background(), nil))
}
func TestDeleteComment(t *testing.T) {
RegisterT(t)
- author := &models.User{ID: 1, Role: models.RoleVisitor}
- notAuthor := &models.User{ID: 2, Role: models.RoleVisitor}
- administrator := &models.User{ID: 3, Role: models.RoleAdministrator}
+ author := &models.User{ID: 1, Role: enum.RoleVisitor}
+ notAuthor := &models.User{ID: 2, Role: enum.RoleVisitor}
+ administrator := &models.User{ID: 3, Role: enum.RoleAdministrator}
+ comment := &models.Comment{
+ ID: 1,
+ User: author,
+ Content: "Comment #1",
+ }
- services.SetCurrentUser(author)
- post1, _ := services.Posts.Add("Post #1", "")
- commentID, _ := services.Posts.AddComment(post1, "Comment #1")
+ bus.AddHandler(func(ctx context.Context, q *query.GetCommentByID) error {
+ if q.CommentID == comment.ID {
+ q.Result = comment
+ return nil
+ }
+ return app.ErrNotFound
+ })
action := &actions.DeleteComment{
Model: &models.DeleteComment{
- CommentID: commentID,
+ CommentID: comment.ID,
},
}
- authorized := action.IsAuthorized(notAuthor, services)
+ authorized := action.IsAuthorized(context.Background(), notAuthor)
Expect(authorized).IsFalse()
- authorized = action.IsAuthorized(administrator, services)
+ authorized = action.IsAuthorized(context.Background(), author)
+ Expect(authorized).IsTrue()
+
+ authorized = action.IsAuthorized(context.Background(), administrator)
Expect(authorized).IsTrue()
}
diff --git a/app/actions/settings.go b/app/actions/settings.go
index ef1d52937..40f0fc3e1 100644
--- a/app/actions/settings.go
+++ b/app/actions/settings.go
@@ -1,10 +1,11 @@
package actions
import (
+ "context"
"fmt"
- "github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/pkg/validate"
)
@@ -21,12 +22,12 @@ func (input *UpdateUserSettings) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *UpdateUserSettings) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *UpdateUserSettings) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil
}
-// Validate is current model is valid
-func (input *UpdateUserSettings) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *UpdateUserSettings) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
if input.Model.Name == "" {
@@ -43,7 +44,7 @@ func (input *UpdateUserSettings) Validate(user *models.User, services *app.Servi
input.Model.Avatar.BlobKey = user.AvatarBlobKey
messages, err := validate.ImageUpload(input.Model.Avatar, validate.ImageUploadOpts{
- IsRequired: input.Model.AvatarType == models.AvatarTypeCustom,
+ IsRequired: input.Model.AvatarType == enum.AvatarTypeCustom,
MinHeight: 50,
MinWidth: 50,
ExactRatio: true,
@@ -57,7 +58,7 @@ func (input *UpdateUserSettings) Validate(user *models.User, services *app.Servi
if input.Model.Settings != nil {
for k, v := range input.Model.Settings {
ok := false
- for _, e := range models.AllNotificationEvents {
+ for _, e := range enum.AllNotificationEvents {
if e.UserSettingsKeyName == k {
ok = true
if !e.Validate(v) {
diff --git a/app/actions/settings_test.go b/app/actions/settings_test.go
index 7feb757ec..5c395c7a1 100644
--- a/app/actions/settings_test.go
+++ b/app/actions/settings_test.go
@@ -1,10 +1,12 @@
package actions_test
import (
+ "context"
"testing"
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
. "github.com/getfider/fider/app/pkg/assert"
)
@@ -19,8 +21,8 @@ func TestInvalidUserNames(t *testing.T) {
action := actions.UpdateUserSettings{}
action.Initialize()
action.Model.Name = name
- action.Model.AvatarType = models.AvatarTypeGravatar
- result := action.Validate(&models.User{}, services)
+ action.Model.AvatarType = enum.AvatarTypeGravatar
+ result := action.Validate(context.Background(), &models.User{})
ExpectFailed(result, "name")
}
}
@@ -35,8 +37,8 @@ func TestValidUserNames(t *testing.T) {
action := actions.UpdateUserSettings{}
action.Initialize()
action.Model.Name = name
- action.Model.AvatarType = models.AvatarTypeGravatar
- result := action.Validate(&models.User{}, services)
+ action.Model.AvatarType = enum.AvatarTypeGravatar
+ result := action.Validate(context.Background(), &models.User{})
ExpectSuccess(result)
}
}
@@ -49,14 +51,14 @@ func TestInvalidSettings(t *testing.T) {
"bad_name": "3",
},
map[string]string{
- models.NotificationEventNewComment.UserSettingsKeyName: "4",
+ enum.NotificationEventNewComment.UserSettingsKeyName: "4",
},
} {
action := actions.UpdateUserSettings{}
action.Initialize()
action.Model.Name = "John Snow"
action.Model.Settings = settings
- result := action.Validate(&models.User{}, services)
+ result := action.Validate(context.Background(), &models.User{})
ExpectFailed(result, "settings", "avatarType")
}
}
@@ -67,23 +69,23 @@ func TestValidSettings(t *testing.T) {
for _, settings := range []map[string]string{
nil,
map[string]string{
- models.NotificationEventNewPost.UserSettingsKeyName: models.NotificationEventNewPost.DefaultSettingValue,
- models.NotificationEventNewComment.UserSettingsKeyName: models.NotificationEventNewComment.DefaultSettingValue,
- models.NotificationEventChangeStatus.UserSettingsKeyName: models.NotificationEventChangeStatus.DefaultSettingValue,
+ enum.NotificationEventNewPost.UserSettingsKeyName: enum.NotificationEventNewPost.DefaultSettingValue,
+ enum.NotificationEventNewComment.UserSettingsKeyName: enum.NotificationEventNewComment.DefaultSettingValue,
+ enum.NotificationEventChangeStatus.UserSettingsKeyName: enum.NotificationEventChangeStatus.DefaultSettingValue,
},
map[string]string{
- models.NotificationEventNewComment.UserSettingsKeyName: models.NotificationEventNewComment.DefaultSettingValue,
+ enum.NotificationEventNewComment.UserSettingsKeyName: enum.NotificationEventNewComment.DefaultSettingValue,
},
} {
action := actions.UpdateUserSettings{}
action.Initialize()
action.Model.Name = "John Snow"
action.Model.Settings = settings
- action.Model.AvatarType = models.AvatarTypeGravatar
+ action.Model.AvatarType = enum.AvatarTypeGravatar
- result := action.Validate(&models.User{
+ result := action.Validate(context.Background(), &models.User{
AvatarBlobKey: "jon.png",
- }, services)
+ })
ExpectSuccess(result)
Expect(action.Model.Avatar.BlobKey).Equals("jon.png")
diff --git a/app/actions/signin.go b/app/actions/signin.go
index 2140cb58d..43f753b04 100644
--- a/app/actions/signin.go
+++ b/app/actions/signin.go
@@ -1,8 +1,12 @@
package actions
import (
- "github.com/getfider/fider/app"
+ "context"
+
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/validate"
)
@@ -19,12 +23,12 @@ func (input *SignInByEmail) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *SignInByEmail) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *SignInByEmail) IsAuthorized(ctx context.Context, user *models.User) bool {
return true
}
-// Validate is current model is valid
-func (input *SignInByEmail) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *SignInByEmail) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
if input.Model.Email == "" {
@@ -54,12 +58,12 @@ func (input *CompleteProfile) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CompleteProfile) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *CompleteProfile) IsAuthorized(ctx context.Context, user *models.User) bool {
return true
}
-// Validate is current model is valid
-func (input *CompleteProfile) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *CompleteProfile) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
if input.Model.Name == "" {
@@ -73,12 +77,16 @@ func (input *CompleteProfile) Validate(user *models.User, services *app.Services
if input.Model.Key == "" {
result.AddFieldFailure("key", "Key is required.")
} else {
- request1, err1 := services.Tenants.FindVerificationByKey(models.EmailVerificationKindSignIn, input.Model.Key)
- request2, err2 := services.Tenants.FindVerificationByKey(models.EmailVerificationKindUserInvitation, input.Model.Key)
+ findBySignIn := &query.GetVerificationByKey{Kind: enum.EmailVerificationKindSignIn, Key: input.Model.Key}
+ err1 := bus.Dispatch(ctx, findBySignIn)
+
+ findByUserInvitation := &query.GetVerificationByKey{Kind: enum.EmailVerificationKindUserInvitation, Key: input.Model.Key}
+ err2 := bus.Dispatch(ctx, findByUserInvitation)
+
if err1 == nil {
- input.Model.Email = request1.Email
+ input.Model.Email = findBySignIn.Result.Email
} else if err2 == nil {
- input.Model.Email = request2.Email
+ input.Model.Email = findByUserInvitation.Result.Email
} else {
result.AddFieldFailure("key", "Key is invalid.")
}
diff --git a/app/actions/signin_test.go b/app/actions/signin_test.go
index b881a2dde..ded3e036b 100644
--- a/app/actions/signin_test.go
+++ b/app/actions/signin_test.go
@@ -1,19 +1,24 @@
package actions_test
import (
+ "context"
"testing"
- "time"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
)
func TestSignInByEmail_EmptyEmail(t *testing.T) {
RegisterT(t)
action := actions.SignInByEmail{Model: &models.SignInByEmail{Email: " "}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "email")
}
@@ -21,7 +26,7 @@ func TestSignInByEmail_InvalidEmail(t *testing.T) {
RegisterT(t)
action := actions.SignInByEmail{Model: &models.SignInByEmail{Email: "Hi :)"}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "email")
}
@@ -32,7 +37,7 @@ func TestSignInByEmail_ShouldHaveVerificationKey(t *testing.T) {
action.Initialize()
action.Model.Email = "[email protected]"
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
Expect(action.Model.VerificationKey).IsNotEmpty()
}
@@ -41,7 +46,7 @@ func TestCompleteProfile_EmptyNameAndKey(t *testing.T) {
RegisterT(t)
action := actions.CompleteProfile{Model: &models.CompleteProfile{}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "name", "key")
}
@@ -51,24 +56,40 @@ func TestCompleteProfile_LongName(t *testing.T) {
action := actions.CompleteProfile{Model: &models.CompleteProfile{
Name: "123456789012345678901234567890123456789012345678901", // 51 chars
}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "name", "key")
}
func TestCompleteProfile_UnknownKey(t *testing.T) {
RegisterT(t)
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ return app.ErrNotFound
+ })
+
action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: "1234567890"}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "key")
}
func TestCompleteProfile_ValidKey(t *testing.T) {
RegisterT(t)
- e := &models.SignInByEmail{Email: "[email protected]"}
- services.Tenants.SaveVerificationKey("1234567890", 30*time.Minute, e)
- action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: "1234567890"}}
- result := action.Validate(nil, services)
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: key}}
+ result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
Expect(action.Model.Email).Equals("[email protected]")
@@ -77,10 +98,21 @@ func TestCompleteProfile_ValidKey(t *testing.T) {
func TestCompleteProfile_UserInvitation_ValidKey(t *testing.T) {
RegisterT(t)
- e := &models.UserInvitation{Email: "[email protected]"}
- services.Tenants.SaveVerificationKey("1234567890", 30*time.Minute, e)
- action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: "1234567890"}}
- result := action.Validate(nil, services)
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindUserInvitation {
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: key}}
+ result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
Expect(action.Model.Email).Equals("[email protected]")
diff --git a/app/actions/tag.go b/app/actions/tag.go
index 10aa65c91..462eba4ac 100644
--- a/app/actions/tag.go
+++ b/app/actions/tag.go
@@ -1,10 +1,14 @@
package actions
import (
+ "context"
"regexp"
+ "github.com/getfider/fider/app/models/query"
+
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/validate"
"github.com/gosimple/slug"
@@ -25,19 +29,21 @@ func (input *CreateEditTag) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateEditTag) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *CreateEditTag) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil && user.IsAdministrator()
}
-// Validate is current model is valid
-func (input *CreateEditTag) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *CreateEditTag) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
+
if input.Model.Slug != "" {
- tag, err := services.Tags.GetBySlug(input.Model.Slug)
+ getSlug := &query.GetTagBySlug{Slug: input.Model.Slug}
+ err := bus.Dispatch(ctx, getSlug)
if err != nil {
return validate.Error(err)
}
- input.Tag = tag
+ input.Tag = getSlug.Result
}
if input.Model.Name == "" {
@@ -45,10 +51,11 @@ func (input *CreateEditTag) Validate(user *models.User, services *app.Services)
} else if len(input.Model.Name) > 30 {
result.AddFieldFailure("name", "Name must have less than 30 characters.")
} else {
- duplicateTag, err := services.Tags.GetBySlug(slug.Make(input.Model.Name))
+ getDuplicateSlug := &query.GetTagBySlug{Slug: slug.Make(input.Model.Name)}
+ err := bus.Dispatch(ctx, getDuplicateSlug)
if err != nil && errors.Cause(err) != app.ErrNotFound {
return validate.Error(err)
- } else if err == nil && (input.Tag == nil || input.Tag.ID != duplicateTag.ID) {
+ } else if err == nil && (input.Tag == nil || input.Tag.ID != getDuplicateSlug.Result.ID) {
result.AddFieldFailure("name", "This tag name is already in use.")
}
}
@@ -77,18 +84,19 @@ func (input *DeleteTag) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *DeleteTag) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *DeleteTag) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil && user.IsAdministrator()
}
-// Validate is current model is valid
-func (input *DeleteTag) Validate(user *models.User, services *app.Services) *validate.Result {
- tag, err := services.Tags.GetBySlug(input.Model.Slug)
+// Validate if current model is valid
+func (input *DeleteTag) Validate(ctx context.Context, user *models.User) *validate.Result {
+ getSlug := &query.GetTagBySlug{Slug: input.Model.Slug}
+ err := bus.Dispatch(ctx, getSlug)
if err != nil {
return validate.Error(err)
}
- input.Tag = tag
+ input.Tag = getSlug.Result
return validate.Success()
}
@@ -106,23 +114,19 @@ func (input *AssignUnassignTag) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *AssignUnassignTag) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *AssignUnassignTag) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil && user.IsCollaborator()
}
-// Validate is current model is valid
-func (input *AssignUnassignTag) Validate(user *models.User, services *app.Services) *validate.Result {
- post, err := services.Posts.GetByNumber(input.Model.Number)
- if err != nil {
- return validate.Error(err)
- }
-
- tag, err := services.Tags.GetBySlug(input.Model.Slug)
- if err != nil {
+// Validate if current model is valid
+func (input *AssignUnassignTag) Validate(ctx context.Context, user *models.User) *validate.Result {
+ getPost := &query.GetPostByNumber{Number: input.Model.Number}
+ getSlug := &query.GetTagBySlug{Slug: input.Model.Slug}
+ if err := bus.Dispatch(ctx, getPost, getSlug); err != nil {
return validate.Error(err)
}
- input.Tag = tag
- input.Post = post
+ input.Post = getPost.Result
+ input.Tag = getSlug.Result
return validate.Success()
}
diff --git a/app/actions/tag_test.go b/app/actions/tag_test.go
index 1a25cefbb..a0a1f969d 100644
--- a/app/actions/tag_test.go
+++ b/app/actions/tag_test.go
@@ -1,8 +1,14 @@
package actions_test
import (
+ "context"
"testing"
+ "github.com/getfider/fider/app"
+
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
. "github.com/getfider/fider/app/pkg/assert"
@@ -12,7 +18,10 @@ import (
func TestCreateEditTag_InvalidName(t *testing.T) {
RegisterT(t)
- services.Tags.Add("Feature Request", "000000", true)
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ q.Result = &models.Tag{Slug: "feature-request", Name: "Feature Request", Color: "000000"}
+ return nil
+ })
for _, name := range []string{
"",
@@ -20,7 +29,7 @@ func TestCreateEditTag_InvalidName(t *testing.T) {
rand.String(31),
} {
action := &actions.CreateEditTag{Model: &models.CreateEditTag{Name: name, Color: "FFFFFF"}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "name")
}
}
@@ -28,6 +37,10 @@ func TestCreateEditTag_InvalidName(t *testing.T) {
func TestCreateEditTag_InvalidColor(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ return app.ErrNotFound
+ })
+
for _, color := range []string{
"",
"ABC",
@@ -36,7 +49,7 @@ func TestCreateEditTag_InvalidColor(t *testing.T) {
"000000X",
} {
action := &actions.CreateEditTag{Model: &models.CreateEditTag{Name: "Bug", Color: color}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "color")
}
}
@@ -44,15 +57,24 @@ func TestCreateEditTag_InvalidColor(t *testing.T) {
func TestCreateEditTag_ValidInput(t *testing.T) {
RegisterT(t)
- tag, _ := services.Tags.Add("To Discuss", "000000", true)
+ tag := &models.Tag{Slug: "to-discuss", Name: "To Discuss", Color: "000000"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ if q.Slug == tag.Slug {
+ q.Result = tag
+ return nil
+ } else {
+ q.Result = nil
+ return app.ErrNotFound
+ }
+ })
action := &actions.CreateEditTag{Model: &models.CreateEditTag{Name: "Bug", Color: "FF0000"}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
Expect(action.Tag).IsNil()
action = &actions.CreateEditTag{Model: &models.CreateEditTag{Name: "New Name", Slug: "to-discuss", Color: "FF0000"}}
- result = action.Validate(nil, services)
+ result = action.Validate(context.Background(), nil)
ExpectSuccess(result)
Expect(action.Tag).Equals(tag)
}
diff --git a/app/actions/tenant.go b/app/actions/tenant.go
index 8faec3994..bcebc7a48 100644
--- a/app/actions/tenant.go
+++ b/app/actions/tenant.go
@@ -1,8 +1,11 @@
package actions
import (
+ "context"
+
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/validate"
@@ -21,12 +24,12 @@ func (input *CreateTenant) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateTenant) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *CreateTenant) IsAuthorized(ctx context.Context, user *models.User) bool {
return true
}
-// Validate is current model is valid
-func (input *CreateTenant) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *CreateTenant) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
var err error
@@ -62,7 +65,7 @@ func (input *CreateTenant) Validate(user *models.User, services *app.Services) *
result.AddFieldFailure("tenantName", "Name is required.")
}
- messages, err := validate.Subdomain(services.Tenants, input.Model.Subdomain)
+ messages, err := validate.Subdomain(ctx, input.Model.Subdomain)
if err != nil {
return validate.Error(err)
}
@@ -89,17 +92,19 @@ func (input *UpdateTenantSettings) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *UpdateTenantSettings) IsAuthorized(user *models.User, services *app.Services) bool {
- return user != nil && user.Role == models.RoleAdministrator
+func (input *UpdateTenantSettings) IsAuthorized(ctx context.Context, user *models.User) bool {
+ return user != nil && user.Role == enum.RoleAdministrator
}
-// Validate is current model is valid
-func (input *UpdateTenantSettings) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *UpdateTenantSettings) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
- if services.Tenants.Current() != nil {
- input.Model.Logo.BlobKey = services.Tenants.Current().LogoBlobKey
+ tenant, hasTenant := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ if hasTenant {
+ input.Model.Logo.BlobKey = tenant.LogoBlobKey
}
+
messages, err := validate.ImageUpload(input.Model.Logo, validate.ImageUploadOpts{
IsRequired: false,
MinHeight: 200,
@@ -125,7 +130,7 @@ func (input *UpdateTenantSettings) Validate(user *models.User, services *app.Ser
}
if input.Model.CNAME != "" {
- messages := validate.CNAME(services.Tenants, input.Model.CNAME)
+ messages := validate.CNAME(ctx, input.Model.CNAME)
result.AddFieldFailure("cname", messages...)
}
@@ -144,12 +149,12 @@ func (input *UpdateTenantAdvancedSettings) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *UpdateTenantAdvancedSettings) IsAuthorized(user *models.User, services *app.Services) bool {
- return user != nil && user.Role == models.RoleAdministrator
+func (input *UpdateTenantAdvancedSettings) IsAuthorized(ctx context.Context, user *models.User) bool {
+ return user != nil && user.Role == enum.RoleAdministrator
}
-// Validate is current model is valid
-func (input *UpdateTenantAdvancedSettings) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *UpdateTenantAdvancedSettings) Validate(ctx context.Context, user *models.User) *validate.Result {
return validate.Success()
}
@@ -165,11 +170,11 @@ func (input *UpdateTenantPrivacy) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *UpdateTenantPrivacy) IsAuthorized(user *models.User, services *app.Services) bool {
- return user != nil && user.Role == models.RoleAdministrator
+func (input *UpdateTenantPrivacy) IsAuthorized(ctx context.Context, user *models.User) bool {
+ return user != nil && user.Role == enum.RoleAdministrator
}
-// Validate is current model is valid
-func (input *UpdateTenantPrivacy) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *UpdateTenantPrivacy) Validate(ctx context.Context, user *models.User) *validate.Result {
return validate.Success()
}
diff --git a/app/actions/tenant_test.go b/app/actions/tenant_test.go
index 194abf456..9b27e17bc 100644
--- a/app/actions/tenant_test.go
+++ b/app/actions/tenant_test.go
@@ -1,12 +1,18 @@
package actions_test
import (
+ "context"
"testing"
+ "github.com/getfider/fider/app"
+
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
)
func TestCreateTenant_ShouldHaveVerificationKey(t *testing.T) {
@@ -27,7 +33,7 @@ func TestCreateTenant_EmptyToken(t *testing.T) {
LegalAgreement: true,
},
}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "token", "tenantName", "subdomain")
}
@@ -41,7 +47,7 @@ func TestCreateTenant_EmptyTenantName(t *testing.T) {
LegalAgreement: true,
},
}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "tenantName", "subdomain")
}
@@ -55,7 +61,7 @@ func TestCreateTenant_EmptyEmail(t *testing.T) {
LegalAgreement: true,
},
}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "email", "tenantName", "subdomain")
}
@@ -69,13 +75,18 @@ func TestCreateTenant_InvalidEmail(t *testing.T) {
LegalAgreement: true,
},
}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "email", "tenantName", "subdomain")
}
func TestCreateTenant_NoAgreement(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.IsSubdomainAvailable) error {
+ q.Result = true
+ return nil
+ })
+
action := actions.CreateTenant{
Model: &models.CreateTenant{
Name: "Jon",
@@ -85,7 +96,7 @@ func TestCreateTenant_NoAgreement(t *testing.T) {
LegalAgreement: false,
},
}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "legalAgreement")
}
@@ -99,7 +110,7 @@ func TestCreateTenant_EmptyName(t *testing.T) {
LegalAgreement: true,
},
}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "name", "tenantName", "subdomain")
}
@@ -113,22 +124,22 @@ func TestCreateTenant_EmptySubdomain(t *testing.T) {
LegalAgreement: true,
},
}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "subdomain")
}
func TestUpdateTenantSettings_Unauthorized(t *testing.T) {
RegisterT(t)
- admin := &models.User{ID: 1, Role: models.RoleAdministrator}
- collaborator := &models.User{ID: 2, Role: models.RoleCollaborator}
+ admin := &models.User{ID: 1, Role: enum.RoleAdministrator}
+ collaborator := &models.User{ID: 2, Role: enum.RoleCollaborator}
action := actions.UpdateTenantSettings{}
action.Initialize()
- Expect(action.IsAuthorized(admin, nil)).IsTrue()
- Expect(action.IsAuthorized(collaborator, nil)).IsFalse()
- Expect(action.IsAuthorized(nil, nil)).IsFalse()
+ Expect(action.IsAuthorized(context.Background(), admin)).IsTrue()
+ Expect(action.IsAuthorized(context.Background(), collaborator)).IsFalse()
+ Expect(action.IsAuthorized(context.Background(), nil)).IsFalse()
}
func TestUpdateTenantSettings_EmptyTitle(t *testing.T) {
@@ -136,7 +147,7 @@ func TestUpdateTenantSettings_EmptyTitle(t *testing.T) {
action := actions.UpdateTenantSettings{}
action.Initialize()
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "title")
}
@@ -144,7 +155,7 @@ func TestUpdateTenantSettings_InvalidCNAME(t *testing.T) {
RegisterT(t)
action := actions.UpdateTenantSettings{Model: &models.UpdateTenantSettings{Title: "Ok", CNAME: "bla"}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "cname")
}
@@ -152,7 +163,7 @@ func TestUpdateTenantSettings_LargeTitle(t *testing.T) {
RegisterT(t)
action := actions.UpdateTenantSettings{Model: &models.UpdateTenantSettings{Title: "123456789012345678901234567890123456789012345678901234567890123"}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "title")
}
@@ -160,13 +171,14 @@ func TestUpdateTenantSettings_LargeInvitation(t *testing.T) {
RegisterT(t)
action := actions.UpdateTenantSettings{Model: &models.UpdateTenantSettings{Title: "Ok", Invitation: "123456789012345678901234567890123456789012345678901234567890123"}}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, "invitation")
}
func TestUpdateTenantSettings_ExistingTenant_WithLogo(t *testing.T) {
RegisterT(t)
- services.SetCurrentTenant(&models.Tenant{
+
+ ctx := context.WithValue(context.Background(), app.TenantCtxKey, &models.Tenant{
ID: 1,
LogoBlobKey: "hello-world.png",
})
@@ -175,7 +187,7 @@ func TestUpdateTenantSettings_ExistingTenant_WithLogo(t *testing.T) {
action.Initialize()
action.Model.Title = "OK"
action.Model.Invitation = "Share your ideas!"
- result := action.Validate(nil, services)
+ result := action.Validate(ctx, nil)
ExpectSuccess(result)
Expect(action.Model.Logo.BlobKey).Equals("hello-world.png")
}
diff --git a/app/actions/user.go b/app/actions/user.go
index ffd50eed1..be3e60950 100644
--- a/app/actions/user.go
+++ b/app/actions/user.go
@@ -1,8 +1,13 @@
package actions
import (
+ "context"
+
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/validate"
)
@@ -19,12 +24,12 @@ func (input *CreateUser) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateUser) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *CreateUser) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil && user.IsAdministrator()
}
-// Validate is current model is valid
-func (input *CreateUser) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *CreateUser) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
if input.Model.Name == "" {
@@ -63,17 +68,17 @@ func (input *ChangeUserRole) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *ChangeUserRole) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *ChangeUserRole) IsAuthorized(ctx context.Context, user *models.User) bool {
if user == nil {
return false
}
return user.IsAdministrator() && user.ID != input.Model.UserID
}
-// Validate is current model is valid
-func (input *ChangeUserRole) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *ChangeUserRole) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
- if input.Model.Role < models.RoleVisitor || input.Model.Role > models.RoleAdministrator {
+ if input.Model.Role < enum.RoleVisitor || input.Model.Role > enum.RoleAdministrator {
return validate.Error(app.ErrNotFound)
}
@@ -81,14 +86,15 @@ func (input *ChangeUserRole) Validate(user *models.User, services *app.Services)
result.AddFieldFailure("userID", "It is not allowed to change your own Role.")
}
- target, err := services.Users.GetByID(input.Model.UserID)
+ userByID := &query.GetUserByID{UserID: input.Model.UserID}
+ err := bus.Dispatch(ctx, userByID)
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
result.AddFieldFailure("userID", "User not found.")
} else {
return validate.Error(err)
}
- } else if target.Tenant.ID != user.Tenant.ID {
+ } else if userByID.Result.Tenant.ID != user.Tenant.ID {
result.AddFieldFailure("userID", "User not found.")
}
return result
@@ -107,12 +113,12 @@ func (input *ChangeUserEmail) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *ChangeUserEmail) IsAuthorized(user *models.User, services *app.Services) bool {
+func (input *ChangeUserEmail) IsAuthorized(ctx context.Context, user *models.User) bool {
return user != nil
}
-// Validate is current model is valid
-func (input *ChangeUserEmail) Validate(user *models.User, services *app.Services) *validate.Result {
+// Validate if current model is valid
+func (input *ChangeUserEmail) Validate(ctx context.Context, user *models.User) *validate.Result {
result := validate.Success()
if input.Model.Email == "" {
@@ -136,11 +142,12 @@ func (input *ChangeUserEmail) Validate(user *models.User, services *app.Services
return result
}
- existing, err := services.Users.GetByEmail(input.Model.Email)
+ userByEmail := &query.GetUserByEmail{Email: input.Model.Email}
+ err := bus.Dispatch(ctx, userByEmail)
if err != nil && errors.Cause(err) != app.ErrNotFound {
return validate.Error(err)
}
- if err == nil && existing.ID != user.ID {
+ if err == nil && userByEmail.Result.ID != user.ID {
result.AddFieldFailure("email", "This email is already in use by someone else")
return result
}
diff --git a/app/actions/user_test.go b/app/actions/user_test.go
index 3bc2905a0..a85294e2c 100644
--- a/app/actions/user_test.go
+++ b/app/actions/user_test.go
@@ -1,12 +1,16 @@
package actions_test
import (
+ "context"
"testing"
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/rand"
)
@@ -44,7 +48,7 @@ func TestCreateUser_InvalidInput(t *testing.T) {
action := &actions.CreateUser{
Model: testCase.input,
}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectFailed(result, testCase.expected...)
if testCase.message != "" {
for k, v := range result.Errors {
@@ -87,7 +91,7 @@ func TestCreateUser_ValidInput(t *testing.T) {
action := &actions.CreateUser{
Model: testCase.input,
}
- result := action.Validate(nil, services)
+ result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
}
}
@@ -96,57 +100,51 @@ func TestChangeUserRole_Unauthorized(t *testing.T) {
RegisterT(t)
for _, user := range []*models.User{
- &models.User{ID: 1, Role: models.RoleVisitor},
- &models.User{ID: 1, Role: models.RoleCollaborator},
- &models.User{ID: 2, Role: models.RoleAdministrator},
+ &models.User{ID: 1, Role: enum.RoleVisitor},
+ &models.User{ID: 1, Role: enum.RoleCollaborator},
+ &models.User{ID: 2, Role: enum.RoleAdministrator},
} {
action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: 2}}
- Expect(action.IsAuthorized(user, nil)).IsFalse()
+ Expect(action.IsAuthorized(context.Background(), user)).IsFalse()
}
}
func TestChangeUserRole_Authorized(t *testing.T) {
RegisterT(t)
- user := &models.User{ID: 2, Role: models.RoleAdministrator}
+ user := &models.User{ID: 2, Role: enum.RoleAdministrator}
action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: 1}}
- Expect(action.IsAuthorized(user, nil)).IsTrue()
+ Expect(action.IsAuthorized(context.Background(), user)).IsTrue()
}
func TestChangeUserRole_InvalidRole(t *testing.T) {
RegisterT(t)
- tenant := &models.Tenant{ID: 1}
- services.SetCurrentTenant(tenant)
-
- targetUser := &models.User{
- Tenant: tenant,
- }
- services.Users.Register(targetUser)
-
- currentUser := &models.User{
- Tenant: tenant,
- Role: models.RoleAdministrator,
- }
- services.Users.Register(currentUser)
+ targetUser := &models.User{Role: enum.RoleVisitor}
+ currentUser := &models.User{Role: enum.RoleAdministrator}
action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: targetUser.ID, Role: 4}}
- action.IsAuthorized(currentUser, nil)
- result := action.Validate(currentUser, services)
+ action.IsAuthorized(context.Background(), currentUser)
+ result := action.Validate(context.Background(), currentUser)
Expect(result.Err).Equals(app.ErrNotFound)
}
func TestChangeUserRole_InvalidUser(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ return app.ErrNotFound
+ })
+
currentUser := &models.User{
Tenant: &models.Tenant{ID: 1},
- Role: models.RoleAdministrator,
+ Role: enum.RoleAdministrator,
}
- action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: 999, Role: models.RoleAdministrator}}
- action.IsAuthorized(currentUser, nil)
- result := action.Validate(currentUser, services)
+ ctx := context.Background()
+ action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: 999, Role: enum.RoleAdministrator}}
+ action.IsAuthorized(ctx, currentUser)
+ result := action.Validate(ctx, currentUser)
ExpectFailed(result, "userID")
}
@@ -156,17 +154,23 @@ func TestChangeUserRole_InvalidUser_Tenant(t *testing.T) {
targetUser := &models.User{
Tenant: &models.Tenant{ID: 1},
}
- services.Users.Register(targetUser)
currentUser := &models.User{
Tenant: &models.Tenant{ID: 2},
- Role: models.RoleAdministrator,
+ Role: enum.RoleAdministrator,
}
- services.Users.Register(currentUser)
- action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: targetUser.ID, Role: models.RoleAdministrator}}
- action.IsAuthorized(currentUser, nil)
- result := action.Validate(currentUser, services)
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ if q.UserID == targetUser.ID {
+ q.Result = targetUser
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: targetUser.ID, Role: enum.RoleAdministrator}}
+ action.IsAuthorized(context.Background(), currentUser)
+ result := action.Validate(context.Background(), currentUser)
ExpectFailed(result, "userID")
}
@@ -175,16 +179,19 @@ func TestChangeUserRole_CurrentUser(t *testing.T) {
currentUser := &models.User{
Tenant: &models.Tenant{ID: 2},
- Role: models.RoleAdministrator,
+ Role: enum.RoleAdministrator,
}
- services.Users.Register(currentUser)
- action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: currentUser.ID, Role: models.RoleVisitor}}
- action.IsAuthorized(currentUser, nil)
- result := action.Validate(currentUser, services)
- ExpectFailed(result, "userID")
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ if q.UserID == currentUser.ID {
+ q.Result = currentUser
+ return nil
+ }
+ return app.ErrNotFound
+ })
- user, err := services.Users.GetByID(currentUser.ID)
- Expect(err).IsNil()
- Expect(user.Role).Equals(models.RoleAdministrator)
+ action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: currentUser.ID, Role: enum.RoleVisitor}}
+ action.IsAuthorized(context.Background(), currentUser)
+ result := action.Validate(context.Background(), currentUser)
+ ExpectFailed(result, "userID")
}
diff --git a/app/cmd/migrate.go b/app/cmd/migrate.go
index 49543f068..1ef5d14bf 100644
--- a/app/cmd/migrate.go
+++ b/app/cmd/migrate.go
@@ -1,23 +1,29 @@
package cmd
import (
+ "context"
+
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/dbx"
"github.com/getfider/fider/app/pkg/log"
- "github.com/getfider/fider/app/pkg/log/console"
"github.com/getfider/fider/app/pkg/rand"
+ _ "github.com/getfider/fider/app/services/log/console"
)
// RunMigrate run all pending migrations on current DATABASE_URL
// Returns an exitcode, 0 for OK and 1 for ERROR
func RunMigrate() int {
- logger := console.NewLogger("MIGRATE")
- logger.SetProperty(log.PropertyKeyContextID, rand.String(32))
- db := dbx.NewWithLogger(logger)
- defer db.Close()
+ bus.Init()
+
+ ctx := log.WithProperties(context.Background(), dto.Props{
+ log.PropertyKeyTag: "MIGRATE",
+ log.PropertyKeyContextID: rand.String(32),
+ })
- err := db.Migrate("/migrations")
+ err := dbx.Migrate(ctx, "/migrations")
if err != nil {
- logger.Error(err)
+ log.Error(ctx, err)
return 1
}
return 0
diff --git a/app/cmd/routes.go b/app/cmd/routes.go
index 1bc35011f..9d3bcc43e 100644
--- a/app/cmd/routes.go
+++ b/app/cmd/routes.go
@@ -8,15 +8,17 @@ import (
"github.com/getfider/fider/app/handlers"
"github.com/getfider/fider/app/handlers/apiv1"
"github.com/getfider/fider/app/middlewares"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/pkg/web"
)
func routes(r *web.Engine) *web.Engine {
r.Worker().Use(middlewares.WorkerSetup())
- r.NotFound(func(c web.Context) error {
- next := func(c web.Context) error {
+ r.Use(middlewares.CatchPanic())
+
+ r.NotFound(func(c *web.Context) error {
+ next := func(c *web.Context) error {
return c.NotFound()
}
next = middlewares.Tenant()(next)
@@ -70,7 +72,7 @@ func routes(r *web.Engine) *web.Engine {
tenantAssets.Use(middlewares.ClientCache(30 * 24 * time.Hour))
tenantAssets.Get("/favicon/*bkey", handlers.Favicon())
tenantAssets.Get("/images/*bkey", handlers.ViewUploadedImage())
- tenantAssets.Get("/custom/:md5.css", func(c web.Context) error {
+ tenantAssets.Get("/custom/:md5.css", func(c *web.Context) error {
return c.Blob(http.StatusOK, "text/css", []byte(c.Tenant().CustomCSS))
})
}
@@ -86,8 +88,8 @@ func routes(r *web.Engine) *web.Engine {
r.Get("/signin", handlers.SignInPage())
r.Get("/not-invited", handlers.NotInvitedPage())
- r.Get("/signin/verify", handlers.VerifySignInKey(models.EmailVerificationKindSignIn))
- r.Get("/invite/verify", handlers.VerifySignInKey(models.EmailVerificationKindUserInvitation))
+ r.Get("/signin/verify", handlers.VerifySignInKey(enum.EmailVerificationKindSignIn))
+ r.Get("/invite/verify", handlers.VerifySignInKey(enum.EmailVerificationKindUserInvitation))
r.Post("/_api/signin/complete", handlers.CompleteSignInProfile())
r.Post("/_api/signin", handlers.SignInByEmail())
@@ -105,10 +107,10 @@ func routes(r *web.Engine) *web.Engine {
** This is a temporary redirect and should be removed in the future
** START
*/
- r.Get("/ideas/:number", func(c web.Context) error {
+ r.Get("/ideas/:number", func(c *web.Context) error {
return c.PermanentRedirect(strings.Replace(c.Request.URL.Path, "/ideas/", "/posts/", 1))
})
- r.Get("/ideas/:number/*all", func(c web.Context) error {
+ r.Get("/ideas/:number/*all", func(c *web.Context) error {
return c.PermanentRedirect(strings.Replace(c.Request.URL.Path, "/ideas/", "/posts/", 1))
})
/*
@@ -133,7 +135,7 @@ func routes(r *web.Engine) *web.Engine {
ui.Get("/_api/notifications/unread/total", handlers.TotalUnreadNotifications())
//From this step, only Collaborators and Administrators are allowed
- ui.Use(middlewares.IsAuthorized(models.RoleCollaborator, models.RoleAdministrator))
+ ui.Use(middlewares.IsAuthorized(enum.RoleCollaborator, enum.RoleAdministrator))
ui.Get("/admin", handlers.GeneralSettingsPage())
ui.Get("/admin/advanced", handlers.AdvancedSettingsPage())
@@ -145,7 +147,7 @@ func routes(r *web.Engine) *web.Engine {
ui.Get("/_api/admin/oauth/:provider", handlers.GetOAuthConfig())
//From this step, only Administrators are allowed
- ui.Use(middlewares.IsAuthorized(models.RoleAdministrator))
+ ui.Use(middlewares.IsAuthorized(enum.RoleAdministrator))
ui.Get("/admin/export", handlers.Page("Export · Site Settings", "", "Export.page"))
ui.Get("/admin/export/posts.csv", handlers.ExportPostsToCSV())
@@ -187,7 +189,7 @@ func routes(r *web.Engine) *web.Engine {
api.Delete("/api/v1/posts/:number/subscription", apiv1.Unsubscribe())
//From this step, only Collaborators and Administrators are allowed
- api.Use(middlewares.IsAuthorized(models.RoleCollaborator, models.RoleAdministrator))
+ api.Use(middlewares.IsAuthorized(enum.RoleCollaborator, enum.RoleAdministrator))
api.Get("/api/v1/users", apiv1.ListUsers())
api.Put("/api/v1/posts/:number", apiv1.UpdatePost())
@@ -199,7 +201,7 @@ func routes(r *web.Engine) *web.Engine {
api.Delete("/api/v1/posts/:number/tags/:slug", apiv1.UnassignTag())
//From this step, only Administrators are allowed
- api.Use(middlewares.IsAuthorized(models.RoleAdministrator))
+ api.Use(middlewares.IsAuthorized(enum.RoleAdministrator))
api.Post("/api/v1/users", apiv1.CreateUser())
api.Delete("/api/v1/posts/:number", apiv1.DeletePost())
diff --git a/app/cmd/server.go b/app/cmd/server.go
index 45ae1bd0a..c58f31c2f 100644
--- a/app/cmd/server.go
+++ b/app/cmd/server.go
@@ -1,22 +1,41 @@
package cmd
import (
+ "context"
"os"
"os/signal"
"syscall"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/web"
+
+ _ "github.com/getfider/fider/app/services/billing"
+ _ "github.com/getfider/fider/app/services/blob/fs"
+ _ "github.com/getfider/fider/app/services/blob/s3"
+ _ "github.com/getfider/fider/app/services/blob/sql"
+ _ "github.com/getfider/fider/app/services/email/mailgun"
+ _ "github.com/getfider/fider/app/services/email/smtp"
+ _ "github.com/getfider/fider/app/services/httpclient"
+ _ "github.com/getfider/fider/app/services/log/console"
+ _ "github.com/getfider/fider/app/services/log/sql"
+ _ "github.com/getfider/fider/app/services/oauth"
+ _ "github.com/getfider/fider/app/services/sqlstore/postgres"
)
//RunServer starts the Fider Server
//Returns an exitcode, 0 for OK and 1 for ERROR
func RunServer(settings *models.SystemSettings) int {
- exit := RunMigrate()
- if exit != 0 {
- return exit
+ svcs := bus.Init()
+ ctx := log.WithProperty(context.Background(), log.PropertyKeyTag, "BOOTSTRAP")
+ for _, s := range svcs {
+ log.Debugf(ctx, "Service '@{ServiceCategory}.@{ServiceName}' has been initialized.", dto.Props{
+ "ServiceCategory": s.Category(),
+ "ServiceName": s.Name(),
+ })
}
e := routes(web.New(settings))
@@ -34,7 +53,6 @@ func listenSignals(e *web.Engine, settings *models.SystemSettings) int {
case syscall.SIGINT, syscall.SIGTERM:
err := e.Stop()
if err != nil {
- e.Logger().Error(errors.Wrap(err, "failed to stop fider"))
return 1
}
return 0
diff --git a/app/cmd/signals_unix.go b/app/cmd/signals_unix.go
index 604ce7661..96876fa8c 100644
--- a/app/cmd/signals_unix.go
+++ b/app/cmd/signals_unix.go
@@ -19,11 +19,11 @@ var extraSignals = []os.Signal{syscall.SIGUSR1}
func handleExtraSignal(s os.Signal, e *web.Engine, settings *models.SystemSettings) int {
switch s {
case syscall.SIGUSR1:
- e.Logger().Info("SIGUSR1 received")
- e.Logger().Info("Dumping process status")
+ println("SIGUSR1 received")
+ println("Dumping process status")
buf := new(bytes.Buffer)
- pprof.Lookup("goroutine").WriteTo(buf, 1)
- pprof.Lookup("heap").WriteTo(buf, 1)
+ _ = pprof.Lookup("goroutine").WriteTo(buf, 1)
+ _ = pprof.Lookup("heap").WriteTo(buf, 1)
buf.WriteString("\n")
buf.WriteString(fmt.Sprintf("# FIDER v%s\n", settings.Version))
buf.WriteString(fmt.Sprintf("# BuildTime: %s\n", settings.BuildTime))
@@ -31,7 +31,7 @@ func handleExtraSignal(s os.Signal, e *web.Engine, settings *models.SystemSettin
buf.WriteString(fmt.Sprintf("# Environment: %s\n", settings.Environment))
buf.WriteString(fmt.Sprintf("# Worker Queue: %d\n", e.Worker().Length()))
buf.WriteString(fmt.Sprintf("# Num Goroutines: %d\n", runtime.NumGoroutine()))
- e.Logger().Info(buf.String())
+ println(buf.String())
}
return -1
}
diff --git a/app/const.go b/app/const.go
index 72eb2cbfc..afff51844 100644
--- a/app/const.go
+++ b/app/const.go
@@ -7,3 +7,29 @@ var ErrNotFound = errors.New("Object not found")
// InvitePlaceholder represents the placeholder used by members to invite other users
var InvitePlaceholder = "%invite%"
+
+//ErrUserIDRequired is used when OAuth integration returns an empty user ID
+var ErrUserIDRequired = errors.New("UserID is required during OAuth integration")
+
+type key string
+
+func createKey(name string) key {
+ return key("FIDER_CTX_" + name)
+}
+
+const (
+ //FacebookProvider is const for 'facebook'
+ FacebookProvider = "facebook"
+ //GoogleProvider is const for 'google'
+ GoogleProvider = "google"
+ //GitHubProvider is const for 'github'
+ GitHubProvider = "github"
+)
+
+var (
+ RequestCtxKey = createKey("REQUEST")
+ TransactionCtxKey = createKey("TRANSACTION")
+ TenantCtxKey = createKey("TENANT")
+ UserCtxKey = createKey("USER")
+ LogPropsCtxKey = createKey("LOG_PROPS")
+)
diff --git a/app/handlers/admin.go b/app/handlers/admin.go
index df8f04f92..3e861c2cd 100644
--- a/app/handlers/admin.go
+++ b/app/handlers/admin.go
@@ -2,13 +2,15 @@ package handlers
import (
"github.com/getfider/fider/app/actions"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/web"
- webutil "github.com/getfider/fider/app/pkg/web/util"
)
// GeneralSettingsPage is the general settings page
func GeneralSettingsPage() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
return c.Page(web.Props{
Title: "General · Site Settings",
ChunkName: "GeneralSettings.page",
@@ -18,7 +20,7 @@ func GeneralSettingsPage() web.HandlerFunc {
// AdvancedSettingsPage is the advanced settings page
func AdvancedSettingsPage() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
return c.Page(web.Props{
Title: "Advanced · Site Settings",
ChunkName: "AdvancedSettings.page",
@@ -31,19 +33,21 @@ func AdvancedSettingsPage() web.HandlerFunc {
// UpdateSettings update current tenant' settings
func UpdateSettings() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.UpdateTenantSettings)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := webutil.ProcessImageUpload(c, input.Model.Logo, "logos")
- if err != nil {
- return c.Failure(err)
- }
-
- err = c.Services().Tenants.UpdateSettings(input.Model)
- if err != nil {
+ if err := bus.Dispatch(c,
+ &cmd.UploadImage{
+ Image: input.Model.Logo,
+ Folder: "logos",
+ },
+ &cmd.UpdateTenantSettings{
+ Settings: input.Model,
+ },
+ ); err != nil {
return c.Failure(err)
}
@@ -53,14 +57,13 @@ func UpdateSettings() web.HandlerFunc {
// UpdateAdvancedSettings update current tenant' advanced settings
func UpdateAdvancedSettings() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.UpdateTenantAdvancedSettings)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := c.Services().Tenants.UpdateAdvancedSettings(input.Model)
- if err != nil {
+ if err := bus.Dispatch(c, &cmd.UpdateTenantAdvancedSettings{Settings: input.Model}); err != nil {
return c.Failure(err)
}
@@ -70,14 +73,14 @@ func UpdateAdvancedSettings() web.HandlerFunc {
// UpdatePrivacy update current tenant's privacy settings
func UpdatePrivacy() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.UpdateTenantPrivacy)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := c.Services().Tenants.UpdatePrivacy(input.Model)
- if err != nil {
+ updateSettings := &cmd.UpdateTenantPrivacySettings{Settings: input.Model}
+ if err := bus.Dispatch(c, updateSettings); err != nil {
return c.Failure(err)
}
@@ -87,9 +90,9 @@ func UpdatePrivacy() web.HandlerFunc {
// ManageMembers is the page used by administrators to change member's role
func ManageMembers() web.HandlerFunc {
- return func(c web.Context) error {
- users, err := c.Services().Users.GetAll()
- if err != nil {
+ return func(c *web.Context) error {
+ allUsers := &query.GetAllUsers{}
+ if err := bus.Dispatch(c, allUsers); err != nil {
return c.Failure(err)
}
@@ -97,7 +100,7 @@ func ManageMembers() web.HandlerFunc {
Title: "Manage Members · Site Settings",
ChunkName: "ManageMembers.page",
Data: web.Map{
- "users": users,
+ "users": allUsers.Result,
},
})
}
@@ -105,9 +108,9 @@ func ManageMembers() web.HandlerFunc {
// ManageAuthentication is the page used by administrators to change site authentication settings
func ManageAuthentication() web.HandlerFunc {
- return func(c web.Context) error {
- providers, err := c.Services().OAuth.ListAllProviders()
- if err != nil {
+ return func(c *web.Context) error {
+ listProviders := &query.ListAllOAuthProviders{}
+ if err := bus.Dispatch(c, listProviders); err != nil {
return c.Failure(err)
}
@@ -115,7 +118,7 @@ func ManageAuthentication() web.HandlerFunc {
Title: "Authentication · Site Settings",
ChunkName: "ManageAuthentication.page",
Data: web.Map{
- "providers": providers,
+ "providers": listProviders.Result,
},
})
}
@@ -123,31 +126,35 @@ func ManageAuthentication() web.HandlerFunc {
// GetOAuthConfig returns OAuth config based on given provider
func GetOAuthConfig() web.HandlerFunc {
- return func(c web.Context) error {
- config, err := c.Services().Tenants.GetOAuthConfigByProvider(c.Param("provider"))
- if err != nil {
+ return func(c *web.Context) error {
+ getConfig := &query.GetCustomOAuthConfigByProvider{
+ Provider: c.Param("provider"),
+ }
+ if err := bus.Dispatch(c, getConfig); err != nil {
return c.Failure(err)
}
- return c.Ok(config)
+ return c.Ok(getConfig.Result)
}
}
// SaveOAuthConfig is used to create/edit OAuth configurations
func SaveOAuthConfig() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.CreateEditOAuthConfig)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := webutil.ProcessImageUpload(c, input.Model.Logo, "logos")
- if err != nil {
- return c.Failure(err)
- }
-
- err = c.Services().Tenants.SaveOAuthConfig(input.Model)
- if err != nil {
+ if err := bus.Dispatch(c,
+ &cmd.UploadImage{
+ Image: input.Model.Logo,
+ Folder: "logos",
+ },
+ &cmd.SaveCustomOAuthConfig{
+ Config: input.Model,
+ },
+ ); err != nil {
return c.Failure(err)
}
diff --git a/app/handlers/admin_test.go b/app/handlers/admin_test.go
index 77c54d34a..cbd86c348 100644
--- a/app/handlers/admin_test.go
+++ b/app/handlers/admin_test.go
@@ -1,14 +1,20 @@
package handlers_test
import (
+ "context"
"encoding/base64"
"io/ioutil"
"net/http"
"testing"
+ "github.com/getfider/fider/app/models/cmd"
+
+ "github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/mock"
+ "github.com/getfider/fider/app/services/blob/fs"
"github.com/getfider/fider/app/handlers"
)
@@ -16,7 +22,17 @@ import (
func TestUpdateSettingsHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ var updateCmd *cmd.UpdateTenantSettings
+ bus.AddHandler(func(ctx context.Context, c *cmd.UpdateTenantSettings) error {
+ updateCmd = c
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.UploadImage) error {
+ return nil
+ })
+
+ server := mock.NewServer()
mock.DemoTenant.LogoBlobKey = "logos/hello-world.png"
code, _ := server.
@@ -27,21 +43,32 @@ func TestUpdateSettingsHandler(t *testing.T) {
`{ "title": "GoT", "invitation": "Join us!", "welcomeMessage": "Welcome to GoT Feedback Forum" }`,
)
- tenant, _ := services.Tenants.GetByDomain("demo")
Expect(code).Equals(http.StatusOK)
- Expect(tenant.Name).Equals("GoT")
- Expect(tenant.Invitation).Equals("Join us!")
- Expect(tenant.WelcomeMessage).Equals("Welcome to GoT Feedback Forum")
- Expect(tenant.LogoBlobKey).Equals("logos/hello-world.png")
+ Expect(updateCmd.Settings.Title).Equals("GoT")
+ Expect(updateCmd.Settings.Invitation).Equals("Join us!")
+ Expect(updateCmd.Settings.WelcomeMessage).Equals("Welcome to GoT Feedback Forum")
+ Expect(updateCmd.Settings.Logo.BlobKey).Equals("logos/hello-world.png")
}
func TestUpdateSettingsHandler_NewLogo(t *testing.T) {
RegisterT(t)
+ bus.Init(fs.Service{})
+
+ var updateCmd *cmd.UpdateTenantSettings
+ bus.AddHandler(func(ctx context.Context, c *cmd.UpdateTenantSettings) error {
+ updateCmd = c
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.UploadImage) error {
+ c.Image.BlobKey = c.Folder + "/" + c.Image.Upload.FileName
+ return nil
+ })
logoBytes, _ := ioutil.ReadFile(env.Etc("logo.png"))
logoB64 := base64.StdEncoding.EncodeToString(logoBytes)
- server, services := mock.NewServer()
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
@@ -59,19 +86,27 @@ func TestUpdateSettingsHandler_NewLogo(t *testing.T) {
}
}`)
- tenant, _ := services.Tenants.GetByDomain("demo")
Expect(code).Equals(http.StatusOK)
- Expect(tenant.Name).Equals("GoT")
- Expect(tenant.Invitation).Equals("Join us!")
- Expect(tenant.WelcomeMessage).Equals("Welcome to GoT Feedback Forum")
- Expect(tenant.LogoBlobKey).ContainsSubstring("logos/")
- Expect(tenant.LogoBlobKey).ContainsSubstring("picture.png")
+ Expect(updateCmd.Settings.Title).Equals("GoT")
+ Expect(updateCmd.Settings.Invitation).Equals("Join us!")
+ Expect(updateCmd.Settings.WelcomeMessage).Equals("Welcome to GoT Feedback Forum")
+ Expect(updateCmd.Settings.Logo.BlobKey).Equals("logos/picture.png")
}
func TestUpdateSettingsHandler_RemoveLogo(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ var updateCmd *cmd.UpdateTenantSettings
+ bus.AddHandler(func(ctx context.Context, c *cmd.UpdateTenantSettings) error {
+ updateCmd = c
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.UploadImage) error {
+ return nil
+ })
+
+ server := mock.NewServer()
mock.DemoTenant.LogoBlobKey = "logos/hello-world.png"
code, _ := server.
@@ -87,18 +122,23 @@ func TestUpdateSettingsHandler_RemoveLogo(t *testing.T) {
}
}`)
- tenant, _ := services.Tenants.GetByDomain("demo")
Expect(code).Equals(http.StatusOK)
- Expect(tenant.Name).Equals("GoT")
- Expect(tenant.Invitation).Equals("Join us!")
- Expect(tenant.WelcomeMessage).Equals("Welcome to GoT Feedback Forum")
- Expect(tenant.LogoBlobKey).Equals("")
+ Expect(updateCmd.Settings.Title).Equals("GoT")
+ Expect(updateCmd.Settings.Invitation).Equals("Join us!")
+ Expect(updateCmd.Settings.WelcomeMessage).Equals("Welcome to GoT Feedback Forum")
+ Expect(updateCmd.Settings.Logo.Remove).IsTrue()
}
func TestUpdatePrivacyHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ var updateCmd *cmd.UpdateTenantPrivacySettings
+ bus.AddHandler(func(ctx context.Context, c *cmd.UpdateTenantPrivacySettings) error {
+ updateCmd = c
+ return nil
+ })
+
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
@@ -107,15 +147,18 @@ func TestUpdatePrivacyHandler(t *testing.T) {
`{ "isPrivate": true }`,
)
- tenant, _ := services.Tenants.GetByDomain("demo")
Expect(code).Equals(http.StatusOK)
- Expect(tenant.IsPrivate).IsTrue()
+ Expect(updateCmd.Settings.IsPrivate).IsTrue()
}
func TestManageMembersHandler(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.GetAllUsers) error {
+ return nil
+ })
+
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
Execute(
diff --git a/app/handlers/apiv1/invite.go b/app/handlers/apiv1/invite.go
index 72c4fb495..4e2c9af76 100644
--- a/app/handlers/apiv1/invite.go
+++ b/app/handlers/apiv1/invite.go
@@ -5,7 +5,9 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
- "github.com/getfider/fider/app/pkg/email"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/markdown"
"github.com/getfider/fider/app/pkg/web"
@@ -14,7 +16,7 @@ import (
// SendSampleInvite to current user's email
func SendSampleInvite() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := &actions.InviteUsers{IsSampleInvite: true}
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
@@ -22,14 +24,19 @@ func SendSampleInvite() web.HandlerFunc {
if c.User().Email != "" {
input.Model.Message = strings.Replace(input.Model.Message, app.InvitePlaceholder, "*the link to accept invitation will be here*", -1)
- to := email.NewRecipient(c.User().Name, c.User().Email, email.Params{
+ to := dto.NewRecipient(c.User().Name, c.User().Email, dto.Props{
"subject": input.Model.Subject,
"message": markdown.Full(input.Model.Message),
})
- err := c.Services().Emailer.Send(&c, "invite_email", email.Params{}, c.Tenant().Name, to)
- if err != nil {
- return c.Failure(err)
- }
+
+ bus.Publish(c, &cmd.SendMail{
+ From: c.Tenant().Name,
+ To: []dto.Recipient{to},
+ TemplateName: "invite_email",
+ Props: dto.Props{
+ "logo": web.LogoURL(c),
+ },
+ })
}
return c.Ok(web.Map{})
@@ -38,13 +45,13 @@ func SendSampleInvite() web.HandlerFunc {
// SendInvites sends an email to each recipient
func SendInvites() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.InviteUsers)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- c.Logger().Warnf("Sending @{TotalInvites:magenta} invites by @{ClientIP:magenta}", log.Props{
+ log.Warnf(c, "Sending @{TotalInvites:magenta} invites by @{ClientIP:magenta}", dto.Props{
"TotalInvites": len(input.Invitations),
"ClientIP": c.Request.ClientIP,
})
diff --git a/app/handlers/apiv1/post.go b/app/handlers/apiv1/post.go
index c9e2f2d90..6eb6a0051 100644
--- a/app/handlers/apiv1/post.go
+++ b/app/handlers/apiv1/post.go
@@ -3,103 +3,109 @@ package apiv1
import (
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/web"
- webutil "github.com/getfider/fider/app/pkg/web/util"
"github.com/getfider/fider/app/tasks"
)
// SearchPosts return existing posts based on search criteria
func SearchPosts() web.HandlerFunc {
- return func(c web.Context) error {
- posts, err := c.Services().Posts.Search(
- c.QueryParam("query"),
- c.QueryParam("view"),
- c.QueryParam("limit"),
- c.QueryParamAsArray("tags"),
- )
- if err != nil {
+ return func(c *web.Context) error {
+ searchPosts := &query.SearchPosts{
+ Query: c.QueryParam("query"),
+ View: c.QueryParam("view"),
+ Limit: c.QueryParam("limit"),
+ Tags: c.QueryParamAsArray("tags"),
+ }
+ if err := bus.Dispatch(c, searchPosts); err != nil {
return c.Failure(err)
}
- return c.Ok(posts)
+
+ return c.Ok(searchPosts.Result)
}
}
// CreatePost creates a new post on current tenant
func CreatePost() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.CreateNewPost)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- posts := c.Services().Posts
-
- err := webutil.ProcessMultiImageUpload(c, input.Model.Attachments, "attachments")
- if err != nil {
+ if err := bus.Dispatch(c, &cmd.UploadImages{Images: input.Model.Attachments, Folder: "attachments"}); err != nil {
return c.Failure(err)
}
- post, err := posts.Add(input.Model.Title, input.Model.Description)
- if err != nil {
- return c.Failure(err)
+ newPost := &cmd.AddNewPost{
+ Title: input.Model.Title,
+ Description: input.Model.Description,
}
-
- err = c.Services().Posts.SetAttachments(post, nil, input.Model.Attachments)
+ err := bus.Dispatch(c, newPost)
if err != nil {
return c.Failure(err)
}
- if err := posts.AddVote(post, c.User()); err != nil {
+ setAttachments := &cmd.SetAttachments{Post: newPost.Result, Attachments: input.Model.Attachments}
+ addVote := &cmd.AddVote{Post: newPost.Result, User: c.User()}
+ if err = bus.Dispatch(c, setAttachments, addVote); err != nil {
return c.Failure(err)
}
- c.Enqueue(tasks.NotifyAboutNewPost(post))
+ c.Enqueue(tasks.NotifyAboutNewPost(newPost.Result))
return c.Ok(web.Map{
- "id": post.ID,
- "number": post.Number,
- "title": post.Title,
- "slug": post.Slug,
+ "id": newPost.Result.ID,
+ "number": newPost.Result.Number,
+ "title": newPost.Result.Title,
+ "slug": newPost.Result.Slug,
})
}
}
// GetPost retrieves the existing post by number
func GetPost() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
number, err := c.ParamAsInt("number")
if err != nil {
return c.NotFound()
}
- post, err := c.Services().Posts.GetByNumber(number)
- if err != nil {
+ getPost := &query.GetPostByNumber{Number: number}
+ if err := bus.Dispatch(c, getPost); err != nil {
return c.Failure(err)
}
- return c.Ok(post)
+ return c.Ok(getPost.Result)
}
}
// UpdatePost updates an existing post of current tenant
func UpdatePost() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.UpdatePost)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := webutil.ProcessMultiImageUpload(c, input.Model.Attachments, "attachments")
- if err != nil {
- return c.Failure(err)
- }
-
- _, err = c.Services().Posts.Update(input.Post, input.Model.Title, input.Model.Description)
- if err != nil {
- return c.Failure(err)
- }
-
- err = c.Services().Posts.SetAttachments(input.Post, nil, input.Model.Attachments)
+ err := bus.Dispatch(c,
+ &cmd.UploadImages{
+ Images: input.Model.Attachments,
+ Folder: "attachments",
+ },
+ &cmd.UpdatePost{
+ Post: input.Post,
+ Title: input.Model.Title,
+ Description: input.Model.Description,
+ },
+ &cmd.SetAttachments{
+ Post: input.Post,
+ Attachments: input.Model.Attachments,
+ },
+ )
if err != nil {
return c.Failure(err)
}
@@ -110,28 +116,35 @@ func UpdatePost() web.HandlerFunc {
// SetResponse changes current post staff response
func SetResponse() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.SetResponse)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- post, err := c.Services().Posts.GetByNumber(input.Model.Number)
- if err != nil {
+ getPost := &query.GetPostByNumber{Number: input.Model.Number}
+ if err := bus.Dispatch(c, getPost); err != nil {
return c.Failure(err)
}
- prevStatus := post.Status
- if input.Model.Status == models.PostDuplicate {
- err = c.Services().Posts.MarkAsDuplicate(post, input.Original)
+ prevStatus := getPost.Result.Status
+
+ var command bus.Msg
+ if input.Model.Status == enum.PostDuplicate {
+ command = &cmd.MarkPostAsDuplicate{Post: getPost.Result, Original: input.Original}
} else {
- err = c.Services().Posts.SetResponse(post, input.Model.Text, input.Model.Status)
+ command = &cmd.SetPostResponse{
+ Post: getPost.Result,
+ Text: input.Model.Text,
+ Status: input.Model.Status,
+ }
}
- if err != nil {
+
+ if err := bus.Dispatch(c, command); err != nil {
return c.Failure(err)
}
- c.Enqueue(tasks.NotifyAboutStatusChange(post, prevStatus))
+ c.Enqueue(tasks.NotifyAboutStatusChange(getPost.Result, prevStatus))
return c.Ok(web.Map{})
}
@@ -139,13 +152,17 @@ func SetResponse() web.HandlerFunc {
// DeletePost deletes an existing post of current tenant
func DeletePost() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.DeletePost)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := c.Services().Posts.SetResponse(input.Post, input.Model.Text, models.PostDeleted)
+ err := bus.Dispatch(c, &cmd.SetPostResponse{
+ Post: input.Post,
+ Text: input.Model.Text,
+ Status: enum.PostDeleted,
+ })
if err != nil {
return c.Failure(err)
}
@@ -161,103 +178,107 @@ func DeletePost() web.HandlerFunc {
// ListComments returns a list of all comments of a post
func ListComments() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
number, err := c.ParamAsInt("number")
if err != nil {
return c.NotFound()
}
- post, err := c.Services().Posts.GetByNumber(number)
- if err != nil {
+ getPost := &query.GetPostByNumber{Number: number}
+ if err := bus.Dispatch(c, getPost); err != nil {
return c.Failure(err)
}
- comments, err := c.Services().Posts.GetCommentsByPost(post)
- if err != nil {
+ getComments := &query.GetCommentsByPost{Post: getPost.Result}
+ if err := bus.Dispatch(c, getComments); err != nil {
return c.Failure(err)
}
- return c.Ok(comments)
+ return c.Ok(getComments.Result)
}
}
// GetComment returns a single comment by its ID
func GetComment() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
id, err := c.ParamAsInt("id")
if err != nil {
return c.NotFound()
}
- comment, err := c.Services().Posts.GetCommentByID(id)
- if err != nil {
+ commentByID := &query.GetCommentByID{CommentID: id}
+ if bus.Dispatch(c, commentByID); err != nil {
return c.Failure(err)
}
- return c.Ok(comment)
+ return c.Ok(commentByID.Result)
}
}
// PostComment creates a new comment on given post
func PostComment() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.AddNewComment)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := webutil.ProcessMultiImageUpload(c, input.Model.Attachments, "attachments")
- if err != nil {
+ getPost := &query.GetPostByNumber{Number: input.Model.Number}
+ if err := bus.Dispatch(c, getPost); err != nil {
return c.Failure(err)
}
- post, err := c.Services().Posts.GetByNumber(input.Model.Number)
- if err != nil {
+ if err := bus.Dispatch(c, &cmd.UploadImages{Images: input.Model.Attachments, Folder: "attachments"}); err != nil {
return c.Failure(err)
}
- id, err := c.Services().Posts.AddComment(post, input.Model.Content)
- if err != nil {
- return c.Failure(err)
+ addNewComment := &cmd.AddNewComment{
+ Post: getPost.Result,
+ Content: input.Model.Content,
}
-
- comment, err := c.Services().Posts.GetCommentByID(id)
- if err != nil {
+ if err := bus.Dispatch(c, addNewComment); err != nil {
return c.Failure(err)
}
- err = c.Services().Posts.SetAttachments(post, comment, input.Model.Attachments)
- if err != nil {
+ if err := bus.Dispatch(c, &cmd.SetAttachments{
+ Post: getPost.Result,
+ Comment: addNewComment.Result,
+ Attachments: input.Model.Attachments,
+ }); err != nil {
return c.Failure(err)
}
- c.Enqueue(tasks.NotifyAboutNewComment(post, input.Model))
+ c.Enqueue(tasks.NotifyAboutNewComment(getPost.Result, input.Model))
return c.Ok(web.Map{
- "id": id,
+ "id": addNewComment.Result.ID,
})
}
}
// UpdateComment changes an existing comment with new content
func UpdateComment() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.EditComment)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := webutil.ProcessMultiImageUpload(c, input.Model.Attachments, "attachments")
- if err != nil {
- return c.Failure(err)
- }
-
- err = c.Services().Posts.UpdateComment(input.Model.ID, input.Model.Content)
- if err != nil {
- return c.Failure(err)
- }
-
- err = c.Services().Posts.SetAttachments(input.Post, input.Comment, input.Model.Attachments)
+ err := bus.Dispatch(c,
+ &cmd.UploadImages{
+ Images: input.Model.Attachments,
+ Folder: "attachments",
+ },
+ &cmd.UpdateComment{
+ CommentID: input.Model.ID,
+ Content: input.Model.Content,
+ },
+ &cmd.SetAttachments{
+ Post: input.Post,
+ Comment: input.Comment,
+ Attachments: input.Model.Attachments,
+ },
+ )
if err != nil {
return c.Failure(err)
}
@@ -268,13 +289,15 @@ func UpdateComment() web.HandlerFunc {
// DeleteComment deletes an existing comment by its ID
func DeleteComment() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.DeleteComment)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := c.Services().Posts.DeleteComment(input.Model.CommentID)
+ err := bus.Dispatch(c, &cmd.DeleteComment{
+ CommentID: input.Model.CommentID,
+ })
if err != nil {
return c.Failure(err)
}
@@ -285,66 +308,76 @@ func DeleteComment() web.HandlerFunc {
// AddVote adds current user to given post list of votes
func AddVote() web.HandlerFunc {
- return func(c web.Context) error {
- return addOrRemove(c, c.Services().Posts.AddVote)
+ return func(c *web.Context) error {
+ return addOrRemove(c, func(post *models.Post, user *models.User) bus.Msg {
+ return &cmd.AddVote{Post: post, User: user}
+ })
}
}
// RemoveVote removes current user from given post list of votes
func RemoveVote() web.HandlerFunc {
- return func(c web.Context) error {
- return addOrRemove(c, c.Services().Posts.RemoveVote)
+ return func(c *web.Context) error {
+ return addOrRemove(c, func(post *models.Post, user *models.User) bus.Msg {
+ return &cmd.RemoveVote{Post: post, User: user}
+ })
}
}
// Subscribe adds current user to list of subscribers of given post
func Subscribe() web.HandlerFunc {
- return func(c web.Context) error {
- return addOrRemove(c, c.Services().Posts.AddSubscriber)
+ return func(c *web.Context) error {
+ return addOrRemove(c, func(post *models.Post, user *models.User) bus.Msg {
+ return &cmd.AddSubscriber{Post: post, User: user}
+ })
}
}
// Unsubscribe removes current user from list of subscribers of given post
func Unsubscribe() web.HandlerFunc {
- return func(c web.Context) error {
- return addOrRemove(c, c.Services().Posts.RemoveSubscriber)
+ return func(c *web.Context) error {
+ return addOrRemove(c, func(post *models.Post, user *models.User) bus.Msg {
+ return &cmd.RemoveSubscriber{Post: post, User: user}
+ })
}
}
// ListVotes returns a list of all votes on given post
func ListVotes() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
number, err := c.ParamAsInt("number")
if err != nil {
return c.NotFound()
}
- post, err := c.Services().Posts.GetByNumber(number)
- if err != nil {
+ getPost := &query.GetPostByNumber{Number: number}
+ if err := bus.Dispatch(c, getPost); err != nil {
return c.Failure(err)
}
- votes, err := c.Services().Posts.ListVotes(post, -1)
+ listVotes := &query.ListPostVotes{PostID: getPost.Result.ID}
+ err = bus.Dispatch(c, listVotes)
if err != nil {
return c.Failure(err)
}
- return c.Ok(votes)
+ return c.Ok(listVotes.Result)
}
}
-func addOrRemove(c web.Context, addOrRemove func(post *models.Post, user *models.User) error) error {
+func addOrRemove(c *web.Context, getCommand func(post *models.Post, user *models.User) bus.Msg) error {
number, err := c.ParamAsInt("number")
if err != nil {
return c.NotFound()
}
- post, err := c.Services().Posts.GetByNumber(number)
- if err != nil {
+ getPost := &query.GetPostByNumber{Number: number}
+ if err := bus.Dispatch(c, getPost); err != nil {
return c.Failure(err)
}
- err = addOrRemove(post, c.User())
+ cmd := getCommand(getPost.Result, c.User())
+ err = bus.Dispatch(c, cmd)
if err != nil {
return c.Failure(err)
}
diff --git a/app/handlers/apiv1/post_test.go b/app/handlers/apiv1/post_test.go
index b564cfab4..9f17814be 100644
--- a/app/handlers/apiv1/post_test.go
+++ b/app/handlers/apiv1/post_test.go
@@ -1,99 +1,134 @@
package apiv1_test
import (
+ "context"
"fmt"
"net/http"
"testing"
+ "github.com/getfider/fider/app/models"
+
"github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app/models/cmd"
+
"github.com/getfider/fider/app/handlers/apiv1"
- "github.com/getfider/fider/app/models"
. "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/mock"
)
func TestCreatePostHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- code, _ := server.
+ var newPost *cmd.AddNewPost
+ bus.AddHandler(func(ctx context.Context, c *cmd.AddNewPost) error {
+ newPost = c
+ c.Result = &models.Post{
+ ID: 1,
+ Title: c.Title,
+ Description: c.Description,
+ }
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostBySlug) error {
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetAttachments) error { return nil })
+ bus.AddHandler(func(ctx context.Context, c *cmd.AddVote) error { return nil })
+ bus.AddHandler(func(ctx context.Context, c *cmd.UploadImages) error { return nil })
+
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
ExecutePost(apiv1.CreatePost(), `{ "title": "My newest post :)" }`)
- post, err := services.Posts.GetByID(1)
Expect(code).Equals(http.StatusOK)
- Expect(err).IsNil()
- Expect(post.Title).Equals("My newest post :)")
- Expect(post.VotesCount).Equals(1)
+ Expect(newPost.Title).Equals("My newest post :)")
+ Expect(newPost.Description).Equals("")
}
func TestCreatePostHandler_WithoutTitle(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- code, _ := server.
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
ExecutePost(apiv1.CreatePost(), `{ "title": "" }`)
- _, err := services.Posts.GetByID(1)
Expect(code).Equals(http.StatusBadRequest)
- Expect(err).IsNotNil()
}
func TestGetPostHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- post, _ := services.Posts.Add("My First Post", "Such an amazing description")
+ post := &models.Post{ID: 5, Number: 5, Title: "My First Post", Description: "Such an amazing description"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ if q.Number == post.Number {
+ q.Result = post
+ return nil
+ }
+ return app.ErrNotFound
+ })
- code, query := server.
+ code, query := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
AddParam("number", post.Number).
ExecuteAsJSON(apiv1.GetPost())
-
+
Expect(code).Equals(http.StatusOK)
- Expect(query.String("title")).Equals("My First Post")
- Expect(query.String("description")).Equals("Such an amazing description")
+ Expect(query.String("title")).Equals(post.Title)
+ Expect(query.String("description")).Equals(post.Description)
}
func TestUpdatePostHandler_TenantStaff(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.AryaStark)
- post, _ := services.Posts.Add("My First Post", "With a description")
-
- code, _ := server.
+ post := &models.Post{ID: 5, Number: 5, Title: "My First Post", Description: "With a description"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ if q.Number == post.Number {
+ q.Result = post
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostBySlug) error { return app.ErrNotFound })
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetAttachments) error { return nil })
+ bus.AddHandler(func(ctx context.Context, c *cmd.UploadImages) error { return nil })
+
+ var updatePost *cmd.UpdatePost
+ bus.AddHandler(func(ctx context.Context, c *cmd.UpdatePost) error {
+ updatePost = c
+ return nil
+ })
+
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
AddParam("number", post.Number).
ExecutePost(apiv1.UpdatePost(), `{ "title": "the new title", "description": "new description" }`)
- post, _ = services.Posts.GetByNumber(post.Number)
Expect(code).Equals(http.StatusOK)
- Expect(post.Title).Equals("the new title")
- Expect(post.Description).Equals("new description")
+ Expect(updatePost.Post).Equals(post)
+ Expect(updatePost.Title).Equals("the new title")
+ Expect(updatePost.Description).Equals("new description")
}
func TestUpdatePostHandler_NonAuthorized(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- post, _ := services.Posts.Add("My First Post", "With a description")
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostBySlug) error { return app.ErrNotFound })
- code, _ := server.
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.AryaStark).
- AddParam("number", post.Number).
+ AddParam("number", "5").
ExecutePost(apiv1.UpdatePost(), `{ "title": "the new title", "description": "new description" }`)
Expect(code).Equals(http.StatusForbidden)
@@ -102,12 +137,18 @@ func TestUpdatePostHandler_NonAuthorized(t *testing.T) {
func TestUpdatePostHandler_InvalidTitle(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- post, _ := services.Posts.Add("My First Post", "With a description")
+ post := &models.Post{ID: 5, Number: 5, Title: "My First Post", Description: "Such an amazing description"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ if q.Number == post.Number {
+ q.Result = post
+ return nil
+ }
+ return app.ErrNotFound
+ })
- code, _ := server.
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostBySlug) error { return app.ErrNotFound })
+
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
AddParam("number", post.Number).
@@ -119,9 +160,19 @@ func TestUpdatePostHandler_InvalidTitle(t *testing.T) {
func TestUpdatePostHandler_InvalidPost(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ post := &models.Post{ID: 5, Number: 5, Title: "My First Post", Description: "Such an amazing description"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ if q.Number == post.Number {
+ q.Result = post
+ return nil
+ }
+ return app.ErrNotFound
+ })
- code, _ := server.
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostBySlug) error { return app.ErrNotFound })
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error { return app.ErrNotFound })
+
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
AddParam("number", 999).
@@ -133,13 +184,33 @@ func TestUpdatePostHandler_InvalidPost(t *testing.T) {
func TestUpdatePostHandler_DuplicateTitle(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- post1, _ := services.Posts.Add("My First Post", "With a description")
- services.Posts.Add("My Second Post", "With a description")
-
- code, _ := server.
+ post1 := &models.Post{ID: 1, Number: 1, Title: "My First Post", Slug: "my-first-post"}
+ post2 := &models.Post{ID: 2, Number: 2, Title: "My Second Post", Slug: "my-second-post"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ if q.Number == post1.Number {
+ q.Result = post1
+ return nil
+ }
+ if q.Number == post2.Number {
+ q.Result = post2
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostBySlug) error {
+ if q.Slug == post1.Slug {
+ q.Result = post1
+ return nil
+ }
+ if q.Slug == post2.Slug {
+ q.Result = post2
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
AddParam("number", post1.Number).
@@ -151,81 +222,94 @@ func TestUpdatePostHandler_DuplicateTitle(t *testing.T) {
func TestSetResponseHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.AryaStark)
- post, _ := services.Posts.Add("The Post #1", "The Description #1")
- services.Posts.AddVote(post, mock.AryaStark)
-
- code, _ := server.
+ post := &models.Post{ID: 1, Number: 1, Title: "My First Post", Slug: "my-first-post"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ if q.Number == post.Number {
+ q.Result = post
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ var setResponse *cmd.SetPostResponse
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetPostResponse) error {
+ setResponse = c
+ return nil
+ })
+
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
- AddParam("number", post.ID).
- ExecutePost(apiv1.SetResponse(), fmt.Sprintf(`{ "status": "%s", "text": "Done!" }`, models.PostCompleted.Name()))
-
- post, _ = services.Posts.GetByNumber(post.Number)
+ AddParam("number", post.Number).
+ ExecutePost(apiv1.SetResponse(), fmt.Sprintf(`{ "status": "%s", "text": "Done!" }`, enum.PostCompleted.Name()))
Expect(code).Equals(http.StatusOK)
- Expect(post.Status).Equals(models.PostCompleted)
- Expect(post.Response.Text).Equals("Done!")
- Expect(post.Response.User.ID).Equals(mock.JonSnow.ID)
+ Expect(setResponse.Post).Equals(post)
+ Expect(setResponse.Status).Equals(enum.PostCompleted)
+ Expect(setResponse.Text).Equals("Done!")
}
func TestSetResponseHandler_Unauthorized(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.AryaStark)
- post, _ := services.Posts.Add("The Post #1", "The Description #1")
- services.Posts.AddVote(post, mock.AryaStark)
-
- code, _ := server.
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.AryaStark).
- AddParam("number", post.ID).
- ExecutePost(apiv1.SetResponse(), fmt.Sprintf(`{ "status": "%s", "text": "Done!" }`, models.PostCompleted.Name()))
-
- post, _ = services.Posts.GetByNumber(post.Number)
+ AddParam("number", 5).
+ ExecutePost(apiv1.SetResponse(), fmt.Sprintf(`{ "status": "%s", "text": "Done!" }`, enum.PostCompleted.Name()))
Expect(code).Equals(http.StatusForbidden)
- Expect(post.Status).Equals(models.PostOpen)
}
func TestSetResponseHandler_Duplicate(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.AryaStark)
- post1, _ := services.Posts.Add("The Post #1", "The Description #1")
- post2, _ := services.Posts.Add("The Post #2", "The Description #2")
-
- body := fmt.Sprintf(`{ "status": "%s", "originalNumber": %d }`, models.PostDuplicate.Name(), post2.Number)
- code, _ := server.
+ var markAsDuplicate *cmd.MarkPostAsDuplicate
+ bus.AddHandler(func(ctx context.Context, c *cmd.MarkPostAsDuplicate) error {
+ markAsDuplicate = c
+ return nil
+ })
+
+ post1 := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ post2 := &models.Post{ID: 2, Number: 2, Title: "The Post #2", Description: "The Description #2"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ if q.Number == post1.Number {
+ q.Result = post1
+ return nil
+ }
+ if q.Number == post2.Number {
+ q.Result = post2
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ body := fmt.Sprintf(`{ "status": "%s", "originalNumber": %d }`, enum.PostDuplicate.Name(), post2.Number)
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
AddParam("number", post1.ID).
ExecutePost(apiv1.SetResponse(), body)
- Expect(code).Equals(http.StatusOK)
- post1, _ = services.Posts.GetByNumber(post1.Number)
- Expect(post1.Status).Equals(models.PostDuplicate)
-
- post2, _ = services.Posts.GetByNumber(post2.Number)
- Expect(post2.Status).Equals(models.PostOpen)
+ Expect(code).Equals(http.StatusOK)
+ Expect(markAsDuplicate.Post).Equals(post1)
+ Expect(markAsDuplicate.Original).Equals(post2)
}
func TestSetResponseHandler_Duplicate_NotFound(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.AryaStark)
- post1, _ := services.Posts.Add("The Post #1", "The Description #1")
-
- body := fmt.Sprintf(`{ "status": "%s", "originalNumber": 9999 }`, models.PostDuplicate.Name())
- code, _ := server.
+ post1 := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ if q.Number == post1.Number {
+ q.Result = post1
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ body := fmt.Sprintf(`{ "status": "%s", "originalNumber": 9999 }`, enum.PostDuplicate.Name())
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
AddParam("number", post1.ID).
@@ -237,13 +321,17 @@ func TestSetResponseHandler_Duplicate_NotFound(t *testing.T) {
func TestSetResponseHandler_Duplicate_Itself(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.AryaStark)
- post, _ := services.Posts.Add("The Post #1", "The Description #1")
-
- body := fmt.Sprintf(`{ "status": "%s", "originalNumber": %d }`, models.PostDuplicate.Name(), post.Number)
- code, _ := server.
+ post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ if q.Number == post.Number {
+ q.Result = post
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ body := fmt.Sprintf(`{ "status": "%s", "originalNumber": %d }`, enum.PostDuplicate.Name(), post.Number)
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
AddParam("number", post.ID).
@@ -255,31 +343,37 @@ func TestSetResponseHandler_Duplicate_Itself(t *testing.T) {
func TestAddVoteHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- first, _ := services.Posts.Add("The Post #1", "The Description #1")
- second, _ := services.Posts.Add("The Post #2", "The Description #2")
+ post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ q.Result = post
+ return nil
+ })
- code, _ := server.
+ var addVote *cmd.AddVote
+ bus.AddHandler(func(ctx context.Context, c *cmd.AddVote) error {
+ addVote = c
+ return nil
+ })
+
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.AryaStark).
- AddParam("number", second.Number).
+ AddParam("number", post.Number).
Execute(apiv1.AddVote())
- first, _ = services.Posts.GetByNumber(1)
- second, _ = services.Posts.GetByNumber(2)
-
Expect(code).Equals(http.StatusOK)
- Expect(first.VotesCount).Equals(0)
- Expect(second.VotesCount).Equals(1)
+ Expect(addVote.Post).Equals(post)
+ Expect(addVote.User).Equals(mock.AryaStark)
}
func TestAddVoteHandler_InvalidPost(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
- code, _ := server.
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ return app.ErrNotFound
+ })
+
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.AryaStark).
AddParam("number", 999).
@@ -291,71 +385,101 @@ func TestAddVoteHandler_InvalidPost(t *testing.T) {
func TestRemoveVoteHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- post, _ := services.Posts.Add("The Post #1", "The Description #1")
- services.Posts.AddVote(post, mock.JonSnow)
- services.Posts.AddVote(post, mock.AryaStark)
+ post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ q.Result = post
+ return nil
+ })
- code, _ := server.
+ var removeVote *cmd.RemoveVote
+ bus.AddHandler(func(ctx context.Context, c *cmd.RemoveVote) error {
+ removeVote = c
+ return nil
+ })
+
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.AryaStark).
AddParam("number", post.ID).
Execute(apiv1.RemoveVote())
- post, _ = services.Posts.GetByNumber(post.Number)
-
Expect(code).Equals(http.StatusOK)
- Expect(post.VotesCount).Equals(1)
+ Expect(removeVote.Post).Equals(post)
+ Expect(removeVote.User).Equals(mock.AryaStark)
}
func TestDeletePostHandler_Authorized(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- post, _ := services.Posts.Add("The Post #1", "The Description #1")
+ post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ q.Result = post
+ return nil
+ })
- code, _ := server.
+ bus.AddHandler(func(ctx context.Context, q *query.PostIsReferenced) error {
+ q.Result = false
+ return nil
+ })
+
+ var deletePost *cmd.SetPostResponse
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetPostResponse) error {
+ deletePost = c
+ return nil
+ })
+
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
AddParam("number", post.Number).
ExecutePost(apiv1.DeletePost(), `{ }`)
Expect(code).Equals(http.StatusOK)
- post, err := services.Posts.GetByNumber(post.Number)
- Expect(post).IsNil()
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(deletePost.Post).Equals(post)
+ Expect(deletePost.Status).Equals(enum.PostDeleted)
+ Expect(deletePost.Text).Equals("")
}
func TestPostCommentHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- post, _ := services.Posts.Add("My First Post", "With a description")
+ post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ q.Result = post
+ return nil
+ })
- code, _ := server.
+ var newComment *cmd.AddNewComment
+ bus.AddHandler(func(ctx context.Context, c *cmd.AddNewComment) error {
+ newComment = c
+ c.Result = &models.Comment{ID: 1, Content: c.Content}
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetAttachments) error { return nil })
+ bus.AddHandler(func(ctx context.Context, c *cmd.UploadImages) error { return nil })
+
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
AddParam("number", post.Number).
ExecutePost(apiv1.PostComment(), `{ "content": "This is a comment!" }`)
Expect(code).Equals(http.StatusOK)
+ Expect(newComment.Post).Equals(post)
+ Expect(newComment.Content).Equals("This is a comment!")
}
func TestPostCommentHandler_WithoutContent(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- post, _ := services.Posts.Add("My First Post", "With a description")
+ post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ q.Result = post
+ return nil
+ })
- code, _ := server.
+ code, _ := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
AddParam("number", post.Number).
@@ -364,78 +488,89 @@ func TestPostCommentHandler_WithoutContent(t *testing.T) {
Expect(code).Equals(http.StatusBadRequest)
}
-func TestAddCommentHandler(t *testing.T) {
+func TestUpdateCommentHandler_Authorized(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.AryaStark)
- post, _ := services.Posts.Add("The Post #1", "The Description #1")
+ server := mock.NewServer()
- code, _ := server.
- OnTenant(mock.DemoTenant).
- AsUser(mock.JonSnow).
- AddParam("number", post.Number).
- ExecutePost(apiv1.PostComment(), `{ "content": "My first comment" }`)
+ post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ q.Result = post
+ return nil
+ })
- Expect(code).Equals(http.StatusOK)
- comments, _ := services.Posts.GetCommentsByPost(post)
- Expect(comments).HasLen(1)
-}
+ comment := &models.Comment{ID: 5, Content: "Old comment text", User: mock.AryaStark}
+ bus.AddHandler(func(ctx context.Context, q *query.GetCommentByID) error {
+ q.Result = comment
+ return nil
+ })
-func TestUpdateCommentHandler_Authorized(t *testing.T) {
- RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.GetAttachments) error { return nil })
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetAttachments) error { return nil })
+ bus.AddHandler(func(ctx context.Context, c *cmd.UploadImages) error { return nil })
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.AryaStark)
- post, _ := services.Posts.Add("The Post #1", "The Description #1")
- commentID, _ := services.Posts.AddComment(post, "My first comment")
+ var updateComment *cmd.UpdateComment
+ bus.AddHandler(func(ctx context.Context, c *cmd.UpdateComment) error {
+ updateComment = c
+ return nil
+ })
code, _ := server.
OnTenant(mock.DemoTenant).
AsUser(mock.AryaStark).
AddParam("number", post.Number).
- AddParam("id", commentID).
+ AddParam("id", comment.ID).
ExecutePost(apiv1.UpdateComment(), `{ "content": "My first comment has been edited" }`)
Expect(code).Equals(http.StatusOK)
- comment, _ := services.Posts.GetCommentByID(commentID)
- Expect(comment.Content).Equals("My first comment has been edited")
+ Expect(updateComment.Content).Equals("My first comment has been edited")
}
func TestUpdateCommentHandler_Unauthorized(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- post, _ := services.Posts.Add("The Post #1", "The Description #1")
- commentID, _ := services.Posts.AddComment(post, "My first comment")
+ server := mock.NewServer()
+
+ post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ q.Result = post
+ return nil
+ })
+
+ comment := &models.Comment{ID: 5, Content: "Old comment text", User: mock.JonSnow}
+ bus.AddHandler(func(ctx context.Context, q *query.GetCommentByID) error {
+ q.Result = comment
+ return nil
+ })
code, _ := server.
OnTenant(mock.DemoTenant).
AsUser(mock.AryaStark).
AddParam("number", post.Number).
- AddParam("id", commentID).
+ AddParam("id", comment.ID).
ExecutePost(apiv1.UpdateComment(), `{ "content": "My first comment has been edited" }`)
Expect(code).Equals(http.StatusForbidden)
- comment, _ := services.Posts.GetCommentByID(commentID)
- Expect(comment.Content).Equals("My first comment")
}
func TestListCommentHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- post, _ := services.Posts.Add("My First Post", "With a description")
- services.Posts.AddComment(post, "This is ...")
- services.Posts.AddComment(post, "Great!")
-
- code, query := server.
+ post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ q.Result = post
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetCommentsByPost) error {
+ q.Result = []*models.Comment{
+ &models.Comment{ID: 1, Content: "First Comment"},
+ &models.Comment{ID: 2, Content: "First Comment"},
+ }
+ return nil
+ })
+
+ code, query := mock.NewServer().
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
AddParam("number", post.Number).
diff --git a/app/handlers/apiv1/tag.go b/app/handlers/apiv1/tag.go
index 729ade870..2cfc15d51 100644
--- a/app/handlers/apiv1/tag.go
+++ b/app/handlers/apiv1/tag.go
@@ -2,31 +2,33 @@ package apiv1
import (
"github.com/getfider/fider/app/actions"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/web"
)
// ListTags returns all tags
func ListTags() web.HandlerFunc {
- return func(c web.Context) error {
- tags, err := c.Services().Tags.GetAll()
- if err != nil {
+ return func(c *web.Context) error {
+ q := &query.GetAllTags{}
+ if err := bus.Dispatch(c, q); err != nil {
return c.Failure(err)
}
- return c.Ok(tags)
+ return c.Ok(q.Result)
}
}
// AssignTag to existing dea
func AssignTag() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.AssignUnassignTag)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := c.Services().Tags.AssignTag(input.Tag, input.Post)
+ err := bus.Dispatch(c, &cmd.AssignTag{Tag: input.Tag, Post: input.Post})
if err != nil {
return c.Failure(err)
}
@@ -37,13 +39,13 @@ func AssignTag() web.HandlerFunc {
// UnassignTag from existing dea
func UnassignTag() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.AssignUnassignTag)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := c.Services().Tags.UnassignTag(input.Tag, input.Post)
+ err := bus.Dispatch(c, &cmd.UnassignTag{Tag: input.Tag, Post: input.Post})
if err != nil {
return c.Failure(err)
}
@@ -54,40 +56,46 @@ func UnassignTag() web.HandlerFunc {
// CreateEditTag creates a new tag on current tenant
func CreateEditTag() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.CreateEditTag)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- var (
- tag *models.Tag
- err error
- )
-
if input.Model.Slug != "" {
- tag, err = c.Services().Tags.Update(input.Tag, input.Model.Name, input.Model.Color, input.Model.IsPublic)
- } else {
- tag, err = c.Services().Tags.Add(input.Model.Name, input.Model.Color, input.Model.IsPublic)
+ updateTag := &cmd.UpdateTag{
+ TagID: input.Tag.ID,
+ Name: input.Model.Name,
+ Color: input.Model.Color,
+ IsPublic: input.Model.IsPublic,
+ }
+ if err := bus.Dispatch(c, updateTag); err != nil {
+ return c.Failure(err)
+ }
+ return c.Ok(updateTag.Result)
}
- if err != nil {
+ addNewTag := &cmd.AddNewTag{
+ Name: input.Model.Name,
+ Color: input.Model.Color,
+ IsPublic: input.Model.IsPublic,
+ }
+ if err := bus.Dispatch(c, addNewTag); err != nil {
return c.Failure(err)
}
-
- return c.Ok(tag)
+ return c.Ok(addNewTag.Result)
}
}
// DeleteTag deletes an existing tag
func DeleteTag() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.DeleteTag)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := c.Services().Tags.Delete(input.Tag)
+ err := bus.Dispatch(c, &cmd.DeleteTag{Tag: input.Tag})
if err != nil {
return c.Failure(err)
}
diff --git a/app/handlers/apiv1/tag_test.go b/app/handlers/apiv1/tag_test.go
index d2b00f0b0..62aedde2c 100644
--- a/app/handlers/apiv1/tag_test.go
+++ b/app/handlers/apiv1/tag_test.go
@@ -1,13 +1,17 @@
package apiv1_test
import (
+ "context"
"net/http"
"testing"
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/handlers/apiv1"
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/pkg/web"
)
@@ -15,7 +19,17 @@ import (
func TestCreateTagHandler_ValidRequests(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ return app.ErrNotFound
+ })
+
+ var addNewTag *cmd.AddNewTag
+ bus.AddHandler(func(ctx context.Context, c *cmd.AddNewTag) error {
+ addNewTag = c
+ return nil
+ })
+
+ server := mock.NewServer()
status, _ := server.
AsUser(mock.JonSnow).
ExecutePost(
@@ -25,17 +39,18 @@ func TestCreateTagHandler_ValidRequests(t *testing.T) {
Expect(status).Equals(http.StatusOK)
- tag, err := services.Tags.GetBySlug("feature-request")
- Expect(err).IsNil()
- Expect(tag.Name).Equals("Feature Request")
- Expect(tag.Slug).Equals("feature-request")
- Expect(tag.Color).Equals("00FF00")
- Expect(tag.IsPublic).IsTrue()
+ Expect(addNewTag.Name).Equals("Feature Request")
+ Expect(addNewTag.Color).Equals("00FF00")
+ Expect(addNewTag.IsPublic).IsTrue()
}
func TestCreateTagHandler_InvalidRequests(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ return app.ErrNotFound
+ })
+
var testCases = []string{
`{ }`,
`{ "name": "" }`,
@@ -46,7 +61,7 @@ func TestCreateTagHandler_InvalidRequests(t *testing.T) {
}
for _, testCase := range testCases {
- server, _ := mock.NewServer()
+ server := mock.NewServer()
status, _ := server.
AsUser(mock.JonSnow).
ExecutePostAsJSON(apiv1.CreateEditTag(), testCase)
@@ -58,8 +73,13 @@ func TestCreateTagHandler_InvalidRequests(t *testing.T) {
func TestCreateTagHandler_AlreadyInUse(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.Tags.Add("Bug", "0000FF", true)
+ tag := &models.Tag{Name: "Bug", Slug: "bug"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ q.Result = tag
+ return nil
+ })
+
+ server := mock.NewServer()
status, _ := server.
AsUser(mock.JonSnow).
@@ -74,7 +94,7 @@ func TestCreateTagHandler_AlreadyInUse(t *testing.T) {
func TestCreateTagHandler_Collaborator(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
status, _ := server.
AsUser(mock.AryaStark).
ExecutePost(
@@ -88,7 +108,11 @@ func TestCreateTagHandler_Collaborator(t *testing.T) {
func TestEditInvalidTagHandler(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
status, _ := server.
AsUser(mock.JonSnow).
AddParam("slug", "bug").
@@ -103,8 +127,19 @@ func TestEditInvalidTagHandler(t *testing.T) {
func TestEditExistingTagHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.Tags.Add("Bug", "0000FF", true)
+ tag := &models.Tag{ID: 5, Name: "Bug", Slug: "bug", Color: "0000FF", IsPublic: true}
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ q.Result = tag
+ return nil
+ })
+
+ var updateTag *cmd.UpdateTag
+ bus.AddHandler(func(ctx context.Context, c *cmd.UpdateTag) error {
+ updateTag = c
+ return nil
+ })
+
+ server := mock.NewServer()
status, _ := server.
AsUser(mock.JonSnow).
@@ -115,20 +150,20 @@ func TestEditExistingTagHandler(t *testing.T) {
)
Expect(status).Equals(http.StatusOK)
- tag, err := services.Tags.GetBySlug("bug")
- Expect(tag).IsNil()
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
-
- tag, err = services.Tags.GetBySlug("feature-request")
- Expect(tag).IsNotNil()
- Expect(err).IsNil()
+ Expect(updateTag.TagID).Equals(5)
+ Expect(updateTag.Name).Equals("Feature Request")
+ Expect(updateTag.Color).Equals("000000")
+ Expect(updateTag.IsPublic).IsTrue()
}
func TestDeleteInvalidTagHandler(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
- status, _ := server.
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ return app.ErrNotFound
+ })
+
+ status, _ := mock.NewServer().
AsUser(mock.JonSnow).
AddParam("slug", "bug").
Execute(apiv1.DeleteTag())
@@ -139,67 +174,93 @@ func TestDeleteInvalidTagHandler(t *testing.T) {
func TestDeleteExistingTagHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.Tags.Add("Bug", "0000FF", true)
+ tag := &models.Tag{ID: 5, Name: "Bug", Slug: "bug", Color: "0000FF", IsPublic: true}
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ q.Result = tag
+ return nil
+ })
- status, _ := server.
+ var deleteTag *cmd.DeleteTag
+ bus.AddHandler(func(ctx context.Context, c *cmd.DeleteTag) error {
+ deleteTag = c
+ return nil
+ })
+
+ status, _ := mock.NewServer().
AsUser(mock.JonSnow).
AddParam("slug", "bug").
Execute(apiv1.DeleteTag())
- tag, err := services.Tags.GetBySlug("bug")
Expect(status).Equals(http.StatusOK)
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(tag).IsNil()
+ Expect(deleteTag.Tag).Equals(tag)
}
func TestDeleteExistingTagHandler_Collaborator(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.Tags.Add("Bug", "0000FF", true)
+ tag := &models.Tag{ID: 5, Name: "Bug", Slug: "bug", Color: "0000FF", IsPublic: true}
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ q.Result = tag
+ return nil
+ })
- status, _ := server.
+ status, _ := mock.NewServer().
AsUser(mock.AryaStark).
AddParam("slug", "bug").
Execute(apiv1.DeleteTag())
- tag, err := services.Tags.GetBySlug("bug")
Expect(status).Equals(http.StatusForbidden)
- Expect(tag).IsNotNil()
- Expect(err).IsNil()
}
func TestAssignTagHandler_Success(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- tag, _ := services.Tags.Add("Bug", "0000FF", true)
- post, _ := services.Posts.Add("Post Title", "Post Description")
-
- status, _ := server.
+ post := &models.Post{ID: 2, Number: 2}
+ tag := &models.Tag{ID: 5, Slug: "bug"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ q.Result = post
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ q.Result = tag
+ return nil
+ })
+
+ var assignTag *cmd.AssignTag
+ bus.AddHandler(func(ctx context.Context, c *cmd.AssignTag) error {
+ assignTag = c
+ return nil
+ })
+
+ status, _ := mock.NewServer().
AsUser(mock.JonSnow).
AddParam("slug", tag.Slug).
AddParam("number", post.Number).
Execute(apiv1.AssignTag())
- tags, err := services.Tags.GetAssigned(post)
Expect(status).Equals(http.StatusOK)
- Expect(err).IsNil()
- Expect(tags[0]).Equals(tag)
+ Expect(assignTag.Post).Equals(post)
+ Expect(assignTag.Tag).Equals(tag)
}
func TestAssignTagHandler_UnknownTag(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ post := &models.Post{ID: 2, Number: 2}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ q.Result = post
+ return nil
+ })
- status, _ := server.
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ return app.ErrNotFound
+ })
+
+ status, _ := mock.NewServer().
AsUser(mock.JonSnow).
AddParam("slug", "bug").
- AddParam("number", 1).
+ AddParam("number", post.Number).
Execute(apiv1.AssignTag())
Expect(status).Equals(http.StatusNotFound)
@@ -214,16 +275,10 @@ func TestAssignOrUnassignTagHandler_Unauthorized(t *testing.T) {
}
for _, handler := range testCases {
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- tag, _ := services.Tags.Add("Bug", "0000FF", true)
- post, _ := services.Posts.Add("Post Title", "Post Description")
-
- status, _ := server.
+ status, _ := mock.NewServer().
AsUser(mock.AryaStark).
- AddParam("slug", tag.Slug).
- AddParam("number", post.Number).
+ AddParam("slug", "feature-request").
+ AddParam("number", "500").
Execute(handler)
Expect(status).Equals(http.StatusForbidden)
@@ -233,33 +288,46 @@ func TestAssignOrUnassignTagHandler_Unauthorized(t *testing.T) {
func TestUnassignTagHandler_Success(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- tag, _ := services.Tags.Add("Bug", "0000FF", true)
- post, _ := services.Posts.Add("Post Title", "Post Description")
- services.Tags.AssignTag(tag, post)
-
- status, _ := server.
+ post := &models.Post{ID: 2, Number: 2}
+ tag := &models.Tag{ID: 5, Slug: "bug"}
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ q.Result = post
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
+ q.Result = tag
+ return nil
+ })
+
+ var unassignTag *cmd.UnassignTag
+ bus.AddHandler(func(ctx context.Context, c *cmd.UnassignTag) error {
+ unassignTag = c
+ return nil
+ })
+
+ status, _ := mock.NewServer().
AsUser(mock.JonSnow).
AddParam("slug", tag.Slug).
AddParam("number", post.Number).
Execute(apiv1.UnassignTag())
- tags, err := services.Tags.GetAssigned(post)
Expect(status).Equals(http.StatusOK)
- Expect(err).IsNil()
- Expect(tags).HasLen(0)
+ Expect(unassignTag.Post).Equals(post)
+ Expect(unassignTag.Tag).Equals(tag)
}
func TestListTagsHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- services.Tags.Add("Bug", "0000FF", true)
- services.Tags.Add("Feature Request", "0000FF", true)
+ tag1 := &models.Tag{ID: 2, Name: "Bug", Slug: "bug", Color: "0000FF", IsPublic: true}
+ tag2 := &models.Tag{ID: 5, Name: "Feature Request", Slug: "feature-request", Color: "0000FF", IsPublic: true}
+ bus.AddHandler(func(ctx context.Context, q *query.GetAllTags) error {
+ q.Result = []*models.Tag{tag1, tag2}
+ return nil
+ })
+
+ server := mock.NewServer()
status, query := server.
AsUser(mock.JonSnow).
diff --git a/app/handlers/apiv1/user.go b/app/handlers/apiv1/user.go
index de0b58987..78abe6ff3 100644
--- a/app/handlers/apiv1/user.go
+++ b/app/handlers/apiv1/user.go
@@ -4,42 +4,53 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/web"
)
// ListUsers returns all registered users
func ListUsers() web.HandlerFunc {
- return func(c web.Context) error {
- users, err := c.Services().Users.GetAll()
- if err != nil {
+ return func(c *web.Context) error {
+ allUsers := &query.GetAllUsers{}
+ if err := bus.Dispatch(c, allUsers); err != nil {
return c.Failure(err)
}
- return c.Ok(users)
+ return c.Ok(allUsers.Result)
}
}
// CreateUser is used to create new users
func CreateUser() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.CreateUser)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- user, err := c.Services().Users.GetByProvider("reference", input.Model.Reference)
+ var user *models.User
+
+ getByReference := &query.GetUserByProvider{Provider: "reference", UID: input.Model.Reference}
+ err := bus.Dispatch(c, getByReference)
+ user = getByReference.Result
+
if err != nil && errors.Cause(err) == app.ErrNotFound {
if input.Model.Email != "" {
- user, err = c.Services().Users.GetByEmail(input.Model.Email)
+ getByEmail := &query.GetUserByEmail{Email: input.Model.Email}
+ err = bus.Dispatch(c, getByEmail)
+ user = getByEmail.Result
}
if err != nil && errors.Cause(err) == app.ErrNotFound {
user = &models.User{
Tenant: c.Tenant(),
Name: input.Model.Name,
Email: input.Model.Email,
- Role: models.RoleVisitor,
+ Role: enum.RoleVisitor,
}
- err = c.Services().Users.Register(user)
+ err = bus.Dispatch(c, &cmd.RegisterUser{User: user})
}
}
@@ -48,9 +59,10 @@ func CreateUser() web.HandlerFunc {
}
if input.Model.Reference != "" && !user.HasProvider("reference") {
- if err := c.Services().Users.RegisterProvider(user.ID, &models.UserProvider{
- Name: "reference",
- UID: input.Model.Reference,
+ if err := bus.Dispatch(c, &cmd.RegisterUserProvider{
+ UserID: user.ID,
+ ProviderName: "reference",
+ ProviderUID: input.Model.Reference,
}); err != nil {
return c.Failure(err)
}
diff --git a/app/handlers/apiv1/user_test.go b/app/handlers/apiv1/user_test.go
index 58bedd332..ccc5bdf5b 100644
--- a/app/handlers/apiv1/user_test.go
+++ b/app/handlers/apiv1/user_test.go
@@ -1,21 +1,34 @@
package apiv1_test
import (
+ "context"
"net/http"
"testing"
+ "github.com/getfider/fider/app"
+
"github.com/getfider/fider/app/handlers/apiv1"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/mock"
)
func TestListUsersHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
+ bus.AddHandler(func(ctx context.Context, q *query.GetAllUsers) error {
+ q.Result = []*models.User{
+ &models.User{ID: 1, Name: "User 1"},
+ &models.User{ID: 2, Name: "User 2"},
+ }
+ return nil
+ })
+
+ server := mock.NewServer()
status, query := server.
AsUser(mock.JonSnow).
@@ -29,9 +42,25 @@ func TestListUsersHandler(t *testing.T) {
func TestCreateUser_ExistingEmail(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
+ server := mock.NewServer()
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error {
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ if q.Email == mock.AryaStark.Email {
+ q.Result = mock.AryaStark
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ var newProvider *cmd.RegisterUserProvider
+ bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUserProvider) error {
+ newProvider = c
+ return nil
+ })
status, query := server.
AsUser(mock.JonSnow).
@@ -45,24 +74,28 @@ func TestCreateUser_ExistingEmail(t *testing.T) {
Expect(status).Equals(http.StatusOK)
id := query.Int32("id")
- user, err := services.Users.GetByID(id)
- Expect(err).IsNil()
- Expect(user.ID).Equals(mock.AryaStark.ID)
- Expect(user.Name).Equals("Arya Stark")
- Expect(user.Email).Equals("[email protected]")
- Expect(user.Tenant).Equals(mock.DemoTenant)
- Expect(user.Role).Equals(models.RoleVisitor)
- Expect(user.Providers).HasLen(1)
- Expect(user.Providers[0].Name).Equals("reference")
- Expect(user.Providers[0].UID).Equals("AA564645")
+ Expect(id).Equals(mock.AryaStark.ID)
+ Expect(newProvider.UserID).Equals(id)
+ Expect(newProvider.ProviderName).Equals("reference")
+ Expect(newProvider.ProviderUID).Equals("AA564645")
}
func TestCreateUser_ExistingEmail_NoReference(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
+ server := mock.NewServer()
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error {
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ if q.Email == mock.AryaStark.Email {
+ q.Result = mock.AryaStark
+ return nil
+ }
+ return app.ErrNotFound
+ })
status, query := server.
AsUser(mock.JonSnow).
@@ -74,22 +107,49 @@ func TestCreateUser_ExistingEmail_NoReference(t *testing.T) {
}`)
Expect(status).Equals(http.StatusOK)
- id := query.Int32("id")
- user, err := services.Users.GetByID(id)
- Expect(err).IsNil()
- Expect(user.ID).Equals(mock.AryaStark.ID)
- Expect(user.Name).Equals("Arya Stark")
- Expect(user.Email).Equals("[email protected]")
- Expect(user.Tenant).Equals(mock.DemoTenant)
- Expect(user.Providers).HasLen(0)
+ Expect(query.Int32("id")).Equals(mock.AryaStark.ID)
}
func TestCreateUser_NewUser(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
+ server := mock.NewServer()
+
+ var newUser *models.User
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error {
+ if newUser != nil {
+ if q.Provider == newUser.Providers[0].Name && q.UID == newUser.Providers[0].UID {
+ q.Result = newUser
+ return nil
+ }
+ }
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
+ if newUser != nil {
+ panic("newUser is already set")
+ }
+
+ c.User.ID = 1
+ newUser = c.User
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUserProvider) error {
+ if c.UserID == newUser.ID {
+ newUser.Providers = append(newUser.Providers, &models.UserProvider{
+ Name: c.ProviderName,
+ UID: c.ProviderUID,
+ })
+ }
+ return nil
+ })
status, query := server.
AsUser(mock.JonSnow).
@@ -103,15 +163,14 @@ func TestCreateUser_NewUser(t *testing.T) {
Expect(status).Equals(http.StatusOK)
userID := query.Int32("id")
- user, err := services.Users.GetByID(userID)
- Expect(err).IsNil()
- Expect(user.ID).Equals(userID)
- Expect(user.Name).Equals("Martin")
- Expect(user.Email).Equals("[email protected]")
- Expect(user.Tenant).Equals(mock.DemoTenant)
- Expect(user.Providers).HasLen(1)
- Expect(user.Providers[0].Name).Equals("reference")
- Expect(user.Providers[0].UID).Equals("89014714")
+ Expect(newUser.ID).Equals(userID)
+ Expect(newUser.Name).Equals("Martin")
+ Expect(newUser.Email).Equals("[email protected]")
+ Expect(newUser.Tenant).Equals(mock.DemoTenant)
+ Expect(newUser.Role).Equals(enum.RoleVisitor)
+ Expect(newUser.Providers).HasLen(1)
+ Expect(newUser.Providers[0].UID).Equals("89014714")
+ Expect(newUser.Providers[0].Name).Equals("reference")
// Try to recreate another user with same reference
status, query = server.
@@ -126,11 +185,4 @@ func TestCreateUser_NewUser(t *testing.T) {
Expect(status).Equals(http.StatusOK)
theOtherUserID := query.Int32("id")
Expect(theOtherUserID).Equals(userID)
- user, err = services.Users.GetByID(theOtherUserID)
- Expect(err).IsNil()
- Expect(user.Name).Equals("Martin")
- Expect(user.Email).Equals("[email protected]")
- Expect(user.Providers).HasLen(1)
- Expect(user.Providers[0].Name).Equals("reference")
- Expect(user.Providers[0].UID).Equals("89014714")
}
diff --git a/app/handlers/billing.go b/app/handlers/billing.go
index 811f4c883..8cbbe043d 100644
--- a/app/handlers/billing.go
+++ b/app/handlers/billing.go
@@ -2,49 +2,54 @@ package handlers
import (
"github.com/getfider/fider/app/actions"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/web"
)
// BillingPage is the billing settings page
func BillingPage() web.HandlerFunc {
- return func(c web.Context) error {
- var err error
+ return func(c *web.Context) error {
if c.Tenant().Billing.StripeCustomerID == "" {
- _, err = c.Services().Billing.CreateCustomer("")
- if err != nil {
- return err
+ if err := bus.Dispatch(c, &cmd.CreateBillingCustomer{}); err != nil {
+ return c.Failure(err)
}
- err = c.Services().Tenants.UpdateBillingSettings(c.Tenant().Billing)
- if err != nil {
- return err
+ if err := bus.Dispatch(c, &cmd.UpdateTenantBillingSettings{
+ Settings: c.Tenant().Billing,
+ }); err != nil {
+ return c.Failure(err)
}
}
- var invoiceDue *models.UpcomingInvoice
+ getUpcomingInvoiceQuery := &query.GetUpcomingInvoice{}
if c.Tenant().Billing.StripeSubscriptionID != "" {
- invoiceDue, err = c.Services().Billing.GetUpcomingInvoice()
+ err := bus.Dispatch(c, getUpcomingInvoiceQuery)
if err != nil {
return c.Failure(err)
}
}
- paymentInfo, err := c.Services().Billing.GetPaymentInfo()
+ paymentInfo := query.GetPaymentInfo{}
+ err := bus.Dispatch(c, paymentInfo)
if err != nil {
return c.Failure(err)
}
- var plans []*models.BillingPlan
- if paymentInfo != nil {
- plans, err = c.Services().Billing.ListPlans(paymentInfo.AddressCountry)
+ listPlansQuery := &query.ListBillingPlans{}
+ if paymentInfo.Result != nil {
+ listPlansQuery.CountryCode = paymentInfo.Result.AddressCountry
+ err = bus.Dispatch(c, listPlansQuery)
if err != nil {
+ println(err.Error())
return c.Failure(err)
}
}
- tenantUserCount, err := c.Services().Users.Count()
- if err != nil {
+ countUsers := &query.CountUsers{}
+ allCountries := &query.GetAllCountries{}
+ if err := bus.Dispatch(c, countUsers); err != nil {
return c.Failure(err)
}
@@ -52,11 +57,11 @@ func BillingPage() web.HandlerFunc {
Title: "Billing · Site Settings",
ChunkName: "Billing.page",
Data: web.Map{
- "invoiceDue": invoiceDue,
- "tenantUserCount": tenantUserCount,
- "plans": plans,
- "paymentInfo": paymentInfo,
- "countries": models.GetAllCountries(),
+ "invoiceDue": getUpcomingInvoiceQuery.Result,
+ "tenantUserCount": countUsers.Result,
+ "plans": listPlansQuery.Result,
+ "paymentInfo": paymentInfo.Result,
+ "countries": allCountries.Result,
},
})
}
@@ -64,14 +69,13 @@ func BillingPage() web.HandlerFunc {
// UpdatePaymentInfo on stripe based on given input
func UpdatePaymentInfo() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.CreateEditBillingPaymentInfo)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := c.Services().Billing.UpdatePaymentInfo(input.Model)
- if err != nil {
+ if err := bus.Dispatch(c, &cmd.UpdatePaymentInfo{Input: input.Model}); err != nil {
return c.Failure(err)
}
@@ -81,52 +85,58 @@ func UpdatePaymentInfo() web.HandlerFunc {
// GetBillingPlans returns a list of plans for given country code
func GetBillingPlans() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
countryCode := c.Param("countryCode")
- plans, err := c.Services().Billing.ListPlans(countryCode)
+ listPlansQuery := &query.ListBillingPlans{CountryCode: countryCode}
+ err := bus.Dispatch(c, listPlansQuery)
if err != nil {
return c.Failure(err)
}
- return c.Ok(plans)
+ return c.Ok(listPlansQuery.Result)
}
}
// BillingSubscribe subscribes current tenant to given plan on stripe
func BillingSubscribe() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
planID := c.Param("planID")
- paymentInfo, err := c.Services().Billing.GetPaymentInfo()
+ paymentInfoQuery := &query.GetPaymentInfo{}
+ err := bus.Dispatch(c, paymentInfoQuery)
if err != nil {
return c.Failure(err)
}
- plan, err := c.Services().Billing.GetPlanByID(paymentInfo.AddressCountry, planID)
+ getPlanByIDQuery := &query.GetBillingPlanByID{
+ PlanID: planID,
+ CountryCode: paymentInfoQuery.Result.AddressCountry,
+ }
+ err = bus.Dispatch(c, getPlanByIDQuery)
if err != nil {
return c.Failure(err)
}
+ plan := getPlanByIDQuery.Result
- userCount, err := c.Services().Users.Count()
+ countUsers := &query.CountUsers{}
+ err = bus.Dispatch(c, countUsers)
if err != nil {
return c.Failure(err)
}
- if plan.MaxUsers > 0 && userCount > plan.MaxUsers {
+ if plan.MaxUsers > 0 && countUsers.Result > plan.MaxUsers {
return c.Unauthorized()
}
- err = c.Services().Billing.Subscribe(plan.ID)
- if err != nil {
+ if err = bus.Dispatch(c, &cmd.CreateBillingSubscription{
+ PlanID: plan.ID,
+ }); err != nil {
return c.Failure(err)
}
- err = c.Services().Tenants.UpdateBillingSettings(c.Tenant().Billing)
- if err != nil {
- return err
- }
- err = c.Services().Tenants.Activate(c.Tenant().ID)
- if err != nil {
- return err
+ updateBilling := &cmd.UpdateTenantBillingSettings{Settings: c.Tenant().Billing}
+ activateTenant := &cmd.ActivateTenant{TenantID: c.Tenant().ID}
+ if err := bus.Dispatch(c, updateBilling, activateTenant); err != nil {
+ return c.Failure(err)
}
return c.Ok(web.Map{})
@@ -135,15 +145,16 @@ func BillingSubscribe() web.HandlerFunc {
// CancelBillingSubscription cancels current subscription from current tenant
func CancelBillingSubscription() web.HandlerFunc {
- return func(c web.Context) error {
- err := c.Services().Billing.CancelSubscription()
+ return func(c *web.Context) error {
+ err := bus.Dispatch(c, &cmd.CancelBillingSubscription{})
if err != nil {
return c.Failure(err)
}
- err = c.Services().Tenants.UpdateBillingSettings(c.Tenant().Billing)
- if err != nil {
- return err
+ if err := bus.Dispatch(c, &cmd.UpdateTenantBillingSettings{
+ Settings: c.Tenant().Billing,
+ }); err != nil {
+ return c.Failure(err)
}
return c.Ok(web.Map{})
diff --git a/app/handlers/common.go b/app/handlers/common.go
index 1e11e63ea..9c175ccc7 100644
--- a/app/handlers/common.go
+++ b/app/handlers/common.go
@@ -7,8 +7,16 @@ import (
"strings"
"time"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+
+ "github.com/getfider/fider/app/models/query"
+
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/dbx"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
@@ -17,8 +25,8 @@ import (
//Health always returns OK
func Health() web.HandlerFunc {
- return func(c web.Context) error {
- err := c.Engine().Database().Ping()
+ return func(c *web.Context) error {
+ err := dbx.Ping()
if err != nil {
return c.Failure(err)
}
@@ -28,7 +36,7 @@ func Health() web.HandlerFunc {
//LegalPage returns a legal page with content from a file
func LegalPage(title, file string) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
bytes, err := ioutil.ReadFile(env.Etc(file))
if err != nil {
return c.NotFound()
@@ -45,13 +53,13 @@ func LegalPage(title, file string) web.HandlerFunc {
//Sitemap returns the sitemap.xml of current site
func Sitemap() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
if c.Tenant().IsPrivate {
return c.NotFound()
}
- posts, err := c.Services().Posts.GetAll()
- if err != nil {
+ allPosts := &query.GetAllPosts{}
+ if err := bus.Dispatch(c, allPosts); err != nil {
return c.Failure(err)
}
@@ -60,7 +68,7 @@ func Sitemap() web.HandlerFunc {
text.WriteString(`<?xml version="1.0" encoding="UTF-8"?>`)
text.WriteString(`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`)
text.WriteString(fmt.Sprintf("<url> <loc>%s</loc> </url>", baseURL))
- for _, post := range posts {
+ for _, post := range allPosts.Result {
text.WriteString(fmt.Sprintf("<url> <loc>%s/posts/%d/%s</loc> </url>", baseURL, post.Number, post.Slug))
}
text.WriteString(`</urlset>`)
@@ -72,7 +80,7 @@ func Sitemap() web.HandlerFunc {
//RobotsTXT return content of robots.txt file
func RobotsTXT() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
bytes, err := ioutil.ReadFile(env.Path("./robots.txt"))
if err != nil {
return c.NotFound()
@@ -85,7 +93,7 @@ func RobotsTXT() web.HandlerFunc {
//Page returns a page without properties
func Page(title, description, chunkName string) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
return c.Page(web.Props{
Title: title,
Description: description,
@@ -96,7 +104,7 @@ func Page(title, description, chunkName string) web.HandlerFunc {
//BrowserNotSupported returns an error page for browser that Fider dosn't support
func BrowserNotSupported() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
return c.Render(http.StatusOK, "browser-not-supported.html", web.Props{
Title: "Browser not supported",
Description: "We don't support this version of your browser",
@@ -112,24 +120,25 @@ type NewLogError struct {
//LogError logs an error coming from the UI
func LogError() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(NewLogError)
err := c.Bind(input)
if err != nil {
return c.Failure(err)
}
- c.Logger().Errorf(input.Message, log.Props{
+ log.Debugf(c, input.Message, dto.Props{
"Data": input.Data,
})
return c.Ok(web.Map{})
}
}
-func validateKey(kind models.EmailVerificationKind, c web.Context) (*models.EmailVerification, error) {
+func validateKey(kind enum.EmailVerificationKind, c *web.Context) (*models.EmailVerification, error) {
key := c.QueryParam("k")
//If key has been used, return NotFound
- result, err := c.Services().Tenants.FindVerificationByKey(kind, key)
+ findByKey := &query.GetVerificationByKey{Kind: kind, Key: key}
+ err := bus.Dispatch(c, findByKey)
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
return nil, c.NotFound()
@@ -138,20 +147,20 @@ func validateKey(kind models.EmailVerificationKind, c web.Context) (*models.Emai
}
//If key has been used, return Gone
- if result.VerifiedAt != nil {
+ if findByKey.Result.VerifiedAt != nil {
return nil, c.Gone()
}
//If key expired, return Gone
- if time.Now().After(result.ExpiresAt) {
- err = c.Services().Tenants.SetKeyAsVerified(key)
+ if time.Now().After(findByKey.Result.ExpiresAt) {
+ err = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: key})
if err != nil {
return nil, c.Failure(err)
}
return nil, c.Gone()
}
- return result, nil
+ return findByKey.Result, nil
}
func between(n, min, max int) int {
diff --git a/app/handlers/common_test.go b/app/handlers/common_test.go
index 37542a736..14bb5d63f 100644
--- a/app/handlers/common_test.go
+++ b/app/handlers/common_test.go
@@ -1,10 +1,15 @@
package handlers_test
import (
+ "context"
"io/ioutil"
"net/http"
"testing"
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+
"github.com/getfider/fider/app/handlers"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/mock"
@@ -13,7 +18,7 @@ import (
func TestHealthHandler(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, _ := server.
Execute(handlers.Health())
@@ -23,7 +28,7 @@ func TestHealthHandler(t *testing.T) {
func TestPageHandler(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, _ := server.
Execute(handlers.Page("The Title", "The Description", "TheChunk.Page"))
@@ -33,7 +38,7 @@ func TestPageHandler(t *testing.T) {
func TestLegalPageHandler(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, _ := server.
Execute(handlers.LegalPage("Terms of Service", "terms.md"))
@@ -43,7 +48,7 @@ func TestLegalPageHandler(t *testing.T) {
func TestLegalPageHandler_Invalid(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, _ := server.
Execute(handlers.LegalPage("Some Page", "somepage.md"))
@@ -53,7 +58,7 @@ func TestLegalPageHandler_Invalid(t *testing.T) {
func TestRobotsTXT(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, response := server.
WithURL("https://demo.test.fider.io/robots.txt").
Execute(handlers.RobotsTXT())
@@ -70,7 +75,12 @@ Sitemap: https://demo.test.fider.io/sitemap.xml`)
func TestSitemap(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.GetAllPosts) error {
+ q.Result = []*models.Post{}
+ return nil
+ })
+
+ server := mock.NewServer()
code, response := server.
OnTenant(mock.DemoTenant).
WithURL("http://demo.test.fider.io:3000/sitemap.xml").
@@ -84,11 +94,15 @@ func TestSitemap(t *testing.T) {
func TestSitemap_WithPosts(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.Posts.SetCurrentUser(mock.AryaStark)
- services.Posts.Add("My new idea 1", "")
- services.Posts.SetCurrentUser(mock.AryaStark)
- services.Posts.Add("The other idea", "")
+ bus.AddHandler(func(ctx context.Context, q *query.GetAllPosts) error {
+ q.Result = []*models.Post{
+ &models.Post{Number: 1, Slug: "my-new-idea-1", Title: "My new idea 1"},
+ &models.Post{Number: 2, Slug: "the-other-idea", Title: "The other idea"},
+ }
+ return nil
+ })
+
+ server := mock.NewServer()
code, response := server.
OnTenant(mock.DemoTenant).
@@ -103,11 +117,7 @@ func TestSitemap_WithPosts(t *testing.T) {
func TestSitemap_PrivateTenant_WithPosts(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.Posts.SetCurrentUser(mock.AryaStark)
- services.Posts.Add("My new idea 1", "")
- services.Posts.SetCurrentUser(mock.AryaStark)
- services.Posts.Add("The other idea", "")
+ server := mock.NewServer()
mock.DemoTenant.IsPrivate = true
diff --git a/app/handlers/images.go b/app/handlers/images.go
index 3737779b6..3f57547a8 100644
--- a/app/handlers/images.go
+++ b/app/handlers/images.go
@@ -10,6 +10,11 @@ import (
"strings"
"time"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/crypto"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/log"
@@ -20,7 +25,7 @@ import (
//LetterAvatar returns a letter gravatar picture based on given name
func LetterAvatar() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
id := c.Param("id")
name := c.Param("name")
if name == "" {
@@ -52,7 +57,7 @@ func LetterAvatar() web.HandlerFunc {
//Gravatar returns a gravatar picture of fallsback to letter avatar based on name
func Gravatar() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
id, err := c.ParamAsInt("id")
if err != nil {
return c.NotFound()
@@ -66,35 +71,35 @@ func Gravatar() web.HandlerFunc {
size = between(size, 50, 200)
if err == nil && id > 0 {
- user, err := c.Services().Users.GetByID(id)
- if err == nil && user.Tenant.ID == c.Tenant().ID {
- if user.Email != "" {
- url := fmt.Sprintf("https://www.gravatar.com/avatar/%s?s=%d&d=404", crypto.MD5(strings.ToLower(user.Email)), size)
+ userByID := &query.GetUserByID{UserID: id}
+ err := bus.Dispatch(c, userByID)
+ if err == nil && userByID.Result.Tenant.ID == c.Tenant().ID {
+ if userByID.Result.Email != "" {
+ url := fmt.Sprintf("https://www.gravatar.com/avatar/%s?s=%d&d=404", crypto.MD5(strings.ToLower(userByID.Result.Email)), size)
cacheKey := fmt.Sprintf("gravatar:%s", url)
//If gravatar was found in cache
if image, found := c.Engine().Cache().Get(cacheKey); found {
- c.Logger().Debugf("Gravatar found in cache: @{GravatarURL}", log.Props{
+ log.Debugf(c, "Gravatar found in cache: @{GravatarURL}", dto.Props{
"GravatarURL": cacheKey,
})
imageInBytes := image.([]byte)
return c.Image(http.DetectContentType(imageInBytes), imageInBytes)
}
- c.Logger().Debugf("Requesting gravatar: @{GravatarURL}", log.Props{
+ log.Debugf(c, "Requesting gravatar: @{GravatarURL}", dto.Props{
"GravatarURL": url,
})
- resp, err := http.Get(url)
- if err == nil {
- defer resp.Body.Close()
-
- if resp.StatusCode == http.StatusOK {
- bytes, err := ioutil.ReadAll(resp.Body)
- if err == nil {
- c.Engine().Cache().Set(cacheKey, bytes, 24*time.Hour)
- return c.Image(http.DetectContentType(bytes), bytes)
- }
- }
+
+ req := &cmd.HTTPRequest{
+ URL: url,
+ Method: "GET",
+ }
+ err := bus.Dispatch(c, req)
+ if err == nil && req.ResponseStatusCode == http.StatusOK {
+ bytes := req.ResponseBody
+ c.Engine().Cache().Set(cacheKey, bytes, 24*time.Hour)
+ return c.Image(http.DetectContentType(bytes), bytes)
}
}
}
@@ -106,7 +111,7 @@ func Gravatar() web.HandlerFunc {
//Favicon returns the Fider favicon by given size
func Favicon() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
var (
bytes []byte
err error
@@ -115,12 +120,13 @@ func Favicon() web.HandlerFunc {
bkey := c.Param("bkey")
if bkey != "" {
- logo, err := c.Services().Blobs.Get(bkey)
+ q := &query.GetBlobByKey{Key: bkey}
+ err := bus.Dispatch(c, q)
if err != nil {
return c.Failure(err)
}
- bytes = logo.Object
- contentType = logo.ContentType
+ bytes = q.Result.Content
+ contentType = q.Result.ContentType
} else {
bytes, err = ioutil.ReadFile(env.Path("favicon.png"))
contentType = "image/png"
@@ -157,7 +163,7 @@ func Favicon() web.HandlerFunc {
//ViewUploadedImage returns any uploaded image by given ID and size
func ViewUploadedImage() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
bkey := c.Param("bkey")
size, err := c.QueryParamAsInt("size")
@@ -167,12 +173,13 @@ func ViewUploadedImage() web.HandlerFunc {
size = between(size, 0, 2000)
- logo, err := c.Services().Blobs.Get(bkey)
+ q := &query.GetBlobByKey{Key: bkey}
+ err = bus.Dispatch(c, q)
if err != nil {
return c.Failure(err)
}
- bytes := logo.Object
+ bytes := q.Result.Content
if size > 0 {
bytes, err = imagic.Apply(bytes, imagic.Resize(size))
if err != nil {
@@ -180,6 +187,6 @@ func ViewUploadedImage() web.HandlerFunc {
}
}
- return c.Image(logo.ContentType, bytes)
+ return c.Image(q.Result.ContentType, bytes)
}
}
diff --git a/app/handlers/images_test.go b/app/handlers/images_test.go
index 2be3a665a..e90b74b5a 100644
--- a/app/handlers/images_test.go
+++ b/app/handlers/images_test.go
@@ -1,10 +1,16 @@
package handlers_test
import (
+ "context"
"io/ioutil"
"net/http"
"testing"
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/services/httpclient"
+
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/mock"
@@ -14,14 +20,25 @@ import (
func TestGravatarHandler(t *testing.T) {
RegisterT(t)
+ bus.Init(httpclient.Service{})
+
+ server := mock.NewServer()
- server, services := mock.NewServer()
user := &models.User{
+ ID: 3,
Name: "Darth Vader",
- Email: "[email protected]",
+ Email: "[email protected]",
Tenant: mock.DemoTenant,
}
- services.Users.Register(user)
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ if q.UserID == user.ID {
+ q.Result = user
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
code, response := server.
WithURL("https://demo.test.fider.io/?size=50").
OnTenant(mock.DemoTenant).
@@ -36,14 +53,25 @@ func TestGravatarHandler(t *testing.T) {
func TestGravatarNotFound_LetterAvatarHandler(t *testing.T) {
RegisterT(t)
+ bus.Init(httpclient.Service{})
+
+ server := mock.NewServer()
- server, services := mock.NewServer()
user := &models.User{
+ ID: 3,
Name: "Darth Vader",
Tenant: mock.DemoTenant,
}
- services.Users.Register(user)
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ if q.UserID == user.ID {
+ q.Result = user
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
code, response := server.
OnTenant(mock.DemoTenant).
WithURL("https://demo.test.fider.io/?size=50").
@@ -59,8 +87,9 @@ func TestGravatarNotFound_LetterAvatarHandler(t *testing.T) {
func TestUnknownUser_LetterAvatarHandler(t *testing.T) {
RegisterT(t)
+ bus.Init(httpclient.Service{})
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, response := server.
OnTenant(mock.DemoTenant).
WithURL("https://demo.test.fider.io/?size=50").
diff --git a/app/handlers/notification.go b/app/handlers/notification.go
index 80aaf2bc5..ce3bb0122 100644
--- a/app/handlers/notification.go
+++ b/app/handlers/notification.go
@@ -1,28 +1,31 @@
package handlers
import (
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/web"
)
// TotalUnreadNotifications returns the total number of unread notifications
func TotalUnreadNotifications() web.HandlerFunc {
- return func(c web.Context) error {
- total, err := c.Services().Notifications.TotalUnread()
- if err != nil {
+ return func(c *web.Context) error {
+ q := &query.CountUnreadNotifications{}
+ if err := bus.Dispatch(c, q); err != nil {
return c.Failure(err)
}
return c.Ok(web.Map{
- "total": total,
+ "total": q.Result,
})
}
}
// Notifications is the home for unread and recent notifications
func Notifications() web.HandlerFunc {
- return func(c web.Context) error {
- notifications, err := c.Services().Notifications.GetActiveNotifications()
- if err != nil {
+ return func(c *web.Context) error {
+ q := &query.GetActiveNotifications{}
+ if err := bus.Dispatch(c, q); err != nil {
return c.Failure(err)
}
@@ -30,7 +33,7 @@ func Notifications() web.HandlerFunc {
Title: "Notifications",
ChunkName: "MyNotifications.page",
Data: web.Map{
- "notifications": notifications,
+ "notifications": q.Result,
},
})
}
@@ -38,29 +41,30 @@ func Notifications() web.HandlerFunc {
// ReadNotification marks it as read and redirect to its content
func ReadNotification() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
id, err := c.ParamAsInt("id")
if err != nil {
return c.Failure(err)
}
- notification, err := c.Services().Notifications.GetNotification(id)
- if err != nil {
+ q := &query.GetNotificationByID{ID: id}
+ if err := bus.Dispatch(c, q); err != nil {
return c.Failure(err)
}
- if err = c.Services().Notifications.MarkAsRead(notification.ID); err != nil {
+ if err = bus.Dispatch(c, &cmd.MarkNotificationAsRead{ID: q.Result.ID}); err != nil {
return c.Failure(err)
}
- return c.Redirect(c.BaseURL() + notification.Link)
+ return c.Redirect(c.BaseURL() + q.Result.Link)
}
}
// ReadAllNotifications marks all unread notifications as read
func ReadAllNotifications() web.HandlerFunc {
- return func(c web.Context) error {
- if err := c.Services().Notifications.MarkAllAsRead(); err != nil {
+ return func(c *web.Context) error {
+
+ if err := bus.Dispatch(c, &cmd.MarkAllNotificationsAsRead{}); err != nil {
return c.Failure(err)
}
diff --git a/app/handlers/notification_test.go b/app/handlers/notification_test.go
index d9c806a89..9dfed435f 100644
--- a/app/handlers/notification_test.go
+++ b/app/handlers/notification_test.go
@@ -1,9 +1,16 @@
package handlers_test
import (
+ "context"
"net/http"
"testing"
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+
"github.com/getfider/fider/app/handlers"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/mock"
@@ -11,27 +18,27 @@ import (
func TestTotalUnreadNotificationsHandler(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.CountUnreadNotifications) error {
+ q.Result = 5
+ return nil
+ })
- server, services := mock.NewServer()
- services.SetCurrentUser(mock.AryaStark)
- services.Notifications.Insert(mock.JonSnow, "Title", "http://example.com", 1)
+ server := mock.NewServer()
code, query := server.
- OnTenant(mock.DemoTenant).
- AsUser(mock.JonSnow).
ExecuteAsJSON(handlers.TotalUnreadNotifications())
Expect(code).Equals(http.StatusOK)
- Expect(query.Int32("total")).Equals(1)
+ Expect(query.Int32("total")).Equals(5)
}
func TestNotificationsHandler(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveNotifications) error {
+ return nil
+ })
- server, services := mock.NewServer()
- services.SetCurrentUser(mock.AryaStark)
- services.Notifications.Insert(mock.JonSnow, "Title", "http://example.com", 1)
- services.Notifications.Insert(mock.JonSnow, "Title 2", "http://example.com", 1)
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
@@ -44,17 +51,36 @@ func TestNotificationsHandler(t *testing.T) {
func TestReadNotificationHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentUser(mock.JonSnow)
- services.SetCurrentUser(mock.AryaStark)
- not1, _ := services.Notifications.Insert(mock.JonSnow, "Title", "/abc", 1)
- not2, _ := services.Notifications.Insert(mock.JonSnow, "Title 2", "/def", 1)
+ not1 := &models.Notification{ID: 1, Link: "/abc"}
+ not2 := &models.Notification{ID: 2, Link: "/def"}
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetNotificationByID) error {
+ if q.ID == 1 {
+ q.Result = not1
+ } else if q.ID == 2 {
+ q.Result = not2
+ } else {
+ q.Result = nil
+ }
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.MarkNotificationAsRead) error {
+ if c.ID == 1 {
+ not1.Read = true
+ } else if c.ID == 2 {
+ not2.Read = true
+ }
+ return nil
+ })
+
+ server := mock.NewServer()
code, resp := server.
OnTenant(mock.DemoTenant).
WithURL("http://example.com").
AsUser(mock.JonSnow).
- AddParam("id", not2.ID).
+ AddParam("id", 2).
Execute(handlers.ReadNotification())
Expect(code).Equals(http.StatusTemporaryRedirect)
@@ -66,10 +92,13 @@ func TestReadNotificationHandler(t *testing.T) {
func TestReadAllNotificationsHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentUser(mock.AryaStark)
- not1, _ := services.Notifications.Insert(mock.JonSnow, "Title", "/abc", 1)
- not2, _ := services.Notifications.Insert(mock.JonSnow, "Title 2", "/def", 1)
+ called := false
+ bus.AddHandler(func(ctx context.Context, c *cmd.MarkAllNotificationsAsRead) error {
+ called = true
+ return nil
+ })
+
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
@@ -77,6 +106,5 @@ func TestReadAllNotificationsHandler(t *testing.T) {
Execute(handlers.ReadAllNotifications())
Expect(code).Equals(http.StatusOK)
- Expect(not1.Read).IsTrue()
- Expect(not2.Read).IsTrue()
+ Expect(called).IsTrue()
}
diff --git a/app/handlers/oauth.go b/app/handlers/oauth.go
index 359a14308..e5ab9c20e 100644
--- a/app/handlers/oauth.go
+++ b/app/handlers/oauth.go
@@ -6,17 +6,24 @@ import (
"strings"
"time"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/jwt"
+ "github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/web"
- "github.com/getfider/fider/app/pkg/web/util"
+ webutil "github.com/getfider/fider/app/pkg/web/util"
)
// OAuthEcho exchanges OAuth Code for a user profile and return directly to the UI, without storing it
func OAuthEcho() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
provider := c.Param("provider")
code := c.QueryParam("code")
@@ -26,11 +33,12 @@ func OAuthEcho() web.HandlerFunc {
identifier := c.QueryParam("identifier")
if identifier == "" || identifier != c.SessionID() {
- c.Logger().Warn("OAuth identifier doesn't match with user session ID. Aborting sign in process.")
+ log.Warn(c, "OAuth identifier doesn't match with user session ID. Aborting sign in process.")
return c.Redirect("/")
}
- body, err := c.Services().OAuth.GetRawProfile(provider, code)
+ rawProfile := &query.GetOAuthRawProfile{Provider: provider, Code: code}
+ err := bus.Dispatch(c, rawProfile)
if err != nil {
return c.Page(web.Props{
Title: "OAuth Test Page",
@@ -41,14 +49,15 @@ func OAuthEcho() web.HandlerFunc {
})
}
- profile, _ := c.Services().OAuth.ParseRawProfile(provider, body)
+ parseRawProfile := &cmd.ParseOAuthRawProfile{Provider: provider, Body: rawProfile.Result}
+ _ = bus.Dispatch(c, parseRawProfile)
return c.Page(web.Props{
Title: "OAuth Test Page",
ChunkName: "OAuthEcho.page",
Data: web.Map{
- "body": body,
- "profile": profile,
+ "body": rawProfile.Result,
+ "profile": parseRawProfile.Result,
},
})
}
@@ -58,7 +67,7 @@ func OAuthEcho() web.HandlerFunc {
// The user profile is then used to either get an existing user on Fider or creating a new one
// Once Fider user is retrieved/created, an authentication cookie is store in user's browser
func OAuthToken() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
provider := c.Param("provider")
redirectURL, _ := url.ParseRequestURI(c.QueryParam("redirect"))
redirectURL.ResolveReference(c.Request.URL)
@@ -70,20 +79,25 @@ func OAuthToken() web.HandlerFunc {
identifier := c.QueryParam("identifier")
if identifier == "" || identifier != c.SessionID() {
- c.Logger().Warn("OAuth identifier doesn't match with user session ID. Aborting sign in process.")
+ log.Warn(c, "OAuth identifier doesn't match with user session ID. Aborting sign in process.")
return c.Redirect(redirectURL.String())
}
- oauthUser, err := c.Services().OAuth.GetProfile(provider, code)
- if err != nil {
+ oauthUser := &query.GetOAuthProfile{Provider: provider, Code: code}
+ if err := bus.Dispatch(c, oauthUser); err != nil {
return c.Failure(err)
}
- users := c.Services().Users
+ var user *models.User
- user, err := users.GetByProvider(provider, oauthUser.ID)
- if errors.Cause(err) == app.ErrNotFound && oauthUser.Email != "" {
- user, err = users.GetByEmail(oauthUser.Email)
+ userByProvider := &query.GetUserByProvider{Provider: provider, UID: oauthUser.Result.ID}
+ err := bus.Dispatch(c, userByProvider)
+ user = userByProvider.Result
+
+ if errors.Cause(err) == app.ErrNotFound && oauthUser.Result.Email != "" {
+ userByEmail := &query.GetUserByEmail{Email: oauthUser.Result.Email}
+ err = bus.Dispatch(c, userByEmail)
+ user = userByEmail.Result
}
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
@@ -92,31 +106,30 @@ func OAuthToken() web.HandlerFunc {
}
user = &models.User{
- Name: oauthUser.Name,
+ Name: oauthUser.Result.Name,
Tenant: c.Tenant(),
- Email: oauthUser.Email,
- Role: models.RoleVisitor,
+ Email: oauthUser.Result.Email,
+ Role: enum.RoleVisitor,
Providers: []*models.UserProvider{
&models.UserProvider{
- UID: oauthUser.ID,
+ UID: oauthUser.Result.ID,
Name: provider,
},
},
}
- err = users.Register(user)
- if err != nil {
+ if err = bus.Dispatch(c, &cmd.RegisterUser{User: user}); err != nil {
return c.Failure(err)
}
} else {
return c.Failure(err)
}
} else if !user.HasProvider(provider) {
- err = users.RegisterProvider(user.ID, &models.UserProvider{
- UID: oauthUser.ID,
- Name: provider,
- })
- if err != nil {
+ if err = bus.Dispatch(c, &cmd.RegisterUserProvider{
+ UserID: user.ID,
+ ProviderName: provider,
+ ProviderUID: oauthUser.Result.ID,
+ }); err != nil {
return c.Failure(err)
}
}
@@ -132,7 +145,7 @@ func OAuthToken() web.HandlerFunc {
// If the request is for a sign in, we redirect the user to the tenant address
// If the request is for a sign up, we exchange the OAuth code and get the user profile
func OAuthCallback() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
c.Response.Header().Add("X-Robots-Tag", "noindex")
provider := c.Param("provider")
@@ -160,16 +173,16 @@ func OAuthCallback() web.HandlerFunc {
//Sign up process
if redirectURL.Path == "/signup" {
- oauthUser, err := c.Services().OAuth.GetProfile(provider, code)
- if err != nil {
+ oauthUser := &query.GetOAuthProfile{Provider: provider, Code: code}
+ if err := bus.Dispatch(c, oauthUser); err != nil {
return c.Failure(err)
}
claims := jwt.OAuthClaims{
- OAuthID: oauthUser.ID,
+ OAuthID: oauthUser.Result.ID,
OAuthProvider: provider,
- OAuthName: oauthUser.Name,
- OAuthEmail: oauthUser.Email,
+ OAuthName: oauthUser.Result.Name,
+ OAuthEmail: oauthUser.Result.Email,
Metadata: jwt.Metadata{
ExpiresAt: time.Now().Add(10 * time.Minute).Unix(),
},
@@ -200,7 +213,7 @@ func OAuthCallback() web.HandlerFunc {
// SignInByOAuth is responsible for redirecting the user to the OAuth authorization URL for given provider
// A cookie is stored in user's browser with a random identifier that is later used to verify the authenticity of the request
func SignInByOAuth() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
c.Response.Header().Add("X-Robots-Tag", "noindex")
provider := c.Param("provider")
@@ -217,10 +230,14 @@ func SignInByOAuth() web.HandlerFunc {
return c.Redirect(redirect)
}
- authURL, err := c.Services().OAuth.GetAuthURL(provider, redirect, c.SessionID())
- if err != nil {
+ authURL := &query.GetOAuthAuthorizationURL{
+ Provider: provider,
+ Redirect: redirect,
+ Identifier: c.SessionID(),
+ }
+ if err := bus.Dispatch(c, authURL); err != nil {
return c.Failure(err)
}
- return c.Redirect(authURL)
+ return c.Redirect(authURL.Result)
}
}
diff --git a/app/handlers/oauth_test.go b/app/handlers/oauth_test.go
index a6e5ed447..75533a587 100644
--- a/app/handlers/oauth_test.go
+++ b/app/handlers/oauth_test.go
@@ -1,27 +1,34 @@
package handlers_test
import (
+ "context"
"testing"
+ "github.com/getfider/fider/app/models/dto"
+
+ "github.com/getfider/fider/app/services/oauth"
+
+ "github.com/getfider/fider/app"
+
"net/http"
"net/url"
- "github.com/getfider/fider/app"
"github.com/getfider/fider/app/handlers"
"github.com/getfider/fider/app/middlewares"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/mock"
- "github.com/getfider/fider/app/pkg/oauth"
"github.com/getfider/fider/app/pkg/web"
)
func TestSignOutHandler(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, response := server.
WithURL("http://demo.test.fider.io/signout?redirect=/").
AddCookie(web.CookieAuthName, "some-value").
@@ -35,26 +42,28 @@ func TestSignOutHandler(t *testing.T) {
func TestSignInByOAuthHandler(t *testing.T) {
RegisterT(t)
+ bus.Init(&oauth.Service{})
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, response := server.
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
WithURL("http://avengers.test.fider.io/oauth/facebook").
Use(middlewares.Session()).
Execute(handlers.SignInByOAuth())
Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io/oauth/token?provider=facebook&redirect=http://avengers.test.fider.io|MY_SESSION_ID")
+ Expect(response.Header().Get("Location")).Equals("https://www.facebook.com/v3.1/dialog/oauth?client_id=FB_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%2Foauth%2Ffacebook%2Fcallback&response_type=code&scope=public_profile+email&state=http%3A%2F%2Favengers.test.fider.io%7CMY_SESSION_ID")
}
func TestSignInByOAuthHandler_AuthenticatedUser(t *testing.T) {
RegisterT(t)
+ bus.Init(&oauth.Service{})
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, response := server.
AsUser(mock.JonSnow).
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
WithURL("http://avengers.test.fider.io/oauth/facebook?redirect=http://avengers.test.fider.io").
Use(middlewares.Session()).
@@ -66,27 +75,28 @@ func TestSignInByOAuthHandler_AuthenticatedUser(t *testing.T) {
func TestSignInByOAuthHandler_AuthenticatedUser_UsingEcho(t *testing.T) {
RegisterT(t)
+ bus.Init(&oauth.Service{})
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, response := server.
AsUser(mock.JonSnow).
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
WithURL("http://avengers.test.fider.io/oauth/facebook?redirect=http://avengers.test.fider.io/oauth/facebook/echo").
Use(middlewares.Session()).
Execute(handlers.SignInByOAuth())
Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io/oauth/token?provider=facebook&redirect=http://avengers.test.fider.io/oauth/facebook/echo|MY_SESSION_ID")
+ Expect(response.Header().Get("Location")).Equals("https://www.facebook.com/v3.1/dialog/oauth?client_id=FB_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%2Foauth%2Ffacebook%2Fcallback&response_type=code&scope=public_profile+email&state=http%3A%2F%2Favengers.test.fider.io%2Foauth%2Ffacebook%2Fecho%7CMY_SESSION_ID")
}
func TestCallbackHandler_InvalidState(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, _ := server.
WithURL("http://login.test.fider.io/oauth/callback?state=abc").
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
Execute(handlers.OAuthCallback())
Expect(code).Equals(http.StatusInternalServerError)
@@ -95,11 +105,11 @@ func TestCallbackHandler_InvalidState(t *testing.T) {
func TestCallbackHandler_InvalidCode(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, response := server.
WithURL("http://login.test.fider.io/oauth/callback?state=http://avengers.test.fider.io").
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
Execute(handlers.OAuthCallback())
Expect(code).Equals(http.StatusTemporaryRedirect)
@@ -109,10 +119,10 @@ func TestCallbackHandler_InvalidCode(t *testing.T) {
func TestCallbackHandler_SignIn(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, response := server.
WithURL("http://login.test.fider.io/oauth/callback?state=http://avengers.test.fider.io|888&code=123").
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
Execute(handlers.OAuthCallback())
Expect(code).Equals(http.StatusTemporaryRedirect)
@@ -121,11 +131,11 @@ func TestCallbackHandler_SignIn(t *testing.T) {
func TestCallbackHandler_SignIn_WithPath(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, response := server.
WithURL("http://login.test.fider.io/oauth/callback?state=http://avengers.test.fider.io/some-page|888&code=123").
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
Execute(handlers.OAuthCallback())
Expect(code).Equals(http.StatusTemporaryRedirect)
@@ -135,10 +145,24 @@ func TestCallbackHandler_SignIn_WithPath(t *testing.T) {
func TestCallbackHandler_SignUp(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ oauthUser := &dto.OAuthUserProfile{
+ ID: "FB123",
+ Name: "Jon Snow",
+ Email: "[email protected]",
+ }
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetOAuthProfile) error {
+ if q.Provider == app.FacebookProvider && q.Code == "123" {
+ q.Result = oauthUser
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
code, response := server.
WithURL("http://login.test.fider.io/oauth/callback?state=http://demo.test.fider.io/signup&code=123").
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
Execute(handlers.OAuthCallback())
Expect(code).Equals(http.StatusTemporaryRedirect)
@@ -148,21 +172,43 @@ func TestCallbackHandler_SignUp(t *testing.T) {
Expect(location.Path).Equals("/signup")
ExpectOAuthToken(location.Query().Get("token"), &jwt.OAuthClaims{
OAuthProvider: "facebook",
- OAuthID: "FB123",
- OAuthName: "Jon Snow",
- OAuthEmail: "[email protected]",
+ OAuthID: oauthUser.ID,
+ OAuthName: oauthUser.Name,
+ OAuthEmail: oauthUser.Email,
})
}
func TestOAuthTokenHandler_ExistingUserAndProvider(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ oauthUser := &dto.OAuthUserProfile{
+ ID: "FB123",
+ Name: "Jon Snow",
+ Email: "[email protected]",
+ }
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetOAuthProfile) error {
+ if q.Provider == app.FacebookProvider && q.Code == "123" {
+ q.Result = oauthUser
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error {
+ if q.Provider == app.FacebookProvider && q.UID == oauthUser.ID {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
code, response := server.
WithURL("http://demo.test.fider.io/oauth/facebook/token?code=123&identifier=MY_SESSION_ID&redirect=/hello").
OnTenant(mock.DemoTenant).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
Use(middlewares.Session()).
Execute(handlers.OAuthToken())
@@ -174,63 +220,93 @@ func TestOAuthTokenHandler_ExistingUserAndProvider(t *testing.T) {
func TestOAuthTokenHandler_NewUser(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ var registeredUser *models.User
+ bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
+ registeredUser = c.User
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error {
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetOAuthProfile) error {
+ if q.Provider == app.FacebookProvider && q.Code == "456" {
+ q.Result = &dto.OAuthUserProfile{
+ ID: "FB456",
+ Name: "Some Facebook Guy",
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
code, response := server.
WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456&identifier=MY_SESSION_ID&redirect=/hello").
OnTenant(mock.DemoTenant).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
Use(middlewares.Session()).
Execute(handlers.OAuthToken())
Expect(code).Equals(http.StatusTemporaryRedirect)
Expect(response.Header().Get("Location")).Equals("/hello")
- user, err := services.Users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.Name).Equals("Some Facebook Guy")
+ Expect(registeredUser.Name).Equals("Some Facebook Guy")
- ExpectFiderAuthCookie(response, user)
+ ExpectFiderAuthCookie(response, registeredUser)
}
func TestOAuthTokenHandler_NewUserWithoutEmail(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.Users.Register(&models.User{
- Name: "Some Guy",
- Email: "",
- Tenant: mock.DemoTenant,
- Providers: []*models.UserProvider{
- &models.UserProvider{UID: "GO999", Name: oauth.GoogleProvider},
- },
+ server := mock.NewServer()
+ var newUser *models.User
+ bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
+ c.User.ID = 1
+ newUser = c.User
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error {
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetOAuthProfile) error {
+ if q.Provider == app.FacebookProvider && q.Code == "798" {
+ q.Result = &dto.OAuthUserProfile{
+ ID: "FB798",
+ Name: "Mark",
+ Email: "",
+ }
+ return nil
+ }
+ return app.ErrNotFound
})
code, response := server.
WithURL("http://demo.test.fider.io/oauth/facebook/token?code=798&identifier=MY_SESSION_ID&redirect=/").
OnTenant(mock.DemoTenant).
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
Use(middlewares.Session()).
Execute(handlers.OAuthToken())
- user, err := services.Users.GetByID(3)
- Expect(err).IsNil()
- Expect(user.ID).Equals(3)
- Expect(user.Name).Equals("Some Guy")
- Expect(user.Providers).HasLen(1)
-
- user, err = services.Users.GetByID(4)
- Expect(err).IsNil()
- Expect(user.ID).Equals(4)
- Expect(user.Name).Equals("Mark")
- Expect(user.Providers).HasLen(1)
+ Expect(newUser.ID).Equals(1)
+ Expect(newUser.Name).Equals("Mark")
+ Expect(newUser.Providers).HasLen(1)
Expect(code).Equals(http.StatusTemporaryRedirect)
Expect(response.Header().Get("Location")).Equals("/")
ExpectFiderAuthCookie(response, &models.User{
- ID: 4,
+ ID: 1,
Name: "Mark",
})
}
@@ -238,53 +314,101 @@ func TestOAuthTokenHandler_NewUserWithoutEmail(t *testing.T) {
func TestOAuthTokenHandler_ExistingUser_WithoutEmail(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.Users.Register(&models.User{
+ user := &models.User{
+ ID: 3,
Name: "Some Facebook Guy",
Email: "",
Tenant: mock.DemoTenant,
Providers: []*models.UserProvider{
- &models.UserProvider{UID: "FB456", Name: oauth.FacebookProvider},
+ &models.UserProvider{UID: "FB456", Name: app.FacebookProvider},
},
+ }
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetOAuthProfile) error {
+ if q.Provider == app.FacebookProvider && q.Code == "456" {
+ q.Result = &dto.OAuthUserProfile{
+ ID: "FB456",
+ Name: "Some Facebook Guy",
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error {
+ if q.Provider == "facebook" && q.UID == "FB456" {
+ q.Result = user
+ return nil
+ }
+ return app.ErrNotFound
})
code, response := server.
WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456&identifier=MY_SESSION_ID&redirect=/").
OnTenant(mock.DemoTenant).
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
Use(middlewares.Session()).
Execute(handlers.OAuthToken())
Expect(code).Equals(http.StatusTemporaryRedirect)
- _, err := services.Users.GetByID(4)
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
-
Expect(response.Header().Get("Location")).Equals("/")
ExpectFiderAuthCookie(response, &models.User{
- ID: 3,
- Name: "Some Facebook Guy",
+ ID: 3,
+ Name: "Some Facebook Guy",
+ Email: "",
})
}
func TestOAuthTokenHandler_ExistingUser_NewProvider(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ var newProvider *models.UserProvider
+ bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUserProvider) error {
+ newProvider = &models.UserProvider{
+ Name: c.ProviderName,
+ UID: c.ProviderUID,
+ }
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetOAuthProfile) error {
+ if q.Provider == app.GoogleProvider && q.Code == "123" {
+ q.Result = &dto.OAuthUserProfile{
+ ID: "GO123",
+ Name: "Jon Snow",
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error {
+ if q.Provider == app.GoogleProvider && q.UID == "GO123" {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=123&identifier=MY_SESSION_ID&redirect=/").
+ WithURL("http://demo.test.fider.io/oauth/google/token?code=123&identifier=MY_SESSION_ID&redirect=/").
OnTenant(mock.DemoTenant).
- AddParam("provider", oauth.GoogleProvider).
+ AddParam("provider", app.GoogleProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
Use(middlewares.Session()).
Execute(handlers.OAuthToken())
Expect(code).Equals(http.StatusTemporaryRedirect)
- user, err := services.Users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.Providers).HasLen(2)
+ Expect(newProvider.Name).Equals("google")
+ Expect(newProvider.UID).Equals("GO123")
Expect(response.Header().Get("Location")).Equals("/")
ExpectFiderAuthCookie(response, mock.JonSnow)
@@ -292,21 +416,38 @@ func TestOAuthTokenHandler_ExistingUser_NewProvider(t *testing.T) {
func TestOAuthTokenHandler_NewUser_PrivateTenant(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+
+ server := mock.NewServer()
mock.AvengersTenant.IsPrivate = true
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error {
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetOAuthProfile) error {
+ if q.Provider == app.FacebookProvider && q.Code == "456" {
+ q.Result = &dto.OAuthUserProfile{
+ ID: "FB456",
+ Name: "Some Facebook Guy",
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
code, response := server.
WithURL("http://feedback.theavengers.com/oauth/facebook/token?code=456&identifier=MY_SESSION_ID&redirect=/").
OnTenant(mock.AvengersTenant).
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
Use(middlewares.Session()).
Execute(handlers.OAuthToken())
- user, err := services.Users.GetByEmail("[email protected]")
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(user).IsNil()
-
Expect(code).Equals(http.StatusTemporaryRedirect)
Expect(response.Header().Get("Location")).Equals("/not-invited")
ExpectFiderAuthCookie(response, nil)
@@ -314,13 +455,13 @@ func TestOAuthTokenHandler_NewUser_PrivateTenant(t *testing.T) {
func TestOAuthTokenHandler_InvalidIdentifier(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
mock.AvengersTenant.IsPrivate = true
code, response := server.
WithURL("http://feedback.theavengers.com/oauth/facebook/token?code=456&identifier=SOME_OTHER_ID&redirect=/").
OnTenant(mock.AvengersTenant).
- AddParam("provider", oauth.FacebookProvider).
+ AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
Use(middlewares.Session()).
Execute(handlers.OAuthToken())
diff --git a/app/handlers/post.go b/app/handlers/post.go
index b81ef092e..40cc26475 100644
--- a/app/handlers/post.go
+++ b/app/handlers/post.go
@@ -1,6 +1,8 @@
package handlers
import (
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/csv"
"github.com/getfider/fider/app/pkg/markdown"
"github.com/getfider/fider/app/pkg/web"
@@ -8,26 +10,19 @@ import (
// Index is the default home page
func Index() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
c.SetCanonicalURL("")
- posts, err := c.Services().Posts.Search(
- c.QueryParam("query"),
- c.QueryParam("view"),
- c.QueryParam("limit"),
- c.QueryParamAsArray("tags"),
- )
- if err != nil {
- return c.Failure(err)
+ searchPosts := &query.SearchPosts{
+ Query: c.QueryParam("query"),
+ View: c.QueryParam("view"),
+ Limit: c.QueryParam("limit"),
+ Tags: c.QueryParamAsArray("tags"),
}
+ getAllTags := &query.GetAllTags{}
+ countPerStatus := &query.CountPostPerStatus{}
- tags, err := c.Services().Tags.GetAll()
- if err != nil {
- return c.Failure(err)
- }
-
- stats, err := c.Services().Posts.CountPerStatus()
- if err != nil {
+ if err := bus.Dispatch(c, searchPosts, getAllTags, countPerStatus); err != nil {
return c.Failure(err)
}
@@ -42,9 +37,9 @@ func Index() web.HandlerFunc {
Description: description,
ChunkName: "Home.page",
Data: web.Map{
- "posts": posts,
- "tags": tags,
- "countPerStatus": stats,
+ "posts": searchPosts.Result,
+ "tags": getAllTags.Result,
+ "countPerStatus": countPerStatus.Result,
},
})
}
@@ -52,54 +47,37 @@ func Index() web.HandlerFunc {
// PostDetails shows details of given Post by id
func PostDetails() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
number, err := c.ParamAsInt("number")
if err != nil {
return c.NotFound()
}
- posts := c.Services().Posts
- post, err := posts.GetByNumber(number)
- if err != nil {
- return c.Failure(err)
- }
-
- comments, err := posts.GetCommentsByPost(post)
- if err != nil {
- return c.Failure(err)
- }
-
- tags, err := c.Services().Tags.GetAll()
- if err != nil {
+ getPost := &query.GetPostByNumber{Number: number}
+ if err := bus.Dispatch(c, getPost); err != nil {
return c.Failure(err)
}
- subscribed, err := c.Services().Users.HasSubscribedTo(post.ID)
- if err != nil {
- return c.Failure(err)
- }
-
- votes, err := c.Services().Posts.ListVotes(post, 6)
- if err != nil {
- return c.Failure(err)
- }
-
- attachments, err := c.Services().Posts.GetAttachments(post, nil)
- if err != nil {
+ isSubscribed := &query.UserSubscribedTo{PostID: getPost.Result.ID}
+ getComments := &query.GetCommentsByPost{Post: getPost.Result}
+ getAllTags := &query.GetAllTags{}
+ listVotes := &query.ListPostVotes{PostID: getPost.Result.ID, Limit: 6}
+ getAttachments := &query.GetAttachments{Post: getPost.Result}
+ if err := bus.Dispatch(c, getAllTags, getComments, listVotes, isSubscribed, getAttachments); err != nil {
return c.Failure(err)
}
return c.Page(web.Props{
- Title: post.Title,
- Description: markdown.PlainText(post.Description),
+ Title: getPost.Result.Title,
+ Description: markdown.PlainText(getPost.Result.Description),
ChunkName: "ShowPost.page",
Data: web.Map{
- "comments": comments,
- "subscribed": subscribed,
- "post": post,
- "tags": tags,
- "votes": votes,
- "attachments": attachments,
+ "comments": getComments.Result,
+ "subscribed": isSubscribed.Result,
+ "post": getPost.Result,
+ "tags": getAllTags.Result,
+ "votes": listVotes.Result,
+ "attachments": getAttachments.Result,
},
})
}
@@ -107,14 +85,14 @@ func PostDetails() web.HandlerFunc {
// ExportPostsToCSV returns a CSV with all posts
func ExportPostsToCSV() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
- posts, err := c.Services().Posts.GetAll()
- if err != nil {
+ allPosts := &query.GetAllPosts{}
+ if err := bus.Dispatch(c, allPosts); err != nil {
return c.Failure(err)
}
- bytes, err := csv.FromPosts(posts)
+ bytes, err := csv.FromPosts(allPosts.Result)
if err != nil {
return c.Failure(err)
}
diff --git a/app/handlers/post_test.go b/app/handlers/post_test.go
index 333a3f112..76098f6cc 100644
--- a/app/handlers/post_test.go
+++ b/app/handlers/post_test.go
@@ -1,9 +1,16 @@
package handlers_test
import (
+ "context"
"net/http"
"testing"
+ "github.com/getfider/fider/app"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+
"github.com/getfider/fider/app/handlers"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/mock"
@@ -12,8 +19,22 @@ import (
func TestIndexHandler(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
- code, _ := server.OnTenant(mock.DemoTenant).AsUser(mock.JonSnow).Execute(handlers.Index())
+ bus.AddHandler(func(ctx context.Context, q *query.CountPostPerStatus) error {
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetAllTags) error {
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.SearchPosts) error {
+ return nil
+ })
+
+ server := mock.NewServer()
+ code, _ := server.OnTenant(mock.DemoTenant).
+ AsUser(mock.JonSnow).
+ Execute(handlers.Index())
Expect(code).Equals(http.StatusOK)
}
@@ -21,10 +42,34 @@ func TestIndexHandler(t *testing.T) {
func TestDetailsHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.SetCurrentTenant(mock.DemoTenant)
- services.SetCurrentUser(mock.JonSnow)
- post, _ := services.Posts.Add("My Post", "My Post Description")
+ post := &models.Post{Number: 1, Title: "My Post Title"}
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ q.Result = post
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetCommentsByPost) error {
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetAttachments) error {
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.ListPostVotes) error {
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetAllTags) error {
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.UserSubscribedTo) error {
+ return nil
+ })
+
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
@@ -38,7 +83,11 @@ func TestDetailsHandler(t *testing.T) {
func TestDetailsHandler_NotFound(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
diff --git a/app/handlers/settings.go b/app/handlers/settings.go
index 67b37e5db..90ec01f7d 100644
--- a/app/handlers/settings.go
+++ b/app/handlers/settings.go
@@ -3,23 +3,31 @@ package handlers
import (
"time"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/pkg/bus"
+
"github.com/getfider/fider/app/tasks"
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/pkg/web"
- webutil "github.com/getfider/fider/app/pkg/web/util"
)
// ChangeUserEmail register the intent of changing user email
func ChangeUserEmail() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.ChangeUserEmail)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := c.Services().Tenants.SaveVerificationKey(input.Model.VerificationKey, 24*time.Hour, input.Model)
+ err := bus.Dispatch(c, &cmd.SaveVerificationKey{
+ Key: input.Model.VerificationKey,
+ Duration: 24 * time.Hour,
+ Request: input.Model,
+ })
if err != nil {
return c.Failure(err)
}
@@ -32,8 +40,8 @@ func ChangeUserEmail() web.HandlerFunc {
// VerifyChangeEmailKey checks if key is correct and update user's email
func VerifyChangeEmailKey() web.HandlerFunc {
- return func(c web.Context) error {
- result, err := validateKey(models.EmailVerificationKindChangeEmail, c)
+ return func(c *web.Context) error {
+ result, err := validateKey(enum.EmailVerificationKindChangeEmail, c)
if result == nil {
return err
}
@@ -42,12 +50,15 @@ func VerifyChangeEmailKey() web.HandlerFunc {
return c.Redirect(c.BaseURL())
}
- err = c.Services().Users.ChangeEmail(result.UserID, result.Email)
- if err != nil {
+ changeEmail := &cmd.ChangeUserEmail{
+ UserID: result.UserID,
+ Email: result.Email,
+ }
+ if err = bus.Dispatch(c, changeEmail); err != nil {
return c.Failure(err)
}
- err = c.Services().Tenants.SetKeyAsVerified(result.Key)
+ err = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: result.Key})
if err != nil {
return c.Failure(err)
}
@@ -57,9 +68,9 @@ func VerifyChangeEmailKey() web.HandlerFunc {
// UserSettings is the current user's profile settings page
func UserSettings() web.HandlerFunc {
- return func(c web.Context) error {
- settings, err := c.Services().Users.GetUserSettings()
- if err != nil {
+ return func(c *web.Context) error {
+ settings := &query.GetCurrentUserSettings{}
+ if err := bus.Dispatch(c, settings); err != nil {
return err
}
@@ -67,7 +78,7 @@ func UserSettings() web.HandlerFunc {
Title: "Settings",
ChunkName: "MySettings.page",
Data: web.Map{
- "userSettings": settings,
+ "userSettings": settings.Result,
},
})
}
@@ -75,23 +86,26 @@ func UserSettings() web.HandlerFunc {
// UpdateUserSettings updates current user settings
func UpdateUserSettings() web.HandlerFunc {
- return func(c web.Context) error {
- var err error
-
+ return func(c *web.Context) error {
input := new(actions.UpdateUserSettings)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- if err = webutil.ProcessImageUpload(c, input.Model.Avatar, "avatars"); err != nil {
- return c.Failure(err)
- }
-
- if err = c.Services().Users.Update(input.Model); err != nil {
- return c.Failure(err)
- }
-
- if err = c.Services().Users.UpdateSettings(input.Model.Settings); err != nil {
+ if err := bus.Dispatch(c,
+ &cmd.UploadImage{
+ Image: input.Model.Avatar,
+ Folder: "avatars",
+ },
+ &cmd.UpdateCurrentUser{
+ Name: input.Model.Name,
+ Avatar: input.Model.Avatar,
+ AvatarType: input.Model.AvatarType,
+ },
+ &cmd.UpdateCurrentUserSettings{
+ Settings: input.Model.Settings,
+ },
+ ); err != nil {
return c.Failure(err)
}
@@ -101,14 +115,18 @@ func UpdateUserSettings() web.HandlerFunc {
// ChangeUserRole changes given user role
func ChangeUserRole() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.ChangeUserRole)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := c.Services().Users.ChangeRole(input.Model.UserID, input.Model.Role)
- if err != nil {
+ changeRole := &cmd.ChangeUserRole{
+ UserID: input.Model.UserID,
+ Role: input.Model.Role,
+ }
+
+ if err := bus.Dispatch(c, changeRole); err != nil {
return c.Failure(err)
}
@@ -118,9 +136,8 @@ func ChangeUserRole() web.HandlerFunc {
// DeleteUser erases current user personal data and sign them out
func DeleteUser() web.HandlerFunc {
- return func(c web.Context) error {
- err := c.Services().Users.Delete()
- if err != nil {
+ return func(c *web.Context) error {
+ if err := bus.Dispatch(c, &cmd.DeleteCurrentUser{}); err != nil {
return c.Failure(err)
}
@@ -131,14 +148,14 @@ func DeleteUser() web.HandlerFunc {
// RegenerateAPIKey regenerates current user's API Key
func RegenerateAPIKey() web.HandlerFunc {
- return func(c web.Context) error {
- apiKey, err := c.Services().Users.RegenerateAPIKey()
- if err != nil {
+ return func(c *web.Context) error {
+ regenerateAPIKey := &cmd.RegenerateAPIKey{}
+ if err := bus.Dispatch(c, regenerateAPIKey); err != nil {
return c.Failure(err)
}
return c.Ok(web.Map{
- "apiKey": apiKey,
+ "apiKey": regenerateAPIKey.Result,
})
}
}
diff --git a/app/handlers/settings_test.go b/app/handlers/settings_test.go
index 103fc0fb5..92a3bdc15 100644
--- a/app/handlers/settings_test.go
+++ b/app/handlers/settings_test.go
@@ -1,17 +1,24 @@
package handlers_test
import (
+ "context"
"fmt"
"net/http"
"testing"
"time"
"github.com/getfider/fider/app"
+
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app/models/cmd"
+
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/handlers"
. "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/pkg/web"
)
@@ -19,7 +26,11 @@ import (
func TestSettingsHandler(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.GetCurrentUserSettings) error {
+ return nil
+ })
+
+ server := mock.NewServer()
code, _ := server.
AsUser(mock.JonSnow).
Execute(handlers.UserSettings())
@@ -30,7 +41,7 @@ func TestSettingsHandler(t *testing.T) {
func TestUpdateUserSettingsHandler_EmptyInput(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, _ := server.
AsUser(mock.JonSnow).
ExecutePost(handlers.UpdateUserSettings(), `{ }`)
@@ -41,26 +52,58 @@ func TestUpdateUserSettingsHandler_EmptyInput(t *testing.T) {
func TestUpdateUserSettingsHandler_ValidName(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ var newName string
+ bus.AddHandler(func(ctx context.Context, c *cmd.UpdateCurrentUser) error {
+ newName = c.Name
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.UpdateCurrentUserSettings) error {
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.UploadImage) error {
+ Expect(c.Image.Upload).IsNil()
+ Expect(c.Image.Remove).IsFalse()
+ return nil
+ })
+
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
ExecutePost(handlers.UpdateUserSettings(), `{ "name": "Jon Stark", "avatarType": "gravatar" }`)
- user, _ := services.Users.GetByEmail("[email protected]")
-
Expect(code).Equals(http.StatusOK)
- Expect(user.Name).Equals("Jon Stark")
+ Expect(newName).Equals("Jon Stark")
}
func TestUpdateUserSettingsHandler_NewSettings(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ var updateCmd *cmd.UpdateCurrentUser
+ bus.AddHandler(func(ctx context.Context, c *cmd.UpdateCurrentUser) error {
+ updateCmd = c
+ return nil
+ })
+
+ var updateSettingsCmd *cmd.UpdateCurrentUserSettings
+ bus.AddHandler(func(ctx context.Context, c *cmd.UpdateCurrentUserSettings) error {
+ updateSettingsCmd = c
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.UploadImage) error {
+ Expect(c.Image.Upload).IsNil()
+ Expect(c.Image.Remove).IsFalse()
+ return nil
+ })
+
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
- ExecutePost(handlers.UpdateUserSettings(), `{
+ ExecutePost(handlers.UpdateUserSettings(), `{
"name": "Jon Stark",
"avatarType": "gravatar",
"settings": {
@@ -70,61 +113,98 @@ func TestUpdateUserSettingsHandler_NewSettings(t *testing.T) {
}
}`)
- user, _ := services.Users.GetByEmail("[email protected]")
Expect(code).Equals(http.StatusOK)
- Expect(user.Name).Equals("Jon Stark")
+ Expect(updateCmd.Name).Equals("Jon Stark")
+ Expect(updateCmd.AvatarType).Equals(enum.AvatarTypeGravatar)
- settings, _ := services.Users.GetUserSettings()
- Expect(settings).Equals(map[string]string{
- models.NotificationEventNewPost.UserSettingsKeyName: "1",
- models.NotificationEventNewComment.UserSettingsKeyName: "2",
- models.NotificationEventChangeStatus.UserSettingsKeyName: "3",
- })
+ Expect(updateSettingsCmd.Settings[enum.NotificationEventNewPost.UserSettingsKeyName]).Equals("1")
+ Expect(updateSettingsCmd.Settings[enum.NotificationEventNewComment.UserSettingsKeyName]).Equals("2")
+ Expect(updateSettingsCmd.Settings[enum.NotificationEventChangeStatus.UserSettingsKeyName]).Equals("3")
}
func TestChangeRoleHandler_Valid(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ if q.UserID == mock.AryaStark.ID {
+ q.Result = mock.AryaStark
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ var changeRole *cmd.ChangeUserRole
+ bus.AddHandler(func(ctx context.Context, c *cmd.ChangeUserRole) error {
+ changeRole = c
+ return nil
+ })
+
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
- AddParam("role", models.RoleAdministrator).
+ AddParam("role", enum.RoleAdministrator).
ExecutePost(handlers.ChangeUserRole(), fmt.Sprintf(`{ "userID": %d }`, mock.AryaStark.ID))
- user, _ := services.Users.GetByID(mock.AryaStark.ID)
-
Expect(code).Equals(http.StatusOK)
- Expect(user.Role).Equals(models.RoleAdministrator)
+ Expect(changeRole.UserID).Equals(mock.AryaStark.ID)
+ Expect(changeRole.Role).Equals(enum.RoleAdministrator)
}
func TestChangeUserEmailHandler_Valid(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ return app.ErrNotFound
+ })
+
+ var saveKeyCmd *cmd.SaveVerificationKey
+ bus.AddHandler(func(ctx context.Context, c *cmd.SaveVerificationKey) error {
+ saveKeyCmd = c
+ return nil
+ })
+
for _, email := range []string{
} {
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
ExecutePost(handlers.ChangeUserEmail(), fmt.Sprintf(`{ "email": "%s" }`, email))
Expect(code).Equals(http.StatusOK)
+ Expect(saveKeyCmd.Key).HasLen(64)
+ Expect(saveKeyCmd.Request.GetKind()).Equals(enum.EmailVerificationKindChangeEmail)
+ Expect(saveKeyCmd.Request.GetEmail()).Equals(email)
}
}
func TestChangeUserEmailHandler_Invalid(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ if q.Email == mock.JonSnow.Email {
+ q.Result = mock.JonSnow
+ return nil
+ }
+
+ if q.Email == mock.AryaStark.Email {
+ q.Result = mock.AryaStark
+ return nil
+ }
+
+ return app.ErrNotFound
+ })
+
for _, email := range []string{
"",
"jon.snow",
} {
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
@@ -137,61 +217,87 @@ func TestChangeUserEmailHandler_Invalid(t *testing.T) {
func TestVerifyChangeEmailKeyHandler_Success(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- request := &models.ChangeUserEmail{
- Requestor: mock.JonSnow,
- Email: "[email protected]",
- }
+ server := mock.NewServer()
+
+ key := "th3-s3cr3t"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindChangeEmail {
+ q.Result = &models.EmailVerification{
+ UserID: mock.JonSnow.ID,
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: time.Now().Add(10 * time.Minute),
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ var changeEmailCmd *cmd.ChangeUserEmail
+ bus.AddHandler(func(ctx context.Context, c *cmd.ChangeUserEmail) error {
+ changeEmailCmd = c
+ return nil
+ })
+
+ verified := false
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
+ if c.Key == key {
+ verified = true
+ }
+ return nil
+ })
- services.Tenants.SaveVerificationKey("th3-s3cr3t", 24*time.Hour, request)
code, _ := server.
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
- WithURL("/change-email/verify?k=th3-s3cr3t").
+ WithURL("/change-email/verify?k=" + key).
Execute(handlers.VerifyChangeEmailKey())
Expect(code).Equals(http.StatusTemporaryRedirect)
- user, err := services.Users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.ID).Equals(mock.JonSnow.ID)
- Expect(user.Name).Equals(mock.JonSnow.Name)
- Expect(user.Email).Equals(mock.JonSnow.Email)
-
- result, err := services.Tenants.FindVerificationByKey(models.EmailVerificationKindChangeEmail, "th3-s3cr3t")
- Expect(err).IsNil()
- Expect(result.VerifiedAt).IsNotNil()
+ Expect(changeEmailCmd.UserID).Equals(mock.JonSnow.ID)
+ Expect(changeEmailCmd.Email).Equals("[email protected]")
+ Expect(verified).IsTrue()
}
func TestVerifyChangeEmailKeyHandler_DifferentUser(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- request := &models.ChangeUserEmail{
- Requestor: mock.JonSnow,
- Email: "[email protected]",
- }
- services.Tenants.SaveVerificationKey("th3-s3cr3t", 24*time.Hour, request)
+ key := "th3-s3cr3t"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindChangeEmail {
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: time.Now().Add(10 * time.Minute),
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
+
code, _ := server.
OnTenant(mock.DemoTenant).
AsUser(mock.AryaStark).
- WithURL("/change-email/verify?k=th3-s3cr3t").
+ WithURL("/change-email/verify?k=" + key).
Execute(handlers.VerifyChangeEmailKey())
Expect(code).Equals(http.StatusTemporaryRedirect)
-
- _, err := services.Users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- _, err = services.Users.GetByEmail("[email protected]")
- Expect(err).IsNil()
-
- _, err = services.Users.GetByEmail("[email protected]")
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
}
func TestDeleteUserHandler(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ var deleteCmd *cmd.DeleteCurrentUser
+ bus.AddHandler(func(ctx context.Context, c *cmd.DeleteCurrentUser) error {
+ deleteCmd = c
+ return nil
+ })
+
+ server := mock.NewServer()
code, response := server.
AsUser(mock.JonSnow).
Execute(handlers.DeleteUser())
@@ -200,7 +306,5 @@ func TestDeleteUserHandler(t *testing.T) {
Expect(response.Header().Get("Set-Cookie")).ContainsSubstring(web.CookieAuthName + "=; Path=/; Expires=")
Expect(response.Header().Get("Set-Cookie")).ContainsSubstring("Max-Age=0; HttpOnly")
- user, err := services.Users.GetByEmail("[email protected]")
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(user).IsNil()
+ Expect(deleteCmd).IsNotNil()
}
diff --git a/app/handlers/signin.go b/app/handlers/signin.go
index 4f8ac40df..725e5f839 100644
--- a/app/handlers/signin.go
+++ b/app/handlers/signin.go
@@ -4,9 +4,14 @@ import (
"net/http"
"time"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/web"
webutil "github.com/getfider/fider/app/pkg/web/util"
@@ -15,9 +20,9 @@ import (
// SignInPage renders the sign in page
func SignInPage() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
- if c.Tenant().IsPrivate || c.Tenant().Status == models.TenantLocked {
+ if c.Tenant().IsPrivate || c.Tenant().Status == enum.TenantLocked {
return c.Page(web.Props{
Title: "Sign in",
ChunkName: "SignIn.page",
@@ -30,7 +35,7 @@ func SignInPage() web.HandlerFunc {
// NotInvitedPage renders the not invited page
func NotInvitedPage() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
return c.Render(http.StatusForbidden, "not-invited.html", web.Props{
Title: "Not Invited",
Description: "We couldn't find your account for your email address.",
@@ -40,13 +45,17 @@ func NotInvitedPage() web.HandlerFunc {
// SignInByEmail sends a new email with verification key
func SignInByEmail() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.SignInByEmail)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := c.Services().Tenants.SaveVerificationKey(input.Model.VerificationKey, 30*time.Minute, input.Model)
+ err := bus.Dispatch(c, &cmd.SaveVerificationKey{
+ Key: input.Model.VerificationKey,
+ Duration: 30 * time.Minute,
+ Request: input.Model,
+ })
if err != nil {
return c.Failure(err)
}
@@ -58,16 +67,16 @@ func SignInByEmail() web.HandlerFunc {
}
// VerifySignInKey checks if verify key is correct and sign in user
-func VerifySignInKey(kind models.EmailVerificationKind) web.HandlerFunc {
- return func(c web.Context) error {
+func VerifySignInKey(kind enum.EmailVerificationKind) web.HandlerFunc {
+ return func(c *web.Context) error {
result, err := validateKey(kind, c)
if result == nil {
return err
}
var user *models.User
- if kind == models.EmailVerificationKindSignUp && c.Tenant().Status == models.TenantPending {
- if err = c.Services().Tenants.Activate(c.Tenant().ID); err != nil {
+ if kind == enum.EmailVerificationKindSignUp && c.Tenant().Status == enum.TenantPending {
+ if err = bus.Dispatch(c, &cmd.ActivateTenant{TenantID: c.Tenant().ID}); err != nil {
return c.Failure(err)
}
@@ -75,14 +84,16 @@ func VerifySignInKey(kind models.EmailVerificationKind) web.HandlerFunc {
Name: result.Name,
Email: result.Email,
Tenant: c.Tenant(),
- Role: models.RoleAdministrator,
+ Role: enum.RoleAdministrator,
}
- if err = c.Services().Users.Register(user); err != nil {
+ if err = bus.Dispatch(c, &cmd.RegisterUser{User: user}); err != nil {
return c.Failure(err)
}
- } else if kind == models.EmailVerificationKindSignIn {
- user, err = c.Services().Users.GetByEmail(result.Email)
+ } else if kind == enum.EmailVerificationKindSignIn {
+ userByEmail := &query.GetUserByEmail{Email: result.Email}
+ err = bus.Dispatch(c, userByEmail)
+ user = userByEmail.Result
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
if c.Tenant().IsPrivate {
@@ -92,8 +103,10 @@ func VerifySignInKey(kind models.EmailVerificationKind) web.HandlerFunc {
}
return c.Failure(err)
}
- } else if kind == models.EmailVerificationKindUserInvitation {
- user, err = c.Services().Users.GetByEmail(result.Email)
+ } else if kind == enum.EmailVerificationKindUserInvitation {
+ userByEmail := &query.GetUserByEmail{Email: result.Email}
+ err = bus.Dispatch(c, userByEmail)
+ user = userByEmail.Result
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
if c.Tenant().IsPrivate {
@@ -107,7 +120,7 @@ func VerifySignInKey(kind models.EmailVerificationKind) web.HandlerFunc {
return c.NotFound()
}
- err = c.Services().Tenants.SetKeyAsVerified(result.Key)
+ err = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: result.Key})
if err != nil {
return c.Failure(err)
}
@@ -120,13 +133,13 @@ func VerifySignInKey(kind models.EmailVerificationKind) web.HandlerFunc {
// CompleteSignInProfile handles the action to update user profile
func CompleteSignInProfile() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.CompleteProfile)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- _, err := c.Services().Users.GetByEmail(input.Model.Email)
+ err := bus.Dispatch(c, &query.GetUserByEmail{Email: input.Model.Email})
if errors.Cause(err) != app.ErrNotFound {
return c.Ok(web.Map{})
}
@@ -135,14 +148,14 @@ func CompleteSignInProfile() web.HandlerFunc {
Name: input.Model.Name,
Email: input.Model.Email,
Tenant: c.Tenant(),
- Role: models.RoleVisitor,
+ Role: enum.RoleVisitor,
}
- err = c.Services().Users.Register(user)
+ err = bus.Dispatch(c, &cmd.RegisterUser{User: user})
if err != nil {
return c.Failure(err)
}
- err = c.Services().Tenants.SetKeyAsVerified(input.Model.Key)
+ err = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: input.Model.Key})
if err != nil {
return c.Failure(err)
}
@@ -155,7 +168,7 @@ func CompleteSignInProfile() web.HandlerFunc {
// SignOut remove auth cookies
func SignOut() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
c.RemoveCookie(web.CookieAuthName)
return c.Redirect(c.QueryParam("redirect"))
}
diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.go
index 8c75ec57d..d5e08bef3 100644
--- a/app/handlers/signin_test.go
+++ b/app/handlers/signin_test.go
@@ -1,15 +1,22 @@
package handlers_test
import (
+ "context"
"testing"
"time"
+ "github.com/getfider/fider/app"
+
"net/http"
"net/http/httptest"
"github.com/getfider/fider/app/handlers"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/pkg/web"
@@ -18,7 +25,7 @@ import (
func TestSignInByEmailHandler_WithoutEmail(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, _ := server.
ExecutePost(handlers.SignInByEmail(), "{ }")
@@ -28,22 +35,36 @@ func TestSignInByEmailHandler_WithoutEmail(t *testing.T) {
func TestSignInByEmailHandler_WithEmail(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ var saveKeyCmd *cmd.SaveVerificationKey
+ bus.AddHandler(func(ctx context.Context, c *cmd.SaveVerificationKey) error {
+ saveKeyCmd = c
+ return nil
+ })
+
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
ExecutePost(handlers.SignInByEmail(), `{ "email": "[email protected]" }`)
Expect(code).Equals(http.StatusOK)
+ Expect(saveKeyCmd.Key).HasLen(64)
+ Expect(saveKeyCmd.Request.GetKind()).Equals(enum.EmailVerificationKindSignIn)
+ Expect(saveKeyCmd.Request.GetEmail()).Equals("[email protected]")
+ Expect(saveKeyCmd.Request.GetName()).Equals("")
}
func TestVerifySignInKeyHandler_UnknownKey(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
WithURL("http://demo.test.fider.io/signin/verify?k=unknown").
- Execute(handlers.VerifySignInKey(models.EmailVerificationKindSignIn))
+ Execute(handlers.VerifySignInKey(enum.EmailVerificationKindSignIn))
Expect(code).Equals(http.StatusNotFound)
}
@@ -51,16 +72,27 @@ func TestVerifySignInKeyHandler_UnknownKey(t *testing.T) {
func TestVerifySignInKeyHandler_UsedKey(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
-
- e := &models.SignInByEmail{Email: "[email protected]"}
- services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
- services.Tenants.SetKeyAsVerified("1234567890")
+ server := mock.NewServer()
+
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
+ now := time.Now()
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ VerifiedAt: &now,
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
code, _ := server.
OnTenant(mock.DemoTenant).
- WithURL("http://demo.test.fider.io/signin/verify?k=1234567890").
- Execute(handlers.VerifySignInKey(models.EmailVerificationKindSignIn))
+ WithURL("http://demo.test.fider.io/signin/verify?k=" + key).
+ Execute(handlers.VerifySignInKey(enum.EmailVerificationKindSignIn))
Expect(code).Equals(http.StatusGone)
}
@@ -68,52 +100,128 @@ func TestVerifySignInKeyHandler_UsedKey(t *testing.T) {
func TestVerifySignInKeyHandler_ExpiredKey(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ server := mock.NewServer()
+
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
+ now := time.Now().Add(-5 * time.Minute)
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: now,
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
- e := &models.SignInByEmail{Email: "[email protected]"}
- services.Tenants.SaveVerificationKey("1234567890", 5*time.Minute, e)
- request, _ := services.Tenants.FindVerificationByKey(models.EmailVerificationKindSignIn, "1234567890")
- request.ExpiresAt = request.CreatedAt.Add(-6 * time.Minute) //reduce 1 minute
+ verified := false
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
+ if c.Key == key {
+ verified = true
+ }
+ return nil
+ })
code, _ := server.
OnTenant(mock.DemoTenant).
- WithURL("http://demo.test.fider.io/signin/verify?k=1234567890").
- Execute(handlers.VerifySignInKey(models.EmailVerificationKindSignIn))
+ WithURL("http://demo.test.fider.io/signin/verify?k=" + key).
+ Execute(handlers.VerifySignInKey(enum.EmailVerificationKindSignIn))
Expect(code).Equals(http.StatusGone)
+ Expect(verified).IsTrue()
}
func TestVerifySignInKeyHandler_CorrectKey_ExistingUser(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ server := mock.NewServer()
+
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
+ expiresAt := time.Now().Add(5 * time.Minute)
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: expiresAt,
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ if q.Email == mock.JonSnow.Email {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
- e := &models.SignInByEmail{Email: "[email protected]"}
- services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
+ verified := false
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
+ if c.Key == key {
+ verified = true
+ }
+ return nil
+ })
code, response := server.
OnTenant(mock.DemoTenant).
- WithURL("http://demo.test.fider.io/signin/verify?k=1234567890").
- Execute(handlers.VerifySignInKey(models.EmailVerificationKindSignIn))
+ WithURL("http://demo.test.fider.io/signin/verify?k=" + key).
+ Execute(handlers.VerifySignInKey(enum.EmailVerificationKindSignIn))
Expect(code).Equals(http.StatusTemporaryRedirect)
Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
+ Expect(verified).IsTrue()
ExpectFiderAuthCookie(response, mock.JonSnow)
}
func TestVerifySignInKeyHandler_CorrectKey_NewUser(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.SearchPosts) error {
+ return nil
+ })
- e := &models.SignInByEmail{Email: "[email protected]"}
- services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
+ bus.AddHandler(func(ctx context.Context, q *query.CountPostPerStatus) error {
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetAllTags) error {
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ return app.ErrNotFound
+ })
+
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
+ expiresAt := time.Now().Add(5 * time.Minute)
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: expiresAt,
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
- WithURL("http://demo.test.fider.io/signin/verify?k=1234567890").
- Execute(handlers.VerifySignInKey(models.EmailVerificationKindSignIn))
+ WithURL("http://demo.test.fider.io/signin/verify?k=" + key).
+ Execute(handlers.VerifySignInKey(enum.EmailVerificationKindSignIn))
Expect(code).Equals(http.StatusOK)
}
@@ -121,16 +229,32 @@ func TestVerifySignInKeyHandler_CorrectKey_NewUser(t *testing.T) {
func TestVerifySignInKeyHandler_PrivateTenant_SignInRequest_NonInviteNewUser(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- mock.DemoTenant.IsPrivate = true
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
+ expiresAt := time.Now().Add(5 * time.Minute)
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: expiresAt,
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ return app.ErrNotFound
+ })
- e := &models.SignInByEmail{Email: "[email protected]"}
- services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
+ server := mock.NewServer()
+ mock.DemoTenant.IsPrivate = true
code, _ := server.
OnTenant(mock.DemoTenant).
- WithURL("http://demo.test.fider.io/signin/verify?k=1234567890").
- Execute(handlers.VerifySignInKey(models.EmailVerificationKindSignIn))
+ WithURL("http://demo.test.fider.io/signin/verify?k=" + key).
+ Execute(handlers.VerifySignInKey(enum.EmailVerificationKindSignIn))
Expect(code).Equals(http.StatusForbidden)
}
@@ -138,64 +262,138 @@ func TestVerifySignInKeyHandler_PrivateTenant_SignInRequest_NonInviteNewUser(t *
func TestVerifySignInKeyHandler_PrivateTenant_SignInRequest_RegisteredUser(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ server := mock.NewServer()
mock.DemoTenant.IsPrivate = true
- services.Users.Register(&models.User{
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
+ expiresAt := time.Now().Add(5 * time.Minute)
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: expiresAt,
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ user := &models.User{
Name: "Hot Pie",
Tenant: mock.DemoTenant,
+ }
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ if q.Email == user.Email {
+ q.Result = user
+ return nil
+ }
+ return app.ErrNotFound
})
- e := &models.SignInByEmail{Email: "[email protected]"}
- services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
+ verified := false
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
+ if c.Key == key {
+ verified = true
+ }
+ return nil
+ })
code, response := server.
OnTenant(mock.DemoTenant).
- WithURL("http://demo.test.fider.io/signin/verify?k=1234567890").
- Execute(handlers.VerifySignInKey(models.EmailVerificationKindSignIn))
+ WithURL("http://demo.test.fider.io/signin/verify?k=" + key).
+ Execute(handlers.VerifySignInKey(enum.EmailVerificationKindSignIn))
Expect(code).Equals(http.StatusTemporaryRedirect)
Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
+ Expect(verified).IsTrue()
}
func TestVerifySignInKeyHandler_PrivateTenant_InviteRequest_ExistingUser(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ server := mock.NewServer()
mock.DemoTenant.IsPrivate = true
- services.Users.Register(&models.User{
+ user := &models.User{
Name: "Hot Pie",
Tenant: mock.DemoTenant,
+ }
+
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindUserInvitation {
+ expiresAt := time.Now().Add(5 * time.Minute)
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: expiresAt,
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
})
- e := &models.UserInvitation{Email: "[email protected]"}
- services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
+ verified := false
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
+ if c.Key == key {
+ verified = true
+ }
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ if q.Email == user.Email {
+ q.Result = user
+ return nil
+ }
+ return app.ErrNotFound
+ })
code, response := server.
OnTenant(mock.DemoTenant).
- WithURL("http://demo.test.fider.io/invite/verify?k=1234567890").
- Execute(handlers.VerifySignInKey(models.EmailVerificationKindUserInvitation))
+ WithURL("http://demo.test.fider.io/invite/verify?k=" + key).
+ Execute(handlers.VerifySignInKey(enum.EmailVerificationKindUserInvitation))
Expect(code).Equals(http.StatusTemporaryRedirect)
Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
+ Expect(verified).IsTrue()
}
func TestVerifySignInKeyHandler_PrivateTenant_InviteRequest_NewUser(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ server := mock.NewServer()
mock.DemoTenant.IsPrivate = true
- e := &models.UserInvitation{Email: "[email protected]"}
- services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindUserInvitation {
+ expiresAt := time.Now().Add(5 * time.Minute)
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: expiresAt,
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ return app.ErrNotFound
+ })
code, _ := server.
OnTenant(mock.DemoTenant).
- WithURL("http://demo.test.fider.io/invite/verify?k=1234567890").
- Execute(handlers.VerifySignInKey(models.EmailVerificationKindUserInvitation))
+ WithURL("http://demo.test.fider.io/invite/verify?k=" + key).
+ Execute(handlers.VerifySignInKey(enum.EmailVerificationKindUserInvitation))
Expect(code).Equals(http.StatusOK)
}
@@ -203,33 +401,67 @@ func TestVerifySignInKeyHandler_PrivateTenant_InviteRequest_NewUser(t *testing.T
func TestVerifySignUpKeyHandler_PendingTenant(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ server := mock.NewServer()
+ mock.DemoTenant.Status = enum.TenantPending
+
+ var newUser *models.User
+ bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
+ newUser = c.User
+ return nil
+ })
+
+ activated := false
+ bus.AddHandler(func(ctx context.Context, c *cmd.ActivateTenant) error {
+ activated = true
+ return nil
+ })
+
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindSignUp {
+ expiresAt := time.Now().Add(5 * time.Minute)
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: expiresAt,
+ Name: "Hot Pie",
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
- e := &models.CreateTenant{Email: "[email protected]", Name: "Hot Pie"}
- services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
- mock.DemoTenant.Status = models.TenantPending
+ verified := false
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
+ if c.Key == key {
+ verified = true
+ }
+ return nil
+ })
code, response := server.
OnTenant(mock.DemoTenant).
- WithURL("http://demo.test.fider.io/signup/verify?k=1234567890").
+ WithURL("http://demo.test.fider.io/signup/verify?k=" + key).
Execute(handlers.VerifySignUpKey())
- tenant, _ := services.Tenants.GetByDomain("demo")
-
Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(tenant.Status).Equals(models.TenantActive)
Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
+ Expect(newUser.Name).Equals("Hot Pie")
+ Expect(newUser.Email).Equals("[email protected]")
+ Expect(activated).IsTrue()
+ Expect(verified).IsTrue()
}
func TestCompleteSignInProfileHandler_UnknownKey(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
WithURL("http://demo.test.fider.io/signin/complete").
- ExecutePost(handlers.CompleteSignInProfile(), `{ }`)
+ ExecutePost(handlers.CompleteSignInProfile(), `{ }`)
Expect(code).Equals(http.StatusBadRequest)
}
@@ -237,15 +469,35 @@ func TestCompleteSignInProfileHandler_UnknownKey(t *testing.T) {
func TestCompleteSignInProfileHandler_ExistingUser_CorrectKey(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ server := mock.NewServer()
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ if q.Email == mock.JonSnow.Email {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
- e := &models.SignInByEmail{Email: mock.JonSnow.Email}
- services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
+ expiresAt := time.Now().Add(5 * time.Minute)
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: expiresAt,
+ Email: mock.JonSnow.Email,
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
code, _ := server.
OnTenant(mock.DemoTenant).
WithURL("http://demo.test.fider.io/signin/complete").
- ExecutePost(handlers.CompleteSignInProfile(), `{ "name": "Hot Pie", "key": "1234567890" }`)
+ ExecutePost(handlers.CompleteSignInProfile(), `{ "name": "Hot Pie", "key": "`+key+`" }`)
Expect(code).Equals(http.StatusOK)
}
@@ -253,33 +505,58 @@ func TestCompleteSignInProfileHandler_ExistingUser_CorrectKey(t *testing.T) {
func TestCompleteSignInProfileHandler_CorrectKey(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ server := mock.NewServer()
- e := &models.SignInByEmail{Email: "[email protected]"}
- services.Tenants.SaveVerificationKey("1234567890", 15*time.Minute, e)
+ var newUser *models.User
+ bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
+ newUser = c.User
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ return app.ErrNotFound
+ })
+
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
+ expiresAt := time.Now().Add(5 * time.Minute)
+ q.Result = &models.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: expiresAt,
+ Email: "[email protected]",
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ verified := false
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
+ if c.Key == key {
+ verified = true
+ }
+ return nil
+ })
code, response := server.
OnTenant(mock.DemoTenant).
WithURL("http://demo.test.fider.io/signin/complete").
- ExecutePost(handlers.CompleteSignInProfile(), `{ "name": "Hot Pie", "key": "1234567890" }`)
+ ExecutePost(handlers.CompleteSignInProfile(), `{ "name": "Hot Pie", "key": "`+key+`" }`)
Expect(code).Equals(http.StatusOK)
- user, err := services.Users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.Name).Equals("Hot Pie")
- Expect(user.Email).Equals("[email protected]")
+ Expect(newUser.Name).Equals("Hot Pie")
+ Expect(newUser.Email).Equals("[email protected]")
+ Expect(verified).IsTrue()
- ExpectFiderAuthCookie(response, user)
-
- request, err := services.Tenants.FindVerificationByKey(models.EmailVerificationKindSignIn, "1234567890")
- Expect(err).IsNil()
- Expect(request.VerifiedAt).IsNotNil()
+ ExpectFiderAuthCookie(response, newUser)
}
func TestSignInPageHandler_AuthenticatedUser(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, response := server.
OnTenant(mock.DemoTenant).
AsUser(mock.AryaStark).
@@ -293,7 +570,7 @@ func TestSignInPageHandler_AuthenticatedUser(t *testing.T) {
func TestSignInPageHandler_NonPrivateTenant(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, response := server.
OnTenant(mock.DemoTenant).
WithURL("http://demo.test.fider.io/signin").
@@ -306,7 +583,7 @@ func TestSignInPageHandler_NonPrivateTenant(t *testing.T) {
func TestSignInPageHandler_PrivateTenant_UnauthenticatedUser(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
mock.DemoTenant.IsPrivate = true
code, _ := server.
diff --git a/app/handlers/signup.go b/app/handlers/signup.go
index f5668c48b..2014bfffb 100644
--- a/app/handlers/signup.go
+++ b/app/handlers/signup.go
@@ -3,7 +3,13 @@ package handlers
import (
"time"
- "github.com/getfider/fider/app/pkg/web/util"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/pkg/bus"
+
+ webutil "github.com/getfider/fider/app/pkg/web/util"
"github.com/getfider/fider/app/tasks"
@@ -20,10 +26,10 @@ import (
// CheckAvailability checks if given domain is available to be used
func CheckAvailability() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
subdomain := strings.ToLower(c.Param("subdomain"))
- messages, _ := validate.Subdomain(c.Services().Tenants, subdomain)
+ messages, _ := validate.Subdomain(c, subdomain)
if len(messages) > 0 {
return c.Ok(web.Map{
"message": strings.Join(messages, ","),
@@ -36,7 +42,7 @@ func CheckAvailability() web.HandlerFunc {
//CreateTenant creates a new tenant
func CreateTenant() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
input := new(actions.CreateTenant)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
@@ -44,21 +50,26 @@ func CreateTenant() web.HandlerFunc {
socialSignUp := input.Model.Token != ""
- status := models.TenantPending
+ status := enum.TenantPending
if socialSignUp {
- status = models.TenantActive
+ status = enum.TenantActive
}
- tenant, err := c.Services().Tenants.Add(input.Model.TenantName, input.Model.Subdomain, status)
+ createTenant := &cmd.CreateTenant{
+ Name: input.Model.TenantName,
+ Subdomain: input.Model.Subdomain,
+ Status: status,
+ }
+ err := bus.Dispatch(c, createTenant)
if err != nil {
return c.Failure(err)
}
- c.SetTenant(tenant)
+ c.SetTenant(createTenant.Result)
user := &models.User{
- Tenant: tenant,
- Role: models.RoleAdministrator,
+ Tenant: createTenant.Result,
+ Role: enum.RoleAdministrator,
}
if socialSignUp {
@@ -68,7 +79,7 @@ func CreateTenant() web.HandlerFunc {
{UID: input.Model.UserClaims.OAuthID, Name: input.Model.UserClaims.OAuthProvider},
}
- if err := c.Services().Users.Register(user); err != nil {
+ if err := bus.Dispatch(c, &cmd.RegisterUser{User: user}); err != nil {
return c.Failure(err)
}
@@ -82,12 +93,16 @@ func CreateTenant() web.HandlerFunc {
user.Name = input.Model.Name
user.Email = input.Model.Email
- err := c.Services().Tenants.SaveVerificationKey(input.Model.VerificationKey, 48*time.Hour, input.Model)
+ err := bus.Dispatch(c, &cmd.SaveVerificationKey{
+ Key: input.Model.VerificationKey,
+ Duration: 48 * time.Hour,
+ Request: input.Model,
+ })
if err != nil {
return c.Failure(err)
}
- c.Enqueue(tasks.SendSignUpEmail(input.Model, c.TenantBaseURL(tenant)))
+ c.Enqueue(tasks.SendSignUpEmail(input.Model, web.TenantBaseURL(c, createTenant.Result)))
}
return c.Ok(web.Map{})
@@ -96,18 +111,19 @@ func CreateTenant() web.HandlerFunc {
//SignUp is the entry point for installation / signup
func SignUp() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
if env.IsSingleHostMode() {
- tenant, err := c.Services().Tenants.First()
+ firstTenant := &query.GetFirstTenant{}
+ err := bus.Dispatch(c, firstTenant)
if err != nil && errors.Cause(err) != app.ErrNotFound {
return c.Failure(err)
}
- if tenant != nil {
+ if firstTenant.Result != nil {
return c.Redirect("/")
}
} else {
- baseURL := webutil.GetOAuthBaseURL(c)
+ baseURL := web.OAuthBaseURL(c)
if !strings.HasPrefix(c.Request.URL.String(), baseURL) {
return c.Redirect(baseURL + "/signup")
}
@@ -123,9 +139,9 @@ func SignUp() web.HandlerFunc {
// VerifySignUpKey checks if verify key is correct, activate the tenant and sign in user
func VerifySignUpKey() web.HandlerFunc {
- return func(c web.Context) error {
- if c.Tenant().Status == models.TenantPending {
- return VerifySignInKey(models.EmailVerificationKindSignUp)(c)
+ return func(c *web.Context) error {
+ if c.Tenant().Status == enum.TenantPending {
+ return VerifySignInKey(enum.EmailVerificationKindSignUp)(c)
}
return c.NotFound()
}
diff --git a/app/handlers/signup_test.go b/app/handlers/signup_test.go
index 1bf887c82..40f84b0f8 100644
--- a/app/handlers/signup_test.go
+++ b/app/handlers/signup_test.go
@@ -1,17 +1,22 @@
package handlers_test
import (
+ "context"
+ "fmt"
"net/http"
"testing"
"time"
- "fmt"
-
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/handlers"
+
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app/handlers"
. "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/pkg/web"
@@ -20,7 +25,7 @@ import (
func TestSignUpHandler_MultiTenant(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, _ := server.
WithURL("http://login.test.fider.io/signup").
Execute(handlers.SignUp())
@@ -31,7 +36,7 @@ func TestSignUpHandler_MultiTenant(t *testing.T) {
func TestSignUpHandler_MultiTenant_WrongURL(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, response := server.
WithURL("http://demo.test.fider.io/signup").
Execute(handlers.SignUp())
@@ -43,7 +48,11 @@ func TestSignUpHandler_MultiTenant_WrongURL(t *testing.T) {
func TestSignUpHandler_SingleTenant_NoTenants(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewSingleTenantServer()
+ bus.AddHandler(func(ctx context.Context, q *query.GetFirstTenant) error {
+ return app.ErrNotFound
+ })
+
+ server := mock.NewSingleTenantServer()
code, _ := server.Execute(handlers.SignUp())
Expect(code).Equals(http.StatusOK)
@@ -52,8 +61,12 @@ func TestSignUpHandler_SingleTenant_NoTenants(t *testing.T) {
func TestSignUpHandler_SingleTenant_WithTenants(t *testing.T) {
RegisterT(t)
- server, services := mock.NewSingleTenantServer()
- services.Tenants.Add("Game of Thrones", "got", models.TenantActive)
+ bus.AddHandler(func(ctx context.Context, q *query.GetFirstTenant) error {
+ q.Result = &models.Tenant{ID: 2, Name: "MyCompany"}
+ return nil
+ })
+
+ server := mock.NewSingleTenantServer()
code, _ := server.Execute(handlers.SignUp())
Expect(code).Equals(http.StatusTemporaryRedirect)
@@ -62,7 +75,7 @@ func TestSignUpHandler_SingleTenant_WithTenants(t *testing.T) {
func TestCheckAvailabilityHandler_InvalidSubdomain(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, response := server.AddParam("subdomain", "").ExecuteAsJSON(handlers.CheckAvailability())
Expect(code).Equals(http.StatusOK)
@@ -72,7 +85,12 @@ func TestCheckAvailabilityHandler_InvalidSubdomain(t *testing.T) {
func TestCheckAvailabilityHandler_UnavailableSubdomain(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.IsSubdomainAvailable) error {
+ q.Result = false
+ return nil
+ })
+
+ server := mock.NewServer()
code, response := server.AddParam("subdomain", "demo").ExecuteAsJSON(handlers.CheckAvailability())
Expect(code).Equals(http.StatusOK)
@@ -82,7 +100,12 @@ func TestCheckAvailabilityHandler_UnavailableSubdomain(t *testing.T) {
func TestCheckAvailabilityHandler_ValidSubdomain(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.IsSubdomainAvailable) error {
+ q.Result = true
+ return nil
+ })
+
+ server := mock.NewServer()
code, response := server.AddParam("subdomain", "mycompany").ExecuteAsJSON(handlers.CheckAvailability())
Expect(code).Equals(http.StatusOK)
@@ -92,7 +115,7 @@ func TestCheckAvailabilityHandler_ValidSubdomain(t *testing.T) {
func TestCreateTenantHandler_EmptyInput(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
code, _ := server.ExecutePost(handlers.CreateTenant(), `{ }`)
Expect(code).Equals(http.StatusBadRequest)
@@ -101,7 +124,24 @@ func TestCreateTenantHandler_EmptyInput(t *testing.T) {
func TestCreateTenantHandler_WithSocialAccount(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ var newUser *models.User
+ bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
+ newUser = c.User
+ return nil
+ })
+
+ var newTenant *cmd.CreateTenant
+ bus.AddHandler(func(ctx context.Context, c *cmd.CreateTenant) error {
+ newTenant = c
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.IsSubdomainAvailable) error {
+ q.Result = true
+ return nil
+ })
+
+ server := mock.NewServer()
token, _ := jwt.Encode(jwt.OAuthClaims{
OAuthID: "123",
OAuthName: "Jon Snow",
@@ -110,33 +150,27 @@ func TestCreateTenantHandler_WithSocialAccount(t *testing.T) {
})
code, response := server.ExecutePost(
handlers.CreateTenant(),
- fmt.Sprintf(`{
- "token": "%s",
- "tenantName": "My Company",
- "subdomain": "mycompany",
+ fmt.Sprintf(`{
+ "token": "%s",
+ "tenantName": "My Company",
+ "subdomain": "mycompany",
"legalAgreement": true
}`, token),
)
- tenant, err := services.Tenants.GetByDomain("mycompany")
-
Expect(code).Equals(http.StatusOK)
- Expect(err).IsNil()
- Expect(tenant.Name).Equals("My Company")
- Expect(tenant.Subdomain).Equals("mycompany")
- Expect(tenant.Status).Equals(models.TenantActive)
+ Expect(newTenant.Name).Equals("My Company")
+ Expect(newTenant.Subdomain).Equals("mycompany")
+ Expect(newTenant.Status).Equals(enum.TenantActive)
- services.SetCurrentTenant(tenant)
- user, err := services.Users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.Name).Equals("Jon Snow")
- Expect(user.Email).Equals("[email protected]")
- Expect(user.Role).Equals(models.RoleAdministrator)
+ Expect(newUser.Name).Equals("Jon Snow")
+ Expect(newUser.Email).Equals("[email protected]")
+ Expect(newUser.Role).Equals(enum.RoleAdministrator)
cookie := web.ParseCookie(response.Header().Get("Set-Cookie"))
Expect(cookie.Name).Equals(web.CookieSignUpAuthName)
- ExpectFiderToken(cookie.Value, user)
+ ExpectFiderToken(cookie.Value, newUser)
Expect(cookie.Domain).Equals("test.fider.io")
Expect(cookie.HttpOnly).IsTrue()
Expect(cookie.Path).Equals("/")
@@ -146,7 +180,25 @@ func TestCreateTenantHandler_WithSocialAccount(t *testing.T) {
func TestCreateTenantHandler_SingleHost_WithSocialAccount(t *testing.T) {
RegisterT(t)
- server, services := mock.NewSingleTenantServer()
+ var newUser *models.User
+ bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
+ c.User.ID = 1
+ newUser = c.User
+ return nil
+ })
+
+ var newTenant *cmd.CreateTenant
+ bus.AddHandler(func(ctx context.Context, c *cmd.CreateTenant) error {
+ newTenant = c
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.IsSubdomainAvailable) error {
+ q.Result = true
+ return nil
+ })
+
+ server := mock.NewSingleTenantServer()
token, _ := jwt.Encode(jwt.OAuthClaims{
OAuthID: "123",
OAuthName: "Jon Snow",
@@ -155,28 +207,22 @@ func TestCreateTenantHandler_SingleHost_WithSocialAccount(t *testing.T) {
})
code, response := server.ExecutePost(
handlers.CreateTenant(),
- fmt.Sprintf(`{
- "token": "%s",
+ fmt.Sprintf(`{
+ "token": "%s",
"tenantName": "My Company",
"legalAgreement": true
}`, token),
)
- tenant, err := services.Tenants.First()
-
Expect(code).Equals(http.StatusOK)
- Expect(err).IsNil()
- Expect(tenant.Name).Equals("My Company")
- Expect(tenant.Subdomain).Equals("default")
- Expect(tenant.Status).Equals(models.TenantActive)
+ Expect(newTenant.Name).Equals("My Company")
+ Expect(newTenant.Subdomain).Equals("default")
+ Expect(newTenant.Status).Equals(enum.TenantActive)
- services.SetCurrentTenant(tenant)
- user, err := services.Users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.Name).Equals("Jon Snow")
- Expect(user.Email).Equals("[email protected]")
- Expect(user.Role).Equals(models.RoleAdministrator)
+ Expect(newUser.Name).Equals("Jon Snow")
+ Expect(newUser.Email).Equals("[email protected]")
+ Expect(newUser.Role).Equals(enum.RoleAdministrator)
ExpectFiderAuthCookie(response, &models.User{
ID: 1,
@@ -188,31 +234,51 @@ func TestCreateTenantHandler_SingleHost_WithSocialAccount(t *testing.T) {
func TestCreateTenantHandler_WithEmailAndName(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
+ panic("Should not register any user")
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.IsSubdomainAvailable) error {
+ q.Result = true
+ return nil
+ })
+
+ var newTenant *cmd.CreateTenant
+ bus.AddHandler(func(ctx context.Context, c *cmd.CreateTenant) error {
+ newTenant = c
+ c.Result = &models.Tenant{ID: 1, Name: c.Name, Subdomain: c.Subdomain, Status: c.Status}
+ return nil
+ })
+
+ var saveKeyCmd *cmd.SaveVerificationKey
+ bus.AddHandler(func(ctx context.Context, c *cmd.SaveVerificationKey) error {
+ saveKeyCmd = c
+ return nil
+ })
+
+ server := mock.NewServer()
code, response := server.ExecutePost(
handlers.CreateTenant(),
- `{
- "name": "Jon Snow",
- "email": "[email protected]",
- "tenantName": "My Company",
- "subdomain": "mycompany",
- "legalAgreement": true
+ `{
+ "name": "Jon Snow",
+ "email": "[email protected]",
+ "tenantName": "My Company",
+ "subdomain": "mycompany",
+ "legalAgreement": true
}`,
)
Expect(code).Equals(http.StatusOK)
Expect(response.Header().Get("Set-Cookie")).IsEmpty()
- tenant, err := services.Tenants.GetByDomain("mycompany")
-
Expect(code).Equals(http.StatusOK)
- Expect(err).IsNil()
- Expect(tenant.Name).Equals("My Company")
- Expect(tenant.Subdomain).Equals("mycompany")
- Expect(tenant.Status).Equals(models.TenantPending)
+ Expect(newTenant.Name).Equals("My Company")
+ Expect(newTenant.Subdomain).Equals("mycompany")
+ Expect(newTenant.Status).Equals(enum.TenantPending)
- user, err := services.Users.GetByEmail("[email protected]")
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(user).IsNil()
+ Expect(saveKeyCmd.Key).HasLen(64)
+ Expect(saveKeyCmd.Request.GetKind()).Equals(enum.EmailVerificationKindSignUp)
+ Expect(saveKeyCmd.Request.GetEmail()).Equals("[email protected]")
+ Expect(saveKeyCmd.Request.GetName()).Equals("Jon Snow")
}
diff --git a/app/handlers/tag.go b/app/handlers/tag.go
index d03e92c06..7fc69d573 100644
--- a/app/handlers/tag.go
+++ b/app/handlers/tag.go
@@ -1,14 +1,16 @@
package handlers
import (
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/web"
)
// ManageTags is the home page for managing tags
func ManageTags() web.HandlerFunc {
- return func(c web.Context) error {
- tags, err := c.Services().Tags.GetAll()
- if err != nil {
+ return func(c *web.Context) error {
+ getAllTags := &query.GetAllTags{}
+ if err := bus.Dispatch(c, getAllTags); err != nil {
return c.Failure(err)
}
@@ -16,7 +18,7 @@ func ManageTags() web.HandlerFunc {
Title: "Manage Tags · Site Settings",
ChunkName: "ManageTags.page",
Data: web.Map{
- "tags": tags,
+ "tags": getAllTags.Result,
},
})
}
diff --git a/app/handlers/user.go b/app/handlers/user.go
index abb7c5573..d4fd646b6 100644
--- a/app/handlers/user.go
+++ b/app/handlers/user.go
@@ -1,18 +1,20 @@
package handlers
import (
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/web"
)
// BlockUser is used to block an existing user from using Fider
func BlockUser() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
userID, err := c.ParamAsInt("userID")
if err != nil {
return c.NotFound()
}
- err = c.Services().Users.Block(userID)
+ err = bus.Dispatch(c, &cmd.BlockUser{UserID: userID})
if err != nil {
return c.Failure(err)
}
@@ -23,13 +25,13 @@ func BlockUser() web.HandlerFunc {
// UnblockUser is used to unblock an existing user so they can use Fider again
func UnblockUser() web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
userID, err := c.ParamAsInt("userID")
if err != nil {
return c.NotFound()
}
- err = c.Services().Users.Unblock(userID)
+ err = bus.Dispatch(c, &cmd.UnblockUser{UserID: userID})
if err != nil {
return c.Failure(err)
}
diff --git a/app/middlewares/auth.go b/app/middlewares/auth.go
index fa9f68309..41d62c517 100644
--- a/app/middlewares/auth.go
+++ b/app/middlewares/auth.go
@@ -1,14 +1,14 @@
package middlewares
import (
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/pkg/web"
)
// IsAuthenticated blocks non-authenticated requests
func IsAuthenticated() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
if !c.IsAuthenticated() {
return c.Unauthorized()
}
@@ -18,9 +18,9 @@ func IsAuthenticated() web.MiddlewareFunc {
}
// IsAuthorized blocks non-authorized requests
-func IsAuthorized(roles ...models.Role) web.MiddlewareFunc {
+func IsAuthorized(roles ...enum.Role) web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
user := c.User()
for _, role := range roles {
if user.Role == role {
diff --git a/app/middlewares/auth_test.go b/app/middlewares/auth_test.go
index 79b1185c6..86f24b404 100644
--- a/app/middlewares/auth_test.go
+++ b/app/middlewares/auth_test.go
@@ -5,7 +5,7 @@ import (
"testing"
"github.com/getfider/fider/app/middlewares"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/pkg/web"
@@ -14,9 +14,9 @@ import (
func TestIsAuthorized_WithAllowedRole(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
- server.Use(middlewares.IsAuthorized(models.RoleAdministrator, models.RoleCollaborator))
- status, _ := server.AsUser(mock.JonSnow).Execute(func(c web.Context) error {
+ server := mock.NewServer()
+ server.Use(middlewares.IsAuthorized(enum.RoleAdministrator, enum.RoleCollaborator))
+ status, _ := server.AsUser(mock.JonSnow).Execute(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -26,9 +26,9 @@ func TestIsAuthorized_WithAllowedRole(t *testing.T) {
func TestIsAuthorized_WithForbiddenRole(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
- server.Use(middlewares.IsAuthorized(models.RoleAdministrator, models.RoleCollaborator))
- status, _ := server.AsUser(mock.AryaStark).Execute(func(c web.Context) error {
+ server := mock.NewServer()
+ server.Use(middlewares.IsAuthorized(enum.RoleAdministrator, enum.RoleCollaborator))
+ status, _ := server.AsUser(mock.AryaStark).Execute(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -38,9 +38,9 @@ func TestIsAuthorized_WithForbiddenRole(t *testing.T) {
func TestIsAuthenticated_WithUser(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.IsAuthenticated())
- status, _ := server.AsUser(mock.AryaStark).Execute(func(c web.Context) error {
+ status, _ := server.AsUser(mock.AryaStark).Execute(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -50,10 +50,10 @@ func TestIsAuthenticated_WithUser(t *testing.T) {
func TestIsAuthenticated_WithoutUser(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.IsAuthenticated())
- status, _ := server.Execute(func(c web.Context) error {
+ status, _ := server.Execute(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
diff --git a/app/middlewares/cache.go b/app/middlewares/cache.go
index f0a6fa1d1..0dbe466cd 100644
--- a/app/middlewares/cache.go
+++ b/app/middlewares/cache.go
@@ -10,7 +10,7 @@ import (
// ClientCache adds Cache-Control header for X seconds
func ClientCache(d time.Duration) web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
c.Response.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%.f", d.Seconds()))
return next(c)
}
diff --git a/app/middlewares/cache_test.go b/app/middlewares/cache_test.go
index e70db6fec..cb1811e13 100644
--- a/app/middlewares/cache_test.go
+++ b/app/middlewares/cache_test.go
@@ -14,9 +14,9 @@ import (
func TestCache(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.ClientCache(5 * time.Minute))
- handler := func(c web.Context) error {
+ handler := func(c *web.Context) error {
return c.NoContent(http.StatusOK)
}
diff --git a/app/middlewares/common.go b/app/middlewares/common.go
index b3c9d8296..b4bf54d35 100644
--- a/app/middlewares/common.go
+++ b/app/middlewares/common.go
@@ -8,7 +8,7 @@ import (
// RequireBillingEnabled returns 404 if billing is not enabled, otherwise it continues the chain
func RequireBillingEnabled() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
if !env.IsBillingEnabled() || c.Tenant().Billing == nil {
return c.NotFound()
}
diff --git a/app/middlewares/compress.go b/app/middlewares/compress.go
index e3c57c486..be17b7581 100644
--- a/app/middlewares/compress.go
+++ b/app/middlewares/compress.go
@@ -31,7 +31,7 @@ func Compress() web.MiddlewareFunc {
pool.New = func() interface{} {
return gzip.NewWriter(ioutil.Discard)
}
- return func(c web.Context) error {
+ return func(c *web.Context) error {
res := c.Response
if strings.Contains(c.Request.GetHeader("Accept-Encoding"), "gzip") {
writer := pool.Get().(*gzip.Writer)
@@ -65,7 +65,7 @@ func (w *gzipResponseWriter) Flush() {
w.writer.Reset(w.response)
w.buffer.WriteTo(w.writer)
w.writer.Close()
- } else {
+ } else if w.code > 0 {
w.response.WriteHeader(w.code)
w.buffer.WriteTo(w.response)
}
diff --git a/app/middlewares/compress_test.go b/app/middlewares/compress_test.go
index f571d330e..fb0fa1233 100644
--- a/app/middlewares/compress_test.go
+++ b/app/middlewares/compress_test.go
@@ -20,9 +20,9 @@ func TestCompress(t *testing.T) {
data += "Hello World\n"
}
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.Compress())
- handler := func(c web.Context) error {
+ handler := func(c *web.Context) error {
return c.String(http.StatusOK, data)
}
@@ -41,9 +41,9 @@ func TestCompress(t *testing.T) {
func TestCompress_SmallResponse(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.Compress())
- handler := func(c web.Context) error {
+ handler := func(c *web.Context) error {
return c.String(http.StatusOK, "Hello World")
}
diff --git a/app/middlewares/cors.go b/app/middlewares/cors.go
index dd39d93fc..9afe79639 100644
--- a/app/middlewares/cors.go
+++ b/app/middlewares/cors.go
@@ -7,7 +7,7 @@ import (
// CORS adds Cross-Origin Resource Sharing response headers
func CORS() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
c.Response.Header().Set("Access-Control-Allow-Origin", "*")
c.Response.Header().Set("Access-Control-Allow-Methods", "GET")
return next(c)
diff --git a/app/middlewares/cors_test.go b/app/middlewares/cors_test.go
index aececf5c3..d2efda72e 100644
--- a/app/middlewares/cors_test.go
+++ b/app/middlewares/cors_test.go
@@ -13,9 +13,9 @@ import (
func TestCORS(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.CORS())
- handler := func(c web.Context) error {
+ handler := func(c *web.Context) error {
return c.NoContent(http.StatusOK)
}
diff --git a/app/middlewares/maintenance.go b/app/middlewares/maintenance.go
index 3b71c8430..fc18f9c2e 100644
--- a/app/middlewares/maintenance.go
+++ b/app/middlewares/maintenance.go
@@ -10,7 +10,7 @@ import (
// Maintenance returns a maintenance page when system is under maintenance
func Maintenance() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
if env.Config.Maintenance.Enabled == false {
return next(c)
}
diff --git a/app/middlewares/maintenance_test.go b/app/middlewares/maintenance_test.go
index df905b2e4..bdce5ef8d 100644
--- a/app/middlewares/maintenance_test.go
+++ b/app/middlewares/maintenance_test.go
@@ -15,9 +15,9 @@ import (
func TestMaintenance_Disabled(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.Maintenance())
- handler := func(c web.Context) error {
+ handler := func(c *web.Context) error {
return c.NoContent(http.StatusOK)
}
@@ -33,11 +33,11 @@ func TestMaintenance_Enabled(t *testing.T) {
env.Config.Maintenance.Enabled = false
}()
- server, _ := mock.NewServer()
+ server := mock.NewServer()
env.Config.Maintenance.Enabled = true
server.Use(middlewares.ClientCache(30 * time.Hour))
server.Use(middlewares.Maintenance())
- handler := func(c web.Context) error {
+ handler := func(c *web.Context) error {
return c.NoContent(http.StatusOK)
}
diff --git a/app/middlewares/panic.go b/app/middlewares/panic.go
new file mode 100644
index 000000000..aea50b9e3
--- /dev/null
+++ b/app/middlewares/panic.go
@@ -0,0 +1,30 @@
+package middlewares
+
+import (
+ "time"
+
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/log"
+ "github.com/getfider/fider/app/pkg/web"
+)
+
+func CatchPanic() web.MiddlewareFunc {
+ return func(next web.HandlerFunc) web.HandlerFunc {
+ return func(c *web.Context) error {
+ defer func() {
+ if r := recover(); r != nil {
+ c.Failure(errors.Panicked(r))
+ c.Rollback()
+ log.Infof(c, "@{HttpMethod:magenta} @{URL:magenta} panicked in @{ElapsedMs:magenta}ms (rolled back)", dto.Props{
+ "HttpMethod": c.Request.Method,
+ "URL": c.Request.URL.String(),
+ "ElapsedMs": time.Since(c.Request.StartTime).Nanoseconds() / int64(time.Millisecond),
+ })
+ }
+ }()
+
+ return next(c)
+ }
+ }
+}
diff --git a/app/middlewares/panic_test.go b/app/middlewares/panic_test.go
new file mode 100644
index 000000000..f955df143
--- /dev/null
+++ b/app/middlewares/panic_test.go
@@ -0,0 +1,36 @@
+package middlewares_test
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/getfider/fider/app/middlewares"
+ "github.com/getfider/fider/app/pkg/mock"
+ "github.com/getfider/fider/app/pkg/web"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+)
+
+func TestCatchPanic_Success(t *testing.T) {
+ RegisterT(t)
+
+ server := mock.NewServer()
+ server.Use(middlewares.CatchPanic())
+ status, _ := server.Execute(func(c *web.Context) error {
+ return c.Ok(web.Map{})
+ })
+
+ Expect(status).Equals(http.StatusOK)
+}
+
+func TestCatchPanic_Panic(t *testing.T) {
+ RegisterT(t)
+
+ server := mock.NewServer()
+ server.Use(middlewares.CatchPanic())
+ status, _ := server.Execute(func(c *web.Context) error {
+ panic("Boom!")
+ })
+
+ Expect(status).Equals(http.StatusInternalServerError)
+}
diff --git a/app/middlewares/security.go b/app/middlewares/security.go
index f90b696c3..04e4ec67a 100644
--- a/app/middlewares/security.go
+++ b/app/middlewares/security.go
@@ -11,7 +11,7 @@ import (
// Secure adds web security related Http Headers to response
func Secure() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
cdnHost := env.Config.CDN.Host
if cdnHost != "" && !env.IsSingleHostMode() {
cdnHost = "*." + cdnHost
diff --git a/app/middlewares/security_test.go b/app/middlewares/security_test.go
index f15774b2a..269d4d297 100644
--- a/app/middlewares/security_test.go
+++ b/app/middlewares/security_test.go
@@ -14,11 +14,11 @@ import (
func TestSecureWithoutCDN(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.Secure())
var ctxID string
- status, response := server.Execute(func(c web.Context) error {
+ status, response := server.Execute(func(c *web.Context) error {
ctxID = c.ContextID()
return c.NoContent(http.StatusOK)
})
@@ -37,11 +37,11 @@ func TestSecureWithCDN(t *testing.T) {
env.Config.CDN.Host = "test.fider.io"
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.Secure())
var ctxID string
- status, response := server.Execute(func(c web.Context) error {
+ status, response := server.Execute(func(c *web.Context) error {
ctxID = c.ContextID()
return c.NoContent(http.StatusOK)
})
@@ -60,11 +60,11 @@ func TestSecureWithCDN_SingleHost(t *testing.T) {
env.Config.CDN.Host = "test.fider.io"
- server, _ := mock.NewSingleTenantServer()
+ server := mock.NewSingleTenantServer()
server.Use(middlewares.Secure())
var ctxID string
- status, response := server.Execute(func(c web.Context) error {
+ status, response := server.Execute(func(c *web.Context) error {
ctxID = c.ContextID()
return c.NoContent(http.StatusOK)
})
diff --git a/app/middlewares/session.go b/app/middlewares/session.go
index ff5716a6d..212dbfa79 100644
--- a/app/middlewares/session.go
+++ b/app/middlewares/session.go
@@ -11,7 +11,7 @@ import (
// Session starts a new Session if an Session ID is not yet set
func Session() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
cookie, err := c.Request.Cookie(web.CookieSessionName)
if err != nil {
nextYear := time.Now().Add(365 * 24 * time.Hour)
diff --git a/app/middlewares/session_test.go b/app/middlewares/session_test.go
index e39924e23..3d8ae69df 100644
--- a/app/middlewares/session_test.go
+++ b/app/middlewares/session_test.go
@@ -14,11 +14,11 @@ import (
func TestSession_New(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.Session())
var sessionID string
- status, response := server.Execute(func(c web.Context) error {
+ status, response := server.Execute(func(c *web.Context) error {
sessionID = c.SessionID()
return c.NoContent(http.StatusOK)
})
@@ -35,12 +35,12 @@ func TestSession_New(t *testing.T) {
func TestSession_ExistingSession(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.Session())
status, response := server.
AddCookie(web.CookieSessionName, "MY_SESSION_VALUE").
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -51,11 +51,11 @@ func TestSession_ExistingSession(t *testing.T) {
func TestSession_RemoveSessionIfResponseIsCached(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.Session())
server.Use(middlewares.ClientCache(30 * time.Hour))
- status, response := server.Execute(func(c web.Context) error {
+ status, response := server.Execute(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
diff --git a/app/middlewares/setup.go b/app/middlewares/setup.go
index bcff86819..45f6b6fd2 100644
--- a/app/middlewares/setup.go
+++ b/app/middlewares/setup.go
@@ -1,82 +1,56 @@
package middlewares
import (
- "fmt"
"time"
+ "github.com/getfider/fider/app/pkg/dbx"
+
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/pkg/billing"
- "github.com/getfider/fider/app/pkg/di"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/web"
- webutil "github.com/getfider/fider/app/pkg/web/util"
"github.com/getfider/fider/app/pkg/worker"
- "github.com/getfider/fider/app/storage/postgres"
)
-// Noop does nothing
-func Noop() web.MiddlewareFunc {
- return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
- return next(c)
- }
- }
-}
-
//WorkerSetup current context with some services
func WorkerSetup() worker.MiddlewareFunc {
return func(next worker.Job) worker.Job {
return func(c *worker.Context) (err error) {
start := time.Now()
- c.Logger().Debugf("Task '@{TaskName:magenta}' started on worker '@{WorkerID:magenta}'", log.Props{
+ log.Debugf(c, "Task '@{TaskName:magenta}' started on worker '@{WorkerID:magenta}'", dto.Props{
"TaskName": c.TaskName(),
"WorkerID": c.WorkerID(),
})
- trx, err := c.Database().Begin()
+ trx, err := dbx.BeginTx(c)
if err != nil {
err = c.Failure(err)
- c.Logger().Debugf("Task '@{TaskName:magenta}' finished in @{ElapsedMs:magenta}ms", log.Props{
+ log.Debugf(c, "Task '@{TaskName:magenta}' finished in @{ElapsedMs:magenta}ms", dto.Props{
"TaskName": c.TaskName(),
"ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
})
return err
}
- trx.SetLogger(c.Logger())
-
//In case it panics somewhere
defer func() {
if r := recover(); r != nil {
- err, ok := r.(error)
- if !ok {
- err = fmt.Errorf("%v", r)
- }
- c.Failure(err)
+ c.Failure(errors.Panicked(r))
trx.Rollback()
- c.Logger().Debugf("Task '@{TaskName:magenta}' panicked in @{ElapsedMs:magenta}ms (rolled back)", log.Props{
+ log.Debugf(c, "Task '@{TaskName:magenta}' panicked in @{ElapsedMs:magenta}ms (rolled back)", dto.Props{
"TaskName": c.TaskName(),
"ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
})
}
}()
- c.SetServices(&app.Services{
- Logger: c.Logger(),
- Tenants: postgres.NewTenantStorage(trx),
- Users: postgres.NewUserStorage(trx, c),
- Posts: postgres.NewPostStorage(trx, c),
- Tags: postgres.NewTagStorage(trx),
- Notifications: postgres.NewNotificationStorage(trx),
- Emailer: di.NewEmailer(c.Logger()),
- Blobs: di.NewBlobStorage(c.Database()),
- Billing: billing.NewClient(),
- })
+ c.Set(app.TransactionCtxKey, trx)
//Execute the chain
if err = next(c); err != nil {
trx.Rollback()
- c.Logger().Debugf("Task '@{TaskName:magenta}' finished in @{ElapsedMs:magenta}ms (rolled back)", log.Props{
+ log.Debugf(c, "Task '@{TaskName:magenta}' finished in @{ElapsedMs:magenta}ms (rolled back)", dto.Props{
"TaskName": c.TaskName(),
"ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
})
@@ -85,10 +59,10 @@ func WorkerSetup() worker.MiddlewareFunc {
//No errors, so try to commit it
if err = trx.Commit(); err != nil {
- c.Logger().Errorf("Failed to commit request with: @{Error}", log.Props{
+ log.Errorf(c, "Failed to commit request with: @{Error}", dto.Props{
"Error": err.Error(),
})
- c.Logger().Debugf("Task '@{TaskName:magenta}' finished in @{ElapsedMs:magenta}ms (rolled back)", log.Props{
+ log.Debugf(c, "Task '@{TaskName:magenta}' finished in @{ElapsedMs:magenta}ms (rolled back)", dto.Props{
"TaskName": c.TaskName(),
"ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
})
@@ -96,7 +70,7 @@ func WorkerSetup() worker.MiddlewareFunc {
}
//Still no errors, everything is fine!
- c.Logger().Debugf("Task '@{TaskName:magenta}' finished in @{ElapsedMs:magenta}ms (committed)", log.Props{
+ log.Debugf(c, "Task '@{TaskName:magenta}' finished in @{ElapsedMs:magenta}ms (committed)", dto.Props{
"TaskName": c.TaskName(),
"ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
})
@@ -108,90 +82,55 @@ func WorkerSetup() worker.MiddlewareFunc {
//WebSetup current context with some services
func WebSetup() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
- start := time.Now()
- c.Logger().Infof("@{HttpMethod:magenta} @{URL:magenta} started for @{ClientIP:magenta}", log.Props{
+ return func(c *web.Context) error {
+ log.Infof(c, "@{HttpMethod:magenta} @{URL:magenta} started for @{ClientIP:magenta}", dto.Props{
"HttpMethod": c.Request.Method,
"URL": c.Request.URL.String(),
"ClientIP": c.Request.ClientIP,
})
- //In case it panics somewhere
- defer func() {
- if r := recover(); r != nil {
- err, ok := r.(error)
- if !ok {
- err = fmt.Errorf("%v", r)
- }
- c.Failure(err)
- c.Rollback()
- c.Logger().Infof("@{HttpMethod:magenta} @{URL:magenta} panicked in @{ElapsedMs:magenta}ms (rolled back)", log.Props{
- "HttpMethod": c.Request.Method,
- "URL": c.Request.URL.String(),
- "ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
- })
- }
- }()
-
- trx, err := c.Engine().Database().Begin()
+ trx, err := dbx.BeginTx(c)
if err != nil {
err = c.Failure(err)
- c.Logger().Infof("@{HttpMethod:magenta} @{URL:magenta} finished in @{ElapsedMs:magenta}ms", log.Props{
+ log.Infof(c, "@{HttpMethod:magenta} @{URL:magenta} finished in @{ElapsedMs:magenta}ms", dto.Props{
"HttpMethod": c.Request.Method,
"URL": c.Request.URL.String(),
- "ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
+ "ElapsedMs": time.Since(c.Request.StartTime).Nanoseconds() / int64(time.Millisecond),
})
return err
}
- trx.SetLogger(c.Logger())
-
- oauthBaseURL := webutil.GetOAuthBaseURL(c)
- tenantStorage := postgres.NewTenantStorage(trx)
-
- c.SetActiveTransaction(trx)
- c.SetServices(&app.Services{
- Logger: c.Logger(),
- Tenants: tenantStorage,
- OAuth: web.NewOAuthService(oauthBaseURL, tenantStorage),
- Users: postgres.NewUserStorage(trx, &c),
- Posts: postgres.NewPostStorage(trx, &c),
- Tags: postgres.NewTagStorage(trx),
- Notifications: postgres.NewNotificationStorage(trx),
- Emailer: di.NewEmailer(c.Logger()),
- Blobs: di.NewBlobStorage(c.Engine().Database()),
- Billing: billing.NewClient(),
- })
+ c.Set(app.TransactionCtxKey, trx)
//Execute the chain
if err := next(c); err != nil {
c.Rollback()
- c.Logger().Infof("@{HttpMethod:magenta} @{URL:magenta} finished in @{ElapsedMs:magenta}ms (rolled back)", log.Props{
+ log.Infof(c, "@{HttpMethod:magenta} @{URL:magenta} finished in @{ElapsedMs:magenta}ms (rolled back)", dto.Props{
"HttpMethod": c.Request.Method,
"URL": c.Request.URL.String(),
- "ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
+ "ElapsedMs": time.Since(c.Request.StartTime).Nanoseconds() / int64(time.Millisecond),
})
return err
}
//No errors, so try to commit it
if err := c.Commit(); err != nil {
- c.Logger().Errorf("Failed to commit request with: @{Error}", log.Props{
+ log.Errorf(c, "Failed to commit request with: @{Error}", dto.Props{
"Error": err.Error(),
})
- c.Logger().Infof("@{HttpMethod:magenta} @{URL:magenta} finished in @{ElapsedMs:magenta}ms (rolled back)", log.Props{
+ log.Infof(c, "@{HttpMethod:magenta} @{URL:magenta} finished in @{ElapsedMs:magenta}ms (rolled back)", dto.Props{
"HttpMethod": c.Request.Method,
"URL": c.Request.URL.String(),
- "ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
+ "ElapsedMs": time.Since(c.Request.StartTime).Nanoseconds() / int64(time.Millisecond),
})
return err
}
//Still no errors, everything is fine!
- c.Logger().Infof("@{HttpMethod:magenta} @{URL:magenta} finished in @{ElapsedMs:magenta}ms (committed)", log.Props{
+ log.Infof(c, "@{HttpMethod:magenta} @{URL:magenta} finished in @{ElapsedMs:magenta}ms (committed)", dto.Props{
"HttpMethod": c.Request.Method,
"URL": c.Request.URL.String(),
- "ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
+ "ElapsedMs": time.Since(c.Request.StartTime).Nanoseconds() / int64(time.Millisecond),
})
return nil
}
diff --git a/app/middlewares/setup_test.go b/app/middlewares/setup_test.go
index a6738bd79..97304b67b 100644
--- a/app/middlewares/setup_test.go
+++ b/app/middlewares/setup_test.go
@@ -1,14 +1,16 @@
package middlewares_test
import (
+ "context"
"errors"
"net/http"
"testing"
+ "github.com/getfider/fider/app"
+
"github.com/getfider/fider/app/middlewares"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/dbx"
- "github.com/getfider/fider/app/pkg/log/noop"
"github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/pkg/web"
"github.com/getfider/fider/app/pkg/worker"
@@ -17,10 +19,12 @@ import (
func TestWebSetup(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.WebSetup())
- status, _ := server.Execute(func(c web.Context) error {
- Expect(c.ActiveTransaction()).IsNotNil()
+ status, _ := server.Execute(func(c *web.Context) error {
+ trx, ok := c.Value(app.TransactionCtxKey).(*dbx.Trx)
+ Expect(ok).IsTrue()
+ Expect(trx).IsNotNil()
return c.NoContent(http.StatusOK)
})
@@ -30,33 +34,21 @@ func TestWebSetup(t *testing.T) {
func TestWebSetup_Failure(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.WebSetup())
- status, _ := server.Execute(func(c web.Context) error {
+ status, _ := server.Execute(func(c *web.Context) error {
return c.Failure(errors.New("Something went wrong..."))
})
Expect(status).Equals(http.StatusInternalServerError)
}
-func TestWebSetup_Panic(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
- server.Use(middlewares.WebSetup())
- status, _ := server.Execute(func(c web.Context) error {
- panic("Boom!")
- })
-
- Expect(status).Equals(http.StatusInternalServerError)
-}
-
func TestWebSetup_NotQueueTask_OnFailure(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.WebSetup())
- status, _ := server.Execute(func(c web.Context) error {
+ status, _ := server.Execute(func(c *web.Context) error {
c.Enqueue(mock.NewNoopTask())
return c.Failure(errors.New("Something went wrong..."))
})
@@ -68,9 +60,9 @@ func TestWebSetup_NotQueueTask_OnFailure(t *testing.T) {
func TestWebSetup_QueueTask_OnSuccess(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.WebSetup())
- status, _ := server.Execute(func(c web.Context) error {
+ status, _ := server.Execute(func(c *web.Context) error {
c.Enqueue(mock.NewNoopTask())
return c.Ok(web.Map{})
})
@@ -82,10 +74,10 @@ func TestWebSetup_QueueTask_OnSuccess(t *testing.T) {
func TestWorkerSetup(t *testing.T) {
RegisterT(t)
- c := worker.NewContext("0", worker.Task{Name: "Any Task"}, dbx.New(), noop.NewLogger())
+ c := worker.NewContext(context.Background(), "0", worker.Task{Name: "Any Task"})
mw := middlewares.WorkerSetup()
err := mw(func(c *worker.Context) error {
- Expect(c.Services()).IsNotNil()
+ Expect(c.Value(app.TransactionCtxKey)).IsNotNil()
return nil
})(c)
Expect(err).IsNil()
@@ -94,10 +86,10 @@ func TestWorkerSetup(t *testing.T) {
func TestWorkerSetup_Failure(t *testing.T) {
RegisterT(t)
- c := worker.NewContext("0", worker.Task{Name: "Any Task"}, dbx.New(), noop.NewLogger())
+ c := worker.NewContext(context.Background(), "0", worker.Task{Name: "Any Task"})
mw := middlewares.WorkerSetup()
err := mw(func(c *worker.Context) error {
- Expect(c.Services()).IsNotNil()
+ Expect(c.Value(app.TransactionCtxKey)).IsNotNil()
return errors.New("Not Found")
})(c)
Expect(err).IsNotNil()
diff --git a/app/middlewares/tenant.go b/app/middlewares/tenant.go
index 36f1ce40a..da1be8a9e 100644
--- a/app/middlewares/tenant.go
+++ b/app/middlewares/tenant.go
@@ -3,9 +3,11 @@ package middlewares
import (
"net/http"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/web"
@@ -22,14 +24,15 @@ func Tenant() web.MiddlewareFunc {
// SingleTenant inject default tenant into current context
func SingleTenant() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
- tenant, err := c.Services().Tenants.First()
+ return func(c *web.Context) error {
+ firstTenant := &query.GetFirstTenant{}
+ err := bus.Dispatch(c, firstTenant)
if err != nil && errors.Cause(err) != app.ErrNotFound {
return c.Failure(err)
}
- if tenant != nil {
- c.SetTenant(tenant)
+ if firstTenant.Result != nil {
+ c.SetTenant(firstTenant.Result)
}
return next(c)
@@ -40,7 +43,7 @@ func SingleTenant() web.MiddlewareFunc {
// MultiTenant extract tenant information from hostname and inject it into current context
func MultiTenant() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
hostname := c.Request.URL.Hostname()
// If no tenant is specified, redirect user to getfider.com
@@ -52,16 +55,17 @@ func MultiTenant() web.MiddlewareFunc {
}
}
- tenant, err := c.Services().Tenants.GetByDomain(hostname)
+ byDomain := &query.GetTenantByDomain{Domain: hostname}
+ err := bus.Dispatch(c, byDomain)
if err != nil && errors.Cause(err) != app.ErrNotFound {
return c.Failure(err)
}
- if tenant != nil {
- c.SetTenant(tenant)
+ if byDomain.Result != nil {
+ c.SetTenant(byDomain.Result)
- if tenant.CNAME != "" && !c.IsAjax() {
- baseURL := c.TenantBaseURL(tenant)
+ if byDomain.Result.CNAME != "" && !c.IsAjax() {
+ baseURL := web.TenantBaseURL(c, byDomain.Result)
if baseURL != c.BaseURL() {
link := baseURL + c.Request.URL.RequestURI()
c.SetCanonicalURL(link)
@@ -77,7 +81,7 @@ func MultiTenant() web.MiddlewareFunc {
// RequireTenant returns 404 if tenant is not available
func RequireTenant() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
if c.Tenant() == nil {
if env.IsSingleHostMode() {
return c.Redirect("/signup")
@@ -92,8 +96,8 @@ func RequireTenant() web.MiddlewareFunc {
// BlockPendingTenants blocks requests for pending tenants
func BlockPendingTenants() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
- if c.Tenant().Status == models.TenantPending {
+ return func(c *web.Context) error {
+ if c.Tenant().Status == enum.TenantPending {
return c.Render(http.StatusOK, "pending-activation.html", web.Props{
Title: "Pending Activation",
Description: "We sent you a confirmation email with a link to activate your site. Please check your inbox to activate it.",
@@ -107,7 +111,7 @@ func BlockPendingTenants() web.MiddlewareFunc {
// CheckTenantPrivacy blocks requests of unauthenticated users for private tenants
func CheckTenantPrivacy() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
if c.Tenant().IsPrivate && !c.IsAuthenticated() {
return c.Redirect("/signin")
}
@@ -119,13 +123,13 @@ func CheckTenantPrivacy() web.MiddlewareFunc {
// BlockLockedTenants blocks requests of non-administrator users on locked tenants
func BlockLockedTenants() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
- if c.Tenant().Status == models.TenantLocked {
+ return func(c *web.Context) error {
+ if c.Tenant().Status == enum.TenantLocked {
if c.Request.IsAPI() {
return c.JSON(http.StatusLocked, web.Map{})
}
- isAdmin := c.IsAuthenticated() && c.User().Role == models.RoleAdministrator
+ isAdmin := c.IsAuthenticated() && c.User().Role == enum.RoleAdministrator
if !isAdmin {
return c.Redirect("/signin")
}
diff --git a/app/middlewares/tenant_test.go b/app/middlewares/tenant_test.go
index 26ec3da4f..7cbf7ce8f 100644
--- a/app/middlewares/tenant_test.go
+++ b/app/middlewares/tenant_test.go
@@ -1,13 +1,18 @@
package middlewares_test
import (
+ "context"
"errors"
"net/http"
"testing"
+ "github.com/getfider/fider/app"
"github.com/getfider/fider/app/middlewares"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/pkg/web"
)
@@ -36,13 +41,24 @@ var testCases = []struct {
func TestMultiTenant(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.GetTenantByDomain) error {
+ if q.Domain == "avengers.test.fider.io" {
+ q.Result = mock.AvengersTenant
+ return nil
+ } else if q.Domain == "demo.test.fider.io" {
+ q.Result = mock.DemoTenant
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
for _, testCase := range testCases {
for _, url := range testCase.urls {
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.MultiTenant())
- status, response := server.WithURL(url).Execute(func(c web.Context) error {
+ status, response := server.WithURL(url).Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.Tenant().Name)
})
@@ -55,10 +71,18 @@ func TestMultiTenant(t *testing.T) {
func TestMultiTenant_SubSubDomain(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.GetTenantByDomain) error {
+ if q.Domain == "demo.test.fider.io" {
+ q.Result = mock.DemoTenant
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
server.Use(middlewares.MultiTenant())
- status, _ := server.WithURL("http://demo.demo.test.fider.io").Execute(func(c web.Context) error {
+ status, _ := server.WithURL("http://demo.demo.test.fider.io").Execute(func(c *web.Context) error {
if c.Tenant() == nil {
return c.Ok(web.Map{})
}
@@ -71,10 +95,14 @@ func TestMultiTenant_SubSubDomain(t *testing.T) {
func TestMultiTenant_UnknownDomain(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.GetTenantByDomain) error {
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
server.Use(middlewares.MultiTenant())
- status, _ := server.WithURL("http://somedomain.com").Execute(func(c web.Context) error {
+ status, _ := server.WithURL("http://somedomain.com").Execute(func(c *web.Context) error {
if c.Tenant() == nil {
return c.Ok(web.Map{})
}
@@ -87,6 +115,17 @@ func TestMultiTenant_UnknownDomain(t *testing.T) {
func TestMultiTenant_CanonicalHeader(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.GetTenantByDomain) error {
+ if q.Domain == "avengers.test.fider.io" {
+ q.Result = mock.AvengersTenant
+ return nil
+ } else if q.Domain == "demo.test.fider.io" {
+ q.Result = mock.DemoTenant
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
var testCases = []struct {
input string
output string
@@ -125,7 +164,7 @@ func TestMultiTenant_CanonicalHeader(t *testing.T) {
}
for _, testCase := range testCases {
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.MultiTenant())
if testCase.isAjax {
@@ -135,8 +174,8 @@ func TestMultiTenant_CanonicalHeader(t *testing.T) {
var canonicalURL string
status, _ := server.
WithURL(testCase.input).
- Execute(func(c web.Context) error {
- canonicalURL, _ = c.Get("Canonical-URL").(string)
+ Execute(func(c *web.Context) error {
+ canonicalURL, _ = c.Value("Canonical-URL").(string)
return c.Ok(web.Map{})
})
@@ -148,10 +187,15 @@ func TestMultiTenant_CanonicalHeader(t *testing.T) {
func TestSingleTenant_NoTenants(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewSingleTenantServer()
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetFirstTenant) error {
+ return app.ErrNotFound
+ })
+
+ server := mock.NewSingleTenantServer()
server.Use(middlewares.SingleTenant())
- status, _ := server.WithURL("http://somedomain.com").Execute(func(c web.Context) error {
+ status, _ := server.WithURL("http://somedomain.com").Execute(func(c *web.Context) error {
if c.Tenant() == nil {
return c.Ok(web.Map{})
}
@@ -164,11 +208,15 @@ func TestSingleTenant_NoTenants(t *testing.T) {
func TestSingleTenant_WithTenants_ShouldSetFirstToContext(t *testing.T) {
RegisterT(t)
- server, services := mock.NewSingleTenantServer()
+ bus.AddHandler(func(ctx context.Context, q *query.GetFirstTenant) error {
+ q.Result = &models.Tenant{Name: "MyCompany", Subdomain: "mycompany", Status: enum.TenantActive}
+ return nil
+ })
+
+ server := mock.NewSingleTenantServer()
server.Use(middlewares.SingleTenant())
- services.Tenants.Add("MyCompany", "mycompany", models.TenantActive)
- status, response := server.WithURL("http://somedomain.com").Execute(func(c web.Context) error {
+ status, response := server.WithURL("http://somedomain.com").Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.Tenant().Name)
})
@@ -179,11 +227,11 @@ func TestSingleTenant_WithTenants_ShouldSetFirstToContext(t *testing.T) {
func TestBlockPendingTenants_Active(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
- mock.DemoTenant.Status = models.TenantActive
+ server := mock.NewServer()
+ mock.DemoTenant.Status = enum.TenantActive
server.Use(middlewares.BlockPendingTenants())
- status, _ := server.OnTenant(mock.DemoTenant).Execute(func(c web.Context) error {
+ status, _ := server.OnTenant(mock.DemoTenant).Execute(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -193,11 +241,11 @@ func TestBlockPendingTenants_Active(t *testing.T) {
func TestBlockPendingTenants_Pending(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
- mock.DemoTenant.Status = models.TenantPending
+ server := mock.NewServer()
+ mock.DemoTenant.Status = enum.TenantPending
server.Use(middlewares.BlockPendingTenants())
- status, _ := server.OnTenant(mock.DemoTenant).Execute(func(c web.Context) error {
+ status, _ := server.OnTenant(mock.DemoTenant).Execute(func(c *web.Context) error {
return c.NoContent(http.StatusTeapot)
})
@@ -207,29 +255,29 @@ func TestBlockPendingTenants_Pending(t *testing.T) {
func TestCheckTenantPrivacy_Private_Unauthenticated(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
mock.DemoTenant.IsPrivate = true
server.Use(middlewares.CheckTenantPrivacy())
- status, response := server.OnTenant(mock.DemoTenant).Execute(func(c web.Context) error {
+ status, response := server.OnTenant(mock.DemoTenant).Execute(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
Expect(status).Equals(http.StatusTemporaryRedirect)
- Expect(response.HeaderMap.Get("Location")).Equals("/signin")
+ Expect(response.Header().Get("Location")).Equals("/signin")
}
func TestCheckTenantPrivacy_Private_Authenticated(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
mock.DemoTenant.IsPrivate = true
server.Use(middlewares.CheckTenantPrivacy())
status, _ := server.
OnTenant(mock.DemoTenant).
AsUser(mock.AryaStark).
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -239,13 +287,13 @@ func TestCheckTenantPrivacy_Private_Authenticated(t *testing.T) {
func TestCheckTenantPrivacy_NotPrivate_Unauthenticated(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
mock.DemoTenant.IsPrivate = false
server.Use(middlewares.CheckTenantPrivacy())
status, _ := server.
OnTenant(mock.DemoTenant).
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -254,11 +302,16 @@ func TestCheckTenantPrivacy_NotPrivate_Unauthenticated(t *testing.T) {
func TestRequireTenant_MultiHostMode_NoTenants_404(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetTenantByDomain) error {
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
server.Use(middlewares.MultiTenant())
server.Use(middlewares.RequireTenant())
- status, _ := server.WithURL("http://somedomain.com").Execute(func(c web.Context) error {
+ status, _ := server.WithURL("http://somedomain.com").Execute(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -267,11 +320,20 @@ func TestRequireTenant_MultiHostMode_NoTenants_404(t *testing.T) {
func TestRequireTenant_MultiHostMode_ValidTenant(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetTenantByDomain) error {
+ if q.Domain == "avengers.test.fider.io" {
+ q.Result = mock.AvengersTenant
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
server.Use(middlewares.MultiTenant())
server.Use(middlewares.RequireTenant())
- status, response := server.WithURL("http://avengers.test.fider.io").Execute(func(c web.Context) error {
+ status, response := server.WithURL("http://avengers.test.fider.io").Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.Tenant().Name)
})
@@ -281,25 +343,36 @@ func TestRequireTenant_MultiHostMode_ValidTenant(t *testing.T) {
func TestRequireTenant_SingleHostMode_NoTenants_RedirectToSignUp(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewSingleTenantServer()
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetFirstTenant) error {
+ return app.ErrNotFound
+ })
+
+ server := mock.NewSingleTenantServer()
server.Use(middlewares.SingleTenant())
server.Use(middlewares.RequireTenant())
- status, response := server.WithURL("http://somedomain.com").Execute(func(c web.Context) error {
+ status, response := server.WithURL("http://somedomain.com").Execute(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
Expect(status).Equals(http.StatusTemporaryRedirect)
- Expect(response.HeaderMap.Get("Location")).Equals("/signup")
+ Expect(response.Header().Get("Location")).Equals("/signup")
}
func TestRequireTenant_SingleHostMode_ValidTenant(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetFirstTenant) error {
+ q.Result = mock.DemoTenant
+ return nil
+ })
+
+ server := mock.NewServer()
server.Use(middlewares.SingleTenant())
server.Use(middlewares.RequireTenant())
- status, response := server.WithURL("http://demo.test.fider.io").Execute(func(c web.Context) error {
+ status, response := server.WithURL("http://demo.test.fider.io").Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.Tenant().Name)
})
@@ -309,13 +382,13 @@ func TestRequireTenant_SingleHostMode_ValidTenant(t *testing.T) {
func TestBlockLockedTenants_ActiveTenant(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.BlockLockedTenants())
status, response := server.
WithURL("http://demo.test.fider.io").
OnTenant(mock.DemoTenant).
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.Tenant().Name)
})
@@ -325,14 +398,14 @@ func TestBlockLockedTenants_ActiveTenant(t *testing.T) {
func TestBlockLockedTenants_LockedTenant(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.BlockLockedTenants())
- mock.DemoTenant.Status = models.TenantLocked
+ mock.DemoTenant.Status = enum.TenantLocked
status, response := server.
WithURL("http://demo.test.fider.io").
OnTenant(mock.DemoTenant).
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.Tenant().Name)
})
@@ -342,14 +415,14 @@ func TestBlockLockedTenants_LockedTenant(t *testing.T) {
func TestBlockLockedTenants_LockedTenant_APICall(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.BlockLockedTenants())
- mock.DemoTenant.Status = models.TenantLocked
+ mock.DemoTenant.Status = enum.TenantLocked
status, _ := server.
WithURL("http://demo.test.fider.io/api/v1/posts").
OnTenant(mock.DemoTenant).
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.Tenant().Name)
})
diff --git a/app/middlewares/user.go b/app/middlewares/user.go
index dfc767011..cd77164fa 100644
--- a/app/middlewares/user.go
+++ b/app/middlewares/user.go
@@ -5,6 +5,10 @@ import (
"strconv"
"strings"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+
"github.com/getfider/fider/app/pkg/validate"
"github.com/getfider/fider/app/models"
@@ -19,7 +23,7 @@ import (
// User gets JWT Auth token from cookie and insert into context
func User() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
var (
token string
user *models.User
@@ -39,11 +43,12 @@ func User() web.MiddlewareFunc {
claims, err := jwt.DecodeFiderClaims(token)
if err != nil {
c.RemoveCookie(web.CookieAuthName)
- c.SetClaims(claims)
return next(c)
}
- user, err = c.Services().Users.GetByID(claims.UserID)
+ userByClaimsID := &query.GetUserByID{UserID: claims.UserID}
+ err = bus.Dispatch(c, userByClaimsID)
+ user = userByClaimsID.Result
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
c.RemoveCookie(web.CookieAuthName)
@@ -56,13 +61,15 @@ func User() web.MiddlewareFunc {
parts := strings.Split(authHeader, "Bearer")
if len(parts) == 2 {
apiKey := strings.TrimSpace(parts[1])
- user, err = c.Services().Users.GetByAPIKey(apiKey)
+ getUserByAPIKey := &query.GetUserByAPIKey{APIKey: apiKey}
+ err = bus.Dispatch(c, getUserByAPIKey)
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
return c.HandleValidation(validate.Failed("API Key is invalid"))
}
return err
}
+ user = getUserByAPIKey.Result
if !user.IsCollaborator() {
return c.HandleValidation(validate.Failed("API Key is invalid"))
@@ -76,7 +83,9 @@ func User() web.MiddlewareFunc {
if err != nil {
return c.HandleValidation(validate.Failed(fmt.Sprintf("User not found for given impersonate UserID '%s'", impersonateUserIDStr)))
}
- user, err = c.Services().Users.GetByID(impersonateUserID)
+ userByImpersonateID := &query.GetUserByID{UserID: impersonateUserID}
+ err = bus.Dispatch(c, userByImpersonateID)
+ user = userByImpersonateID.Result
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
return c.HandleValidation(validate.Failed(fmt.Sprintf("User not found for given impersonate UserID '%s'", impersonateUserIDStr)))
@@ -90,13 +99,13 @@ func User() web.MiddlewareFunc {
if user != nil && c.Tenant() != nil && user.Tenant.ID == c.Tenant().ID {
// only administrators should be allowed to sign in to a locked tenant
- if c.Tenant().Status == models.TenantLocked && !user.IsAdministrator() {
+ if c.Tenant().Status == enum.TenantLocked && !user.IsAdministrator() {
c.RemoveCookie(web.CookieAuthName)
return c.Unauthorized()
}
// blocked users are unable to sign in
- if user.Status == models.UserBlocked {
+ if user.Status == enum.UserBlocked {
c.RemoveCookie(web.CookieAuthName)
return c.Unauthorized()
}
diff --git a/app/middlewares/user_test.go b/app/middlewares/user_test.go
index 1032f9839..87534b46e 100644
--- a/app/middlewares/user_test.go
+++ b/app/middlewares/user_test.go
@@ -1,15 +1,20 @@
package middlewares_test
import (
- "fmt"
+ "context"
"net/http"
"strconv"
"testing"
"time"
+ "github.com/getfider/fider/app"
+
"github.com/getfider/fider/app/middlewares"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/pkg/web"
@@ -18,9 +23,9 @@ import (
func TestUser_NoCookie(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
server.Use(middlewares.User())
- status, _ := server.Execute(func(c web.Context) error {
+ status, _ := server.Execute(func(c *web.Context) error {
if c.IsAuthenticated() {
return c.NoContent(http.StatusOK)
} else {
@@ -34,18 +39,26 @@ func TestUser_NoCookie(t *testing.T) {
func TestUser_WithCookie(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
token, _ := jwt.Encode(jwt.FiderClaims{
UserID: mock.JonSnow.ID,
UserName: mock.JonSnow.Name,
})
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ if q.UserID == mock.JonSnow.ID {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
server.Use(middlewares.User())
status, response := server.
OnTenant(mock.DemoTenant).
AddHeader("Accept", "application/json").
AddCookie(web.CookieAuthName, token).
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.User().Name)
})
@@ -57,19 +70,27 @@ func TestUser_WithCookie(t *testing.T) {
func TestUser_Blocked(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
- mock.JonSnow.Status = models.UserBlocked
+ server := mock.NewServer()
+ mock.JonSnow.Status = enum.UserBlocked
token, _ := jwt.Encode(jwt.FiderClaims{
UserID: mock.JonSnow.ID,
UserName: mock.JonSnow.Name,
})
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ if q.UserID == mock.JonSnow.ID {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
server.Use(middlewares.User())
status, _ := server.
OnTenant(mock.DemoTenant).
AddHeader("Accept", "application/json").
AddCookie(web.CookieAuthName, token).
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.User().Name)
})
@@ -79,19 +100,27 @@ func TestUser_Blocked(t *testing.T) {
func TestUser_LockedTenant_Administrator(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
- mock.DemoTenant.Status = models.TenantLocked
+ server := mock.NewServer()
+ mock.DemoTenant.Status = enum.TenantLocked
token, _ := jwt.Encode(jwt.FiderClaims{
UserID: mock.JonSnow.ID,
UserName: mock.JonSnow.Name,
})
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ if q.UserID == mock.JonSnow.ID {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
server.Use(middlewares.User())
status, response := server.
OnTenant(mock.DemoTenant).
AddHeader("Accept", "application/json").
AddCookie(web.CookieAuthName, token).
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.User().Name)
})
@@ -102,19 +131,27 @@ func TestUser_LockedTenant_Administrator(t *testing.T) {
func TestUser_LockedTenant_Visitor(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
- mock.DemoTenant.Status = models.TenantLocked
+ server := mock.NewServer()
+ mock.DemoTenant.Status = enum.TenantLocked
token, _ := jwt.Encode(jwt.FiderClaims{
UserID: mock.AryaStark.ID,
UserName: mock.AryaStark.Name,
})
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ if q.UserID == mock.AryaStark.ID {
+ q.Result = mock.AryaStark
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
server.Use(middlewares.User())
status, _ := server.
OnTenant(mock.DemoTenant).
AddHeader("Accept", "application/json").
AddCookie(web.CookieAuthName, token).
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.User().Name)
})
@@ -124,17 +161,25 @@ func TestUser_LockedTenant_Visitor(t *testing.T) {
func TestUser_WithCookie_InvalidUser(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
token, _ := jwt.Encode(jwt.FiderClaims{
UserID: 999,
UserName: "Unknown",
})
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ if q.UserID == mock.JonSnow.ID {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
server.Use(middlewares.User())
status, response := server.
OnTenant(mock.AvengersTenant).
AddCookie(web.CookieAuthName, token).
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
if c.User() == nil {
return c.NoContent(http.StatusNoContent)
}
@@ -148,17 +193,21 @@ func TestUser_WithCookie_InvalidUser(t *testing.T) {
func TestUser_WithCookie_DifferentTenant(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
token, _ := jwt.Encode(jwt.FiderClaims{
UserID: mock.JonSnow.ID,
UserName: mock.JonSnow.Name,
})
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ return app.ErrNotFound
+ })
+
server.Use(middlewares.User())
status, _ := server.
OnTenant(mock.AvengersTenant).
AddCookie(web.CookieAuthName, token).
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
if c.User() == nil {
return c.NoContent(http.StatusNoContent)
}
@@ -171,17 +220,25 @@ func TestUser_WithCookie_DifferentTenant(t *testing.T) {
func TestUser_WithSignUpCookie(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ server := mock.NewServer()
token, _ := jwt.Encode(jwt.FiderClaims{
UserID: mock.JonSnow.ID,
UserName: mock.JonSnow.Name,
})
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ if q.UserID == mock.JonSnow.ID {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
server.Use(middlewares.User())
status, response := server.
OnTenant(mock.DemoTenant).
AddCookie(web.CookieSignUpAuthName, token).
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.User().Name)
})
@@ -210,16 +267,22 @@ func TestUser_WithSignUpCookie(t *testing.T) {
func TestUser_ValidAPIKey(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.Users.SetCurrentUser(mock.JonSnow)
- apiKey, _ := services.Users.RegenerateAPIKey()
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByAPIKey) error {
+ if q.APIKey == "1234567890" {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
server.Use(middlewares.User())
status, response := server.
OnTenant(mock.DemoTenant).
WithURL("http://example.com/api/v1").
- AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
- Execute(func(c web.Context) error {
+ AddHeader("Authorization", "Bearer 1234567890").
+ Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.User().Name)
})
@@ -230,14 +293,18 @@ func TestUser_ValidAPIKey(t *testing.T) {
func TestUser_InvalidAPIKey(t *testing.T) {
RegisterT(t)
- server, _ := mock.NewServer()
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByAPIKey) error {
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
server.Use(middlewares.User())
status, query := server.
OnTenant(mock.DemoTenant).
WithURL("http://example.com/api/v1").
AddHeader("Authorization", "Bearer MY-KEY").
- ExecuteAsJSON(func(c web.Context) error {
+ ExecuteAsJSON(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -248,16 +315,18 @@ func TestUser_InvalidAPIKey(t *testing.T) {
func TestUser_ValidAPIKey_Visitor(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.Users.SetCurrentUser(mock.AryaStark)
- apiKey, _ := services.Users.RegenerateAPIKey()
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByAPIKey) error {
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
server.Use(middlewares.User())
status, query := server.
OnTenant(mock.DemoTenant).
WithURL("http://example.com/api/v1").
- AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
- ExecuteAsJSON(func(c web.Context) error {
+ AddHeader("Authorization", "Bearer 12345").
+ ExecuteAsJSON(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -268,25 +337,28 @@ func TestUser_ValidAPIKey_Visitor(t *testing.T) {
func TestUser_Impersonation_Collaborator(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- user := &models.User{
- Name: "The Collaborator",
- Role: models.RoleCollaborator,
- Status: models.UserActive,
- Tenant: mock.DemoTenant,
- }
- services.Users.SetCurrentTenant(mock.DemoTenant)
- services.Users.Register(user)
- services.Users.SetCurrentUser(user)
- apiKey, _ := services.Users.RegenerateAPIKey()
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByAPIKey) error {
+ if q.APIKey == "12345" {
+ q.Result = &models.User{
+ Name: "The Collaborator",
+ Role: enum.RoleCollaborator,
+ Status: enum.UserActive,
+ Tenant: mock.DemoTenant,
+ }
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
server.Use(middlewares.User())
status, query := server.
OnTenant(mock.DemoTenant).
WithURL("http://example.com/api/v1").
- AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
+ AddHeader("Authorization", "Bearer 12345").
AddHeader("X-Fider-UserID", strconv.Itoa(mock.JonSnow.ID)).
- ExecuteAsJSON(func(c web.Context) error {
+ ExecuteAsJSON(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -297,17 +369,23 @@ func TestUser_Impersonation_Collaborator(t *testing.T) {
func TestUser_Impersonation_InvalidUser(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.Users.SetCurrentUser(mock.JonSnow)
- apiKey, _ := services.Users.RegenerateAPIKey()
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByAPIKey) error {
+ if q.APIKey == "1234567890" {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
server.Use(middlewares.User())
status, query := server.
OnTenant(mock.DemoTenant).
WithURL("http://example.com/api/v1").
- AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
+ AddHeader("Authorization", "Bearer 1234567890").
AddHeader("X-Fider-UserID", "ABC").
- ExecuteAsJSON(func(c web.Context) error {
+ ExecuteAsJSON(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -318,17 +396,27 @@ func TestUser_Impersonation_InvalidUser(t *testing.T) {
func TestUser_Impersonation_UserNotFound(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.Users.SetCurrentUser(mock.JonSnow)
- apiKey, _ := services.Users.RegenerateAPIKey()
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByAPIKey) error {
+ if q.APIKey == "1234567890" {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
server.Use(middlewares.User())
status, query := server.
OnTenant(mock.DemoTenant).
WithURL("http://example.com/api/v1").
- AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
+ AddHeader("Authorization", "Bearer 1234567890").
AddHeader("X-Fider-UserID", "999").
- ExecuteAsJSON(func(c web.Context) error {
+ ExecuteAsJSON(func(c *web.Context) error {
return c.NoContent(http.StatusOK)
})
@@ -339,17 +427,31 @@ func TestUser_Impersonation_UserNotFound(t *testing.T) {
func TestUser_Impersonation_ValidUser(t *testing.T) {
RegisterT(t)
- server, services := mock.NewServer()
- services.Users.SetCurrentUser(mock.JonSnow)
- apiKey, _ := services.Users.RegenerateAPIKey()
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
+ if q.UserID == mock.AryaStark.ID {
+ q.Result = mock.AryaStark
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByAPIKey) error {
+ if q.APIKey == "1234567890" {
+ q.Result = mock.JonSnow
+ return nil
+ }
+ return app.ErrNotFound
+ })
+
+ server := mock.NewServer()
server.Use(middlewares.User())
status, response := server.
OnTenant(mock.DemoTenant).
WithURL("http://example.com/api/v1").
- AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
+ AddHeader("Authorization", "Bearer 1234567890").
AddHeader("X-Fider-UserID", strconv.Itoa(mock.AryaStark.ID)).
- Execute(func(c web.Context) error {
+ Execute(func(c *web.Context) error {
return c.String(http.StatusOK, c.User().Name)
})
diff --git a/app/models/cmd/attachment.go b/app/models/cmd/attachment.go
new file mode 100644
index 000000000..43c95cd7e
--- /dev/null
+++ b/app/models/cmd/attachment.go
@@ -0,0 +1,19 @@
+package cmd
+
+import "github.com/getfider/fider/app/models"
+
+type SetAttachments struct {
+ Post *models.Post
+ Comment *models.Comment
+ Attachments []*models.ImageUpload
+}
+
+type UploadImage struct {
+ Image *models.ImageUpload
+ Folder string
+}
+
+type UploadImages struct {
+ Images []*models.ImageUpload
+ Folder string
+}
diff --git a/app/models/cmd/billing.go b/app/models/cmd/billing.go
new file mode 100644
index 000000000..77fba7a23
--- /dev/null
+++ b/app/models/cmd/billing.go
@@ -0,0 +1,23 @@
+package cmd
+
+import "github.com/getfider/fider/app/models/dto"
+
+type CancelBillingSubscription struct {
+}
+
+type CreateBillingSubscription struct {
+ PlanID string
+}
+
+type CreateBillingCustomer struct {
+}
+
+type DeleteBillingCustomer struct {
+}
+
+type ClearPaymentInfo struct {
+}
+
+type UpdatePaymentInfo struct {
+ Input *dto.CreateEditBillingPaymentInfo
+}
diff --git a/app/models/cmd/blob.go b/app/models/cmd/blob.go
new file mode 100644
index 000000000..0133ccc01
--- /dev/null
+++ b/app/models/cmd/blob.go
@@ -0,0 +1,11 @@
+package cmd
+
+type StoreBlob struct {
+ Key string
+ Content []byte
+ ContentType string
+}
+
+type DeleteBlob struct {
+ Key string
+}
diff --git a/app/models/cmd/comment.go b/app/models/cmd/comment.go
new file mode 100644
index 000000000..f03763255
--- /dev/null
+++ b/app/models/cmd/comment.go
@@ -0,0 +1,19 @@
+package cmd
+
+import "github.com/getfider/fider/app/models"
+
+type AddNewComment struct {
+ Post *models.Post
+ Content string
+
+ Result *models.Comment
+}
+
+type UpdateComment struct {
+ CommentID int
+ Content string
+}
+
+type DeleteComment struct {
+ CommentID int
+}
diff --git a/app/models/cmd/email.go b/app/models/cmd/email.go
new file mode 100644
index 000000000..fa47063b2
--- /dev/null
+++ b/app/models/cmd/email.go
@@ -0,0 +1,10 @@
+package cmd
+
+import "github.com/getfider/fider/app/models/dto"
+
+type SendMail struct {
+ From string
+ To []dto.Recipient
+ TemplateName string
+ Props dto.Props
+}
diff --git a/app/models/cmd/event.go b/app/models/cmd/event.go
new file mode 100644
index 000000000..86d6d4e1f
--- /dev/null
+++ b/app/models/cmd/event.go
@@ -0,0 +1,6 @@
+package cmd
+
+type StoreEvent struct {
+ ClientIP string
+ EventName string
+}
diff --git a/app/models/cmd/http.go b/app/models/cmd/http.go
new file mode 100644
index 000000000..c4352456a
--- /dev/null
+++ b/app/models/cmd/http.go
@@ -0,0 +1,18 @@
+package cmd
+
+import (
+ "io"
+
+ "github.com/getfider/fider/app/models/dto"
+)
+
+type HTTPRequest struct {
+ URL string
+ Body io.Reader
+ Method string
+ Headers map[string]string
+ BasicAuth *dto.BasicAuth
+
+ ResponseBody []byte
+ ResponseStatusCode int
+}
diff --git a/app/models/cmd/log.go b/app/models/cmd/log.go
new file mode 100644
index 000000000..23bdb3cdb
--- /dev/null
+++ b/app/models/cmd/log.go
@@ -0,0 +1,24 @@
+package cmd
+
+import "github.com/getfider/fider/app/models/dto"
+
+type LogDebug struct {
+ Message string
+ Props dto.Props
+}
+
+type LogError struct {
+ Err error
+ Message string
+ Props dto.Props
+}
+
+type LogWarn struct {
+ Message string
+ Props dto.Props
+}
+
+type LogInfo struct {
+ Message string
+ Props dto.Props
+}
diff --git a/app/models/cmd/notification.go b/app/models/cmd/notification.go
new file mode 100644
index 000000000..e484d5058
--- /dev/null
+++ b/app/models/cmd/notification.go
@@ -0,0 +1,28 @@
+package cmd
+
+import "github.com/getfider/fider/app/models"
+
+type MarkAllNotificationsAsRead struct{}
+
+type MarkNotificationAsRead struct {
+ ID int
+}
+
+type AddNewNotification struct {
+ User *models.User
+ Title string
+ Link string
+ PostID int
+
+ Result *models.Notification
+}
+
+type AddSubscriber struct {
+ Post *models.Post
+ User *models.User
+}
+
+type RemoveSubscriber struct {
+ Post *models.Post
+ User *models.User
+}
diff --git a/app/models/cmd/oauth.go b/app/models/cmd/oauth.go
new file mode 100644
index 000000000..2dfd922a1
--- /dev/null
+++ b/app/models/cmd/oauth.go
@@ -0,0 +1,17 @@
+package cmd
+
+import (
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/dto"
+)
+
+type SaveCustomOAuthConfig struct {
+ Config *models.CreateEditOAuthConfig
+}
+
+type ParseOAuthRawProfile struct {
+ Provider string
+ Body string
+
+ Result *dto.OAuthUserProfile
+}
diff --git a/app/models/cmd/post.go b/app/models/cmd/post.go
new file mode 100644
index 000000000..2ae401b27
--- /dev/null
+++ b/app/models/cmd/post.go
@@ -0,0 +1,27 @@
+package cmd
+
+import (
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+)
+
+type AddNewPost struct {
+ Title string
+ Description string
+
+ Result *models.Post
+}
+
+type UpdatePost struct {
+ Post *models.Post
+ Title string
+ Description string
+
+ Result *models.Post
+}
+
+type SetPostResponse struct {
+ Post *models.Post
+ Text string
+ Status enum.PostStatus
+}
diff --git a/app/models/cmd/tag.go b/app/models/cmd/tag.go
new file mode 100644
index 000000000..be3ff2c2c
--- /dev/null
+++ b/app/models/cmd/tag.go
@@ -0,0 +1,34 @@
+package cmd
+
+import "github.com/getfider/fider/app/models"
+
+type AddNewTag struct {
+ Name string
+ Color string
+ IsPublic bool
+
+ Result *models.Tag
+}
+
+type UpdateTag struct {
+ TagID int
+ Name string
+ Color string
+ IsPublic bool
+
+ Result *models.Tag
+}
+
+type DeleteTag struct {
+ Tag *models.Tag
+}
+
+type AssignTag struct {
+ Tag *models.Tag
+ Post *models.Post
+}
+
+type UnassignTag struct {
+ Tag *models.Tag
+ Post *models.Post
+}
diff --git a/app/models/cmd/tenant.go b/app/models/cmd/tenant.go
new file mode 100644
index 000000000..9dd031831
--- /dev/null
+++ b/app/models/cmd/tenant.go
@@ -0,0 +1,45 @@
+package cmd
+
+import (
+ "time"
+
+ "github.com/getfider/fider/app/models"
+)
+
+type CreateTenant struct {
+ Name string
+ Subdomain string
+ Status int
+
+ Result *models.Tenant
+}
+
+type UpdateTenantPrivacySettings struct {
+ Settings *models.UpdateTenantPrivacy
+}
+
+type UpdateTenantSettings struct {
+ Settings *models.UpdateTenantSettings
+}
+
+type UpdateTenantBillingSettings struct {
+ Settings *models.TenantBilling
+}
+
+type UpdateTenantAdvancedSettings struct {
+ Settings *models.UpdateTenantAdvancedSettings
+}
+
+type ActivateTenant struct {
+ TenantID int
+}
+
+type SaveVerificationKey struct {
+ Key string
+ Duration time.Duration
+ Request models.NewEmailVerification
+}
+
+type SetKeyAsVerified struct {
+ Key string
+}
diff --git a/app/models/cmd/user.go b/app/models/cmd/user.go
new file mode 100644
index 000000000..3efc7ed3f
--- /dev/null
+++ b/app/models/cmd/user.go
@@ -0,0 +1,51 @@
+package cmd
+
+import (
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+)
+
+type BlockUser struct {
+ UserID int
+}
+
+type UnblockUser struct {
+ UserID int
+}
+
+type RegenerateAPIKey struct {
+ Result string
+}
+
+type DeleteCurrentUser struct {
+}
+
+type ChangeUserRole struct {
+ UserID int
+ Role enum.Role
+}
+
+type ChangeUserEmail struct {
+ UserID int
+ Email string
+}
+
+type UpdateCurrentUserSettings struct {
+ Settings map[string]string
+}
+
+type RegisterUser struct {
+ User *models.User
+}
+
+type RegisterUserProvider struct {
+ UserID int
+ ProviderName string
+ ProviderUID string
+}
+
+type UpdateCurrentUser struct {
+ Name string
+ AvatarType enum.AvatarType
+ Avatar *models.ImageUpload
+}
diff --git a/app/models/cmd/vote.go b/app/models/cmd/vote.go
new file mode 100644
index 000000000..25b68176c
--- /dev/null
+++ b/app/models/cmd/vote.go
@@ -0,0 +1,18 @@
+package cmd
+
+import "github.com/getfider/fider/app/models"
+
+type AddVote struct {
+ Post *models.Post
+ User *models.User
+}
+
+type RemoveVote struct {
+ Post *models.Post
+ User *models.User
+}
+
+type MarkPostAsDuplicate struct {
+ Post *models.Post
+ Original *models.Post
+}
diff --git a/app/models/countries.go b/app/models/countries.go
deleted file mode 100644
index 1e30952dd..000000000
--- a/app/models/countries.go
+++ /dev/null
@@ -1,269 +0,0 @@
-package models
-
-import (
- "github.com/goenning/vat"
-)
-
-// Country is a valid country within Fider
-type Country struct {
- Code string `json:"code"`
- Name string `json:"name"`
- IsEU bool `json:"isEU"`
-}
-
-var countries = []*Country{
- &Country{Code: "AF", Name: "Afghanistan", IsEU: vat.IsEU("AF")},
- &Country{Code: "AX", Name: "Åland Islands", IsEU: vat.IsEU("AX")},
- &Country{Code: "AL", Name: "Albania", IsEU: vat.IsEU("AL")},
- &Country{Code: "DZ", Name: "Algeria", IsEU: vat.IsEU("DZ")},
- &Country{Code: "AS", Name: "American Samoa", IsEU: vat.IsEU("AS")},
- &Country{Code: "AD", Name: "Andorra", IsEU: vat.IsEU("AD")},
- &Country{Code: "AO", Name: "Angola", IsEU: vat.IsEU("AO")},
- &Country{Code: "AI", Name: "Anguilla", IsEU: vat.IsEU("AI")},
- &Country{Code: "AQ", Name: "Antarctica", IsEU: vat.IsEU("AQ")},
- &Country{Code: "AG", Name: "Antigua and Barbuda", IsEU: vat.IsEU("AG")},
- &Country{Code: "AR", Name: "Argentina", IsEU: vat.IsEU("AR")},
- &Country{Code: "AM", Name: "Armenia", IsEU: vat.IsEU("AM")},
- &Country{Code: "AW", Name: "Aruba", IsEU: vat.IsEU("AW")},
- &Country{Code: "AU", Name: "Australia", IsEU: vat.IsEU("AU")},
- &Country{Code: "AT", Name: "Austria", IsEU: vat.IsEU("AT")},
- &Country{Code: "AZ", Name: "Azerbaijan", IsEU: vat.IsEU("AZ")},
- &Country{Code: "BS", Name: "Bahamas", IsEU: vat.IsEU("BS")},
- &Country{Code: "BH", Name: "Bahrain", IsEU: vat.IsEU("BH")},
- &Country{Code: "BD", Name: "Bangladesh", IsEU: vat.IsEU("BD")},
- &Country{Code: "BB", Name: "Barbados", IsEU: vat.IsEU("BB")},
- &Country{Code: "BY", Name: "Belarus", IsEU: vat.IsEU("BY")},
- &Country{Code: "BE", Name: "Belgium", IsEU: vat.IsEU("BE")},
- &Country{Code: "BZ", Name: "Belize", IsEU: vat.IsEU("BZ")},
- &Country{Code: "BJ", Name: "Benin", IsEU: vat.IsEU("BJ")},
- &Country{Code: "BM", Name: "Bermuda", IsEU: vat.IsEU("BM")},
- &Country{Code: "BT", Name: "Bhutan", IsEU: vat.IsEU("BT")},
- &Country{Code: "BO", Name: "Bolivia, Plurinational State of", IsEU: vat.IsEU("BO")},
- &Country{Code: "BQ", Name: "Bonaire, Sint Eustatius and Saba", IsEU: vat.IsEU("BQ")},
- &Country{Code: "BA", Name: "Bosnia and Herzegovina", IsEU: vat.IsEU("BA")},
- &Country{Code: "BW", Name: "Botswana", IsEU: vat.IsEU("BW")},
- &Country{Code: "BV", Name: "Bouvet Island", IsEU: vat.IsEU("BV")},
- &Country{Code: "BR", Name: "Brazil", IsEU: vat.IsEU("BR")},
- &Country{Code: "IO", Name: "British Indian Ocean Territory", IsEU: vat.IsEU("IO")},
- &Country{Code: "BN", Name: "Brunei Darussalam", IsEU: vat.IsEU("BN")},
- &Country{Code: "BG", Name: "Bulgaria", IsEU: vat.IsEU("BG")},
- &Country{Code: "BF", Name: "Burkina Faso", IsEU: vat.IsEU("BF")},
- &Country{Code: "BI", Name: "Burundi", IsEU: vat.IsEU("BI")},
- &Country{Code: "KH", Name: "Cambodia", IsEU: vat.IsEU("KH")},
- &Country{Code: "CM", Name: "Cameroon", IsEU: vat.IsEU("CM")},
- &Country{Code: "CA", Name: "Canada", IsEU: vat.IsEU("CA")},
- &Country{Code: "CV", Name: "Cape Verde", IsEU: vat.IsEU("CV")},
- &Country{Code: "KY", Name: "Cayman Islands", IsEU: vat.IsEU("KY")},
- &Country{Code: "CF", Name: "Central African Republic", IsEU: vat.IsEU("CF")},
- &Country{Code: "TD", Name: "Chad", IsEU: vat.IsEU("TD")},
- &Country{Code: "CL", Name: "Chile", IsEU: vat.IsEU("CL")},
- &Country{Code: "CN", Name: "China", IsEU: vat.IsEU("CN")},
- &Country{Code: "CX", Name: "Christmas Island", IsEU: vat.IsEU("CX")},
- &Country{Code: "CC", Name: "Cocos (Keeling) Islands", IsEU: vat.IsEU("CC")},
- &Country{Code: "CO", Name: "Colombia", IsEU: vat.IsEU("CO")},
- &Country{Code: "KM", Name: "Comoros", IsEU: vat.IsEU("KM")},
- &Country{Code: "CG", Name: "Congo", IsEU: vat.IsEU("CG")},
- &Country{Code: "CD", Name: "Congo, the Democratic Republic of the", IsEU: vat.IsEU("CD")},
- &Country{Code: "CK", Name: "Cook Islands", IsEU: vat.IsEU("CK")},
- &Country{Code: "CR", Name: "Costa Rica", IsEU: vat.IsEU("CR")},
- &Country{Code: "CI", Name: "Côte d'Ivoire", IsEU: vat.IsEU("CI")},
- &Country{Code: "HR", Name: "Croatia", IsEU: vat.IsEU("HR")},
- &Country{Code: "CU", Name: "Cuba", IsEU: vat.IsEU("CU")},
- &Country{Code: "CW", Name: "Curaçao", IsEU: vat.IsEU("CW")},
- &Country{Code: "CY", Name: "Cyprus", IsEU: vat.IsEU("CY")},
- &Country{Code: "CZ", Name: "Czech Republic", IsEU: vat.IsEU("CZ")},
- &Country{Code: "DK", Name: "Denmark", IsEU: vat.IsEU("DK")},
- &Country{Code: "DJ", Name: "Djibouti", IsEU: vat.IsEU("DJ")},
- &Country{Code: "DM", Name: "Dominica", IsEU: vat.IsEU("DM")},
- &Country{Code: "DO", Name: "Dominican Republic", IsEU: vat.IsEU("DO")},
- &Country{Code: "EC", Name: "Ecuador", IsEU: vat.IsEU("EC")},
- &Country{Code: "EG", Name: "Egypt", IsEU: vat.IsEU("EG")},
- &Country{Code: "SV", Name: "El Salvador", IsEU: vat.IsEU("SV")},
- &Country{Code: "GQ", Name: "Equatorial Guinea", IsEU: vat.IsEU("GQ")},
- &Country{Code: "ER", Name: "Eritrea", IsEU: vat.IsEU("ER")},
- &Country{Code: "EE", Name: "Estonia", IsEU: vat.IsEU("EE")},
- &Country{Code: "ET", Name: "Ethiopia", IsEU: vat.IsEU("ET")},
- &Country{Code: "FK", Name: "Falkland Islands (Malvinas)", IsEU: vat.IsEU("FK")},
- &Country{Code: "FO", Name: "Faroe Islands", IsEU: vat.IsEU("FO")},
- &Country{Code: "FJ", Name: "Fiji", IsEU: vat.IsEU("FJ")},
- &Country{Code: "FI", Name: "Finland", IsEU: vat.IsEU("FI")},
- &Country{Code: "FR", Name: "France", IsEU: vat.IsEU("FR")},
- &Country{Code: "GF", Name: "French Guiana", IsEU: vat.IsEU("GF")},
- &Country{Code: "PF", Name: "French Polynesia", IsEU: vat.IsEU("PF")},
- &Country{Code: "TF", Name: "French Southern Territories", IsEU: vat.IsEU("TF")},
- &Country{Code: "GA", Name: "Gabon", IsEU: vat.IsEU("GA")},
- &Country{Code: "GM", Name: "Gambia", IsEU: vat.IsEU("GM")},
- &Country{Code: "GE", Name: "Georgia", IsEU: vat.IsEU("GE")},
- &Country{Code: "DE", Name: "Germany", IsEU: vat.IsEU("DE")},
- &Country{Code: "GH", Name: "Ghana", IsEU: vat.IsEU("GH")},
- &Country{Code: "GI", Name: "Gibraltar", IsEU: vat.IsEU("GI")},
- &Country{Code: "GR", Name: "Greece", IsEU: vat.IsEU("GR")},
- &Country{Code: "GL", Name: "Greenland", IsEU: vat.IsEU("GL")},
- &Country{Code: "GD", Name: "Grenada", IsEU: vat.IsEU("GD")},
- &Country{Code: "GP", Name: "Guadeloupe", IsEU: vat.IsEU("GP")},
- &Country{Code: "GU", Name: "Guam", IsEU: vat.IsEU("GU")},
- &Country{Code: "GT", Name: "Guatemala", IsEU: vat.IsEU("GT")},
- &Country{Code: "GG", Name: "Guernsey", IsEU: vat.IsEU("GG")},
- &Country{Code: "GN", Name: "Guinea", IsEU: vat.IsEU("GN")},
- &Country{Code: "GW", Name: "Guinea-Bissau", IsEU: vat.IsEU("GW")},
- &Country{Code: "GY", Name: "Guyana", IsEU: vat.IsEU("GY")},
- &Country{Code: "HT", Name: "Haiti", IsEU: vat.IsEU("HT")},
- &Country{Code: "HM", Name: "Heard Island and McDonald Islands", IsEU: vat.IsEU("HM")},
- &Country{Code: "VA", Name: "Holy See (Vatican City State)", IsEU: vat.IsEU("VA")},
- &Country{Code: "HN", Name: "Honduras", IsEU: vat.IsEU("HN")},
- &Country{Code: "HK", Name: "Hong Kong", IsEU: vat.IsEU("HK")},
- &Country{Code: "HU", Name: "Hungary", IsEU: vat.IsEU("HU")},
- &Country{Code: "IS", Name: "Iceland", IsEU: vat.IsEU("IS")},
- &Country{Code: "IN", Name: "India", IsEU: vat.IsEU("IN")},
- &Country{Code: "ID", Name: "Indonesia", IsEU: vat.IsEU("ID")},
- &Country{Code: "IR", Name: "Iran, Islamic Republic of", IsEU: vat.IsEU("IR")},
- &Country{Code: "IQ", Name: "Iraq", IsEU: vat.IsEU("IQ")},
- &Country{Code: "IE", Name: "Ireland", IsEU: vat.IsEU("IE")},
- &Country{Code: "IM", Name: "Isle of Man", IsEU: vat.IsEU("IM")},
- &Country{Code: "IL", Name: "Israel", IsEU: vat.IsEU("IL")},
- &Country{Code: "IT", Name: "Italy", IsEU: vat.IsEU("IT")},
- &Country{Code: "JM", Name: "Jamaica", IsEU: vat.IsEU("JM")},
- &Country{Code: "JP", Name: "Japan", IsEU: vat.IsEU("JP")},
- &Country{Code: "JE", Name: "Jersey", IsEU: vat.IsEU("JE")},
- &Country{Code: "JO", Name: "Jordan", IsEU: vat.IsEU("JO")},
- &Country{Code: "KZ", Name: "Kazakhstan", IsEU: vat.IsEU("KZ")},
- &Country{Code: "KE", Name: "Kenya", IsEU: vat.IsEU("KE")},
- &Country{Code: "KI", Name: "Kiribati", IsEU: vat.IsEU("KI")},
- &Country{Code: "KP", Name: "Korea, Democratic People's Republic of", IsEU: vat.IsEU("KP")},
- &Country{Code: "KR", Name: "Korea, Republic of", IsEU: vat.IsEU("KR")},
- &Country{Code: "KW", Name: "Kuwait", IsEU: vat.IsEU("KW")},
- &Country{Code: "KG", Name: "Kyrgyzstan", IsEU: vat.IsEU("KG")},
- &Country{Code: "LA", Name: "Lao People's Democratic Republic", IsEU: vat.IsEU("LA")},
- &Country{Code: "LV", Name: "Latvia", IsEU: vat.IsEU("LV")},
- &Country{Code: "LB", Name: "Lebanon", IsEU: vat.IsEU("LB")},
- &Country{Code: "LS", Name: "Lesotho", IsEU: vat.IsEU("LS")},
- &Country{Code: "LR", Name: "Liberia", IsEU: vat.IsEU("LR")},
- &Country{Code: "LY", Name: "Libya", IsEU: vat.IsEU("LY")},
- &Country{Code: "LI", Name: "Liechtenstein", IsEU: vat.IsEU("LI")},
- &Country{Code: "LT", Name: "Lithuania", IsEU: vat.IsEU("LT")},
- &Country{Code: "LU", Name: "Luxembourg", IsEU: vat.IsEU("LU")},
- &Country{Code: "MO", Name: "Macao", IsEU: vat.IsEU("MO")},
- &Country{Code: "MK", Name: "Macedonia, the former Yugoslav Republic of", IsEU: vat.IsEU("MK")},
- &Country{Code: "MG", Name: "Madagascar", IsEU: vat.IsEU("MG")},
- &Country{Code: "MW", Name: "Malawi", IsEU: vat.IsEU("MW")},
- &Country{Code: "MY", Name: "Malaysia", IsEU: vat.IsEU("MY")},
- &Country{Code: "MV", Name: "Maldives", IsEU: vat.IsEU("MV")},
- &Country{Code: "ML", Name: "Mali", IsEU: vat.IsEU("ML")},
- &Country{Code: "MT", Name: "Malta", IsEU: vat.IsEU("MT")},
- &Country{Code: "MH", Name: "Marshall Islands", IsEU: vat.IsEU("MH")},
- &Country{Code: "MQ", Name: "Martinique", IsEU: vat.IsEU("MQ")},
- &Country{Code: "MR", Name: "Mauritania", IsEU: vat.IsEU("MR")},
- &Country{Code: "MU", Name: "Mauritius", IsEU: vat.IsEU("MU")},
- &Country{Code: "YT", Name: "Mayotte", IsEU: vat.IsEU("YT")},
- &Country{Code: "MX", Name: "Mexico", IsEU: vat.IsEU("MX")},
- &Country{Code: "FM", Name: "Micronesia, Federated States of", IsEU: vat.IsEU("FM")},
- &Country{Code: "MD", Name: "Moldova, Republic of", IsEU: vat.IsEU("MD")},
- &Country{Code: "MC", Name: "Monaco", IsEU: vat.IsEU("MC")},
- &Country{Code: "MN", Name: "Mongolia", IsEU: vat.IsEU("MN")},
- &Country{Code: "ME", Name: "Montenegro", IsEU: vat.IsEU("ME")},
- &Country{Code: "MS", Name: "Montserrat", IsEU: vat.IsEU("MS")},
- &Country{Code: "MA", Name: "Morocco", IsEU: vat.IsEU("MA")},
- &Country{Code: "MZ", Name: "Mozambique", IsEU: vat.IsEU("MZ")},
- &Country{Code: "MM", Name: "Myanmar", IsEU: vat.IsEU("MM")},
- &Country{Code: "NA", Name: "Namibia", IsEU: vat.IsEU("NA")},
- &Country{Code: "NR", Name: "Nauru", IsEU: vat.IsEU("NR")},
- &Country{Code: "NP", Name: "Nepal", IsEU: vat.IsEU("NP")},
- &Country{Code: "NL", Name: "Netherlands", IsEU: vat.IsEU("NL")},
- &Country{Code: "NC", Name: "New Caledonia", IsEU: vat.IsEU("NC")},
- &Country{Code: "NZ", Name: "New Zealand", IsEU: vat.IsEU("NZ")},
- &Country{Code: "NI", Name: "Nicaragua", IsEU: vat.IsEU("NI")},
- &Country{Code: "NE", Name: "Niger", IsEU: vat.IsEU("NE")},
- &Country{Code: "NG", Name: "Nigeria", IsEU: vat.IsEU("NG")},
- &Country{Code: "NU", Name: "Niue", IsEU: vat.IsEU("NU")},
- &Country{Code: "NF", Name: "Norfolk Island", IsEU: vat.IsEU("NF")},
- &Country{Code: "MP", Name: "Northern Mariana Islands", IsEU: vat.IsEU("MP")},
- &Country{Code: "NO", Name: "Norway", IsEU: vat.IsEU("NO")},
- &Country{Code: "OM", Name: "Oman", IsEU: vat.IsEU("OM")},
- &Country{Code: "PK", Name: "Pakistan", IsEU: vat.IsEU("PK")},
- &Country{Code: "PW", Name: "Palau", IsEU: vat.IsEU("PW")},
- &Country{Code: "PS", Name: "Palestinian Territory, Occupied", IsEU: vat.IsEU("PS")},
- &Country{Code: "PA", Name: "Panama", IsEU: vat.IsEU("PA")},
- &Country{Code: "PG", Name: "Papua New Guinea", IsEU: vat.IsEU("PG")},
- &Country{Code: "PY", Name: "Paraguay", IsEU: vat.IsEU("PY")},
- &Country{Code: "PE", Name: "Peru", IsEU: vat.IsEU("PE")},
- &Country{Code: "PH", Name: "Philippines", IsEU: vat.IsEU("PH")},
- &Country{Code: "PN", Name: "Pitcairn", IsEU: vat.IsEU("PN")},
- &Country{Code: "PL", Name: "Poland", IsEU: vat.IsEU("PL")},
- &Country{Code: "PT", Name: "Portugal", IsEU: vat.IsEU("PT")},
- &Country{Code: "PR", Name: "Puerto Rico", IsEU: vat.IsEU("PR")},
- &Country{Code: "QA", Name: "Qatar", IsEU: vat.IsEU("QA")},
- &Country{Code: "RE", Name: "Réunion", IsEU: vat.IsEU("RE")},
- &Country{Code: "RO", Name: "Romania", IsEU: vat.IsEU("RO")},
- &Country{Code: "RU", Name: "Russian Federation", IsEU: vat.IsEU("RU")},
- &Country{Code: "RW", Name: "Rwanda", IsEU: vat.IsEU("RW")},
- &Country{Code: "BL", Name: "Saint Barthélemy", IsEU: vat.IsEU("BL")},
- &Country{Code: "SH", Name: "Saint Helena, Ascension and Tristan da Cunha", IsEU: vat.IsEU("SH")},
- &Country{Code: "KN", Name: "Saint Kitts and Nevis", IsEU: vat.IsEU("KN")},
- &Country{Code: "LC", Name: "Saint Lucia", IsEU: vat.IsEU("LC")},
- &Country{Code: "MF", Name: "Saint Martin (French part)", IsEU: vat.IsEU("MF")},
- &Country{Code: "PM", Name: "Saint Pierre and Miquelon", IsEU: vat.IsEU("PM")},
- &Country{Code: "VC", Name: "Saint Vincent and the Grenadines", IsEU: vat.IsEU("VC")},
- &Country{Code: "WS", Name: "Samoa", IsEU: vat.IsEU("WS")},
- &Country{Code: "SM", Name: "San Marino", IsEU: vat.IsEU("SM")},
- &Country{Code: "ST", Name: "Sao Tome and Principe", IsEU: vat.IsEU("ST")},
- &Country{Code: "SA", Name: "Saudi Arabia", IsEU: vat.IsEU("SA")},
- &Country{Code: "SN", Name: "Senegal", IsEU: vat.IsEU("SN")},
- &Country{Code: "RS", Name: "Serbia", IsEU: vat.IsEU("RS")},
- &Country{Code: "SC", Name: "Seychelles", IsEU: vat.IsEU("SC")},
- &Country{Code: "SL", Name: "Sierra Leone", IsEU: vat.IsEU("SL")},
- &Country{Code: "SG", Name: "Singapore", IsEU: vat.IsEU("SG")},
- &Country{Code: "SX", Name: "Sint Maarten (Dutch part)", IsEU: vat.IsEU("SX")},
- &Country{Code: "SK", Name: "Slovakia", IsEU: vat.IsEU("SK")},
- &Country{Code: "SI", Name: "Slovenia", IsEU: vat.IsEU("SI")},
- &Country{Code: "SB", Name: "Solomon Islands", IsEU: vat.IsEU("SB")},
- &Country{Code: "SO", Name: "Somalia", IsEU: vat.IsEU("SO")},
- &Country{Code: "ZA", Name: "South Africa", IsEU: vat.IsEU("ZA")},
- &Country{Code: "GS", Name: "South Georgia and the South Sandwich Islands", IsEU: vat.IsEU("GS")},
- &Country{Code: "SS", Name: "South Sudan", IsEU: vat.IsEU("SS")},
- &Country{Code: "ES", Name: "Spain", IsEU: vat.IsEU("ES")},
- &Country{Code: "LK", Name: "Sri Lanka", IsEU: vat.IsEU("LK")},
- &Country{Code: "SD", Name: "Sudan", IsEU: vat.IsEU("SD")},
- &Country{Code: "SR", Name: "Suriname", IsEU: vat.IsEU("SR")},
- &Country{Code: "SJ", Name: "Svalbard and Jan Mayen", IsEU: vat.IsEU("SJ")},
- &Country{Code: "SZ", Name: "Swaziland", IsEU: vat.IsEU("SZ")},
- &Country{Code: "SE", Name: "Sweden", IsEU: vat.IsEU("SE")},
- &Country{Code: "CH", Name: "Switzerland", IsEU: vat.IsEU("CH")},
- &Country{Code: "SY", Name: "Syrian Arab Republic", IsEU: vat.IsEU("SY")},
- &Country{Code: "TW", Name: "Taiwan, Province of China", IsEU: vat.IsEU("TW")},
- &Country{Code: "TJ", Name: "Tajikistan", IsEU: vat.IsEU("TJ")},
- &Country{Code: "TZ", Name: "Tanzania, United Republic of", IsEU: vat.IsEU("TZ")},
- &Country{Code: "TH", Name: "Thailand", IsEU: vat.IsEU("TH")},
- &Country{Code: "TL", Name: "Timor-Leste", IsEU: vat.IsEU("TL")},
- &Country{Code: "TG", Name: "Togo", IsEU: vat.IsEU("TG")},
- &Country{Code: "TK", Name: "Tokelau", IsEU: vat.IsEU("TK")},
- &Country{Code: "TO", Name: "Tonga", IsEU: vat.IsEU("TO")},
- &Country{Code: "TT", Name: "Trinidad and Tobago", IsEU: vat.IsEU("TT")},
- &Country{Code: "TN", Name: "Tunisia", IsEU: vat.IsEU("TN")},
- &Country{Code: "TR", Name: "Turkey", IsEU: vat.IsEU("TR")},
- &Country{Code: "TM", Name: "Turkmenistan", IsEU: vat.IsEU("TM")},
- &Country{Code: "TC", Name: "Turks and Caicos Islands", IsEU: vat.IsEU("TC")},
- &Country{Code: "TV", Name: "Tuvalu", IsEU: vat.IsEU("TV")},
- &Country{Code: "UG", Name: "Uganda", IsEU: vat.IsEU("UG")},
- &Country{Code: "UA", Name: "Ukraine", IsEU: vat.IsEU("UA")},
- &Country{Code: "AE", Name: "United Arab Emirates", IsEU: vat.IsEU("AE")},
- &Country{Code: "GB", Name: "United Kingdom", IsEU: vat.IsEU("GB")},
- &Country{Code: "US", Name: "United States", IsEU: vat.IsEU("US")},
- &Country{Code: "UM", Name: "United States Minor Outlying Islands", IsEU: vat.IsEU("UM")},
- &Country{Code: "UY", Name: "Uruguay", IsEU: vat.IsEU("UY")},
- &Country{Code: "UZ", Name: "Uzbekistan", IsEU: vat.IsEU("UZ")},
- &Country{Code: "VU", Name: "Vanuatu", IsEU: vat.IsEU("VU")},
- &Country{Code: "VE", Name: "Venezuela, Bolivarian Republic of", IsEU: vat.IsEU("VE")},
- &Country{Code: "VN", Name: "Viet Nam", IsEU: vat.IsEU("VN")},
- &Country{Code: "VG", Name: "Virgin Islands, British", IsEU: vat.IsEU("VG")},
- &Country{Code: "VI", Name: "Virgin Islands, U.S.", IsEU: vat.IsEU("VI")},
- &Country{Code: "WF", Name: "Wallis and Futuna", IsEU: vat.IsEU("WF")},
- &Country{Code: "EH", Name: "Western Sahara", IsEU: vat.IsEU("EH")},
- &Country{Code: "YE", Name: "Yemen", IsEU: vat.IsEU("YE")},
- &Country{Code: "ZM", Name: "Zambia", IsEU: vat.IsEU("ZM")},
- &Country{Code: "ZW", Name: "Zimbabwe", IsEU: vat.IsEU("ZW")},
-}
-
-// GetAllCountries returns a list of all known countries
-func GetAllCountries() []*Country {
- return countries
-}
diff --git a/app/models/billing.go b/app/models/dto/billing.go
similarity index 93%
rename from app/models/billing.go
rename to app/models/dto/billing.go
index 5cd40deb2..5a19563a7 100644
--- a/app/models/billing.go
+++ b/app/models/dto/billing.go
@@ -1,26 +1,30 @@
-package models
+package dto
import "time"
-// CreateEditBillingPaymentInfo is the input model to create or edit billing payment info
-type CreateEditBillingPaymentInfo struct {
- Name string `json:"name"`
- Email string `json:"email"`
- Card *CreateEditBillingPaymentInfoCard `json:"card"`
- AddressLine1 string `json:"addressLine1"`
- AddressLine2 string `json:"addressLine2"`
- AddressCity string `json:"addressCity"`
- AddressState string `json:"addressState"`
- AddressPostalCode string `json:"addressPostalCode"`
- AddressCountry string `json:"addressCountry" format:"upper"`
- VATNumber string `json:"vatNumber"`
+// Country is a valid country within Fider
+type Country struct {
+ Code string `json:"code"`
+ Name string `json:"name"`
+ IsEU bool `json:"isEU"`
}
-// CreateEditBillingPaymentInfoCard is the input model for a card during billing payment info update
-type CreateEditBillingPaymentInfoCard struct {
- Type string `json:"type"`
- Token string `json:"token"`
- Country string `json:"country"`
+// BillingPlan is the model for billing plan from Stripe
+type BillingPlan struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Currency string `json:"currency"`
+ MaxUsers int `json:"maxUsers"`
+ Price int64 `json:"price"`
+ Interval string `json:"interval"`
+}
+
+// UpcomingInvoice is the model for upcoming invoice from Stripe
+type UpcomingInvoice struct {
+ Currency string `json:"currency"`
+ DueDate time.Time `json:"dueDate"`
+ AmountDue int64 `json:"amountDue"`
}
// PaymentInfo is the model for billing payment info
@@ -42,20 +46,23 @@ type PaymentInfo struct {
VATNumber string `json:"vatNumber"`
}
-// BillingPlan is the model for billing plan from Stripe
-type BillingPlan struct {
- ID string `json:"id"`
- Name string `json:"name"`
- Description string `json:"description"`
- Currency string `json:"currency"`
- MaxUsers int `json:"maxUsers"`
- Price int64 `json:"price"`
- Interval string `json:"interval"`
+// CreateEditBillingPaymentInfo is the input model to create or edit billing payment info
+type CreateEditBillingPaymentInfo struct {
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Card *CreateEditBillingPaymentInfoCard `json:"card"`
+ AddressLine1 string `json:"addressLine1"`
+ AddressLine2 string `json:"addressLine2"`
+ AddressCity string `json:"addressCity"`
+ AddressState string `json:"addressState"`
+ AddressPostalCode string `json:"addressPostalCode"`
+ AddressCountry string `json:"addressCountry" format:"upper"`
+ VATNumber string `json:"vatNumber"`
}
-// UpcomingInvoice is the model for upcoming invoice from Stripe
-type UpcomingInvoice struct {
- Currency string `json:"currency"`
- DueDate time.Time `json:"dueDate"`
- AmountDue int64 `json:"amountDue"`
+// CreateEditBillingPaymentInfoCard is the input model for a card during billing payment info update
+type CreateEditBillingPaymentInfoCard struct {
+ Type string `json:"type"`
+ Token string `json:"token"`
+ Country string `json:"country"`
}
diff --git a/app/models/dto/blob.go b/app/models/dto/blob.go
new file mode 100644
index 000000000..3c6b6dee6
--- /dev/null
+++ b/app/models/dto/blob.go
@@ -0,0 +1,7 @@
+package dto
+
+type Blob struct {
+ Size int64
+ Content []byte
+ ContentType string
+}
diff --git a/app/models/dto/email.go b/app/models/dto/email.go
new file mode 100644
index 000000000..b48f16681
--- /dev/null
+++ b/app/models/dto/email.go
@@ -0,0 +1,33 @@
+package dto
+
+import "net/mail"
+
+// Recipient contains details of who is receiving the email
+type Recipient struct {
+ Name string
+ Address string
+ Props Props
+}
+
+// NewRecipient creates a new Recipient
+func NewRecipient(name, address string, props Props) Recipient {
+ return Recipient{
+ Name: name,
+ Address: address,
+ Props: props,
+ }
+}
+
+// Strings returns the RFC format to send emails via SMTP
+func (r Recipient) String() string {
+ if r.Address == "" {
+ return ""
+ }
+
+ address := mail.Address{
+ Name: r.Name,
+ Address: r.Address,
+ }
+
+ return address.String()
+}
diff --git a/app/models/dto/http.go b/app/models/dto/http.go
new file mode 100644
index 000000000..654a17019
--- /dev/null
+++ b/app/models/dto/http.go
@@ -0,0 +1,6 @@
+package dto
+
+type BasicAuth struct {
+ User string
+ Password string
+}
diff --git a/app/models/dto/oauth.go b/app/models/dto/oauth.go
new file mode 100644
index 000000000..bde602df6
--- /dev/null
+++ b/app/models/dto/oauth.go
@@ -0,0 +1,20 @@
+package dto
+
+//OAuthUserProfile represents an OAuth user profile
+type OAuthUserProfile struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+}
+
+//OAuthProviderOption represents an OAuth provider that can be used to authenticate
+type OAuthProviderOption struct {
+ Provider string `json:"provider"`
+ DisplayName string `json:"displayName"`
+ ClientID string `json:"clientID"`
+ URL string `json:"url"`
+ CallbackURL string `json:"callbackURL"`
+ LogoBlobKey string `json:"logoBlobKey"`
+ IsCustomProvider bool `json:"isCustomProvider"`
+ IsEnabled bool `json:"isEnabled"`
+}
diff --git a/app/models/dto/props.go b/app/models/dto/props.go
new file mode 100644
index 000000000..f0b4d62ba
--- /dev/null
+++ b/app/models/dto/props.go
@@ -0,0 +1,31 @@
+package dto
+
+import (
+ "database/sql/driver"
+ "encoding/json"
+)
+
+// Props is a map of key:value
+type Props map[string]interface{}
+
+// Value converts props into a database value
+func (p Props) Value() (driver.Value, error) {
+ j, err := json.Marshal(p)
+ return j, err
+}
+
+// Merge current props with given props
+func (p Props) Merge(props Props) Props {
+ new := Props{}
+ if p != nil {
+ for k, v := range p {
+ new[k] = v
+ }
+ }
+ if props != nil {
+ for k, v := range props {
+ new[k] = v
+ }
+ }
+ return new
+}
diff --git a/app/models/dto/props_test.go b/app/models/dto/props_test.go
new file mode 100644
index 000000000..f55df6265
--- /dev/null
+++ b/app/models/dto/props_test.go
@@ -0,0 +1,27 @@
+package dto_test
+
+import (
+ "testing"
+
+ "github.com/getfider/fider/app/models/dto"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+)
+
+func TestPropsMerge(t *testing.T) {
+ RegisterT(t)
+
+ p1 := dto.Props{
+ "name": "Jon",
+ "age": 26,
+ }
+ p2 := p1.Merge(dto.Props{
+ "age": 30,
+ "email": "[email protected]",
+ })
+ Expect(p2).Equals(dto.Props{
+ "name": "Jon",
+ "age": 30,
+ "email": "[email protected]",
+ })
+}
diff --git a/app/models/enum/avatar.go b/app/models/enum/avatar.go
new file mode 100644
index 000000000..9286b355f
--- /dev/null
+++ b/app/models/enum/avatar.go
@@ -0,0 +1,41 @@
+package enum
+
+//AvatarType are the possible types of a user avatar
+type AvatarType int
+
+var (
+ //AvatarTypeLetter is the default avatar type for users
+ AvatarTypeLetter AvatarType = 1
+ //AvatarTypeGravatar fetches avatar from gravatar (if available)
+ AvatarTypeGravatar AvatarType = 2
+ //AvatarTypeCustom uses a user uploaded avatar
+ AvatarTypeCustom AvatarType = 3
+)
+
+var avatarTypesIDs = map[AvatarType]string{
+ AvatarTypeLetter: "letter",
+ AvatarTypeGravatar: "gravatar",
+ AvatarTypeCustom: "custom",
+}
+
+var avatarTypesName = map[string]AvatarType{
+ "letter": AvatarTypeLetter,
+ "gravatar": AvatarTypeGravatar,
+ "custom": AvatarTypeCustom,
+}
+
+// String returns the string version of the user status
+func (t AvatarType) String() string {
+ return avatarTypesIDs[t]
+}
+
+// MarshalText returns the Text version of the avatar type
+func (t AvatarType) MarshalText() ([]byte, error) {
+ return []byte(avatarTypesIDs[t]), nil
+}
+
+// UnmarshalText parse string into a avatar type
+func (t *AvatarType) UnmarshalText(text []byte) error {
+ *t = avatarTypesName[string(text)]
+ return nil
+}
diff --git a/app/models/enum/email_kind.go b/app/models/enum/email_kind.go
new file mode 100644
index 000000000..33a77ae55
--- /dev/null
+++ b/app/models/enum/email_kind.go
@@ -0,0 +1,15 @@
+package enum
+
+//EmailVerificationKind specifies which kind of process is being verified by email
+type EmailVerificationKind int16
+
+const (
+ //EmailVerificationKindSignIn is the sign in by email process
+ EmailVerificationKindSignIn EmailVerificationKind = 1
+ //EmailVerificationKindSignUp is the sign up (create tenant) by name and email process
+ EmailVerificationKindSignUp EmailVerificationKind = 2
+ //EmailVerificationKindChangeEmail is the change user email process
+ EmailVerificationKindChangeEmail EmailVerificationKind = 3
+ //EmailVerificationKindUserInvitation is the sign in invitation sent to an user
+ EmailVerificationKindUserInvitation EmailVerificationKind = 4
+)
diff --git a/app/models/enum/notification.go b/app/models/enum/notification.go
new file mode 100644
index 000000000..35685b4ef
--- /dev/null
+++ b/app/models/enum/notification.go
@@ -0,0 +1,76 @@
+package enum
+
+import (
+ "strconv"
+)
+
+//NotificationChannel represents the medium that the notification is sent
+type NotificationChannel int
+
+var (
+ //NotificationChannelWeb is a in-app notification
+ NotificationChannelWeb NotificationChannel = 1
+ //NotificationChannelEmail is an email notification
+ NotificationChannelEmail NotificationChannel = 2
+)
+
+//NotificationEvent represents all possible notification events
+type NotificationEvent struct {
+ UserSettingsKeyName string
+ DefaultSettingValue string
+ RequiresSubscriptionUserRoles []Role
+ DefaultEnabledUserRoles []Role
+ Validate func(string) bool
+}
+
+func notificationEventValidation(v string) bool {
+ return v == "0" || v == "1" || v == "2" || v == "3"
+}
+
+var (
+ //NotificationEventNewPost is triggered when a new post is posted
+ NotificationEventNewPost = NotificationEvent{
+ UserSettingsKeyName: "event_notification_new_post",
+ DefaultSettingValue: strconv.Itoa(int(NotificationChannelWeb | NotificationChannelEmail)),
+ RequiresSubscriptionUserRoles: []Role{},
+ DefaultEnabledUserRoles: []Role{
+ RoleAdministrator,
+ RoleCollaborator,
+ },
+ Validate: notificationEventValidation,
+ }
+ //NotificationEventNewComment is triggered when a new comment is posted
+ NotificationEventNewComment = NotificationEvent{
+ UserSettingsKeyName: "event_notification_new_comment",
+ DefaultSettingValue: strconv.Itoa(int(NotificationChannelWeb | NotificationChannelEmail)),
+ RequiresSubscriptionUserRoles: []Role{
+ RoleVisitor,
+ },
+ DefaultEnabledUserRoles: []Role{
+ RoleAdministrator,
+ RoleCollaborator,
+ RoleVisitor,
+ },
+ Validate: notificationEventValidation,
+ }
+ //NotificationEventChangeStatus is triggered when a new post has its status changed
+ NotificationEventChangeStatus = NotificationEvent{
+ UserSettingsKeyName: "event_notification_change_status",
+ DefaultSettingValue: strconv.Itoa(int(NotificationChannelWeb | NotificationChannelEmail)),
+ RequiresSubscriptionUserRoles: []Role{
+ RoleVisitor,
+ },
+ DefaultEnabledUserRoles: []Role{
+ RoleAdministrator,
+ RoleCollaborator,
+ RoleVisitor,
+ },
+ Validate: notificationEventValidation,
+ }
+ //AllNotificationEvents contains all possible notification events
+ AllNotificationEvents = []NotificationEvent{
+ NotificationEventNewPost,
+ NotificationEventNewComment,
+ NotificationEventChangeStatus,
+ }
+)
diff --git a/app/models/enum/oauth.go b/app/models/enum/oauth.go
new file mode 100644
index 000000000..46b4ffdd5
--- /dev/null
+++ b/app/models/enum/oauth.go
@@ -0,0 +1,8 @@
+package enum
+
+var (
+ //OAuthConfigDisabled is used to disable an OAuthConfig for signin
+ OAuthConfigDisabled = 1
+ //OAuthConfigEnabled is used to enable an OAuthConfig for public use
+ OAuthConfigEnabled = 2
+)
diff --git a/app/models/enum/post_status.go b/app/models/enum/post_status.go
new file mode 100644
index 000000000..c8e2b0203
--- /dev/null
+++ b/app/models/enum/post_status.go
@@ -0,0 +1,60 @@
+package enum
+
+//PostStatus is the status of a given post
+type PostStatus int
+
+var (
+ //PostOpen is the default status
+ PostOpen PostStatus
+ //PostStarted is used when the post has been accepted and work is in progress
+ PostStarted PostStatus = 1
+ //PostCompleted is used when the post has been accepted and already implemented
+ PostCompleted PostStatus = 2
+ //PostDeclined is used when organizers decide to decline an post
+ PostDeclined PostStatus = 3
+ //PostPlanned is used when organizers have accepted an post and it's on the roadmap
+ PostPlanned PostStatus = 4
+ //PostDuplicate is used when the post has already been posted before
+ PostDuplicate PostStatus = 5
+ //PostDeleted is used when the post is completely removed from the site and should never be shown again
+ PostDeleted PostStatus = 6
+)
+var postStatusIDs = map[PostStatus]string{
+ PostOpen: "open",
+ PostStarted: "started",
+ PostCompleted: "completed",
+ PostDeclined: "declined",
+ PostPlanned: "planned",
+ PostDuplicate: "duplicate",
+ PostDeleted: "deleted",
+}
+
+var postStatusNames = map[string]PostStatus{
+ "open": PostOpen,
+ "started": PostStarted,
+ "completed": PostCompleted,
+ "declined": PostDeclined,
+ "planned": PostPlanned,
+ "duplicate": PostDuplicate,
+ "deleted": PostDeleted,
+}
+
+// MarshalText returns the Text version of the post status
+func (status PostStatus) MarshalText() ([]byte, error) {
+ return []byte(postStatusIDs[status]), nil
+}
+
+// UnmarshalText parse string into a post status
+func (status *PostStatus) UnmarshalText(text []byte) error {
+ *status = postStatusNames[string(text)]
+ return nil
+}
+
+// Name returns the name of a post status
+func (status PostStatus) Name() string {
+ name, ok := postStatusIDs[status]
+ if ok {
+ return name
+ }
+ return "Unknown"
+}
diff --git a/app/models/enum/subscriber.go b/app/models/enum/subscriber.go
new file mode 100644
index 000000000..3a183f056
--- /dev/null
+++ b/app/models/enum/subscriber.go
@@ -0,0 +1,8 @@
+package enum
+
+var (
+ //SubscriberInactive means that the user cancelled the subscription
+ SubscriberInactive = 0
+ //SubscriberActive means that the subscription is active
+ SubscriberActive = 1
+)
diff --git a/app/models/enum/tenant_status.go b/app/models/enum/tenant_status.go
new file mode 100644
index 000000000..0ca4bc307
--- /dev/null
+++ b/app/models/enum/tenant_status.go
@@ -0,0 +1,10 @@
+package enum
+
+var (
+ //TenantActive is the default status for most tenants
+ TenantActive = 1
+ //TenantPending is used for signup via email that requires user confirmation
+ TenantPending = 2
+ //TenantLocked is used when tenants are locked for various reasons
+ TenantLocked = 3
+)
diff --git a/app/models/enum/user_role.go b/app/models/enum/user_role.go
new file mode 100644
index 000000000..7af03f64b
--- /dev/null
+++ b/app/models/enum/user_role.go
@@ -0,0 +1,36 @@
+package enum
+
+//Role is the role of a user inside a tenant
+type Role int
+
+const (
+ //RoleVisitor is the basic role for every user
+ RoleVisitor Role = 1
+ //RoleCollaborator has limited access to administrative console
+ RoleCollaborator Role = 2
+ //RoleAdministrator has full access to administrative console
+ RoleAdministrator Role = 3
+)
+
+var roleIDs = map[Role]string{
+ RoleVisitor: "visitor",
+ RoleCollaborator: "collaborator",
+ RoleAdministrator: "administrator",
+}
+
+var roleNames = map[string]Role{
+ "visitor": RoleVisitor,
+ "collaborator": RoleCollaborator,
+ "administrator": RoleAdministrator,
+}
+
+// MarshalText returns the Text version of the user role
+func (role Role) MarshalText() ([]byte, error) {
+ return []byte(roleIDs[role]), nil
+}
+
+// UnmarshalText parse string into a user role
+func (role *Role) UnmarshalText(text []byte) error {
+ *role = roleNames[string(text)]
+ return nil
+}
diff --git a/app/models/enum/user_status.go b/app/models/enum/user_status.go
new file mode 100644
index 000000000..e72fc31f4
--- /dev/null
+++ b/app/models/enum/user_status.go
@@ -0,0 +1,36 @@
+package enum
+
+//UserStatus is the status of a user
+type UserStatus int
+
+var (
+ //UserActive is the default status for users
+ UserActive UserStatus = 1
+ //UserDeleted is used for users that chose to delete their accounts
+ UserDeleted UserStatus = 2
+ //UserBlocked is used for users that have been blocked by staff members
+ UserBlocked UserStatus = 3
+)
+
+var userStatusIDs = map[UserStatus]string{
+ UserActive: "active",
+ UserDeleted: "deleted",
+ UserBlocked: "blocked",
+}
+
+var userStatusName = map[string]UserStatus{
+ "active": UserActive,
+ "deleted": UserDeleted,
+ "blocked": UserBlocked,
+}
+
+// MarshalText returns the Text version of the user status
+func (status UserStatus) MarshalText() ([]byte, error) {
+ return []byte(userStatusIDs[status]), nil
+}
+
+// UnmarshalText parse string into a user status
+func (status *UserStatus) UnmarshalText(text []byte) error {
+ *status = userStatusName[string(text)]
+ return nil
+}
diff --git a/app/models/feedback.go b/app/models/feedback.go
index 67092cc0e..4ba993b6e 100644
--- a/app/models/feedback.go
+++ b/app/models/feedback.go
@@ -1,25 +1,26 @@
package models
import (
- "strconv"
"time"
+
+ "github.com/getfider/fider/app/models/enum"
)
//Post represents an post on a tenant board
type Post struct {
- ID int `json:"id"`
- Number int `json:"number"`
- Title string `json:"title"`
- Slug string `json:"slug"`
- Description string `json:"description"`
- CreatedAt time.Time `json:"createdAt"`
- User *User `json:"user"`
- HasVoted bool `json:"hasVoted"`
- VotesCount int `json:"votesCount"`
- CommentsCount int `json:"commentsCount"`
- Status PostStatus `json:"status"`
- Response *PostResponse `json:"response,omitempty"`
- Tags []string `json:"tags"`
+ ID int `json:"id"`
+ Number int `json:"number"`
+ Title string `json:"title"`
+ Slug string `json:"slug"`
+ Description string `json:"description"`
+ CreatedAt time.Time `json:"createdAt"`
+ User *User `json:"user"`
+ HasVoted bool `json:"hasVoted"`
+ VotesCount int `json:"votesCount"`
+ CommentsCount int `json:"commentsCount"`
+ Status enum.PostStatus `json:"status"`
+ Response *PostResponse `json:"response,omitempty"`
+ Tags []string `json:"tags"`
}
//VoteUser represents a user that voted on a post
@@ -38,7 +39,7 @@ type Vote struct {
// CanBeVoted returns true if this post can have its vote changed
func (i *Post) CanBeVoted() bool {
- return i.Status != PostCompleted && i.Status != PostDeclined && i.Status != PostDuplicate
+ return i.Status != enum.PostCompleted && i.Status != enum.PostDeclined && i.Status != enum.PostDuplicate
}
// NewPost represents a new post
@@ -85,10 +86,10 @@ type DeleteComment struct {
// SetResponse represents the action to update an post response
type SetResponse struct {
- Number int `route:"number"`
- Status PostStatus `json:"status"`
- Text string `json:"text"`
- OriginalNumber int `json:"originalNumber"`
+ Number int `route:"number"`
+ Status enum.PostStatus `json:"status"`
+ Text string `json:"text"`
+ OriginalNumber int `json:"originalNumber"`
}
//PostResponse is a staff response to a given post
@@ -101,10 +102,10 @@ type PostResponse struct {
//OriginalPost holds details of the original post of a duplicate
type OriginalPost struct {
- Number int `json:"number"`
- Title string `json:"title"`
- Slug string `json:"slug"`
- Status PostStatus `json:"status"`
+ Number int `json:"number"`
+ Title string `json:"title"`
+ Slug string `json:"slug"`
+ Status enum.PostStatus `json:"status"`
}
//Comment represents an user comment on an post
@@ -145,140 +146,3 @@ type AssignUnassignTag struct {
Slug string `route:"slug"`
Number int `route:"number"`
}
-
-//PostStatus is the status of a given post
-type PostStatus int
-
-var (
- //PostOpen is the default status
- PostOpen PostStatus
- //PostStarted is used when the post has been accepted and work is in progress
- PostStarted PostStatus = 1
- //PostCompleted is used when the post has been accepted and already implemented
- PostCompleted PostStatus = 2
- //PostDeclined is used when organizers decide to decline an post
- PostDeclined PostStatus = 3
- //PostPlanned is used when organizers have accepted an post and it's on the roadmap
- PostPlanned PostStatus = 4
- //PostDuplicate is used when the post has already been posted before
- PostDuplicate PostStatus = 5
- //PostDeleted is used when the post is completely removed from the site and should never be shown again
- PostDeleted PostStatus = 6
-)
-var postStatusIDs = map[PostStatus]string{
- PostOpen: "open",
- PostStarted: "started",
- PostCompleted: "completed",
- PostDeclined: "declined",
- PostPlanned: "planned",
- PostDuplicate: "duplicate",
- PostDeleted: "deleted",
-}
-
-var postStatusNames = map[string]PostStatus{
- "open": PostOpen,
- "started": PostStarted,
- "completed": PostCompleted,
- "declined": PostDeclined,
- "planned": PostPlanned,
- "duplicate": PostDuplicate,
- "deleted": PostDeleted,
-}
-
-// MarshalText returns the Text version of the post status
-func (status PostStatus) MarshalText() ([]byte, error) {
- return []byte(postStatusIDs[status]), nil
-}
-
-// UnmarshalText parse string into a post status
-func (status *PostStatus) UnmarshalText(text []byte) error {
- *status = postStatusNames[string(text)]
- return nil
-}
-
-// Name returns the name of a post status
-func (status PostStatus) Name() string {
- name, ok := postStatusIDs[status]
- if ok {
- return name
- }
- return "Unknown"
-}
-
-var (
- //SubscriberInactive means that the user cancelled the subscription
- SubscriberInactive = 0
- //SubscriberActive means that the subscription is active
- SubscriberActive = 1
-)
-
-//NotificationChannel represents the medium that the notification is sent
-type NotificationChannel int
-
-var (
- //NotificationChannelWeb is a in-app notification
- NotificationChannelWeb NotificationChannel = 1
- //NotificationChannelEmail is an email notification
- NotificationChannelEmail NotificationChannel = 2
-)
-
-//NotificationEvent represents all possible notification events
-type NotificationEvent struct {
- UserSettingsKeyName string
- DefaultSettingValue string
- RequiresSubscriptionUserRoles []Role
- DefaultEnabledUserRoles []Role
- Validate func(string) bool
-}
-
-func notificationEventValidation(v string) bool {
- return v == "0" || v == "1" || v == "2" || v == "3"
-}
-
-var (
- //NotificationEventNewPost is triggered when a new post is posted
- NotificationEventNewPost = NotificationEvent{
- UserSettingsKeyName: "event_notification_new_post",
- DefaultSettingValue: strconv.Itoa(int(NotificationChannelWeb | NotificationChannelEmail)),
- RequiresSubscriptionUserRoles: []Role{},
- DefaultEnabledUserRoles: []Role{
- RoleAdministrator,
- RoleCollaborator,
- },
- Validate: notificationEventValidation,
- }
- //NotificationEventNewComment is triggered when a new comment is posted
- NotificationEventNewComment = NotificationEvent{
- UserSettingsKeyName: "event_notification_new_comment",
- DefaultSettingValue: strconv.Itoa(int(NotificationChannelWeb | NotificationChannelEmail)),
- RequiresSubscriptionUserRoles: []Role{
- RoleVisitor,
- },
- DefaultEnabledUserRoles: []Role{
- RoleAdministrator,
- RoleCollaborator,
- RoleVisitor,
- },
- Validate: notificationEventValidation,
- }
- //NotificationEventChangeStatus is triggered when a new post has its status changed
- NotificationEventChangeStatus = NotificationEvent{
- UserSettingsKeyName: "event_notification_change_status",
- DefaultSettingValue: strconv.Itoa(int(NotificationChannelWeb | NotificationChannelEmail)),
- RequiresSubscriptionUserRoles: []Role{
- RoleVisitor,
- },
- DefaultEnabledUserRoles: []Role{
- RoleAdministrator,
- RoleCollaborator,
- RoleVisitor,
- },
- Validate: notificationEventValidation,
- }
- //AllNotificationEvents contains all possible notification events
- AllNotificationEvents = []NotificationEvent{
- NotificationEventNewPost,
- NotificationEventNewComment,
- NotificationEventChangeStatus,
- }
-)
diff --git a/app/models/identity.go b/app/models/identity.go
index 0d19595e3..ce4d0d7f3 100644
--- a/app/models/identity.go
+++ b/app/models/identity.go
@@ -3,6 +3,7 @@ package models
import (
"time"
+ "github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/rand"
)
@@ -22,15 +23,6 @@ type Tenant struct {
CustomCSS string `json:"-"`
}
-var (
- //TenantActive is the default status for most tenants
- TenantActive = 1
- //TenantPending is used for signup via email that requires user confirmation
- TenantPending = 2
- //TenantLocked is used when tenants are locked for various reasons
- TenantLocked = 3
-)
-
//TenantBilling has all the billing information of given tenant
type TenantBilling struct {
StripeCustomerID string
@@ -53,138 +45,14 @@ type User struct {
Name string `json:"name"`
Tenant *Tenant `json:"-"`
Email string `json:"-"`
- Role Role `json:"role"`
+ Role enum.Role `json:"role"`
Providers []*UserProvider `json:"-"`
AvatarBlobKey string `json:"-"`
- AvatarType AvatarType `json:"-"`
+ AvatarType enum.AvatarType `json:"-"`
AvatarURL string `json:"avatarURL,omitempty"`
- Status UserStatus `json:"status"`
-}
-
-//AvatarType are the possible types of a user avatar
-type AvatarType int
-
-var (
- //AvatarTypeLetter is the default avatar type for users
- AvatarTypeLetter AvatarType = 1
- //AvatarTypeGravatar fetches avatar from gravatar (if available)
- AvatarTypeGravatar AvatarType = 2
- //AvatarTypeCustom uses a user uploaded avatar
- AvatarTypeCustom AvatarType = 3
-)
-
-var avatarTypesIDs = map[AvatarType]string{
- AvatarTypeLetter: "letter",
- AvatarTypeGravatar: "gravatar",
- AvatarTypeCustom: "custom",
-}
-
-var avatarTypesName = map[string]AvatarType{
- "letter": AvatarTypeLetter,
- "gravatar": AvatarTypeGravatar,
- "custom": AvatarTypeCustom,
-}
-
-// String returns the string version of the user status
-func (t AvatarType) String() string {
- return avatarTypesIDs[t]
+ Status enum.UserStatus `json:"status"`
}
-// MarshalText returns the Text version of the avatar type
-func (t AvatarType) MarshalText() ([]byte, error) {
- return []byte(avatarTypesIDs[t]), nil
-}
-
-// UnmarshalText parse string into a avatar type
-func (t *AvatarType) UnmarshalText(text []byte) error {
- *t = avatarTypesName[string(text)]
- return nil
-}
-
-//UserStatus is the status of a user
-type UserStatus int
-
-var (
- //UserActive is the default status for users
- UserActive UserStatus = 1
- //UserDeleted is used for users that chose to delete their accounts
- UserDeleted UserStatus = 2
- //UserBlocked is used for users that have been blocked by staff members
- UserBlocked UserStatus = 3
-)
-
-var userStatusIDs = map[UserStatus]string{
- UserActive: "active",
- UserDeleted: "deleted",
- UserBlocked: "blocked",
-}
-
-var userStatusName = map[string]UserStatus{
- "active": UserActive,
- "deleted": UserDeleted,
- "blocked": UserBlocked,
-}
-
-// MarshalText returns the Text version of the user status
-func (status UserStatus) MarshalText() ([]byte, error) {
- return []byte(userStatusIDs[status]), nil
-}
-
-// UnmarshalText parse string into a user status
-func (status *UserStatus) UnmarshalText(text []byte) error {
- *status = userStatusName[string(text)]
- return nil
-}
-
-//Role is the role of a user inside a tenant
-type Role int
-
-const (
- //RoleVisitor is the basic role for every user
- RoleVisitor Role = 1
- //RoleCollaborator has limited access to administrative console
- RoleCollaborator Role = 2
- //RoleAdministrator has full access to administrative console
- RoleAdministrator Role = 3
-)
-
-var roleIDs = map[Role]string{
- RoleVisitor: "visitor",
- RoleCollaborator: "collaborator",
- RoleAdministrator: "administrator",
-}
-
-var roleNames = map[string]Role{
- "visitor": RoleVisitor,
- "collaborator": RoleCollaborator,
- "administrator": RoleAdministrator,
-}
-
-// MarshalText returns the Text version of the user role
-func (role Role) MarshalText() ([]byte, error) {
- return []byte(roleIDs[role]), nil
-}
-
-// UnmarshalText parse string into a user role
-func (role *Role) UnmarshalText(text []byte) error {
- *role = roleNames[string(text)]
- return nil
-}
-
-//EmailVerificationKind specifies which kind of process is being verified by email
-type EmailVerificationKind int16
-
-const (
- //EmailVerificationKindSignIn is the sign in by email process
- EmailVerificationKindSignIn EmailVerificationKind = 1
- //EmailVerificationKindSignUp is the sign up (create tenant) by name and email process
- EmailVerificationKindSignUp EmailVerificationKind = 2
- //EmailVerificationKindChangeEmail is the change user email process
- EmailVerificationKindChangeEmail EmailVerificationKind = 3
- //EmailVerificationKindUserInvitation is the sign in invitation sent to an user
- EmailVerificationKindUserInvitation EmailVerificationKind = 4
-)
-
//HasProvider returns true if current user has registered with given provider
func (u *User) HasProvider(provider string) bool {
for _, p := range u.Providers {
@@ -197,12 +65,12 @@ func (u *User) HasProvider(provider string) bool {
// IsCollaborator returns true if user has special permissions
func (u *User) IsCollaborator() bool {
- return u.Role == RoleCollaborator || u.Role == RoleAdministrator
+ return u.Role == enum.RoleCollaborator || u.Role == enum.RoleAdministrator
}
// IsAdministrator returns true if user is administrator
func (u *User) IsAdministrator() bool {
- return u.Role == RoleAdministrator
+ return u.Role == enum.RoleAdministrator
}
//UserProvider represents the relationship between an User and an Authentication provide
@@ -239,8 +107,8 @@ func (e *CreateTenant) GetUser() *User {
}
//GetKind returns EmailVerificationKindSignUp
-func (e *CreateTenant) GetKind() EmailVerificationKind {
- return EmailVerificationKindSignUp
+func (e *CreateTenant) GetKind() enum.EmailVerificationKind {
+ return enum.EmailVerificationKindSignUp
}
//UpdateTenantSettings is the input model used to update tenant general settings
@@ -298,8 +166,8 @@ func (e *SignInByEmail) GetUser() *User {
}
//GetKind returns EmailVerificationKindSignIn
-func (e *SignInByEmail) GetKind() EmailVerificationKind {
- return EmailVerificationKindSignIn
+func (e *SignInByEmail) GetKind() enum.EmailVerificationKind {
+ return enum.EmailVerificationKindSignIn
}
//ChangeUserEmail is the input model used to change current user's email
@@ -325,8 +193,8 @@ func (e *ChangeUserEmail) GetUser() *User {
}
//GetKind returns EmailVerificationKindSignIn
-func (e *ChangeUserEmail) GetKind() EmailVerificationKind {
- return EmailVerificationKindChangeEmail
+func (e *ChangeUserEmail) GetKind() enum.EmailVerificationKind {
+ return enum.EmailVerificationKindChangeEmail
}
//UserInvitation is the model used to register an invite sent to an user
@@ -351,8 +219,8 @@ func (e *UserInvitation) GetUser() *User {
}
//GetKind returns EmailVerificationKindUserInvitation
-func (e *UserInvitation) GetKind() EmailVerificationKind {
- return EmailVerificationKindUserInvitation
+func (e *UserInvitation) GetKind() enum.EmailVerificationKind {
+ return enum.EmailVerificationKindUserInvitation
}
//NewEmailVerification is used to register a new email verification process
@@ -360,7 +228,7 @@ type NewEmailVerification interface {
GetEmail() string
GetName() string
GetUser() *User
- GetKind() EmailVerificationKind
+ GetKind() enum.EmailVerificationKind
}
//EmailVerification is the model used by email verification process
@@ -369,7 +237,7 @@ type EmailVerification struct {
Name string
Key string
UserID int
- Kind EmailVerificationKind
+ Kind enum.EmailVerificationKind
CreatedAt time.Time
ExpiresAt time.Time
VerifiedAt *time.Time
@@ -385,7 +253,7 @@ type CompleteProfile struct {
// UpdateUserSettings is the model used to update user's settings
type UpdateUserSettings struct {
Name string `json:"name"`
- AvatarType AvatarType `json:"avatarType"`
+ AvatarType enum.AvatarType `json:"avatarType"`
Avatar *ImageUpload `json:"avatar"`
Settings map[string]string `json:"settings"`
}
@@ -399,8 +267,8 @@ type CreateUser struct {
// ChangeUserRole is the input model change role of an user
type ChangeUserRole struct {
- Role Role `route:"role"`
- UserID int `json:"userID"`
+ Role enum.Role `route:"role"`
+ UserID int `json:"userID"`
}
// InviteUsers is used to invite new users into Fider
diff --git a/app/models/infra.go b/app/models/infra.go
index 52d8a5e53..040bd41f4 100644
--- a/app/models/infra.go
+++ b/app/models/infra.go
@@ -86,13 +86,6 @@ func (o OAuthConfig) MarshalJSON() ([]byte, error) {
})
}
-var (
- //OAuthConfigDisabled is used to disable an OAuthConfig for signin
- OAuthConfigDisabled = 1
- //OAuthConfigEnabled is used to enable an OAuthConfig for public use
- OAuthConfigEnabled = 2
-)
-
// APIAuthorize is used during API Authorize process
type APIAuthorize struct {
APIKey string `json:"apiKey"`
diff --git a/app/models/query/attachment.go b/app/models/query/attachment.go
new file mode 100644
index 000000000..53749a69f
--- /dev/null
+++ b/app/models/query/attachment.go
@@ -0,0 +1,10 @@
+package query
+
+import "github.com/getfider/fider/app/models"
+
+type GetAttachments struct {
+ Post *models.Post
+ Comment *models.Comment
+
+ Result []string
+}
diff --git a/app/models/query/billing.go b/app/models/query/billing.go
new file mode 100644
index 000000000..78bd4c099
--- /dev/null
+++ b/app/models/query/billing.go
@@ -0,0 +1,34 @@
+package query
+
+import "github.com/getfider/fider/app/models/dto"
+
+type ListBillingPlans struct {
+ CountryCode string
+
+ Result []*dto.BillingPlan
+}
+
+type GetBillingPlanByID struct {
+ PlanID string
+ CountryCode string
+
+ Result *dto.BillingPlan
+}
+
+type GetUpcomingInvoice struct {
+ Result *dto.UpcomingInvoice
+}
+
+type GetPaymentInfo struct {
+ Result *dto.PaymentInfo
+}
+
+type GetAllCountries struct {
+ Result []*dto.Country
+}
+
+type GetCountryByCode struct {
+ Code string
+
+ Result *dto.Country
+}
diff --git a/app/models/query/blob.go b/app/models/query/blob.go
new file mode 100644
index 000000000..8d786d629
--- /dev/null
+++ b/app/models/query/blob.go
@@ -0,0 +1,9 @@
+package query
+
+import "github.com/getfider/fider/app/models/dto"
+
+type GetBlobByKey struct {
+ Key string
+
+ Result *dto.Blob
+}
diff --git a/app/models/query/comment.go b/app/models/query/comment.go
new file mode 100644
index 000000000..86c02b851
--- /dev/null
+++ b/app/models/query/comment.go
@@ -0,0 +1,15 @@
+package query
+
+import "github.com/getfider/fider/app/models"
+
+type GetCommentByID struct {
+ CommentID int
+
+ Result *models.Comment
+}
+
+type GetCommentsByPost struct {
+ Post *models.Post
+
+ Result []*models.Comment
+}
diff --git a/app/models/query/notification.go b/app/models/query/notification.go
new file mode 100644
index 000000000..3cd2f62b3
--- /dev/null
+++ b/app/models/query/notification.go
@@ -0,0 +1,27 @@
+package query
+
+import (
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+)
+
+type CountUnreadNotifications struct {
+ Result int
+}
+
+type GetNotificationByID struct {
+ ID int
+ Result *models.Notification
+}
+
+type GetActiveNotifications struct {
+ Result []*models.Notification
+}
+
+type GetActiveSubscribers struct {
+ Number int
+ Channel enum.NotificationChannel
+ Event enum.NotificationEvent
+
+ Result []*models.User
+}
diff --git a/app/models/query/oauth.go b/app/models/query/oauth.go
new file mode 100644
index 000000000..c81c80220
--- /dev/null
+++ b/app/models/query/oauth.go
@@ -0,0 +1,46 @@
+package query
+
+import (
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/dto"
+)
+
+type GetCustomOAuthConfigByProvider struct {
+ Provider string
+
+ Result *models.OAuthConfig
+}
+
+type ListCustomOAuthConfig struct {
+ Result []*models.OAuthConfig
+}
+
+type GetOAuthAuthorizationURL struct {
+ Provider string
+ Redirect string
+ Identifier string
+
+ Result string
+}
+
+type GetOAuthProfile struct {
+ Provider string
+ Code string
+
+ Result *dto.OAuthUserProfile
+}
+
+type GetOAuthRawProfile struct {
+ Provider string
+ Code string
+
+ Result string
+}
+
+type ListActiveOAuthProviders struct {
+ Result []*dto.OAuthProviderOption
+}
+
+type ListAllOAuthProviders struct {
+ Result []*dto.OAuthProviderOption
+}
diff --git a/app/models/query/post.go b/app/models/query/post.go
new file mode 100644
index 000000000..5d0f13233
--- /dev/null
+++ b/app/models/query/post.go
@@ -0,0 +1,47 @@
+package query
+
+import (
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+)
+
+type PostIsReferenced struct {
+ PostID int
+
+ Result bool
+}
+
+type CountPostPerStatus struct {
+ Result map[enum.PostStatus]int
+}
+
+type GetPostByID struct {
+ PostID int
+
+ Result *models.Post
+}
+
+type GetPostBySlug struct {
+ Slug string
+
+ Result *models.Post
+}
+
+type GetPostByNumber struct {
+ Number int
+
+ Result *models.Post
+}
+
+type SearchPosts struct {
+ Query string
+ View string
+ Limit string
+ Tags []string
+
+ Result []*models.Post
+}
+
+type GetAllPosts struct {
+ Result []*models.Post
+}
diff --git a/app/models/query/tag.go b/app/models/query/tag.go
new file mode 100644
index 000000000..6fb147737
--- /dev/null
+++ b/app/models/query/tag.go
@@ -0,0 +1,19 @@
+package query
+
+import "github.com/getfider/fider/app/models"
+
+type GetTagBySlug struct {
+ Slug string
+
+ Result *models.Tag
+}
+
+type GetAssignedTags struct {
+ Post *models.Post
+
+ Result []*models.Tag
+}
+
+type GetAllTags struct {
+ Result []*models.Tag
+}
diff --git a/app/models/query/tenant.go b/app/models/query/tenant.go
new file mode 100644
index 000000000..416752d36
--- /dev/null
+++ b/app/models/query/tenant.go
@@ -0,0 +1,35 @@
+package query
+
+import (
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
+)
+
+type IsCNAMEAvailable struct {
+ CNAME string
+
+ Result bool
+}
+
+type IsSubdomainAvailable struct {
+ Subdomain string
+
+ Result bool
+}
+
+type GetVerificationByKey struct {
+ Kind enum.EmailVerificationKind
+ Key string
+
+ Result *models.EmailVerification
+}
+
+type GetFirstTenant struct {
+ Result *models.Tenant
+}
+
+type GetTenantByDomain struct {
+ Domain string
+
+ Result *models.Tenant
+}
diff --git a/app/models/query/user.go b/app/models/query/user.go
new file mode 100644
index 000000000..b44111b72
--- /dev/null
+++ b/app/models/query/user.go
@@ -0,0 +1,46 @@
+package query
+
+import "github.com/getfider/fider/app/models"
+
+type CountUsers struct {
+ Result int
+}
+
+type UserSubscribedTo struct {
+ PostID int
+
+ Result bool
+}
+
+type GetUserByAPIKey struct {
+ APIKey string
+
+ Result *models.User
+}
+
+type GetCurrentUserSettings struct {
+ Result map[string]string
+}
+
+type GetUserByID struct {
+ UserID int
+
+ Result *models.User
+}
+
+type GetUserByEmail struct {
+ Email string
+
+ Result *models.User
+}
+
+type GetUserByProvider struct {
+ Provider string
+ UID string
+
+ Result *models.User
+}
+
+type GetAllUsers struct {
+ Result []*models.User
+}
diff --git a/app/models/query/vote.go b/app/models/query/vote.go
new file mode 100644
index 000000000..a4b0a47d3
--- /dev/null
+++ b/app/models/query/vote.go
@@ -0,0 +1,10 @@
+package query
+
+import "github.com/getfider/fider/app/models"
+
+type ListPostVotes struct {
+ PostID int
+ Limit int
+
+ Result []*models.Vote
+}
diff --git a/app/pkg/assert/assert.go b/app/pkg/assert/assert.go
index 66efb2121..a14565836 100644
--- a/app/pkg/assert/assert.go
+++ b/app/pkg/assert/assert.go
@@ -9,6 +9,7 @@ import (
"testing"
"time"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
)
@@ -42,6 +43,7 @@ var envVariables map[string]string
//RegisterT saves current testing.T for further usage by Expect
func RegisterT(t *testing.T) {
+ bus.Reset()
if currentT == nil {
copyEnv()
}
diff --git a/app/pkg/billing/stripe.go b/app/pkg/billing/stripe.go
deleted file mode 100644
index 74f8e22c4..000000000
--- a/app/pkg/billing/stripe.go
+++ /dev/null
@@ -1,412 +0,0 @@
-package billing
-
-import (
- "fmt"
- "sort"
- "strconv"
- "strings"
- "sync"
- "time"
-
- "github.com/goenning/vat"
-
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/errors"
- stripe "github.com/stripe/stripe-go"
- "github.com/stripe/stripe-go/client"
-)
-
-var stripeClient *client.API
-var mu sync.RWMutex
-var plans []*models.BillingPlan
-
-func init() {
- stripe.LogLevel = 0
- stripeClient = &client.API{}
- stripeClient.Init(env.Config.Stripe.SecretKey, nil)
-}
-
-// Client is a billing client wrapper for Stripe
-type Client struct {
- stripe *client.API
- tenant *models.Tenant
- user *models.User
-}
-
-// NewClient creates a new billing client
-func NewClient() *Client {
- return &Client{
- stripe: stripeClient,
- }
-}
-
-// SetCurrentTenant to current context
-func (c *Client) SetCurrentTenant(tenant *models.Tenant) {
- c.tenant = tenant
-}
-
-// SetCurrentUser to current context
-func (c *Client) SetCurrentUser(user *models.User) {
- c.user = user
-}
-
-// CreateCustomer on Stripe
-func (c *Client) CreateCustomer(email string) (string, error) {
- if c.tenant.Billing == nil {
- return "", errors.New("Tenant doesn't have a billing record")
- }
-
- if c.tenant.Billing.StripeCustomerID == "" {
- params := &stripe.CustomerParams{
- Email: stripe.String(email),
- Description: stripe.String(c.tenant.Name),
- }
- params.AddMetadata("tenant_id", strconv.Itoa(c.tenant.ID))
- params.AddMetadata("tenant_subdomain", c.tenant.Subdomain)
- customer, err := c.stripe.Customers.New(params)
- if err != nil {
- return "", errors.Wrap(err, "failed to create Stripe customer")
- }
- c.tenant.Billing.StripeCustomerID = customer.ID
- return customer.ID, nil
- }
-
- return c.tenant.Billing.StripeCustomerID, nil
-}
-
-// DeleteCustomer on Stripe
-func (c *Client) DeleteCustomer() error {
- if !env.IsTest() {
- return errors.New("Stripe customer can only be deleted on test mode")
- }
-
- _, err := c.stripe.Customers.Del(c.tenant.Billing.StripeCustomerID, &stripe.CustomerParams{})
- if err != nil {
- return errors.Wrap(err, "failed to delete Stripe customer")
- }
- return nil
-}
-
-// GetPaymentInfo from a stripe card
-func (c *Client) GetPaymentInfo() (*models.PaymentInfo, error) {
- if c.tenant.Billing == nil || c.tenant.Billing.StripeCustomerID == "" {
- return nil, nil
- }
-
- customerID := c.tenant.Billing.StripeCustomerID
-
- customer, err := c.stripe.Customers.Get(customerID, &stripe.CustomerParams{})
- if err != nil {
- return nil, errors.Wrap(err, "failed to get customer")
- }
-
- if customer.Metadata["tenant_id"] != strconv.Itoa(c.tenant.ID) {
- panic(fmt.Sprintf("Stripe TenantID (%s) doesn't match current Tenant ID (%s). Aborting.", customer.Metadata["tenant_id"], strconv.Itoa(c.tenant.ID)))
- }
-
- if customer.DefaultSource == nil {
- return nil, nil
- }
-
- card, err := c.stripe.Cards.Get(customer.DefaultSource.ID, &stripe.CardParams{
- Customer: stripe.String(customerID),
- })
- if err != nil {
- return nil, errors.Wrap(err, "failed to get customer's card")
- }
-
- info := &models.PaymentInfo{
- Email: customer.Email,
- Name: card.Name,
- StripeCardID: card.ID,
- CardCountry: card.Country,
- CardBrand: string(card.Brand),
- CardLast4: card.Last4,
- CardExpMonth: card.ExpMonth,
- CardExpYear: card.ExpYear,
- AddressCity: card.AddressCity,
- AddressCountry: card.AddressCountry,
- AddressLine1: card.AddressLine1,
- AddressLine2: card.AddressLine2,
- AddressState: card.AddressState,
- AddressPostalCode: card.AddressZip,
- }
-
- if customer.TaxInfo != nil {
- info.VATNumber = customer.TaxInfo.TaxID
- }
-
- return info, nil
-}
-
-// ClearPaymentInfo removes all payment information from stripe
-func (c *Client) ClearPaymentInfo() error {
- current, err := c.GetPaymentInfo()
- if err != nil {
- return err
- }
-
- if current != nil {
- customerID := c.tenant.Billing.StripeCustomerID
- _, err = c.stripe.Customers.Update(customerID, &stripe.CustomerParams{
- Description: stripe.String(c.tenant.Name),
- Email: stripe.String(""),
- TaxInfo: &stripe.CustomerTaxInfoParams{
- Type: stripe.String(string(stripe.CustomerTaxInfoTypeVAT)),
- TaxID: stripe.String(""),
- },
- })
- if err != nil {
- return errors.Wrap(err, "failed to delete customer billing email")
- }
- if current.StripeCardID != "" {
- _, err = c.stripe.Cards.Del(current.StripeCardID, &stripe.CardParams{
- Customer: stripe.String(customerID),
- })
- if err != nil {
- return errors.Wrap(err, "failed to delete customer card")
- }
- }
- }
-
- return nil
-}
-
-// UpdatePaymentInfo creates or updates customer payment info on Stripe
-func (c *Client) UpdatePaymentInfo(input *models.CreateEditBillingPaymentInfo) error {
- customerID := c.tenant.Billing.StripeCustomerID
- current, err := c.GetPaymentInfo()
- if err != nil {
- return err
- }
-
- if !vat.IsEU(input.AddressCountry) {
- input.VATNumber = ""
- }
-
- // update customer info
- params := &stripe.CustomerParams{
- Email: stripe.String(input.Email),
- Description: stripe.String(input.Name),
- Shipping: &stripe.CustomerShippingDetailsParams{
- Name: stripe.String(input.Name),
- Address: &stripe.AddressParams{
- City: stripe.String(input.AddressCity),
- Country: stripe.String(input.AddressCountry),
- Line1: stripe.String(input.AddressLine1),
- Line2: stripe.String(input.AddressLine2),
- PostalCode: stripe.String(input.AddressPostalCode),
- State: stripe.String(input.AddressState),
- },
- },
- TaxInfo: &stripe.CustomerTaxInfoParams{
- Type: stripe.String(string(stripe.CustomerTaxInfoTypeVAT)),
- TaxID: stripe.String(input.VATNumber),
- },
- }
- _, err = c.stripe.Customers.Update(customerID, params)
- if err != nil {
- return errors.Wrap(err, "failed to update customer billing email")
- }
-
- // new card, just create it
- if current == nil || current.StripeCardID == "" {
- _, err = c.stripe.Cards.New(&stripe.CardParams{
- Customer: stripe.String(customerID),
- Token: stripe.String(input.Card.Token),
- })
- if err != nil {
- return errors.Wrap(err, "failed to create stripe card")
- }
- return nil
- }
-
- // replacing card, create new and delete old
- if input.Card != nil && input.Card.Token != "" {
- _, err = c.stripe.Cards.New(&stripe.CardParams{
- Customer: stripe.String(customerID),
- Token: stripe.String(input.Card.Token),
- })
- if err != nil {
- return errors.Wrap(err, "failed to create new stripe card")
- }
-
- _, err = c.stripe.Cards.Del(current.StripeCardID, &stripe.CardParams{
- Customer: stripe.String(customerID),
- Token: stripe.String(input.Card.Token),
- })
- if err != nil {
- return errors.Wrap(err, "failed to delete old stripe card")
- }
- return nil
- }
-
- // updating card, just update current card
- _, err = c.stripe.Cards.Update(current.StripeCardID, &stripe.CardParams{
- Customer: stripe.String(customerID),
- Name: stripe.String(input.Name),
- AddressCity: stripe.String(input.AddressCity),
- AddressCountry: stripe.String(input.AddressCountry),
- AddressLine1: stripe.String(input.AddressLine1),
- AddressLine2: stripe.String(input.AddressLine2),
- AddressState: stripe.String(input.AddressState),
- AddressZip: stripe.String(input.AddressPostalCode),
- })
- if err != nil {
- return errors.Wrap(err, "failed to update stripe card")
- }
- return nil
-}
-
-// GetPlanByID return a plan by its ID
-func (c *Client) GetPlanByID(countryCode, planID string) (*models.BillingPlan, error) {
- plans, err := c.ListPlans(countryCode)
- if err != nil {
- return nil, err
- }
-
- for _, plan := range plans {
- if plan.ID == planID {
- return plan, nil
- }
- }
- return nil, errors.New("failed to get plan by id: " + planID)
-}
-
-// ListPlans on Stripe
-func (c *Client) ListPlans(countryCode string) ([]*models.BillingPlan, error) {
- if plans != nil {
- return c.filterByCountryCode(plans, countryCode), nil
- }
-
- mu.Lock()
- defer mu.Unlock()
-
- if plans == nil {
- plans = make([]*models.BillingPlan, 0)
- it := c.stripe.Plans.List(&stripe.PlanListParams{
- Active: stripe.Bool(true),
- })
- for it.Next() {
- plan := it.Plan()
- name, ok := plan.Metadata["friendly_name"]
- if !ok {
- name = plan.Nickname
- }
- maxUsers, _ := strconv.Atoi(plan.Metadata["max_users"])
- plans = append(plans, &models.BillingPlan{
- ID: plan.ID,
- Name: name,
- Description: plan.Metadata["description"],
- MaxUsers: maxUsers,
- Price: plan.Amount,
- Currency: strings.ToUpper(string(plan.Currency)),
- Interval: string(plan.Interval),
- })
- }
- if err := it.Err(); err != nil {
- return nil, err
- }
- sort.Slice(plans, func(i, j int) bool {
- return plans[i].Price < plans[j].Price
- })
- }
-
- return c.filterByCountryCode(plans, countryCode), nil
-}
-
-func (c *Client) filterByCountryCode(plans []*models.BillingPlan, countryCode string) []*models.BillingPlan {
- currency := "USD"
- if vat.IsEU(countryCode) {
- currency = "EUR"
- }
-
- filteredPlans := make([]*models.BillingPlan, 0)
- for _, p := range plans {
- if p.Currency == currency {
- filteredPlans = append(filteredPlans, p)
- }
- }
- return filteredPlans
-}
-
-// Subscribe current tenant to given plan on Stripe
-func (c *Client) Subscribe(planID string) error {
- customerID := c.tenant.Billing.StripeCustomerID
- if c.tenant.Billing.StripeSubscriptionID != "" {
- sub, err := c.stripe.Subscriptions.Get(c.tenant.Billing.StripeSubscriptionID, nil)
- if err != nil {
- return errors.Wrap(err, "failed to get stripe subscription")
- }
- sub, err = c.stripe.Subscriptions.Update(c.tenant.Billing.StripeSubscriptionID, &stripe.SubscriptionParams{
- CancelAtPeriodEnd: stripe.Bool(false),
- Items: []*stripe.SubscriptionItemsParams{
- {
- ID: stripe.String(sub.Items.Data[0].ID),
- Plan: stripe.String(planID),
- },
- },
- })
-
- if err != nil {
- return errors.Wrap(err, "failed to update stripe subscription")
- }
-
- c.tenant.Billing.SubscriptionEndsAt = nil
- } else {
- sub, err := c.stripe.Subscriptions.New(&stripe.SubscriptionParams{
- Customer: stripe.String(customerID),
- Items: []*stripe.SubscriptionItemsParams{
- {
- Plan: stripe.String(planID),
- },
- },
- })
-
- if err != nil {
- return errors.Wrap(err, "failed to create stripe subscription")
- }
-
- c.tenant.Billing.StripeSubscriptionID = sub.ID
- }
-
- c.tenant.Billing.StripePlanID = planID
- return nil
-}
-
-// CancelSubscription from current tenant on Stripe
-func (c *Client) CancelSubscription() error {
- sub, err := c.stripe.Subscriptions.Update(c.tenant.Billing.StripeSubscriptionID, &stripe.SubscriptionParams{
- CancelAtPeriodEnd: stripe.Bool(true),
- })
- if err != nil {
- return errors.Wrap(err, "failed to cancel stripe subscription")
- }
- endDate := time.Unix(sub.CurrentPeriodEnd, 0)
- c.tenant.Billing.SubscriptionEndsAt = &endDate
- return nil
-}
-
-// GetUpcomingInvoice returns the next due invoice for current tenant
-func (c *Client) GetUpcomingInvoice() (*models.UpcomingInvoice, error) {
- inv, err := c.stripe.Invoices.GetNext(&stripe.InvoiceParams{
- Customer: stripe.String(c.tenant.Billing.StripeCustomerID),
- Subscription: stripe.String(c.tenant.Billing.StripeSubscriptionID),
- })
- if err != nil {
- if stripeErr, ok := err.(*stripe.Error); ok {
- if stripeErr.HTTPStatusCode == 404 {
- return nil, nil
- }
- }
- return nil, errors.Wrap(err, "failed to get upcoming invoice")
- }
-
- dueDate := time.Unix(inv.Date, 0)
- return &models.UpcomingInvoice{
- Currency: strings.ToUpper(string(inv.Currency)),
- AmountDue: inv.AmountDue,
- DueDate: dueDate,
- }, nil
-}
diff --git a/app/pkg/billing/stripe_test.go b/app/pkg/billing/stripe_test.go
deleted file mode 100644
index e4d366d2c..000000000
--- a/app/pkg/billing/stripe_test.go
+++ /dev/null
@@ -1,212 +0,0 @@
-package billing_test
-
-import (
- "testing"
- "time"
-
- "github.com/getfider/fider/app/pkg/env"
-
- "github.com/getfider/fider/app/pkg/billing"
-
- "github.com/getfider/fider/app/models"
- . "github.com/getfider/fider/app/pkg/assert"
-)
-
-func TestCreateCustomer_WithSubscription(t *testing.T) {
- RegisterT(t)
- if !env.IsBillingEnabled() {
- return
- }
-
- tenant := &models.Tenant{
- ID: 2,
- Name: "Game Inc.",
- Subdomain: "gameinc",
- Billing: &models.TenantBilling{},
- }
- client := billing.NewClient()
- client.SetCurrentTenant(tenant)
- customerID, err := client.CreateCustomer("")
- Expect(err).IsNil()
- Expect(customerID).IsNotEmpty()
- Expect(customerID).Equals(tenant.Billing.StripeCustomerID)
-
- err = client.UpdatePaymentInfo(&models.CreateEditBillingPaymentInfo{
- Email: "[email protected]",
- Card: &models.CreateEditBillingPaymentInfoCard{
- Token: "tok_visa",
- },
- })
- Expect(err).IsNil()
-
- err = client.Subscribe("plan_EKTT1YWe1Zmrtp")
- Expect(err).IsNil()
- Expect(tenant.Billing.StripeSubscriptionID).IsNotEmpty()
- Expect(tenant.Billing.StripePlanID).Equals("plan_EKTT1YWe1Zmrtp")
-
- inv, err := client.GetUpcomingInvoice()
- Expect(err).IsNil()
- Expect(int(inv.AmountDue)).Equals(900)
- Expect(inv.Currency).Equals("USD")
-
- err = client.CancelSubscription()
- Expect(err).IsNil()
- Expect(tenant.Billing.SubscriptionEndsAt).IsNotNil()
-
- err = client.DeleteCustomer()
- Expect(err).IsNil()
-}
-
-var forUnitTestingTenant = &models.Tenant{
- ID: 5,
- Name: "For Unit Testing (DO NOT DELETE)",
- Subdomain: "unittesting",
- Billing: &models.TenantBilling{
- StripeCustomerID: "cus_EICBuXBIkhI2EV",
- },
-}
-
-func TestUpdatePaymentInfo(t *testing.T) {
- RegisterT(t)
- if !env.IsBillingEnabled() {
- return
- }
-
- var firstCardID string
-
- client := billing.NewClient()
- client.SetCurrentTenant(forUnitTestingTenant)
-
- err := client.ClearPaymentInfo()
- Expect(err).IsNil()
-
- //Creating a new card
- err = client.UpdatePaymentInfo(&models.CreateEditBillingPaymentInfo{
- Email: "[email protected]",
- VATNumber: "IE1234",
- Card: &models.CreateEditBillingPaymentInfoCard{
- Token: "tok_visa",
- },
- AddressCountry: "IE",
- })
- Expect(err).IsNil()
-
- info, err := client.GetPaymentInfo()
- Expect(err).IsNil()
- firstCardID = info.StripeCardID
-
- Expect(info.StripeCardID).IsNotEmpty()
- Expect(info.Email).Equals("[email protected]")
- Expect(info.VATNumber).Equals("IE1234")
- Expect(info.CardBrand).Equals("Visa")
- Expect(info.CardCountry).Equals("US")
- Expect(info.CardLast4).Equals("4242")
- Expect(int(info.CardExpMonth)).Equals(int(time.Now().Month()))
- Expect(int(info.CardExpYear)).Equals(time.Now().Year() + 1)
- Expect(info.Name).Equals("")
- Expect(info.AddressLine1).Equals("")
- Expect(info.AddressLine2).Equals("")
- Expect(info.AddressCity).Equals("")
- Expect(info.AddressState).Equals("")
- Expect(info.AddressPostalCode).Equals("")
- Expect(info.AddressCountry).Equals("")
-
- //Update existing card
- err = client.UpdatePaymentInfo(&models.CreateEditBillingPaymentInfo{
- Email: "[email protected]",
- Name: "Jon Snow",
- AddressLine1: "Street 1",
- AddressLine2: "Av. ABC",
- AddressCity: "New York",
- AddressState: "NYC",
- AddressPostalCode: "12098",
- AddressCountry: "US",
- })
- Expect(err).IsNil()
-
- info, err = client.GetPaymentInfo()
- Expect(err).IsNil()
- Expect(info.Name).Equals("Jon Snow")
- Expect(info.VATNumber).Equals("")
- Expect(info.CardLast4).Equals("4242")
- Expect(info.AddressLine1).Equals("Street 1")
- Expect(info.AddressLine2).Equals("Av. ABC")
- Expect(info.AddressCity).Equals("New York")
- Expect(info.AddressState).Equals("NYC")
- Expect(info.AddressPostalCode).Equals("12098")
- Expect(info.AddressCountry).Equals("US")
-
- //Replace card
- err = client.UpdatePaymentInfo(&models.CreateEditBillingPaymentInfo{
- Email: "[email protected]",
- Card: &models.CreateEditBillingPaymentInfoCard{
- Token: "tok_br",
- },
- })
- Expect(err).IsNil()
-
- info, err = client.GetPaymentInfo()
- Expect(err).IsNil()
- Expect(info.StripeCardID).IsNotEmpty()
- Expect(info.StripeCardID).NotEquals(firstCardID)
- Expect(info.Email).Equals("[email protected]")
- Expect(info.VATNumber).Equals("")
- Expect(info.CardBrand).Equals("Visa")
- Expect(info.CardCountry).Equals("BR")
- Expect(info.CardLast4).Equals("0002")
- Expect(int(info.CardExpMonth)).Equals(int(time.Now().Month()))
- Expect(int(info.CardExpYear)).Equals(time.Now().Year() + 1)
- Expect(info.Name).Equals("")
- Expect(info.AddressLine1).Equals("")
- Expect(info.AddressLine2).Equals("")
- Expect(info.AddressCity).Equals("")
- Expect(info.AddressState).Equals("")
- Expect(info.AddressPostalCode).Equals("")
- Expect(info.AddressCountry).Equals("")
-}
-
-func TestListPlans(t *testing.T) {
- RegisterT(t)
- if !env.IsBillingEnabled() {
- return
- }
-
- client := billing.NewClient()
- plans, err := client.ListPlans("US")
- Expect(err).IsNil()
- Expect(plans).HasLen(3)
-
- Expect(plans[0].ID).Equals("plan_EKTT1YWe1Zmrtp")
- Expect(plans[0].Name).Equals("Starter")
- Expect(plans[0].Currency).Equals("USD")
- Expect(plans[0].MaxUsers).Equals(200)
-
- Expect(plans[1].ID).Equals("plan_DoK187GZcnFpKY")
- Expect(plans[1].Name).Equals("Business (monthly)")
- Expect(plans[1].Currency).Equals("USD")
- Expect(plans[1].MaxUsers).Equals(0)
-
- Expect(plans[2].ID).Equals("plan_DpN9SkJMjNTvLd")
- Expect(plans[2].Name).Equals("Business (yearly)")
- Expect(plans[2].Currency).Equals("USD")
- Expect(plans[2].MaxUsers).Equals(0)
-
- plans, err = client.ListPlans("DE")
- Expect(err).IsNil()
- Expect(plans).HasLen(3)
-
- Expect(plans[0].ID).Equals("plan_EKTSnrGmj5BuKI")
- Expect(plans[0].Name).Equals("Starter")
- Expect(plans[0].Currency).Equals("EUR")
-
- Expect(plans[0].MaxUsers).Equals(200)
- Expect(plans[1].ID).Equals("plan_EKPnahGhiTEnCc")
- Expect(plans[1].Name).Equals("Business (monthly)")
- Expect(plans[1].Currency).Equals("EUR")
- Expect(plans[1].MaxUsers).Equals(0)
-
- Expect(plans[2].ID).Equals("plan_EKTU4xD7LNI9dO")
- Expect(plans[2].Name).Equals("Business (yearly)")
- Expect(plans[2].Currency).Equals("EUR")
- Expect(plans[2].MaxUsers).Equals(0)
-}
diff --git a/app/pkg/blob/blob_test.go b/app/pkg/blob/blob_test.go
deleted file mode 100644
index 7bf77f030..000000000
--- a/app/pkg/blob/blob_test.go
+++ /dev/null
@@ -1,254 +0,0 @@
-package blob_test
-
-import (
- "io/ioutil"
- "os"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- awss3 "github.com/aws/aws-sdk-go/service/s3"
- "github.com/getfider/fider/app/pkg/errors"
-
- "github.com/getfider/fider/app/pkg/rand"
-
- "github.com/getfider/fider/app/pkg/dbx"
-
- "github.com/getfider/fider/app/models"
-
- "github.com/getfider/fider/app/pkg/blob/fs"
- "github.com/getfider/fider/app/pkg/blob/s3"
- "github.com/getfider/fider/app/pkg/blob/sql"
-
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/blob"
- "github.com/getfider/fider/app/pkg/env"
-)
-
-var tenant1 = &models.Tenant{ID: 1}
-var tenant2 = &models.Tenant{ID: 2}
-
-func setupS3(t *testing.T) *s3.Storage {
- RegisterT(t)
-
- bucket := "test-bucket"
- s3.DefaultClient.DeleteBucket(&awss3.DeleteBucketInput{
- Bucket: aws.String(bucket),
- })
- s3.DefaultClient.CreateBucket(&awss3.CreateBucketInput{
- Bucket: aws.String(bucket),
- })
-
- return s3.NewStorage(bucket)
-}
-
-func setupSQL(t *testing.T) *sql.Storage {
- RegisterT(t)
-
- db := dbx.New()
- db.Seed()
- return sql.NewStorage(db)
-}
-
-func setupFS(t *testing.T) *fs.Storage {
- RegisterT(t)
-
- err := os.RemoveAll("./tmp/fs_test")
- Expect(err).IsNil()
-
- return fs.NewStorage("./tmp/fs_test")
-}
-
-type blobTestCase func(client blob.Storage, t *testing.T)
-type setupFunction func(t *testing.T) blob.Storage
-
-var tests = []struct {
- name string
- test blobTestCase
-}{
- {"AllOperations", AllOperations},
- {"DeleteUnkownFile", DeleteUnkownFile},
- {"SameKey_DifferentTenant", SameKey_DifferentTenant},
- {"KeyFormats", KeyFormats},
-}
-
-func TestBlobStorage(t *testing.T) {
- sqlClient := setupSQL(t)
- s3Client := setupS3(t)
- fsClient := setupFS(t)
-
- for _, tt := range tests {
- t.Run("Test_FS_"+tt.name, func(t *testing.T) {
- tt.test(fsClient, t)
- })
-
- t.Run("Test_S3_"+tt.name, func(t *testing.T) {
- tt.test(s3Client, t)
- })
-
- t.Run("Test_SQL_"+tt.name, func(t *testing.T) {
- tt.test(sqlClient, t)
- })
- }
-}
-
-func AllOperations(client blob.Storage, t *testing.T) {
- var testCases = []struct {
- localPath string
- key string
- contentType string
- }{
- {"/app/pkg/blob/testdata/file.txt", "some/path/to/file.txt", "text/plain; charset=utf-8"},
- {"/app/pkg/blob/testdata/file2.png", "file2.png", "image/png"},
- }
-
- for _, testCase := range testCases {
- bytes, _ := ioutil.ReadFile(env.Path(testCase.localPath))
- err := client.Put(testCase.key, bytes, testCase.contentType)
- Expect(err).IsNil()
-
- b, err := client.Get(testCase.key)
- Expect(err).IsNil()
- Expect(b.Key).Equals(testCase.key)
- Expect(b.Object).Equals(bytes)
- Expect(b.Size).Equals(int64(len(bytes)))
- Expect(b.ContentType).Equals(testCase.contentType)
-
- err = client.Delete(testCase.key)
- Expect(err).IsNil()
-
- b, err = client.Get(testCase.key)
- Expect(b).IsNil()
- Expect(err).Equals(blob.ErrNotFound)
- }
-}
-
-func DeleteUnkownFile(client blob.Storage, t *testing.T) {
- err := client.Delete("path/somefile.txt")
- Expect(err).IsNil()
-}
-
-func SameKey_DifferentTenant(client blob.Storage, t *testing.T) {
- client.SetCurrentTenant(tenant1)
- key := "path/to/file3.txt"
- bytes, _ := ioutil.ReadFile(env.Path("/app/pkg/blob/testdata/file3.txt"))
-
- err := client.Put(key, bytes, "text/plain; charset=utf-8")
- Expect(err).IsNil()
-
- b, err := client.Get(key)
- Expect(err).IsNil()
- Expect(b.Object).Equals(bytes)
-
- client.SetCurrentTenant(tenant2)
-
- b, err = client.Get(key)
- Expect(b).IsNil()
- Expect(err).Equals(blob.ErrNotFound)
-
- client.SetCurrentTenant(nil)
-
- b, err = client.Get(key)
- Expect(b).IsNil()
- Expect(err).Equals(blob.ErrNotFound)
-}
-
-func SameKey_DifferentTenant_Delete(client blob.Storage, t *testing.T) {
- key := "path/to/super-file.txt"
- bytes1, _ := ioutil.ReadFile(env.Path("/app/pkg/blob/testdata/file.txt"))
- bytes2, _ := ioutil.ReadFile(env.Path("/app/pkg/blob/testdata/file3.txt"))
-
- client.SetCurrentTenant(tenant1)
- err := client.Put(key, bytes1, "text/plain; charset=utf-8")
- Expect(err).IsNil()
-
- client.SetCurrentTenant(tenant2)
- err = client.Put(key, bytes2, "text/plain; charset=utf-8")
- Expect(err).IsNil()
-
- client.SetCurrentTenant(tenant1)
- b, err := client.Get(key)
- Expect(err).IsNil()
- Expect(b.Object).Equals(len(bytes1))
-
- client.SetCurrentTenant(tenant2)
- b, err = client.Get(key)
- Expect(err).IsNil()
- Expect(b.Object).Equals(len(bytes2))
-
- client.SetCurrentTenant(tenant1)
- err = client.Delete(key)
- Expect(err).IsNil()
-
- client.SetCurrentTenant(tenant2)
- b, err = client.Get(key)
- Expect(err).IsNil()
- Expect(b.Object).Equals(len(bytes2))
- Expect(err).IsNil()
-
- client.SetCurrentTenant(nil)
- b, err = client.Get(key)
- Expect(b).IsNil()
- Expect(err).Equals(blob.ErrNotFound)
-}
-
-func KeyFormats(client blob.Storage, t *testing.T) {
- RegisterT(t)
-
- testCases := []struct {
- key string
- valid bool
- }{
- {
- key: "Jon",
- valid: true,
- },
- {
- key: "ASDHASJDKHAJSDJ.png",
- valid: true,
- },
- {
- key: "",
- valid: false,
- },
- {
- key: "/path/to/Jon",
- valid: false,
- },
- {
- key: "path/to/Jon/",
- valid: false,
- },
- {
- key: " file.txt",
- valid: false,
- },
- {
- key: "file with space.txt",
- valid: false,
- },
- {
- key: rand.String(513),
- valid: false,
- },
- }
-
- for _, testCase := range testCases {
- err := client.Put(testCase.key, make([]byte, 0), "text/plain; charset=utf-8")
- if testCase.valid {
- Expect(err).IsNil()
- } else {
- Expect(errors.Cause(err)).Equals(blob.ErrInvalidKeyFormat)
- }
- }
-}
-
-func TestSanitizeFileName(t *testing.T) {
- RegisterT(t)
-
- Expect(blob.SanitizeFileName("João.txt")).Equals("joao.txt")
- Expect(blob.SanitizeFileName(" Jon")).Equals("jon")
- Expect(blob.SanitizeFileName("Jon.png")).Equals("jon.png")
- Expect(blob.SanitizeFileName("Jon Snow.png ")).Equals("jon-snow.png")
- Expect(blob.SanitizeFileName(" ヒキワリ.png")).Equals("hikiwari.png")
- Expect(blob.SanitizeFileName("люди рождаются свободными.png")).Equals("liudi-rozhdaiutsia-svobodnymi.png")
-}
diff --git a/app/pkg/blob/fs/fs.go b/app/pkg/blob/fs/fs.go
deleted file mode 100644
index 25e6c7439..000000000
--- a/app/pkg/blob/fs/fs.go
+++ /dev/null
@@ -1,103 +0,0 @@
-package fs
-
-import (
- "io/ioutil"
- "net/http"
- "os"
- "path"
- "path/filepath"
- "strconv"
-
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/blob"
- "github.com/getfider/fider/app/pkg/errors"
-)
-
-var perm os.FileMode = 0744
-
-var _ blob.Storage = (*Storage)(nil)
-
-// Storage stores blobs on FileSystem
-type Storage struct {
- path string
- tenant *models.Tenant
-}
-
-// NewStorage creates a new FileSystem Storage
-func NewStorage(path string) *Storage {
- err := os.MkdirAll(path, perm)
- if err != nil {
- panic(errors.Wrap(err, "failed to create path '%s'", path))
- }
-
- return &Storage{
- path: path,
- }
-}
-
-// SetCurrentTenant to current context
-func (s *Storage) SetCurrentTenant(tenant *models.Tenant) {
- s.tenant = tenant
-}
-
-func (s *Storage) keyFullPath(key string) string {
- if s.tenant != nil {
- return path.Join(s.path, "tenants", strconv.Itoa(s.tenant.ID), key)
- }
- return path.Join(s.path, key)
-}
-
-// Get returns a blob with given key
-func (s *Storage) Get(key string) (*blob.Blob, error) {
- fullPath := s.keyFullPath(key)
- stats, err := os.Stat(fullPath)
- if err != nil {
- if os.IsNotExist(err) {
- return nil, blob.ErrNotFound
- }
- return nil, errors.Wrap(err, "failed to get stats '%s' from FileSystem", key)
- }
-
- file, err := ioutil.ReadFile(fullPath)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get read '%s' from FileSystem", key)
- }
-
- return &blob.Blob{
- Key: key,
- Size: stats.Size(),
- ContentType: http.DetectContentType(file),
- Object: file,
- }, nil
-}
-
-// Delete a blob with given key
-func (s *Storage) Delete(key string) error {
- fullPath := s.keyFullPath(key)
- err := os.Remove(fullPath)
- if err != nil && !os.IsNotExist(err) {
- return errors.Wrap(err, "failed to delete file '%s' from FileSystem", key)
- }
- return nil
-}
-
-// Put a blob with given key and content. Blobs with same key are replaced.
-func (s *Storage) Put(key string, content []byte, contentType string) error {
- if err := blob.ValidateKey(key); err != nil {
- return errors.Wrap(err, "failed to validate blob key '%s'", key)
- }
-
- fullPath := s.keyFullPath(key)
- err := os.MkdirAll(filepath.Dir(fullPath), perm)
-
- if err != nil {
- return errors.Wrap(err, "failed to create folder '%s' on FileSystem", fullPath)
- }
-
- err = ioutil.WriteFile(fullPath, content, perm)
- if err != nil {
- return errors.Wrap(err, "failed to create file '%s' on FileSystem", fullPath)
- }
-
- return nil
-}
diff --git a/app/pkg/blob/s3/s3.go b/app/pkg/blob/s3/s3.go
deleted file mode 100644
index 7f41e49aa..000000000
--- a/app/pkg/blob/s3/s3.go
+++ /dev/null
@@ -1,130 +0,0 @@
-package s3
-
-import (
- "bytes"
- "io/ioutil"
- "path"
- "strconv"
- "strings"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/aws/awserr"
- "github.com/aws/aws-sdk-go/aws/credentials"
- "github.com/aws/aws-sdk-go/aws/session"
- "github.com/aws/aws-sdk-go/service/s3"
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/blob"
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/errors"
-)
-
-var _ blob.Storage = (*Storage)(nil)
-
-// Storage stores blobs on an S3 compatible service
-type Storage struct {
- bucket *string
- tenant *models.Tenant
-}
-
-func isNotFound(err error) bool {
- if awsErr, ok := err.(awserr.Error); ok {
- return awsErr.Code() == s3.ErrCodeNoSuchKey
- }
- return false
-}
-
-//DefaultClient is an S3 Client
-var DefaultClient *s3.S3
-
-func init() {
- s3EnvConfig := env.Config.BlobStorage.S3
- if s3EnvConfig.EndpointURL != "" {
- s3Config := &aws.Config{
- Credentials: credentials.NewStaticCredentials(s3EnvConfig.AccessKeyID, s3EnvConfig.SecretAccessKey, ""),
- Endpoint: aws.String(s3EnvConfig.EndpointURL),
- Region: aws.String(s3EnvConfig.Region),
- DisableSSL: aws.Bool(strings.HasSuffix(s3EnvConfig.EndpointURL, "http://")),
- S3ForcePathStyle: aws.Bool(true),
- }
- awsSession := session.New(s3Config)
- DefaultClient = s3.New(awsSession)
- }
-}
-
-// NewStorage creates a S3 compatible service storage
-func NewStorage(bucket string) *Storage {
- return &Storage{
- bucket: aws.String(bucket),
- }
-}
-
-func (s *Storage) keyFullPathURL(key string) string {
- if s.tenant != nil {
- return path.Join("tenants", strconv.Itoa(s.tenant.ID), key)
- }
- return key
-}
-
-// SetCurrentTenant to current context
-func (s *Storage) SetCurrentTenant(tenant *models.Tenant) {
- s.tenant = tenant
-}
-
-// Get returns a blob with given key
-func (s *Storage) Get(key string) (*blob.Blob, error) {
- resp, err := DefaultClient.GetObject(&s3.GetObjectInput{
- Bucket: s.bucket,
- Key: aws.String(s.keyFullPathURL(key)),
- })
- if err != nil {
- if isNotFound(err) {
- return nil, blob.ErrNotFound
- }
- return nil, errors.Wrap(err, "failed to get blob '%s' from S3", key)
- }
- defer resp.Body.Close()
-
- bytes, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return nil, errors.Wrap(err, "failed to read blob body '%s' from S3", key)
- }
-
- return &blob.Blob{
- Key: key,
- Size: *resp.ContentLength,
- ContentType: *resp.ContentType,
- Object: bytes,
- }, nil
-}
-
-// Delete a blob with given key
-func (s *Storage) Delete(key string) error {
- _, err := DefaultClient.DeleteObject(&s3.DeleteObjectInput{
- Bucket: s.bucket,
- Key: aws.String(s.keyFullPathURL(key)),
- })
- if err != nil && !isNotFound(err) {
- return errors.Wrap(err, "failed to delete blob '%s' from S3", key)
- }
- return nil
-}
-
-// Put a blob with given key and content. Blobs with same key are replaced.
-func (s *Storage) Put(key string, content []byte, contentType string) error {
- if err := blob.ValidateKey(key); err != nil {
- return errors.Wrap(err, "failed to validate blob key '%s'", key)
- }
-
- reader := bytes.NewReader(content)
- _, err := DefaultClient.PutObject(&s3.PutObjectInput{
- Bucket: s.bucket,
- Key: aws.String(s.keyFullPathURL(key)),
- ContentType: aws.String(contentType),
- ACL: aws.String(s3.ObjectCannedACLPrivate),
- Body: reader,
- })
- if err != nil {
- return errors.Wrap(err, "failed to upload blob '%s' to S3", key)
- }
- return nil
-}
diff --git a/app/pkg/blob/sql/sql.go b/app/pkg/blob/sql/sql.go
deleted file mode 100644
index 525e9e987..000000000
--- a/app/pkg/blob/sql/sql.go
+++ /dev/null
@@ -1,128 +0,0 @@
-package sql
-
-import (
- "database/sql"
- "time"
-
- "github.com/getfider/fider/app"
-
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/blob"
- "github.com/getfider/fider/app/pkg/dbx"
- "github.com/getfider/fider/app/pkg/errors"
-)
-
-var _ blob.Storage = (*Storage)(nil)
-
-type dbBlob struct {
- ContentType string `db:"content_type"`
- Size int64 `db:"size"`
- Content []byte `db:"file"`
-}
-
-// Storage stores blobs on FileSystem
-type Storage struct {
- db *dbx.Database
- tenant *models.Tenant
-}
-
-// NewStorage creates a new SQL Storage
-func NewStorage(db *dbx.Database) *Storage {
- return &Storage{
- db: db,
- }
-}
-
-// SetCurrentTenant to current context
-func (s *Storage) SetCurrentTenant(tenant *models.Tenant) {
- s.tenant = tenant
-}
-
-// Get returns a blob with given key
-func (s *Storage) Get(key string) (*blob.Blob, error) {
- var tenantID sql.NullInt64
- if s.tenant != nil {
- tenantID.Scan(s.tenant.ID)
- }
-
- trx, err := s.db.Begin()
- if err != nil {
- return nil, errors.Wrap(err, "failed to open transaction")
- }
- defer trx.Commit()
-
- b := dbBlob{}
- err = trx.Get(&b, "SELECT file, content_type, size FROM blobs WHERE key = $1 AND (tenant_id = $2 OR ($2 IS NULL AND tenant_id IS NULL))", key, tenantID)
- if err != nil {
- if err == app.ErrNotFound {
- return nil, blob.ErrNotFound
- }
- return nil, errors.Wrap(err, "failed to get blob with key '%s'", key)
- }
-
- return &blob.Blob{
- Key: key,
- Size: b.Size,
- ContentType: b.ContentType,
- Object: b.Content,
- }, nil
-}
-
-// Delete a blob with given key
-func (s *Storage) Delete(key string) error {
- var tenantID sql.NullInt64
- if s.tenant != nil {
- tenantID.Scan(s.tenant.ID)
- }
-
- trx, err := s.db.Begin()
- if err != nil {
- return errors.Wrap(err, "failed to open transaction")
- }
- defer trx.Commit()
-
- _, err = trx.Execute("DELETE FROM blobs WHERE key = $1 AND (tenant_id = $2 OR ($2 IS NULL AND tenant_id IS NULL))", key, tenantID)
- if err != nil {
- return errors.Wrap(err, "failed to delete blob with key '%s'", key)
- }
-
- if err != nil {
- return errors.Wrap(err, "failed to commit deletion of blob with key '%s'", key)
- }
-
- return nil
-}
-
-// Put a blob with given key and content. Blobs with same key are replaced.
-func (s *Storage) Put(key string, content []byte, contentType string) error {
- if err := blob.ValidateKey(key); err != nil {
- return errors.Wrap(err, "failed to validate blob key '%s'", key)
- }
-
- var tenantID sql.NullInt64
- if s.tenant != nil {
- tenantID.Scan(s.tenant.ID)
- }
-
- trx, err := s.db.Begin()
- if err != nil {
- return errors.Wrap(err, "failed to open transaction")
- }
- defer trx.Commit()
-
- now := time.Now()
- _, err = trx.Execute(`
- INSERT INTO blobs (tenant_id, key, size, content_type, file, created_at, modified_at)
- VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (tenant_id, key)
- DO UPDATE SET size = $3, content_type = $4, file = $5, modified_at = $7
- `, tenantID, key, int64(len(content)), contentType, content, now, now)
- if err != nil {
- return errors.Wrap(err, "failed to store blob with key '%s'", key)
- }
-
- if err != nil {
- return errors.Wrap(err, "failed to commit store of blob with key '%s'", key)
- }
-
- return nil
-}
diff --git a/app/pkg/bus/bus.go b/app/pkg/bus/bus.go
new file mode 100644
index 000000000..10226647f
--- /dev/null
+++ b/app/pkg/bus/bus.go
@@ -0,0 +1,160 @@
+package bus
+
+import (
+ "context"
+ "fmt"
+ "reflect"
+ "sync"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+type HandlerFunc interface{}
+type Msg interface{}
+
+type Service interface {
+ Name() string
+ Category() string
+ Enabled() bool
+ Init()
+}
+
+var handlers = make(map[string]HandlerFunc)
+var listeners = make(map[string][]HandlerFunc)
+var services = make([]Service, 0)
+var busLock = &sync.RWMutex{}
+
+func Register(svc Service) {
+ busLock.Lock()
+ defer busLock.Unlock()
+
+ services = append(services, svc)
+}
+
+func Reset() {
+ busLock.Lock()
+ defer busLock.Unlock()
+ services = make([]Service, 0)
+ handlers = make(map[string]HandlerFunc)
+ listeners = make(map[string][]HandlerFunc)
+}
+
+// Initializes the bus services that have been registered via bus.Register
+// Services that set via Init(...services) are always registered (regardless of Enabled() function)
+/// and have preference over services registered from bus.Register
+func Init(forcedServices ...Service) []Service {
+ initializedServices := make([]Service, 0)
+ for _, svc := range forcedServices {
+ initializedServices = append(initializedServices, svc)
+ svc.Init()
+ }
+
+ for _, svc := range services {
+ if svc.Enabled() {
+ initializedServices = append(initializedServices, svc)
+ svc.Init()
+ }
+ }
+ return initializedServices
+}
+
+func AddHandler(handler HandlerFunc) {
+ busLock.Lock()
+ defer busLock.Unlock()
+
+ handlerType := reflect.TypeOf(handler)
+ elem := handlerType.In(1).Elem()
+ handlers[keyForElement(elem)] = handler
+}
+
+func AddListener(handler HandlerFunc) {
+ busLock.Lock()
+ defer busLock.Unlock()
+
+ handlerType := reflect.TypeOf(handler)
+ elem := handlerType.In(1).Elem()
+ eventName := keyForElement(elem)
+ _, exists := listeners[eventName]
+ if !exists {
+ listeners[eventName] = make([]HandlerFunc, 0)
+ }
+ listeners[eventName] = append(listeners[eventName], handler)
+}
+
+func Dispatch(ctx context.Context, msgs ...Msg) error {
+ if len(msgs) == 0 {
+ return nil
+ }
+
+ busLock.RLock()
+ defer busLock.RUnlock()
+
+ for _, msg := range msgs {
+ typeof := reflect.TypeOf(msg)
+ if typeof.Kind() != reflect.Ptr {
+ panic(fmt.Errorf("'%s' is not a pointer", keyForElement(typeof)))
+ }
+
+ elem := typeof.Elem()
+ key := keyForElement(elem)
+ handler := handlers[key]
+ if handler == nil {
+ panic(fmt.Errorf("could not find handler for '%s'", key))
+ }
+
+ var params = []reflect.Value{
+ reflect.ValueOf(ctx),
+ reflect.ValueOf(msg),
+ }
+
+ ret := reflect.ValueOf(handler).Call(params)
+ if err := ret[0].Interface(); err != nil {
+ return err.(error)
+ }
+ }
+
+ return nil
+}
+
+func Publish(ctx context.Context, msgs ...Msg) {
+ if len(msgs) == 0 {
+ return
+ }
+
+ busLock.RLock()
+ defer busLock.RUnlock()
+
+ for _, msg := range msgs {
+ typeof := reflect.TypeOf(msg)
+ if typeof.Kind() != reflect.Ptr {
+ panic(fmt.Errorf("'%s' is not a pointer", keyForElement(typeof)))
+ }
+
+ elem := typeof.Elem()
+ key := keyForElement(elem)
+ msgListeners := listeners[key]
+
+ var params = []reflect.Value{
+ reflect.ValueOf(ctx),
+ reflect.ValueOf(msg),
+ }
+
+ for _, msgListener := range msgListeners {
+ ret := reflect.ValueOf(msgListener).Call(params)
+ if len(ret) > 0 {
+ if err, isErr := ret[0].Interface().(error); isErr {
+ Publish(ctx, &cmd.LogError{
+ Err: errors.Wrap(err, "failed to execute msg '%s'", key),
+ })
+ }
+ }
+ }
+ }
+}
+
+func keyForElement(t reflect.Type) string {
+ msgTypeName := t.Name()
+ pkgPath := t.PkgPath()
+ return pkgPath + "." + msgTypeName
+}
diff --git a/app/pkg/bus/bus_test.go b/app/pkg/bus/bus_test.go
new file mode 100644
index 000000000..fe59a1835
--- /dev/null
+++ b/app/pkg/bus/bus_test.go
@@ -0,0 +1,119 @@
+package bus_test
+
+import (
+ "context"
+ "testing"
+
+ "github.com/getfider/fider/app/models/cmd"
+
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/errors"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+)
+
+func TestBus_SimpleMessage(t *testing.T) {
+ RegisterT(t)
+ bus.Register(GreeterService{})
+ bus.Init()
+ ctx := context.WithValue(context.Background(), GreetingKey, "Good Morning")
+ cmd := &SayHelloCommand{Name: "Fider"}
+ err := bus.Dispatch(ctx, cmd)
+ Expect(err).IsNil()
+ Expect(cmd.Result).Equals("Good Morning Fider")
+}
+
+func TestBus_MessageIsNotPointer_ShouldPanic(t *testing.T) {
+ RegisterT(t)
+ bus.Register(GreeterService{})
+ bus.Init()
+
+ defer func() {
+ if r := recover(); r != nil {
+ panicText := (r.(error)).Error()
+ Expect(panicText).Equals("'github.com/getfider/fider/app/pkg/bus_test.SayHelloCommand' is not a pointer")
+ }
+ }()
+
+ cmd := SayHelloCommand{Name: "Fider"}
+ err := bus.Dispatch(context.Background(), cmd)
+ Expect(err).IsNil()
+}
+
+func TestBus_OverwriteService(t *testing.T) {
+ RegisterT(t)
+
+ bus.Register(GreeterService{})
+ bus.Register(BetterGreeterService{})
+ bus.Init()
+ cmd := &SayHelloCommand{Name: "Fider"}
+ err := bus.Dispatch(context.Background(), cmd)
+ Expect(err).IsNil()
+ Expect(cmd.Result).Equals("Hello Fider")
+}
+
+func TestBus_MultipleMessages(t *testing.T) {
+ RegisterT(t)
+
+ bus.Register(BetterGreeterService{})
+ bus.Init()
+ cmd1 := &SayHelloCommand{Name: "John"}
+ cmd2 := &SayHelloCommand{Name: "Mary"}
+ cmd3 := &SayHelloCommand{Name: "Bob"}
+ err := bus.Dispatch(context.Background(), cmd1, cmd2, cmd3)
+ Expect(err).IsNil()
+ Expect(cmd1.Result).Equals("Hello John")
+ Expect(cmd2.Result).Equals("Hello Mary")
+ Expect(cmd3.Result).Equals("Hello Bob")
+}
+
+func TestBus_MultipleListeners(t *testing.T) {
+ RegisterT(t)
+ value1 := ""
+ bus.AddListener(func(ctx context.Context, c *SayHelloCommand) {
+ value1 = c.Name
+ })
+
+ value2 := ""
+ bus.AddListener(func(ctx context.Context, c *SayHelloCommand) {
+ value2 = c.Name
+ })
+
+ bus.Publish(context.Background(), &SayHelloCommand{Name: "Fider"})
+ Expect(value1).Equals("Fider")
+ Expect(value2).Equals("Fider")
+}
+
+func TestBus_MultiplePublish(t *testing.T) {
+ RegisterT(t)
+ value1 := ""
+ bus.AddListener(func(ctx context.Context, c *SayHelloCommand) {
+ value1 += c.Name
+ })
+
+ value2 := ""
+ bus.AddListener(func(ctx context.Context, c *SayHelloCommand) {
+ value2 += c.Name
+ })
+
+ bus.Publish(context.Background(), &SayHelloCommand{Name: "123"}, &SayHelloCommand{Name: "456"})
+ Expect(value1).Equals("123456")
+ Expect(value2).Equals("123456")
+}
+
+func TestBus_PublishError(t *testing.T) {
+ RegisterT(t)
+ boom := errors.New("BOOM")
+
+ var err error
+ bus.AddListener(func(ctx context.Context, c *cmd.LogError) {
+ err = c.Err
+ })
+
+ bus.AddListener(func(ctx context.Context, c *SayHelloCommand) error {
+ return boom
+ })
+
+ bus.Publish(context.Background(), &SayHelloCommand{Name: "123"})
+ Expect(errors.Cause(err)).Equals(boom)
+}
diff --git a/app/pkg/bus/greeter_test.go b/app/pkg/bus/greeter_test.go
new file mode 100644
index 000000000..3c5a67a38
--- /dev/null
+++ b/app/pkg/bus/greeter_test.go
@@ -0,0 +1,66 @@
+package bus_test
+
+import (
+ "context"
+
+ "github.com/getfider/fider/app/pkg/bus"
+)
+
+type SayHelloCommand struct {
+ Name string
+ Result string
+}
+
+var GreetingKey = "GreetingKey"
+
+type GreeterService struct {
+}
+
+func (s GreeterService) Name() string {
+ return "Greeter"
+}
+
+func (s GreeterService) Category() string {
+ return "greeter"
+}
+
+func (s GreeterService) Enabled() bool {
+ return true
+}
+
+func (s GreeterService) Init() {
+ bus.AddHandler(Greet)
+}
+
+var getGreeting = func(ctx context.Context) string {
+ return ctx.Value(GreetingKey).(string)
+}
+
+func Greet(ctx context.Context, cmd *SayHelloCommand) error {
+ cmd.Result = getGreeting(ctx) + " " + cmd.Name
+ return nil
+}
+
+type BetterGreeterService struct {
+}
+
+func (s BetterGreeterService) Name() string {
+ return "BetterGreeter"
+}
+
+func (s BetterGreeterService) Category() string {
+ return "greeter"
+}
+
+func (s BetterGreeterService) Enabled() bool {
+ return true
+}
+
+func (s BetterGreeterService) Init() {
+ bus.AddHandler(SayHello)
+}
+
+func SayHello(ctx context.Context, cmd *SayHelloCommand) error {
+ cmd.Result = "Hello " + cmd.Name
+ return nil
+}
diff --git a/app/pkg/log/colors.go b/app/pkg/color/color.go
similarity index 92%
rename from app/pkg/log/colors.go
rename to app/pkg/color/color.go
index 913911477..073771013 100644
--- a/app/pkg/log/colors.go
+++ b/app/pkg/color/color.go
@@ -1,4 +1,4 @@
-package log
+package color
import (
"fmt"
@@ -16,8 +16,8 @@ var (
resetAll = "\033[0m"
)
-// Color return content with given color
-func Color(colorName string, content interface{}) string {
+// FromName return content with given color name
+func FromName(colorName string, content interface{}) string {
switch strings.ToUpper(colorName) {
case "RED":
return Red(content)
diff --git a/app/pkg/csv/csv_test.go b/app/pkg/csv/csv_test.go
index 11d3b21d1..503b2ebc3 100644
--- a/app/pkg/csv/csv_test.go
+++ b/app/pkg/csv/csv_test.go
@@ -6,6 +6,7 @@ import (
"time"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/enum"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/csv"
)
@@ -61,7 +62,7 @@ var declinedPost = &models.Post{
},
VotesCount: 4,
CommentsCount: 2,
- Status: models.PostDeclined,
+ Status: enum.PostDeclined,
Response: &models.PostResponse{
Text: "Nothing we need to do",
RespondedAt: time.Date(2018, 4, 4, 19, 48, 10, 0, time.UTC),
@@ -82,7 +83,7 @@ var openPost = &models.Post{
},
VotesCount: 4,
CommentsCount: 2,
- Status: models.PostOpen,
+ Status: enum.PostOpen,
}
var duplicatePost = &models.Post{
@@ -95,7 +96,7 @@ var duplicatePost = &models.Post{
},
VotesCount: 4,
CommentsCount: 2,
- Status: models.PostDuplicate,
+ Status: enum.PostDuplicate,
Response: &models.PostResponse{
Text: "This has already been suggested",
RespondedAt: time.Date(2018, 3, 17, 10, 15, 42, 0, time.UTC),
diff --git a/app/pkg/dbx/dbx.go b/app/pkg/dbx/dbx.go
index e057b33c5..abd848288 100644
--- a/app/pkg/dbx/dbx.go
+++ b/app/pkg/dbx/dbx.go
@@ -1,6 +1,7 @@
package dbx
import (
+ "context"
"database/sql"
"io/ioutil"
"reflect"
@@ -9,123 +10,82 @@ import (
"strings"
"github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/dto"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
- "github.com/getfider/fider/app/pkg/log/noop"
- //required
- _ "github.com/lib/pq"
+ "github.com/lib/pq"
)
-// New creates a new Database instance without logging
-func New() *Database {
- return NewWithLogger(noop.NewLogger())
-}
+var conn *sql.DB
+var rowMapper *RowMapper
-// NewWithLogger creates a new Database instance with logging or panic
-func NewWithLogger(logger log.Logger) *Database {
- conn, err := sql.Open("postgres", env.Config.Database.URL)
+func init() {
+ var err error
+ conn, err = sql.Open("postgres", env.Config.Database.URL)
if err != nil {
- panic(errors.Wrap(err, "failed to open connection to the database"))
+ panic(wrap(err, "failed to open connection to the database"))
}
conn.SetMaxIdleConns(env.Config.Database.MaxIdleConns)
conn.SetMaxOpenConns(env.Config.Database.MaxOpenConns)
-
- return &Database{conn, logger, NewRowMapper()}
-}
-
-// Database represents a connection to a SQL database
-type Database struct {
- conn *sql.DB
- logger log.Logger
- mapper *RowMapper
+ rowMapper = NewRowMapper()
}
-// Connection returns current database connection
-func (db *Database) Connection() *sql.DB {
- return db.conn
+func Connection() *sql.DB {
+ return conn
}
// Ping checks if current database connection is healthy
-func (db *Database) Ping() error {
- _, err := db.conn.Exec("SELECT 1")
+func Ping() error {
+ _, err := conn.Exec("SELECT 1")
return err
}
-// SetLogger replaces current database Logger
-func (db *Database) SetLogger(logger log.Logger) {
- db.logger = logger
-}
-
-// Begin returns a new SQL transaction
-func (db *Database) Begin() (*Trx, error) {
- tx, err := db.conn.Begin()
+// BeginTx returns a new SQL transaction
+func BeginTx(ctx context.Context) (*Trx, error) {
+ tx, err := conn.BeginTx(ctx, nil)
if err != nil {
- return nil, errors.Wrap(err, "failed to start new transaction")
+ return nil, wrap(err, "failed to start new transaction")
}
- return &Trx{tx: tx, logger: db.logger, mapper: db.mapper}, nil
+ return &Trx{tx: tx, ctx: ctx}, nil
}
-// Close connection to database
-func (db *Database) Close() error {
- if db.conn != nil {
- return db.conn.Close()
- }
- return nil
-}
-
-func (db *Database) load(path string) {
+func load(path string) {
content, err := ioutil.ReadFile(env.Path(path))
if err != nil {
- panic(errors.Wrap(err, "failed to read file %s", path))
+ panic(wrap(err, "failed to read file %s", path))
}
- _, err = db.conn.Exec(string(content))
+ _, err = conn.Exec(string(content))
if err != nil {
- panic(errors.Wrap(err, "failed to execute %s", path))
+ panic(wrap(err, "failed to execute %s", path))
}
}
// Seed clean and insert new seed data for testing
-func (db *Database) Seed() {
+func Seed() {
if env.IsTest() {
- db.load("/app/pkg/dbx/setup.sql")
+ load("/app/pkg/dbx/setup.sql")
}
}
//Trx represents a Database transaction
type Trx struct {
- tx *sql.Tx
- logger log.Logger
- mapper *RowMapper
+ tx *sql.Tx
+ ctx context.Context
}
var formatter = strings.NewReplacer("\t", "", "\n", " ")
-// SetLogger replaces current transaction Logger
-func (trx *Trx) SetLogger(logger log.Logger) {
- trx.logger = logger
-}
-
-// NoLogs disable logs for this transaction
-func (trx *Trx) NoLogs() {
- trx.logger.Disable()
-}
-
-// ResumeLogs resume logs for this transaction
-func (trx *Trx) ResumeLogs() {
- trx.logger.Enable()
-}
-
// Execute given SQL command
func (trx *Trx) Execute(command string, args ...interface{}) (int64, error) {
- if trx.logger.IsEnabled(log.DEBUG) {
+ if log.IsEnabled(log.DEBUG) {
command = formatter.Replace(command)
start := time.Now()
defer func() {
- trx.logger.Debugf("@{Command:yellow} @{Args:blue} executed in @{ElapsedMs:magenta}ms", log.Props{
+ log.Debugf(trx.ctx, "@{Command:yellow} @{Args:blue} executed in @{ElapsedMs:magenta}ms", dto.Props{
"Command": command,
"Args": args,
"ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
@@ -133,9 +93,9 @@ func (trx *Trx) Execute(command string, args ...interface{}) (int64, error) {
}()
}
- result, err := trx.tx.Exec(command, args...)
+ result, err := trx.tx.ExecContext(trx.ctx, command, args...)
if err != nil {
- return 0, errors.Wrap(err, "failed to execute trx.Execute")
+ return 0, wrap(err, "failed to execute trx.Execute")
}
rows, _ := result.RowsAffected()
@@ -144,11 +104,11 @@ func (trx *Trx) Execute(command string, args ...interface{}) (int64, error) {
// Scalar returns first row and first column
func (trx *Trx) Scalar(data interface{}, command string, args ...interface{}) error {
- if trx.logger.IsEnabled(log.DEBUG) {
+ if log.IsEnabled(log.DEBUG) {
command = formatter.Replace(command)
start := time.Now()
defer func() {
- trx.logger.Debugf("@{Command:yellow} @{Args:blue} executed in @{ElapsedMs:magenta}ms", log.Props{
+ log.Debugf(trx.ctx, "@{Command:yellow} @{Args:blue} executed in @{ElapsedMs:magenta}ms", dto.Props{
"Command": command,
"Args": args,
"ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
@@ -156,24 +116,24 @@ func (trx *Trx) Scalar(data interface{}, command string, args ...interface{}) er
}()
}
- row := trx.tx.QueryRow(command, args...)
+ row := trx.tx.QueryRowContext(trx.ctx, command, args...)
err := row.Scan(data)
if err != nil {
if err == sql.ErrNoRows {
return app.ErrNotFound
}
- return errors.Wrap(err, "failed to execute trx.Scalar")
+ return wrap(err, "failed to execute trx.Scalar")
}
return nil
}
// Get first row and bind to given data
func (trx *Trx) Get(data interface{}, command string, args ...interface{}) error {
- if trx.logger.IsEnabled(log.DEBUG) {
+ if log.IsEnabled(log.DEBUG) {
command = formatter.Replace(command)
start := time.Now()
defer func() {
- trx.logger.Debugf("@{Command:yellow} @{Args:blue} executed in @{ElapsedMs:magenta}ms", log.Props{
+ log.Debugf(trx.ctx, "@{Command:yellow} @{Args:blue} executed in @{ElapsedMs:magenta}ms", dto.Props{
"Command": command,
"Args": args,
"ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
@@ -181,17 +141,17 @@ func (trx *Trx) Get(data interface{}, command string, args ...interface{}) error
}()
}
- rows, err := trx.tx.Query(command, args...)
+ rows, err := trx.tx.QueryContext(trx.ctx, command, args...)
if err != nil {
- return errors.Wrap(err, "failed to execute trx.Get")
+ return wrap(err, "failed to execute trx.Get")
}
defer rows.Close()
if rows.Next() {
columns, _ := rows.Columns()
- err := trx.mapper.Map(data, columns, rows.Scan)
+ err := rowMapper.Map(data, columns, rows.Scan)
if err != nil {
- return errors.Wrap(err, "failed to map result to model")
+ return wrap(err, "failed to map result to model")
}
return nil
}
@@ -199,45 +159,13 @@ func (trx *Trx) Get(data interface{}, command string, args ...interface{}) error
return app.ErrNotFound
}
-// QueryIntArray executes given SQL command and return first column as int
-func (trx *Trx) QueryIntArray(command string, args ...interface{}) ([]int, error) {
- if trx.logger.IsEnabled(log.DEBUG) {
- command = formatter.Replace(command)
- start := time.Now()
- defer func() {
- trx.logger.Debugf("@{Command:yellow} @{Args:blue} executed in @{ElapsedMs:magenta}ms", log.Props{
- "Command": command,
- "Args": args,
- "ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
- })
- }()
- }
-
- rows, err := trx.tx.Query(command, args...)
- if err != nil {
- return nil, errors.Wrap(err, "failed to execute trx.QueryIntArray")
- }
-
- defer rows.Close()
- values := make([]int, 0)
- for rows.Next() {
- var value int
- if err := rows.Scan(&value); err != nil {
- return nil, errors.Wrap(err, "failed to execute row.Scan")
- }
- values = append(values, value)
- }
-
- return values, nil
-}
-
// Exists returns true if at least one record is found
func (trx *Trx) Exists(command string, args ...interface{}) (bool, error) {
- if trx.logger.IsEnabled(log.DEBUG) {
+ if log.IsEnabled(log.DEBUG) {
command = formatter.Replace(command)
start := time.Now()
defer func() {
- trx.logger.Debugf("@{Command:yellow} @{Args:blue} executed in @{ElapsedMs:magenta}ms", log.Props{
+ log.Debugf(trx.ctx, "@{Command:yellow} @{Args:blue} executed in @{ElapsedMs:magenta}ms", dto.Props{
"Command": command,
"Args": args,
"ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
@@ -245,9 +173,9 @@ func (trx *Trx) Exists(command string, args ...interface{}) (bool, error) {
}()
}
- rows, err := trx.tx.Query(command, args...)
+ rows, err := trx.tx.QueryContext(trx.ctx, command, args...)
if err != nil {
- return false, errors.Wrap(err, "failed to execute trx.Exists")
+ return false, wrap(err, "failed to execute trx.Exists")
}
defer rows.Close()
@@ -256,11 +184,11 @@ func (trx *Trx) Exists(command string, args ...interface{}) (bool, error) {
// Count returns number of rows
func (trx *Trx) Count(command string, args ...interface{}) (int, error) {
- if trx.logger.IsEnabled(log.DEBUG) {
+ if log.IsEnabled(log.DEBUG) {
command = formatter.Replace(command)
start := time.Now()
defer func() {
- trx.logger.Debugf("@{Command:yellow} @{Args:blue} executed in @{ElapsedMs:magenta}ms", log.Props{
+ log.Debugf(trx.ctx, "@{Command:yellow} @{Args:blue} executed in @{ElapsedMs:magenta}ms", dto.Props{
"Command": command,
"Args": args,
"ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
@@ -268,9 +196,9 @@ func (trx *Trx) Count(command string, args ...interface{}) (int, error) {
}()
}
- rows, err := trx.tx.Query(command, args...)
+ rows, err := trx.tx.QueryContext(trx.ctx, command, args...)
if err != nil {
- return 0, errors.Wrap(err, "failed to execute trx.Count")
+ return 0, wrap(err, "failed to execute trx.Count")
}
defer rows.Close()
@@ -283,11 +211,11 @@ func (trx *Trx) Count(command string, args ...interface{}) (int, error) {
//Select all matched rows bind to given data
func (trx *Trx) Select(data interface{}, command string, args ...interface{}) error {
- if trx.logger.IsEnabled(log.DEBUG) {
+ if log.IsEnabled(log.DEBUG) {
command = formatter.Replace(command)
start := time.Now()
defer func() {
- trx.logger.Debugf("@{Command:yellow} @{Args:blue} executed in @{ElapsedMs:magenta}ms", log.Props{
+ log.Debugf(trx.ctx, "@{Command:yellow} @{Args:blue} executed in @{ElapsedMs:magenta}ms", dto.Props{
"Command": command,
"Args": args,
"ElapsedMs": time.Since(start).Nanoseconds() / int64(time.Millisecond),
@@ -295,9 +223,9 @@ func (trx *Trx) Select(data interface{}, command string, args ...interface{}) er
}()
}
- rows, err := trx.tx.Query(command, args...)
+ rows, err := trx.tx.QueryContext(trx.ctx, command, args...)
if err != nil {
- return errors.Wrap(err, "failed to execute trx.Select")
+ return wrap(err, "failed to execute trx.Select")
}
defer rows.Close()
@@ -310,8 +238,8 @@ func (trx *Trx) Select(data interface{}, command string, args ...interface{}) er
columns, _ = rows.Columns()
}
item := reflect.New(itemType)
- if err = trx.mapper.Map(item.Interface(), columns, rows.Scan); err != nil {
- return errors.Wrap(err, "failed to map result to model")
+ if err = rowMapper.Map(item.Interface(), columns, rows.Scan); err != nil {
+ return wrap(err, "failed to map result to model")
}
items = reflect.Append(items, item)
}
@@ -325,8 +253,8 @@ func (trx *Trx) Select(data interface{}, command string, args ...interface{}) er
// Commit current transaction
func (trx *Trx) Commit() error {
err := trx.tx.Commit()
- if err != nil {
- return errors.Wrap(err, "failed to commit transaction")
+ if err != nil && err != sql.ErrTxDone {
+ return wrap(err, "failed to commit transaction")
}
return nil
}
@@ -334,8 +262,17 @@ func (trx *Trx) Commit() error {
// Rollback current transaction
func (trx *Trx) Rollback() error {
err := trx.tx.Rollback()
- if err != nil {
- return errors.Wrap(err, "failed to rollback transaction")
+ if err != nil && err != sql.ErrTxDone {
+ return wrap(err, "failed to rollback transaction")
}
return nil
}
+
+func wrap(err error, format string, a ...interface{}) error {
+ if pqErr, ok := err.(*pq.Error); ok {
+ if pqErr.Code == "57014" { //query canceled
+ return errors.Wrap(context.Canceled, format, a...)
+ }
+ }
+ return errors.Wrap(err, format, a...)
+}
diff --git a/app/pkg/dbx/dbx_test.go b/app/pkg/dbx/dbx_test.go
index 41af16b91..263456564 100644
--- a/app/pkg/dbx/dbx_test.go
+++ b/app/pkg/dbx/dbx_test.go
@@ -1,6 +1,7 @@
package dbx_test
import (
+ "context"
"encoding/json"
"io/ioutil"
"os"
@@ -34,9 +35,7 @@ type tenant struct {
}
func TestMain(m *testing.M) {
- db := dbx.New()
- db.Seed()
- db.Close()
+ dbx.Seed()
code := m.Run()
os.Exit(code)
@@ -44,10 +43,8 @@ func TestMain(m *testing.M) {
func TestBind_SimpleStruct(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
u := user{}
@@ -60,10 +57,8 @@ func TestBind_SimpleStruct(t *testing.T) {
func TestBind_DeepNestedStruct(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
u := userProvider{}
@@ -82,10 +77,8 @@ func TestBind_DeepNestedStruct(t *testing.T) {
func TestBind_SimpleStruct_SingleField(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
u := user{}
@@ -97,10 +90,8 @@ func TestBind_SimpleStruct_SingleField(t *testing.T) {
func TestBind_SimpleStruct_Multiple(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
u := []*user{}
@@ -115,10 +106,8 @@ func TestBind_SimpleStruct_Multiple(t *testing.T) {
func TestBind_NestedStruct(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
u := userWithTenant{}
@@ -141,10 +130,8 @@ func TestBind_NestedStruct(t *testing.T) {
func TestBind_NestedStruct_Multiple(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
u := []*userWithTenant{}
@@ -169,10 +156,8 @@ func TestBind_NestedStruct_Multiple(t *testing.T) {
func TestExists_True(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
exists, err := trx.Exists("SELECT 1 FROM users WHERE id = 1")
@@ -182,10 +167,8 @@ func TestExists_True(t *testing.T) {
func TestExists_False(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
exists, err := trx.Exists("SELECT 1 FROM users WHERE id = 0")
@@ -195,10 +178,8 @@ func TestExists_False(t *testing.T) {
func TestCount(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
count, err := trx.Count("SELECT 1 FROM users WHERE id = 1")
@@ -208,10 +189,8 @@ func TestCount(t *testing.T) {
func TestCount_Empty(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
count, err := trx.Count("SELECT 1 FROM users WHERE id = 0")
@@ -221,10 +200,8 @@ func TestCount_Empty(t *testing.T) {
func TestScalar(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
var value int
@@ -235,10 +212,8 @@ func TestScalar(t *testing.T) {
func TestArray(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
type postTags struct {
@@ -257,10 +232,8 @@ func TestArray(t *testing.T) {
func TestArray_Empty(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
type postTags struct {
@@ -279,10 +252,8 @@ func TestArray_Empty(t *testing.T) {
func TestByteArray(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(context.Background())
defer trx.Rollback()
type file struct {
diff --git a/app/pkg/dbx/migrate.go b/app/pkg/dbx/migrate.go
index ab614fd02..9e55d5f75 100644
--- a/app/pkg/dbx/migrate.go
+++ b/app/pkg/dbx/migrate.go
@@ -1,6 +1,7 @@
package dbx
import (
+ "context"
"database/sql"
stdErrors "errors"
"io/ioutil"
@@ -9,6 +10,7 @@ import (
"strconv"
"strings"
+ "github.com/getfider/fider/app/models/dto"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
@@ -18,8 +20,8 @@ import (
var ErrNoChanges = stdErrors.New("nothing to migrate.")
// Migrate the database to latest version
-func (db *Database) Migrate(path string) error {
- db.logger.Info("Running migrations...")
+func Migrate(ctx context.Context, path string) error {
+ log.Info(ctx, "Running migrations...")
dir, err := os.Open(env.Path(path))
if err != nil {
return errors.Wrap(err, "failed to open dir '%s'", path)
@@ -47,46 +49,55 @@ func (db *Database) Migrate(path string) error {
}
sort.Ints(versions)
- db.logger.Infof("Found total of @{Total} migration files.", log.Props{
+ log.Infof(ctx, "Found total of @{Total} migration files.", dto.Props{
"Total": len(versions),
})
- lastVersion, err := db.getLastMigration()
+ lastVersion, err := getLastMigration()
if err != nil {
return errors.Wrap(err, "failed to get last migration record")
}
- db.logger.Infof("Current version is @{Version}", log.Props{
+ log.Infof(ctx, "Current version is @{Version}", dto.Props{
"Version": lastVersion,
})
+ totalMigrationsExecuted := 0
+
// Apply all migrations
for _, version := range versions {
if version > lastVersion {
fileName := versionFiles[version]
- db.logger.Infof("Running Version: @{Version} (@{FileName})", log.Props{
+ log.Infof(ctx, "Running Version: @{Version} (@{FileName})", dto.Props{
"Version": version,
"FileName": fileName,
})
- err := db.runMigration(version, path, fileName)
+ err := runMigration(ctx, version, path, fileName)
if err != nil {
return errors.Wrap(err, "failed to run migration '%s'", fileName)
}
+ totalMigrationsExecuted++
}
}
- db.logger.Info("Migrations finished with success.")
+ if totalMigrationsExecuted > 0 {
+ log.Infof(ctx, "@{Count} migrations have been applied.", dto.Props{
+ "Count": totalMigrationsExecuted,
+ })
+ } else {
+ log.Info(ctx, "Migrations are already up to date.")
+ }
return nil
}
-func (db Database) runMigration(version int, path, fileName string) error {
+func runMigration(ctx context.Context, version int, path, fileName string) error {
filePath := env.Path(path + "/" + fileName)
content, err := ioutil.ReadFile(filePath)
if err != nil {
return errors.Wrap(err, "failed to read file '%s'", filePath)
}
- trx, err := db.Begin()
+ trx, err := BeginTx(ctx)
if err != nil {
return err
}
@@ -104,8 +115,8 @@ func (db Database) runMigration(version int, path, fileName string) error {
return trx.Commit()
}
-func (db Database) getLastMigration() (int, error) {
- _, err := db.conn.Exec(`CREATE TABLE IF NOT EXISTS migrations_history (
+func getLastMigration() (int, error) {
+ _, err := conn.Exec(`CREATE TABLE IF NOT EXISTS migrations_history (
version BIGINT PRIMARY KEY,
filename VARCHAR(100) null,
date TIMESTAMPTZ NOT NULL DEFAULT NOW()
@@ -115,7 +126,7 @@ func (db Database) getLastMigration() (int, error) {
}
var lastVersion sql.NullInt64
- row := db.conn.QueryRow("SELECT MAX(version) FROM migrations_history LIMIT 1")
+ row := conn.QueryRow("SELECT MAX(version) FROM migrations_history LIMIT 1")
err = row.Scan(&lastVersion)
if err != nil {
return 0, err
@@ -124,7 +135,7 @@ func (db Database) getLastMigration() (int, error) {
if !lastVersion.Valid {
// If it's the first run, maybe we have records on old migrations table, so try to get from it.
// This SHOULD be removed in the far future.
- row := db.conn.QueryRow("SELECT version FROM schema_migrations LIMIT 1")
+ row := conn.QueryRow("SELECT version FROM schema_migrations LIMIT 1")
row.Scan(&lastVersion)
}
diff --git a/app/pkg/dbx/migrate_test.go b/app/pkg/dbx/migrate_test.go
index 352a8d8e4..618fa0e5e 100644
--- a/app/pkg/dbx/migrate_test.go
+++ b/app/pkg/dbx/migrate_test.go
@@ -1,31 +1,32 @@
package dbx_test
import (
+ "context"
"testing"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/dbx"
)
-func setupMigrationTest(t *testing.T) *dbx.Database {
+func setupMigrationTest(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- trx, _ := db.Begin()
+ ctx := context.Background()
+
+ trx, _ := dbx.BeginTx(ctx)
trx.Execute("DELETE FROM migrations_history WHERE version >= 210001010000")
trx.Execute("DROP TABLE IF EXISTS dummy")
trx.Execute("DROP TABLE IF EXISTS foo")
trx.Commit()
- return db
}
func TestMigrate_Success(t *testing.T) {
- db := setupMigrationTest(t)
- defer db.Close()
+ setupMigrationTest(t)
+ ctx := context.Background()
- err := db.Migrate("/app/pkg/dbx/testdata/migration_success")
+ err := dbx.Migrate(ctx, "/app/pkg/dbx/testdata/migration_success")
Expect(err).IsNil()
- trx, _ := db.Begin()
+ trx, _ := dbx.BeginTx(ctx)
var value string
err = trx.Scalar(&value, "SELECT description FROM dummy WHERE id = 200 LIMIT 1")
Expect(err).IsNil()
@@ -39,12 +40,13 @@ func TestMigrate_Success(t *testing.T) {
}
func TestMigrate_Failure(t *testing.T) {
- db := setupMigrationTest(t)
- defer db.Close()
- trx, _ := db.Begin()
+ setupMigrationTest(t)
+ ctx := context.Background()
+
+ trx, _ := dbx.BeginTx(ctx)
defer trx.Rollback()
- err := db.Migrate("/app/pkg/dbx/testdata/migration_failure")
+ err := dbx.Migrate(context.Background(), "/app/pkg/dbx/testdata/migration_failure")
Expect(err).IsNotNil()
_, err = trx.Execute("SELECT description FROM dummy")
diff --git a/app/pkg/di/blob.go b/app/pkg/di/blob.go
deleted file mode 100644
index 68866c8d5..000000000
--- a/app/pkg/di/blob.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package di
-
-import (
- "strings"
-
- "github.com/getfider/fider/app/pkg/blob"
- "github.com/getfider/fider/app/pkg/blob/fs"
- "github.com/getfider/fider/app/pkg/blob/s3"
- "github.com/getfider/fider/app/pkg/blob/sql"
- "github.com/getfider/fider/app/pkg/dbx"
- "github.com/getfider/fider/app/pkg/email"
- "github.com/getfider/fider/app/pkg/email/mailgun"
- "github.com/getfider/fider/app/pkg/email/noop"
- "github.com/getfider/fider/app/pkg/email/smtp"
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/log"
- "github.com/getfider/fider/app/pkg/web/http"
-)
-
-// NewEmailer creates a new emailer instance based on current configuration
-func NewEmailer(logger log.Logger) email.Sender {
- if env.IsTest() {
- return noop.NewSender()
- }
-
- if env.Config.Email.Mailgun.APIKey != "" {
- return mailgun.NewSender(
- logger,
- http.NewClient(),
- env.Config.Email.Mailgun.Domain,
- env.Config.Email.Mailgun.APIKey,
- )
- }
-
- return smtp.NewSender(
- logger,
- env.Config.Email.SMTP.Host,
- env.Config.Email.SMTP.Port,
- env.Config.Email.SMTP.Username,
- env.Config.Email.SMTP.Password,
- )
-}
-
-// NewBlobStorage creates a new blob storage instance based on current configuration
-func NewBlobStorage(db *dbx.Database) blob.Storage {
- storageType := strings.ToLower(env.Config.BlobStorage.Type)
- switch storageType {
- case "sql":
- return sql.NewStorage(db)
- case "s3":
- return s3.NewStorage(env.Config.BlobStorage.S3.BucketName)
- case "fs":
- return fs.NewStorage(env.Config.BlobStorage.FS.Path)
- }
- panic("Invalid blob storage type: " + storageType)
-}
diff --git a/app/pkg/email/email.go b/app/pkg/email/email.go
deleted file mode 100644
index ad61dbef2..000000000
--- a/app/pkg/email/email.go
+++ /dev/null
@@ -1,153 +0,0 @@
-package email
-
-import (
- "bytes"
- "html/template"
- "net/mail"
- "regexp"
- "strings"
-
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/env"
-)
-
-var cache = make(map[string]*template.Template, 0)
-
-// Params used to replace variables on emails
-type Params map[string]interface{}
-
-// Merge given params into current params
-func (p Params) Merge(p2 Params) Params {
- for k, v := range p2 {
- p[k] = v
- }
- return p
-}
-
-// Message represents what is sent by email
-type Message struct {
- Subject string
- Body string
-}
-
-var baseTpl, _ = template.ParseFiles(env.Path("/views/templates/base_email.tpl"))
-
-// RenderMessage returns the HTML of an email based on template and params
-func RenderMessage(ctx Context, templateName string, params Params) *Message {
- tpl, ok := cache[templateName]
- if !ok || env.IsDevelopment() {
- var err error
- file := env.Path("/views/templates", templateName+".tpl")
- tpl, err = template.ParseFiles(file)
- if err != nil {
- panic(err)
- }
- cache[templateName] = tpl
- }
-
- var bf bytes.Buffer
- if err := tpl.Execute(&bf, params); err != nil {
- panic(err)
- }
-
- lines := strings.Split(bf.String(), "\n")
- body := strings.TrimLeft(strings.Join(lines[2:], "\n"), " ")
-
- logo, ok := params["logo"].(string)
- if !ok || logo == "" {
- logo = ctx.LogoURL()
- }
-
- bf.Reset()
- if err := baseTpl.Execute(&bf, Params{
- "logo": logo,
- "body": template.HTML(body),
- }); err != nil {
- panic(err)
- }
-
- return &Message{
- Subject: strings.TrimLeft(lines[0], "subject: "),
- Body: bf.String(),
- }
-}
-
-// Context holds everything emailers need to know about execution context
-type Context interface {
- Tenant() *models.Tenant
- BaseURL() string
- LogoURL() string
-}
-
-// NoReply is the default 'from' address
-var NoReply = env.Config.Email.NoReply
-
-// Recipient contains details of who is receiving the email
-type Recipient struct {
- Name string
- Address string
- Params Params
-}
-
-// NewRecipient creates a new Recipient
-func NewRecipient(name, address string, params Params) Recipient {
- return Recipient{
- Name: name,
- Address: address,
- Params: params,
- }
-}
-
-// Strings returns the RFC format to send emails via SMTP
-func (r Recipient) String() string {
- if r.Address == "" {
- return ""
- }
-
- address := mail.Address{
- Name: r.Name,
- Address: r.Address,
- }
-
- return address.String()
-}
-
-var whitelist = env.Config.Email.Whitelist
-var whitelistRegex = regexp.MustCompile(whitelist)
-var blacklist = env.Config.Email.Blacklist
-var blacklistRegex = regexp.MustCompile(blacklist)
-
-// SetWhitelist can be used to change email whitelist during runtime
-func SetWhitelist(s string) {
- whitelist = s
- whitelistRegex = regexp.MustCompile(whitelist)
-}
-
-// SetBlacklist can be used to change email blacklist during runtime
-func SetBlacklist(s string) {
- blacklist = s
- blacklistRegex = regexp.MustCompile(blacklist)
-}
-
-// CanSendTo returns true if Fider is allowed to send email to given address
-func CanSendTo(address string) bool {
- if strings.TrimSpace(address) == "" {
- return false
- }
-
- if whitelist != "" {
- return whitelistRegex.MatchString(address)
- }
-
- if blacklist != "" {
- return !blacklistRegex.MatchString(address)
- }
-
- return true
-}
-
-// Sender is used to send emails
-type Sender interface {
- Send(ctx Context, templateName string, params Params, from string, to Recipient) error
- BatchSend(ctx Context, templateName string, params Params, from string, to []Recipient) error
-}
diff --git a/app/pkg/email/mailgun/mailgun.go b/app/pkg/email/mailgun/mailgun.go
deleted file mode 100644
index e1cd30b94..000000000
--- a/app/pkg/email/mailgun/mailgun.go
+++ /dev/null
@@ -1,155 +0,0 @@
-package mailgun
-
-import (
- "encoding/json"
- "fmt"
- "net/url"
- "strings"
-
- "github.com/getfider/fider/app/pkg/email"
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/log"
- "github.com/getfider/fider/app/pkg/web/http"
-)
-
-// Known base URLs
-// Should Mailgun add other regions we'll just need to add their URLs here
-// Use upper case keys - incoming env var values are normalized before being used
-var baseURLs = map[string]string{
- "US" : "https://api.mailgun.net/v3/%s/messages",
- "EU" : "https://api.eu.mailgun.net/v3/%s/messages",
-}
-
-//Sender is used to send emails
-type Sender struct {
- logger log.Logger
- client http.Client
- domain string
- apiKey string
-}
-
-//NewSender creates a new mailgun email sender
-func NewSender(logger log.Logger, client http.Client, domain, apiKey string) *Sender {
- return &Sender{logger, client, domain, apiKey}
-}
-
-//Send an email
-func (s *Sender) Send(ctx email.Context, templateName string, params email.Params, from string, to email.Recipient) error {
- return s.BatchSend(ctx, templateName, params, from, []email.Recipient{to})
-}
-
-// Try getting the base URL of the Mailgun API using Environment vars and the Sender's domain
-// Fall back to the URL for the US region if that fails to maintain compatibility with older installs
-func (s *Sender) GetBaseURL() string {
- var regionCode = env.Config.Email.Mailgun.Region
- regionCode = strings.ToUpper(regionCode)
-
- // Default to the US domain if no region code was provided (ENV not set)
- // or if the provided code isn't valid
- if len(regionCode) < 1 {
- regionCode = "US"
- } else if len(baseURLs[regionCode]) < 1 {
- s.logger.Warnf(
- "Unknown Mailgun region code '@{Code}' configured - falling back to 'US'",
- log.Props{
- "Code": env.Config.Email.Mailgun.Region,
- },
- )
-
- regionCode = "US"
- }
-
- return fmt.Sprintf(baseURLs[regionCode], s.domain)
-}
-
-// BatchSend an email to multiple recipients
-func (s *Sender) BatchSend(ctx email.Context, templateName string, params email.Params, from string, to []email.Recipient) error {
- if len(to) == 0 {
- return nil
- }
-
- isBatch := len(to) > 1
-
- var message *email.Message
- if isBatch {
- // Replace recipient specific Go templates variables with Mailgun template variables
- for k := range to[0].Params {
- params[k] = fmt.Sprintf("%%recipient.%s%%", k)
- }
- message = email.RenderMessage(ctx, templateName, params)
- } else {
- message = email.RenderMessage(ctx, templateName, params.Merge(to[0].Params))
- }
-
- form := url.Values{}
- form.Add("from", email.NewRecipient(from, email.NoReply, email.Params{}).String())
- form.Add("h:Reply-To", email.NoReply)
- form.Add("subject", message.Subject)
- form.Add("html", message.Body)
- form.Add("o:tag", fmt.Sprintf("template:%s", templateName))
- if ctx.Tenant() != nil && !env.IsSingleHostMode() {
- form.Add("o:tag", fmt.Sprintf("tenant:%s", ctx.Tenant().Subdomain))
- }
-
- // Set Mailgun's var based on each recipient's variables
- recipientVariables := make(map[string]email.Params, 0)
- for _, r := range to {
- if r.Address != "" {
- if email.CanSendTo(r.Address) {
- form.Add("to", r.String())
- recipientVariables[r.Address] = r.Params
- } else {
- s.logger.Warnf("Skipping email to '@{Name} <@{Address}>'.", log.Props{
- "Name": r.Name,
- "Address": r.Address,
- })
- }
- }
- }
-
- // If we skipped all recipients, just return
- if len(recipientVariables) == 0 {
- return nil
- }
-
- if isBatch {
- json, err := json.Marshal(recipientVariables)
- if err != nil {
- return errors.Wrap(err, "failed to marshal recipient variables")
- }
-
- form.Add("recipient-variables", string(json))
- }
-
- if isBatch {
- s.logger.Debugf("Sending email to @{CountRecipients} recipients with template @{TemplateName}.", log.Props{
- "CountRecipients": len(recipientVariables),
- "TemplateName": templateName,
- })
- } else {
- s.logger.Debugf("Sending email to @{Address} with template @{TemplateName}.", log.Props{
- "Address": to[0].Address,
- "TemplateName": templateName,
- })
- }
-
- request, err := http.NewRequest("POST", s.GetBaseURL(), strings.NewReader(form.Encode()))
- if err != nil {
- return errors.Wrap(err, "failed to create POST request")
- }
-
- request.SetBasicAuth("api", s.apiKey)
- request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
-
- resp, err := s.client.Do(request)
- if err != nil {
- return errors.Wrap(err, "failed to send email with template %s", templateName)
- }
-
- defer resp.Body.Close()
- s.logger.Debugf("Email sent with response code @{StatusCode}.", log.Props{
- "StatusCode": resp.StatusCode,
- })
- return nil
-}
diff --git a/app/pkg/email/noop/noop.go b/app/pkg/email/noop/noop.go
deleted file mode 100644
index eba3407e6..000000000
--- a/app/pkg/email/noop/noop.go
+++ /dev/null
@@ -1,53 +0,0 @@
-package noop
-
-import (
- "github.com/getfider/fider/app/pkg/email"
-)
-
-type request struct {
- Context email.Context
- TemplateName string
- Params email.Params
- From string
- To []email.Recipient
-}
-
-// Sender does not send emails
-type Sender struct {
- Requests []*request
-}
-
-// NewSender creates a new NoopSender
-func NewSender() *Sender {
- return &Sender{
- Requests: make([]*request, 0),
- }
-}
-
-// Send an email
-func (s *Sender) Send(ctx email.Context, templateName string, params email.Params, from string, to email.Recipient) error {
- s.Requests = append(s.Requests, &request{
- Context: ctx,
- TemplateName: templateName,
- Params: params,
- From: from,
- To: []email.Recipient{to},
- })
- return nil
-
-}
-
-// BatchSend an email to multiple recipients
-func (s *Sender) BatchSend(ctx email.Context, templateName string, params email.Params, from string, to []email.Recipient) error {
- if len(to) > 0 {
- s.Requests = append(s.Requests, &request{
- Context: ctx,
- TemplateName: templateName,
- Params: params,
- From: from,
- To: to,
- })
- }
-
- return nil
-}
diff --git a/app/pkg/email/smtp/smtp.go b/app/pkg/email/smtp/smtp.go
deleted file mode 100644
index b62e0f43c..000000000
--- a/app/pkg/email/smtp/smtp.go
+++ /dev/null
@@ -1,177 +0,0 @@
-package smtp
-
-import (
- "crypto/rand"
- "crypto/tls"
- "encoding/hex"
- "fmt"
- "net"
- gosmtp "net/smtp"
- "net/url"
- "strconv"
- "time"
-
- "github.com/getfider/fider/app/pkg/email"
- "github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/log"
-)
-
-func authenticate(username string, password string, host string) gosmtp.Auth {
- if username == "" && password == "" {
- return nil
- }
- return AgnosticAuth("", username, password, host)
-}
-
-type builder struct {
- content string
-}
-
-func (b *builder) Set(key, value string) {
- b.content += fmt.Sprintf("%s: %s\r\n", key, value)
-}
-
-func (b *builder) Body(body string) {
- b.content += "\r\n" + body
-}
-
-func (b *builder) Bytes() []byte {
- return []byte(b.content)
-}
-
-//Sender is used to send emails
-type Sender struct {
- logger log.Logger
- host string
- port string
- username string
- password string
- send func(string, string, gosmtp.Auth, string, []string, []byte) error
-}
-
-//NewSender creates a new mailgun email sender
-func NewSender(logger log.Logger, host, port, username, password string) *Sender {
- return &Sender{logger, host, port, username, password, sendMail}
-}
-
-//ReplaceSend can be used to mock internal send function
-func (s *Sender) ReplaceSend(send func(string, string, gosmtp.Auth, string, []string, []byte) error) {
- s.send = send
-}
-
-//Send an email
-func (s *Sender) Send(ctx email.Context, templateName string, params email.Params, from string, to email.Recipient) error {
- if to.Address == "" {
- return nil
- }
-
- u, err := url.Parse(ctx.BaseURL())
- localname := "localhost"
- if err == nil {
- localname = u.Hostname()
- }
-
- if !email.CanSendTo(to.Address) {
- s.logger.Warnf("Skipping email to '@{Name} <@{Address}>'.", log.Props{
- "Name": to.Name,
- "Address": to.Address,
- })
- return nil
- }
-
- s.logger.Debugf("Sending email to @{Address} with template @{TemplateName} and params @{Params}.", log.Props{
- "Address": to.Address,
- "TemplateName": templateName,
- "Params": to.Params,
- })
-
- message := email.RenderMessage(ctx, templateName, params.Merge(to.Params))
- b := builder{}
- b.Set("From", email.NewRecipient(from, email.NoReply, email.Params{}).String())
- b.Set("Reply-To", email.NoReply)
- b.Set("To", to.String())
- b.Set("Subject", message.Subject)
- b.Set("MIME-version", "1.0")
- b.Set("Content-Type", "text/html; charset=\"UTF-8\"")
- b.Set("Date", time.Now().Format(time.RFC1123Z))
- b.Set("Message-ID", generateMessageID(localname))
- b.Body(message.Body)
-
- servername := fmt.Sprintf("%s:%s", s.host, s.port)
- auth := authenticate(s.username, s.password, s.host)
- err = s.send(localname, servername, auth, email.NoReply, []string{to.Address}, b.Bytes())
- if err != nil {
- return errors.Wrap(err, "failed to send email with template %s", templateName)
- }
- s.logger.Debug("Email sent.")
- return nil
-}
-
-// BatchSend an email to multiple recipients
-func (s *Sender) BatchSend(ctx email.Context, templateName string, params email.Params, from string, to []email.Recipient) error {
- for _, r := range to {
- if err := s.Send(ctx, templateName, params, from, r); err != nil {
- return errors.Wrap(err, "failed to batch send email to %d recipients", len(to))
- }
- }
- return nil
-}
-
-func sendMail(localName, serverAddress string, a gosmtp.Auth, from string, to []string, msg []byte) error {
- host, _, _ := net.SplitHostPort(serverAddress)
- c, err := gosmtp.Dial(serverAddress)
- if err != nil {
- return err
- }
- defer c.Close()
- if err = c.Hello(localName); err != nil {
- return err
- }
- if ok, _ := c.Extension("STARTTLS"); ok {
- config := &tls.Config{ServerName: host}
- if err = c.StartTLS(config); err != nil {
- return err
- }
- }
- if a != nil {
- if ok, _ := c.Extension("AUTH"); !ok {
- return errors.New("smtp: server doesn't support AUTH")
- }
- if err = c.Auth(a); err != nil {
- return err
- }
- }
- if err = c.Mail(from); err != nil {
- return err
- }
- for _, addr := range to {
- if err = c.Rcpt(addr); err != nil {
- return err
- }
- }
- w, err := c.Data()
- if err != nil {
- return err
- }
- _, err = w.Write(msg)
- if err != nil {
- return err
- }
- err = w.Close()
- if err != nil {
- return err
- }
- return c.Quit()
-}
-
-func generateMessageID(localName string) string {
- timestamp := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
- buf := make([]byte, 16)
- _, err := rand.Read(buf)
- if err != nil {
- panic(err)
- }
- randStr := hex.EncodeToString(buf)
- messageID := fmt.Sprintf("<%s.%s@%s>", randStr, timestamp, localName)
- return messageID
-}
diff --git a/app/pkg/errors/errors.go b/app/pkg/errors/errors.go
index 6fd87802d..54021a4fb 100644
--- a/app/pkg/errors/errors.go
+++ b/app/pkg/errors/errors.go
@@ -4,6 +4,8 @@ import (
stdError "errors"
"fmt"
"runtime"
+ "runtime/debug"
+ "strings"
)
type theError struct {
@@ -29,6 +31,16 @@ func Wrap(err error, format string, a ...interface{}) error {
return wrap(err, 0, format, a...)
}
+//Panicked wraps panick errow with extra details of error
+func Panicked(r interface{}) error {
+ err, ok := r.(error)
+ if !ok {
+ err = fmt.Errorf("%v", r)
+ }
+ err = Wrap(err, identifyPanic())
+ return Wrap(err, string(debug.Stack()))
+}
+
//Stack add current code location without adding more info
func Stack(err error) error {
return wrap(err, 0, "")
@@ -64,6 +76,34 @@ func wrap(err error, skip int, format string, a ...interface{}) error {
}
}
+func identifyPanic() string {
+ var name, file string
+ var line int
+ var pc [16]uintptr
+
+ n := runtime.Callers(4, pc[:])
+ for _, pc := range pc[:n] {
+ fn := runtime.FuncForPC(pc)
+ if fn == nil {
+ continue
+ }
+ file, line = fn.FileLine(pc)
+ name = fn.Name()
+ if !strings.HasPrefix(name, "runtime.") {
+ break
+ }
+ }
+
+ switch {
+ case name != "":
+ return fmt.Sprintf("%v:%v", name, line)
+ case file != "":
+ return fmt.Sprintf("%v:%v", file, line)
+ }
+
+ return fmt.Sprintf("pc:%x", pc)
+}
+
//Cause returns the original cause of the error stack
func Cause(err error) error {
casted, ok := err.(*theError)
diff --git a/app/pkg/errors/errors_test.go b/app/pkg/errors/errors_test.go
index 0b05de3f7..838dc2794 100644
--- a/app/pkg/errors/errors_test.go
+++ b/app/pkg/errors/errors_test.go
@@ -77,3 +77,22 @@ func TestNilErrors(t *testing.T) {
Expect(errors.Stack(nil)).IsNil()
Expect(errors.Wrap(nil, "")).IsNil()
}
+
+func TestPanicked(t *testing.T) {
+ RegisterT(t)
+
+ defer func() {
+ if r := recover(); r != nil {
+ err := errors.Panicked(r)
+ Expect(err.Error()).ContainsSubstring(`
+runtime/debug.Stack`)
+ Expect(err.Error()).ContainsSubstring(`
+github.com/getfider/fider/app/pkg/errors.Panicked`)
+ Expect(err.Error()).ContainsSubstring(`
+- github.com/getfider/fider/app/pkg/errors_test.TestPanicked:97 (app/pkg/errors/errors.go:40)
+- Boom!`)
+ }
+ }()
+
+ panic("Boom!")
+}
diff --git a/app/pkg/log/console/logger.go b/app/pkg/log/console/logger.go
deleted file mode 100644
index 84ab27d17..000000000
--- a/app/pkg/log/console/logger.go
+++ /dev/null
@@ -1,142 +0,0 @@
-package console
-
-import (
- "fmt"
- stdLog "log"
- "os"
- "strings"
- "time"
-
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/log"
-)
-
-// Logger output messages to console
-type Logger struct {
- logger *stdLog.Logger
- level log.Level
- tag string
- props log.Props
- enabled bool
-}
-
-// NewLogger creates a new Logger
-func NewLogger(tag string) *Logger {
- level := strings.ToUpper(env.Config.Log.Level)
- return &Logger{
- tag: tag,
- logger: stdLog.New(os.Stdout, "", 0),
- level: log.ParseLevel(level),
- props: make(log.Props, 0),
- enabled: !env.IsTest(),
- }
-}
-
-// Disable logs for this logger
-func (l *Logger) Disable() {
- l.enabled = false
-}
-
-// Enable logs for this logger
-func (l *Logger) Enable() {
- l.enabled = true
-}
-
-// SetLevel increases/decreases current log level
-func (l *Logger) SetLevel(level log.Level) {
- l.level = level
-}
-
-// IsEnabled returns true if given level is enabled
-func (l *Logger) IsEnabled(level log.Level) bool {
- return l.enabled && level >= l.level
-}
-
-// Debug logs a DEBUG message
-func (l *Logger) Debug(message string) {
- l.log(log.DEBUG, message, nil)
-}
-
-// Debugf logs a DEBUG message
-func (l *Logger) Debugf(message string, props log.Props) {
- l.log(log.DEBUG, message, props)
-}
-
-// Info logs a INFO message
-func (l *Logger) Info(message string) {
- l.log(log.INFO, message, nil)
-}
-
-// Infof logs a INFO message
-func (l *Logger) Infof(message string, props log.Props) {
- l.log(log.INFO, message, props)
-}
-
-// Warn logs a WARN message
-func (l *Logger) Warn(message string) {
- l.log(log.WARN, message, nil)
-}
-
-// Warnf logs a WARN message
-func (l *Logger) Warnf(message string, props log.Props) {
- l.log(log.WARN, message, props)
-}
-
-// Errorf logs a ERROR message
-func (l *Logger) Errorf(message string, props log.Props) {
- l.log(log.ERROR, message, props)
-}
-
-// Error logs a ERROR message
-func (l *Logger) Error(err error) {
- if err != nil {
- l.log(log.ERROR, err.Error(), nil)
- } else {
- l.log(log.ERROR, "nil", nil)
- }
-}
-
-// Write writes len(p) bytes from p to the underlying data stream.
-func (l *Logger) Write(p []byte) (int, error) {
- l.Debug(fmt.Sprintf("%s", p))
- return len(p), nil
-}
-
-// New returns a copy of current logger with empty context
-func (l *Logger) New() log.Logger {
- return NewLogger(l.tag)
-}
-
-// SetProperty with given key:value into current logger context
-func (l *Logger) SetProperty(key string, value interface{}) {
- l.props[key] = value
-}
-
-func (l *Logger) log(level log.Level, message string, props log.Props) {
- props = l.props.Merge(props)
- if !l.IsEnabled(level) {
- return
- }
- message = log.Parse(message, props, true)
- contextID := l.props[log.PropertyKeyContextID]
- l.logger.Printf("%s [%s] [%s] [%s] %s\n", colorizeLevel(level), time.Now().Format(time.RFC3339), l.tag, contextID, message)
-}
-
-func colorizeLevel(level log.Level) string {
- var color func(interface{}) string
-
- switch level {
- case log.DEBUG:
- color = log.Magenta
- case log.INFO:
- color = log.Blue
- case log.WARN:
- color = log.Yellow
- case log.ERROR:
- color = log.Red
- default:
- color = log.Red
- }
-
- return log.Bold(color(level.String()))
-}
diff --git a/app/pkg/log/database/logger.go b/app/pkg/log/database/logger.go
deleted file mode 100644
index 94c5972c5..000000000
--- a/app/pkg/log/database/logger.go
+++ /dev/null
@@ -1,149 +0,0 @@
-package database
-
-import (
- "fmt"
- "strings"
- "time"
-
- "github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/log/console"
-
- "github.com/getfider/fider/app/pkg/dbx"
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/log"
-)
-
-// Logger writes logs to a SQL database
-type Logger struct {
- db *dbx.Database
- console log.Logger
- level log.Level
- tag string
- props log.Props
- enabled bool
-}
-
-// NewLogger creates a new Logger
-func NewLogger(tag string, db *dbx.Database) *Logger {
- level := strings.ToUpper(env.Config.Log.Level)
- return &Logger{
- tag: tag,
- db: db,
- console: console.NewLogger(tag),
- level: log.ParseLevel(level),
- props: make(log.Props, 0),
- enabled: true,
- }
-}
-
-// Disable logs for this logger
-func (l *Logger) Disable() {
- l.enabled = false
-}
-
-// Enable logs for this logger
-func (l *Logger) Enable() {
- l.enabled = true
-}
-
-// SetLevel increases/decreases current log level
-func (l *Logger) SetLevel(level log.Level) {
- l.level = level
- l.console.SetLevel(level)
-}
-
-// IsEnabled returns true if given level is enabled
-func (l *Logger) IsEnabled(level log.Level) bool {
- return l.enabled && level >= l.level
-}
-
-// Debug logs a DEBUG message
-func (l *Logger) Debug(message string) {
- l.console.Debug(message)
- l.log(log.DEBUG, message, nil)
-}
-
-// Debugf logs a DEBUG message
-func (l *Logger) Debugf(message string, props log.Props) {
- l.console.Debugf(message, props)
- l.log(log.DEBUG, message, props)
-}
-
-// Info logs a INFO message
-func (l *Logger) Info(message string) {
- l.console.Info(message)
- l.log(log.INFO, message, nil)
-}
-
-// Infof logs a INFO message
-func (l *Logger) Infof(message string, props log.Props) {
- l.console.Infof(message, props)
- l.log(log.INFO, message, props)
-}
-
-// Warn logs a WARN message
-func (l *Logger) Warn(message string) {
- l.console.Warn(message)
- l.log(log.WARN, message, nil)
-}
-
-// Warnf logs a WARN message
-func (l *Logger) Warnf(message string, props log.Props) {
- l.console.Warnf(message, props)
- l.log(log.WARN, message, props)
-}
-
-// Errorf logs a ERROR message
-func (l *Logger) Errorf(message string, props log.Props) {
- l.console.Errorf(message, props)
- l.log(log.ERROR, message, props)
-}
-
-// Error logs a ERROR message
-func (l *Logger) Error(err error) {
- if err != nil {
- l.log(log.ERROR, err.Error(), nil)
- } else {
- l.log(log.ERROR, "nil", nil)
- }
- l.console.Error(err)
-}
-
-// Write writes len(p) bytes from p to the underlying data stream.
-func (l *Logger) Write(p []byte) (int, error) {
- l.console.Write(p)
- l.Debug(fmt.Sprintf("%s", p))
- return len(p), nil
-}
-
-// New returns a copy of current logger with empty context
-func (l *Logger) New() log.Logger {
- return NewLogger(l.tag, l.db)
-}
-
-// SetProperty with given key:value into current logger context
-func (l *Logger) SetProperty(key string, value interface{}) {
- l.props[key] = value
- l.console.SetProperty(key, value)
-}
-
-func (l *Logger) log(level log.Level, message string, props log.Props) {
- if !l.IsEnabled(level) {
- return
- }
-
- props = l.props.Merge(props)
- message = log.Parse(message, props, false)
-
- go l.fireAndForgetLog(level, message, props)
-}
-
-func (l *Logger) fireAndForgetLog(level log.Level, message string, props log.Props) {
- _, err := l.db.Connection().Exec(
- "INSERT INTO logs (tag, level, text, created_at, properties) VALUES ($1, $2, $3, $4, $5)",
- l.tag, level.String(), message, time.Now(), props,
- )
- if err != nil {
- l.console.Error(errors.Wrap(err, "failed to insert log"))
- }
-}
diff --git a/app/pkg/log/database/logger_test.go b/app/pkg/log/database/logger_test.go
deleted file mode 100644
index 1e1d6341e..000000000
--- a/app/pkg/log/database/logger_test.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package database_test
-
-import (
- "testing"
-
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/dbx"
- "github.com/getfider/fider/app/pkg/log"
- "github.com/getfider/fider/app/pkg/log/database"
-)
-
-type logEntry struct {
- Tag string `db:"tag"`
- Level string `db:"level"`
- Text string `db:"text"`
-}
-
-func TestLog(t *testing.T) {
- RegisterT(t)
- db := dbx.New()
- defer db.Close()
- db.Connection().Exec("DELETE FROM logs WHERE properties->>'ContextID' = 'MyContextID'")
-
- trx, _ := db.Begin()
- defer trx.Commit()
-
- logger := database.NewLogger("TEST", db)
- logger.SetLevel(log.INFO)
- logger.SetProperty(log.PropertyKeyContextID, "MyContextID")
- db.SetLogger(logger)
-
- logger.Infof("2 + 2 is @{Result}", log.Props{"Result": 4})
- logger.Debugf("2 + 2 is @{Result}", log.Props{"Result": 4})
-
- Expect(func() int {
- count, err := trx.Count("SELECT * FROM logs WHERE properties->>'ContextID' = 'MyContextID'")
- Expect(err).IsNil()
- return count
- }).EventuallyEquals(1)
-
- var entries []*logEntry
- err := trx.Select(&entries, "SELECT tag, level, text FROM logs WHERE properties->>'ContextID' = 'MyContextID'")
- Expect(err).IsNil()
- Expect(entries).HasLen(1)
- Expect(entries[0].Tag).Equals("TEST")
- Expect(entries[0].Level).Equals("INFO")
- Expect(entries[0].Text).Equals("2 + 2 is 4")
-}
diff --git a/app/pkg/log/level.go b/app/pkg/log/level.go
new file mode 100644
index 000000000..cdb11c7d2
--- /dev/null
+++ b/app/pkg/log/level.go
@@ -0,0 +1,48 @@
+package log
+
+// Level defines all possible log levels
+type Level uint8
+
+const (
+ // DEBUG for verbose logs
+ DEBUG Level = iota + 1
+ // INFO for WARN+ERROR+INFO logs
+ INFO
+ // WARN for WARN+ERROR logs
+ WARN
+ // ERROR for ERROR only logs
+ ERROR
+ // NONE is used to disable logs
+ NONE
+)
+
+// parseLevel returns a log.Level based on input string
+func parseLevel(level string) Level {
+ switch level {
+ case "DEBUG":
+ return DEBUG
+ case "WARN":
+ return WARN
+ case "ERROR":
+ return ERROR
+ default:
+ return INFO
+ }
+}
+
+func (l Level) String() string {
+ switch l {
+ case DEBUG:
+ return "DEBUG"
+ case INFO:
+ return "INFO"
+ case WARN:
+ return "WARN"
+ case ERROR:
+ return "ERROR"
+ case NONE:
+ return "NONE"
+ default:
+ return "???"
+ }
+}
diff --git a/app/pkg/log/log.go b/app/pkg/log/log.go
index 9d047e2cf..378392e9b 100644
--- a/app/pkg/log/log.go
+++ b/app/pkg/log/log.go
@@ -1,141 +1,49 @@
package log
import (
- "database/sql/driver"
- "encoding/json"
- "fmt"
- "regexp"
+ "context"
"strings"
-)
-
-// Level defines all possible log levels
-type Level uint8
-// Logger defines the logging interface.
-type Logger interface {
- Disable()
- Enable()
- SetLevel(level Level)
- SetProperty(key string, value interface{})
- Debug(message string)
- Debugf(message string, props Props)
- Info(message string)
- Infof(message string, props Props)
- Warn(format string)
- Warnf(message string, props Props)
- Error(err error)
- Errorf(message string, props Props)
- IsEnabled(level Level) bool
- Write(p []byte) (int, error)
- New() Logger
-}
-
-const (
- // PropertyKeySessionID is the session id of current logger
- PropertyKeySessionID = "SessionID"
- // PropertyKeyContextID is the context id of current logger
- PropertyKeyContextID = "ContextID"
- // PropertyKeyUserID is the user id of current logger
- PropertyKeyUserID = "UserID"
- // PropertyKeyTenantID is the tenant id of current logger
- PropertyKeyTenantID = "TenantID"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/env"
)
-const (
- // DEBUG for verbose logs
- DEBUG Level = iota + 1
- // INFO for WARN+ERROR+INFO logs
- INFO
- // WARN for WARN+ERROR logs
- WARN
- // ERROR for ERROR only logs
- ERROR
- // NONE is used to disable logs
- NONE
-)
+var CurrentLevel = parseLevel(strings.ToUpper(env.Config.Log.Level))
-// ParseLevel returns a log.Level based on input string
-func ParseLevel(level string) Level {
- switch level {
- case "DEBUG":
- return DEBUG
- case "WARN":
- return WARN
- case "ERROR":
- return ERROR
- default:
- return INFO
- }
+func IsEnabled(level Level) bool {
+ return CurrentLevel <= level
}
-func (l Level) String() string {
- switch l {
- case DEBUG:
- return "DEBUG"
- case INFO:
- return "INFO"
- case WARN:
- return "WARN"
- case ERROR:
- return "ERROR"
- case NONE:
- return "NONE"
- default:
- return "???"
- }
+func Debug(ctx context.Context, message string) {
+ bus.Publish(ctx, &cmd.LogDebug{Message: message})
}
-// Props is a map of key:value
-type Props map[string]interface{}
+func Debugf(ctx context.Context, message string, props dto.Props) {
+ bus.Publish(ctx, &cmd.LogDebug{Message: message, Props: props})
+}
-// Value converts props into a database value
-func (p Props) Value() (driver.Value, error) {
- j, err := json.Marshal(p)
- return j, err
+func Info(ctx context.Context, message string) {
+ bus.Publish(ctx, &cmd.LogInfo{Message: message})
}
-// Merge current props with given props
-func (p Props) Merge(props Props) Props {
- new := Props{}
- if p != nil {
- for k, v := range p {
- new[k] = v
- }
- }
- if props != nil {
- for k, v := range props {
- new[k] = v
- }
- }
- return new
+func Infof(ctx context.Context, message string, props dto.Props) {
+ bus.Publish(ctx, &cmd.LogInfo{Message: message, Props: props})
}
-var placeholderFinder = regexp.MustCompile("@{.*?}")
+func Warn(ctx context.Context, message string) {
+ bus.Publish(ctx, &cmd.LogWarn{Message: message})
+}
-// Parse is used to merge props into format and return a text message
-func Parse(format string, props Props, colorize bool) string {
- if props == nil || len(props) == 0 {
- return format
- }
+func Warnf(ctx context.Context, message string, props dto.Props) {
+ bus.Publish(ctx, &cmd.LogWarn{Message: message, Props: props})
+}
- for {
- indexes := placeholderFinder.FindSubmatchIndex([]byte(format))
- if len(indexes) == 0 {
- return format
- }
+func Error(ctx context.Context, err error) {
+ bus.Publish(ctx, &cmd.LogError{Err: err})
+}
- ph := format[indexes[0]:indexes[1]]
- phContent := ph[2 : len(ph)-1]
- phSeparatorIdx := strings.Index(phContent, ":")
- value := props[phContent]
- if phSeparatorIdx >= 0 {
- phName := phContent[:phSeparatorIdx]
- phColor := phContent[phSeparatorIdx+1:]
- value = props[phName]
- if colorize {
- value = Color(phColor, value)
- }
- }
- format = fmt.Sprintf("%s%v%s", format[:indexes[0]], value, format[indexes[1]:])
- }
+func Errorf(ctx context.Context, message string, props dto.Props) {
+ bus.Publish(ctx, &cmd.LogError{Message: message, Props: props})
}
diff --git a/app/pkg/log/log_test.go b/app/pkg/log/log_test.go
index 22e1922c8..c55443c82 100644
--- a/app/pkg/log/log_test.go
+++ b/app/pkg/log/log_test.go
@@ -1,97 +1,35 @@
package log_test
import (
+ "context"
"testing"
+ "github.com/getfider/fider/app/models/dto"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/log"
)
-func TestLevel_Parse(t *testing.T) {
+func TestLog_WithProperty(t *testing.T) {
RegisterT(t)
-
- Expect(log.ParseLevel("DEBUG")).Equals(log.DEBUG)
- Expect(log.ParseLevel("INFO")).Equals(log.INFO)
- Expect(log.ParseLevel("WARN")).Equals(log.WARN)
- Expect(log.ParseLevel("ERROR")).Equals(log.ERROR)
- Expect(log.ParseLevel("NONE")).Equals(log.INFO)
- Expect(log.ParseLevel("")).Equals(log.INFO)
+ ctx := log.WithProperty(context.Background(), "Name", "Jon Snow")
+ Expect(log.GetProperty(ctx, "Name")).Equals("Jon Snow")
}
-func TestLevel_ToString(t *testing.T) {
+func TestLog_WithProperties(t *testing.T) {
RegisterT(t)
-
- Expect(log.DEBUG.String()).Equals("DEBUG")
- Expect(log.INFO.String()).Equals("INFO")
- Expect(log.WARN.String()).Equals("WARN")
- Expect(log.ERROR.String()).Equals("ERROR")
- Expect(log.DEBUG.String()).Equals("DEBUG")
- Expect(log.Level(88).String()).Equals("???")
-}
-
-func TestPropsMerge(t *testing.T) {
- RegisterT(t)
-
- Expect(log.Props{
- "Name": "John",
- }.Merge(nil)).Equals(log.Props{"Name": "John"})
-
- Expect(log.Props{
- "Name": "John",
- }.Merge(log.Props{
- "Name": "Maria",
- })).Equals(log.Props{"Name": "Maria"})
-
- Expect(log.Props(nil).Merge(log.Props{
- "Name": "Maria",
- })).Equals(log.Props{"Name": "Maria"})
-
- Expect(log.Props{
- "Name": "John",
- "DOB": "05/02/1998",
- }.Merge(log.Props{
- "Name": "Maria",
- "Age": 66,
- })).Equals(log.Props{
- "Age": 66,
- "DOB": "05/02/1998",
- "Name": "Maria",
+ ctx := log.WithProperties(context.Background(), dto.Props{
+ "Name": "Jon Snow",
+ "Age": 12,
})
-}
+ Expect(log.GetProperty(ctx, "Name")).Equals("Jon Snow")
+ Expect(log.GetProperty(ctx, "Age")).Equals(12)
-func TestParseText(t *testing.T) {
- RegisterT(t)
-
- var testCases = []struct {
- format string
- props log.Props
- colorize bool
- expected string
- }{
- {"Hello World", nil, true, "Hello World"},
- {"Hello World", log.Props{}, true, "Hello World"},
- {"Hello @{Name}", log.Props{
- "Name": "John",
- }, true, "Hello John"},
- {"My name is @{Name} and I'm @{Age} years old", log.Props{
- "Name": "John",
- "Age": 55,
- }, true, "My name is John and I'm 55 years old"},
- {"Hello @{Name}", nil, true, "Hello @{Name}"},
- {"Hello @{Name}", log.Props{"Age": 55}, true, "Hello <nil>"},
- {"Hello @{Name:blue}", log.Props{
- "Name": "John",
- }, true, "Hello \033[34mJohn\033[0m"},
- {"Hello @{Name:undefined}", log.Props{
- "Name": "John",
- }, true, "Hello John"},
- {"Hello @{Name:blue}", log.Props{
- "Name": "John",
- }, false, "Hello John"},
- }
+ ctx = log.WithProperty(ctx, "Age", 15)
+ Expect(log.GetProperty(ctx, "Name")).Equals("Jon Snow")
+ Expect(log.GetProperty(ctx, "Age")).Equals(15)
- for _, testCase := range testCases {
- text := log.Parse(testCase.format, testCase.props, testCase.colorize)
- Expect(text).Equals(testCase.expected)
- }
+ Expect(log.GetProperties(ctx)).Equals(dto.Props{
+ "Name": "Jon Snow",
+ "Age": 15,
+ })
}
diff --git a/app/pkg/log/noop/logger.go b/app/pkg/log/noop/logger.go
deleted file mode 100644
index ec3efe245..000000000
--- a/app/pkg/log/noop/logger.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package noop
-
-import (
- "github.com/getfider/fider/app/pkg/log"
-)
-
-// Logger doesn't log anything
-type Logger struct {
- enabled bool
-}
-
-// NewLogger creates a new Logger
-func NewLogger() *Logger {
- return &Logger{}
-}
-
-// Disable logs for this logger
-func (l *Logger) Disable() {
-}
-
-// Enable logs for this logger
-func (l *Logger) Enable() {
-}
-
-// SetLevel increases/decreases current log level
-func (l *Logger) SetLevel(level log.Level) {
-}
-
-// IsEnabled returns true if given level is enabled
-func (l *Logger) IsEnabled(level log.Level) bool {
- return true
-}
-
-// Debug logs a DEBUG message
-func (l *Logger) Debug(message string) {
-}
-
-// Debugf logs a DEBUG message
-func (l *Logger) Debugf(message string, props log.Props) {
-}
-
-// Info logs a INFO message
-func (l *Logger) Info(message string) {
-}
-
-// Infof logs a INFO message
-func (l *Logger) Infof(message string, props log.Props) {
-}
-
-// Warn logs a WARN message
-func (l *Logger) Warn(message string) {
-}
-
-// Warnf logs a WARN message
-func (l *Logger) Warnf(message string, props log.Props) {
-}
-
-// Error logs a ERROR message
-func (l *Logger) Error(err error) {
-}
-
-// Errorf logs a ERROR message
-func (l *Logger) Errorf(message string, props log.Props) {
-}
-
-// Write writes len(p) bytes from p to the underlying data stream.
-func (l *Logger) Write(p []byte) (int, error) {
- return 0, nil
-}
-
-// New returns a copy of current logger with empty context
-func (l *Logger) New() log.Logger {
- return NewLogger()
-}
-
-// SetProperty with given key:value into current logger context
-func (l *Logger) SetProperty(key string, value interface{}) {
-}
-
-func (l *Logger) log(level log.Level, format string, args ...interface{}) {
-}
diff --git a/app/pkg/log/parse.go b/app/pkg/log/parse.go
new file mode 100644
index 000000000..ecc0d148e
--- /dev/null
+++ b/app/pkg/log/parse.go
@@ -0,0 +1,40 @@
+package log
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/color"
+)
+
+var placeholderFinder = regexp.MustCompile("@{.*?}")
+
+// Parse is used to merge props into format and return a text message
+func Parse(format string, props dto.Props, colorize bool) string {
+ if props == nil || len(props) == 0 {
+ return format
+ }
+
+ for {
+ indexes := placeholderFinder.FindSubmatchIndex([]byte(format))
+ if len(indexes) == 0 {
+ return format
+ }
+
+ ph := format[indexes[0]:indexes[1]]
+ phContent := ph[2 : len(ph)-1]
+ phSeparatorIdx := strings.Index(phContent, ":")
+ value := props[phContent]
+ if phSeparatorIdx >= 0 {
+ phName := phContent[:phSeparatorIdx]
+ phColor := phContent[phSeparatorIdx+1:]
+ value = props[phName]
+ if colorize {
+ value = color.FromName(phColor, value)
+ }
+ }
+ format = fmt.Sprintf("%s%v%s", format[:indexes[0]], value, format[indexes[1]:])
+ }
+}
diff --git a/app/pkg/log/props.go b/app/pkg/log/props.go
new file mode 100644
index 000000000..6e2224f3e
--- /dev/null
+++ b/app/pkg/log/props.go
@@ -0,0 +1,56 @@
+package log
+
+import (
+ "context"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/dto"
+)
+
+type logCtxKey string
+
+const (
+ // PropertyKeySessionID is the session id of current logger
+ PropertyKeySessionID = "SessionID"
+ // PropertyKeyContextID is the context id of current logger
+ PropertyKeyContextID = "ContextID"
+ // PropertyKeyUserID is the user id of current logger
+ PropertyKeyUserID = "UserID"
+ // PropertyKeyTenantID is the tenant id of current logger
+ PropertyKeyTenantID = "TenantID"
+ // PropertyKeyTag is the tag of current logger
+ PropertyKeyTag = "Tag"
+)
+
+func GetProperties(ctx context.Context) dto.Props {
+ props, ok := ctx.Value(app.LogPropsCtxKey).(*dto.Props)
+ if ok {
+ return *props
+ }
+ return dto.Props{}
+}
+
+func GetProperty(ctx context.Context, key string) interface{} {
+ props := GetProperties(ctx)
+ return props[key]
+}
+
+func WithProperty(ctx context.Context, key string, value interface{}) context.Context {
+ return WithProperties(ctx, dto.Props{
+ key: value,
+ })
+}
+
+func WithProperties(ctx context.Context, kv dto.Props) context.Context {
+ props, ok := ctx.Value(app.LogPropsCtxKey).(*dto.Props)
+ if !ok {
+ props = &dto.Props{}
+ ctx = context.WithValue(ctx, app.LogPropsCtxKey, props)
+ }
+
+ for key, value := range kv {
+ (*props)[key] = value
+ }
+
+ return ctx
+}
diff --git a/app/pkg/mock/client.go b/app/pkg/mock/client.go
deleted file mode 100644
index a6e81bf24..000000000
--- a/app/pkg/mock/client.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package mock
-
-import (
- "bytes"
- "io/ioutil"
- "net/http"
-)
-
-// HTTPClient is an mocked implementation of HTTP Client
-type HTTPClient struct {
- Requests []*http.Request
-}
-
-// NewHTTPClient creates a new HTTPClient
-func NewHTTPClient() *HTTPClient {
- return &HTTPClient{
- Requests: make([]*http.Request, 0),
- }
-}
-
-// Do saves the request internally for later inspection
-func (client *HTTPClient) Do(req *http.Request) (*http.Response, error) {
- client.Requests = append(client.Requests, req)
-
- return &http.Response{
- StatusCode: http.StatusOK,
- Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
- }, nil
-}
-
-// Reset the internal request store
-func (client *HTTPClient) Reset() {
- client.Requests = make([]*http.Request, 0)
-}
diff --git a/app/pkg/mock/oauth.go b/app/pkg/mock/oauth.go
deleted file mode 100644
index 601fb83f5..000000000
--- a/app/pkg/mock/oauth.go
+++ /dev/null
@@ -1,68 +0,0 @@
-package mock
-
-import "github.com/getfider/fider/app/pkg/oauth"
-
-//OAuthService implements a mocked OAuthService
-type OAuthService struct{}
-
-//GetAuthURL returns authentication url for given provider
-func (s *OAuthService) GetAuthURL(provider, redirect, identifier string) (string, error) {
- return "http://avengers.test.fider.io/oauth/token?provider=" + provider + "&redirect=" + redirect + "|" + identifier, nil
-}
-
-//GetRawProfile returns raw JSON response from Profile API
-func (s *OAuthService) GetRawProfile(provider string, code string) (string, error) {
- return "", nil
-}
-
-//ParseRawProfile parses raw profile response into UserProfile model
-func (s *OAuthService) ParseRawProfile(provider, body string) (*oauth.UserProfile, error) {
- return nil, nil
-}
-
-//GetProfile returns user profile based on provider and code
-func (s *OAuthService) GetProfile(provider string, code string) (*oauth.UserProfile, error) {
- if provider == "facebook" && code == "123" {
- return &oauth.UserProfile{
- ID: "FB123",
- Name: "Jon Snow",
- Email: "[email protected]",
- }, nil
- }
-
- if provider == "facebook" && code == "456" {
- return &oauth.UserProfile{
- ID: "FB456",
- Name: "Some Facebook Guy",
- Email: "[email protected]",
- }, nil
- }
-
- if provider == "facebook" && code == "798" {
- return &oauth.UserProfile{
- ID: "FB798",
- Name: "Mark",
- Email: "",
- }, nil
- }
-
- if provider == "google" && code == "123" {
- return &oauth.UserProfile{
- ID: "GO123",
- Name: "Jon Snow",
- Email: "[email protected]",
- }, nil
- }
-
- return nil, nil
-}
-
-//ListActiveProviders returns a list of all providers for current tenant
-func (s *OAuthService) ListActiveProviders() ([]*oauth.ProviderOption, error) {
- return []*oauth.ProviderOption{}, nil
-}
-
-//ListAllProviders returns a list of all providers for current tenant
-func (s *OAuthService) ListAllProviders() ([]*oauth.ProviderOption, error) {
- return []*oauth.ProviderOption{}, nil
-}
diff --git a/app/pkg/mock/server.go b/app/pkg/mock/server.go
index 59b13154b..03b66caf4 100644
--- a/app/pkg/mock/server.go
+++ b/app/pkg/mock/server.go
@@ -1,35 +1,39 @@
package mock
import (
+ "context"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
- "github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/jsonq"
- "github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/web"
)
// Server is a HTTP server wrapper for testing purpose
type Server struct {
engine *web.Engine
- context web.Context
+ context *web.Context
recorder *httptest.ResponseRecorder
middleware []web.MiddlewareFunc
}
-func createServer(services *app.Services) *Server {
+func createServer() *Server {
+ bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {
+ return nil
+ })
+
settings := &models.SystemSettings{}
engine := web.New(settings)
request, _ := http.NewRequest("GET", "/", nil)
recorder := httptest.NewRecorder()
- context := engine.NewContext(recorder, request, make(web.StringMap, 0))
- context.SetServices(services)
+ context := web.NewContext(engine, request, recorder, make(web.StringMap))
return &Server{
engine: engine,
@@ -53,14 +57,12 @@ func (s *Server) Use(middleware web.MiddlewareFunc) *Server {
// OnTenant set current context tenant
func (s *Server) OnTenant(tenant *models.Tenant) *Server {
s.context.SetTenant(tenant)
- s.context.Services().SetCurrentTenant(tenant)
return s
}
// AsUser set current context user
func (s *Server) AsUser(user *models.User) *Server {
s.context.SetUser(user)
- s.context.Services().SetCurrentUser(user)
return s
}
@@ -88,12 +90,6 @@ func (s *Server) WithClientIP(clientIP string) *Server {
return s
}
-// WithClaims set current context user claims
-func (s *Server) WithClaims(claims *jwt.FiderClaims) *Server {
- s.context.SetClaims(claims)
- return s
-}
-
// WithURL set current context Request URL
func (s *Server) WithURL(fullURL string) *Server {
u, _ := url.Parse(fullURL)
diff --git a/app/pkg/mock/setup.go b/app/pkg/mock/setup.go
index a1f358a3e..c18f65d0b 100644
--- a/app/pkg/mock/setup.go
+++ b/app/pkg/mock/setup.go
@@ -3,12 +3,8 @@ package mock
import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/billing"
- "github.com/getfider/fider/app/pkg/blob/fs"
- "github.com/getfider/fider/app/pkg/email/noop"
+ "github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/oauth"
- "github.com/getfider/fider/app/storage/inmemory"
)
// DemoTenant is a mocked tenant
@@ -24,67 +20,60 @@ var JonSnow *models.User
var AryaStark *models.User
// NewSingleTenantServer creates a new multitenant test server
-func NewSingleTenantServer() (*Server, *app.Services) {
- services := createServices(false)
- server := createServer(services)
+func NewSingleTenantServer() *Server {
+ server := createServer()
env.Config.HostMode = "single"
- return server, services
+ return server
}
-// NewServer creates a new server and services for HTTP testing
-func NewServer() (*Server, *app.Services) {
- services := createServices(true)
- server := createServer(services)
+// NewServer creates a new server for HTTP testing
+func NewServer() *Server {
+ seed()
+ server := createServer()
env.Config.HostMode = "multi"
- return server, services
+ return server
}
-// NewWorker creates a new worker and services for worker testing
-func NewWorker() (*Worker, *app.Services) {
- services := createServices(true)
- worker := createWorker(services)
- return worker, services
+// NewWorker creates a new worker for worker testing
+func NewWorker() *Worker {
+ seed()
+ worker := createWorker()
+ return worker
}
-func createServices(seed bool) *app.Services {
- services := &app.Services{
- Tenants: inmemory.NewTenantStorage(),
- Users: &inmemory.UserStorage{},
- Tags: inmemory.NewTagStorage(),
- Notifications: inmemory.NewNotificationStorage(),
- Posts: inmemory.NewPostStorage(),
- OAuth: &OAuthService{},
- Emailer: noop.NewSender(),
- Blobs: fs.NewStorage(env.Path("tmp")),
- Billing: billing.NewClient(),
+func seed() {
+ DemoTenant = &models.Tenant{
+ ID: 1,
+ Name: "Demonstration",
+ Subdomain: "demo",
+ Status: enum.TenantActive,
+ }
+ AvengersTenant = &models.Tenant{
+ ID: 2,
+ Name: "Avengers",
+ Subdomain: "avengers",
+ Status: enum.TenantActive,
+ CNAME: "feedback.theavengers.com",
}
- if seed {
- DemoTenant, _ = services.Tenants.Add("Demonstration", "demo", models.TenantActive)
- AvengersTenant, _ = services.Tenants.Add("Avengers", "avengers", models.TenantActive)
- AvengersTenant.CNAME = "feedback.theavengers.com"
-
- JonSnow = &models.User{
- Name: "Jon Snow",
- Email: "[email protected]",
- Tenant: DemoTenant,
- Status: models.UserActive,
- Role: models.RoleAdministrator,
- Providers: []*models.UserProvider{
- {UID: "FB1234", Name: oauth.FacebookProvider},
- },
- }
- services.Users.Register(JonSnow)
-
- AryaStark = &models.User{
- Name: "Arya Stark",
- Email: "[email protected]",
- Tenant: DemoTenant,
- Status: models.UserActive,
- Role: models.RoleVisitor,
- }
- services.Users.Register(AryaStark)
+ JonSnow = &models.User{
+ ID: 1,
+ Name: "Jon Snow",
+ Email: "[email protected]",
+ Tenant: DemoTenant,
+ Status: enum.UserActive,
+ Role: enum.RoleAdministrator,
+ Providers: []*models.UserProvider{
+ {UID: "FB1234", Name: app.FacebookProvider},
+ },
}
- return services
+ AryaStark = &models.User{
+ ID: 2,
+ Name: "Arya Stark",
+ Email: "[email protected]",
+ Tenant: DemoTenant,
+ Status: enum.UserActive,
+ Role: enum.RoleVisitor,
+ }
}
diff --git a/app/pkg/mock/worker.go b/app/pkg/mock/worker.go
index c12ac74b4..198d7924c 100644
--- a/app/pkg/mock/worker.go
+++ b/app/pkg/mock/worker.go
@@ -1,9 +1,12 @@
package mock
import (
+ "context"
+ "net/url"
+
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/log/noop"
+ "github.com/getfider/fider/app/pkg/web"
"github.com/getfider/fider/app/pkg/worker"
)
@@ -11,14 +14,11 @@ import (
type Worker struct {
tenant *models.Tenant
user *models.User
- services *app.Services
baseURL string
}
-func createWorker(services *app.Services) *Worker {
- return &Worker{
- services: services,
- }
+func createWorker() *Worker {
+ return &Worker{}
}
// OnTenant set current context tenant
@@ -41,11 +41,22 @@ func (w *Worker) WithBaseURL(baseURL string) *Worker {
// Execute given task with current context
func (w *Worker) Execute(task worker.Task) error {
- context := worker.NewContext("0", task, nil, noop.NewLogger())
- context.SetServices(w.services)
- context.SetUser(w.user)
- context.SetTenant(w.tenant)
- context.SetBaseURL(w.baseURL)
+ task.OriginContext = context.Background()
+
+ if w.user != nil {
+ task.OriginContext = context.WithValue(task.OriginContext, app.UserCtxKey, w.user)
+ }
+
+ if w.tenant != nil {
+ task.OriginContext = context.WithValue(task.OriginContext, app.TenantCtxKey, w.tenant)
+ }
+
+ u, _ := url.Parse(w.baseURL)
+ if u != nil {
+ task.OriginContext = context.WithValue(task.OriginContext, app.RequestCtxKey, web.Request{URL: u})
+ }
+
+ context := worker.NewContext(context.Background(), "0", task)
return task.Job(context)
}
diff --git a/app/pkg/oauth/oauth.go b/app/pkg/oauth/oauth.go
deleted file mode 100644
index bdee4a6e8..000000000
--- a/app/pkg/oauth/oauth.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package oauth
-
-import (
- "errors"
-)
-
-const (
- //FacebookProvider is const for 'facebook'
- FacebookProvider = "facebook"
- //GoogleProvider is const for 'google'
- GoogleProvider = "google"
- //GitHubProvider is const for 'github'
- GitHubProvider = "github"
-)
-
-//ErrUserIDRequired is used when OAuth integration returns an empty user ID
-var ErrUserIDRequired = errors.New("UserID is required during OAuth integration")
-
-//UserProfile represents an OAuth user profile
-type UserProfile struct {
- ID string `json:"id"`
- Name string `json:"name"`
- Email string `json:"email"`
-}
-
-//ProviderOption represents an OAuth provider that can be used to authenticate
-type ProviderOption struct {
- Provider string `json:"provider"`
- DisplayName string `json:"displayName"`
- ClientID string `json:"clientID"`
- URL string `json:"url"`
- CallbackURL string `json:"callbackURL"`
- LogoBlobKey string `json:"logoBlobKey"`
- IsCustomProvider bool `json:"isCustomProvider"`
- IsEnabled bool `json:"isEnabled"`
-}
-
-//Service provides OAuth operations
-type Service interface {
- GetAuthURL(provider, redirect, identifier string) (string, error)
- GetProfile(provider string, code string) (*UserProfile, error)
- GetRawProfile(provider string, code string) (string, error)
- ParseRawProfile(provider, body string) (*UserProfile, error)
- ListActiveProviders() ([]*ProviderOption, error)
- ListAllProviders() ([]*ProviderOption, error)
-}
diff --git a/app/pkg/validate/general.go b/app/pkg/validate/general.go
index 4a8328a2d..cc654d696 100644
--- a/app/pkg/validate/general.go
+++ b/app/pkg/validate/general.go
@@ -1,13 +1,16 @@
package validate
import (
+ "context"
"fmt"
"net/url"
"regexp"
"strings"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+
"github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/storage"
)
var emailRegex = regexp.MustCompile("^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$")
@@ -45,7 +48,7 @@ func URL(rawurl string) []string {
}
//CNAME validates given cname
-func CNAME(tenants storage.Tenant, cname string) []string {
+func CNAME(ctx context.Context, cname string) []string {
cname = strings.ToLower(cname)
if !env.IsSingleHostMode() {
@@ -63,8 +66,9 @@ func CNAME(tenants storage.Tenant, cname string) []string {
return []string{fmt.Sprintf("'%s' is not a valid custom domain.", cname)}
}
- available, _ := tenants.IsCNAMEAvailable(cname)
- if !available {
+ isAvailable := &query.IsCNAMEAvailable{CNAME: cname}
+ bus.Dispatch(ctx, isAvailable)
+ if !isAvailable.Result {
return []string{"This custom domain is already in use by someone else."}
}
diff --git a/app/pkg/validate/general_test.go b/app/pkg/validate/general_test.go
index 1e0e2a1a1..09c71fac3 100644
--- a/app/pkg/validate/general_test.go
+++ b/app/pkg/validate/general_test.go
@@ -1,13 +1,14 @@
package validate_test
import (
+ "context"
"testing"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/rand"
"github.com/getfider/fider/app/pkg/validate"
- "github.com/getfider/fider/app/storage/inmemory"
)
func TestInvalidEmail(t *testing.T) {
@@ -84,13 +85,19 @@ func TestInvalidCNAME(t *testing.T) {
"test.fider.io",
"@google.com",
} {
- messages := validate.CNAME(inmemory.NewTenantStorage(), cname)
+ messages := validate.CNAME(context.Background(), cname)
Expect(len(messages) > 0).IsTrue()
}
}
func TestValidHostname(t *testing.T) {
RegisterT(t)
+
+ bus.AddHandler(func(ctx context.Context, q *query.IsCNAMEAvailable) error {
+ q.Result = true
+ return nil
+ })
+
for _, cname := range []string{
"google.com",
"feedback.fider.io",
@@ -99,27 +106,25 @@ func TestValidHostname(t *testing.T) {
"got.com",
"hi.m",
} {
- messages := validate.CNAME(inmemory.NewTenantStorage(), cname)
+ messages := validate.CNAME(context.Background(), cname)
Expect(messages).HasLen(0)
}
}
func TestValidCNAME_Availability(t *testing.T) {
RegisterT(t)
- tenants := inmemory.NewTenantStorage()
- tenant, _ := tenants.Add("Footbook", "footbook", models.TenantActive)
- tenant.CNAME = "footbook.com"
- tenant, _ = tenants.Add("Your Company", "yourcompany", models.TenantActive)
- tenant.CNAME = "fider.yourcompany.com"
- tenant, _ = tenants.Add("New York", "newyork", models.TenantActive)
- tenant.CNAME = "feedback.newyork.com"
+
+ bus.AddHandler(func(ctx context.Context, q *query.IsCNAMEAvailable) error {
+ q.Result = q.CNAME != "footbook.com" && q.CNAME != "fider.yourcompany.com" && q.CNAME != "feedback.newyork.com"
+ return nil
+ })
for _, cname := range []string{
"footbook.com",
"fider.yourcompany.com",
"feedback.newyork.com",
} {
- messages := validate.CNAME(tenants, cname)
+ messages := validate.CNAME(context.Background(), cname)
Expect(len(messages) > 0).IsTrue()
}
@@ -128,7 +133,7 @@ func TestValidCNAME_Availability(t *testing.T) {
"yourcompany.com",
"anything.com",
} {
- messages := validate.CNAME(tenants, cname)
+ messages := validate.CNAME(context.Background(), cname)
Expect(messages).HasLen(0)
}
}
diff --git a/app/pkg/validate/subdomain.go b/app/pkg/validate/subdomain.go
index 6de78438f..f34d3972c 100644
--- a/app/pkg/validate/subdomain.go
+++ b/app/pkg/validate/subdomain.go
@@ -1,18 +1,20 @@
package validate
import (
+ "context"
"fmt"
"regexp"
"strings"
- "github.com/getfider/fider/app/storage"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
)
var domainRegex = regexp.MustCompile("^[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]$")
//Subdomain validates given subdomain
-func Subdomain(tenants storage.Tenant, subdomain string) ([]string, error) {
+func Subdomain(ctx context.Context, subdomain string) ([]string, error) {
subdomain = strings.ToLower(subdomain)
if len(subdomain) <= 2 {
@@ -36,12 +38,12 @@ func Subdomain(tenants storage.Tenant, subdomain string) ([]string, error) {
return []string{fmt.Sprintf("%s is a reserved subdomain.", subdomain)}, nil
}
- available, err := tenants.IsSubdomainAvailable(subdomain)
- if err != nil {
+ isAvailable := &query.IsSubdomainAvailable{Subdomain: subdomain}
+ if err := bus.Dispatch(ctx, isAvailable); err != nil {
return nil, err
}
- if !available {
+ if !isAvailable.Result {
return []string{"This subdomain is not available anymore."}, nil
}
diff --git a/app/pkg/validate/subdomain_test.go b/app/pkg/validate/subdomain_test.go
index 4d2bfdc45..5e8637cda 100644
--- a/app/pkg/validate/subdomain_test.go
+++ b/app/pkg/validate/subdomain_test.go
@@ -1,12 +1,14 @@
package validate_test
import (
+ "context"
"testing"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/query"
+
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/validate"
- "github.com/getfider/fider/app/storage/inmemory"
)
func TestInvalidSubdomains(t *testing.T) {
@@ -23,7 +25,7 @@ func TestInvalidSubdomains(t *testing.T) {
"my+company",
"1234567890123456789012345678901234567890ABC",
} {
- messages, err := validate.Subdomain(nil, subdomain)
+ messages, err := validate.Subdomain(context.Background(), subdomain)
Expect(len(messages) > 0).IsTrue()
Expect(err).IsNil()
}
@@ -32,10 +34,10 @@ func TestInvalidSubdomains(t *testing.T) {
func TestValidSubdomains_Availability(t *testing.T) {
RegisterT(t)
- tenants := inmemory.NewTenantStorage()
- tenants.Add("Footbook", "footbook", models.TenantActive)
- tenants.Add("Your Company", "yourcompany", models.TenantActive)
- tenants.Add("New York", "newyork", models.TenantActive)
+ bus.AddHandler(func(ctx context.Context, q *query.IsSubdomainAvailable) error {
+ q.Result = q.Subdomain != "footbook" && q.Subdomain != "yourcompany" && q.Subdomain != "newyork"
+ return nil
+ })
for _, subdomain := range []string{
"footbook",
@@ -43,7 +45,7 @@ func TestValidSubdomains_Availability(t *testing.T) {
"newyork",
"NewYork",
} {
- messages, err := validate.Subdomain(tenants, subdomain)
+ messages, err := validate.Subdomain(context.Background(), subdomain)
Expect(len(messages) > 0).IsTrue()
Expect(err).IsNil()
}
@@ -52,7 +54,7 @@ func TestValidSubdomains_Availability(t *testing.T) {
"my-company",
"123-company",
} {
- messages, err := validate.Subdomain(tenants, subdomain)
+ messages, err := validate.Subdomain(context.Background(), subdomain)
Expect(messages).HasLen(0)
Expect(err).IsNil()
}
diff --git a/app/pkg/validate/validation.go b/app/pkg/validate/validation.go
index 9e1867d0e..d98f5abb6 100644
--- a/app/pkg/validate/validation.go
+++ b/app/pkg/validate/validation.go
@@ -1,14 +1,15 @@
package validate
import (
- "github.com/getfider/fider/app"
+ "context"
+
"github.com/getfider/fider/app/models"
)
// Validatable defines which models can be validated against context
type Validatable interface {
- Validate(user *models.User, services *app.Services) *Result
- IsAuthorized(user *models.User, services *app.Services) bool
+ Validate(ctx context.Context, user *models.User) *Result
+ IsAuthorized(ctx context.Context, user *models.User) bool
}
// ErrorItem holds a reference to something that went wrong
diff --git a/app/pkg/blob/autocert.go b/app/pkg/web/autocert.go
similarity index 57%
rename from app/pkg/blob/autocert.go
rename to app/pkg/web/autocert.go
index fb94b39dd..e4f44d35c 100644
--- a/app/pkg/blob/autocert.go
+++ b/app/pkg/web/autocert.go
@@ -1,9 +1,15 @@
-package blob
+package web
import (
"context"
"strings"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/services/blob"
+
"golang.org/x/crypto/acme/autocert"
)
@@ -12,44 +18,44 @@ var _ autocert.Cache = (*Cache)(nil)
// Cache provides a Blob backend to the autocert cache.
type Cache struct {
- storage Storage
}
-// NewAutoCert returns a new AutoCert cache using Blob Storage
-func NewAutoCert(storage Storage) *Cache {
- return &Cache{storage}
+// NewAutoCertCache returns a new AutoCert cache using Blob Storage
+func NewAutoCertCache() *Cache {
+ return &Cache{}
}
// Get returns a certificate data for the specified key.
// If there's no such key, Get returns ErrCacheMiss.
func (c *Cache) Get(ctx context.Context, key string) ([]byte, error) {
- b, err := c.storage.Get(c.formatKey(key))
- if err == ErrNotFound {
+ q := &query.GetBlobByKey{
+ Key: c.formatKey(key),
+ }
+ err := bus.Dispatch(ctx, q)
+ if errors.Cause(err) == blob.ErrNotFound {
return nil, autocert.ErrCacheMiss
}
if err != nil {
return nil, err
}
- return b.Object, nil
+ return q.Result.Content, nil
}
// Put stores the data in the cache under the specified key.
func (c *Cache) Put(ctx context.Context, key string, data []byte) error {
- err := c.storage.Put(c.formatKey(key), data, "application/x-pem-file")
- if err != nil {
- return err
- }
- return nil
+ return bus.Dispatch(ctx, &cmd.StoreBlob{
+ Key: c.formatKey(key),
+ Content: data,
+ ContentType: "application/x-pem-file",
+ })
}
// Delete removes a certificate data from the cache under the specified key.
// If there's no such key in the cache, Delete returns nil.
func (c *Cache) Delete(ctx context.Context, key string) error {
- err := c.storage.Delete(c.formatKey(key))
- if err != nil {
- return err
- }
- return nil
+ return bus.Dispatch(ctx, &cmd.DeleteBlob{
+ Key: c.formatKey(key),
+ })
}
func (c *Cache) formatKey(key string) string {
diff --git a/app/pkg/web/autocert_test.go b/app/pkg/web/autocert_test.go
new file mode 100644
index 000000000..911af26fb
--- /dev/null
+++ b/app/pkg/web/autocert_test.go
@@ -0,0 +1,29 @@
+package web
+
+import (
+ "crypto/tls"
+ "testing"
+
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/services/blob/fs"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+)
+
+func Test_UseAutoCert(t *testing.T) {
+ RegisterT(t)
+ bus.Init(fs.Service{})
+
+ manager, err := NewCertificateManager("", "")
+ Expect(err).IsNil()
+
+ invalidServerNames := []string{"ideas.app.com", "feedback.mysite.com"}
+
+ for _, serverName := range invalidServerNames {
+ cert, err := manager.GetCertificate(&tls.ClientHelloInfo{
+ ServerName: serverName,
+ })
+ Expect(err.Error()).ContainsSubstring(`acme/autocert: unable to authorize "` + serverName + `"; challenge "tls-alpn-01" failed with error: acme: authorization error`)
+ Expect(cert).IsNil()
+ }
+}
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.go
index 1795c5787..56a95b993 100644
--- a/app/pkg/web/context.go
+++ b/app/pkg/web/context.go
@@ -2,28 +2,32 @@ package web
import (
"bytes"
+ "context"
"encoding/json"
"fmt"
"io"
- "io/ioutil"
"net/http"
"net/url"
"strconv"
"time"
+ "github.com/getfider/fider/app/pkg/dbx"
+
"strings"
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/blob"
- "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/log"
+ "github.com/getfider/fider/app/pkg/rand"
"github.com/getfider/fider/app/pkg/validate"
"github.com/getfider/fider/app/pkg/worker"
+ "github.com/getfider/fider/app/services/blob"
)
// Map defines a generic map of type `map[string]interface{}`
@@ -61,71 +65,83 @@ const CookieAuthName = "auth"
// CookieSignUpAuthName is the name of the cookie that holds the temporary Authentication Token
const CookieSignUpAuthName = "__signup_auth"
-var (
- prefixKey = "__CTX_"
- tenantContextKey = prefixKey + "TENANT"
- userContextKey = prefixKey + "USER"
- claimsContextKey = prefixKey + "CLAIMS"
- transactionContextKey = prefixKey + "TRANSACTION"
- servicesContextKey = prefixKey + "SERVICES"
- tasksContextKey = prefixKey + "TASKS"
-)
-
//Context shared between http pipeline
type Context struct {
- id string
- sessionID string
+ context.Context
Response http.ResponseWriter
Request Request
+ id string
+ sessionID string
engine *Engine
- logger log.Logger
params StringMap
- store Map
- worker worker.Worker
+ tasks []worker.Task
+}
+
+//NewContext creates a new web Context
+func NewContext(engine *Engine, req *http.Request, res http.ResponseWriter, params StringMap) *Context {
+ contextID := rand.String(32)
+
+ wrappedRequest := WrapRequest(req)
+
+ ctx := context.WithValue(req.Context(), app.RequestCtxKey, wrappedRequest)
+
+ ctx = log.WithProperties(ctx, dto.Props{
+ log.PropertyKeyContextID: contextID,
+ log.PropertyKeyTag: "WEB",
+ })
+
+ return &Context{
+ Context: ctx,
+ id: contextID,
+ engine: engine,
+ Request: wrappedRequest,
+ Response: res,
+ params: params,
+ tasks: make([]worker.Task, 0),
+ }
}
//Engine returns main HTTP engine
-func (ctx *Context) Engine() *Engine {
- return ctx.engine
+func (c *Context) Engine() *Engine {
+ return c.engine
}
//SessionID returns the current session ID
-func (ctx *Context) SessionID() string {
- return ctx.sessionID
+func (c *Context) SessionID() string {
+ return c.sessionID
}
//SetSessionID sets the session ID on current context
-func (ctx *Context) SetSessionID(id string) {
- ctx.sessionID = id
- ctx.logger.SetProperty(log.PropertyKeySessionID, id)
+func (c *Context) SetSessionID(id string) {
+ c.sessionID = id
+ c.Context = log.WithProperty(c.Context, log.PropertyKeySessionID, id)
}
//ContextID returns the unique id for this context
-func (ctx *Context) ContextID() string {
- return ctx.id
+func (c *Context) ContextID() string {
+ return c.id
}
//Commit everything that is pending on current context
-func (ctx *Context) Commit() error {
- if trx := ctx.ActiveTransaction(); trx != nil {
+func (c *Context) Commit() error {
+ trx, ok := c.Value(app.TransactionCtxKey).(*dbx.Trx)
+ if ok && trx != nil {
if err := trx.Commit(); err != nil {
return err
}
}
- tasks, ok := ctx.Get(tasksContextKey).([]worker.Task)
- if ok {
- for _, task := range tasks {
- ctx.worker.Enqueue(task)
- }
+ for _, task := range c.tasks {
+ c.engine.worker.Enqueue(task)
}
return nil
}
//Rollback everything that is pending on current context
-func (ctx *Context) Rollback() error {
- if trx := ctx.ActiveTransaction(); trx != nil {
+func (c *Context) Rollback() error {
+ trx, ok := c.Value(app.TransactionCtxKey).(*dbx.Trx)
+ if ok && trx != nil {
return trx.Rollback()
}
@@ -133,33 +149,14 @@ func (ctx *Context) Rollback() error {
}
//Enqueue given task to be processed in background
-func (ctx *Context) Enqueue(task worker.Task) {
- wrap := func(c *Context) worker.Job {
- return func(wc *worker.Context) error {
- wc.SetUser(c.User())
- wc.SetTenant(c.Tenant())
- wc.SetBaseURL(c.BaseURL())
- wc.SetLogoURL(c.LogoURL())
- wc.SetAssetsBaseURL(c.TenantAssetsURL(""))
- return task.Job(wc)
- }
- }
-
- tasks, ok := ctx.Get(tasksContextKey).([]worker.Task)
- if !ok {
- tasks = make([]worker.Task, 0)
- }
-
- ctx.Set(tasksContextKey, append(tasks, worker.Task{
- OriginSessionID: ctx.SessionID(),
- Name: task.Name,
- Job: wrap(ctx),
- }))
+func (c *Context) Enqueue(task worker.Task) {
+ task.OriginContext = c
+ c.tasks = append(c.tasks, task)
}
//Tenant returns current tenant
-func (ctx *Context) Tenant() *models.Tenant {
- tenant, ok := ctx.Get(tenantContextKey).(*models.Tenant)
+func (c *Context) Tenant() *models.Tenant {
+ tenant, ok := c.Value(app.TenantCtxKey).(*models.Tenant)
if ok {
return tenant
}
@@ -167,19 +164,16 @@ func (ctx *Context) Tenant() *models.Tenant {
}
//SetTenant update HTTP context with current tenant
-func (ctx *Context) SetTenant(tenant *models.Tenant) {
+func (c *Context) SetTenant(tenant *models.Tenant) {
if tenant != nil {
- ctx.logger.SetProperty(log.PropertyKeyTenantID, tenant.ID)
- }
- if ctx.Services() != nil {
- ctx.Services().SetCurrentTenant(tenant)
+ c.Context = log.WithProperty(c.Context, log.PropertyKeyTenantID, tenant.ID)
}
- ctx.Set(tenantContextKey, tenant)
+ c.Set(app.TenantCtxKey, tenant)
}
//Bind context values into given model
-func (ctx *Context) Bind(i interface{}) error {
- err := ctx.engine.binder.Bind(i, ctx)
+func (c *Context) Bind(i interface{}) error {
+ err := c.engine.binder.Bind(i, c)
if err != nil {
return errors.Wrap(err, "failed to bind request to model")
}
@@ -187,76 +181,76 @@ func (ctx *Context) Bind(i interface{}) error {
}
//BindTo context values into given model
-func (ctx *Context) BindTo(i actions.Actionable) *validate.Result {
- err := ctx.engine.binder.Bind(i.Initialize(), ctx)
+func (c *Context) BindTo(i actions.Actionable) *validate.Result {
+ err := c.engine.binder.Bind(i.Initialize(), c)
if err != nil {
if err == ErrContentTypeNotAllowed {
return validate.Failed(err.Error())
}
return validate.Error(errors.Wrap(err, "failed to bind request to action"))
}
- if !i.IsAuthorized(ctx.User(), ctx.Services()) {
+ if !i.IsAuthorized(c, c.User()) {
return validate.Unauthorized()
}
- return i.Validate(ctx.User(), ctx.Services())
-}
-
-//Logger returns current logger
-func (ctx *Context) Logger() log.Logger {
- return ctx.logger
+ return i.Validate(c, c.User())
}
//IsAuthenticated returns true if user is authenticated
-func (ctx *Context) IsAuthenticated() bool {
- return ctx.Get(userContextKey) != nil
+func (c *Context) IsAuthenticated() bool {
+ return c.Value(app.UserCtxKey) != nil
}
//IsAjax returns true if request is AJAX
-func (ctx *Context) IsAjax() bool {
- accept := ctx.Request.GetHeader("Accept")
- contentType := ctx.Request.GetHeader("Content-Type")
+func (c *Context) IsAjax() bool {
+ accept := c.Request.GetHeader("Accept")
+ contentType := c.Request.GetHeader("Content-Type")
return strings.Contains(accept, JSONContentType) || strings.Contains(contentType, JSONContentType)
}
//Unauthorized returns a 403 response
-func (ctx *Context) Unauthorized() error {
- return ctx.Render(http.StatusForbidden, "403.html", Props{
+func (c *Context) Unauthorized() error {
+ return c.Render(http.StatusForbidden, "403.html", Props{
Title: "Not Authorized",
Description: "You are not authorized to view this page.",
})
}
//NotFound returns a 404 page
-func (ctx *Context) NotFound() error {
- return ctx.Render(http.StatusNotFound, "404.html", Props{
+func (c *Context) NotFound() error {
+ return c.Render(http.StatusNotFound, "404.html", Props{
Title: "Page not found",
Description: "The link you clicked may be broken or the page may have been removed.",
})
}
//Gone returns a 410 page
-func (ctx *Context) Gone() error {
- return ctx.Render(http.StatusGone, "410.html", Props{
+func (c *Context) Gone() error {
+ return c.Render(http.StatusGone, "410.html", Props{
Title: "Expired",
Description: "The link you clicked has expired.",
})
}
//Failure returns a 500 page
-func (ctx *Context) Failure(err error) error {
+func (c *Context) Failure(err error) error {
err = errors.StackN(err, 1)
cause := errors.Cause(err)
+
+ if cause == context.Canceled {
+ return nil
+ }
+
if cause == app.ErrNotFound || cause == blob.ErrNotFound {
- return ctx.NotFound()
+ return c.NotFound()
}
- ctx.Logger().Errorf(err.Error(), log.Props{
- "Body": ctx.Request.Body,
- "HttpMethod": ctx.Request.Method,
- "URL": ctx.Request.URL.String(),
+ log.Errorf(c, err.Error(), dto.Props{
+ "Body": c.Request.Body,
+ "HttpMethod": c.Request.Method,
+ "URL": c.Request.URL.String(),
})
- ctx.Render(http.StatusInternalServerError, "500.html", Props{
+ c.Render(http.StatusInternalServerError, "500.html", Props{
Title: "Shoot! Well, this is unexpected…",
Description: "An error has occurred and we're working to fix the problem!",
})
@@ -264,111 +258,96 @@ func (ctx *Context) Failure(err error) error {
}
//HandleValidation handles given validation result property to return 400 or 500
-func (ctx *Context) HandleValidation(result *validate.Result) error {
+func (c *Context) HandleValidation(result *validate.Result) error {
if result.Err != nil {
- return ctx.Failure(result.Err)
+ return c.Failure(result.Err)
}
if !result.Authorized {
- return ctx.Unauthorized()
+ return c.Unauthorized()
}
- return ctx.BadRequest(Map{
+ return c.BadRequest(Map{
"errors": result.Errors,
})
}
//Attachment returns an attached file
-func (ctx *Context) Attachment(fileName, contentType string, file []byte) error {
- ctx.Response.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", fileName))
+func (c *Context) Attachment(fileName, contentType string, file []byte) error {
+ c.Response.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", fileName))
- return ctx.Blob(http.StatusOK, contentType, file)
+ return c.Blob(http.StatusOK, contentType, file)
}
//Ok returns 200 OK with JSON result
-func (ctx *Context) Ok(data interface{}) error {
- return ctx.JSON(http.StatusOK, data)
+func (c *Context) Ok(data interface{}) error {
+ return c.JSON(http.StatusOK, data)
}
//BadRequest returns 400 BadRequest with JSON result
-func (ctx *Context) BadRequest(dict Map) error {
- return ctx.JSON(http.StatusBadRequest, dict)
+func (c *Context) BadRequest(dict Map) error {
+ return c.JSON(http.StatusBadRequest, dict)
}
//Page returns a page with given variables
-func (ctx *Context) Page(props Props) error {
- if len(env.Config.Rendergun.URL) > 0 && ctx.Request.IsCrawler() {
+func (c *Context) Page(props Props) error {
+ if len(env.Config.Rendergun.URL) > 0 && c.Request.IsCrawler() {
html := new(bytes.Buffer)
- ctx.engine.renderer.Render(html, "index.html", props, ctx)
- return ctx.prerender(http.StatusOK, html)
+ c.engine.renderer.Render(html, http.StatusOK, "index.html", props, c)
+ return c.prerender(http.StatusOK, html)
}
- return ctx.Render(http.StatusOK, "index.html", props)
+ return c.Render(http.StatusOK, "index.html", props)
}
// Render renders a template with data and sends a text/html response with status
-func (ctx *Context) Render(code int, template string, props Props) error {
- if ctx.IsAjax() {
- return ctx.JSON(code, Map{})
+func (c *Context) Render(code int, template string, props Props) error {
+ if c.IsAjax() {
+ return c.JSON(code, Map{})
}
buf := new(bytes.Buffer)
- ctx.engine.renderer.Render(buf, template, props, ctx)
+ c.engine.renderer.Render(buf, code, template, props, c)
- return ctx.Blob(code, UTF8HTMLContentType, buf.Bytes())
+ return c.Blob(code, UTF8HTMLContentType, buf.Bytes())
}
-func (ctx *Context) prerender(code int, html io.Reader) error {
- renderURL := fmt.Sprintf("%s/render?url=%s", env.Config.Rendergun.URL, ctx.Request.URL.String())
- req, _ := http.NewRequest("POST", renderURL, html)
- req.Header.Set("Content-Type", "text/html")
- req.Header.Set("x-rendergun-wait-until", "networkidle0")
- req.Header.Set("x-rendergun-block-ads", "true")
- req.Header.Set("x-rendergun-abort-request", "assets\\/css\\/(common|vendor|main)\\.")
-
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- ctx.Logger().Error(errors.Wrap(err, "failed to execute rendergun"))
- return ctx.TryAgainLater(24 * time.Hour)
+func (c *Context) prerender(code int, html io.Reader) error {
+ req := &cmd.HTTPRequest{
+ Method: "POST",
+ URL: fmt.Sprintf("%s/render?url=%s", env.Config.Rendergun.URL, c.Request.URL.String()),
+ Body: html,
+ Headers: map[string]string{
+ "Content-Type": "text/html",
+ "x-rendergun-wait-until": "networkidle0",
+ "x-rendergun-block-ads": "true",
+ "x-rendergun-abort-request": "assets\\/css\\/(common|vendor|main)\\.",
+ },
}
- defer resp.Body.Close()
- prerendered, err := ioutil.ReadAll(resp.Body)
+ err := bus.Dispatch(c, req)
if err != nil {
- ctx.Logger().Error(errors.Wrap(err, "failed to copy response from rendergun to output"))
- return ctx.TryAgainLater(24 * time.Hour)
+ log.Error(c, errors.Wrap(err, "failed to execute rendergun"))
+ return c.TryAgainLater(24 * time.Hour)
}
- return ctx.Blob(code, UTF8HTMLContentType, prerendered)
+
+ return c.Blob(code, UTF8HTMLContentType, req.ResponseBody)
}
//TryAgainLater returns a service unavailable response with Retry-After header
-func (ctx *Context) TryAgainLater(d time.Duration) error {
- ctx.Response.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
- ctx.Response.Header().Set("Retry-After", fmt.Sprintf("%.0f", d.Seconds()))
- return ctx.NoContent(http.StatusServiceUnavailable)
+func (c *Context) TryAgainLater(d time.Duration) error {
+ c.Response.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
+ c.Response.Header().Set("Retry-After", fmt.Sprintf("%.0f", d.Seconds()))
+ return c.NoContent(http.StatusServiceUnavailable)
}
//AddParam add a single param to route parameters list
-func (ctx *Context) AddParam(name, value string) {
- ctx.params[name] = value
-}
-
-//Claims returns current user claims
-func (ctx *Context) Claims() *jwt.FiderClaims {
- claims, ok := ctx.Get(claimsContextKey).(*jwt.FiderClaims)
- if ok {
- return claims
- }
- return nil
-}
-
-//SetClaims update HTTP context with current user claims
-func (ctx *Context) SetClaims(claims *jwt.FiderClaims) {
- ctx.Set(claimsContextKey, claims)
+func (c *Context) AddParam(name, value string) {
+ c.params[name] = value
}
//User returns authenticated user
-func (ctx *Context) User() *models.User {
- user, ok := ctx.Get(userContextKey).(*models.User)
+func (c *Context) User() *models.User {
+ user, ok := c.Value(app.UserCtxKey).(*models.User)
if ok {
return user
}
@@ -376,105 +355,52 @@ func (ctx *Context) User() *models.User {
}
//SetUser update HTTP context with current user
-func (ctx *Context) SetUser(user *models.User) {
+func (c *Context) SetUser(user *models.User) {
if user != nil {
- ctx.logger.SetProperty(log.PropertyKeyUserID, user.ID)
- }
- if ctx.Services() != nil {
- ctx.Services().SetCurrentUser(user)
- }
- ctx.Set(userContextKey, user)
-}
-
-//Services returns current app.Services from context
-func (ctx *Context) Services() *app.Services {
- svc, ok := ctx.Get(servicesContextKey).(*app.Services)
- if ok {
- return svc
+ c.Context = log.WithProperty(c.Context, log.PropertyKeyUserID, user.ID)
}
- return nil
+ c.Set(app.UserCtxKey, user)
}
//AddCookie adds a cookie
-func (ctx *Context) AddCookie(name, value string, expires time.Time) *http.Cookie {
+func (c *Context) AddCookie(name, value string, expires time.Time) *http.Cookie {
cookie := &http.Cookie{
Name: name,
Value: value,
HttpOnly: true,
Path: "/",
Expires: expires,
- Secure: ctx.Request.IsSecure,
+ Secure: c.Request.IsSecure,
}
- http.SetCookie(ctx.Response, cookie)
+ http.SetCookie(c.Response, cookie)
return cookie
}
//RemoveCookie removes a cookie
-func (ctx *Context) RemoveCookie(name string) {
- http.SetCookie(ctx.Response, &http.Cookie{
+func (c *Context) RemoveCookie(name string) {
+ http.SetCookie(c.Response, &http.Cookie{
Name: name,
Path: "/",
HttpOnly: true,
MaxAge: -1,
Expires: time.Now().Add(-100 * time.Hour),
- Secure: ctx.Request.IsSecure,
+ Secure: c.Request.IsSecure,
})
}
-//SetServices update current context with app.Services
-func (ctx *Context) SetServices(services *app.Services) {
- ctx.Set(servicesContextKey, services)
-}
-
-//SetActiveTransaction adds transaction to context
-func (ctx *Context) SetActiveTransaction(trx *dbx.Trx) {
- ctx.Set(transactionContextKey, trx)
-}
-
-//ActiveTransaction returns current active Database transaction
-func (ctx *Context) ActiveTransaction() *dbx.Trx {
- return ctx.Get(transactionContextKey).(*dbx.Trx)
-}
-
//BaseURL returns base URL
-func (ctx *Context) BaseURL() string {
- address := ctx.Request.URL.Scheme + "://" + ctx.Request.URL.Hostname()
-
- if ctx.Request.URL.Port() != "" {
- address += ":" + ctx.Request.URL.Port()
- }
-
- return address
-}
-
-//TenantBaseURL returns base URL for a given tenant
-func (ctx *Context) TenantBaseURL(tenant *models.Tenant) string {
- if env.IsSingleHostMode() {
- return ctx.BaseURL()
- }
-
- address := ctx.Request.URL.Scheme + "://"
- if tenant.CNAME != "" {
- address += tenant.CNAME
- } else {
- address += tenant.Subdomain + env.MultiTenantDomain()
- }
-
- if ctx.Request.URL.Port() != "" {
- address += ":" + ctx.Request.URL.Port()
- }
-
- return address
+func (c *Context) BaseURL() string {
+ return c.Request.BaseURL()
}
//QueryParam returns querystring parameter for given key
-func (ctx *Context) QueryParam(key string) string {
- return ctx.Request.URL.Query().Get(key)
+func (c *Context) QueryParam(key string) string {
+ return c.Request.URL.Query().Get(key)
}
//QueryParamAsInt returns querystring parameter for given key
-func (ctx *Context) QueryParamAsInt(key string) (int, error) {
- value := ctx.QueryParam(key)
+func (c *Context) QueryParamAsInt(key string) (int, error) {
+ value := c.QueryParam(key)
if value == "" {
return 0, nil
}
@@ -486,8 +412,8 @@ func (ctx *Context) QueryParamAsInt(key string) (int, error) {
}
//QueryParamAsArray returns querystring parameter for given key as an array
-func (ctx *Context) QueryParamAsArray(key string) []string {
- param := ctx.QueryParam(key)
+func (c *Context) QueryParamAsArray(key string) []string {
+ param := c.QueryParam(key)
if param != "" {
return strings.Split(param, ",")
}
@@ -495,16 +421,16 @@ func (ctx *Context) QueryParamAsArray(key string) []string {
}
//Param returns parameter as string
-func (ctx *Context) Param(name string) string {
- if ctx.params == nil {
+func (c *Context) Param(name string) string {
+ if c.params == nil {
return ""
}
- return strings.TrimPrefix(ctx.params[name], "/")
+ return strings.TrimPrefix(c.params[name], "/")
}
//ParamAsInt returns parameter as int
-func (ctx *Context) ParamAsInt(name string) (int, error) {
- value := ctx.Param(name)
+func (c *Context) ParamAsInt(name string) (int, error) {
+ value := c.Param(name)
intValue, err := strconv.Atoi(value)
if err != nil {
return 0, errors.Wrap(err, "failed to parse %s to integer", value)
@@ -512,133 +438,170 @@ func (ctx *Context) ParamAsInt(name string) (int, error) {
return intValue, nil
}
-// Get retrieves data from the context.
-func (ctx *Context) Get(key string) interface{} {
- return ctx.store[key]
-}
-
// Set saves data in the context.
-func (ctx *Context) Set(key string, val interface{}) {
- if ctx.store == nil {
- ctx.store = make(Map)
- }
- ctx.store[key] = val
+func (c *Context) Set(key interface{}, val interface{}) {
+ c.Context = context.WithValue(c.Context, key, val)
}
// String returns a text response with status code.
-func (ctx *Context) String(code int, text string) error {
- return ctx.Blob(code, UTF8PlainContentType, []byte(text))
+func (c *Context) String(code int, text string) error {
+ return c.Blob(code, UTF8PlainContentType, []byte(text))
}
// XML returns a XML response with status code.
-func (ctx *Context) XML(code int, text string) error {
- return ctx.Blob(code, UTF8XMLContentType, []byte(text))
+func (c *Context) XML(code int, text string) error {
+ return c.Blob(code, UTF8XMLContentType, []byte(text))
}
// JSON returns a JSON response with status code.
-func (ctx *Context) JSON(code int, i interface{}) error {
+func (c *Context) JSON(code int, i interface{}) error {
b, err := json.Marshal(i)
if err != nil {
return errors.Wrap(err, "failed to marshal response to JSON")
}
- return ctx.Blob(code, UTF8JSONContentType, b)
+ return c.Blob(code, UTF8JSONContentType, b)
}
// Image sends an image blob response with status code and content type.
-func (ctx *Context) Image(contentType string, b []byte) error {
+func (c *Context) Image(contentType string, b []byte) error {
if !strings.HasPrefix(contentType, "image/") {
- return ctx.Failure(errors.New("'%s' is not an image", ctx.Request.URL.String()))
+ return c.Failure(errors.New("'%s' is not an image", c.Request.URL.String()))
}
- return ctx.Blob(http.StatusOK, contentType, b)
+ return c.Blob(http.StatusOK, contentType, b)
}
// Blob sends a blob response with status code and content type.
-func (ctx *Context) Blob(code int, contentType string, b []byte) error {
- ctx.Response.Header().Set("Content-Type", contentType)
- ctx.Response.WriteHeader(code)
- _, err := ctx.Response.Write(b)
+func (c *Context) Blob(code int, contentType string, b []byte) error {
+ c.Response.Header().Set("Content-Type", contentType)
+ c.Response.WriteHeader(code)
+ _, err := c.Response.Write(b)
return err
}
// NoContent sends a response with no body and a status code.
-func (ctx *Context) NoContent(code int) error {
- ctx.Response.WriteHeader(code)
+func (c *Context) NoContent(code int) error {
+ c.Response.WriteHeader(code)
return nil
}
// Redirect the request to a provided URL
-func (ctx *Context) Redirect(url string) error {
- ctx.Response.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
- ctx.Response.Header().Set("Location", url)
- ctx.Response.WriteHeader(http.StatusTemporaryRedirect)
+func (c *Context) Redirect(url string) error {
+ c.Response.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
+ c.Response.Header().Set("Location", url)
+ c.Response.WriteHeader(http.StatusTemporaryRedirect)
return nil
}
// PermanentRedirect the request to a provided URL
-func (ctx *Context) PermanentRedirect(url string) error {
- ctx.Response.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
- ctx.Response.Header().Set("Location", url)
- ctx.Response.WriteHeader(http.StatusMovedPermanently)
+func (c *Context) PermanentRedirect(url string) error {
+ c.Response.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
+ c.Response.Header().Set("Location", url)
+ c.Response.WriteHeader(http.StatusMovedPermanently)
return nil
}
+// SetCanonicalURL sets the canonical link on the HTTP Response Headers
+func (c *Context) SetCanonicalURL(rawurl string) {
+ u, err := url.Parse(rawurl)
+ if err == nil {
+ if u.Host == "" {
+ baseURL, ok := c.Value("Canonical-BaseURL").(string)
+ if !ok {
+ baseURL = c.BaseURL()
+ }
+ if len(rawurl) > 0 && rawurl[0] != '/' {
+ rawurl = "/" + rawurl
+ }
+ rawurl = baseURL + rawurl
+ } else {
+ c.Set("Canonical-BaseURL", u.Scheme+"://"+u.Host)
+ }
+
+ c.Set("Canonical-URL", rawurl)
+ }
+}
+
// GlobalAssetsURL return the full URL to a globally shared static asset
-func (ctx *Context) GlobalAssetsURL(path string, a ...interface{}) string {
+func GlobalAssetsURL(ctx context.Context, path string, a ...interface{}) string {
+ request := ctx.Value(app.RequestCtxKey).(Request)
path = fmt.Sprintf(path, a...)
if env.Config.CDN.Host != "" {
if env.IsSingleHostMode() {
- return ctx.Request.URL.Scheme + "://" + env.Config.CDN.Host + path
+ return request.URL.Scheme + "://" + env.Config.CDN.Host + path
}
- return ctx.Request.URL.Scheme + "://cdn." + env.Config.CDN.Host + path
+ return request.URL.Scheme + "://cdn." + env.Config.CDN.Host + path
}
- return ctx.BaseURL() + path
+ return request.BaseURL() + path
+}
+
+//TenantBaseURL returns base URL for a given tenant
+func TenantBaseURL(ctx context.Context, tenant *models.Tenant) string {
+ request := ctx.Value(app.RequestCtxKey).(Request)
+
+ if env.IsSingleHostMode() {
+ return request.BaseURL()
+ }
+
+ address := request.URL.Scheme + "://"
+ if tenant.CNAME != "" {
+ address += tenant.CNAME
+ } else {
+ address += tenant.Subdomain + env.MultiTenantDomain()
+ }
+
+ if request.URL.Port() != "" {
+ address += ":" + request.URL.Port()
+ }
+
+ return address
}
// TenantAssetsURL return the full URL to a tenant-specific static asset
-func (ctx *Context) TenantAssetsURL(path string, a ...interface{}) string {
+func TenantAssetsURL(ctx context.Context, path string, a ...interface{}) string {
+ request := ctx.Value(app.RequestCtxKey).(Request)
+ tenant, hasTenant := ctx.Value(app.TenantCtxKey).(*models.Tenant)
path = fmt.Sprintf(path, a...)
- if env.Config.CDN.Host != "" && ctx.Tenant() != nil {
+ if env.Config.CDN.Host != "" && hasTenant {
if env.IsSingleHostMode() {
- return ctx.Request.URL.Scheme + "://" + env.Config.CDN.Host + path
+ return request.URL.Scheme + "://" + env.Config.CDN.Host + path
}
- return ctx.Request.URL.Scheme + "://" + ctx.Tenant().Subdomain + "." + env.Config.CDN.Host + path
+ return request.URL.Scheme + "://" + tenant.Subdomain + "." + env.Config.CDN.Host + path
}
- return ctx.BaseURL() + path
+ return request.BaseURL() + path
}
// LogoURL return the full URL to the tenant-specific logo URL
-func (ctx *Context) LogoURL() string {
- if ctx.Tenant() != nil && ctx.Tenant().LogoBlobKey != "" {
- return ctx.TenantAssetsURL("/images/%s?size=200", ctx.Tenant().LogoBlobKey)
+func LogoURL(ctx context.Context) string {
+ tenant, hasTenant := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ if hasTenant && tenant.LogoBlobKey != "" {
+ return TenantAssetsURL(ctx, "/images/%s?size=200", tenant.LogoBlobKey)
}
return "https://getfider.com/images/logo-100x100.png"
}
-// FaviconURL return the full URL to the tenant-specific favicon URL
-func (ctx *Context) FaviconURL() string {
- if ctx.Tenant() != nil && ctx.Tenant().LogoBlobKey != "" {
- return ctx.TenantAssetsURL("/favicon/%s", ctx.Tenant().LogoBlobKey)
+// BaseURL return the base URL from given context
+func BaseURL(ctx context.Context) string {
+ request, ok := ctx.Value(app.RequestCtxKey).(Request)
+ if ok {
+ return request.BaseURL()
}
- return ctx.GlobalAssetsURL("/favicon")
+ return ""
}
-// SetCanonicalURL sets the canonical link on the HTTP Response Headers
-func (ctx *Context) SetCanonicalURL(rawurl string) {
- u, err := url.Parse(rawurl)
- if err == nil {
- if u.Host == "" {
- baseURL, ok := ctx.Get("Canonical-BaseURL").(string)
- if !ok {
- baseURL = ctx.BaseURL()
- }
- if len(rawurl) > 0 && rawurl[0] != '/' {
- rawurl = "/" + rawurl
- }
- rawurl = baseURL + rawurl
- } else {
- ctx.Set("Canonical-BaseURL", u.Scheme+"://"+u.Host)
- }
+// OAuthBaseURL returns the OAuth base URL used for host-wide OAuth authentication
+// For Single Tenant HostMode, BaseURL is the current BaseURL
+// For Multi Tenant HostMode, BaseURL is //login.{HOST_DOMAIN}
+func OAuthBaseURL(ctx context.Context) string {
+ request := ctx.Value(app.RequestCtxKey).(Request)
+
+ if env.IsSingleHostMode() {
+ return BaseURL(ctx)
+ }
- ctx.Set("Canonical-URL", rawurl)
+ oauthBaseURL := request.URL.Scheme + "://login" + env.MultiTenantDomain()
+ port := request.URL.Port()
+ if port != "" {
+ oauthBaseURL += ":" + port
}
+ return oauthBaseURL
}
diff --git a/app/pkg/web/context_test.go b/app/pkg/web/context_test.go
index b6c572e06..75e04a966 100644
--- a/app/pkg/web/context_test.go
+++ b/app/pkg/web/context_test.go
@@ -32,8 +32,7 @@ func newGetContext(rawurl string, headers map[string]string) *web.Context {
}
}
- ctx := e.NewContext(res, req, nil)
- return &ctx
+ return web.NewContext(e, req, res, nil)
}
func newBodyContext(method string, params web.StringMap, body, contentType string) *web.Context {
@@ -42,8 +41,7 @@ func newBodyContext(method string, params web.StringMap, body, contentType strin
req := httptest.NewRequest(method, "/some/resource", strings.NewReader(body))
req.Host = "demo.test.fider.io:3000"
req.Header.Set("Content-Type", contentType)
- ctx := e.NewContext(res, req, params)
- return &ctx
+ return web.NewContext(e, req, res, params)
}
func TestContextID(t *testing.T) {
@@ -97,7 +95,7 @@ func TestTenantURL(t *testing.T) {
ID: 1,
Subdomain: "theavengers",
}
- Expect(ctx.TenantBaseURL(tenant)).Equals("http://theavengers.test.fider.io:3000")
+ Expect(web.TenantBaseURL(ctx, tenant)).Equals("http://theavengers.test.fider.io:3000")
}
func TestTenantURL_WithCNAME(t *testing.T) {
@@ -109,7 +107,7 @@ func TestTenantURL_WithCNAME(t *testing.T) {
Subdomain: "theavengers",
CNAME: "feedback.theavengers.com",
}
- Expect(ctx.TenantBaseURL(tenant)).Equals("http://feedback.theavengers.com:3000")
+ Expect(web.TenantBaseURL(ctx, tenant)).Equals("http://feedback.theavengers.com:3000")
}
func TestTenantURL_SingleHostMode(t *testing.T) {
@@ -121,7 +119,7 @@ func TestTenantURL_SingleHostMode(t *testing.T) {
ID: 1,
Subdomain: "theavengers",
}
- Expect(ctx.TenantBaseURL(tenant)).Equals("http://demo.test.fider.io:3000")
+ Expect(web.TenantBaseURL(ctx, tenant)).Equals("http://demo.test.fider.io:3000")
}
func TestGlobalAssetsURL_SingleHostMode(t *testing.T) {
@@ -129,12 +127,12 @@ func TestGlobalAssetsURL_SingleHostMode(t *testing.T) {
env.Config.HostMode = "single"
ctx := newGetContext("http://feedback.theavengers.com:3000", nil)
- Expect(ctx.GlobalAssetsURL("/assets/main.js")).Equals("http://feedback.theavengers.com:3000/assets/main.js")
- Expect(ctx.GlobalAssetsURL("/assets/main.css")).Equals("http://feedback.theavengers.com:3000/assets/main.css")
+ Expect(web.GlobalAssetsURL(ctx, "/assets/main.js")).Equals("http://feedback.theavengers.com:3000/assets/main.js")
+ Expect(web.GlobalAssetsURL(ctx, "/assets/main.css")).Equals("http://feedback.theavengers.com:3000/assets/main.css")
env.Config.CDN.Host = "assets-fider.io"
- Expect(ctx.GlobalAssetsURL("/assets/main.js")).Equals("http://assets-fider.io/assets/main.js")
- Expect(ctx.GlobalAssetsURL("/assets/main.css")).Equals("http://assets-fider.io/assets/main.css")
+ Expect(web.GlobalAssetsURL(ctx, "/assets/main.js")).Equals("http://assets-fider.io/assets/main.js")
+ Expect(web.GlobalAssetsURL(ctx, "/assets/main.css")).Equals("http://assets-fider.io/assets/main.css")
}
func TestGlobalAssetsURL_MultiHostMode(t *testing.T) {
@@ -148,12 +146,12 @@ func TestGlobalAssetsURL_MultiHostMode(t *testing.T) {
CNAME: "feedback.theavengers.com",
})
- Expect(ctx.GlobalAssetsURL("/assets/main.js")).Equals("http://theavengers.test.fider.io:3000/assets/main.js")
- Expect(ctx.GlobalAssetsURL("/assets/main.css")).Equals("http://theavengers.test.fider.io:3000/assets/main.css")
+ Expect(web.GlobalAssetsURL(ctx, "/assets/main.js")).Equals("http://theavengers.test.fider.io:3000/assets/main.js")
+ Expect(web.GlobalAssetsURL(ctx, "/assets/main.css")).Equals("http://theavengers.test.fider.io:3000/assets/main.css")
env.Config.CDN.Host = "assets-fider.io"
- Expect(ctx.GlobalAssetsURL("/assets/main.js")).Equals("http://cdn.assets-fider.io/assets/main.js")
- Expect(ctx.GlobalAssetsURL("/assets/main.css")).Equals("http://cdn.assets-fider.io/assets/main.css")
+ Expect(web.GlobalAssetsURL(ctx, "/assets/main.js")).Equals("http://cdn.assets-fider.io/assets/main.js")
+ Expect(web.GlobalAssetsURL(ctx, "/assets/main.css")).Equals("http://cdn.assets-fider.io/assets/main.css")
}
func TestTenantAssetsURL_SingleHostMode(t *testing.T) {
@@ -166,12 +164,12 @@ func TestTenantAssetsURL_SingleHostMode(t *testing.T) {
Subdomain: "theavengers",
})
- Expect(ctx.TenantAssetsURL("/assets/main.js")).Equals("http://feedback.theavengers.com:3000/assets/main.js")
- Expect(ctx.TenantAssetsURL("/assets/main.css")).Equals("http://feedback.theavengers.com:3000/assets/main.css")
+ Expect(web.TenantAssetsURL(ctx, "/assets/main.js")).Equals("http://feedback.theavengers.com:3000/assets/main.js")
+ Expect(web.TenantAssetsURL(ctx, "/assets/main.css")).Equals("http://feedback.theavengers.com:3000/assets/main.css")
env.Config.CDN.Host = "assets-fider.io"
- Expect(ctx.TenantAssetsURL("/assets/main.js")).Equals("http://assets-fider.io/assets/main.js")
- Expect(ctx.TenantAssetsURL("/assets/main.css")).Equals("http://assets-fider.io/assets/main.css")
+ Expect(web.TenantAssetsURL(ctx, "/assets/main.js")).Equals("http://assets-fider.io/assets/main.js")
+ Expect(web.TenantAssetsURL(ctx, "/assets/main.css")).Equals("http://assets-fider.io/assets/main.css")
}
func TestTenantAssetsURL_MultiHostMode(t *testing.T) {
@@ -185,12 +183,12 @@ func TestTenantAssetsURL_MultiHostMode(t *testing.T) {
CNAME: "feedback.theavengers.com",
})
- Expect(ctx.TenantAssetsURL("/assets/main.js")).Equals("http://theavengers.test.fider.io:3000/assets/main.js")
- Expect(ctx.TenantAssetsURL("/assets/main.css")).Equals("http://theavengers.test.fider.io:3000/assets/main.css")
+ Expect(web.TenantAssetsURL(ctx, "/assets/main.js")).Equals("http://theavengers.test.fider.io:3000/assets/main.js")
+ Expect(web.TenantAssetsURL(ctx, "/assets/main.css")).Equals("http://theavengers.test.fider.io:3000/assets/main.css")
env.Config.CDN.Host = "assets-fider.io"
- Expect(ctx.TenantAssetsURL("/assets/main.js")).Equals("http://theavengers.assets-fider.io/assets/main.js")
- Expect(ctx.TenantAssetsURL("/assets/main.css")).Equals("http://theavengers.assets-fider.io/assets/main.css")
+ Expect(web.TenantAssetsURL(ctx, "/assets/main.js")).Equals("http://theavengers.assets-fider.io/assets/main.js")
+ Expect(web.TenantAssetsURL(ctx, "/assets/main.css")).Equals("http://theavengers.assets-fider.io/assets/main.css")
}
func TestCanonicalURL_SameDomain(t *testing.T) {
@@ -199,16 +197,16 @@ func TestCanonicalURL_SameDomain(t *testing.T) {
ctx := newGetContext("http://theavengers.test.fider.io:3000", nil)
ctx.SetCanonicalURL("")
- Expect(ctx.Get("Canonical-URL")).Equals(`http://theavengers.test.fider.io:3000`)
+ Expect(ctx.Value("Canonical-URL")).Equals(`http://theavengers.test.fider.io:3000`)
ctx.SetCanonicalURL("/some-url")
- Expect(ctx.Get("Canonical-URL")).Equals(`http://theavengers.test.fider.io:3000/some-url`)
+ Expect(ctx.Value("Canonical-URL")).Equals(`http://theavengers.test.fider.io:3000/some-url`)
ctx.SetCanonicalURL("/some-other-url")
- Expect(ctx.Get("Canonical-URL")).Equals(`http://theavengers.test.fider.io:3000/some-other-url`)
+ Expect(ctx.Value("Canonical-URL")).Equals(`http://theavengers.test.fider.io:3000/some-other-url`)
ctx.SetCanonicalURL("page-b/abc.html")
- Expect(ctx.Get("Canonical-URL")).Equals(`http://theavengers.test.fider.io:3000/page-b/abc.html`)
+ Expect(ctx.Value("Canonical-URL")).Equals(`http://theavengers.test.fider.io:3000/page-b/abc.html`)
}
func TestCanonicalURL_DifferentDomain(t *testing.T) {
@@ -217,16 +215,16 @@ func TestCanonicalURL_DifferentDomain(t *testing.T) {
ctx := newGetContext("http://theavengers.test.fider.io:3000", nil)
ctx.SetCanonicalURL("http://feedback.theavengers.com/some-url")
- Expect(ctx.Get("Canonical-URL")).Equals(`http://feedback.theavengers.com/some-url`)
+ Expect(ctx.Value("Canonical-URL")).Equals(`http://feedback.theavengers.com/some-url`)
ctx.SetCanonicalURL("")
- Expect(ctx.Get("Canonical-URL")).Equals(`http://feedback.theavengers.com`)
+ Expect(ctx.Value("Canonical-URL")).Equals(`http://feedback.theavengers.com`)
ctx.SetCanonicalURL("/some-other-url")
- Expect(ctx.Get("Canonical-URL")).Equals(`http://feedback.theavengers.com/some-other-url`)
+ Expect(ctx.Value("Canonical-URL")).Equals(`http://feedback.theavengers.com/some-other-url`)
ctx.SetCanonicalURL("page-b/abc.html")
- Expect(ctx.Get("Canonical-URL")).Equals(`http://feedback.theavengers.com/page-b/abc.html`)
+ Expect(ctx.Value("Canonical-URL")).Equals(`http://feedback.theavengers.com/page-b/abc.html`)
}
func TestTryAgainLater(t *testing.T) {
@@ -240,3 +238,27 @@ func TestTryAgainLater(t *testing.T) {
Expect(resp.Header().Get("Cache-Control")).Equals("no-cache, no-store, must-revalidate")
Expect(resp.Header().Get("Retry-After")).Equals("86400")
}
+
+func TestGetOAuthBaseURL(t *testing.T) {
+ RegisterT(t)
+
+ ctx := newGetContext("https://mydomain.com/hello-world", nil)
+
+ env.Config.HostMode = "multi"
+ Expect(web.OAuthBaseURL(ctx)).Equals("https://login.test.fider.io")
+
+ env.Config.HostMode = "single"
+ Expect(web.OAuthBaseURL(ctx)).Equals("https://mydomain.com")
+}
+
+func TestGetOAuthBaseURL_WithPort(t *testing.T) {
+ RegisterT(t)
+
+ ctx := newGetContext("http://demo.test.fider.io:3000/hello-world", nil)
+
+ env.Config.HostMode = "multi"
+ Expect(web.OAuthBaseURL(ctx)).Equals("http://login.test.fider.io:3000")
+
+ env.Config.HostMode = "single"
+ Expect(web.OAuthBaseURL(ctx)).Equals("http://demo.test.fider.io:3000")
+}
diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.go
index 2bc0106e0..cda51379b 100644
--- a/app/pkg/web/engine.go
+++ b/app/pkg/web/engine.go
@@ -3,6 +3,7 @@ package web
import (
"context"
"fmt"
+ "io/ioutil"
stdLog "log"
"net/http"
"os"
@@ -12,11 +13,10 @@ import (
"time"
"github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/models/dto"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
- "github.com/getfider/fider/app/pkg/log/database"
"github.com/getfider/fider/app/pkg/rand"
"github.com/getfider/fider/app/pkg/worker"
"github.com/julienschmidt/httprouter"
@@ -45,22 +45,21 @@ type notFoundHandler struct {
}
func (h *notFoundHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
- ctx := h.engine.NewContext(res, req, nil)
+ ctx := NewContext(h.engine, req, res, nil)
h.handler(ctx)
}
//HandlerFunc represents an HTTP handler
-type HandlerFunc func(Context) error
+type HandlerFunc func(*Context) error
//MiddlewareFunc represents an HTTP middleware
type MiddlewareFunc func(HandlerFunc) HandlerFunc
//Engine is our web engine wrapper
type Engine struct {
+ context.Context
mux *httprouter.Router
- logger log.Logger
renderer *Renderer
- db *dbx.Database
binder *DefaultBinder
middlewares []MiddlewareFunc
worker worker.Worker
@@ -70,21 +69,19 @@ type Engine struct {
//New creates a new Engine
func New(settings *models.SystemSettings) *Engine {
- db := dbx.New()
- logger := database.NewLogger("WEB", db)
- logger.SetProperty(log.PropertyKeyContextID, rand.String(32))
-
- bgLogger := database.NewLogger("BGW", db)
- bgLogger.SetProperty(log.PropertyKeyContextID, rand.String(32))
+ ctx := context.Background()
+ ctx = log.WithProperties(ctx, dto.Props{
+ log.PropertyKeyContextID: rand.String(32),
+ log.PropertyKeyTag: "WEB",
+ })
router := &Engine{
+ Context: ctx,
mux: httprouter.New(),
- db: db,
- logger: logger,
- renderer: NewRenderer(settings, logger),
+ renderer: NewRenderer(settings),
binder: NewDefaultBinder(),
middlewares: make([]MiddlewareFunc, 0),
- worker: worker.New(db, bgLogger),
+ worker: worker.New(),
cache: cache.New(5*time.Minute, 10*time.Minute),
}
@@ -93,8 +90,8 @@ func New(settings *models.SystemSettings) *Engine {
//Start the server.
func (e *Engine) Start(address string) {
- e.logger.Info("Application is starting")
- e.logger.Infof("GO_ENV: @{Env}", log.Props{
+ log.Info(e, "Application is starting")
+ log.Infof(e, "GO_ENV: @{Env}", dto.Props{
"Env": env.Config.Environment,
})
@@ -108,13 +105,13 @@ func (e *Engine) Start(address string) {
keyFilePath = env.Etc(env.Config.SSLCertKey)
}
+ stdLog.SetOutput(ioutil.Discard)
e.server = &http.Server{
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
Addr: address,
Handler: e.mux,
- ErrorLog: stdLog.New(e.logger, "", 0),
TLSConfig: getDefaultTLSConfig(),
}
@@ -127,20 +124,20 @@ func (e *Engine) Start(address string) {
certManager *CertificateManager
)
if env.Config.AutoSSL {
- certManager, err = NewCertificateManager(certFilePath, keyFilePath, e.db)
+ certManager, err = NewCertificateManager(certFilePath, keyFilePath)
if err != nil {
panic(errors.Wrap(err, "failed to initialize CertificateManager"))
}
e.server.TLSConfig.GetCertificate = certManager.GetCertificate
- e.logger.Infof("https (auto ssl) server started on @{Address}", log.Props{"Address": address})
+ log.Infof(e, "https (auto ssl) server started on @{Address}", dto.Props{"Address": address})
go certManager.StartHTTPServer()
err = e.server.ListenAndServeTLS("", "")
} else if certFilePath == "" && keyFilePath == "" {
- e.logger.Infof("http server started on @{Address}", log.Props{"Address": address})
+ log.Infof(e, "http server started on @{Address}", dto.Props{"Address": address})
err = e.server.ListenAndServe()
} else {
- e.logger.Infof("https server started on @{Address}", log.Props{"Address": address})
+ log.Infof(e, "https server started on @{Address}", dto.Props{"Address": address})
err = e.server.ListenAndServeTLS(certFilePath, keyFilePath)
}
@@ -154,50 +151,21 @@ func (e *Engine) Stop() error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
- e.logger.Info("server is shutting down")
+ log.Info(e, "server is shutting down")
if err := e.server.Shutdown(ctx); err != nil {
return errors.Wrap(err, "failed to shutdown server")
}
- e.logger.Info("server has shutdown")
+ log.Info(e, "server has shutdown")
- e.logger.Info("worker is shutting down")
+ log.Info(e, "worker is shutting down")
if err := e.worker.Shutdown(ctx); err != nil {
return errors.Wrap(err, "failed to shutdown worker")
}
- e.logger.Info("worker has shutdown")
+ log.Info(e, "worker has shutdown")
return nil
}
-//NewContext creates and return a new context
-func (e *Engine) NewContext(res http.ResponseWriter, req *http.Request, params StringMap) Context {
- contextID := rand.String(32)
- request := WrapRequest(req)
- ctxLogger := e.logger.New()
- ctxLogger.SetProperty(log.PropertyKeyContextID, contextID)
- ctxLogger.SetProperty("UserAgent", req.Header.Get("User-Agent"))
-
- return Context{
- id: contextID,
- Response: res,
- Request: request,
- engine: e,
- logger: ctxLogger,
- params: params,
- worker: e.worker,
- }
-}
-
-//Logger returns current logger
-func (e *Engine) Logger() log.Logger {
- return e.logger
-}
-
-//Database returns current database
-func (e *Engine) Database() *dbx.Database {
- return e.db
-}
-
//Cache returns current cache
func (e *Engine) Cache() *cache.Cache {
return e.cache
@@ -260,7 +228,7 @@ func (e *Engine) handle(middlewares []MiddlewareFunc, handler HandlerFunc) httpr
for _, p := range ps {
params[p.Key] = p.Value
}
- ctx := e.NewContext(res, req, params)
+ ctx := NewContext(e, req, res, params)
next(ctx)
}
return h
@@ -315,7 +283,7 @@ func (g *Group) Static(prefix, root string) {
var h HandlerFunc
if fi.IsDir() {
- h = func(c Context) error {
+ h = func(c *Context) error {
filePath := path.Join(root, c.Param("filepath"))
fi, err := os.Stat(filePath)
if err == nil && !fi.IsDir() {
@@ -325,7 +293,7 @@ func (g *Group) Static(prefix, root string) {
return c.NotFound()
}
} else {
- h = func(c Context) error {
+ h = func(c *Context) error {
http.ServeFile(c.Response, c.Request.instance, root)
return nil
}
diff --git a/app/pkg/web/engine_test.go b/app/pkg/web/engine_test.go
index a3336ff81..33c264538 100644
--- a/app/pkg/web/engine_test.go
+++ b/app/pkg/web/engine_test.go
@@ -19,27 +19,27 @@ func StartServer() {
group := e.Group()
{
- group.Get("/api/ping", func(c web.Context) error {
- if c.Get("the-name") != nil {
+ group.Get("/api/ping", func(c *web.Context) error {
+ if c.Value("the-name") != nil {
panic("key: the-name should not be set")
}
return c.String(http.StatusOK, "pong")
})
group.Use(func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
+ return func(c *web.Context) error {
c.Set("the-name", c.QueryParam("name"))
return next(c)
}
})
- group.Get("/api/echo", func(c web.Context) error {
- return c.String(http.StatusOK, c.Get("the-name").(string))
+ group.Get("/api/echo", func(c *web.Context) error {
+ return c.String(http.StatusOK, c.Value("the-name").(string))
})
}
- e.Get("/hello", func(c web.Context) error {
- if c.Get("name") != nil {
+ e.Get("/hello", func(c *web.Context) error {
+ if c.Value("name") != nil {
panic("ERROR!")
}
return c.String(http.StatusOK, "")
diff --git a/app/pkg/web/http/client.go b/app/pkg/web/http/client.go
deleted file mode 100644
index 9f39af0eb..000000000
--- a/app/pkg/web/http/client.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package http
-
-import (
- "io"
- "net/http"
- gohttp "net/http"
- "time"
-
- "github.com/getfider/fider/app/pkg/env"
-)
-
-func init() {
- //Increase transport timeouts when running Tests
- if env.IsTest() {
- transport := gohttp.DefaultTransport.(*gohttp.Transport)
- transport.TLSHandshakeTimeout = 30 * time.Second
- }
-}
-
-// Client is an interface for HTTP Client
-type Client interface {
- Do(req *gohttp.Request) (*gohttp.Response, error)
-}
-
-// DefaultClient is the default HTTP Client
-type DefaultClient struct {
-}
-
-// NewClient creates a new defaultClient
-func NewClient() *DefaultClient {
- return &DefaultClient{}
-}
-
-// NewRequest creates a new HTTP Request
-func NewRequest(method, url string, body io.Reader) (*gohttp.Request, error) {
- return gohttp.NewRequest(method, url, body)
-}
-
-// Do sends the request using http.DefaultClient
-func (client *DefaultClient) Do(req *http.Request) (*http.Response, error) {
- return http.DefaultClient.Do(req)
-}
diff --git a/app/pkg/web/oauth.go b/app/pkg/web/oauth.go
deleted file mode 100644
index e2e6e1af4..000000000
--- a/app/pkg/web/oauth.go
+++ /dev/null
@@ -1,308 +0,0 @@
-package web
-
-import (
- "fmt"
- "io/ioutil"
- "net/http"
- "net/url"
- "strings"
-
- "github.com/getfider/fider/app/pkg/env"
-
- jwt "github.com/dgrijalva/jwt-go"
- "github.com/getfider/fider/app/pkg/validate"
- "github.com/getfider/fider/app/storage"
-
- "github.com/getfider/fider/app/pkg/jsonq"
-
- "github.com/getfider/fider/app/models"
-
- "github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/oauth"
- "golang.org/x/oauth2"
- "golang.org/x/oauth2/facebook"
- "golang.org/x/oauth2/github"
-)
-
-func getProviderStatus(key string) int {
- if key == "" {
- return models.OAuthConfigDisabled
- }
- return models.OAuthConfigEnabled
-}
-
-var (
- systemProviders = []*models.OAuthConfig{
- &models.OAuthConfig{
- Provider: oauth.FacebookProvider,
- DisplayName: "Facebook",
- ProfileURL: "https://graph.facebook.com/me?fields=name,email",
- Status: getProviderStatus(env.Config.OAuth.Facebook.AppID),
- ClientID: env.Config.OAuth.Facebook.AppID,
- ClientSecret: env.Config.OAuth.Facebook.Secret,
- Scope: "public_profile email",
- AuthorizeURL: facebook.Endpoint.AuthURL,
- TokenURL: facebook.Endpoint.TokenURL,
- JSONUserIDPath: "id",
- JSONUserNamePath: "name",
- JSONUserEmailPath: "email",
- },
- &models.OAuthConfig{
- Provider: oauth.GoogleProvider,
- DisplayName: "Google",
- ProfileURL: "https://www.googleapis.com/oauth2/v2/userinfo",
- Status: getProviderStatus(env.Config.OAuth.Google.ClientID),
- ClientID: env.Config.OAuth.Google.ClientID,
- ClientSecret: env.Config.OAuth.Google.Secret,
- Scope: "profile email",
- AuthorizeURL: "https://accounts.google.com/o/oauth2/v2/auth",
- TokenURL: "https://www.googleapis.com/oauth2/v4/token",
- JSONUserIDPath: "id",
- JSONUserNamePath: "name",
- JSONUserEmailPath: "email",
- },
- &models.OAuthConfig{
- Provider: oauth.GitHubProvider,
- DisplayName: "GitHub",
- ProfileURL: "https://api.github.com/user",
- Status: getProviderStatus(env.Config.OAuth.GitHub.ClientID),
- ClientID: env.Config.OAuth.GitHub.ClientID,
- ClientSecret: env.Config.OAuth.GitHub.Secret,
- Scope: "user:email",
- AuthorizeURL: github.Endpoint.AuthURL,
- TokenURL: github.Endpoint.TokenURL,
- JSONUserIDPath: "id",
- JSONUserNamePath: "name, login",
- JSONUserEmailPath: "email",
- },
- }
-)
-
-//OAuthService implements real OAuth operations using Golang's oauth2 package
-type OAuthService struct {
- oauthBaseURL string
- tenantStorage storage.Tenant
- configCache map[string]*models.OAuthConfig
-}
-
-//NewOAuthService creates a new OAuthService
-func NewOAuthService(oauthBaseURL string, tenantStorage storage.Tenant) *OAuthService {
- configCache := make(map[string]*models.OAuthConfig, 0)
-
- return &OAuthService{
- oauthBaseURL,
- tenantStorage,
- configCache,
- }
-}
-
-//GetAuthURL returns authentication url for given provider
-func (s *OAuthService) GetAuthURL(provider, redirect, identifier string) (string, error) {
- config, err := s.getConfig(provider)
- if err != nil {
- return "", err
- }
-
- authURL, _ := url.Parse(config.AuthorizeURL)
- parameters := url.Values{}
- parameters.Add("client_id", config.ClientID)
- parameters.Add("scope", config.Scope)
- parameters.Add("redirect_uri", fmt.Sprintf("%s/oauth/%s/callback", s.oauthBaseURL, provider))
- parameters.Add("response_type", "code")
- parameters.Add("state", redirect+"|"+identifier)
- authURL.RawQuery = parameters.Encode()
- return authURL.String(), nil
-}
-
-//GetProfile returns user profile based on provider (only if enabled) and code
-func (s *OAuthService) GetProfile(provider string, code string) (*oauth.UserProfile, error) {
- config, err := s.getConfig(provider)
- if err != nil {
- return nil, err
- }
-
- if config.Status == models.OAuthConfigDisabled {
- return nil, errors.New("Provider %s is disabled", provider)
- }
-
- body, err := s.GetRawProfile(provider, code)
- if err != nil {
- return nil, err
- }
-
- return s.ParseRawProfile(provider, body)
-}
-
-//GetRawProfile returns raw JSON response from Profile API
-func (s *OAuthService) GetRawProfile(provider string, code string) (string, error) {
- config, err := s.getConfig(provider)
- if err != nil {
- return "", err
- }
-
- exchange := (&oauth2.Config{
- ClientID: config.ClientID,
- ClientSecret: config.ClientSecret,
- Endpoint: oauth2.Endpoint{
- AuthURL: config.AuthorizeURL,
- TokenURL: config.TokenURL,
- },
- RedirectURL: fmt.Sprintf("%s/oauth/%s/callback", s.oauthBaseURL, provider),
- }).Exchange
-
- oauthToken, err := exchange(oauth2.NoContext, code)
- if err != nil {
- return "", err
- }
-
- if config.ProfileURL == "" {
- parts := strings.Split(oauthToken.AccessToken, ".")
- if len(parts) != 3 {
- return "", errors.New("AccessToken is not JWT")
- }
-
- body, _ := jwt.DecodeSegment(parts[1])
- return string(body), nil
- }
-
- statusCode, body, err := s.doGet(config.ProfileURL, oauthToken.AccessToken)
- if err != nil {
- return "", err
- }
-
- if statusCode != 200 {
- return "", errors.New("Failed to request profile. Status Code: %d. Body: %s", statusCode, body)
- }
-
- return body, nil
-}
-
-//ParseRawProfile parses raw profile response into UserProfile model
-func (s *OAuthService) ParseRawProfile(provider, body string) (*oauth.UserProfile, error) {
- config, err := s.getConfig(provider)
- if err != nil {
- return nil, err
- }
-
- query := jsonq.New(body)
- profile := &oauth.UserProfile{
- ID: strings.TrimSpace(query.String(config.JSONUserIDPath)),
- Name: strings.TrimSpace(query.String(config.JSONUserNamePath)),
- Email: strings.ToLower(strings.TrimSpace(query.String(config.JSONUserEmailPath))),
- }
-
- if profile.ID == "" {
- return nil, oauth.ErrUserIDRequired
- }
-
- if profile.Name == "" && profile.Email != "" {
- parts := strings.Split(profile.Email, "@")
- profile.Name = parts[0]
- }
-
- if profile.Name == "" {
- profile.Name = "Anonymous"
- }
-
- if len(validate.Email(profile.Email)) != 0 {
- profile.Email = ""
- }
-
- return profile, nil
-}
-
-//ListActiveProviders returns a list of all enabled providers for current tenant
-func (s *OAuthService) ListActiveProviders() ([]*oauth.ProviderOption, error) {
- list := make([]*oauth.ProviderOption, 0)
- providers, err := s.ListAllProviders()
- if err != nil {
- return nil, err
- }
-
- for _, p := range providers {
- if p.IsEnabled {
- list = append(list, p)
- }
- }
- return list, nil
-}
-
-//ListAllProviders returns a list of all providers for current tenant
-func (s *OAuthService) ListAllProviders() ([]*oauth.ProviderOption, error) {
- providers, err := s.allOAuthConfigs()
- if err != nil {
- return nil, err
- }
-
- list := make([]*oauth.ProviderOption, 0)
-
- for _, p := range providers {
- list = append(list, &oauth.ProviderOption{
- Provider: p.Provider,
- DisplayName: p.DisplayName,
- ClientID: p.ClientID,
- URL: fmt.Sprintf("/oauth/%s", p.Provider),
- CallbackURL: fmt.Sprintf("%s/oauth/%s/callback", s.oauthBaseURL, p.Provider),
- IsCustomProvider: string(p.Provider[0]) == "_",
- LogoBlobKey: p.LogoBlobKey,
- IsEnabled: p.Status == models.OAuthConfigEnabled,
- })
- }
-
- return list, nil
-}
-
-func (s *OAuthService) allOAuthConfigs() ([]*models.OAuthConfig, error) {
- list := make([]*models.OAuthConfig, 0)
-
- for _, p := range systemProviders {
- list = append(list, p)
- }
-
- customProviders, err := s.tenantStorage.ListOAuthConfig()
- if err != nil {
- return nil, errors.Wrap(err, "failed to get list of custom OAuth providers")
- }
-
- for _, p := range customProviders {
- list = append(list, p)
- }
-
- return list, nil
-}
-
-func (s *OAuthService) doGet(url, accessToken string) (int, string, error) {
- req, _ := http.NewRequest("GET", url, nil)
- req.Header.Set("Authorization", "Bearer "+accessToken)
- r, err := http.DefaultClient.Do(req)
-
- if err != nil {
- return 0, "", err
- }
-
- defer r.Body.Close()
-
- bytes, err := ioutil.ReadAll(r.Body)
- return r.StatusCode, string(bytes), err
-}
-
-func (s *OAuthService) getConfig(provider string) (*models.OAuthConfig, error) {
- for _, config := range systemProviders {
- if config.Status == models.OAuthConfigEnabled && config.Provider == provider {
- return config, nil
- }
- }
-
- var err error
- config, ok := s.configCache[provider]
- if !ok {
- config, err = s.tenantStorage.GetOAuthConfigByProvider(provider)
- if err != nil {
- return nil, err
- }
-
- s.configCache[provider] = config
- }
-
- return config, nil
-}
diff --git a/app/pkg/web/oauth_test.go b/app/pkg/web/oauth_test.go
deleted file mode 100644
index 886a7fe2b..000000000
--- a/app/pkg/web/oauth_test.go
+++ /dev/null
@@ -1,256 +0,0 @@
-package web_test
-
-import (
- "testing"
-
- "github.com/getfider/fider/app/models"
-
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/oauth"
- "github.com/getfider/fider/app/pkg/web"
- "github.com/getfider/fider/app/storage/inmemory"
-)
-
-func TestGetAuthURL_Facebook(t *testing.T) {
- RegisterT(t)
-
- svc := web.NewOAuthService("http://login.test.fider.io:3000", inmemory.NewTenantStorage())
- authURL, err := svc.GetAuthURL(oauth.FacebookProvider, "http://example.org", "456")
-
- Expect(err).IsNil()
- Expect(authURL).Equals("https://www.facebook.com/v3.1/dialog/oauth?client_id=FB_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Ffacebook%2Fcallback&response_type=code&scope=public_profile+email&state=http%3A%2F%2Fexample.org%7C456")
-}
-
-func TestGetAuthURL_Google(t *testing.T) {
- RegisterT(t)
-
- svc := web.NewOAuthService("http://login.test.fider.io:3000", inmemory.NewTenantStorage())
- authURL, err := svc.GetAuthURL(oauth.GoogleProvider, "http://example.org", "123")
-
- Expect(err).IsNil()
- Expect(authURL).Equals("https://accounts.google.com/o/oauth2/v2/auth?client_id=GO_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgoogle%2Fcallback&response_type=code&scope=profile+email&state=http%3A%2F%2Fexample.org%7C123")
-}
-
-func TestGetAuthURL_GitHub(t *testing.T) {
- RegisterT(t)
-
- svc := web.NewOAuthService("http://login.test.fider.io:3000", inmemory.NewTenantStorage())
- authURL, err := svc.GetAuthURL(oauth.GitHubProvider, "http://example.org", "456")
-
- Expect(err).IsNil()
- Expect(authURL).Equals("https://github.com/login/oauth/authorize?client_id=GH_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgithub%2Fcallback&response_type=code&scope=user%3Aemail&state=http%3A%2F%2Fexample.org%7C456")
-}
-
-func TestGetAuthURL_Custom(t *testing.T) {
- RegisterT(t)
-
- tenants := inmemory.NewTenantStorage()
- tenants.SaveOAuthConfig(&models.CreateEditOAuthConfig{
- Provider: "_custom",
- ClientID: "CU_CL_ID",
- Scope: "profile email",
- AuthorizeURL: "https://example.org/oauth/authorize",
- })
- svc := web.NewOAuthService("http://login.test.fider.io:3000", tenants)
- authURL, err := svc.GetAuthURL("_custom", "http://example.org", "456")
-
- Expect(err).IsNil()
- Expect(authURL).Equals("https://example.org/oauth/authorize?client_id=CU_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2F_custom%2Fcallback&response_type=code&scope=profile+email&state=http%3A%2F%2Fexample.org%7C456")
-}
-
-func TestParseProfileResponse_AllFields(t *testing.T) {
- RegisterT(t)
-
- storage := inmemory.NewTenantStorage()
- storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{
- Provider: "_test1",
- JSONUserIDPath: "id",
- JSONUserNamePath: "name",
- JSONUserEmailPath: "email",
- })
- svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)
- profile, err := svc.ParseRawProfile(
- "_test1",
- `{"name":"Jon Snow","email":"jon\u0040got.com","id":"789654"}`,
- )
-
- Expect(err).IsNil()
- Expect(profile.ID).Equals("789654")
- Expect(profile.Name).Equals("Jon Snow")
- Expect(profile.Email).Equals("[email protected]")
-}
-
-func TestParseProfileResponse_WithoutEmail(t *testing.T) {
- RegisterT(t)
-
- storage := inmemory.NewTenantStorage()
- storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{
- Provider: "_test1",
- JSONUserIDPath: "id",
- JSONUserNamePath: "name",
- JSONUserEmailPath: "email",
- })
- svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)
- profile, err := svc.ParseRawProfile(
- "_test1",
- `{"name":"Jon Snow","id":"1"}`,
- )
-
- Expect(err).IsNil()
- Expect(profile.ID).Equals("1")
- Expect(profile.Name).Equals("Jon Snow")
- Expect(profile.Email).Equals("")
-}
-
-func TestParseProfileResponse_NestedData(t *testing.T) {
- RegisterT(t)
-
- storage := inmemory.NewTenantStorage()
- storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{
- Provider: "_test1",
- JSONUserIDPath: "id",
- JSONUserNamePath: "profile.name",
- JSONUserEmailPath: "profile.email",
- })
- svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)
- profile, err := svc.ParseRawProfile(
- "_test1",
- `{
- "id": "123",
- "profile": {
- "name": "Jon Snow",
- "email": "[email protected]"
- }
- }`,
- )
-
- Expect(err).IsNil()
- Expect(profile.ID).Equals("123")
- Expect(profile.Name).Equals("Jon Snow")
- Expect(profile.Email).Equals("[email protected]")
-}
-
-func TestParseProfileResponse_WithFallback(t *testing.T) {
- RegisterT(t)
-
- storage := inmemory.NewTenantStorage()
- storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{
- Provider: "_test1",
- JSONUserIDPath: "id",
- JSONUserNamePath: "profile.name, profile.login",
- JSONUserEmailPath: "profile.email",
- })
- svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)
- profile, err := svc.ParseRawProfile(
- "_test1",
- `{
- "id": 123,
- "profile": {
- "login": "jonny",
- "email": "[email protected]"
- }
- }`,
- )
-
- Expect(err).IsNil()
- Expect(profile.ID).Equals("123")
- Expect(profile.Name).Equals("jonny")
- Expect(profile.Email).Equals("[email protected]")
-}
-
-func TestParseProfileResponse_UseEmailWhenNameIsEmpty(t *testing.T) {
- RegisterT(t)
-
- storage := inmemory.NewTenantStorage()
- storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{
- Provider: "_test1",
- JSONUserIDPath: "id",
- JSONUserNamePath: "profile.name",
- JSONUserEmailPath: "profile.email",
- })
- svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)
- profile, err := svc.ParseRawProfile(
- "_test1",
- `{
- "id": "123",
- "profile": {
- "email": "[email protected]"
- }
- }`,
- )
-
- Expect(err).IsNil()
- Expect(profile.ID).Equals("123")
- Expect(profile.Name).Equals("jon")
- Expect(profile.Email).Equals("[email protected]")
-}
-
-func TestParseProfileResponse_InvalidEmail(t *testing.T) {
- RegisterT(t)
-
- storage := inmemory.NewTenantStorage()
- storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{
- Provider: "_test1",
- JSONUserIDPath: "id",
- JSONUserNamePath: "profile.name",
- JSONUserEmailPath: "profile.email",
- })
- svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)
- profile, err := svc.ParseRawProfile(
- "_test1",
- `{
- "id": "AB123",
- "profile": {
- "name": "Jon Snow",
- "email": "jon"
- }
- }`,
- )
-
- Expect(err).IsNil()
- Expect(profile.ID).Equals("AB123")
- Expect(profile.Name).Equals("Jon Snow")
- Expect(profile.Email).Equals("")
-}
-
-func TestParseProfileResponse_EmptyID(t *testing.T) {
- RegisterT(t)
-
- storage := inmemory.NewTenantStorage()
- storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{
- Provider: "_test1",
- JSONUserIDPath: "id",
- JSONUserNamePath: "name",
- JSONUserEmailPath: "email",
- })
- svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)
- profile, err := svc.ParseRawProfile(
- "_test1",
- `{}`,
- )
-
- Expect(errors.Cause(err)).Equals(oauth.ErrUserIDRequired)
- Expect(profile).IsNil()
-}
-
-func TestParseProfileResponse_EmptyName(t *testing.T) {
- RegisterT(t)
-
- storage := inmemory.NewTenantStorage()
- storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{
- Provider: "_test1",
- JSONUserIDPath: "id",
- JSONUserNamePath: "name",
- JSONUserEmailPath: "email",
- })
- svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)
- profile, err := svc.ParseRawProfile(
- "_test1",
- `{ "id": "A0" }`,
- )
-
- Expect(err).IsNil()
- Expect(profile.ID).Equals("A0")
- Expect(profile.Name).Equals("Anonymous")
-}
diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.go
index 68638be4b..7e3059489 100644
--- a/app/pkg/web/renderer.go
+++ b/app/pkg/web/renderer.go
@@ -9,15 +9,18 @@ import (
"strings"
"sync"
+ "github.com/getfider/fider/app/models/dto"
+
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+
"io/ioutil"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/crypto"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/markdown"
- "github.com/getfider/fider/app/pkg/oauth"
)
var templateFunctions = template.FuncMap{
@@ -37,7 +40,6 @@ type clientAssets struct {
//Renderer is the default HTML Render
type Renderer struct {
templates map[string]*template.Template
- logger log.Logger
settings *models.SystemSettings
assets *clientAssets
chunkedAssets map[string]*clientAssets
@@ -45,10 +47,9 @@ type Renderer struct {
}
// NewRenderer creates a new Renderer
-func NewRenderer(settings *models.SystemSettings, logger log.Logger) *Renderer {
+func NewRenderer(settings *models.SystemSettings) *Renderer {
return &Renderer{
templates: make(map[string]*template.Template),
- logger: logger,
settings: settings,
mutex: sync.RWMutex{},
}
@@ -143,7 +144,7 @@ func getClientAssets(assets []string) *clientAssets {
}
//Render a template based on parameters
-func (r *Renderer) Render(w io.Writer, name string, props Props, ctx *Context) {
+func (r *Renderer) Render(w io.Writer, statusCode int, name string, props Props, ctx *Context) {
var err error
if r.assets == nil || env.IsDevelopment() {
@@ -158,12 +159,13 @@ func (r *Renderer) Render(w io.Writer, name string, props Props, ctx *Context) {
tmpl = r.add(name)
}
- public := make(Map, 0)
- private := make(Map, 0)
+ public := make(Map)
+ private := make(Map)
+ tenant := ctx.Tenant()
tenantName := "Fider"
- if ctx.Tenant() != nil {
- tenantName = ctx.Tenant().Name
+ if tenant != nil {
+ tenantName = tenant.Name
}
title := tenantName
@@ -183,23 +185,31 @@ func (r *Renderer) Render(w io.Writer, name string, props Props, ctx *Context) {
}
private["assets"] = r.assets
- private["logo"] = ctx.LogoURL()
- private["favicon"] = ctx.FaviconURL()
+ private["logo"] = LogoURL(ctx)
+
+ if tenant == nil || tenant.LogoBlobKey == "" {
+ private["favicon"] = GlobalAssetsURL(ctx, "/favicon")
+ } else {
+ private["favicon"] = TenantAssetsURL(ctx, "/favicon/%s", tenant.LogoBlobKey)
+ }
+
private["currentURL"] = ctx.Request.URL.String()
- if canonicalURL := ctx.Get("Canonical-URL"); canonicalURL != nil {
+ if canonicalURL := ctx.Value("Canonical-URL"); canonicalURL != nil {
private["canonicalURL"] = canonicalURL
}
- oauthProviders := make([]*oauth.ProviderOption, 0)
- if !ctx.IsAuthenticated() && ctx.Services() != nil {
- oauthProviders, err = ctx.Services().OAuth.ListActiveProviders()
+ oauthProviders := &query.ListActiveOAuthProviders{
+ Result: make([]*dto.OAuthProviderOption, 0),
+ }
+ if !ctx.IsAuthenticated() && statusCode >= 200 && statusCode < 300 {
+ err = bus.Dispatch(ctx, oauthProviders)
if err != nil {
panic(errors.Wrap(err, "failed to get list of providers"))
}
}
public["contextID"] = ctx.ContextID()
- public["tenant"] = ctx.Tenant()
+ public["tenant"] = tenant
public["props"] = props.Data
public["settings"] = &Map{
"mode": r.settings.Mode,
@@ -212,9 +222,9 @@ func (r *Renderer) Render(w io.Writer, name string, props Props, ctx *Context) {
"domain": r.settings.Domain,
"hasLegal": r.settings.HasLegal,
"baseURL": ctx.BaseURL(),
- "tenantAssetsURL": ctx.TenantAssetsURL(""),
- "globalAssetsURL": ctx.GlobalAssetsURL(""),
- "oauth": oauthProviders,
+ "tenantAssetsURL": TenantAssetsURL(ctx, ""),
+ "globalAssetsURL": GlobalAssetsURL(ctx, ""),
+ "oauth": oauthProviders.Result,
}
if ctx.IsAuthenticated() {
diff --git a/app/pkg/web/renderer_test.go b/app/pkg/web/renderer_test.go
index f86b5b9bd..74b618bf3 100644
--- a/app/pkg/web/renderer_test.go
+++ b/app/pkg/web/renderer_test.go
@@ -2,14 +2,21 @@ package web_test
import (
"bytes"
+ "context"
"io/ioutil"
+ "net/http"
"strings"
"testing"
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/enum"
+
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/log/noop"
"github.com/getfider/fider/app/pkg/web"
)
@@ -23,52 +30,72 @@ func compareRendererResponse(buf *bytes.Buffer, fileName string, ctx *web.Contex
func TestRenderer_Basic(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {
+ return nil
+ })
+
buf := new(bytes.Buffer)
ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
- renderer := web.NewRenderer(&models.SystemSettings{}, noop.NewLogger())
- renderer.Render(buf, "index.html", web.Props{}, ctx)
+ renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer.Render(buf, http.StatusOK, "index.html", web.Props{}, ctx)
compareRendererResponse(buf, "/app/pkg/web/testdata/basic.html", ctx)
}
func TestRenderer_WithChunkPreload(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {
+ return nil
+ })
+
buf := new(bytes.Buffer)
ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
- renderer := web.NewRenderer(&models.SystemSettings{}, noop.NewLogger())
- renderer.Render(buf, "index.html", web.Props{ChunkName: "Test.page"}, ctx)
+ renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer.Render(buf, http.StatusOK, "index.html", web.Props{ChunkName: "Test.page"}, ctx)
compareRendererResponse(buf, "/app/pkg/web/testdata/chunk.html", ctx)
}
func TestRenderer_Tenant(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {
+ return nil
+ })
+
buf := new(bytes.Buffer)
ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
ctx.SetTenant(&models.Tenant{Name: "Game of Thrones"})
- renderer := web.NewRenderer(&models.SystemSettings{}, noop.NewLogger())
- renderer.Render(buf, "index.html", web.Props{}, ctx)
+ renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer.Render(buf, http.StatusOK, "index.html", web.Props{}, ctx)
compareRendererResponse(buf, "/app/pkg/web/testdata/tenant.html", ctx)
}
func TestRenderer_WithCanonicalURL(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {
+ return nil
+ })
+
buf := new(bytes.Buffer)
ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
ctx.SetCanonicalURL("http://feedback.demo.org")
- renderer := web.NewRenderer(&models.SystemSettings{}, noop.NewLogger())
- renderer.Render(buf, "index.html", web.Props{}, ctx)
+ renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer.Render(buf, http.StatusOK, "index.html", web.Props{}, ctx)
compareRendererResponse(buf, "/app/pkg/web/testdata/canonical.html", ctx)
}
func TestRenderer_Props(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {
+ return nil
+ })
+
buf := new(bytes.Buffer)
ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
- renderer := web.NewRenderer(&models.SystemSettings{}, noop.NewLogger())
- renderer.Render(buf, "index.html", web.Props{
+ renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer.Render(buf, http.StatusOK, "index.html", web.Props{
Title: "My Page Title",
Description: "My Page Description",
Data: web.Map{
@@ -87,22 +114,64 @@ func TestRenderer_Props(t *testing.T) {
func TestRenderer_AuthenticatedUser(t *testing.T) {
RegisterT(t)
+ bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {
+ return nil
+ })
+
buf := new(bytes.Buffer)
ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
ctx.SetUser(&models.User{
ID: 5,
Name: "Jon Snow",
- Status: models.UserActive,
- Role: models.RoleAdministrator,
- AvatarType: models.AvatarTypeGravatar,
+ Status: enum.UserActive,
+ Role: enum.RoleAdministrator,
+ AvatarType: enum.AvatarTypeGravatar,
AvatarURL: "https://demo.test.fider.io:3000/avatars/gravatar/5/Jon%20Snow",
})
- renderer := web.NewRenderer(&models.SystemSettings{}, noop.NewLogger())
- renderer.Render(buf, "index.html", web.Props{
+ renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer.Render(buf, http.StatusOK, "index.html", web.Props{
Title: "My Page Title",
Description: "My Page Description",
}, ctx)
compareRendererResponse(buf, "/app/pkg/web/testdata/user.html", ctx)
}
+
+func TestRenderer_WithOAuth(t *testing.T) {
+ RegisterT(t)
+
+ bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {
+ q.Result = []*dto.OAuthProviderOption{
+ &dto.OAuthProviderOption{
+ Provider: app.GoogleProvider,
+ DisplayName: "Google",
+ ClientID: "1234",
+ URL: "https://demo.test.fider.io:3000/oauth/google",
+ CallbackURL: "https://demo.test.fider.io:3000/oauth/google/callback",
+ LogoBlobKey: "google.png",
+ IsCustomProvider: false,
+ IsEnabled: true,
+ },
+ }
+ return nil
+ })
+
+ buf := new(bytes.Buffer)
+ ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
+ renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer.Render(buf, http.StatusOK, "index.html", web.Props{}, ctx)
+ compareRendererResponse(buf, "/app/pkg/web/testdata/oauth.html", ctx)
+}
+
+func TestRenderer_NonOK(t *testing.T) {
+ RegisterT(t)
+
+ // it should not dispatch query.ListActiveOAuthProviders
+ buf := new(bytes.Buffer)
+ ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
+ renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer.Render(buf, http.StatusNotFound, "index.html", web.Props{}, ctx)
+ renderer.Render(buf, http.StatusBadRequest, "index.html", web.Props{}, ctx)
+ renderer.Render(buf, http.StatusTemporaryRedirect, "index.html", web.Props{}, ctx)
+}
diff --git a/app/pkg/web/request.go b/app/pkg/web/request.go
index 4dadcaf3e..ae420d5b7 100644
--- a/app/pkg/web/request.go
+++ b/app/pkg/web/request.go
@@ -7,6 +7,7 @@ import (
"net/url"
"regexp"
"strings"
+ "time"
"github.com/getfider/fider/app/pkg/errors"
)
@@ -19,6 +20,7 @@ type Request struct {
ContentLength int64
Body string
IsSecure bool
+ StartTime time.Time
URL *url.URL
}
@@ -58,6 +60,7 @@ func WrapRequest(request *http.Request) Request {
Body: string(bodyBytes),
URL: u,
IsSecure: protocol == "https",
+ StartTime: time.Now(),
}
}
@@ -106,3 +109,14 @@ var crawlerRegex = regexp.MustCompile("(?i)(baidu)|(msnbot)|(bingbot)|(bingprevi
func (r *Request) IsCrawler() bool {
return crawlerRegex.MatchString(r.GetHeader("User-Agent"))
}
+
+//BaseURL returns base URL
+func (r *Request) BaseURL() string {
+ address := r.URL.Scheme + "://" + r.URL.Hostname()
+
+ if r.URL.Port() != "" {
+ address += ":" + r.URL.Port()
+ }
+
+ return address
+}
diff --git a/app/pkg/web/ssl.go b/app/pkg/web/ssl.go
index 6b628bea5..223510369 100644
--- a/app/pkg/web/ssl.go
+++ b/app/pkg/web/ssl.go
@@ -8,9 +8,6 @@ import (
"golang.org/x/crypto/acme"
- "github.com/getfider/fider/app/pkg/blob"
- "github.com/getfider/fider/app/pkg/dbx"
- "github.com/getfider/fider/app/pkg/di"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
"golang.org/x/crypto/acme/autocert"
@@ -48,11 +45,11 @@ type CertificateManager struct {
}
//NewCertificateManager creates a new CertificateManager
-func NewCertificateManager(certFile, keyFile string, db *dbx.Database) (*CertificateManager, error) {
+func NewCertificateManager(certFile, keyFile string) (*CertificateManager, error) {
manager := &CertificateManager{
autossl: autocert.Manager{
Prompt: autocert.AcceptTOS,
- Cache: blob.NewAutoCert(di.NewBlobStorage(db)),
+ Cache: NewAutoCertCache(),
Client: acmeClient(),
},
}
diff --git a/app/pkg/web/ssl_test.go b/app/pkg/web/ssl_test.go
index fc374b743..6704d0278 100644
--- a/app/pkg/web/ssl_test.go
+++ b/app/pkg/web/ssl_test.go
@@ -4,7 +4,6 @@ import (
"crypto/tls"
"testing"
- "github.com/getfider/fider/app/pkg/dbx"
"github.com/getfider/fider/app/pkg/env"
. "github.com/getfider/fider/app/pkg/assert"
@@ -12,8 +11,6 @@ import (
func Test_GetCertificate(t *testing.T) {
RegisterT(t)
- db := dbx.New()
- defer db.Close()
var testCases = []struct {
mode string
@@ -37,7 +34,7 @@ func Test_GetCertificate(t *testing.T) {
keyFile := env.Path("/app/pkg/web/testdata/" + testCase.cert + ".key")
wildcardCert, _ := tls.LoadX509KeyPair(certFile, keyFile)
- manager, err := NewCertificateManager(certFile, keyFile, db)
+ manager, err := NewCertificateManager(certFile, keyFile)
Expect(err).IsNil()
cert, err := manager.GetCertificate(&tls.ClientHelloInfo{
ServerName: testCase.serverName,
@@ -52,22 +49,3 @@ func Test_GetCertificate(t *testing.T) {
}
}
}
-
-func Test_UseAutoCert(t *testing.T) {
- RegisterT(t)
- db := dbx.New()
- defer db.Close()
-
- manager, err := NewCertificateManager("", "", db)
- Expect(err).IsNil()
-
- invalidServerNames := []string{"ideas.app.com", "feedback.mysite.com"}
-
- for _, serverName := range invalidServerNames {
- cert, err := manager.GetCertificate(&tls.ClientHelloInfo{
- ServerName: serverName,
- })
- Expect(err.Error()).ContainsSubstring(`acme/autocert: unable to authorize "` + serverName + `"; challenge "tls-alpn-01" failed with error: acme: authorization error`)
- Expect(cert).IsNil()
- }
-}
diff --git a/app/pkg/web/testdata/oauth.html b/app/pkg/web/testdata/oauth.html
new file mode 100755
index 000000000..e422d290a
--- /dev/null
+++ b/app/pkg/web/testdata/oauth.html
@@ -0,0 +1,55 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8"/>
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <link rel="icon" href="https://demo.test.fider.io:3000/favicon?size=64" sizes="64x64" type="image/png">
+ <link rel="icon" href="https://demo.test.fider.io:3000/favicon?size=192" sizes="192x192" type="image/png">
+ <link rel="apple-touch-icon" href="https://demo.test.fider.io:3000/favicon?size=180&bg=white" sizes="180x180" type="image/png">
+
+
+
+ <link rel="stylesheet" href="https://demo.test.fider.io:3000/assets/css/file1.css" />
+
+
+
+ <title>Fider</title>
+ <meta name="description" content="" />
+ <meta property="og:title" content="Fider" />
+ <meta property="og:description" content="" />
+ <meta property="og:type" content="website" />
+ <meta property="og:url" content="https://demo.test.fider.io:3000/" />
+ <meta property="og:image" content="https://getfider.com/images/logo-100x100.png">
+</head>
+<body>
+ <noscript class="container">
+ <div class="c-segment">
+ <h2>Please enable JavaScript</h2>
+ <p>This website relies on JavaScript-based technologies and services.</p>
+ <p>Please enable JavaScript and then reload the page.</p>
+ </div>
+ </noscript>
+
+
+
+ <div id="root"></div><div id="root-modal"></div><div id="root-toastify"></div>
+
+ <script id="server-data" type="application/json">
+
+ {"contextID":"CONTEXT_ID","props":null,"settings":{"baseURL":"https://demo.test.fider.io:3000","buildTime":"","compiler":"","domain":"","environment":"","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":false,"mode":"","oauth":[{"provider":"google","displayName":"Google","clientID":"1234","url":"https://demo.test.fider.io:3000/oauth/google","callbackURL":"https://demo.test.fider.io:3000/oauth/google/callback","logoBlobKey":"google.png","isCustomProvider":false,"isEnabled":true}],"stripePublicKey":"","tenantAssetsURL":"https://demo.test.fider.io:3000","version":""},"tenant":null,"title":"Fider"}
+
+ </script>
+ <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=es6,fetch" crossorigin="anonymous"></script>
+
+
+
+ <script src="https://demo.test.fider.io:3000/assets/js/file1.js" crossorigin="anonymous"></script>
+
+ <script src="https://demo.test.fider.io:3000/assets/js/file2.js" crossorigin="anonymous"></script>
+
+
+
+
+</body>
+</html>
diff --git a/app/pkg/web/util/webutil.go b/app/pkg/web/util/webutil.go
index b50bfa4f4..6ad3903ab 100644
--- a/app/pkg/web/util/webutil.go
+++ b/app/pkg/web/util/webutil.go
@@ -1,16 +1,13 @@
package webutil
import (
- "fmt"
"net/http"
"time"
"github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/blob"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/jwt"
- "github.com/getfider/fider/app/pkg/rand"
"github.com/getfider/fider/app/pkg/web"
)
@@ -33,18 +30,18 @@ func encode(user *models.User) string {
}
//AddAuthUserCookie generates Auth Token and adds a cookie
-func AddAuthUserCookie(ctx web.Context, user *models.User) {
+func AddAuthUserCookie(ctx *web.Context, user *models.User) {
AddAuthTokenCookie(ctx, encode(user))
}
//AddAuthTokenCookie adds given token to a cookie
-func AddAuthTokenCookie(ctx web.Context, token string) {
+func AddAuthTokenCookie(ctx *web.Context, token string) {
expiresAt := time.Now().Add(365 * 24 * time.Hour)
ctx.AddCookie(web.CookieAuthName, token, expiresAt)
}
//SetSignUpAuthCookie sets a temporary domain-wide Auth Token
-func SetSignUpAuthCookie(ctx web.Context, user *models.User) {
+func SetSignUpAuthCookie(ctx *web.Context, user *models.User) {
http.SetCookie(ctx.Response, &http.Cookie{
Name: web.CookieSignUpAuthName,
Domain: env.MultiTenantDomain(),
@@ -57,7 +54,7 @@ func SetSignUpAuthCookie(ctx web.Context, user *models.User) {
}
//GetSignUpAuthCookie returns the temporary temporary domain-wide Auth Token and removes it
-func GetSignUpAuthCookie(ctx web.Context) string {
+func GetSignUpAuthCookie(ctx *web.Context) string {
cookie, err := ctx.Request.Cookie(web.CookieSignUpAuthName)
if err == nil {
http.SetCookie(ctx.Response, &http.Cookie{
@@ -73,44 +70,3 @@ func GetSignUpAuthCookie(ctx web.Context) string {
}
return ""
}
-
-// GetOAuthBaseURL returns the OAuth base URL used for host-wide OAuth authentication
-// For Single Tenant HostMode, BaseURL is the current BaseURL
-// For Multi Tenant HostMode, BaseURL is //login.{HOST_DOMAIN}
-func GetOAuthBaseURL(ctx web.Context) string {
- if env.IsSingleHostMode() {
- return ctx.BaseURL()
- }
-
- oauthBaseURL := ctx.Request.URL.Scheme + "://login" + env.MultiTenantDomain()
- port := ctx.Request.URL.Port()
- if port != "" {
- oauthBaseURL += ":" + port
- }
-
- return oauthBaseURL
-}
-
-// ProcessMultiImageUpload uploads multiple image to blob (if it's a new one)
-func ProcessMultiImageUpload(c web.Context, imgs []*models.ImageUpload, preffix string) error {
- for _, img := range imgs {
- err := ProcessImageUpload(c, img, preffix)
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-// ProcessImageUpload uploads image to blob (if it's a new one)
-func ProcessImageUpload(c web.Context, img *models.ImageUpload, preffix string) error {
- if img.Upload != nil && len(img.Upload.Content) > 0 {
- bkey := fmt.Sprintf("%s/%s-%s", preffix, rand.String(64), blob.SanitizeFileName(img.Upload.FileName))
- err := c.Services().Blobs.Put(bkey, img.Upload.Content, img.Upload.ContentType)
- if err != nil {
- return errors.Wrap(err, "failed to upload new blob")
- }
- img.BlobKey = bkey
- }
- return nil
-}
diff --git a/app/pkg/web/util/webutil_test.go b/app/pkg/web/util/webutil_test.go
deleted file mode 100644
index c410ba7e7..000000000
--- a/app/pkg/web/util/webutil_test.go
+++ /dev/null
@@ -1,106 +0,0 @@
-package webutil_test
-
-import (
- "io/ioutil"
- "net/url"
- "testing"
-
- "github.com/getfider/fider/app"
- "github.com/getfider/fider/app/pkg/di"
-
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/env"
- webutil "github.com/getfider/fider/app/pkg/web/util"
-
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/web"
-)
-
-func newContext(rawurl string) web.Context {
- url, _ := url.Parse(rawurl)
-
- return web.Context{
- Request: web.Request{
- URL: url,
- },
- }
-}
-
-func TestGetOAuthBaseURL(t *testing.T) {
- RegisterT(t)
-
- ctx := newContext("https://mydomain.com/hello-world")
-
- env.Config.HostMode = "multi"
- Expect(webutil.GetOAuthBaseURL(ctx)).Equals("https://login.test.fider.io")
-
- env.Config.HostMode = "single"
- Expect(webutil.GetOAuthBaseURL(ctx)).Equals("https://mydomain.com")
-}
-
-func TestGetOAuthBaseURL_WithPort(t *testing.T) {
- RegisterT(t)
-
- ctx := newContext("http://demo.test.fider.io:3000/hello-world")
-
- env.Config.HostMode = "multi"
- Expect(webutil.GetOAuthBaseURL(ctx)).Equals("http://login.test.fider.io:3000")
-
- env.Config.HostMode = "single"
- Expect(webutil.GetOAuthBaseURL(ctx)).Equals("http://demo.test.fider.io:3000")
-}
-
-func TestProcessImageUpload(t *testing.T) {
- RegisterT(t)
-
- img, _ := ioutil.ReadFile(env.Path("/app/pkg/web/testdata/logo3-200w.gif"))
- services := &app.Services{
- Blobs: di.NewBlobStorage(nil),
- }
- ctx := newContext("http://demo.test.fider.io:3000/hello-world")
- ctx.SetServices(services)
-
- upload := &models.ImageUpload{
- Upload: &models.ImageUploadData{
- Content: img,
- ContentType: "image/gif",
- },
- }
- err := webutil.ProcessImageUpload(ctx, upload, "attachments")
- Expect(err).IsNil()
- Expect(upload.BlobKey).ContainsSubstring("attachments/")
-
- blob, err := services.Blobs.Get(upload.BlobKey)
- Expect(err).IsNil()
- Expect(blob.ContentType).Equals("image/gif")
- Expect(blob.Object).Equals(img)
- Expect(int(blob.Size)).Equals(len(img))
-}
-
-func TestMultiProcessImageUpload(t *testing.T) {
- RegisterT(t)
-
- img, _ := ioutil.ReadFile(env.Path("/app/pkg/web/testdata/logo3-200w.gif"))
- services := &app.Services{
- Blobs: di.NewBlobStorage(nil),
- }
- ctx := newContext("http://demo.test.fider.io:3000/hello-world")
- ctx.SetServices(services)
-
- upload1 := &models.ImageUpload{
- Upload: &models.ImageUploadData{
- Content: img,
- ContentType: "image/gif",
- },
- }
- upload2 := &models.ImageUpload{
- Upload: &models.ImageUploadData{
- Content: img,
- ContentType: "image/gif",
- },
- }
- err := webutil.ProcessMultiImageUpload(ctx, []*models.ImageUpload{upload1, upload2}, "attachments")
- Expect(err).IsNil()
- Expect(upload1.BlobKey).ContainsSubstring("attachments/")
- Expect(upload2.BlobKey).ContainsSubstring("attachments/")
-}
diff --git a/app/pkg/worker/context.go b/app/pkg/worker/context.go
index 0bd45a511..696382412 100644
--- a/app/pkg/worker/context.go
+++ b/app/pkg/worker/context.go
@@ -1,11 +1,11 @@
package worker
import (
- "fmt"
+ "context"
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/models/dto"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/rand"
@@ -13,78 +13,34 @@ import (
//Context holds references to services available for jobs
type Context struct {
- workerID string
- taskName string
- services *app.Services
- logger log.Logger
- db *dbx.Database
- baseURL string
- logoURL string
- assetsBaseURL string
- user *models.User
- tenant *models.Tenant
+ context.Context
+ workerID string
+ taskName string
}
//NewContext creates a new context
-func NewContext(workerID string, task Task, db *dbx.Database, logger log.Logger) *Context {
- ctxLogger := logger.New()
- contextID := rand.String(32)
-
- ctxLogger.SetProperty(log.PropertyKeyContextID, contextID)
- if task.OriginSessionID != "" {
- ctxLogger.SetProperty(log.PropertyKeySessionID, task.OriginSessionID)
+func NewContext(ctx context.Context, workerID string, task Task) *Context {
+ ctx = log.WithProperty(ctx, log.PropertyKeyContextID, rand.String(32))
+
+ if task.OriginContext != nil {
+ ctx = context.WithValue(ctx, app.RequestCtxKey, task.OriginContext.Value(app.RequestCtxKey))
+ ctx = context.WithValue(ctx, app.TenantCtxKey, task.OriginContext.Value(app.TenantCtxKey))
+ ctx = context.WithValue(ctx, app.UserCtxKey, task.OriginContext.Value(app.UserCtxKey))
+
+ ctx = log.WithProperties(ctx, dto.Props{
+ log.PropertyKeySessionID: log.GetProperty(task.OriginContext, log.PropertyKeySessionID),
+ log.PropertyKeyUserID: log.GetProperty(task.OriginContext, log.PropertyKeyUserID),
+ log.PropertyKeyTenantID: log.GetProperty(task.OriginContext, log.PropertyKeyTenantID),
+ })
}
return &Context{
+ Context: ctx,
workerID: workerID,
taskName: task.Name,
- db: db,
- logger: ctxLogger,
- }
-}
-
-//SetBaseURL on context
-func (c *Context) SetBaseURL(baseURL string) {
- c.baseURL = baseURL
-}
-
-//SetLogoURL on context
-func (c *Context) SetLogoURL(logoURL string) {
- c.logoURL = logoURL
-}
-
-//SetAssetsBaseURL on context
-func (c *Context) SetAssetsBaseURL(assetsBaseURL string) {
- c.assetsBaseURL = assetsBaseURL
-}
-
-//SetUser on context
-func (c *Context) SetUser(user *models.User) {
- c.user = user
- if user != nil {
- c.logger.SetProperty(log.PropertyKeyUserID, user.ID)
- }
- if c.services != nil {
- c.services.SetCurrentUser(user)
- }
-}
-
-//SetTenant on context
-func (c *Context) SetTenant(tenant *models.Tenant) {
- c.tenant = tenant
- if tenant != nil {
- c.logger.SetProperty(log.PropertyKeyTenantID, tenant.ID)
- }
- if c.services != nil {
- c.services.SetCurrentTenant(tenant)
}
}
-//SetServices on current context
-func (c *Context) SetServices(services *app.Services) {
- c.services = services
-}
-
//WorkerID executing current context
func (c *Context) WorkerID() string {
return c.workerID
@@ -95,50 +51,32 @@ func (c *Context) TaskName() string {
return c.taskName
}
-//BaseURL from current context
-func (c Context) BaseURL() string {
- return c.baseURL
+// Set saves data in the context.
+func (c *Context) Set(key interface{}, val interface{}) {
+ c.Context = context.WithValue(c.Context, key, val)
}
//User from current context
func (c *Context) User() *models.User {
- return c.user
+ user, ok := c.Value(app.UserCtxKey).(*models.User)
+ if ok {
+ return user
+ }
+ return nil
}
//Tenant from current context
func (c *Context) Tenant() *models.Tenant {
- return c.tenant
-}
-
-//Services from current context
-func (c *Context) Services() *app.Services {
- return c.services
-}
-
-//Logger from current context
-func (c *Context) Logger() log.Logger {
- return c.logger
-}
-
-//Database from current context
-func (c *Context) Database() *dbx.Database {
- return c.db
+ tenant, ok := c.Value(app.TenantCtxKey).(*models.Tenant)
+ if ok {
+ return tenant
+ }
+ return nil
}
//Failure logs details of error
func (c *Context) Failure(err error) error {
err = errors.StackN(err, 1)
- c.logger.Error(err)
+ log.Error(c, err)
return err
}
-
-// LogoURL return the full URL to the tenant-specific logo URL
-func (c Context) LogoURL() string {
- return c.logoURL
-}
-
-// TenantAssetsURL return the full URL to a tenant-specific static asset
-func (c Context) TenantAssetsURL(path string, a ...interface{}) string {
- path = fmt.Sprintf(path, a...)
- return c.assetsBaseURL + path
-}
diff --git a/app/pkg/worker/worker.go b/app/pkg/worker/worker.go
index 616e3ebb6..ce27afdb5 100644
--- a/app/pkg/worker/worker.go
+++ b/app/pkg/worker/worker.go
@@ -6,8 +6,9 @@ import (
"sync"
"time"
- "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/models/dto"
"github.com/getfider/fider/app/pkg/log"
+ "github.com/getfider/fider/app/pkg/rand"
)
//MiddlewareFunc is worker middleware
@@ -18,16 +19,15 @@ type Job func(c *Context) error
//Task represents the Name and Job to be run on background
type Task struct {
- OriginSessionID string
- Name string
- Job Job
+ OriginContext context.Context
+ Name string
+ Job Job
}
//Worker is a process that runs tasks
type Worker interface {
Run(id string)
Enqueue(task Task)
- Logger() log.Logger
Use(middleware MiddlewareFunc)
Length() int64
Shutdown(ctx context.Context) error
@@ -35,8 +35,7 @@ type Worker interface {
//BackgroundWorker is a worker that runs tasks on background
type BackgroundWorker struct {
- db *dbx.Database
- logger log.Logger
+ context.Context
queue chan Task
len int64
middleware MiddlewareFunc
@@ -46,11 +45,17 @@ type BackgroundWorker struct {
var maxQueueSize = 100
//New creates a new BackgroundWorker
-func New(db *dbx.Database, logger log.Logger) *BackgroundWorker {
+func New() *BackgroundWorker {
+ ctx := context.Background()
+
+ ctx = log.WithProperties(ctx, dto.Props{
+ log.PropertyKeyContextID: rand.String(32),
+ log.PropertyKeyTag: "BGW",
+ })
+
return &BackgroundWorker{
- db: db,
- logger: logger,
- queue: make(chan Task, maxQueueSize),
+ Context: ctx,
+ queue: make(chan Task, maxQueueSize),
middleware: func(next Job) Job {
return next
},
@@ -59,11 +64,11 @@ func New(db *dbx.Database, logger log.Logger) *BackgroundWorker {
//Run initializes the worker loop
func (w *BackgroundWorker) Run(workerID string) {
- w.logger.Infof("Starting worker @{WorkerID:magenta}.", log.Props{
+ log.Infof(w, "Starting worker @{WorkerID:magenta}.", dto.Props{
"WorkerID": workerID,
})
for task := range w.queue {
- c := NewContext(workerID, task, w.db, w.logger)
+ c := NewContext(w, workerID, task)
w.middleware(task.Job)(c)
w.Lock()
@@ -83,7 +88,7 @@ func (w *BackgroundWorker) Shutdown(ctx context.Context) error {
return nil
}
- w.logger.Infof("Waiting for work queue: @{Count}", log.Props{
+ log.Infof(w, "Waiting for work queue: @{Count}", dto.Props{
"Count": count,
})
@@ -105,11 +110,6 @@ func (w *BackgroundWorker) Enqueue(task Task) {
w.queue <- task
}
-//Logger from current worker
-func (w *BackgroundWorker) Logger() log.Logger {
- return w.logger
-}
-
//Length from current queue length
func (w *BackgroundWorker) Length() int64 {
w.RLock()
diff --git a/app/pkg/worker/worker_test.go b/app/pkg/worker/worker_test.go
index abbbd9ffc..07e303aaa 100644
--- a/app/pkg/worker/worker_test.go
+++ b/app/pkg/worker/worker_test.go
@@ -6,17 +6,13 @@ import (
"testing"
"time"
- "github.com/getfider/fider/app/pkg/log/noop"
- "github.com/getfider/fider/app/pkg/rand"
-
"github.com/getfider/fider/app/pkg/worker"
. "github.com/getfider/fider/app/pkg/assert"
)
var dummyTask = worker.Task{
- OriginSessionID: rand.String(32),
- Name: "Do Something",
+ Name: "Do Something",
Job: func(c *worker.Context) error {
return nil
},
@@ -28,10 +24,10 @@ func TestBackgroundWorker(t *testing.T) {
var finished bool
mu := &sync.RWMutex{}
- w := worker.New(nil, noop.NewLogger())
+ w := worker.New()
w.Enqueue(worker.Task{
Name: "Do Something",
- Job: func(c *worker.Context) error {
+ Job: func(ctx *worker.Context) error {
mu.Lock()
defer mu.Unlock()
finished = true
@@ -54,7 +50,7 @@ func TestBackgroundWorker_ShutdownWhenEmpty(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
- w := worker.New(nil, noop.NewLogger())
+ w := worker.New()
Expect(w.Shutdown(ctx)).IsNil()
}
@@ -64,7 +60,7 @@ func TestBackgroundWorker_ShutdownWithStuckTasks(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
- w := worker.New(nil, noop.NewLogger())
+ w := worker.New()
w.Enqueue(dummyTask)
Expect(w.Shutdown(ctx)).IsNotNil()
}
@@ -75,7 +71,7 @@ func TestBackgroundWorker_ShutdownWithRunningTasks(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
- w := worker.New(nil, noop.NewLogger())
+ w := worker.New()
w.Enqueue(dummyTask)
go w.Run("worker-1")
Expect(w.Shutdown(ctx)).IsNil()
diff --git a/app/services.go b/app/services.go
deleted file mode 100644
index f768752ae..000000000
--- a/app/services.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package app
-
-import (
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/billing"
- "github.com/getfider/fider/app/pkg/blob"
- "github.com/getfider/fider/app/pkg/email"
- "github.com/getfider/fider/app/pkg/log"
- "github.com/getfider/fider/app/pkg/oauth"
- "github.com/getfider/fider/app/storage"
-)
-
-// Services holds reference to all Fider services
-type Services struct {
- Logger log.Logger
- OAuth oauth.Service
- Users storage.User
- Tags storage.Tag
- Tenants storage.Tenant
- Notifications storage.Notification
- Posts storage.Post
- Emailer email.Sender
- Blobs blob.Storage
- Billing *billing.Client
-}
-
-// SetCurrentTenant to current context
-func (s *Services) SetCurrentTenant(tenant *models.Tenant) {
- s.Users.SetCurrentTenant(tenant)
- s.Tags.SetCurrentTenant(tenant)
- s.Tenants.SetCurrentTenant(tenant)
- s.Posts.SetCurrentTenant(tenant)
- s.Notifications.SetCurrentTenant(tenant)
- s.Blobs.SetCurrentTenant(tenant)
- s.Billing.SetCurrentTenant(tenant)
-}
-
-// SetCurrentUser to current context
-func (s *Services) SetCurrentUser(user *models.User) {
- s.Users.SetCurrentUser(user)
- s.Tags.SetCurrentUser(user)
- s.Tenants.SetCurrentUser(user)
- s.Posts.SetCurrentUser(user)
- s.Notifications.SetCurrentUser(user)
- s.Billing.SetCurrentUser(user)
-}
diff --git a/app/services/billing/billing.go b/app/services/billing/billing.go
new file mode 100644
index 000000000..a170637aa
--- /dev/null
+++ b/app/services/billing/billing.go
@@ -0,0 +1,56 @@
+package billing
+
+import (
+ "context"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/stripe/stripe-go"
+ "github.com/stripe/stripe-go/client"
+)
+
+var stripeClient *client.API
+
+func init() {
+ bus.Register(Service{})
+}
+
+type Service struct{}
+
+func (s Service) Name() string {
+ return "Stripe"
+}
+
+func (s Service) Category() string {
+ return "billing"
+}
+
+func (s Service) Enabled() bool {
+ return env.IsBillingEnabled()
+}
+
+func (s Service) Init() {
+ stripe.LogLevel = 0
+ stripeClient = &client.API{}
+ stripeClient.Init(env.Config.Stripe.SecretKey, nil)
+
+ bus.AddHandler(listPlans)
+ bus.AddHandler(getPlanByID)
+ bus.AddHandler(cancelSubscription)
+ bus.AddHandler(subscribe)
+ bus.AddHandler(getUpcomingInvoice)
+ bus.AddHandler(createCustomer)
+ bus.AddHandler(deleteCustomer)
+ bus.AddHandler(getPaymentInfo)
+ bus.AddHandler(clearPaymentInfo)
+ bus.AddHandler(updatePaymentInfo)
+ bus.AddHandler(getAllCountries)
+ bus.AddHandler(getCountryByCode)
+}
+
+func using(ctx context.Context, handler func(tenant *models.Tenant) error) error {
+ tenant, _ := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ return handler(tenant)
+}
diff --git a/app/services/billing/billing_test.go b/app/services/billing/billing_test.go
new file mode 100644
index 000000000..0e35655e5
--- /dev/null
+++ b/app/services/billing/billing_test.go
@@ -0,0 +1,242 @@
+package billing_test
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/getfider/fider/app"
+
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/env"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/query"
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/services/billing"
+)
+
+func TestCreateCustomer_WithSubscription(t *testing.T) {
+ RegisterT(t)
+ if !env.IsBillingEnabled() {
+ return
+ }
+
+ bus.Init(billing.Service{})
+
+ tenant := &models.Tenant{
+ ID: 2,
+ Name: "Game Inc.",
+ Subdomain: "gameinc",
+ Billing: &models.TenantBilling{},
+ }
+ ctx := context.WithValue(context.Background(), app.TenantCtxKey, tenant)
+
+ err := bus.Dispatch(ctx, &cmd.CreateBillingCustomer{})
+ Expect(err).IsNil()
+ Expect(tenant.Billing.StripeCustomerID).IsNotEmpty()
+
+ err = bus.Dispatch(ctx, &cmd.UpdatePaymentInfo{
+ Input: &dto.CreateEditBillingPaymentInfo{
+ Email: "[email protected]",
+ Card: &dto.CreateEditBillingPaymentInfoCard{
+ Token: "tok_visa",
+ },
+ },
+ })
+ Expect(err).IsNil()
+
+ createSubscription := &cmd.CreateBillingSubscription{PlanID: "plan_EKTT1YWe1Zmrtp"}
+ err = bus.Dispatch(ctx, createSubscription)
+ Expect(err).IsNil()
+ Expect(tenant.Billing.StripeSubscriptionID).IsNotEmpty()
+ Expect(tenant.Billing.StripePlanID).Equals("plan_EKTT1YWe1Zmrtp")
+
+ invoiceQuery := &query.GetUpcomingInvoice{}
+ err = bus.Dispatch(ctx, invoiceQuery)
+ Expect(err).IsNil()
+ Expect(int(invoiceQuery.Result.AmountDue)).Equals(900)
+ Expect(invoiceQuery.Result.Currency).Equals("USD")
+
+ err = bus.Dispatch(ctx, &cmd.CancelBillingSubscription{})
+ Expect(err).IsNil()
+ Expect(tenant.Billing.SubscriptionEndsAt).IsNotNil()
+
+ err = bus.Dispatch(ctx, &cmd.DeleteBillingCustomer{})
+ Expect(err).IsNil()
+}
+
+var forUnitTestingTenant = &models.Tenant{
+ ID: 5,
+ Name: "For Unit Testing (DO NOT DELETE)",
+ Subdomain: "unittesting",
+ Billing: &models.TenantBilling{
+ StripeCustomerID: "cus_EICBuXBIkhI2EV",
+ },
+}
+
+func TestUpdatePaymentInfo(t *testing.T) {
+ RegisterT(t)
+ if !env.IsBillingEnabled() {
+ return
+ }
+
+ bus.Init(billing.Service{})
+
+ var firstCardID string
+
+ ctx := context.WithValue(context.Background(), app.TenantCtxKey, forUnitTestingTenant)
+
+ err := bus.Dispatch(ctx, &cmd.ClearPaymentInfo{})
+ Expect(err).IsNil()
+
+ //Creating a new card
+ err = bus.Dispatch(ctx, &cmd.UpdatePaymentInfo{
+ Input: &dto.CreateEditBillingPaymentInfo{
+ Email: "[email protected]",
+ VATNumber: "IE1234",
+ Card: &dto.CreateEditBillingPaymentInfoCard{
+ Token: "tok_visa",
+ },
+ AddressCountry: "IE",
+ },
+ })
+
+ paymentInfoQuery := &query.GetPaymentInfo{}
+ err = bus.Dispatch(ctx, paymentInfoQuery)
+ Expect(err).IsNil()
+ info := paymentInfoQuery.Result
+
+ firstCardID = info.StripeCardID
+
+ Expect(info.StripeCardID).IsNotEmpty()
+ Expect(info.Email).Equals("[email protected]")
+ Expect(info.VATNumber).Equals("IE1234")
+ Expect(info.CardBrand).Equals("Visa")
+ Expect(info.CardCountry).Equals("US")
+ Expect(info.CardLast4).Equals("4242")
+ Expect(int(info.CardExpMonth)).Equals(int(time.Now().Month()))
+ Expect(int(info.CardExpYear)).Equals(time.Now().Year() + 1)
+ Expect(info.Name).Equals("")
+ Expect(info.AddressLine1).Equals("")
+ Expect(info.AddressLine2).Equals("")
+ Expect(info.AddressCity).Equals("")
+ Expect(info.AddressState).Equals("")
+ Expect(info.AddressPostalCode).Equals("")
+ Expect(info.AddressCountry).Equals("")
+
+ //Update existing card
+ err = bus.Dispatch(ctx, &cmd.UpdatePaymentInfo{
+ Input: &dto.CreateEditBillingPaymentInfo{
+ Email: "[email protected]",
+ Name: "Jon Snow",
+ AddressLine1: "Street 1",
+ AddressLine2: "Av. ABC",
+ AddressCity: "New York",
+ AddressState: "NYC",
+ AddressPostalCode: "12098",
+ AddressCountry: "US",
+ },
+ })
+ Expect(err).IsNil()
+
+ paymentInfoQuery = &query.GetPaymentInfo{}
+ err = bus.Dispatch(ctx, paymentInfoQuery)
+ Expect(err).IsNil()
+ info = paymentInfoQuery.Result
+
+ Expect(info.Name).Equals("Jon Snow")
+ Expect(info.VATNumber).Equals("")
+ Expect(info.CardLast4).Equals("4242")
+ Expect(info.AddressLine1).Equals("Street 1")
+ Expect(info.AddressLine2).Equals("Av. ABC")
+ Expect(info.AddressCity).Equals("New York")
+ Expect(info.AddressState).Equals("NYC")
+ Expect(info.AddressPostalCode).Equals("12098")
+ Expect(info.AddressCountry).Equals("US")
+
+ //Replace card
+ err = bus.Dispatch(ctx, &cmd.UpdatePaymentInfo{
+ Input: &dto.CreateEditBillingPaymentInfo{
+ Email: "[email protected]",
+ Card: &dto.CreateEditBillingPaymentInfoCard{
+ Token: "tok_br",
+ },
+ },
+ })
+ Expect(err).IsNil()
+
+ paymentInfoQuery = &query.GetPaymentInfo{}
+ err = bus.Dispatch(ctx, paymentInfoQuery)
+ Expect(err).IsNil()
+ info = paymentInfoQuery.Result
+
+ Expect(info.StripeCardID).IsNotEmpty()
+ Expect(info.StripeCardID).NotEquals(firstCardID)
+ Expect(info.Email).Equals("[email protected]")
+ Expect(info.VATNumber).Equals("")
+ Expect(info.CardBrand).Equals("Visa")
+ Expect(info.CardCountry).Equals("BR")
+ Expect(info.CardLast4).Equals("0002")
+ Expect(int(info.CardExpMonth)).Equals(int(time.Now().Month()))
+ Expect(int(info.CardExpYear)).Equals(time.Now().Year() + 1)
+ Expect(info.Name).Equals("")
+ Expect(info.AddressLine1).Equals("")
+ Expect(info.AddressLine2).Equals("")
+ Expect(info.AddressCity).Equals("")
+ Expect(info.AddressState).Equals("")
+ Expect(info.AddressPostalCode).Equals("")
+ Expect(info.AddressCountry).Equals("")
+}
+
+func TestListPlans(t *testing.T) {
+ RegisterT(t)
+ if !env.IsBillingEnabled() {
+ return
+ }
+
+ bus.Init(billing.Service{})
+ ctx := context.Background()
+
+ q := &query.ListBillingPlans{CountryCode: "US"}
+ err := bus.Dispatch(ctx, q)
+ Expect(err).IsNil()
+ Expect(q.Result).HasLen(3)
+
+ Expect(q.Result[0].ID).Equals("plan_EKTT1YWe1Zmrtp")
+ Expect(q.Result[0].Name).Equals("Starter")
+ Expect(q.Result[0].Currency).Equals("USD")
+ Expect(q.Result[0].MaxUsers).Equals(200)
+
+ Expect(q.Result[1].ID).Equals("plan_DoK187GZcnFpKY")
+ Expect(q.Result[1].Name).Equals("Business (monthly)")
+ Expect(q.Result[1].Currency).Equals("USD")
+ Expect(q.Result[1].MaxUsers).Equals(0)
+
+ Expect(q.Result[2].ID).Equals("plan_DpN9SkJMjNTvLd")
+ Expect(q.Result[2].Name).Equals("Business (yearly)")
+ Expect(q.Result[2].Currency).Equals("USD")
+ Expect(q.Result[2].MaxUsers).Equals(0)
+
+ q = &query.ListBillingPlans{CountryCode: "DE"}
+ err = bus.Dispatch(ctx, q)
+ Expect(err).IsNil()
+ Expect(q.Result).HasLen(3)
+
+ Expect(q.Result[0].ID).Equals("plan_EKTSnrGmj5BuKI")
+ Expect(q.Result[0].Name).Equals("Starter")
+ Expect(q.Result[0].Currency).Equals("EUR")
+
+ Expect(q.Result[0].MaxUsers).Equals(200)
+ Expect(q.Result[1].ID).Equals("plan_EKPnahGhiTEnCc")
+ Expect(q.Result[1].Name).Equals("Business (monthly)")
+ Expect(q.Result[1].Currency).Equals("EUR")
+ Expect(q.Result[1].MaxUsers).Equals(0)
+
+ Expect(q.Result[2].ID).Equals("plan_EKTU4xD7LNI9dO")
+ Expect(q.Result[2].Name).Equals("Business (yearly)")
+ Expect(q.Result[2].Currency).Equals("EUR")
+ Expect(q.Result[2].MaxUsers).Equals(0)
+}
diff --git a/app/services/billing/country.go b/app/services/billing/country.go
new file mode 100644
index 000000000..7f456421e
--- /dev/null
+++ b/app/services/billing/country.go
@@ -0,0 +1,278 @@
+package billing
+
+import (
+ "context"
+
+ "github.com/getfider/fider/app"
+
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/goenning/vat"
+)
+
+func getAllCountries(ctx context.Context, q *query.GetAllCountries) error {
+ q.Result = allCountries
+ return nil
+}
+
+func getCountryByCode(ctx context.Context, q *query.GetCountryByCode) error {
+ for _, c := range allCountries {
+ if c.Code == q.Code {
+ q.Result = c
+ return nil
+ }
+ }
+ return app.ErrNotFound
+}
+
+var allCountries = []*dto.Country{
+ &dto.Country{Code: "AF", Name: "Afghanistan", IsEU: vat.IsEU("AF")},
+ &dto.Country{Code: "AX", Name: "Åland Islands", IsEU: vat.IsEU("AX")},
+ &dto.Country{Code: "AL", Name: "Albania", IsEU: vat.IsEU("AL")},
+ &dto.Country{Code: "DZ", Name: "Algeria", IsEU: vat.IsEU("DZ")},
+ &dto.Country{Code: "AS", Name: "American Samoa", IsEU: vat.IsEU("AS")},
+ &dto.Country{Code: "AD", Name: "Andorra", IsEU: vat.IsEU("AD")},
+ &dto.Country{Code: "AO", Name: "Angola", IsEU: vat.IsEU("AO")},
+ &dto.Country{Code: "AI", Name: "Anguilla", IsEU: vat.IsEU("AI")},
+ &dto.Country{Code: "AQ", Name: "Antarctica", IsEU: vat.IsEU("AQ")},
+ &dto.Country{Code: "AG", Name: "Antigua and Barbuda", IsEU: vat.IsEU("AG")},
+ &dto.Country{Code: "AR", Name: "Argentina", IsEU: vat.IsEU("AR")},
+ &dto.Country{Code: "AM", Name: "Armenia", IsEU: vat.IsEU("AM")},
+ &dto.Country{Code: "AW", Name: "Aruba", IsEU: vat.IsEU("AW")},
+ &dto.Country{Code: "AU", Name: "Australia", IsEU: vat.IsEU("AU")},
+ &dto.Country{Code: "AT", Name: "Austria", IsEU: vat.IsEU("AT")},
+ &dto.Country{Code: "AZ", Name: "Azerbaijan", IsEU: vat.IsEU("AZ")},
+ &dto.Country{Code: "BS", Name: "Bahamas", IsEU: vat.IsEU("BS")},
+ &dto.Country{Code: "BH", Name: "Bahrain", IsEU: vat.IsEU("BH")},
+ &dto.Country{Code: "BD", Name: "Bangladesh", IsEU: vat.IsEU("BD")},
+ &dto.Country{Code: "BB", Name: "Barbados", IsEU: vat.IsEU("BB")},
+ &dto.Country{Code: "BY", Name: "Belarus", IsEU: vat.IsEU("BY")},
+ &dto.Country{Code: "BE", Name: "Belgium", IsEU: vat.IsEU("BE")},
+ &dto.Country{Code: "BZ", Name: "Belize", IsEU: vat.IsEU("BZ")},
+ &dto.Country{Code: "BJ", Name: "Benin", IsEU: vat.IsEU("BJ")},
+ &dto.Country{Code: "BM", Name: "Bermuda", IsEU: vat.IsEU("BM")},
+ &dto.Country{Code: "BT", Name: "Bhutan", IsEU: vat.IsEU("BT")},
+ &dto.Country{Code: "BO", Name: "Bolivia, Plurinational State of", IsEU: vat.IsEU("BO")},
+ &dto.Country{Code: "BQ", Name: "Bonaire, Sint Eustatius and Saba", IsEU: vat.IsEU("BQ")},
+ &dto.Country{Code: "BA", Name: "Bosnia and Herzegovina", IsEU: vat.IsEU("BA")},
+ &dto.Country{Code: "BW", Name: "Botswana", IsEU: vat.IsEU("BW")},
+ &dto.Country{Code: "BV", Name: "Bouvet Island", IsEU: vat.IsEU("BV")},
+ &dto.Country{Code: "BR", Name: "Brazil", IsEU: vat.IsEU("BR")},
+ &dto.Country{Code: "IO", Name: "British Indian Ocean Territory", IsEU: vat.IsEU("IO")},
+ &dto.Country{Code: "BN", Name: "Brunei Darussalam", IsEU: vat.IsEU("BN")},
+ &dto.Country{Code: "BG", Name: "Bulgaria", IsEU: vat.IsEU("BG")},
+ &dto.Country{Code: "BF", Name: "Burkina Faso", IsEU: vat.IsEU("BF")},
+ &dto.Country{Code: "BI", Name: "Burundi", IsEU: vat.IsEU("BI")},
+ &dto.Country{Code: "KH", Name: "Cambodia", IsEU: vat.IsEU("KH")},
+ &dto.Country{Code: "CM", Name: "Cameroon", IsEU: vat.IsEU("CM")},
+ &dto.Country{Code: "CA", Name: "Canada", IsEU: vat.IsEU("CA")},
+ &dto.Country{Code: "CV", Name: "Cape Verde", IsEU: vat.IsEU("CV")},
+ &dto.Country{Code: "KY", Name: "Cayman Islands", IsEU: vat.IsEU("KY")},
+ &dto.Country{Code: "CF", Name: "Central African Republic", IsEU: vat.IsEU("CF")},
+ &dto.Country{Code: "TD", Name: "Chad", IsEU: vat.IsEU("TD")},
+ &dto.Country{Code: "CL", Name: "Chile", IsEU: vat.IsEU("CL")},
+ &dto.Country{Code: "CN", Name: "China", IsEU: vat.IsEU("CN")},
+ &dto.Country{Code: "CX", Name: "Christmas Island", IsEU: vat.IsEU("CX")},
+ &dto.Country{Code: "CC", Name: "Cocos (Keeling) Islands", IsEU: vat.IsEU("CC")},
+ &dto.Country{Code: "CO", Name: "Colombia", IsEU: vat.IsEU("CO")},
+ &dto.Country{Code: "KM", Name: "Comoros", IsEU: vat.IsEU("KM")},
+ &dto.Country{Code: "CG", Name: "Congo", IsEU: vat.IsEU("CG")},
+ &dto.Country{Code: "CD", Name: "Congo, the Democratic Republic of the", IsEU: vat.IsEU("CD")},
+ &dto.Country{Code: "CK", Name: "Cook Islands", IsEU: vat.IsEU("CK")},
+ &dto.Country{Code: "CR", Name: "Costa Rica", IsEU: vat.IsEU("CR")},
+ &dto.Country{Code: "CI", Name: "Côte d'Ivoire", IsEU: vat.IsEU("CI")},
+ &dto.Country{Code: "HR", Name: "Croatia", IsEU: vat.IsEU("HR")},
+ &dto.Country{Code: "CU", Name: "Cuba", IsEU: vat.IsEU("CU")},
+ &dto.Country{Code: "CW", Name: "Curaçao", IsEU: vat.IsEU("CW")},
+ &dto.Country{Code: "CY", Name: "Cyprus", IsEU: vat.IsEU("CY")},
+ &dto.Country{Code: "CZ", Name: "Czech Republic", IsEU: vat.IsEU("CZ")},
+ &dto.Country{Code: "DK", Name: "Denmark", IsEU: vat.IsEU("DK")},
+ &dto.Country{Code: "DJ", Name: "Djibouti", IsEU: vat.IsEU("DJ")},
+ &dto.Country{Code: "DM", Name: "Dominica", IsEU: vat.IsEU("DM")},
+ &dto.Country{Code: "DO", Name: "Dominican Republic", IsEU: vat.IsEU("DO")},
+ &dto.Country{Code: "EC", Name: "Ecuador", IsEU: vat.IsEU("EC")},
+ &dto.Country{Code: "EG", Name: "Egypt", IsEU: vat.IsEU("EG")},
+ &dto.Country{Code: "SV", Name: "El Salvador", IsEU: vat.IsEU("SV")},
+ &dto.Country{Code: "GQ", Name: "Equatorial Guinea", IsEU: vat.IsEU("GQ")},
+ &dto.Country{Code: "ER", Name: "Eritrea", IsEU: vat.IsEU("ER")},
+ &dto.Country{Code: "EE", Name: "Estonia", IsEU: vat.IsEU("EE")},
+ &dto.Country{Code: "ET", Name: "Ethiopia", IsEU: vat.IsEU("ET")},
+ &dto.Country{Code: "FK", Name: "Falkland Islands (Malvinas)", IsEU: vat.IsEU("FK")},
+ &dto.Country{Code: "FO", Name: "Faroe Islands", IsEU: vat.IsEU("FO")},
+ &dto.Country{Code: "FJ", Name: "Fiji", IsEU: vat.IsEU("FJ")},
+ &dto.Country{Code: "FI", Name: "Finland", IsEU: vat.IsEU("FI")},
+ &dto.Country{Code: "FR", Name: "France", IsEU: vat.IsEU("FR")},
+ &dto.Country{Code: "GF", Name: "French Guiana", IsEU: vat.IsEU("GF")},
+ &dto.Country{Code: "PF", Name: "French Polynesia", IsEU: vat.IsEU("PF")},
+ &dto.Country{Code: "TF", Name: "French Southern Territories", IsEU: vat.IsEU("TF")},
+ &dto.Country{Code: "GA", Name: "Gabon", IsEU: vat.IsEU("GA")},
+ &dto.Country{Code: "GM", Name: "Gambia", IsEU: vat.IsEU("GM")},
+ &dto.Country{Code: "GE", Name: "Georgia", IsEU: vat.IsEU("GE")},
+ &dto.Country{Code: "DE", Name: "Germany", IsEU: vat.IsEU("DE")},
+ &dto.Country{Code: "GH", Name: "Ghana", IsEU: vat.IsEU("GH")},
+ &dto.Country{Code: "GI", Name: "Gibraltar", IsEU: vat.IsEU("GI")},
+ &dto.Country{Code: "GR", Name: "Greece", IsEU: vat.IsEU("GR")},
+ &dto.Country{Code: "GL", Name: "Greenland", IsEU: vat.IsEU("GL")},
+ &dto.Country{Code: "GD", Name: "Grenada", IsEU: vat.IsEU("GD")},
+ &dto.Country{Code: "GP", Name: "Guadeloupe", IsEU: vat.IsEU("GP")},
+ &dto.Country{Code: "GU", Name: "Guam", IsEU: vat.IsEU("GU")},
+ &dto.Country{Code: "GT", Name: "Guatemala", IsEU: vat.IsEU("GT")},
+ &dto.Country{Code: "GG", Name: "Guernsey", IsEU: vat.IsEU("GG")},
+ &dto.Country{Code: "GN", Name: "Guinea", IsEU: vat.IsEU("GN")},
+ &dto.Country{Code: "GW", Name: "Guinea-Bissau", IsEU: vat.IsEU("GW")},
+ &dto.Country{Code: "GY", Name: "Guyana", IsEU: vat.IsEU("GY")},
+ &dto.Country{Code: "HT", Name: "Haiti", IsEU: vat.IsEU("HT")},
+ &dto.Country{Code: "HM", Name: "Heard Island and McDonald Islands", IsEU: vat.IsEU("HM")},
+ &dto.Country{Code: "VA", Name: "Holy See (Vatican City State)", IsEU: vat.IsEU("VA")},
+ &dto.Country{Code: "HN", Name: "Honduras", IsEU: vat.IsEU("HN")},
+ &dto.Country{Code: "HK", Name: "Hong Kong", IsEU: vat.IsEU("HK")},
+ &dto.Country{Code: "HU", Name: "Hungary", IsEU: vat.IsEU("HU")},
+ &dto.Country{Code: "IS", Name: "Iceland", IsEU: vat.IsEU("IS")},
+ &dto.Country{Code: "IN", Name: "India", IsEU: vat.IsEU("IN")},
+ &dto.Country{Code: "ID", Name: "Indonesia", IsEU: vat.IsEU("ID")},
+ &dto.Country{Code: "IR", Name: "Iran, Islamic Republic of", IsEU: vat.IsEU("IR")},
+ &dto.Country{Code: "IQ", Name: "Iraq", IsEU: vat.IsEU("IQ")},
+ &dto.Country{Code: "IE", Name: "Ireland", IsEU: vat.IsEU("IE")},
+ &dto.Country{Code: "IM", Name: "Isle of Man", IsEU: vat.IsEU("IM")},
+ &dto.Country{Code: "IL", Name: "Israel", IsEU: vat.IsEU("IL")},
+ &dto.Country{Code: "IT", Name: "Italy", IsEU: vat.IsEU("IT")},
+ &dto.Country{Code: "JM", Name: "Jamaica", IsEU: vat.IsEU("JM")},
+ &dto.Country{Code: "JP", Name: "Japan", IsEU: vat.IsEU("JP")},
+ &dto.Country{Code: "JE", Name: "Jersey", IsEU: vat.IsEU("JE")},
+ &dto.Country{Code: "JO", Name: "Jordan", IsEU: vat.IsEU("JO")},
+ &dto.Country{Code: "KZ", Name: "Kazakhstan", IsEU: vat.IsEU("KZ")},
+ &dto.Country{Code: "KE", Name: "Kenya", IsEU: vat.IsEU("KE")},
+ &dto.Country{Code: "KI", Name: "Kiribati", IsEU: vat.IsEU("KI")},
+ &dto.Country{Code: "KP", Name: "Korea, Democratic People's Republic of", IsEU: vat.IsEU("KP")},
+ &dto.Country{Code: "KR", Name: "Korea, Republic of", IsEU: vat.IsEU("KR")},
+ &dto.Country{Code: "KW", Name: "Kuwait", IsEU: vat.IsEU("KW")},
+ &dto.Country{Code: "KG", Name: "Kyrgyzstan", IsEU: vat.IsEU("KG")},
+ &dto.Country{Code: "LA", Name: "Lao People's Democratic Republic", IsEU: vat.IsEU("LA")},
+ &dto.Country{Code: "LV", Name: "Latvia", IsEU: vat.IsEU("LV")},
+ &dto.Country{Code: "LB", Name: "Lebanon", IsEU: vat.IsEU("LB")},
+ &dto.Country{Code: "LS", Name: "Lesotho", IsEU: vat.IsEU("LS")},
+ &dto.Country{Code: "LR", Name: "Liberia", IsEU: vat.IsEU("LR")},
+ &dto.Country{Code: "LY", Name: "Libya", IsEU: vat.IsEU("LY")},
+ &dto.Country{Code: "LI", Name: "Liechtenstein", IsEU: vat.IsEU("LI")},
+ &dto.Country{Code: "LT", Name: "Lithuania", IsEU: vat.IsEU("LT")},
+ &dto.Country{Code: "LU", Name: "Luxembourg", IsEU: vat.IsEU("LU")},
+ &dto.Country{Code: "MO", Name: "Macao", IsEU: vat.IsEU("MO")},
+ &dto.Country{Code: "MK", Name: "Macedonia, the former Yugoslav Republic of", IsEU: vat.IsEU("MK")},
+ &dto.Country{Code: "MG", Name: "Madagascar", IsEU: vat.IsEU("MG")},
+ &dto.Country{Code: "MW", Name: "Malawi", IsEU: vat.IsEU("MW")},
+ &dto.Country{Code: "MY", Name: "Malaysia", IsEU: vat.IsEU("MY")},
+ &dto.Country{Code: "MV", Name: "Maldives", IsEU: vat.IsEU("MV")},
+ &dto.Country{Code: "ML", Name: "Mali", IsEU: vat.IsEU("ML")},
+ &dto.Country{Code: "MT", Name: "Malta", IsEU: vat.IsEU("MT")},
+ &dto.Country{Code: "MH", Name: "Marshall Islands", IsEU: vat.IsEU("MH")},
+ &dto.Country{Code: "MQ", Name: "Martinique", IsEU: vat.IsEU("MQ")},
+ &dto.Country{Code: "MR", Name: "Mauritania", IsEU: vat.IsEU("MR")},
+ &dto.Country{Code: "MU", Name: "Mauritius", IsEU: vat.IsEU("MU")},
+ &dto.Country{Code: "YT", Name: "Mayotte", IsEU: vat.IsEU("YT")},
+ &dto.Country{Code: "MX", Name: "Mexico", IsEU: vat.IsEU("MX")},
+ &dto.Country{Code: "FM", Name: "Micronesia, Federated States of", IsEU: vat.IsEU("FM")},
+ &dto.Country{Code: "MD", Name: "Moldova, Republic of", IsEU: vat.IsEU("MD")},
+ &dto.Country{Code: "MC", Name: "Monaco", IsEU: vat.IsEU("MC")},
+ &dto.Country{Code: "MN", Name: "Mongolia", IsEU: vat.IsEU("MN")},
+ &dto.Country{Code: "ME", Name: "Montenegro", IsEU: vat.IsEU("ME")},
+ &dto.Country{Code: "MS", Name: "Montserrat", IsEU: vat.IsEU("MS")},
+ &dto.Country{Code: "MA", Name: "Morocco", IsEU: vat.IsEU("MA")},
+ &dto.Country{Code: "MZ", Name: "Mozambique", IsEU: vat.IsEU("MZ")},
+ &dto.Country{Code: "MM", Name: "Myanmar", IsEU: vat.IsEU("MM")},
+ &dto.Country{Code: "NA", Name: "Namibia", IsEU: vat.IsEU("NA")},
+ &dto.Country{Code: "NR", Name: "Nauru", IsEU: vat.IsEU("NR")},
+ &dto.Country{Code: "NP", Name: "Nepal", IsEU: vat.IsEU("NP")},
+ &dto.Country{Code: "NL", Name: "Netherlands", IsEU: vat.IsEU("NL")},
+ &dto.Country{Code: "NC", Name: "New Caledonia", IsEU: vat.IsEU("NC")},
+ &dto.Country{Code: "NZ", Name: "New Zealand", IsEU: vat.IsEU("NZ")},
+ &dto.Country{Code: "NI", Name: "Nicaragua", IsEU: vat.IsEU("NI")},
+ &dto.Country{Code: "NE", Name: "Niger", IsEU: vat.IsEU("NE")},
+ &dto.Country{Code: "NG", Name: "Nigeria", IsEU: vat.IsEU("NG")},
+ &dto.Country{Code: "NU", Name: "Niue", IsEU: vat.IsEU("NU")},
+ &dto.Country{Code: "NF", Name: "Norfolk Island", IsEU: vat.IsEU("NF")},
+ &dto.Country{Code: "MP", Name: "Northern Mariana Islands", IsEU: vat.IsEU("MP")},
+ &dto.Country{Code: "NO", Name: "Norway", IsEU: vat.IsEU("NO")},
+ &dto.Country{Code: "OM", Name: "Oman", IsEU: vat.IsEU("OM")},
+ &dto.Country{Code: "PK", Name: "Pakistan", IsEU: vat.IsEU("PK")},
+ &dto.Country{Code: "PW", Name: "Palau", IsEU: vat.IsEU("PW")},
+ &dto.Country{Code: "PS", Name: "Palestinian Territory, Occupied", IsEU: vat.IsEU("PS")},
+ &dto.Country{Code: "PA", Name: "Panama", IsEU: vat.IsEU("PA")},
+ &dto.Country{Code: "PG", Name: "Papua New Guinea", IsEU: vat.IsEU("PG")},
+ &dto.Country{Code: "PY", Name: "Paraguay", IsEU: vat.IsEU("PY")},
+ &dto.Country{Code: "PE", Name: "Peru", IsEU: vat.IsEU("PE")},
+ &dto.Country{Code: "PH", Name: "Philippines", IsEU: vat.IsEU("PH")},
+ &dto.Country{Code: "PN", Name: "Pitcairn", IsEU: vat.IsEU("PN")},
+ &dto.Country{Code: "PL", Name: "Poland", IsEU: vat.IsEU("PL")},
+ &dto.Country{Code: "PT", Name: "Portugal", IsEU: vat.IsEU("PT")},
+ &dto.Country{Code: "PR", Name: "Puerto Rico", IsEU: vat.IsEU("PR")},
+ &dto.Country{Code: "QA", Name: "Qatar", IsEU: vat.IsEU("QA")},
+ &dto.Country{Code: "RE", Name: "Réunion", IsEU: vat.IsEU("RE")},
+ &dto.Country{Code: "RO", Name: "Romania", IsEU: vat.IsEU("RO")},
+ &dto.Country{Code: "RU", Name: "Russian Federation", IsEU: vat.IsEU("RU")},
+ &dto.Country{Code: "RW", Name: "Rwanda", IsEU: vat.IsEU("RW")},
+ &dto.Country{Code: "BL", Name: "Saint Barthélemy", IsEU: vat.IsEU("BL")},
+ &dto.Country{Code: "SH", Name: "Saint Helena, Ascension and Tristan da Cunha", IsEU: vat.IsEU("SH")},
+ &dto.Country{Code: "KN", Name: "Saint Kitts and Nevis", IsEU: vat.IsEU("KN")},
+ &dto.Country{Code: "LC", Name: "Saint Lucia", IsEU: vat.IsEU("LC")},
+ &dto.Country{Code: "MF", Name: "Saint Martin (French part)", IsEU: vat.IsEU("MF")},
+ &dto.Country{Code: "PM", Name: "Saint Pierre and Miquelon", IsEU: vat.IsEU("PM")},
+ &dto.Country{Code: "VC", Name: "Saint Vincent and the Grenadines", IsEU: vat.IsEU("VC")},
+ &dto.Country{Code: "WS", Name: "Samoa", IsEU: vat.IsEU("WS")},
+ &dto.Country{Code: "SM", Name: "San Marino", IsEU: vat.IsEU("SM")},
+ &dto.Country{Code: "ST", Name: "Sao Tome and Principe", IsEU: vat.IsEU("ST")},
+ &dto.Country{Code: "SA", Name: "Saudi Arabia", IsEU: vat.IsEU("SA")},
+ &dto.Country{Code: "SN", Name: "Senegal", IsEU: vat.IsEU("SN")},
+ &dto.Country{Code: "RS", Name: "Serbia", IsEU: vat.IsEU("RS")},
+ &dto.Country{Code: "SC", Name: "Seychelles", IsEU: vat.IsEU("SC")},
+ &dto.Country{Code: "SL", Name: "Sierra Leone", IsEU: vat.IsEU("SL")},
+ &dto.Country{Code: "SG", Name: "Singapore", IsEU: vat.IsEU("SG")},
+ &dto.Country{Code: "SX", Name: "Sint Maarten (Dutch part)", IsEU: vat.IsEU("SX")},
+ &dto.Country{Code: "SK", Name: "Slovakia", IsEU: vat.IsEU("SK")},
+ &dto.Country{Code: "SI", Name: "Slovenia", IsEU: vat.IsEU("SI")},
+ &dto.Country{Code: "SB", Name: "Solomon Islands", IsEU: vat.IsEU("SB")},
+ &dto.Country{Code: "SO", Name: "Somalia", IsEU: vat.IsEU("SO")},
+ &dto.Country{Code: "ZA", Name: "South Africa", IsEU: vat.IsEU("ZA")},
+ &dto.Country{Code: "GS", Name: "South Georgia and the South Sandwich Islands", IsEU: vat.IsEU("GS")},
+ &dto.Country{Code: "SS", Name: "South Sudan", IsEU: vat.IsEU("SS")},
+ &dto.Country{Code: "ES", Name: "Spain", IsEU: vat.IsEU("ES")},
+ &dto.Country{Code: "LK", Name: "Sri Lanka", IsEU: vat.IsEU("LK")},
+ &dto.Country{Code: "SD", Name: "Sudan", IsEU: vat.IsEU("SD")},
+ &dto.Country{Code: "SR", Name: "Suriname", IsEU: vat.IsEU("SR")},
+ &dto.Country{Code: "SJ", Name: "Svalbard and Jan Mayen", IsEU: vat.IsEU("SJ")},
+ &dto.Country{Code: "SZ", Name: "Swaziland", IsEU: vat.IsEU("SZ")},
+ &dto.Country{Code: "SE", Name: "Sweden", IsEU: vat.IsEU("SE")},
+ &dto.Country{Code: "CH", Name: "Switzerland", IsEU: vat.IsEU("CH")},
+ &dto.Country{Code: "SY", Name: "Syrian Arab Republic", IsEU: vat.IsEU("SY")},
+ &dto.Country{Code: "TW", Name: "Taiwan, Province of China", IsEU: vat.IsEU("TW")},
+ &dto.Country{Code: "TJ", Name: "Tajikistan", IsEU: vat.IsEU("TJ")},
+ &dto.Country{Code: "TZ", Name: "Tanzania, United Republic of", IsEU: vat.IsEU("TZ")},
+ &dto.Country{Code: "TH", Name: "Thailand", IsEU: vat.IsEU("TH")},
+ &dto.Country{Code: "TL", Name: "Timor-Leste", IsEU: vat.IsEU("TL")},
+ &dto.Country{Code: "TG", Name: "Togo", IsEU: vat.IsEU("TG")},
+ &dto.Country{Code: "TK", Name: "Tokelau", IsEU: vat.IsEU("TK")},
+ &dto.Country{Code: "TO", Name: "Tonga", IsEU: vat.IsEU("TO")},
+ &dto.Country{Code: "TT", Name: "Trinidad and Tobago", IsEU: vat.IsEU("TT")},
+ &dto.Country{Code: "TN", Name: "Tunisia", IsEU: vat.IsEU("TN")},
+ &dto.Country{Code: "TR", Name: "Turkey", IsEU: vat.IsEU("TR")},
+ &dto.Country{Code: "TM", Name: "Turkmenistan", IsEU: vat.IsEU("TM")},
+ &dto.Country{Code: "TC", Name: "Turks and Caicos Islands", IsEU: vat.IsEU("TC")},
+ &dto.Country{Code: "TV", Name: "Tuvalu", IsEU: vat.IsEU("TV")},
+ &dto.Country{Code: "UG", Name: "Uganda", IsEU: vat.IsEU("UG")},
+ &dto.Country{Code: "UA", Name: "Ukraine", IsEU: vat.IsEU("UA")},
+ &dto.Country{Code: "AE", Name: "United Arab Emirates", IsEU: vat.IsEU("AE")},
+ &dto.Country{Code: "GB", Name: "United Kingdom", IsEU: vat.IsEU("GB")},
+ &dto.Country{Code: "US", Name: "United States", IsEU: vat.IsEU("US")},
+ &dto.Country{Code: "UM", Name: "United States Minor Outlying Islands", IsEU: vat.IsEU("UM")},
+ &dto.Country{Code: "UY", Name: "Uruguay", IsEU: vat.IsEU("UY")},
+ &dto.Country{Code: "UZ", Name: "Uzbekistan", IsEU: vat.IsEU("UZ")},
+ &dto.Country{Code: "VU", Name: "Vanuatu", IsEU: vat.IsEU("VU")},
+ &dto.Country{Code: "VE", Name: "Venezuela, Bolivarian Republic of", IsEU: vat.IsEU("VE")},
+ &dto.Country{Code: "VN", Name: "Viet Nam", IsEU: vat.IsEU("VN")},
+ &dto.Country{Code: "VG", Name: "Virgin Islands, British", IsEU: vat.IsEU("VG")},
+ &dto.Country{Code: "VI", Name: "Virgin Islands, U.S.", IsEU: vat.IsEU("VI")},
+ &dto.Country{Code: "WF", Name: "Wallis and Futuna", IsEU: vat.IsEU("WF")},
+ &dto.Country{Code: "EH", Name: "Western Sahara", IsEU: vat.IsEU("EH")},
+ &dto.Country{Code: "YE", Name: "Yemen", IsEU: vat.IsEU("YE")},
+ &dto.Country{Code: "ZM", Name: "Zambia", IsEU: vat.IsEU("ZM")},
+ &dto.Country{Code: "ZW", Name: "Zimbabwe", IsEU: vat.IsEU("ZW")},
+}
diff --git a/app/services/billing/customer.go b/app/services/billing/customer.go
new file mode 100644
index 000000000..8a3f2f8c1
--- /dev/null
+++ b/app/services/billing/customer.go
@@ -0,0 +1,230 @@
+package billing
+
+import (
+ "context"
+ "fmt"
+ "strconv"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/goenning/vat"
+ "github.com/stripe/stripe-go"
+)
+
+func createCustomer(ctx context.Context, c *cmd.CreateBillingCustomer) error {
+ return using(ctx, func(tenant *models.Tenant) error {
+ if tenant.Billing == nil {
+ return errors.New("Tenant doesn't have a billing record")
+ }
+
+ if tenant.Billing.StripeCustomerID == "" {
+ params := &stripe.CustomerParams{
+ Description: stripe.String(tenant.Name),
+ }
+ params.AddMetadata("tenant_id", strconv.Itoa(tenant.ID))
+ params.AddMetadata("tenant_subdomain", tenant.Subdomain)
+ customer, err := stripeClient.Customers.New(params)
+ if err != nil {
+ return errors.Wrap(err, "failed to create Stripe customer")
+ }
+
+ tenant.Billing.StripeCustomerID = customer.ID
+ return nil
+ }
+
+ return nil
+ })
+}
+
+func deleteCustomer(ctx context.Context, c *cmd.DeleteBillingCustomer) error {
+ return using(ctx, func(tenant *models.Tenant) error {
+ if !env.IsTest() {
+ return errors.New("Stripe customer can only be deleted on test mode")
+ }
+
+ _, err := stripeClient.Customers.Del(tenant.Billing.StripeCustomerID, &stripe.CustomerParams{})
+ if err != nil {
+ return errors.Wrap(err, "failed to delete Stripe customer")
+ }
+ return nil
+ })
+}
+
+func getPaymentInfo(ctx context.Context, q *query.GetPaymentInfo) error {
+ return using(ctx, func(tenant *models.Tenant) error {
+ if tenant.Billing == nil || tenant.Billing.StripeCustomerID == "" {
+ return nil
+ }
+
+ customerID := tenant.Billing.StripeCustomerID
+
+ customer, err := stripeClient.Customers.Get(customerID, &stripe.CustomerParams{})
+ if err != nil {
+ return errors.Wrap(err, "failed to get customer")
+ }
+
+ if customer.Metadata["tenant_id"] != strconv.Itoa(tenant.ID) {
+ panic(fmt.Sprintf("Stripe TenantID (%s) doesn't match current Tenant ID (%s). Aborting.", customer.Metadata["tenant_id"], strconv.Itoa(tenant.ID)))
+ }
+
+ if customer.DefaultSource == nil {
+ return nil
+ }
+
+ card, err := stripeClient.Cards.Get(customer.DefaultSource.ID, &stripe.CardParams{
+ Customer: stripe.String(customerID),
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to get customer's card")
+ }
+
+ q.Result = &dto.PaymentInfo{
+ Email: customer.Email,
+ Name: card.Name,
+ StripeCardID: card.ID,
+ CardCountry: card.Country,
+ CardBrand: string(card.Brand),
+ CardLast4: card.Last4,
+ CardExpMonth: card.ExpMonth,
+ CardExpYear: card.ExpYear,
+ AddressCity: card.AddressCity,
+ AddressCountry: card.AddressCountry,
+ AddressLine1: card.AddressLine1,
+ AddressLine2: card.AddressLine2,
+ AddressState: card.AddressState,
+ AddressPostalCode: card.AddressZip,
+ }
+
+ if customer.TaxInfo != nil {
+ q.Result.VATNumber = customer.TaxInfo.TaxID
+ }
+
+ return nil
+ })
+}
+
+func clearPaymentInfo(ctx context.Context, c *cmd.ClearPaymentInfo) error {
+ return using(ctx, func(tenant *models.Tenant) error {
+ currentInfo := &query.GetPaymentInfo{}
+ if err := getPaymentInfo(ctx, currentInfo); err != nil {
+ return err
+ }
+
+ if currentInfo.Result != nil {
+ customerID := tenant.Billing.StripeCustomerID
+ _, err := stripeClient.Customers.Update(customerID, &stripe.CustomerParams{
+ Description: stripe.String(tenant.Name),
+ Email: stripe.String(""),
+ TaxInfo: &stripe.CustomerTaxInfoParams{
+ Type: stripe.String(string(stripe.CustomerTaxInfoTypeVAT)),
+ TaxID: stripe.String(""),
+ },
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to delete customer billing email")
+ }
+ if currentInfo.Result.StripeCardID != "" {
+ _, err = stripeClient.Cards.Del(currentInfo.Result.StripeCardID, &stripe.CardParams{
+ Customer: stripe.String(customerID),
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to delete customer card")
+ }
+ }
+ }
+
+ return nil
+ })
+}
+
+func updatePaymentInfo(ctx context.Context, c *cmd.UpdatePaymentInfo) error {
+ return using(ctx, func(tenant *models.Tenant) error {
+ customerID := tenant.Billing.StripeCustomerID
+
+ currentInfo := &query.GetPaymentInfo{}
+ if err := getPaymentInfo(ctx, currentInfo); err != nil {
+ return err
+ }
+
+ if !vat.IsEU(c.Input.AddressCountry) {
+ c.Input.VATNumber = ""
+ }
+
+ // update customer info
+ params := &stripe.CustomerParams{
+ Email: stripe.String(c.Input.Email),
+ Description: stripe.String(c.Input.Name),
+ Shipping: &stripe.CustomerShippingDetailsParams{
+ Name: stripe.String(c.Input.Name),
+ Address: &stripe.AddressParams{
+ City: stripe.String(c.Input.AddressCity),
+ Country: stripe.String(c.Input.AddressCountry),
+ Line1: stripe.String(c.Input.AddressLine1),
+ Line2: stripe.String(c.Input.AddressLine2),
+ PostalCode: stripe.String(c.Input.AddressPostalCode),
+ State: stripe.String(c.Input.AddressState),
+ },
+ },
+ TaxInfo: &stripe.CustomerTaxInfoParams{
+ Type: stripe.String(string(stripe.CustomerTaxInfoTypeVAT)),
+ TaxID: stripe.String(c.Input.VATNumber),
+ },
+ }
+ _, err := stripeClient.Customers.Update(customerID, params)
+ if err != nil {
+ return errors.Wrap(err, "failed to update customer billing email")
+ }
+
+ // new card, just create it
+ if currentInfo.Result == nil || currentInfo.Result.StripeCardID == "" {
+ _, err = stripeClient.Cards.New(&stripe.CardParams{
+ Customer: stripe.String(customerID),
+ Token: stripe.String(c.Input.Card.Token),
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to create stripe card")
+ }
+ return nil
+ }
+
+ // replacing card, create new and delete old
+ if c.Input.Card != nil && c.Input.Card.Token != "" {
+ _, err = stripeClient.Cards.New(&stripe.CardParams{
+ Customer: stripe.String(customerID),
+ Token: stripe.String(c.Input.Card.Token),
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to create new stripe card")
+ }
+
+ _, err = stripeClient.Cards.Del(currentInfo.Result.StripeCardID, &stripe.CardParams{
+ Customer: stripe.String(customerID),
+ Token: stripe.String(c.Input.Card.Token),
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to delete old stripe card")
+ }
+ return nil
+ }
+
+ // updating card, just update current card
+ _, err = stripeClient.Cards.Update(currentInfo.Result.StripeCardID, &stripe.CardParams{
+ Customer: stripe.String(customerID),
+ Name: stripe.String(c.Input.Name),
+ AddressCity: stripe.String(c.Input.AddressCity),
+ AddressCountry: stripe.String(c.Input.AddressCountry),
+ AddressLine1: stripe.String(c.Input.AddressLine1),
+ AddressLine2: stripe.String(c.Input.AddressLine2),
+ AddressState: stripe.String(c.Input.AddressState),
+ AddressZip: stripe.String(c.Input.AddressPostalCode),
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to update stripe card")
+ }
+ return nil
+ })
+}
diff --git a/app/services/billing/plans.go b/app/services/billing/plans.go
new file mode 100644
index 000000000..9a9c1f291
--- /dev/null
+++ b/app/services/billing/plans.go
@@ -0,0 +1,92 @@
+package billing
+
+import (
+ "context"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/goenning/vat"
+ "github.com/stripe/stripe-go"
+)
+
+var plansMutex sync.RWMutex
+var allPlans []*dto.BillingPlan
+
+func listPlans(ctx context.Context, q *query.ListBillingPlans) error {
+ if allPlans != nil {
+ q.Result = filterPlansByCountryCode(allPlans, q.CountryCode)
+ return nil
+ }
+
+ plansMutex.Lock()
+ defer plansMutex.Unlock()
+
+ if allPlans == nil {
+ allPlans = make([]*dto.BillingPlan, 0)
+ it := stripeClient.Plans.List(&stripe.PlanListParams{
+ Active: stripe.Bool(true),
+ })
+ for it.Next() {
+ plan := it.Plan()
+ name, ok := plan.Metadata["friendly_name"]
+ if !ok {
+ name = plan.Nickname
+ }
+ maxUsers, _ := strconv.Atoi(plan.Metadata["max_users"])
+ allPlans = append(allPlans, &dto.BillingPlan{
+ ID: plan.ID,
+ Name: name,
+ Description: plan.Metadata["description"],
+ MaxUsers: maxUsers,
+ Price: plan.Amount,
+ Currency: strings.ToUpper(string(plan.Currency)),
+ Interval: string(plan.Interval),
+ })
+ }
+ if err := it.Err(); err != nil {
+ return err
+ }
+ sort.Slice(allPlans, func(i, j int) bool {
+ return allPlans[i].Price < allPlans[j].Price
+ })
+ }
+
+ q.Result = filterPlansByCountryCode(allPlans, q.CountryCode)
+ return nil
+}
+
+func getPlanByID(ctx context.Context, q *query.GetBillingPlanByID) error {
+ listPlansQuery := &query.ListBillingPlans{CountryCode: q.CountryCode}
+ err := listPlans(ctx, listPlansQuery)
+ if err != nil {
+ return err
+ }
+
+ for _, plan := range listPlansQuery.Result {
+ if plan.ID == q.PlanID {
+ q.Result = plan
+ return nil
+ }
+ }
+ return errors.New("failed to get plan by id '%s'", q.PlanID)
+}
+
+func filterPlansByCountryCode(plans []*dto.BillingPlan, countryCode string) []*dto.BillingPlan {
+ currency := "USD"
+ if vat.IsEU(countryCode) {
+ currency = "EUR"
+ }
+
+ filteredPlans := make([]*dto.BillingPlan, 0)
+ for _, p := range plans {
+ if p.Currency == currency {
+ filteredPlans = append(filteredPlans, p)
+ }
+ }
+ return filteredPlans
+}
diff --git a/app/services/billing/subscription.go b/app/services/billing/subscription.go
new file mode 100644
index 000000000..a35e8d44a
--- /dev/null
+++ b/app/services/billing/subscription.go
@@ -0,0 +1,98 @@
+package billing
+
+import (
+ "context"
+ "strings"
+ "time"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/stripe/stripe-go"
+)
+
+func cancelSubscription(ctx context.Context, c *cmd.CancelBillingSubscription) error {
+ return using(ctx, func(tenant *models.Tenant) error {
+ sub, err := stripeClient.Subscriptions.Update(tenant.Billing.StripeSubscriptionID, &stripe.SubscriptionParams{
+ CancelAtPeriodEnd: stripe.Bool(true),
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to cancel stripe subscription")
+ }
+ endDate := time.Unix(sub.CurrentPeriodEnd, 0)
+ tenant.Billing.SubscriptionEndsAt = &endDate
+ return nil
+ })
+}
+
+func subscribe(ctx context.Context, c *cmd.CreateBillingSubscription) error {
+ return using(ctx, func(tenant *models.Tenant) error {
+ customerID := tenant.Billing.StripeCustomerID
+ if tenant.Billing.StripeSubscriptionID != "" {
+ sub, err := stripeClient.Subscriptions.Get(tenant.Billing.StripeSubscriptionID, nil)
+ if err != nil {
+ return errors.Wrap(err, "failed to get stripe subscription")
+ }
+ _, err = stripeClient.Subscriptions.Update(tenant.Billing.StripeSubscriptionID, &stripe.SubscriptionParams{
+ CancelAtPeriodEnd: stripe.Bool(false),
+ Items: []*stripe.SubscriptionItemsParams{
+ {
+ ID: stripe.String(sub.Items.Data[0].ID),
+ Plan: stripe.String(c.PlanID),
+ },
+ },
+ })
+
+ if err != nil {
+ return errors.Wrap(err, "failed to update stripe subscription")
+ }
+
+ tenant.Billing.SubscriptionEndsAt = nil
+ } else {
+ sub, err := stripeClient.Subscriptions.New(&stripe.SubscriptionParams{
+ Customer: stripe.String(customerID),
+ Items: []*stripe.SubscriptionItemsParams{
+ {
+ Plan: stripe.String(c.PlanID),
+ },
+ },
+ })
+
+ if err != nil {
+ return errors.Wrap(err, "failed to create stripe subscription")
+ }
+
+ tenant.Billing.StripeSubscriptionID = sub.ID
+ }
+
+ tenant.Billing.StripePlanID = c.PlanID
+ return nil
+ })
+}
+
+func getUpcomingInvoice(ctx context.Context, q *query.GetUpcomingInvoice) error {
+ return using(ctx, func(tenant *models.Tenant) error {
+ inv, err := stripeClient.Invoices.GetNext(&stripe.InvoiceParams{
+ Customer: stripe.String(tenant.Billing.StripeCustomerID),
+ Subscription: stripe.String(tenant.Billing.StripeSubscriptionID),
+ })
+ if err != nil {
+ if stripeErr, ok := err.(*stripe.Error); ok {
+ if stripeErr.HTTPStatusCode == 404 {
+ return nil
+ }
+ }
+ return errors.Wrap(err, "failed to get upcoming invoice")
+ }
+
+ dueDate := time.Unix(inv.Date, 0)
+ q.Result = &dto.UpcomingInvoice{
+ Currency: strings.ToUpper(string(inv.Currency)),
+ AmountDue: inv.AmountDue,
+ DueDate: dueDate,
+ }
+ return nil
+ })
+}
diff --git a/app/pkg/blob/blob.go b/app/services/blob/blob.go
similarity index 69%
rename from app/pkg/blob/blob.go
rename to app/services/blob/blob.go
index 7532f9705..24bff40ee 100644
--- a/app/pkg/blob/blob.go
+++ b/app/services/blob/blob.go
@@ -5,18 +5,9 @@ import (
"path/filepath"
"strings"
- "github.com/getfider/fider/app/models"
"github.com/gosimple/slug"
)
-// Blob is a file persisted somewhere
-type Blob struct {
- Key string
- Object []byte
- Size int64
- ContentType string
-}
-
// ErrNotFound is returned when given blob is not found
var ErrNotFound = errors.New("Blob not found")
@@ -43,11 +34,3 @@ func ValidateKey(key string) error {
}
return nil
}
-
-// Storage is how Fider persists blobs
-type Storage interface {
- SetCurrentTenant(tenant *models.Tenant)
- Get(key string) (*Blob, error)
- Delete(key string) error
- Put(key string, content []byte, contentType string) error
-}
diff --git a/app/services/blob/blob_test.go b/app/services/blob/blob_test.go
new file mode 100644
index 000000000..a5be9cc05
--- /dev/null
+++ b/app/services/blob/blob_test.go
@@ -0,0 +1,284 @@
+package blob_test
+
+import (
+ "context"
+ "io/ioutil"
+ "os"
+ "testing"
+
+ "github.com/aws/aws-sdk-go/aws"
+ awss3 "github.com/aws/aws-sdk-go/service/s3"
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/rand"
+
+ "github.com/getfider/fider/app/models"
+
+ "github.com/getfider/fider/app/services/blob/fs"
+ "github.com/getfider/fider/app/services/blob/s3"
+ "github.com/getfider/fider/app/services/blob/sql"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/services/blob"
+)
+
+var tenant1 = &models.Tenant{ID: 1}
+var tenant2 = &models.Tenant{ID: 2}
+
+func setupS3(t *testing.T) {
+ RegisterT(t)
+
+ bus.Init(s3.Service{})
+
+ bucket := aws.String(env.Config.BlobStorage.S3.BucketName)
+ s3.DefaultClient.DeleteBucket(&awss3.DeleteBucketInput{
+ Bucket: bucket,
+ })
+ s3.DefaultClient.CreateBucket(&awss3.CreateBucketInput{
+ Bucket: bucket,
+ })
+}
+
+func setupSQL(t *testing.T) {
+ RegisterT(t)
+
+ dbx.Seed()
+
+ bus.Init(sql.Service{})
+}
+
+func setupFS(t *testing.T) {
+ RegisterT(t)
+
+ bus.Init(fs.Service{})
+
+ err := os.RemoveAll(env.Config.BlobStorage.FS.Path)
+ Expect(err).IsNil()
+}
+
+type blobTestCase func(ctx context.Context)
+
+var tests = []struct {
+ name string
+ test blobTestCase
+}{
+ {"AllOperations", AllOperations},
+ {"DeleteUnkownFile", DeleteUnkownFile},
+ {"KeyFormats", KeyFormats},
+ {"SameKey_DifferentTenant", SameKey_DifferentTenant},
+ {"SameKey_DifferentTenant_Delete", SameKey_DifferentTenant_Delete},
+}
+
+func TestBlobStorage(t *testing.T) {
+ for _, tt := range tests {
+ t.Run("Test_FS_"+tt.name, func(t *testing.T) {
+ setupFS(t)
+ tt.test(context.Background())
+ })
+
+ t.Run("Test_S3_"+tt.name, func(t *testing.T) {
+ setupS3(t)
+ tt.test(context.Background())
+ })
+
+ t.Run("Test_SQL_"+tt.name, func(t *testing.T) {
+ setupSQL(t)
+ tt.test(context.Background())
+ })
+ }
+}
+
+func AllOperations(ctx context.Context) {
+ var testCases = []struct {
+ localPath string
+ key string
+ contentType string
+ }{
+ {"/app/services/blob/testdata/file.txt", "some/path/to/file.txt", "text/plain; charset=utf-8"},
+ {"/app/services/blob/testdata/file2.png", "file2.png", "image/png"},
+ }
+
+ for _, testCase := range testCases {
+ bytes, _ := ioutil.ReadFile(env.Path(testCase.localPath))
+ err := bus.Dispatch(ctx, &cmd.StoreBlob{
+ Key: testCase.key,
+ Content: bytes,
+ ContentType: testCase.contentType,
+ })
+ Expect(err).IsNil()
+
+ q := &query.GetBlobByKey{
+ Key: testCase.key,
+ }
+ err = bus.Dispatch(ctx, q)
+ Expect(err).IsNil()
+ Expect(q.Key).Equals(testCase.key)
+ Expect(q.Result.Content).Equals(bytes)
+ Expect(q.Result.Size).Equals(int64(len(bytes)))
+ Expect(q.Result.ContentType).Equals(testCase.contentType)
+
+ err = bus.Dispatch(ctx, &cmd.DeleteBlob{
+ Key: testCase.key,
+ })
+ Expect(err).IsNil()
+
+ q = &query.GetBlobByKey{
+ Key: testCase.key,
+ }
+ err = bus.Dispatch(ctx, q)
+ Expect(q.Result).IsNil()
+ Expect(err).Equals(blob.ErrNotFound)
+ }
+}
+
+func DeleteUnkownFile(ctx context.Context) {
+ err := bus.Dispatch(ctx, &cmd.DeleteBlob{
+ Key: "path/somefile.txt",
+ })
+ Expect(err).IsNil()
+}
+
+func SameKey_DifferentTenant(ctx context.Context) {
+ ctxWithTenant1 := context.WithValue(ctx, app.TenantCtxKey, tenant1)
+ ctxWithTenant2 := context.WithValue(ctx, app.TenantCtxKey, tenant2)
+
+ key := "path/to/file3.txt"
+ bytes, _ := ioutil.ReadFile(env.Path("/app/services/blob/testdata/file3.txt"))
+
+ err := bus.Dispatch(ctxWithTenant1, &cmd.StoreBlob{
+ Key: key,
+ Content: bytes,
+ ContentType: "text/plain; charset=utf-8",
+ })
+ Expect(err).IsNil()
+
+ q := &query.GetBlobByKey{Key: key}
+ err = bus.Dispatch(ctxWithTenant1, q)
+ Expect(err).IsNil()
+ Expect(q.Result.Content).Equals(bytes)
+
+ q = &query.GetBlobByKey{Key: key}
+ err = bus.Dispatch(ctxWithTenant2, q)
+ Expect(err).Equals(blob.ErrNotFound)
+ Expect(q.Result).IsNil()
+
+ q = &query.GetBlobByKey{Key: key}
+ err = bus.Dispatch(ctx, q)
+ Expect(err).Equals(blob.ErrNotFound)
+ Expect(q.Result).IsNil()
+}
+
+func SameKey_DifferentTenant_Delete(ctx context.Context) {
+ ctxWithTenant1 := context.WithValue(ctx, app.TenantCtxKey, tenant1)
+ ctxWithTenant2 := context.WithValue(ctx, app.TenantCtxKey, tenant2)
+
+ key := "path/to/super-file.txt"
+ bytes1, _ := ioutil.ReadFile(env.Path("/app/services/blob/testdata/file.txt"))
+ bytes2, _ := ioutil.ReadFile(env.Path("/app/services/blob/testdata/file3.txt"))
+
+ err := bus.Dispatch(ctxWithTenant1, &cmd.StoreBlob{
+ Key: key,
+ Content: bytes1,
+ ContentType: "text/plain; charset=utf-8",
+ })
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(ctxWithTenant2, &cmd.StoreBlob{
+ Key: key,
+ Content: bytes2,
+ ContentType: "text/plain; charset=utf-8",
+ })
+ Expect(err).IsNil()
+
+ q := &query.GetBlobByKey{Key: key}
+ err = bus.Dispatch(ctxWithTenant1, q)
+ Expect(err).IsNil()
+ Expect(q.Result.Content).Equals(bytes1)
+
+ q = &query.GetBlobByKey{Key: key}
+ err = bus.Dispatch(ctxWithTenant2, q)
+ Expect(err).IsNil()
+ Expect(q.Result.Content).Equals(bytes2)
+
+ err = bus.Dispatch(ctxWithTenant1, &cmd.DeleteBlob{Key: key})
+ Expect(err).IsNil()
+
+ q = &query.GetBlobByKey{Key: key}
+ err = bus.Dispatch(ctxWithTenant2, q)
+ Expect(err).IsNil()
+ Expect(q.Result.Content).Equals(bytes2)
+
+ q = &query.GetBlobByKey{Key: key}
+ err = bus.Dispatch(ctx, q)
+ Expect(err).Equals(blob.ErrNotFound)
+ Expect(q.Result).IsNil()
+}
+
+func KeyFormats(ctx context.Context) {
+ testCases := []struct {
+ key string
+ valid bool
+ }{
+ {
+ key: "Jon",
+ valid: true,
+ },
+ {
+ key: "ASDHASJDKHAJSDJ.png",
+ valid: true,
+ },
+ {
+ key: "",
+ valid: false,
+ },
+ {
+ key: "/path/to/Jon",
+ valid: false,
+ },
+ {
+ key: "path/to/Jon/",
+ valid: false,
+ },
+ {
+ key: " file.txt",
+ valid: false,
+ },
+ {
+ key: "file with space.txt",
+ valid: false,
+ },
+ {
+ key: rand.String(513),
+ valid: false,
+ },
+ }
+
+ for _, testCase := range testCases {
+ err := bus.Dispatch(ctx, &cmd.StoreBlob{
+ Key: testCase.key,
+ Content: []byte{},
+ ContentType: "text/plain; charset=utf-8",
+ })
+ if testCase.valid {
+ Expect(err).IsNil()
+ } else {
+ Expect(errors.Cause(err)).Equals(blob.ErrInvalidKeyFormat)
+ }
+ }
+}
+
+func TestSanitizeFileName(t *testing.T) {
+ RegisterT(t)
+
+ Expect(blob.SanitizeFileName("João.txt")).Equals("joao.txt")
+ Expect(blob.SanitizeFileName(" Jon")).Equals("jon")
+ Expect(blob.SanitizeFileName("Jon.png")).Equals("jon.png")
+ Expect(blob.SanitizeFileName("Jon Snow.png ")).Equals("jon-snow.png")
+ Expect(blob.SanitizeFileName(" ヒキワリ.png")).Equals("hikiwari.png")
+ Expect(blob.SanitizeFileName("люди рождаются свободными.png")).Equals("liudi-rozhdaiutsia-svobodnymi.png")
+}
diff --git a/app/services/blob/fs/fs.go b/app/services/blob/fs/fs.go
new file mode 100644
index 000000000..e3996fcfc
--- /dev/null
+++ b/app/services/blob/fs/fs.go
@@ -0,0 +1,110 @@
+package fs
+
+import (
+ "context"
+ "io/ioutil"
+ "net/http"
+ "os"
+ "path"
+ "path/filepath"
+ "strconv"
+
+ "github.com/getfider/fider/app"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/services/blob"
+
+ "github.com/getfider/fider/app/pkg/bus"
+)
+
+var perm os.FileMode = 0744
+
+func init() {
+ bus.Register(Service{})
+}
+
+type Service struct{}
+
+func (s Service) Name() string {
+ return "FileSystem"
+}
+
+func (s Service) Category() string {
+ return "blobstorage"
+}
+
+func (s Service) Enabled() bool {
+ return env.Config.BlobStorage.Type == "fs"
+}
+
+func (s Service) Init() {
+ bus.AddHandler(getBlobByKey)
+ bus.AddHandler(storeBlob)
+ bus.AddHandler(deleteBlob)
+}
+
+func getBlobByKey(ctx context.Context, q *query.GetBlobByKey) error {
+ fullPath := keyFullPath(ctx, q.Key)
+ stats, err := os.Stat(fullPath)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return blob.ErrNotFound
+ }
+ return errors.Wrap(err, "failed to get stats '%s' from FileSystem", q.Key)
+ }
+
+ file, err := ioutil.ReadFile(fullPath)
+ if err != nil {
+ return errors.Wrap(err, "failed to get read '%s' from FileSystem", q.Key)
+ }
+
+ q.Result = &dto.Blob{
+ Content: file,
+ ContentType: http.DetectContentType(file),
+ Size: stats.Size(),
+ }
+ return nil
+}
+
+func storeBlob(ctx context.Context, c *cmd.StoreBlob) error {
+ if err := blob.ValidateKey(c.Key); err != nil {
+ return errors.Wrap(err, "failed to validate blob key '%s'", c.Key)
+ }
+
+ fullPath := keyFullPath(ctx, c.Key)
+ err := os.MkdirAll(filepath.Dir(fullPath), perm)
+
+ if err != nil {
+ return errors.Wrap(err, "failed to create folder '%s' on FileSystem", fullPath)
+ }
+
+ err = ioutil.WriteFile(fullPath, c.Content, perm)
+ if err != nil {
+ return errors.Wrap(err, "failed to create file '%s' on FileSystem", fullPath)
+ }
+
+ return nil
+}
+
+func deleteBlob(ctx context.Context, c *cmd.DeleteBlob) error {
+ fullPath := keyFullPath(ctx, c.Key)
+ err := os.Remove(fullPath)
+ if err != nil && !os.IsNotExist(err) {
+ return errors.Wrap(err, "failed to delete file '%s' from FileSystem", c.Key)
+ }
+ return nil
+}
+
+func keyFullPath(ctx context.Context, key string) string {
+ basePath := env.Config.BlobStorage.FS.Path
+ tenant, ok := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ if ok {
+ return path.Join(basePath, "tenants", strconv.Itoa(tenant.ID), key)
+ }
+ return path.Join(basePath, key)
+}
diff --git a/app/services/blob/s3/s3.go b/app/services/blob/s3/s3.go
new file mode 100644
index 000000000..210ee764f
--- /dev/null
+++ b/app/services/blob/s3/s3.go
@@ -0,0 +1,144 @@
+package s3
+
+import (
+ "bytes"
+ "context"
+ "io/ioutil"
+ "path"
+ "strconv"
+ "strings"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/credentials"
+ "github.com/aws/aws-sdk-go/aws/session"
+ "github.com/aws/aws-sdk-go/service/s3"
+ "github.com/getfider/fider/app"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/services/blob"
+
+ "github.com/getfider/fider/app/pkg/bus"
+)
+
+//DefaultClient is an S3 Client
+var DefaultClient *s3.S3
+
+func init() {
+ bus.Register(Service{})
+}
+
+type Service struct{}
+
+func (s Service) Name() string {
+ return "S3"
+}
+
+func (s Service) Category() string {
+ return "blobstorage"
+}
+
+func (s Service) Enabled() bool {
+ return env.Config.BlobStorage.Type == "s3"
+}
+
+func (s Service) Init() {
+ s3EnvConfig := env.Config.BlobStorage.S3
+ if s3EnvConfig.EndpointURL != "" {
+ s3Config := &aws.Config{
+ Credentials: credentials.NewStaticCredentials(s3EnvConfig.AccessKeyID, s3EnvConfig.SecretAccessKey, ""),
+ Endpoint: aws.String(s3EnvConfig.EndpointURL),
+ Region: aws.String(s3EnvConfig.Region),
+ DisableSSL: aws.Bool(strings.HasSuffix(s3EnvConfig.EndpointURL, "http://")),
+ S3ForcePathStyle: aws.Bool(true),
+ }
+ awsSession := session.New(s3Config)
+ DefaultClient = s3.New(awsSession)
+ }
+ bus.AddHandler(getBlobByKey)
+ bus.AddHandler(storeBlob)
+ bus.AddHandler(deleteBlob)
+}
+
+func getBlobByKey(ctx context.Context, q *query.GetBlobByKey) error {
+ resp, err := DefaultClient.GetObjectWithContext(ctx, &s3.GetObjectInput{
+ Bucket: aws.String(env.Config.BlobStorage.S3.BucketName),
+ Key: aws.String(keyFullPathURL(ctx, q.Key)),
+ })
+ if err != nil {
+ if isNotFound(err) {
+ return blob.ErrNotFound
+ }
+ return wrap(err, "failed to get blob '%s' from S3", q.Key)
+ }
+ defer resp.Body.Close()
+
+ bytes, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return wrap(err, "failed to read blob body '%s' from S3", q.Key)
+ }
+
+ q.Result = &dto.Blob{
+ Content: bytes,
+ ContentType: *resp.ContentType,
+ Size: *resp.ContentLength,
+ }
+ return nil
+}
+
+func storeBlob(ctx context.Context, c *cmd.StoreBlob) error {
+ if err := blob.ValidateKey(c.Key); err != nil {
+ return wrap(err, "failed to validate blob key '%s'", c.Key)
+ }
+
+ reader := bytes.NewReader(c.Content)
+ _, err := DefaultClient.PutObjectWithContext(ctx, &s3.PutObjectInput{
+ Bucket: aws.String(env.Config.BlobStorage.S3.BucketName),
+ Key: aws.String(keyFullPathURL(ctx, c.Key)),
+ ContentType: aws.String(c.ContentType),
+ ACL: aws.String(s3.ObjectCannedACLPrivate),
+ Body: reader,
+ })
+ if err != nil {
+ return wrap(err, "failed to upload blob '%s' to S3", c.Key)
+ }
+ return nil
+}
+
+func deleteBlob(ctx context.Context, c *cmd.DeleteBlob) error {
+ _, err := DefaultClient.DeleteObjectWithContext(ctx, &s3.DeleteObjectInput{
+ Bucket: aws.String(env.Config.BlobStorage.S3.BucketName),
+ Key: aws.String(keyFullPathURL(ctx, c.Key)),
+ })
+ if err != nil && !isNotFound(err) {
+ return wrap(err, "failed to delete blob '%s' from S3", c.Key)
+ }
+ return nil
+}
+
+func keyFullPathURL(ctx context.Context, key string) string {
+ tenant, ok := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ if ok {
+ return path.Join("tenants", strconv.Itoa(tenant.ID), key)
+ }
+ return key
+}
+
+func isNotFound(err error) bool {
+ if awsErr, ok := err.(awserr.Error); ok {
+ return awsErr.Code() == s3.ErrCodeNoSuchKey
+ }
+ return false
+}
+
+func wrap(err error, format string, a ...interface{}) error {
+ if awsErr, ok := err.(awserr.Error); ok {
+ return errors.Wrap(awsErr.OrigErr(), format, a...)
+ }
+ return errors.Wrap(err, format, a...)
+}
diff --git a/app/services/blob/sql/sql.go b/app/services/blob/sql/sql.go
new file mode 100644
index 000000000..2706a5528
--- /dev/null
+++ b/app/services/blob/sql/sql.go
@@ -0,0 +1,148 @@
+package sql
+
+import (
+ "context"
+ "database/sql"
+ "time"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/dbx"
+
+ "github.com/getfider/fider/app"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/services/blob"
+
+ "github.com/getfider/fider/app/pkg/bus"
+)
+
+func init() {
+ bus.Register(Service{})
+}
+
+type Service struct{}
+
+func (s Service) Name() string {
+ return "SQL"
+}
+
+func (s Service) Category() string {
+ return "blobstorage"
+}
+
+func (s Service) Enabled() bool {
+ return env.Config.BlobStorage.Type == "sql"
+}
+
+func (s Service) Init() {
+ bus.AddHandler(getBlobByKey)
+ bus.AddHandler(storeBlob)
+ bus.AddHandler(deleteBlob)
+}
+
+type dbBlob struct {
+ ContentType string `db:"content_type"`
+ Size int64 `db:"size"`
+ Content []byte `db:"file"`
+}
+
+func getBlobByKey(ctx context.Context, q *query.GetBlobByKey) error {
+ return using(ctx, func(tenant *models.Tenant) error {
+ var tenantID sql.NullInt64
+ if tenant != nil {
+ tenantID.Scan(tenant.ID)
+ }
+
+ trx, err := dbx.BeginTx(ctx)
+ if err != nil {
+ return errors.Wrap(err, "failed to open transaction")
+ }
+ defer trx.Commit()
+
+ b := dbBlob{}
+ err = trx.Get(&b, "SELECT file, content_type, size FROM blobs WHERE key = $1 AND (tenant_id = $2 OR ($2 IS NULL AND tenant_id IS NULL))", q.Key, tenantID)
+ if err != nil {
+ if err == app.ErrNotFound {
+ return blob.ErrNotFound
+ }
+ return errors.Wrap(err, "failed to get blob with key '%s'", q.Key)
+ }
+
+ q.Result = &dto.Blob{
+ Size: b.Size,
+ ContentType: b.ContentType,
+ Content: b.Content,
+ }
+ return nil
+ })
+}
+
+func storeBlob(ctx context.Context, c *cmd.StoreBlob) error {
+ if err := blob.ValidateKey(c.Key); err != nil {
+ return errors.Wrap(err, "failed to validate blob key '%s'", c.Key)
+ }
+
+ return using(ctx, func(tenant *models.Tenant) error {
+ var tenantID sql.NullInt64
+ if tenant != nil {
+ tenantID.Scan(tenant.ID)
+ }
+
+ trx, err := dbx.BeginTx(ctx)
+ if err != nil {
+ return errors.Wrap(err, "failed to open transaction")
+ }
+ defer trx.Commit()
+
+ now := time.Now()
+ _, err = trx.Execute(`
+ INSERT INTO blobs (tenant_id, key, size, content_type, file, created_at, modified_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (tenant_id, key)
+ DO UPDATE SET size = $3, content_type = $4, file = $5, modified_at = $7
+ `, tenantID, c.Key, int64(len(c.Content)), c.ContentType, c.Content, now, now)
+ if err != nil {
+ return errors.Wrap(err, "failed to store blob with key '%s'", c.Key)
+ }
+
+ if err != nil {
+ return errors.Wrap(err, "failed to commit store of blob with key '%s'", c.Key)
+ }
+
+ return nil
+ })
+}
+
+func deleteBlob(ctx context.Context, c *cmd.DeleteBlob) error {
+ return using(ctx, func(tenant *models.Tenant) error {
+ var tenantID sql.NullInt64
+ if tenant != nil {
+ tenantID.Scan(tenant.ID)
+ }
+
+ trx, err := dbx.BeginTx(ctx)
+ if err != nil {
+ return errors.Wrap(err, "failed to open transaction")
+ }
+ defer trx.Commit()
+
+ _, err = trx.Execute("DELETE FROM blobs WHERE key = $1 AND (tenant_id = $2 OR ($2 IS NULL AND tenant_id IS NULL))", c.Key, tenantID)
+ if err != nil {
+ return errors.Wrap(err, "failed to delete blob with key '%s'", c.Key)
+ }
+
+ if err != nil {
+ return errors.Wrap(err, "failed to commit deletion of blob with key '%s'", c.Key)
+ }
+
+ return nil
+ })
+}
+
+func using(ctx context.Context, handler func(tenant *models.Tenant) error) error {
+ tenant, _ := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ return handler(tenant)
+}
diff --git a/app/pkg/blob/testdata/file.txt b/app/services/blob/testdata/file.txt
similarity index 100%
rename from app/pkg/blob/testdata/file.txt
rename to app/services/blob/testdata/file.txt
diff --git a/app/pkg/blob/testdata/file2.png b/app/services/blob/testdata/file2.png
similarity index 100%
rename from app/pkg/blob/testdata/file2.png
rename to app/services/blob/testdata/file2.png
diff --git a/app/pkg/blob/testdata/file3.txt b/app/services/blob/testdata/file3.txt
similarity index 100%
rename from app/pkg/blob/testdata/file3.txt
rename to app/services/blob/testdata/file3.txt
diff --git a/app/services/email/email.go b/app/services/email/email.go
new file mode 100644
index 000000000..0ace66c5f
--- /dev/null
+++ b/app/services/email/email.go
@@ -0,0 +1,45 @@
+package email
+
+import (
+ "regexp"
+ "strings"
+
+ "github.com/getfider/fider/app/pkg/env"
+)
+
+// NoReply is the default 'from' address
+var NoReply = env.Config.Email.NoReply
+
+var whitelist = env.Config.Email.Whitelist
+var whitelistRegex = regexp.MustCompile(whitelist)
+var blacklist = env.Config.Email.Blacklist
+var blacklistRegex = regexp.MustCompile(blacklist)
+
+// SetWhitelist can be used to change email whitelist during runtime
+func SetWhitelist(s string) {
+ whitelist = s
+ whitelistRegex = regexp.MustCompile(whitelist)
+}
+
+// SetBlacklist can be used to change email blacklist during runtime
+func SetBlacklist(s string) {
+ blacklist = s
+ blacklistRegex = regexp.MustCompile(blacklist)
+}
+
+// CanSendTo returns true if Fider is allowed to send email to given address
+func CanSendTo(address string) bool {
+ if strings.TrimSpace(address) == "" {
+ return false
+ }
+
+ if whitelist != "" {
+ return whitelistRegex.MatchString(address)
+ }
+
+ if blacklist != "" {
+ return !blacklistRegex.MatchString(address)
+ }
+
+ return true
+}
diff --git a/app/pkg/email/email_test.go b/app/services/email/email_test.go
similarity index 85%
rename from app/pkg/email/email_test.go
rename to app/services/email/email_test.go
index 1c39b8339..89412a44e 100644
--- a/app/pkg/email/email_test.go
+++ b/app/services/email/email_test.go
@@ -3,10 +3,8 @@ package email_test
import (
"testing"
- "github.com/getfider/fider/app/pkg/log/noop"
- "github.com/getfider/fider/app/pkg/worker"
-
- "github.com/getfider/fider/app/pkg/email"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/services/email"
. "github.com/getfider/fider/app/pkg/assert"
)
@@ -14,8 +12,7 @@ import (
func TestRenderMessage(t *testing.T) {
RegisterT(t)
- ctx := worker.NewContext("ID-1", worker.Task{Name: "TaskName"}, nil, noop.NewLogger())
- message := email.RenderMessage(ctx, "echo_test", email.Params{
+ message := email.RenderMessage("echo_test", dto.Props{
"name": "Fider",
})
Expect(message.Subject).Equals("Message to: Fider")
@@ -114,24 +111,6 @@ func TestCanSendTo(t *testing.T) {
}
}
-func TestParamsMerge(t *testing.T) {
- RegisterT(t)
-
- p1 := email.Params{
- "name": "Jon",
- "age": 26,
- }
- p2 := p1.Merge(email.Params{
- "age": 30,
- "email": "[email protected]",
- })
- Expect(p2).Equals(email.Params{
- "name": "Jon",
- "age": 30,
- "email": "[email protected]",
- })
-}
-
func TestRecipient_String(t *testing.T) {
RegisterT(t)
@@ -173,7 +152,7 @@ func TestRecipient_String(t *testing.T) {
}
for _, testCase := range testCases {
- r := email.NewRecipient(testCase.name, testCase.email, email.Params{})
+ r := dto.NewRecipient(testCase.name, testCase.email, dto.Props{})
Expect(r.String()).Equals(testCase.expected)
}
}
diff --git a/app/services/email/emailmock/emailmock.go b/app/services/email/emailmock/emailmock.go
new file mode 100644
index 000000000..0f3cb5fe0
--- /dev/null
+++ b/app/services/email/emailmock/emailmock.go
@@ -0,0 +1,63 @@
+package emailmock
+
+import (
+ "context"
+
+ "github.com/getfider/fider/app"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/bus"
+)
+
+var MessageHistory = make([]*HistoryItem, 0)
+
+type HistoryItem struct {
+ From string
+ To []dto.Recipient
+ TemplateName string
+ Props dto.Props
+ Tenant *models.Tenant
+}
+
+func init() {
+ bus.Register(Service{})
+}
+
+type Service struct{}
+
+func (s Service) Name() string {
+ return "Mock"
+}
+
+func (s Service) Category() string {
+ return "email"
+}
+
+func (s Service) Enabled() bool {
+ return true
+}
+
+func (s Service) Init() {
+ MessageHistory = make([]*HistoryItem, 0)
+ bus.AddListener(sendMail)
+}
+
+func sendMail(ctx context.Context, c *cmd.SendMail) {
+ if c.Props == nil {
+ c.Props = dto.Props{}
+ }
+ item := &HistoryItem{
+ From: c.From,
+ To: c.To,
+ TemplateName: c.TemplateName,
+ Props: c.Props,
+ }
+
+ tenant, ok := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ if ok {
+ item.Tenant = tenant
+ }
+ MessageHistory = append(MessageHistory, item)
+}
diff --git a/app/services/email/mailgun/mailgun.go b/app/services/email/mailgun/mailgun.go
new file mode 100644
index 000000000..2d180061d
--- /dev/null
+++ b/app/services/email/mailgun/mailgun.go
@@ -0,0 +1,173 @@
+package mailgun
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/url"
+ "strings"
+
+ "github.com/getfider/fider/app"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/log"
+ "github.com/getfider/fider/app/services/email"
+)
+
+// Known base URLs
+// Should Mailgun add other regions we'll just need to add their URLs here
+// Use upper case keys - incoming env var values are normalized before being used
+var baseURLs = map[string]string{
+ "US": "https://api.mailgun.net/v3/%s/messages",
+ "EU": "https://api.eu.mailgun.net/v3/%s/messages",
+}
+
+func init() {
+ bus.Register(Service{})
+}
+
+type Service struct{}
+
+func (s Service) Name() string {
+ return "Mailgun"
+}
+
+func (s Service) Category() string {
+ return "email"
+}
+
+func (s Service) Enabled() bool {
+ return env.Config.Email.Mailgun.APIKey != ""
+}
+
+func (s Service) Init() {
+ bus.AddListener(sendMail)
+}
+
+// Try getting the URL of the Mailgun API using Environment vars and the Sender's domain
+// Fall back to the URL for the US region if that fails to maintain compatibility with older installs
+func getEndpoint(ctx context.Context, domain string) string {
+ var regionCode = env.Config.Email.Mailgun.Region
+ regionCode = strings.ToUpper(regionCode)
+
+ // Default to the US domain if no region code was provided (ENV not set)
+ // or if the provided code isn't valid
+ if len(regionCode) < 1 {
+ regionCode = "US"
+ } else if len(baseURLs[regionCode]) < 1 {
+ log.Warnf(ctx,
+ "Unknown Mailgun region code '@{Code}' configured - falling back to 'US'",
+ dto.Props{
+ "Code": env.Config.Email.Mailgun.Region,
+ },
+ )
+
+ regionCode = "US"
+ }
+
+ return fmt.Sprintf(baseURLs[regionCode], domain)
+}
+
+func sendMail(ctx context.Context, c *cmd.SendMail) {
+ if len(c.To) == 0 {
+ return
+ }
+
+ if c.Props == nil {
+ c.Props = dto.Props{}
+ }
+
+ isBatch := len(c.To) > 1
+
+ var message *email.Message
+ if isBatch {
+ // Replace recipient specific Go templates variables with Mailgun template variables
+ if c.To[0].Props != nil {
+ for k := range c.To[0].Props {
+ c.Props[k] = fmt.Sprintf("%%recipient.%s%%", k)
+ }
+ }
+ message = email.RenderMessage(c.TemplateName, c.Props)
+ } else {
+ message = email.RenderMessage(c.TemplateName, c.Props.Merge(c.To[0].Props))
+ }
+
+ form := url.Values{}
+ form.Add("from", dto.NewRecipient(c.From, email.NoReply, dto.Props{}).String())
+ form.Add("h:Reply-To", email.NoReply)
+ form.Add("subject", message.Subject)
+ form.Add("html", message.Body)
+ form.Add("o:tag", fmt.Sprintf("template:%s", c.TemplateName))
+
+ tenant, ok := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ if ok && !env.IsSingleHostMode() {
+ form.Add("o:tag", fmt.Sprintf("tenant:%s", tenant.Subdomain))
+ }
+
+ // Set Mailgun's var based on each recipient's variables
+ recipientVariables := make(map[string]dto.Props)
+ for _, r := range c.To {
+ if r.Address != "" {
+ if email.CanSendTo(r.Address) {
+ form.Add("to", r.String())
+ recipientVariables[r.Address] = r.Props
+ } else {
+ log.Warnf(ctx, "Skipping email to '@{Name} <@{Address}>'.", dto.Props{
+ "Name": r.Name,
+ "Address": r.Address,
+ })
+ }
+ }
+ }
+
+ // If we skipped all recipients, just return
+ if len(recipientVariables) == 0 {
+ return
+ }
+
+ if isBatch {
+ json, err := json.Marshal(recipientVariables)
+ if err != nil {
+ panic(errors.Wrap(err, "failed to marshal recipient variables"))
+ }
+
+ form.Add("recipient-variables", string(json))
+ }
+
+ if isBatch {
+ log.Debugf(ctx, "Sending email to @{CountRecipients} recipients with template @{TemplateName}.", dto.Props{
+ "CountRecipients": len(recipientVariables),
+ "TemplateName": c.TemplateName,
+ })
+ } else {
+ log.Debugf(ctx, "Sending email to @{Address} with template @{TemplateName}.", dto.Props{
+ "Address": c.To[0].Address,
+ "TemplateName": c.TemplateName,
+ })
+ }
+
+ req := &cmd.HTTPRequest{
+ Method: "POST",
+ URL: getEndpoint(ctx, env.Config.Email.Mailgun.Domain),
+ Body: strings.NewReader(form.Encode()),
+ Headers: map[string]string{
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ BasicAuth: &dto.BasicAuth{
+ User: "api",
+ Password: env.Config.Email.Mailgun.APIKey,
+ },
+ }
+ err := bus.Dispatch(ctx, req)
+ if err != nil {
+ panic(errors.Wrap(err, "failed to send email with template %s", c.TemplateName))
+ }
+ log.Debugf(ctx, "Email sent with response code @{StatusCode}.", dto.Props{
+ "StatusCode": req.ResponseStatusCode,
+ })
+}
diff --git a/app/pkg/email/mailgun/mailgun_test.go b/app/services/email/mailgun/mailgun_test.go
similarity index 54%
rename from app/pkg/email/mailgun/mailgun_test.go
rename to app/services/email/mailgun/mailgun_test.go
index 42d959bfe..04fd1d4c4 100644
--- a/app/pkg/email/mailgun/mailgun_test.go
+++ b/app/services/email/mailgun/mailgun_test.go
@@ -1,54 +1,60 @@
package mailgun_test
import (
+ "context"
"io/ioutil"
"net/url"
"testing"
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/worker"
+ "github.com/getfider/fider/app/services/email/mailgun"
+ "github.com/getfider/fider/app/services/httpclient/httpclientmock"
"github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/email"
- "github.com/getfider/fider/app/pkg/mock"
- "github.com/getfider/fider/app/pkg/email/mailgun"
- "github.com/getfider/fider/app/pkg/log/noop"
+ "github.com/getfider/fider/app/services/email"
. "github.com/getfider/fider/app/pkg/assert"
)
-var logger = noop.NewLogger()
-var client = mock.NewHTTPClient()
-var sender = mailgun.NewSender(logger, client, "mydomain.com", "mys3cr3tk3y")
-var tenant = &models.Tenant{
- Subdomain: "got",
-}
-var ctx = worker.NewContext("ID-1", worker.Task{Name: "TaskName"}, nil, logger)
+var ctx context.Context
-func init() {
- ctx.SetTenant(tenant)
+func reset() {
+ ctx = context.WithValue(context.Background(), app.TenantCtxKey, &models.Tenant{
+ Subdomain: "got",
+ })
+ bus.Init(mailgun.Service{}, httpclientmock.Service{})
}
func TestSend_Success(t *testing.T) {
RegisterT(t)
env.Config.HostMode = "multi"
- client.Reset()
+ reset()
- to := email.Recipient{
- Name: "Jon Sow",
- Address: "[email protected]",
- }
- sender.Send(ctx, "echo_test", email.Params{
- "name": "Hello",
- }, "Fider Test", to)
+ bus.Publish(ctx, &cmd.SendMail{
+ From: "Fider Test",
+ To: []dto.Recipient{
+ dto.Recipient{
+ Name: "Jon Sow",
+ Address: "[email protected]",
+ },
+ },
+ TemplateName: "echo_test",
+ Props: dto.Props{
+ "name": "Hello",
+ },
+ })
- Expect(client.Requests).HasLen(1)
- Expect(client.Requests[0].URL.String()).Equals("https://api.mailgun.net/v3/mydomain.com/messages")
- Expect(client.Requests[0].Header.Get("Authorization")).Equals("Basic YXBpOm15czNjcjN0azN5")
- Expect(client.Requests[0].Header.Get("Content-Type")).Equals("application/x-www-form-urlencoded")
+ Expect(httpclientmock.RequestsHistory).HasLen(1)
+ Expect(httpclientmock.RequestsHistory[0].URL.String()).Equals("https://api.mailgun.net/v3/mydomain.com/messages")
+ Expect(httpclientmock.RequestsHistory[0].Header.Get("Authorization")).Equals("Basic YXBpOm15czNjcjN0azN5")
+ Expect(httpclientmock.RequestsHistory[0].Header.Get("Content-Type")).Equals("application/x-www-form-urlencoded")
- bytes, err := ioutil.ReadAll(client.Requests[0].Body)
+ bytes, err := ioutil.ReadAll(httpclientmock.RequestsHistory[0].Body)
Expect(err).IsNil()
values, err := url.ParseQuery(string(bytes))
Expect(err).IsNil()
@@ -94,64 +100,79 @@ func TestSend_Success(t *testing.T) {
func TestSend_SkipEmptyAddress(t *testing.T) {
RegisterT(t)
- client.Reset()
+ reset()
- to := email.Recipient{
- Name: "Jon Sow",
- Address: "",
- }
- sender.Send(ctx, "echo_test", email.Params{
- "name": "Hello",
- }, "Fider Test", to)
+ bus.Publish(ctx, &cmd.SendMail{
+ From: "Fider Test",
+ To: []dto.Recipient{
+ dto.Recipient{
+ Name: "Jon Sow",
+ Address: "",
+ },
+ },
+ TemplateName: "echo_test",
+ Props: dto.Props{
+ "name": "Hello",
+ },
+ })
- Expect(client.Requests).HasLen(0)
+ Expect(httpclientmock.RequestsHistory).HasLen(0)
}
func TestSend_SkipUnlistedAddress(t *testing.T) {
RegisterT(t)
- client.Reset()
+ reset()
email.SetWhitelist("^.*@gmail.com$")
- to := email.Recipient{
- Name: "Jon Sow",
- Address: "[email protected]",
- }
- sender.Send(ctx, "echo_test", email.Params{
- "name": "Hello",
- }, "Fider Test", to)
+ bus.Publish(ctx, &cmd.SendMail{
+ From: "Fider Test",
+ To: []dto.Recipient{
+ dto.Recipient{
+ Name: "Jon Sow",
+ Address: "[email protected]",
+ },
+ },
+ TemplateName: "echo_test",
+ Props: dto.Props{
+ "name": "Hello",
+ },
+ })
- Expect(client.Requests).HasLen(0)
+ Expect(httpclientmock.RequestsHistory).HasLen(0)
}
func TestBatch_Success(t *testing.T) {
RegisterT(t)
- client.Reset()
+ reset()
email.SetWhitelist("")
- to := []email.Recipient{
- email.Recipient{
- Name: "Jon Sow",
- Address: "[email protected]",
- Params: email.Params{
- "name": "Jon",
+ bus.Publish(ctx, &cmd.SendMail{
+ From: "Fider Test",
+ To: []dto.Recipient{
+ dto.Recipient{
+ Name: "Jon Sow",
+ Address: "[email protected]",
+ Props: dto.Props{
+ "name": "Jon",
+ },
},
- },
- email.Recipient{
- Name: "Arya Stark",
- Address: "[email protected]",
- Params: email.Params{
- "name": "Arya",
+ dto.Recipient{
+ Name: "Arya Stark",
+ Address: "[email protected]",
+ Props: dto.Props{
+ "name": "Arya",
+ },
},
},
- }
- sender.BatchSend(ctx, "echo_test", email.Params{}, "Fider Test", to)
+ TemplateName: "echo_test",
+ })
- Expect(client.Requests).HasLen(1)
- Expect(client.Requests[0].URL.String()).Equals("https://api.mailgun.net/v3/mydomain.com/messages")
- Expect(client.Requests[0].Header.Get("Authorization")).Equals("Basic YXBpOm15czNjcjN0azN5")
- Expect(client.Requests[0].Header.Get("Content-Type")).Equals("application/x-www-form-urlencoded")
+ Expect(httpclientmock.RequestsHistory).HasLen(1)
+ Expect(httpclientmock.RequestsHistory[0].URL.String()).Equals("https://api.mailgun.net/v3/mydomain.com/messages")
+ Expect(httpclientmock.RequestsHistory[0].Header.Get("Authorization")).Equals("Basic YXBpOm15czNjcjN0azN5")
+ Expect(httpclientmock.RequestsHistory[0].Header.Get("Content-Type")).Equals("application/x-www-form-urlencoded")
- bytes, err := ioutil.ReadAll(client.Requests[0].Body)
+ bytes, err := ioutil.ReadAll(httpclientmock.RequestsHistory[0].Body)
Expect(err).IsNil()
values, err := url.ParseQuery(string(bytes))
Expect(err).IsNil()
@@ -201,25 +222,47 @@ func TestBatch_Success(t *testing.T) {
func TestGetBaseURL(t *testing.T) {
RegisterT(t)
+ reset()
+
+ sendMail := &cmd.SendMail{
+ From: "Fider Test",
+ To: []dto.Recipient{
+ dto.Recipient{
+ Name: "Jon Sow",
+ Address: "[email protected]",
+ },
+ },
+ TemplateName: "echo_test",
+ Props: dto.Props{
+ "name": "Hello",
+ },
+ }
// Fall back to US if there is nothing set
env.Config.Email.Mailgun.Region = ""
- Expect(sender.GetBaseURL()).Equals("https://api.mailgun.net/v3/mydomain.com/messages")
-
+ bus.Publish(ctx, sendMail)
+ Expect(httpclientmock.RequestsHistory[0].URL.String()).Equals("https://api.mailgun.net/v3/mydomain.com/messages")
+
// Return the EU domain for EU, ignore the case
env.Config.Email.Mailgun.Region = "EU"
- Expect(sender.GetBaseURL()).Equals("https://api.eu.mailgun.net/v3/mydomain.com/messages")
+ bus.Publish(ctx, sendMail)
+ Expect(httpclientmock.RequestsHistory[1].URL.String()).Equals("https://api.eu.mailgun.net/v3/mydomain.com/messages")
+
env.Config.Email.Mailgun.Region = "eu"
- Expect(sender.GetBaseURL()).Equals("https://api.eu.mailgun.net/v3/mydomain.com/messages")
+ bus.Publish(ctx, sendMail)
+ Expect(httpclientmock.RequestsHistory[2].URL.String()).Equals("https://api.eu.mailgun.net/v3/mydomain.com/messages")
// Return the US domain for US, ignore the case
env.Config.Email.Mailgun.Region = "US"
- Expect(sender.GetBaseURL()).Equals("https://api.mailgun.net/v3/mydomain.com/messages")
+ bus.Publish(ctx, sendMail)
+ Expect(httpclientmock.RequestsHistory[3].URL.String()).Equals("https://api.mailgun.net/v3/mydomain.com/messages")
env.Config.Email.Mailgun.Region = "us"
- Expect(sender.GetBaseURL()).Equals("https://api.mailgun.net/v3/mydomain.com/messages")
+ bus.Publish(ctx, sendMail)
+ Expect(httpclientmock.RequestsHistory[4].URL.String()).Equals("https://api.mailgun.net/v3/mydomain.com/messages")
- // Return the US domain if the region is invalid
+ // Return the US domain if the region is invalid
env.Config.Email.Mailgun.Region = "Mars"
- Expect(sender.GetBaseURL()).Equals("https://api.mailgun.net/v3/mydomain.com/messages")
+ bus.Publish(ctx, sendMail)
+ Expect(httpclientmock.RequestsHistory[5].URL.String()).Equals("https://api.mailgun.net/v3/mydomain.com/messages")
-}
\ No newline at end of file
+}
diff --git a/app/services/email/message.go b/app/services/email/message.go
new file mode 100644
index 000000000..d982df5e3
--- /dev/null
+++ b/app/services/email/message.go
@@ -0,0 +1,55 @@
+package email
+
+import (
+ "bytes"
+ "html/template"
+ "strings"
+
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/env"
+)
+
+var cache = make(map[string]*template.Template)
+
+// Message represents what is sent by email
+type Message struct {
+ Subject string
+ Body string
+}
+
+var baseTpl, _ = template.ParseFiles(env.Path("/views/templates/base_email.tpl"))
+
+// RenderMessage returns the HTML of an email based on template and params
+func RenderMessage(templateName string, params dto.Props) *Message {
+ tpl, ok := cache[templateName]
+ if !ok || env.IsDevelopment() {
+ var err error
+ file := env.Path("/views/templates", templateName+".tpl")
+ tpl, err = template.ParseFiles(file)
+ if err != nil {
+ panic(err)
+ }
+ cache[templateName] = tpl
+ }
+
+ var bf bytes.Buffer
+ if err := tpl.Execute(&bf, params); err != nil {
+ panic(err)
+ }
+
+ lines := strings.Split(bf.String(), "\n")
+ body := strings.TrimLeft(strings.Join(lines[2:], "\n"), " ")
+
+ bf.Reset()
+ if err := baseTpl.Execute(&bf, dto.Props{
+ "logo": params["logo"],
+ "body": template.HTML(body),
+ }); err != nil {
+ panic(err)
+ }
+
+ return &Message{
+ Subject: strings.TrimLeft(lines[0], "subject: "),
+ Body: bf.String(),
+ }
+}
diff --git a/app/pkg/email/smtp/auth.go b/app/services/email/smtp/auth.go
similarity index 100%
rename from app/pkg/email/smtp/auth.go
rename to app/services/email/smtp/auth.go
diff --git a/app/pkg/email/smtp/auth_login.go b/app/services/email/smtp/auth_login.go
similarity index 100%
rename from app/pkg/email/smtp/auth_login.go
rename to app/services/email/smtp/auth_login.go
diff --git a/app/pkg/email/smtp/auth_test.go b/app/services/email/smtp/auth_test.go
similarity index 94%
rename from app/pkg/email/smtp/auth_test.go
rename to app/services/email/smtp/auth_test.go
index 59afe089c..2620a50d8 100644
--- a/app/pkg/email/smtp/auth_test.go
+++ b/app/services/email/smtp/auth_test.go
@@ -5,7 +5,7 @@ import (
"testing"
. "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/email/smtp"
+ "github.com/getfider/fider/app/services/email/smtp"
)
func TestAgnosticAuth_Login(t *testing.T) {
diff --git a/app/services/email/smtp/smtp.go b/app/services/email/smtp/smtp.go
new file mode 100644
index 000000000..41c72cb13
--- /dev/null
+++ b/app/services/email/smtp/smtp.go
@@ -0,0 +1,180 @@
+package smtp
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/tls"
+ "encoding/hex"
+ "fmt"
+ "net"
+ gosmtp "net/smtp"
+ "net/url"
+ "strconv"
+ "time"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/log"
+ "github.com/getfider/fider/app/pkg/web"
+ "github.com/getfider/fider/app/services/email"
+)
+
+func init() {
+ bus.Register(Service{})
+}
+
+type Service struct{}
+
+func (s Service) Name() string {
+ return "SMTP"
+}
+
+func (s Service) Category() string {
+ return "email"
+}
+
+func (s Service) Enabled() bool {
+ return env.Config.Email.Mailgun.APIKey == ""
+}
+
+func (s Service) Init() {
+ bus.AddListener(sendMail)
+}
+
+func sendMail(ctx context.Context, c *cmd.SendMail) {
+ if c.Props == nil {
+ c.Props = dto.Props{}
+ }
+
+ for _, to := range c.To {
+ if to.Address == "" {
+ return
+ }
+
+ u, err := url.Parse(web.BaseURL(ctx))
+ localname := "localhost"
+ if err == nil {
+ localname = u.Hostname()
+ }
+
+ if !email.CanSendTo(to.Address) {
+ log.Warnf(ctx, "Skipping email to '@{Name} <@{Address}>'.", dto.Props{
+ "Name": to.Name,
+ "Address": to.Address,
+ })
+ return
+ }
+
+ log.Debugf(ctx, "Sending email to @{Address} with template @{TemplateName} and params @{Props}.", dto.Props{
+ "Address": to.Address,
+ "TemplateName": c.TemplateName,
+ "Props": to.Props,
+ })
+
+ message := email.RenderMessage(c.TemplateName, c.Props.Merge(to.Props))
+ b := builder{}
+ b.Set("From", dto.NewRecipient(c.From, email.NoReply, dto.Props{}).String())
+ b.Set("Reply-To", email.NoReply)
+ b.Set("To", to.String())
+ b.Set("Subject", message.Subject)
+ b.Set("MIME-version", "1.0")
+ b.Set("Content-Type", "text/html; charset=\"UTF-8\"")
+ b.Set("Date", time.Now().Format(time.RFC1123Z))
+ b.Set("Message-ID", generateMessageID(localname))
+ b.Body(message.Body)
+
+ smtpConfig := env.Config.Email.SMTP
+ servername := fmt.Sprintf("%s:%s", smtpConfig.Host, smtpConfig.Port)
+ auth := authenticate(smtpConfig.Username, smtpConfig.Password, smtpConfig.Host)
+ err = Send(localname, servername, auth, email.NoReply, []string{to.Address}, b.Bytes())
+ if err != nil {
+ panic(errors.Wrap(err, "failed to send email with template %s", c.TemplateName))
+ }
+ log.Debug(ctx, "Email sent.")
+ }
+}
+
+var Send = func(localName, serverAddress string, a gosmtp.Auth, from string, to []string, msg []byte) error {
+ host, _, _ := net.SplitHostPort(serverAddress)
+ c, err := gosmtp.Dial(serverAddress)
+ if err != nil {
+ return err
+ }
+ defer c.Close()
+ if err = c.Hello(localName); err != nil {
+ return err
+ }
+ if ok, _ := c.Extension("STARTTLS"); ok {
+ config := &tls.Config{ServerName: host}
+ if err = c.StartTLS(config); err != nil {
+ return err
+ }
+ }
+ if a != nil {
+ if ok, _ := c.Extension("AUTH"); !ok {
+ return errors.New("smtp: server doesn't support AUTH")
+ }
+ if err = c.Auth(a); err != nil {
+ return err
+ }
+ }
+ if err = c.Mail(from); err != nil {
+ return err
+ }
+ for _, addr := range to {
+ if err = c.Rcpt(addr); err != nil {
+ return err
+ }
+ }
+ w, err := c.Data()
+ if err != nil {
+ return err
+ }
+ _, err = w.Write(msg)
+ if err != nil {
+ return err
+ }
+ err = w.Close()
+ if err != nil {
+ return err
+ }
+ return c.Quit()
+}
+
+func generateMessageID(localName string) string {
+ timestamp := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
+ buf := make([]byte, 16)
+ _, err := rand.Read(buf)
+ if err != nil {
+ panic(err)
+ }
+ randStr := hex.EncodeToString(buf)
+ messageID := fmt.Sprintf("<%s.%s@%s>", randStr, timestamp, localName)
+ return messageID
+}
+
+func authenticate(username string, password string, host string) gosmtp.Auth {
+ if username == "" && password == "" {
+ return nil
+ }
+ return AgnosticAuth("", username, password, host)
+}
+
+type builder struct {
+ content string
+}
+
+func (b *builder) Set(key, value string) {
+ b.content += fmt.Sprintf("%s: %s\r\n", key, value)
+}
+
+func (b *builder) Body(body string) {
+ b.content += "\r\n" + body
+}
+
+func (b *builder) Bytes() []byte {
+ return []byte(b.content)
+}
diff --git a/app/pkg/email/smtp/smtp_test.go b/app/services/email/smtp/smtp_test.go
similarity index 67%
rename from app/pkg/email/smtp/smtp_test.go
rename to app/services/email/smtp/smtp_test.go
index 1c6c63298..580431931 100644
--- a/app/pkg/email/smtp/smtp_test.go
+++ b/app/services/email/smtp/smtp_test.go
@@ -1,16 +1,20 @@
package smtp_test
import (
+ "context"
gosmtp "net/smtp"
"regexp"
"testing"
+ "github.com/getfider/fider/app"
+
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
. "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/email"
- "github.com/getfider/fider/app/pkg/email/smtp"
- "github.com/getfider/fider/app/pkg/log/noop"
- "github.com/getfider/fider/app/pkg/worker"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/services/email"
+ "github.com/getfider/fider/app/services/email/smtp"
)
type request struct {
@@ -21,13 +25,7 @@ type request struct {
body []byte
}
-var logger = noop.NewLogger()
-var sender = smtp.NewSender(logger, "localhost", "1234", "us3r", "p4ss")
-var tenant = &models.Tenant{
- Subdomain: "got",
-}
-
-var ctx = worker.NewContext("ID-1", worker.Task{Name: "TaskName"}, nil, logger)
+var ctx context.Context
var requests = make([]request, 0)
@@ -37,24 +35,32 @@ func mockSend(localname, servername string, auth gosmtp.Auth, from string, to []
}
func reset() {
- ctx.SetTenant(tenant)
- sender.ReplaceSend(mockSend)
+ ctx = context.WithValue(context.Background(), app.TenantCtxKey, &models.Tenant{
+ Subdomain: "got",
+ })
+ smtp.Send = mockSend
requests = make([]request, 0)
+ bus.Init(smtp.Service{})
}
func TestSend_Success(t *testing.T) {
RegisterT(t)
reset()
- to := email.Recipient{
- Name: "Jon Sow",
- Address: "[email protected]",
- }
- err := sender.Send(ctx, "echo_test", email.Params{
- "name": "Hello",
- }, "Fider Test", to)
+ bus.Publish(ctx, &cmd.SendMail{
+ From: "Fider Test",
+ To: []dto.Recipient{
+ dto.Recipient{
+ Name: "Jon Sow",
+ Address: "[email protected]",
+ },
+ },
+ TemplateName: "echo_test",
+ Props: dto.Props{
+ "name": "Hello",
+ },
+ })
- Expect(err).IsNil()
Expect(requests).HasLen(1)
Expect(requests[0].servername).Equals("localhost:1234")
Expect(requests[0].auth).Equals(smtp.AgnosticAuth("", "us3r", "p4ss", "localhost"))
@@ -71,15 +77,20 @@ func TestSend_SkipEmptyAddress(t *testing.T) {
RegisterT(t)
reset()
- to := email.Recipient{
- Name: "Jon Sow",
- Address: "",
- }
- err := sender.Send(ctx, "echo_test", email.Params{
- "name": "Hello",
- }, "Fider Test", to)
+ bus.Publish(ctx, &cmd.SendMail{
+ From: "Fider Test",
+ To: []dto.Recipient{
+ dto.Recipient{
+ Name: "Jon Sow",
+ Address: "",
+ },
+ },
+ TemplateName: "echo_test",
+ Props: dto.Props{
+ "name": "Hello",
+ },
+ })
- Expect(err).IsNil()
Expect(requests).HasLen(0)
}
@@ -88,15 +99,20 @@ func TestSend_SkipUnlistedAddress(t *testing.T) {
reset()
email.SetWhitelist("^.*@gmail.com$")
- to := email.Recipient{
- Name: "Jon Sow",
- Address: "[email protected]",
- }
- err := sender.Send(ctx, "echo_test", email.Params{
- "name": "Hello",
- }, "Fider Test", to)
+ bus.Publish(ctx, &cmd.SendMail{
+ From: "Fider Test",
+ To: []dto.Recipient{
+ dto.Recipient{
+ Name: "Jon Sow",
+ Address: "[email protected]",
+ },
+ },
+ TemplateName: "echo_test",
+ Props: dto.Props{
+ "name": "Hello",
+ },
+ })
- Expect(err).IsNil()
Expect(requests).HasLen(0)
}
@@ -105,25 +121,26 @@ func TestBatch_Success(t *testing.T) {
reset()
email.SetWhitelist("")
- to := []email.Recipient{
- email.Recipient{
- Name: "Jon Sow",
- Address: "[email protected]",
- Params: email.Params{
- "name": "Jon",
+ bus.Publish(ctx, &cmd.SendMail{
+ From: "Fider Test",
+ To: []dto.Recipient{
+ dto.Recipient{
+ Name: "Jon Sow",
+ Address: "[email protected]",
+ Props: dto.Props{
+ "name": "Jon",
+ },
},
- },
- email.Recipient{
- Name: "Arya Stark",
- Address: "[email protected]",
- Params: email.Params{
- "name": "Arya",
+ dto.Recipient{
+ Name: "Arya Stark",
+ Address: "[email protected]",
+ Props: dto.Props{
+ "name": "Arya",
+ },
},
},
- }
-
- err := sender.BatchSend(ctx, "echo_test", email.Params{}, "Fider Test", to)
- Expect(err).IsNil()
+ TemplateName: "echo_test",
+ })
Expect(requests).HasLen(2)
diff --git a/app/services/httpclient/httpclient.go b/app/services/httpclient/httpclient.go
new file mode 100644
index 000000000..ea258ae82
--- /dev/null
+++ b/app/services/httpclient/httpclient.go
@@ -0,0 +1,65 @@
+package httpclient
+
+import (
+ "context"
+ "io/ioutil"
+ "net/http"
+ "time"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/env"
+)
+
+func init() {
+ http.DefaultClient.Timeout = 30 * time.Second
+ bus.Register(Service{})
+}
+
+type Service struct{}
+
+func (s Service) Name() string {
+ return "HTTP"
+}
+
+func (s Service) Category() string {
+ return "httpclient"
+}
+
+func (s Service) Enabled() bool {
+ return !env.IsTest()
+}
+
+func (s Service) Init() {
+ bus.AddHandler(requestHandler)
+}
+
+func requestHandler(ctx context.Context, c *cmd.HTTPRequest) error {
+ req, err := http.NewRequest(c.Method, c.URL, c.Body)
+ if err != nil {
+ return err
+ }
+ req = req.WithContext(ctx)
+
+ for k, v := range c.Headers {
+ req.Header.Set(k, v)
+ }
+ if c.BasicAuth != nil {
+ req.SetBasicAuth(c.BasicAuth.User, c.BasicAuth.Password)
+ }
+
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return err
+ }
+
+ defer res.Body.Close()
+ respBody, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ return err
+ }
+
+ c.ResponseBody = respBody
+ c.ResponseStatusCode = res.StatusCode
+ return nil
+}
diff --git a/app/services/httpclient/httpclientmock/httpclientmock.go b/app/services/httpclient/httpclientmock/httpclientmock.go
new file mode 100644
index 000000000..901e6cadf
--- /dev/null
+++ b/app/services/httpclient/httpclientmock/httpclientmock.go
@@ -0,0 +1,60 @@
+package httpclientmock
+
+import (
+ "context"
+ "net/http"
+ "time"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/env"
+)
+
+func init() {
+ //Increase transport timeouts when running Tests
+ if env.IsTest() {
+ transport := http.DefaultTransport.(*http.Transport)
+ transport.TLSHandshakeTimeout = 30 * time.Second
+ }
+}
+
+type Service struct{}
+
+func (s Service) Name() string {
+ return "Mock"
+}
+
+func (s Service) Category() string {
+ return "httpclient"
+}
+
+var RequestsHistory = make([]*http.Request, 0)
+
+func (s Service) Enabled() bool {
+ return env.IsTest()
+}
+
+func (s Service) Init() {
+ RequestsHistory = make([]*http.Request, 0)
+ bus.AddHandler(requestHandler)
+}
+
+func requestHandler(ctx context.Context, c *cmd.HTTPRequest) error {
+ req, err := http.NewRequest(c.Method, c.URL, c.Body)
+ if err != nil {
+ return err
+ }
+
+ for k, v := range c.Headers {
+ req.Header.Set(k, v)
+ }
+ if c.BasicAuth != nil {
+ req.SetBasicAuth(c.BasicAuth.User, c.BasicAuth.Password)
+ }
+
+ RequestsHistory = append(RequestsHistory, req)
+
+ c.ResponseStatusCode = http.StatusOK
+ c.ResponseBody = []byte("")
+ return nil
+}
diff --git a/app/services/log/console/console.go b/app/services/log/console/console.go
new file mode 100644
index 000000000..46adba46b
--- /dev/null
+++ b/app/services/log/console/console.go
@@ -0,0 +1,103 @@
+package console
+
+import (
+ "context"
+ stdLog "log"
+ "os"
+ "time"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/color"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/log"
+)
+
+var stdOut = stdLog.New(os.Stdout, "", 0)
+
+func init() {
+ bus.Register(Service{})
+}
+
+type Service struct{}
+
+func (s Service) Name() string {
+ return "Console"
+}
+
+func (s Service) Category() string {
+ return "log"
+}
+
+func (s Service) Enabled() bool {
+ return !env.IsTest()
+}
+
+func (s Service) Init() {
+ bus.AddListener(logDebug)
+ bus.AddListener(logWarn)
+ bus.AddListener(logInfo)
+ bus.AddListener(logError)
+}
+
+func logDebug(ctx context.Context, c *cmd.LogDebug) {
+ writeLog(ctx, log.DEBUG, c.Message, c.Props)
+}
+
+func logWarn(ctx context.Context, c *cmd.LogWarn) {
+ writeLog(ctx, log.WARN, c.Message, c.Props)
+}
+
+func logInfo(ctx context.Context, c *cmd.LogInfo) {
+ writeLog(ctx, log.INFO, c.Message, c.Props)
+}
+
+func logError(ctx context.Context, c *cmd.LogError) {
+ if c.Err != nil {
+ writeLog(ctx, log.ERROR, c.Err.Error(), c.Props)
+ } else if c.Message != "" {
+ writeLog(ctx, log.ERROR, c.Message, c.Props)
+ } else {
+ writeLog(ctx, log.ERROR, "nil", c.Props)
+ }
+}
+
+func writeLog(ctx context.Context, level log.Level, message string, props dto.Props) {
+ if !log.IsEnabled(level) {
+ return
+ }
+
+ props = log.GetProperties(ctx).Merge(props)
+ message = log.Parse(message, props, true)
+ tag := props[log.PropertyKeyTag]
+ if tag == nil {
+ tag = "???"
+ }
+
+ contextID := props[log.PropertyKeyContextID]
+ if contextID == nil {
+ stdOut.Printf("%s [%s] [%s] %s\n", colorizeLevel(level), time.Now().Format(time.RFC3339), tag, message)
+ } else {
+ stdOut.Printf("%s [%s] [%s] [%s] %s\n", colorizeLevel(level), time.Now().Format(time.RFC3339), tag, contextID, message)
+ }
+}
+
+func colorizeLevel(level log.Level) string {
+ var colorFunc func(interface{}) string
+
+ switch level {
+ case log.DEBUG:
+ colorFunc = color.Magenta
+ case log.INFO:
+ colorFunc = color.Blue
+ case log.WARN:
+ colorFunc = color.Yellow
+ case log.ERROR:
+ colorFunc = color.Red
+ default:
+ colorFunc = color.Red
+ }
+
+ return color.Bold(colorFunc(level.String()))
+}
diff --git a/app/services/log/sql/sql.go b/app/services/log/sql/sql.go
new file mode 100644
index 000000000..3f95199bd
--- /dev/null
+++ b/app/services/log/sql/sql.go
@@ -0,0 +1,80 @@
+package sql
+
+import (
+ "context"
+ "time"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/log"
+)
+
+func init() {
+ bus.Register(Service{})
+}
+
+type Service struct{}
+
+func (s Service) Name() string {
+ return "SQL"
+}
+
+func (s Service) Category() string {
+ return "log"
+}
+
+func (s Service) Enabled() bool {
+ return !env.IsTest()
+}
+
+func (s Service) Init() {
+ bus.AddListener(logDebug)
+ bus.AddListener(logWarn)
+ bus.AddListener(logInfo)
+ bus.AddListener(logError)
+}
+
+func logDebug(ctx context.Context, c *cmd.LogDebug) {
+ writeLog(ctx, log.DEBUG, c.Message, c.Props)
+}
+
+func logWarn(ctx context.Context, c *cmd.LogWarn) {
+ writeLog(ctx, log.WARN, c.Message, c.Props)
+}
+
+func logInfo(ctx context.Context, c *cmd.LogInfo) {
+ writeLog(ctx, log.INFO, c.Message, c.Props)
+}
+
+func logError(ctx context.Context, c *cmd.LogError) {
+ if c.Err != nil {
+ writeLog(ctx, log.ERROR, c.Err.Error(), c.Props)
+ } else if c.Message != "" {
+ writeLog(ctx, log.ERROR, c.Message, c.Props)
+ } else {
+ writeLog(ctx, log.ERROR, "nil", c.Props)
+ }
+}
+
+func writeLog(ctx context.Context, level log.Level, message string, props dto.Props) {
+ if !log.IsEnabled(level) {
+ return
+ }
+
+ props = log.GetProperties(ctx).Merge(props)
+
+ message = log.Parse(message, props, false)
+ tag := props[log.PropertyKeyTag]
+ if tag == nil {
+ tag = "???"
+ }
+ delete(props, log.PropertyKeyTag)
+
+ go dbx.Connection().Exec(
+ "INSERT INTO logs (tag, level, text, created_at, properties) VALUES ($1, $2, $3, $4, $5)",
+ tag, level.String(), message, time.Now(), props,
+ )
+}
diff --git a/app/services/oauth/oauth.go b/app/services/oauth/oauth.go
new file mode 100644
index 000000000..da85f811a
--- /dev/null
+++ b/app/services/oauth/oauth.go
@@ -0,0 +1,300 @@
+package oauth
+
+import (
+ "context"
+ "fmt"
+ "net/url"
+ "strings"
+
+ "github.com/dgrijalva/jwt-go"
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/jsonq"
+ "github.com/getfider/fider/app/pkg/validate"
+ "github.com/getfider/fider/app/pkg/web"
+ "golang.org/x/oauth2"
+ "golang.org/x/oauth2/facebook"
+ "golang.org/x/oauth2/github"
+)
+
+func init() {
+ bus.Register(Service{})
+}
+
+type Service struct{}
+
+func (s Service) Name() string {
+ return "HTTP"
+}
+
+func (s Service) Category() string {
+ return "OAuth"
+}
+
+func (s Service) Enabled() bool {
+ return true
+}
+
+func (s Service) Init() {
+ bus.AddHandler(parseOAuthRawProfile)
+ bus.AddHandler(getOAuthAuthorizationURL)
+ bus.AddHandler(getOAuthProfile)
+ bus.AddHandler(getOAuthRawProfile)
+ bus.AddHandler(listActiveOAuthProviders)
+ bus.AddHandler(listAllOAuthProviders)
+}
+
+func getProviderStatus(key string) int {
+ if key == "" {
+ return enum.OAuthConfigDisabled
+ }
+ return enum.OAuthConfigEnabled
+}
+
+var (
+ systemProviders = []*models.OAuthConfig{
+ &models.OAuthConfig{
+ Provider: app.FacebookProvider,
+ DisplayName: "Facebook",
+ ProfileURL: "https://graph.facebook.com/me?fields=name,email",
+ Status: getProviderStatus(env.Config.OAuth.Facebook.AppID),
+ ClientID: env.Config.OAuth.Facebook.AppID,
+ ClientSecret: env.Config.OAuth.Facebook.Secret,
+ Scope: "public_profile email",
+ AuthorizeURL: facebook.Endpoint.AuthURL,
+ TokenURL: facebook.Endpoint.TokenURL,
+ JSONUserIDPath: "id",
+ JSONUserNamePath: "name",
+ JSONUserEmailPath: "email",
+ },
+ &models.OAuthConfig{
+ Provider: app.GoogleProvider,
+ DisplayName: "Google",
+ ProfileURL: "https://www.googleapis.com/oauth2/v2/userinfo",
+ Status: getProviderStatus(env.Config.OAuth.Google.ClientID),
+ ClientID: env.Config.OAuth.Google.ClientID,
+ ClientSecret: env.Config.OAuth.Google.Secret,
+ Scope: "profile email",
+ AuthorizeURL: "https://accounts.google.com/o/oauth2/v2/auth",
+ TokenURL: "https://www.googleapis.com/oauth2/v4/token",
+ JSONUserIDPath: "id",
+ JSONUserNamePath: "name",
+ JSONUserEmailPath: "email",
+ },
+ &models.OAuthConfig{
+ Provider: app.GitHubProvider,
+ DisplayName: "GitHub",
+ ProfileURL: "https://api.github.com/user",
+ Status: getProviderStatus(env.Config.OAuth.GitHub.ClientID),
+ ClientID: env.Config.OAuth.GitHub.ClientID,
+ ClientSecret: env.Config.OAuth.GitHub.Secret,
+ Scope: "user:email",
+ AuthorizeURL: github.Endpoint.AuthURL,
+ TokenURL: github.Endpoint.TokenURL,
+ JSONUserIDPath: "id",
+ JSONUserNamePath: "name, login",
+ JSONUserEmailPath: "email",
+ },
+ }
+)
+
+func parseOAuthRawProfile(ctx context.Context, c *cmd.ParseOAuthRawProfile) error {
+ config, err := getConfig(ctx, c.Provider)
+ if err != nil {
+ return err
+ }
+
+ query := jsonq.New(c.Body)
+ profile := &dto.OAuthUserProfile{
+ ID: strings.TrimSpace(query.String(config.JSONUserIDPath)),
+ Name: strings.TrimSpace(query.String(config.JSONUserNamePath)),
+ Email: strings.ToLower(strings.TrimSpace(query.String(config.JSONUserEmailPath))),
+ }
+
+ if profile.ID == "" {
+ return app.ErrUserIDRequired
+ }
+
+ if profile.Name == "" && profile.Email != "" {
+ parts := strings.Split(profile.Email, "@")
+ profile.Name = parts[0]
+ }
+
+ if profile.Name == "" {
+ profile.Name = "Anonymous"
+ }
+
+ if len(validate.Email(profile.Email)) != 0 {
+ profile.Email = ""
+ }
+
+ c.Result = profile
+ return nil
+}
+
+func getOAuthAuthorizationURL(ctx context.Context, q *query.GetOAuthAuthorizationURL) error {
+ config, err := getConfig(ctx, q.Provider)
+ if err != nil {
+ return err
+ }
+
+ oauthBaseURL := web.OAuthBaseURL(ctx)
+ authURL, _ := url.Parse(config.AuthorizeURL)
+ parameters := url.Values{}
+ parameters.Add("client_id", config.ClientID)
+ parameters.Add("scope", config.Scope)
+ parameters.Add("redirect_uri", fmt.Sprintf("%s/oauth/%s/callback", oauthBaseURL, q.Provider))
+ parameters.Add("response_type", "code")
+ parameters.Add("state", q.Redirect+"|"+q.Identifier)
+ authURL.RawQuery = parameters.Encode()
+ q.Result = authURL.String()
+ return nil
+}
+
+func getOAuthProfile(ctx context.Context, q *query.GetOAuthProfile) error {
+ config, err := getConfig(ctx, q.Provider)
+ if err != nil {
+ return err
+ }
+
+ if config.Status == enum.OAuthConfigDisabled {
+ return errors.New("Provider %s is disabled", q.Provider)
+ }
+
+ rawProfile := &query.GetOAuthRawProfile{Provider: q.Provider, Code: q.Code}
+ err = bus.Dispatch(ctx, rawProfile)
+ if err != nil {
+ return err
+ }
+
+ parseRawProfile := &cmd.ParseOAuthRawProfile{Provider: q.Provider, Body: rawProfile.Result}
+ err = bus.Dispatch(ctx, parseRawProfile)
+ if err != nil {
+ return err
+ }
+
+ q.Result = parseRawProfile.Result
+ return nil
+}
+
+func getOAuthRawProfile(ctx context.Context, q *query.GetOAuthRawProfile) error {
+ config, err := getConfig(ctx, q.Provider)
+ if err != nil {
+ return err
+ }
+
+ oauthBaseURL := web.OAuthBaseURL(ctx)
+ exchange := (&oauth2.Config{
+ ClientID: config.ClientID,
+ ClientSecret: config.ClientSecret,
+ Endpoint: oauth2.Endpoint{
+ AuthURL: config.AuthorizeURL,
+ TokenURL: config.TokenURL,
+ },
+ RedirectURL: fmt.Sprintf("%s/oauth/%s/callback", oauthBaseURL, q.Provider),
+ }).Exchange
+
+ oauthToken, err := exchange(ctx, q.Code)
+ if err != nil {
+ return err
+ }
+
+ if config.ProfileURL == "" {
+ parts := strings.Split(oauthToken.AccessToken, ".")
+ if len(parts) != 3 {
+ return errors.New("AccessToken is not JWT")
+ }
+
+ body, _ := jwt.DecodeSegment(parts[1])
+ q.Result = string(body)
+ return nil
+ }
+
+ req := &cmd.HTTPRequest{
+ URL: config.ProfileURL,
+ Method: "GET",
+ Headers: map[string]string{
+ "Authorization": "Bearer " + oauthToken.AccessToken,
+ },
+ }
+
+ if err := bus.Dispatch(ctx, req); err != nil {
+ return err
+ }
+
+ if req.ResponseStatusCode != 200 {
+ return errors.New("Failed to request profile. Status Code: %d. Body: %s", req.ResponseStatusCode, string(req.ResponseBody))
+ }
+
+ q.Result = string(req.ResponseBody)
+ return nil
+}
+
+func listActiveOAuthProviders(ctx context.Context, q *query.ListActiveOAuthProviders) error {
+ allOAuthProviders := &query.ListAllOAuthProviders{}
+ err := bus.Dispatch(ctx, allOAuthProviders)
+ if err != nil {
+ return err
+ }
+
+ list := make([]*dto.OAuthProviderOption, 0)
+ for _, p := range allOAuthProviders.Result {
+ if p.IsEnabled {
+ list = append(list, p)
+ }
+ }
+ q.Result = list
+ return nil
+}
+
+func listAllOAuthProviders(ctx context.Context, q *query.ListAllOAuthProviders) error {
+ oauthProviders := &query.ListCustomOAuthConfig{}
+ err := bus.Dispatch(ctx, oauthProviders)
+ if err != nil {
+ return errors.Wrap(err, "failed to get list of custom OAuth providers")
+ }
+
+ oauthProviders.Result = append(oauthProviders.Result, systemProviders...)
+
+ list := make([]*dto.OAuthProviderOption, 0)
+
+ oauthBaseURL := web.OAuthBaseURL(ctx)
+ for _, p := range oauthProviders.Result {
+ list = append(list, &dto.OAuthProviderOption{
+ Provider: p.Provider,
+ DisplayName: p.DisplayName,
+ ClientID: p.ClientID,
+ URL: fmt.Sprintf("/oauth/%s", p.Provider),
+ CallbackURL: fmt.Sprintf("%s/oauth/%s/callback", oauthBaseURL, p.Provider),
+ IsCustomProvider: string(p.Provider[0]) == "_",
+ LogoBlobKey: p.LogoBlobKey,
+ IsEnabled: p.Status == enum.OAuthConfigEnabled,
+ })
+ }
+
+ q.Result = list
+ return nil
+}
+
+func getConfig(ctx context.Context, provider string) (*models.OAuthConfig, error) {
+ for _, config := range systemProviders {
+ if config.Status == enum.OAuthConfigEnabled && config.Provider == provider {
+ return config, nil
+ }
+ }
+
+ getCustomOAuth := &query.GetCustomOAuthConfigByProvider{Provider: provider}
+ err := bus.Dispatch(ctx, getCustomOAuth)
+ if err != nil {
+ return nil, err
+ }
+
+ return getCustomOAuth.Result, nil
+}
diff --git a/app/services/oauth/oauth_test.go b/app/services/oauth/oauth_test.go
new file mode 100644
index 000000000..ef69c1abc
--- /dev/null
+++ b/app/services/oauth/oauth_test.go
@@ -0,0 +1,404 @@
+package oauth_test
+
+import (
+ "context"
+ "crypto/tls"
+ "net/http/httptest"
+ "net/url"
+ "testing"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/web"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/services/oauth"
+)
+
+func newGetContext(rawurl string) *web.Context {
+ u, _ := url.Parse(rawurl)
+ e := web.New(nil)
+ res := httptest.NewRecorder()
+ req := httptest.NewRequest("GET", u.RequestURI(), nil)
+ req.Host = u.Host
+
+ if u.Scheme == "https" {
+ req.TLS = &tls.ConnectionState{}
+ }
+
+ return web.NewContext(e, req, res, nil)
+}
+func TestGetAuthURL_Facebook(t *testing.T) {
+ RegisterT(t)
+ bus.Init(&oauth.Service{})
+
+ ctx := newGetContext("http://login.test.fider.io:3000")
+ authURL := &query.GetOAuthAuthorizationURL{
+ Provider: app.FacebookProvider,
+ Redirect: "http://example.org",
+ Identifier: "456",
+ }
+
+ err := bus.Dispatch(ctx, authURL)
+ Expect(err).IsNil()
+ Expect(authURL.Result).Equals("https://www.facebook.com/v3.1/dialog/oauth?client_id=FB_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Ffacebook%2Fcallback&response_type=code&scope=public_profile+email&state=http%3A%2F%2Fexample.org%7C456")
+}
+
+func TestGetAuthURL_Google(t *testing.T) {
+ RegisterT(t)
+ bus.Init(&oauth.Service{})
+
+ ctx := newGetContext("http://login.test.fider.io:3000")
+
+ authURL := &query.GetOAuthAuthorizationURL{
+ Provider: app.GoogleProvider,
+ Redirect: "http://example.org",
+ Identifier: "123",
+ }
+
+ err := bus.Dispatch(ctx, authURL)
+ Expect(err).IsNil()
+ Expect(authURL.Result).Equals("https://accounts.google.com/o/oauth2/v2/auth?client_id=GO_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgoogle%2Fcallback&response_type=code&scope=profile+email&state=http%3A%2F%2Fexample.org%7C123")
+}
+
+func TestGetAuthURL_GitHub(t *testing.T) {
+ RegisterT(t)
+ bus.Init(&oauth.Service{})
+
+ ctx := newGetContext("http://login.test.fider.io:3000")
+
+ authURL := &query.GetOAuthAuthorizationURL{
+ Provider: app.GitHubProvider,
+ Redirect: "http://example.org",
+ Identifier: "456",
+ }
+
+ err := bus.Dispatch(ctx, authURL)
+ Expect(err).IsNil()
+ Expect(authURL.Result).Equals("https://github.com/login/oauth/authorize?client_id=GH_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgithub%2Fcallback&response_type=code&scope=user%3Aemail&state=http%3A%2F%2Fexample.org%7C456")
+}
+
+func TestGetAuthURL_Custom(t *testing.T) {
+ RegisterT(t)
+ bus.Init(&oauth.Service{})
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ if q.Provider == "_custom" {
+ q.Result = &models.OAuthConfig{
+ Provider: q.Provider,
+ ClientID: "CU_CL_ID",
+ Scope: "profile email",
+ AuthorizeURL: "https://example.org/oauth/authorize",
+ }
+ }
+ return nil
+ })
+
+ ctx := newGetContext("http://login.test.fider.io:3000")
+ authURL := &query.GetOAuthAuthorizationURL{
+ Provider: "_custom",
+ Redirect: "http://example.org",
+ Identifier: "456",
+ }
+
+ err := bus.Dispatch(ctx, authURL)
+ Expect(err).IsNil()
+ Expect(authURL.Result).Equals("https://example.org/oauth/authorize?client_id=CU_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2F_custom%2Fcallback&response_type=code&scope=profile+email&state=http%3A%2F%2Fexample.org%7C456")
+}
+
+func TestParseProfileResponse_AllFields(t *testing.T) {
+ RegisterT(t)
+ bus.Init(&oauth.Service{})
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ if q.Provider == "_test1" {
+ q.Result = &models.OAuthConfig{
+ Provider: q.Provider,
+ JSONUserIDPath: "id",
+ JSONUserNamePath: "name",
+ JSONUserEmailPath: "email",
+ }
+ }
+ return nil
+ })
+
+ ctx := newGetContext("http://login.test.fider.io:3000")
+ profile := &cmd.ParseOAuthRawProfile{
+ Provider: "_test1",
+ Body: `{"name":"Jon Snow","email":"jon\u0040got.com","id":"789654"}`,
+ }
+
+ err := bus.Dispatch(ctx, profile)
+ Expect(err).IsNil()
+
+ Expect(profile.Result.ID).Equals("789654")
+ Expect(profile.Result.Name).Equals("Jon Snow")
+ Expect(profile.Result.Email).Equals("[email protected]")
+}
+
+func TestParseProfileResponse_WithoutEmail(t *testing.T) {
+ RegisterT(t)
+ bus.Init(&oauth.Service{})
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ if q.Provider == "_test1" {
+ q.Result = &models.OAuthConfig{
+ Provider: q.Provider,
+ JSONUserIDPath: "id",
+ JSONUserNamePath: "name",
+ JSONUserEmailPath: "email",
+ }
+ }
+ return nil
+ })
+
+ ctx := newGetContext("http://login.test.fider.io:3000")
+ profile := &cmd.ParseOAuthRawProfile{
+ Provider: "_test1",
+ Body: `{"name":"Jon Snow","id":"1"}`,
+ }
+ err := bus.Dispatch(ctx, profile)
+ Expect(err).IsNil()
+
+ Expect(profile.Result.ID).Equals("1")
+ Expect(profile.Result.Name).Equals("Jon Snow")
+ Expect(profile.Result.Email).Equals("")
+}
+
+func TestParseProfileResponse_NestedData(t *testing.T) {
+ RegisterT(t)
+ bus.Init(&oauth.Service{})
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ if q.Provider == "_test1" {
+ q.Result = &models.OAuthConfig{
+ Provider: q.Provider,
+ JSONUserIDPath: "id",
+ JSONUserNamePath: "profile.name",
+ JSONUserEmailPath: "profile.email",
+ }
+ }
+ return nil
+ })
+
+ ctx := newGetContext("http://login.test.fider.io:3000")
+ profile := &cmd.ParseOAuthRawProfile{
+ Provider: "_test1",
+ Body: `{
+ "id": "123",
+ "profile": {
+ "name": "Jon Snow",
+ "email": "[email protected]"
+ }
+ }`,
+ }
+ err := bus.Dispatch(ctx, profile)
+ Expect(err).IsNil()
+
+ Expect(profile.Result.ID).Equals("123")
+ Expect(profile.Result.Name).Equals("Jon Snow")
+ Expect(profile.Result.Email).Equals("[email protected]")
+}
+
+func TestParseProfileResponse_WithFallback(t *testing.T) {
+ RegisterT(t)
+ bus.Init(&oauth.Service{})
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ if q.Provider == "_test1" {
+ q.Result = &models.OAuthConfig{
+ Provider: q.Provider,
+ JSONUserIDPath: "id",
+ JSONUserNamePath: "profile.name, profile.login",
+ JSONUserEmailPath: "profile.email",
+ }
+ }
+ return nil
+ })
+
+ ctx := newGetContext("http://login.test.fider.io:3000")
+ profile := &cmd.ParseOAuthRawProfile{
+ Provider: "_test1",
+ Body: `{
+ "id": 123,
+ "profile": {
+ "login": "jonny",
+ "email": "[email protected]"
+ }
+ }`,
+ }
+ err := bus.Dispatch(ctx, profile)
+ Expect(err).IsNil()
+
+ Expect(profile.Result.ID).Equals("123")
+ Expect(profile.Result.Name).Equals("jonny")
+ Expect(profile.Result.Email).Equals("[email protected]")
+}
+
+func TestParseProfileResponse_UseEmailWhenNameIsEmpty(t *testing.T) {
+ RegisterT(t)
+ bus.Init(&oauth.Service{})
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ if q.Provider == "_test1" {
+ q.Result = &models.OAuthConfig{
+ Provider: q.Provider,
+ JSONUserIDPath: "id",
+ JSONUserNamePath: "profile.name",
+ JSONUserEmailPath: "profile.email",
+ }
+ }
+ return nil
+ })
+
+ ctx := newGetContext("http://login.test.fider.io:3000")
+ profile := &cmd.ParseOAuthRawProfile{
+ Provider: "_test1",
+ Body: `{
+ "id": "123",
+ "profile": {
+ "email": "[email protected]"
+ }
+ }`,
+ }
+ err := bus.Dispatch(ctx, profile)
+ Expect(err).IsNil()
+
+ Expect(profile.Result.ID).Equals("123")
+ Expect(profile.Result.Name).Equals("jon")
+ Expect(profile.Result.Email).Equals("[email protected]")
+}
+
+func TestParseProfileResponse_InvalidEmail(t *testing.T) {
+ RegisterT(t)
+ bus.Init(&oauth.Service{})
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ if q.Provider == "_test1" {
+ q.Result = &models.OAuthConfig{
+ Provider: q.Provider,
+ JSONUserIDPath: "id",
+ JSONUserNamePath: "profile.name",
+ JSONUserEmailPath: "profile.email",
+ }
+ }
+ return nil
+ })
+
+ ctx := newGetContext("http://login.test.fider.io:3000")
+ profile := &cmd.ParseOAuthRawProfile{
+ Provider: "_test1",
+ Body: `{
+ "id": "AB123",
+ "profile": {
+ "name": "Jon Snow",
+ "email": "jon"
+ }
+ }`,
+ }
+ err := bus.Dispatch(ctx, profile)
+ Expect(err).IsNil()
+
+ Expect(profile.Result.ID).Equals("AB123")
+ Expect(profile.Result.Name).Equals("Jon Snow")
+ Expect(profile.Result.Email).Equals("")
+}
+
+func TestParseProfileResponse_EmptyID(t *testing.T) {
+ RegisterT(t)
+ bus.Init(&oauth.Service{})
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ if q.Provider == "_test1" {
+ q.Result = &models.OAuthConfig{
+ Provider: q.Provider,
+ JSONUserIDPath: "id",
+ JSONUserNamePath: "name",
+ JSONUserEmailPath: "email",
+ }
+ }
+ return nil
+ })
+
+ ctx := newGetContext("http://login.test.fider.io:3000")
+ profile := &cmd.ParseOAuthRawProfile{
+ Provider: "_test1",
+ Body: `{}`,
+ }
+
+ err := bus.Dispatch(ctx, profile)
+ Expect(errors.Cause(err)).Equals(app.ErrUserIDRequired)
+ Expect(profile.Result).IsNil()
+}
+
+func TestParseProfileResponse_EmptyName(t *testing.T) {
+ RegisterT(t)
+ bus.Init(&oauth.Service{})
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ if q.Provider == "_test1" {
+ q.Result = &models.OAuthConfig{
+ Provider: q.Provider,
+ JSONUserIDPath: "id",
+ JSONUserNamePath: "name",
+ JSONUserEmailPath: "email",
+ }
+ }
+ return nil
+ })
+
+ ctx := newGetContext("http://login.test.fider.io:3000")
+ profile := &cmd.ParseOAuthRawProfile{
+ Provider: "_test1",
+ Body: `{ "id": "A0" }`,
+ }
+
+ err := bus.Dispatch(ctx, profile)
+ Expect(err).IsNil()
+ Expect(profile.Result.ID).Equals("A0")
+ Expect(profile.Result.Name).Equals("Anonymous")
+}
+
+func TestCustomOAuth_Disabled(t *testing.T) {
+ RegisterT(t)
+ bus.Init(&oauth.Service{})
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ if q.Provider == "_test1" {
+ q.Result = &models.OAuthConfig{
+ Provider: q.Provider,
+ JSONUserIDPath: "id",
+ JSONUserNamePath: "name",
+ JSONUserEmailPath: "email",
+ Status: enum.OAuthConfigDisabled,
+ }
+ }
+ return nil
+ })
+
+ ctx := newGetContext("http://login.test.fider.io:3000")
+ rawProfile := &cmd.ParseOAuthRawProfile{
+ Provider: "_test1",
+ Body: `{ "id": "A0", "name": "John" }`,
+ }
+
+ err := bus.Dispatch(ctx, rawProfile)
+ Expect(err).IsNil()
+ Expect(rawProfile.Result.ID).Equals("A0")
+ Expect(rawProfile.Result.Name).Equals("John")
+
+ oauthProfile := &query.GetOAuthProfile{
+ Provider: "_test1",
+ }
+
+ err = bus.Dispatch(ctx, oauthProfile)
+ Expect(err).IsNotNil()
+ Expect(oauthProfile.Result).IsNil()
+}
diff --git a/app/services/sqlstore/postgres/attachment.go b/app/services/sqlstore/postgres/attachment.go
new file mode 100644
index 000000000..614a1923d
--- /dev/null
+++ b/app/services/sqlstore/postgres/attachment.go
@@ -0,0 +1,107 @@
+package postgres
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/rand"
+ "github.com/getfider/fider/app/services/blob"
+)
+
+func setAttachments(ctx context.Context, c *cmd.SetAttachments) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ postID := c.Post.ID
+ var commentID sql.NullInt64
+ if c.Comment != nil {
+ commentID.Scan(c.Comment.ID)
+ }
+
+ for _, attachment := range c.Attachments {
+ if attachment.Remove {
+ if _, err := trx.Execute(
+ "DELETE FROM attachments WHERE tenant_id = $1 AND post_id = $2 AND (comment_id = $3 OR ($3 IS NULL AND comment_id IS NULL)) AND attachment_bkey = $4",
+ tenant.ID, postID, commentID, attachment.BlobKey,
+ ); err != nil {
+ return errors.Wrap(err, "failed to delete attachment")
+ }
+ } else {
+ if _, err := trx.Execute(
+ "INSERT INTO attachments (tenant_id, post_id, comment_id, user_id, attachment_bkey) VALUES ($1, $2, $3, $4, $5)",
+ tenant.ID, postID, commentID, user.ID, attachment.BlobKey,
+ ); err != nil {
+ return errors.Wrap(err, "failed to insert attachment")
+ }
+ }
+ }
+
+ return nil
+ })
+}
+
+func getAttachments(ctx context.Context, q *query.GetAttachments) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ q.Result = make([]string, 0)
+
+ postID := q.Post.ID
+ var commentID sql.NullInt64
+ if q.Comment != nil {
+ commentID.Scan(q.Comment.ID)
+ }
+
+ type entry struct {
+ BlobKey string `db:"attachment_bkey"`
+ }
+
+ entries := []*entry{}
+ err := trx.Select(&entries, `
+ SELECT attachment_bkey
+ FROM attachments
+ WHERE tenant_id = $1 AND post_id = $2 AND (comment_id = $3 OR ($3 IS NULL AND comment_id IS NULL))
+ `, tenant.ID, postID, commentID)
+ if err != nil {
+ return errors.Wrap(err, "failed to get attachments")
+ }
+
+ q.Result = make([]string, len(entries))
+ for i, entry := range entries {
+ q.Result[i] = entry.BlobKey
+ }
+
+ return nil
+ })
+}
+
+func uploadImage(ctx context.Context, c *cmd.UploadImage) error {
+ if c.Image.Upload != nil && len(c.Image.Upload.Content) > 0 {
+ bkey := fmt.Sprintf("%s/%s-%s", c.Folder, rand.String(64), blob.SanitizeFileName(c.Image.Upload.FileName))
+ err := bus.Dispatch(ctx, &cmd.StoreBlob{
+ Key: bkey,
+ Content: c.Image.Upload.Content,
+ ContentType: c.Image.Upload.ContentType,
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to upload new blob")
+ }
+ c.Image.BlobKey = bkey
+ }
+ return nil
+}
+
+func uploadImages(ctx context.Context, c *cmd.UploadImages) error {
+ for _, img := range c.Images {
+ if err := bus.Dispatch(ctx, &cmd.UploadImage{
+ Image: img,
+ Folder: c.Folder,
+ }); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/app/services/sqlstore/postgres/attachment_test.go b/app/services/sqlstore/postgres/attachment_test.go
new file mode 100644
index 000000000..38daf69ec
--- /dev/null
+++ b/app/services/sqlstore/postgres/attachment_test.go
@@ -0,0 +1,91 @@
+package postgres_test
+
+import (
+ "context"
+ "testing"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
+)
+
+func TestUploadImage(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.StoreBlob) error {
+ return nil
+ })
+
+ uploadImage := &cmd.UploadImage{
+ Image: &models.ImageUpload{
+ Upload: &models.ImageUploadData{
+ Content: []byte("Hello World"),
+ ContentType: "text/plain",
+ },
+ },
+ Folder: "avatars",
+ }
+ err := bus.Dispatch(ctx, uploadImage)
+ Expect(err).IsNil()
+ Expect(uploadImage.Image.BlobKey).ContainsSubstring("avatars/")
+ Expect(uploadImage.Image.BlobKey).HasLen(73)
+}
+
+func TestUploadImage_NoContent(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.StoreBlob) error {
+ return nil
+ })
+
+ uploadImage := &cmd.UploadImage{
+ Image: &models.ImageUpload{
+ Upload: &models.ImageUploadData{
+ Content: []byte(""),
+ },
+ },
+ Folder: "avatars",
+ }
+ err := bus.Dispatch(ctx, uploadImage)
+ Expect(err).IsNil()
+ Expect(uploadImage.Image.BlobKey).Equals("")
+}
+
+func TestUploadMultipleImages(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.StoreBlob) error {
+ return nil
+ })
+
+ uploadImages := &cmd.UploadImages{
+ Images: []*models.ImageUpload{
+ &models.ImageUpload{
+ Upload: &models.ImageUploadData{
+ Content: []byte("Hello World 1"),
+ ContentType: "text/plain",
+ },
+ },
+ &models.ImageUpload{
+ Upload: &models.ImageUploadData{
+ Content: []byte("Hello World 2"),
+ ContentType: "text/plain",
+ },
+ },
+ },
+ Folder: "avatars",
+ }
+ err := bus.Dispatch(ctx, uploadImages)
+ Expect(err).IsNil()
+
+ Expect(uploadImages.Images[0].BlobKey).ContainsSubstring("avatars/")
+ Expect(uploadImages.Images[0].BlobKey).HasLen(73)
+
+ Expect(uploadImages.Images[1].BlobKey).ContainsSubstring("avatars/")
+ Expect(uploadImages.Images[1].BlobKey).HasLen(73)
+}
diff --git a/app/services/sqlstore/postgres/comment.go b/app/services/sqlstore/postgres/comment.go
new file mode 100644
index 000000000..da02cca0a
--- /dev/null
+++ b/app/services/sqlstore/postgres/comment.go
@@ -0,0 +1,197 @@
+package postgres
+
+import (
+ "context"
+ "time"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+type dbComment struct {
+ ID int `db:"id"`
+ Content string `db:"content"`
+ CreatedAt time.Time `db:"created_at"`
+ User *dbUser `db:"user"`
+ Attachments []string `db:"attachment_bkeys"`
+ EditedAt dbx.NullTime `db:"edited_at"`
+ EditedBy *dbUser `db:"edited_by"`
+}
+
+func (c *dbComment) toModel(ctx context.Context) *models.Comment {
+ comment := &models.Comment{
+ ID: c.ID,
+ Content: c.Content,
+ CreatedAt: c.CreatedAt,
+ User: c.User.toModel(ctx),
+ Attachments: c.Attachments,
+ }
+ if c.EditedAt.Valid {
+ comment.EditedBy = c.EditedBy.toModel(ctx)
+ comment.EditedAt = &c.EditedAt.Time
+ }
+ return comment
+}
+
+func addNewComment(ctx context.Context, c *cmd.AddNewComment) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ var id int
+ if err := trx.Get(&id, `
+ INSERT INTO comments (tenant_id, post_id, content, user_id, created_at)
+ VALUES ($1, $2, $3, $4, $5)
+ RETURNING id
+ `, tenant.ID, c.Post.ID, c.Content, user.ID, time.Now()); err != nil {
+ return errors.Wrap(err, "failed add new comment")
+ }
+
+ if err := internalAddSubscriber(trx, c.Post, tenant, user, false); err != nil {
+ return err
+ }
+
+ q := &query.GetCommentByID{CommentID: id}
+ if err := getCommentByID(ctx, q); err != nil {
+ return err
+ }
+ c.Result = q.Result
+
+ return nil
+ })
+}
+
+func updateComment(ctx context.Context, c *cmd.UpdateComment) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ _, err := trx.Execute(`
+ UPDATE comments SET content = $1, edited_at = $2, edited_by_id = $3
+ WHERE id = $4 AND tenant_id = $5`, c.Content, time.Now(), user.ID, c.CommentID, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed update comment")
+ }
+ return nil
+ })
+}
+
+func deleteComment(ctx context.Context, c *cmd.DeleteComment) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if _, err := trx.Execute(
+ "UPDATE comments SET deleted_at = $1, deleted_by_id = $2 WHERE id = $3 AND tenant_id = $4",
+ time.Now(), user.ID, c.CommentID, tenant.ID,
+ ); err != nil {
+ return errors.Wrap(err, "failed delete comment")
+ }
+ return nil
+ })
+}
+
+func getCommentByID(ctx context.Context, q *query.GetCommentByID) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ q.Result = nil
+
+ comment := dbComment{}
+ err := trx.Get(&comment,
+ `SELECT c.id,
+ c.content,
+ c.created_at,
+ c.edited_at,
+ u.id AS user_id,
+ u.name AS user_name,
+ u.email AS user_email,
+ u.role AS user_role,
+ u.status AS user_status,
+ u.avatar_type AS user_avatar_type,
+ u.avatar_bkey AS user_avatar_bkey,
+ e.id AS edited_by_id,
+ e.name AS edited_by_name,
+ e.email AS edited_by_email,
+ e.role AS edited_by_role,
+ e.status AS edited_by_status,
+ e.avatar_type AS edited_by_avatar_type,
+ e.avatar_bkey AS edited_by_avatar_bkey
+ FROM comments c
+ INNER JOIN users u
+ ON u.id = c.user_id
+ AND u.tenant_id = c.tenant_id
+ LEFT JOIN users e
+ ON e.id = c.edited_by_id
+ AND e.tenant_id = c.tenant_id
+ WHERE c.id = $1
+ AND c.tenant_id = $2
+ AND c.deleted_at IS NULL`, q.CommentID, tenant.ID)
+
+ if err != nil {
+ return err
+ }
+
+ q.Result = comment.toModel(ctx)
+ return nil
+ })
+}
+
+func getCommentsByPost(ctx context.Context, q *query.GetCommentsByPost) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ q.Result = make([]*models.Comment, 0)
+
+ comments := []*dbComment{}
+ err := trx.Select(&comments,
+ `WITH agg_attachments AS (
+ SELECT
+ c.id as comment_id,
+ ARRAY_REMOVE(ARRAY_AGG(at.attachment_bkey), NULL) as attachment_bkeys
+ FROM attachments at
+ INNER JOIN comments c
+ ON at.tenant_id = c.tenant_id
+ AND at.post_id = c.post_id
+ AND at.comment_id = c.id
+ WHERE at.post_id = $1
+ AND at.tenant_id = $2
+ AND at.comment_id IS NOT NULL
+ GROUP BY c.id
+ )
+ SELECT c.id,
+ c.content,
+ c.created_at,
+ c.edited_at,
+ u.id AS user_id,
+ u.name AS user_name,
+ u.email AS user_email,
+ u.role AS user_role,
+ u.status AS user_status,
+ u.avatar_type AS user_avatar_type,
+ u.avatar_bkey AS user_avatar_bkey,
+ e.id AS edited_by_id,
+ e.name AS edited_by_name,
+ e.email AS edited_by_email,
+ e.role AS edited_by_role,
+ e.status AS edited_by_status,
+ e.avatar_type AS edited_by_avatar_type,
+ e.avatar_bkey AS edited_by_avatar_bkey,
+ at.attachment_bkeys
+ FROM comments c
+ INNER JOIN posts p
+ ON p.id = c.post_id
+ AND p.tenant_id = c.tenant_id
+ INNER JOIN users u
+ ON u.id = c.user_id
+ AND u.tenant_id = c.tenant_id
+ LEFT JOIN users e
+ ON e.id = c.edited_by_id
+ AND e.tenant_id = c.tenant_id
+ LEFT JOIN agg_attachments at
+ ON at.comment_id = c.id
+ WHERE p.id = $1
+ AND p.tenant_id = $2
+ AND c.deleted_at IS NULL
+ ORDER BY c.created_at ASC`, q.Post.ID, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed get comments of post with id '%d'", q.Post.ID)
+ }
+
+ q.Result = make([]*models.Comment, len(comments))
+ for i, comment := range comments {
+ q.Result[i] = comment.toModel(ctx)
+ }
+ return nil
+ })
+}
diff --git a/app/storage/postgres/common.go b/app/services/sqlstore/postgres/common.go
similarity index 55%
rename from app/storage/postgres/common.go
rename to app/services/sqlstore/postgres/common.go
index 82d351727..8670e94dd 100644
--- a/app/storage/postgres/common.go
+++ b/app/services/sqlstore/postgres/common.go
@@ -1,12 +1,13 @@
package postgres
import (
+ "context"
"net/url"
"regexp"
"strings"
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/storage"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/pkg/web"
)
var onlyalphanumeric = regexp.MustCompile("[^a-zA-Z0-9 |]+")
@@ -18,15 +19,15 @@ func ToTSQuery(input string) string {
return strings.Join(strings.Fields(input), "|")
}
-func getViewData(view string) (string, []models.PostStatus, string) {
+func getViewData(view string) (string, []enum.PostStatus, string) {
var (
condition string
sort string
)
- statuses := []models.PostStatus{
- models.PostOpen,
- models.PostStarted,
- models.PostPlanned,
+ statuses := []enum.PostStatus{
+ enum.PostOpen,
+ enum.PostStarted,
+ enum.PostPlanned,
}
switch view {
case "recent":
@@ -40,24 +41,24 @@ func getViewData(view string) (string, []models.PostStatus, string) {
sort = "comments_count"
case "planned":
sort = "response_date"
- statuses = []models.PostStatus{models.PostPlanned}
+ statuses = []enum.PostStatus{enum.PostPlanned}
case "started":
sort = "response_date"
- statuses = []models.PostStatus{models.PostStarted}
+ statuses = []enum.PostStatus{enum.PostStarted}
case "completed":
sort = "response_date"
- statuses = []models.PostStatus{models.PostCompleted}
+ statuses = []enum.PostStatus{enum.PostCompleted}
case "declined":
sort = "response_date"
- statuses = []models.PostStatus{models.PostDeclined}
+ statuses = []enum.PostStatus{enum.PostDeclined}
case "all":
sort = "id"
- statuses = []models.PostStatus{
- models.PostOpen,
- models.PostStarted,
- models.PostPlanned,
- models.PostCompleted,
- models.PostDeclined,
+ statuses = []enum.PostStatus{
+ enum.PostOpen,
+ enum.PostStarted,
+ enum.PostPlanned,
+ enum.PostCompleted,
+ enum.PostDeclined,
}
case "trending":
fallthrough
@@ -67,14 +68,14 @@ func getViewData(view string) (string, []models.PostStatus, string) {
return condition, statuses, sort
}
-func buildAvatarURL(ctx storage.Context, avatarType models.AvatarType, id int, name, avatarBlobKey string) string {
+func buildAvatarURL(ctx context.Context, avatarType enum.AvatarType, id int, name, avatarBlobKey string) string {
if name == "" {
name = "-"
}
- if avatarType == models.AvatarTypeCustom {
- return ctx.TenantAssetsURL("/images/%s", avatarBlobKey)
+ if avatarType == enum.AvatarTypeCustom {
+ return web.TenantAssetsURL(ctx, "/images/%s", avatarBlobKey)
} else {
- return ctx.TenantAssetsURL("/avatars/%s/%d/%s", avatarType.String(), id, url.PathEscape(name))
+ return web.TenantAssetsURL(ctx, "/avatars/%s/%d/%s", avatarType.String(), id, url.PathEscape(name))
}
}
diff --git a/app/storage/postgres/common_test.go b/app/services/sqlstore/postgres/common_test.go
similarity index 58%
rename from app/storage/postgres/common_test.go
rename to app/services/sqlstore/postgres/common_test.go
index 3b29fb049..155a2e9a0 100644
--- a/app/storage/postgres/common_test.go
+++ b/app/services/sqlstore/postgres/common_test.go
@@ -1,10 +1,14 @@
package postgres_test
import (
+ "context"
"testing"
+ "github.com/getfider/fider/app"
+
+ "github.com/getfider/fider/app/models"
. "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/storage/postgres"
+ "github.com/getfider/fider/app/services/sqlstore/postgres"
)
func TestToTSQuery(t *testing.T) {
@@ -31,3 +35,13 @@ func TestToTSQuery(t *testing.T) {
Expect(output).Equals(testcase.expected)
}
}
+
+func withTenant(ctx context.Context, tenant *models.Tenant) context.Context {
+ return context.WithValue(ctx, app.TenantCtxKey, tenant)
+}
+
+func withUser(ctx context.Context, user *models.User) context.Context {
+ ctx = context.WithValue(ctx, app.TenantCtxKey, user.Tenant)
+ ctx = context.WithValue(ctx, app.UserCtxKey, user)
+ return ctx
+}
diff --git a/app/services/sqlstore/postgres/event.go b/app/services/sqlstore/postgres/event.go
new file mode 100644
index 000000000..4ea0e4f81
--- /dev/null
+++ b/app/services/sqlstore/postgres/event.go
@@ -0,0 +1,31 @@
+package postgres
+
+import (
+ "context"
+ "database/sql"
+ "time"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+func storeEvent(ctx context.Context, c *cmd.StoreEvent) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ dbClientIP := sql.NullString{
+ String: c.ClientIP,
+ Valid: len(c.ClientIP) > 0,
+ }
+
+ _, err := trx.Execute(`
+ INSERT INTO events (tenant_id, client_ip, name, created_at)
+ VALUES ($1, $2, $3, $4)
+ RETURNING id
+ `, tenant.ID, dbClientIP, c.EventName, time.Now())
+ if err != nil {
+ return errors.Wrap(err, "failed to insert event")
+ }
+ return nil
+ })
+}
diff --git a/app/services/sqlstore/postgres/event_test.go b/app/services/sqlstore/postgres/event_test.go
new file mode 100644
index 000000000..31d3551d4
--- /dev/null
+++ b/app/services/sqlstore/postgres/event_test.go
@@ -0,0 +1,42 @@
+package postgres_test
+
+import (
+ "testing"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/pkg/bus"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+)
+
+func TestEventStorage_Add(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ clientIP := "127.0.0.1"
+ eventName := "posts.create"
+ err := bus.Dispatch(demoTenantCtx, &cmd.StoreEvent{
+ ClientIP: clientIP,
+ EventName: eventName,
+ })
+ Expect(err).IsNil()
+
+ count, err := trx.Count("SELECT * FROM events WHERE name = 'posts.create' AND client_ip = '127.0.0.1' AND tenant_id = 1")
+ Expect(err).IsNil()
+ Expect(count).Equals(1)
+}
+
+func TestEventStorage_AddWithNullClientIP(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ eventName := "posts.delete"
+ err := bus.Dispatch(avengersTenantCtx, &cmd.StoreEvent{
+ EventName: eventName,
+ })
+ Expect(err).IsNil()
+
+ count, err := trx.Count("SELECT * FROM events WHERE name = 'posts.delete' AND client_ip IS NULL AND tenant_id = 2")
+ Expect(err).IsNil()
+ Expect(count).Equals(1)
+}
diff --git a/app/services/sqlstore/postgres/notification.go b/app/services/sqlstore/postgres/notification.go
new file mode 100644
index 000000000..31bc64d9c
--- /dev/null
+++ b/app/services/sqlstore/postgres/notification.go
@@ -0,0 +1,236 @@
+package postgres
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/lib/pq"
+)
+
+func markAllNotificationsAsRead(ctx context.Context, c *cmd.MarkAllNotificationsAsRead) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if user == nil {
+ return nil
+ }
+ _, err := trx.Execute(`
+ UPDATE notifications SET read = true, updated_at = $1
+ WHERE tenant_id = $2 AND user_id = $3 AND read = false
+ `, time.Now(), tenant.ID, user.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to mark all notifications as read")
+ }
+ return nil
+ })
+}
+
+func countUnreadNotifications(ctx context.Context, q *query.CountUnreadNotifications) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ q.Result = 0
+
+ if user != nil {
+ err := trx.Scalar(&q.Result, "SELECT COUNT(*) FROM notifications WHERE tenant_id = $1 AND user_id = $2 AND read = false", tenant.ID, user.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed count total unread notifications")
+ }
+ }
+ return nil
+ })
+}
+
+func markNotificationAsRead(ctx context.Context, c *cmd.MarkNotificationAsRead) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if user == nil {
+ return nil
+ }
+
+ _, err := trx.Execute(`
+ UPDATE notifications SET read = true, updated_at = $1
+ WHERE id = $2 AND tenant_id = $3 AND user_id = $4 AND read = false
+ `, time.Now(), c.ID, tenant.ID, user.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to mark notification as read")
+ }
+ return nil
+ })
+}
+
+func getNotificationByID(ctx context.Context, q *query.GetNotificationByID) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ q.Result = nil
+ notification := &models.Notification{}
+
+ err := trx.Get(notification, `
+ SELECT id, title, link, read, created_at
+ FROM notifications
+ WHERE id = $1 AND tenant_id = $2 AND user_id = $3
+ `, q.ID, tenant.ID, user.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to get notifications with id '%d'", q.ID)
+ }
+
+ q.Result = notification
+ return nil
+ })
+}
+
+func getActiveNotifications(ctx context.Context, q *query.GetActiveNotifications) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ q.Result = []*models.Notification{}
+ err := trx.Select(&q.Result, `
+ SELECT id, title, link, read, created_at
+ FROM notifications
+ WHERE tenant_id = $1 AND user_id = $2
+ AND (read = false OR updated_at > CURRENT_DATE - INTERVAL '30 days')
+ `, tenant.ID, user.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to get active notifications")
+ }
+ return nil
+ })
+}
+
+func addNewNotification(ctx context.Context, c *cmd.AddNewNotification) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ c.Result = nil
+ if user.ID == c.User.ID {
+ return nil
+ }
+
+ now := time.Now()
+ notification := &models.Notification{
+ Title: c.Title,
+ Link: c.Link,
+ CreatedAt: now,
+ Read: false,
+ }
+ err := trx.Get(&notification.ID, `
+ INSERT INTO notifications (tenant_id, user_id, title, link, read, post_id, author_id, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $8)
+ RETURNING id
+ `, tenant.ID, c.User.ID, c.Title, c.Link, false, c.PostID, user.ID, now)
+ if err != nil {
+ return errors.Wrap(err, "failed to insert notification")
+ }
+
+ c.Result = notification
+ return nil
+ })
+}
+
+func addSubscriber(ctx context.Context, c *cmd.AddSubscriber) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return internalAddSubscriber(trx, c.Post, tenant, c.User, true)
+ })
+}
+
+func removeSubscriber(ctx context.Context, c *cmd.RemoveSubscriber) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ _, err := trx.Execute(`
+ INSERT INTO post_subscribers (tenant_id, user_id, post_id, created_at, updated_at, status)
+ VALUES ($1, $2, $3, $4, $4, $5) ON CONFLICT (user_id, post_id)
+ DO UPDATE SET status = 0, updated_at = $4`,
+ tenant.ID, c.User.ID, c.Post.ID, time.Now(), enum.SubscriberInactive,
+ )
+ if err != nil {
+ return errors.Wrap(err, "failed remove post subscriber")
+ }
+ return nil
+ })
+}
+
+func getActiveSubscribers(ctx context.Context, q *query.GetActiveSubscribers) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ q.Result = make([]*models.User, 0)
+
+ var (
+ users []*dbUser
+ err error
+ )
+
+ if len(q.Event.RequiresSubscriptionUserRoles) == 0 {
+ err = trx.Select(&users, `
+ SELECT DISTINCT u.id, u.name, u.email, u.tenant_id, u.role, u.status
+ FROM users u
+ LEFT JOIN user_settings set
+ ON set.user_id = u.id
+ AND set.tenant_id = u.tenant_id
+ AND set.key = $1
+ WHERE u.tenant_id = $2
+ AND u.status = $5
+ AND (
+ (set.value IS NULL AND u.role = ANY($3))
+ OR CAST(set.value AS integer) & $4 > 0
+ )
+ ORDER by u.id`,
+ q.Event.UserSettingsKeyName,
+ tenant.ID,
+ pq.Array(q.Event.DefaultEnabledUserRoles),
+ q.Channel,
+ enum.UserActive,
+ )
+ } else {
+ err = trx.Select(&users, `
+ SELECT DISTINCT u.id, u.name, u.email, u.tenant_id, u.role, u.status
+ FROM users u
+ LEFT JOIN post_subscribers sub
+ ON sub.user_id = u.id
+ AND sub.post_id = (SELECT id FROM posts p WHERE p.tenant_id = $4 and p.number = $1 LIMIT 1)
+ AND sub.tenant_id = u.tenant_id
+ LEFT JOIN user_settings set
+ ON set.user_id = u.id
+ AND set.key = $3
+ AND set.tenant_id = u.tenant_id
+ WHERE u.tenant_id = $4
+ AND u.status = $8
+ AND ( sub.status = $2 OR (sub.status IS NULL AND NOT u.role = ANY($7)) )
+ AND (
+ (set.value IS NULL AND u.role = ANY($5))
+ OR CAST(set.value AS integer) & $6 > 0
+ )
+ ORDER by u.id`,
+ q.Number,
+ enum.SubscriberActive,
+ q.Event.UserSettingsKeyName,
+ tenant.ID,
+ pq.Array(q.Event.DefaultEnabledUserRoles),
+ q.Channel,
+ pq.Array(q.Event.RequiresSubscriptionUserRoles),
+ enum.UserActive,
+ )
+ }
+
+ if err != nil {
+ return errors.Wrap(err, "failed to get post number '%d' subscribers", q.Number)
+ }
+
+ q.Result = make([]*models.User, len(users))
+ for i, user := range users {
+ q.Result[i] = user.toModel(ctx)
+ }
+ return nil
+ })
+}
+
+func internalAddSubscriber(trx *dbx.Trx, post *models.Post, tenant *models.Tenant, user *models.User, force bool) error {
+ conflict := " DO NOTHING"
+ if force {
+ conflict = "(user_id, post_id) DO UPDATE SET status = $5, updated_at = $4"
+ }
+
+ _, err := trx.Execute(fmt.Sprintf(`
+ INSERT INTO post_subscribers (tenant_id, user_id, post_id, created_at, updated_at, status)
+ VALUES ($1, $2, $3, $4, $4, $5) ON CONFLICT %s`, conflict),
+ tenant.ID, user.ID, post.ID, time.Now(), enum.SubscriberActive,
+ )
+ if err != nil {
+ return errors.Wrap(err, "failed insert post subscriber")
+ }
+ return nil
+}
diff --git a/app/services/sqlstore/postgres/notifications_test.go b/app/services/sqlstore/postgres/notifications_test.go
new file mode 100644
index 000000000..4c1285e62
--- /dev/null
+++ b/app/services/sqlstore/postgres/notifications_test.go
@@ -0,0 +1,154 @@
+package postgres_test
+
+import (
+ "testing"
+ "time"
+
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app/models/cmd"
+
+ "github.com/getfider/fider/app"
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+func TestNotificationStorage_TotalCount(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ q := &query.CountUnreadNotifications{}
+
+ err := bus.Dispatch(ctx, q)
+ Expect(err).IsNil()
+ Expect(q.Result).Equals(0)
+
+ err = bus.Dispatch(demoTenantCtx, q)
+ Expect(err).IsNil()
+ Expect(q.Result).Equals(0)
+}
+
+func TestNotificationStorage_Insert_Read_Count(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "Title", Description: "Description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ addNotification1 := &cmd.AddNewNotification{User: aryaStark, Title: "Hello World", Link: "http://www.google.com.br", PostID: newPost.Result.ID}
+ addNotification2 := &cmd.AddNewNotification{User: aryaStark, Title: "Hello World", Link: "", PostID: newPost.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, addNotification1, addNotification2)
+ Expect(err).IsNil()
+
+ q := &query.CountUnreadNotifications{}
+ err = bus.Dispatch(aryaStarkCtx, q)
+ Expect(err).IsNil()
+ Expect(q.Result).Equals(2)
+
+ Expect(bus.Dispatch(aryaStarkCtx, &cmd.MarkNotificationAsRead{ID: addNotification1.Result.ID})).IsNil()
+ err = bus.Dispatch(aryaStarkCtx, q)
+ Expect(err).IsNil()
+ Expect(q.Result).Equals(1)
+
+ Expect(bus.Dispatch(aryaStarkCtx, &cmd.MarkNotificationAsRead{ID: addNotification2.Result.ID})).IsNil()
+ err = bus.Dispatch(aryaStarkCtx, q)
+ Expect(err).IsNil()
+ Expect(q.Result).Equals(0)
+}
+
+func TestNotificationStorage_GetActiveNotifications(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "Title", Description: "Description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ addNotification1 := &cmd.AddNewNotification{User: aryaStark, Title: "Hello World", Link: "http://www.google.com.br", PostID: newPost.Result.ID}
+ addNotification2 := &cmd.AddNewNotification{User: aryaStark, Title: "Another thing happened", Link: "http://www.google.com.br", PostID: newPost.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, addNotification1, addNotification2)
+ Expect(err).IsNil()
+
+ activeNotifications := &query.GetActiveNotifications{}
+ err = bus.Dispatch(aryaStarkCtx, activeNotifications)
+ Expect(err).IsNil()
+ Expect(activeNotifications.Result).HasLen(2)
+
+ bus.Dispatch(aryaStarkCtx, &cmd.MarkNotificationAsRead{ID: activeNotifications.Result[0].ID})
+ bus.Dispatch(aryaStarkCtx, &cmd.MarkNotificationAsRead{ID: activeNotifications.Result[1].ID})
+
+ trx.Execute("UPDATE notifications SET updated_at = $1 WHERE id = $2", time.Now().AddDate(0, 0, -31), activeNotifications.Result[0].ID)
+
+ err = bus.Dispatch(aryaStarkCtx, activeNotifications)
+ Expect(err).IsNil()
+ Expect(activeNotifications.Result).HasLen(1)
+ Expect(activeNotifications.Result[0].Read).IsTrue()
+}
+
+func TestNotificationStorage_ReadAll(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "Title", Description: "Description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ addNotification1 := &cmd.AddNewNotification{User: aryaStark, Title: "Hello World", Link: "http://www.google.com.br", PostID: newPost.Result.ID}
+ addNotification2 := &cmd.AddNewNotification{User: aryaStark, Title: "Another thing happened", Link: "http://www.google.com.br", PostID: newPost.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, addNotification1, addNotification2)
+ Expect(err).IsNil()
+
+ activeNotifications := &query.GetActiveNotifications{}
+ err = bus.Dispatch(aryaStarkCtx, activeNotifications)
+ Expect(err).IsNil()
+ Expect(activeNotifications.Result).HasLen(2)
+
+ err = bus.Dispatch(aryaStarkCtx, &cmd.MarkAllNotificationsAsRead{})
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(aryaStarkCtx, activeNotifications)
+ Expect(err).IsNil()
+ Expect(activeNotifications.Result).HasLen(2)
+ Expect(activeNotifications.Result[0].Read).IsTrue()
+ Expect(activeNotifications.Result[1].Read).IsTrue()
+}
+
+func TestNotificationStorage_GetNotificationByID(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "Title", Description: "Description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ addNotification := &cmd.AddNewNotification{User: aryaStark, Title: "Hello World", Link: "http://www.google.com.br", PostID: newPost.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, addNotification)
+ Expect(err).IsNil()
+
+ q := &query.GetNotificationByID{ID: addNotification.Result.ID}
+ err = bus.Dispatch(aryaStarkCtx, q)
+ Expect(err).IsNil()
+ Expect(q.Result.Title).Equals("Hello World")
+ Expect(q.Result.Link).Equals("http://www.google.com.br")
+ Expect(q.Result.Read).IsFalse()
+}
+
+func TestNotificationStorage_GetNotificationByID_OtherUser(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "Title", Description: "Description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ addNotification := &cmd.AddNewNotification{User: jonSnow, Title: "Hello World", Link: "http://www.google.com.br", PostID: newPost.Result.ID}
+ err = bus.Dispatch(aryaStarkCtx, addNotification)
+ Expect(err).IsNil()
+
+ q := &query.GetNotificationByID{ID: addNotification.Result.ID}
+ err = bus.Dispatch(aryaStarkCtx, q)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(q.Result).IsNil()
+}
diff --git a/app/services/sqlstore/postgres/oauth.go b/app/services/sqlstore/postgres/oauth.go
new file mode 100644
index 000000000..c6ac4bcae
--- /dev/null
+++ b/app/services/sqlstore/postgres/oauth.go
@@ -0,0 +1,144 @@
+package postgres
+
+import (
+ "context"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/cmd"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+type dbOAuthConfig struct {
+ ID int `db:"id"`
+ Provider string `db:"provider"`
+ DisplayName string `db:"display_name"`
+ LogoBlobKey string `db:"logo_bkey"`
+ Status int `db:"status"`
+ ClientID string `db:"client_id"`
+ ClientSecret string `db:"client_secret"`
+ AuthorizeURL string `db:"authorize_url"`
+ TokenURL string `db:"token_url"`
+ Scope string `db:"scope"`
+ ProfileURL string `db:"profile_url"`
+ JSONUserIDPath string `db:"json_user_id_path"`
+ JSONUserNamePath string `db:"json_user_name_path"`
+ JSONUserEmailPath string `db:"json_user_email_path"`
+}
+
+func (m *dbOAuthConfig) toModel() *models.OAuthConfig {
+ return &models.OAuthConfig{
+ ID: m.ID,
+ Provider: m.Provider,
+ DisplayName: m.DisplayName,
+ Status: m.Status,
+ LogoBlobKey: m.LogoBlobKey,
+ ClientID: m.ClientID,
+ ClientSecret: m.ClientSecret,
+ AuthorizeURL: m.AuthorizeURL,
+ TokenURL: m.TokenURL,
+ ProfileURL: m.ProfileURL,
+ Scope: m.Scope,
+ JSONUserIDPath: m.JSONUserIDPath,
+ JSONUserNamePath: m.JSONUserNamePath,
+ JSONUserEmailPath: m.JSONUserEmailPath,
+ }
+}
+
+func getCustomOAuthConfigByProvider(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if tenant == nil {
+ return app.ErrNotFound
+ }
+
+ config := &dbOAuthConfig{}
+ err := trx.Get(config, `
+ SELECT id, provider, display_name, status, logo_bkey,
+ client_id, client_secret, authorize_url,
+ profile_url, token_url, scope, json_user_id_path,
+ json_user_name_path, json_user_email_path
+ FROM oauth_providers
+ WHERE tenant_id = $1 AND provider = $2
+ `, tenant.ID, q.Provider)
+ if err != nil {
+ return err
+ }
+
+ q.Result = config.toModel()
+ return nil
+ })
+}
+
+func listCustomOAuthConfig(ctx context.Context, q *query.ListCustomOAuthConfig) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ configs := []*dbOAuthConfig{}
+ if tenant != nil {
+ err := trx.Select(&configs, `
+ SELECT id, provider, display_name, status, logo_bkey,
+ client_id, client_secret, authorize_url,
+ profile_url, token_url, scope, json_user_id_path,
+ json_user_name_path, json_user_email_path
+ FROM oauth_providers
+ WHERE tenant_id = $1
+ ORDER BY id`, tenant.ID)
+ if err != nil {
+ return err
+ }
+ }
+
+ q.Result = make([]*models.OAuthConfig, len(configs))
+ for i, config := range configs {
+ q.Result[i] = config.toModel()
+ }
+ return nil
+ })
+}
+
+func saveCustomOAuthConfig(ctx context.Context, c *cmd.SaveCustomOAuthConfig) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ var err error
+
+ if c.Config.Logo.Remove {
+ c.Config.Logo.BlobKey = ""
+ }
+
+ if c.Config.ID == 0 {
+ query := `INSERT INTO oauth_providers (
+ tenant_id, provider, display_name, status,
+ client_id, client_secret, authorize_url,
+ profile_url, token_url, scope, json_user_id_path,
+ json_user_name_path, json_user_email_path, logo_bkey
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
+ RETURNING id`
+
+ err = trx.Get(&c.Config.ID, query, tenant.ID, c.Config.Provider,
+ c.Config.DisplayName, c.Config.Status, c.Config.ClientID, c.Config.ClientSecret,
+ c.Config.AuthorizeURL, c.Config.ProfileURL, c.Config.TokenURL,
+ c.Config.Scope, c.Config.JSONUserIDPath, c.Config.JSONUserNamePath,
+ c.Config.JSONUserEmailPath, c.Config.Logo.BlobKey)
+ } else {
+ query := `
+ UPDATE oauth_providers
+ SET display_name = $3, status = $4, client_id = $5, client_secret = $6,
+ authorize_url = $7, profile_url = $8, token_url = $9, scope = $10,
+ json_user_id_path = $11, json_user_name_path = $12, json_user_email_path = $13,
+ logo_bkey = $14
+ WHERE tenant_id = $1 AND id = $2`
+
+ _, err = trx.Execute(query, tenant.ID, c.Config.ID,
+ c.Config.DisplayName, c.Config.Status, c.Config.ClientID, c.Config.ClientSecret,
+ c.Config.AuthorizeURL, c.Config.ProfileURL, c.Config.TokenURL,
+ c.Config.Scope, c.Config.JSONUserIDPath, c.Config.JSONUserNamePath,
+ c.Config.JSONUserEmailPath, c.Config.Logo.BlobKey)
+ }
+
+ if err != nil {
+ return errors.Wrap(err, "failed to save OAuth Provider")
+ }
+
+ return nil
+ })
+}
diff --git a/app/services/sqlstore/postgres/post.go b/app/services/sqlstore/postgres/post.go
new file mode 100644
index 000000000..71804d82f
--- /dev/null
+++ b/app/services/sqlstore/postgres/post.go
@@ -0,0 +1,450 @@
+package postgres
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "strconv"
+ "time"
+
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/gosimple/slug"
+ "github.com/lib/pq"
+
+ "github.com/getfider/fider/app/pkg/bus"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+type dbPost struct {
+ ID int `db:"id"`
+ Number int `db:"number"`
+ Title string `db:"title"`
+ Slug string `db:"slug"`
+ Description string `db:"description"`
+ CreatedAt time.Time `db:"created_at"`
+ User *dbUser `db:"user"`
+ HasVoted bool `db:"has_voted"`
+ VotesCount int `db:"votes_count"`
+ CommentsCount int `db:"comments_count"`
+ RecentVotes int `db:"recent_votes_count"`
+ RecentComments int `db:"recent_comments_count"`
+ Status int `db:"status"`
+ Response sql.NullString `db:"response"`
+ RespondedAt dbx.NullTime `db:"response_date"`
+ ResponseUser *dbUser `db:"response_user"`
+ OriginalNumber sql.NullInt64 `db:"original_number"`
+ OriginalTitle sql.NullString `db:"original_title"`
+ OriginalSlug sql.NullString `db:"original_slug"`
+ OriginalStatus sql.NullInt64 `db:"original_status"`
+ Tags []string `db:"tags"`
+}
+
+func (i *dbPost) toModel(ctx context.Context) *models.Post {
+ post := &models.Post{
+ ID: i.ID,
+ Number: i.Number,
+ Title: i.Title,
+ Slug: i.Slug,
+ Description: i.Description,
+ CreatedAt: i.CreatedAt,
+ HasVoted: i.HasVoted,
+ VotesCount: i.VotesCount,
+ CommentsCount: i.CommentsCount,
+ Status: enum.PostStatus(i.Status),
+ User: i.User.toModel(ctx),
+ Tags: i.Tags,
+ }
+
+ if i.Response.Valid {
+ post.Response = &models.PostResponse{
+ Text: i.Response.String,
+ RespondedAt: i.RespondedAt.Time,
+ User: i.ResponseUser.toModel(ctx),
+ }
+ if post.Status == enum.PostDuplicate && i.OriginalNumber.Valid {
+ post.Response.Original = &models.OriginalPost{
+ Number: int(i.OriginalNumber.Int64),
+ Slug: i.OriginalSlug.String,
+ Title: i.OriginalTitle.String,
+ Status: enum.PostStatus(i.OriginalStatus.Int64),
+ }
+ }
+ }
+ return post
+}
+
+var (
+ sqlSelectPostsWhere = ` WITH
+ agg_tags AS (
+ SELECT
+ post_id,
+ ARRAY_REMOVE(ARRAY_AGG(tags.slug), NULL) as tags
+ FROM post_tags
+ INNER JOIN tags
+ ON tags.ID = post_tags.TAG_ID
+ AND tags.tenant_id = post_tags.tenant_id
+ WHERE post_tags.tenant_id = $1
+ %s
+ GROUP BY post_id
+ ),
+ agg_comments AS (
+ SELECT
+ post_id,
+ COUNT(CASE WHEN comments.created_at > CURRENT_DATE - INTERVAL '30 days' THEN 1 END) as recent,
+ COUNT(*) as all
+ FROM comments
+ INNER JOIN posts
+ ON posts.id = comments.post_id
+ AND posts.tenant_id = comments.tenant_id
+ WHERE posts.tenant_id = $1
+ AND comments.deleted_at IS NULL
+ GROUP BY post_id
+ ),
+ agg_votes AS (
+ SELECT
+ post_id,
+ COUNT(CASE WHEN post_votes.created_at > CURRENT_DATE - INTERVAL '30 days' THEN 1 END) as recent,
+ COUNT(*) as all
+ FROM post_votes
+ INNER JOIN posts
+ ON posts.id = post_votes.post_id
+ AND posts.tenant_id = post_votes.tenant_id
+ WHERE posts.tenant_id = $1
+ GROUP BY post_id
+ )
+ SELECT p.id,
+ p.number,
+ p.title,
+ p.slug,
+ p.description,
+ p.created_at,
+ COALESCE(agg_s.all, 0) as votes_count,
+ COALESCE(agg_c.all, 0) as comments_count,
+ COALESCE(agg_s.recent, 0) AS recent_votes_count,
+ COALESCE(agg_c.recent, 0) AS recent_comments_count,
+ p.status,
+ u.id AS user_id,
+ u.name AS user_name,
+ u.email AS user_email,
+ u.role AS user_role,
+ u.status AS user_status,
+ u.avatar_type AS user_avatar_type,
+ u.avatar_bkey AS user_avatar_bkey,
+ p.response,
+ p.response_date,
+ r.id AS response_user_id,
+ r.name AS response_user_name,
+ r.email AS response_user_email,
+ r.role AS response_user_role,
+ r.status AS response_user_status,
+ r.avatar_type AS response_user_avatar_type,
+ r.avatar_bkey AS response_user_avatar_bkey,
+ d.number AS original_number,
+ d.title AS original_title,
+ d.slug AS original_slug,
+ d.status AS original_status,
+ COALESCE(agg_t.tags, ARRAY[]::text[]) AS tags,
+ COALESCE(%s, false) AS has_voted
+ FROM posts p
+ INNER JOIN users u
+ ON u.id = p.user_id
+ AND u.tenant_id = $1
+ LEFT JOIN users r
+ ON r.id = p.response_user_id
+ AND r.tenant_id = $1
+ LEFT JOIN posts d
+ ON d.id = p.original_id
+ AND d.tenant_id = $1
+ LEFT JOIN agg_comments agg_c
+ ON agg_c.post_id = p.id
+ LEFT JOIN agg_votes agg_s
+ ON agg_s.post_id = p.id
+ LEFT JOIN agg_tags agg_t
+ ON agg_t.post_id = p.id
+ WHERE p.status != ` + strconv.Itoa(int(enum.PostDeleted)) + ` AND %s`
+)
+
+func postIsReferenced(ctx context.Context, q *query.PostIsReferenced) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ q.Result = false
+
+ exists, err := trx.Exists(`
+ SELECT 1 FROM posts p
+ INNER JOIN posts o
+ ON o.tenant_id = p.tenant_id
+ AND o.id = p.original_id
+ WHERE p.tenant_id = $1
+ AND o.id = $2`, tenant.ID, q.PostID)
+ if err != nil {
+ return errors.Wrap(err, "failed to check if post is referenced")
+ }
+
+ q.Result = exists
+ return nil
+ })
+}
+
+func setPostResponse(ctx context.Context, c *cmd.SetPostResponse) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if c.Status == enum.PostDuplicate {
+ return errors.New("Use MarkAsDuplicate to change an post status to Duplicate")
+ }
+
+ respondedAt := time.Now()
+ if c.Post.Status == c.Status && c.Post.Response != nil {
+ respondedAt = c.Post.Response.RespondedAt
+ }
+
+ _, err := trx.Execute(`
+ UPDATE posts
+ SET response = $3, original_id = NULL, response_date = $4, response_user_id = $5, status = $6
+ WHERE id = $1 and tenant_id = $2
+ `, c.Post.ID, tenant.ID, c.Text, respondedAt, user.ID, c.Status)
+ if err != nil {
+ return errors.Wrap(err, "failed to update post's response")
+ }
+
+ c.Post.Status = c.Status
+ c.Post.Response = &models.PostResponse{
+ Text: c.Text,
+ RespondedAt: respondedAt,
+ User: user,
+ }
+ return nil
+ })
+}
+
+func markPostAsDuplicate(ctx context.Context, c *cmd.MarkPostAsDuplicate) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ respondedAt := time.Now()
+ if c.Post.Status == enum.PostDuplicate && c.Post.Response != nil {
+ respondedAt = c.Post.Response.RespondedAt
+ }
+
+ var users []*dbUser
+ err := trx.Select(&users, "SELECT user_id AS id FROM post_votes WHERE post_id = $1 AND tenant_id = $2", c.Post.ID, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to get votes of post with id '%d'", c.Post.ID)
+ }
+
+ for _, u := range users {
+ err := bus.Dispatch(ctx, &cmd.AddVote{Post: c.Original, User: u.toModel(ctx)})
+ if err != nil {
+ return err
+ }
+ }
+
+ _, err = trx.Execute(`
+ UPDATE posts
+ SET response = '', original_id = $3, response_date = $4, response_user_id = $5, status = $6
+ WHERE id = $1 and tenant_id = $2
+ `, c.Post.ID, tenant.ID, c.Original.ID, respondedAt, user.ID, enum.PostDuplicate)
+ if err != nil {
+ return errors.Wrap(err, "failed to update post's response")
+ }
+
+ c.Post.Status = enum.PostDuplicate
+ c.Post.Response = &models.PostResponse{
+ RespondedAt: respondedAt,
+ User: user,
+ Original: &models.OriginalPost{
+ Number: c.Original.Number,
+ Title: c.Original.Title,
+ Slug: c.Original.Slug,
+ Status: c.Original.Status,
+ },
+ }
+ return nil
+ })
+}
+
+func countPostPerStatus(ctx context.Context, q *query.CountPostPerStatus) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+
+ type dbStatusCount struct {
+ Status enum.PostStatus `db:"status"`
+ Count int `db:"count"`
+ }
+
+ q.Result = make(map[enum.PostStatus]int)
+ stats := []*dbStatusCount{}
+ err := trx.Select(&stats, "SELECT status, COUNT(*) AS count FROM posts WHERE tenant_id = $1 GROUP BY status", tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to count posts per status")
+ }
+
+ for _, v := range stats {
+ q.Result[v.Status] = v.Count
+ }
+ return nil
+ })
+}
+
+func addNewPost(ctx context.Context, c *cmd.AddNewPost) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ var id int
+ err := trx.Get(&id,
+ `INSERT INTO posts (title, slug, number, description, tenant_id, user_id, created_at, status)
+ VALUES ($1, $2, (SELECT COALESCE(MAX(number), 0) + 1 FROM posts p WHERE p.tenant_id = $4), $3, $4, $5, $6, 0)
+ RETURNING id`, c.Title, slug.Make(c.Title), c.Description, tenant.ID, user.ID, time.Now())
+ if err != nil {
+ return errors.Wrap(err, "failed add new post")
+ }
+
+ q := &query.GetPostByID{PostID: id}
+ if err := getPostByID(ctx, q); err != nil {
+ return err
+ }
+ c.Result = q.Result
+
+ if err := internalAddSubscriber(trx, q.Result, tenant, user, false); err != nil {
+ return err
+ }
+
+ return nil
+ })
+}
+
+func updatePost(ctx context.Context, c *cmd.UpdatePost) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ _, err := trx.Execute(`UPDATE posts SET title = $1, slug = $2, description = $3
+ WHERE id = $4 AND tenant_id = $5`, c.Title, slug.Make(c.Title), c.Description, c.Post.ID, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed update post")
+ }
+
+ q := &query.GetPostByID{PostID: c.Post.ID}
+ if err := getPostByID(ctx, q); err != nil {
+ return err
+ }
+ c.Result = q.Result
+ return nil
+ })
+}
+
+func getPostByID(ctx context.Context, q *query.GetPostByID) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ post, err := querySinglePost(ctx, trx, buildPostQuery(user, "p.tenant_id = $1 AND p.id = $2"), tenant.ID, q.PostID)
+ if err != nil {
+ return errors.Wrap(err, "failed to get post with id '%d'", q.PostID)
+ }
+ q.Result = post
+ return nil
+ })
+}
+
+func getPostBySlug(ctx context.Context, q *query.GetPostBySlug) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ post, err := querySinglePost(ctx, trx, buildPostQuery(user, "p.tenant_id = $1 AND p.slug = $2"), tenant.ID, q.Slug)
+ if err != nil {
+ return errors.Wrap(err, "failed to get post with slug '%s'", q.Slug)
+ }
+ q.Result = post
+ return nil
+ })
+}
+
+func getPostByNumber(ctx context.Context, q *query.GetPostByNumber) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ post, err := querySinglePost(ctx, trx, buildPostQuery(user, "p.tenant_id = $1 AND p.number = $2"), tenant.ID, q.Number)
+ if err != nil {
+ return errors.Wrap(err, "failed to get post with number '%d'", q.Number)
+ }
+ q.Result = post
+ return nil
+ })
+}
+
+func searchPosts(ctx context.Context, q *query.SearchPosts) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ innerQuery := buildPostQuery(user, "p.tenant_id = $1 AND p.status = ANY($2)")
+
+ if q.Tags == nil {
+ q.Tags = []string{}
+ }
+
+ if q.Limit != "all" {
+ if _, err := strconv.Atoi(q.Limit); err != nil {
+ q.Limit = "30"
+ }
+ }
+
+ var (
+ posts []*dbPost
+ err error
+ )
+ if q.Query != "" {
+ scoreField := "ts_rank(setweight(to_tsvector(title), 'A') || setweight(to_tsvector(description), 'B'), to_tsquery('english', $3)) + similarity(title, $4) + similarity(description, $4)"
+ sql := fmt.Sprintf(`
+ SELECT * FROM (%s) AS q
+ WHERE %s > 0.1
+ ORDER BY %s DESC
+ LIMIT %s
+ `, innerQuery, scoreField, scoreField, q.Limit)
+ err = trx.Select(&posts, sql, tenant.ID, pq.Array([]enum.PostStatus{
+ enum.PostOpen,
+ enum.PostStarted,
+ enum.PostPlanned,
+ enum.PostCompleted,
+ enum.PostDeclined,
+ }), ToTSQuery(q.Query), q.Query)
+ } else {
+ condition, statuses, sort := getViewData(q.View)
+ sql := fmt.Sprintf(`
+ SELECT * FROM (%s) AS q
+ WHERE tags @> $3 %s
+ ORDER BY %s DESC
+ LIMIT %s
+ `, innerQuery, condition, sort, q.Limit)
+ err = trx.Select(&posts, sql, tenant.ID, pq.Array(statuses), pq.Array(q.Tags))
+ }
+
+ if err != nil {
+ return errors.Wrap(err, "failed to search posts")
+ }
+
+ q.Result = make([]*models.Post, len(posts))
+ for i, post := range posts {
+ q.Result[i] = post.toModel(ctx)
+ }
+ return nil
+ })
+}
+
+func getAllPosts(ctx context.Context, q *query.GetAllPosts) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ searchQuery := &query.SearchPosts{View: "all", Limit: "all"}
+ if err := searchPosts(ctx, searchQuery); err != nil {
+ return errors.Wrap(err, "failed to get all posts")
+ }
+ q.Result = searchQuery.Result
+ return nil
+ })
+}
+
+func querySinglePost(ctx context.Context, trx *dbx.Trx, query string, args ...interface{}) (*models.Post, error) {
+ post := dbPost{}
+
+ if err := trx.Get(&post, query, args...); err != nil {
+ return nil, err
+ }
+
+ return post.toModel(ctx), nil
+}
+
+func buildPostQuery(user *models.User, filter string) string {
+ tagCondition := `AND tags.is_public = true`
+ if user != nil && user.IsCollaborator() {
+ tagCondition = ``
+ }
+ hasVotedSubQuery := "null"
+ if user != nil {
+ hasVotedSubQuery = fmt.Sprintf("(SELECT true FROM post_votes WHERE post_id = p.id AND user_id = %d)", user.ID)
+ }
+ return fmt.Sprintf(sqlSelectPostsWhere, tagCondition, hasVotedSubQuery, filter)
+}
diff --git a/app/services/sqlstore/postgres/post_test.go b/app/services/sqlstore/postgres/post_test.go
new file mode 100644
index 000000000..075d8b27d
--- /dev/null
+++ b/app/services/sqlstore/postgres/post_test.go
@@ -0,0 +1,647 @@
+package postgres_test
+
+import (
+ "io/ioutil"
+ "testing"
+ "time"
+
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+func TestPostStorage_GetAll(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ now := time.Now()
+
+ trx.Execute("INSERT INTO posts (title, slug, number, description, created_at, tenant_id, user_id, status) VALUES ('add twitter integration', 'add-twitter-integration', 1, 'Would be great to see it integrated with twitter', $1, 1, 1, 1)", now)
+ trx.Execute("INSERT INTO posts (title, slug, number, description, created_at, tenant_id, user_id, status) VALUES ('this is my post', 'this-is-my-post', 2, 'no description', $1, 1, 2, 2)", now)
+
+ allPosts := &query.GetAllPosts{}
+ err := bus.Dispatch(demoTenantCtx, allPosts)
+ Expect(err).IsNil()
+ Expect(allPosts.Result).HasLen(2)
+
+ Expect(allPosts.Result[0].Title).Equals("this is my post")
+ Expect(allPosts.Result[0].Slug).Equals("this-is-my-post")
+ Expect(allPosts.Result[0].Number).Equals(2)
+ Expect(allPosts.Result[0].Description).Equals("no description")
+ Expect(allPosts.Result[0].User.Name).Equals("Arya Stark")
+ Expect(allPosts.Result[0].VotesCount).Equals(0)
+ Expect(allPosts.Result[0].Status).Equals(enum.PostCompleted)
+
+ Expect(allPosts.Result[1].Title).Equals("add twitter integration")
+ Expect(allPosts.Result[1].Slug).Equals("add-twitter-integration")
+ Expect(allPosts.Result[1].Number).Equals(1)
+ Expect(allPosts.Result[1].Description).Equals("Would be great to see it integrated with twitter")
+ Expect(allPosts.Result[1].User.Name).Equals("Jon Snow")
+ Expect(allPosts.Result[1].VotesCount).Equals(0)
+ Expect(allPosts.Result[1].Status).Equals(enum.PostStarted)
+
+ search10 := &query.SearchPosts{Query: "twitter", Limit: "10"}
+ search0 := &query.SearchPosts{Query: "twitter", Limit: "0"}
+ err = bus.Dispatch(demoTenantCtx, search10, search0)
+ Expect(err).IsNil()
+
+ Expect(search10.Result).HasLen(1)
+ Expect(search10.Result[0].Slug).Equals("add-twitter-integration")
+ Expect(search0.Result).HasLen(0)
+}
+
+func TestPostStorage_AddAndGet(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ postByID := &query.GetPostByID{PostID: newPost.Result.ID}
+ postBySlug := &query.GetPostBySlug{Slug: "my-new-post"}
+ err = bus.Dispatch(jonSnowCtx, postByID, postBySlug)
+ Expect(err).IsNil()
+
+ Expect(postByID.Result.ID).Equals(newPost.Result.ID)
+ Expect(postByID.Result.Number).Equals(1)
+ Expect(postByID.Result.HasVoted).IsFalse()
+ Expect(postByID.Result.VotesCount).Equals(0)
+ Expect(postByID.Result.Status).Equals(enum.PostOpen)
+ Expect(postByID.Result.Title).Equals("My new post")
+ Expect(postByID.Result.Description).Equals("with this description")
+ Expect(postByID.Result.User.ID).Equals(1)
+ Expect(postByID.Result.User.Name).Equals("Jon Snow")
+ Expect(postByID.Result.User.Email).Equals("[email protected]")
+
+ Expect(postBySlug.Result.ID).Equals(newPost.Result.ID)
+ Expect(postBySlug.Result.Number).Equals(1)
+ Expect(postBySlug.Result.HasVoted).IsFalse()
+ Expect(postBySlug.Result.VotesCount).Equals(0)
+ Expect(postBySlug.Result.Status).Equals(enum.PostOpen)
+ Expect(postBySlug.Result.Title).Equals("My new post")
+ Expect(postBySlug.Result.Description).Equals("with this description")
+ Expect(postBySlug.Result.User.ID).Equals(1)
+ Expect(postBySlug.Result.User.Name).Equals("Jon Snow")
+ Expect(postBySlug.Result.User.Email).Equals("[email protected]")
+}
+
+func TestPostStorage_GetInvalid(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ postByID := &query.GetPostByID{PostID: 1}
+ err := bus.Dispatch(jonSnowCtx, postByID)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(postByID.Result).IsNil()
+}
+
+func TestPostStorage_AddAndReturnComments(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ bus.Dispatch(jonSnowCtx, &cmd.AddNewComment{Post: newPost.Result, Content: "Comment #1"})
+ bus.Dispatch(aryaStarkCtx, &cmd.AddNewComment{Post: newPost.Result, Content: "Comment #2"})
+
+ commentsByPost := &query.GetCommentsByPost{Post: newPost.Result}
+ err = bus.Dispatch(aryaStarkCtx, commentsByPost)
+ Expect(err).IsNil()
+ Expect(commentsByPost.Result).HasLen(2)
+
+ Expect(commentsByPost.Result[0].Content).Equals("Comment #1")
+ Expect(commentsByPost.Result[0].User.Name).Equals("Jon Snow")
+ Expect(commentsByPost.Result[1].Content).Equals("Comment #2")
+ Expect(commentsByPost.Result[1].User.Name).Equals("Arya Stark")
+}
+
+func TestPostStorage_AddGetUpdateComment(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ addNewComment := &cmd.AddNewComment{Post: newPost.Result, Content: "Comment #1"}
+ err = bus.Dispatch(jonSnowCtx, addNewComment)
+ Expect(err).IsNil()
+
+ commentByID := &query.GetCommentByID{CommentID: addNewComment.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, commentByID)
+ Expect(err).IsNil()
+
+ Expect(commentByID.Result.ID).Equals(addNewComment.Result.ID)
+ Expect(commentByID.Result.Content).Equals("Comment #1")
+ Expect(commentByID.Result.User.ID).Equals(jonSnow.ID)
+ Expect(commentByID.Result.EditedAt).IsNil()
+ Expect(commentByID.Result.EditedBy).IsNil()
+
+ updateComment := &cmd.UpdateComment{CommentID: addNewComment.Result.ID, Content: "Comment #1 with edit"}
+ err = bus.Dispatch(aryaStarkCtx, updateComment)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(aryaStarkCtx, commentByID)
+ Expect(err).IsNil()
+
+ Expect(commentByID.Result.ID).Equals(addNewComment.Result.ID)
+ Expect(commentByID.Result.Content).Equals("Comment #1 with edit")
+ Expect(commentByID.Result.User.ID).Equals(jonSnow.ID)
+ Expect(commentByID.Result.EditedAt).IsNotNil()
+ Expect(commentByID.Result.EditedBy.ID).Equals(aryaStark.ID)
+}
+
+func TestPostStorage_AddDeleteComment(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ addNewComment := &cmd.AddNewComment{Post: newPost.Result, Content: "Comment #1"}
+ err = bus.Dispatch(jonSnowCtx, addNewComment)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.DeleteComment{CommentID: addNewComment.Result.ID})
+ Expect(err).IsNil()
+
+ commentByID := &query.GetCommentByID{CommentID: addNewComment.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, commentByID)
+ Expect(err).Equals(app.ErrNotFound)
+ Expect(commentByID.Result).IsNil()
+}
+
+func TestPostStorage_AddAndGet_DifferentTenants(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ jonSnowNewPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, jonSnowNewPost)
+ Expect(err).IsNil()
+
+ tonyStarkNewPost := &cmd.AddNewPost{Title: "My other post", Description: "with other description"}
+ err = bus.Dispatch(tonyStarkCtx, tonyStarkNewPost)
+ Expect(err).IsNil()
+
+ getDemoTenantPost1 := &query.GetPostByNumber{Number: 1}
+ err = bus.Dispatch(demoTenantCtx, getDemoTenantPost1)
+ Expect(err).IsNil()
+ Expect(getDemoTenantPost1.Result.ID).Equals(jonSnowNewPost.Result.ID)
+ Expect(getDemoTenantPost1.Result.Number).Equals(1)
+ Expect(getDemoTenantPost1.Result.Title).Equals("My new post")
+ Expect(getDemoTenantPost1.Result.Slug).Equals("my-new-post")
+
+ getAvengersPost1 := &query.GetPostByNumber{Number: 1}
+ err = bus.Dispatch(avengersTenantCtx, getAvengersPost1)
+ Expect(err).IsNil()
+ Expect(getAvengersPost1.Result.ID).Equals(tonyStarkNewPost.Result.ID)
+ Expect(getAvengersPost1.Result.Number).Equals(1)
+ Expect(getAvengersPost1.Result.Title).Equals("My other post")
+ Expect(getAvengersPost1.Result.Slug).Equals("my-other-post")
+}
+
+func TestPostStorage_Update(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.UpdatePost{Post: newPost.Result, Title: "The new title", Description: "With the new description"})
+ Expect(err).IsNil()
+
+ getPost := &query.GetPostByID{PostID: newPost.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, getPost)
+ Expect(err).IsNil()
+ Expect(getPost.Result.Title).Equals("The new title")
+ Expect(getPost.Result.Description).Equals("With the new description")
+ Expect(getPost.Result.Slug).Equals("the-new-title")
+}
+
+func TestPostStorage_AddVote(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.AddVote{Post: newPost.Result, User: aryaStark})
+ Expect(err).IsNil()
+
+ getPost := &query.GetPostByID{PostID: newPost.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, getPost)
+ Expect(err).IsNil()
+ Expect(getPost.Result.HasVoted).IsFalse()
+ Expect(getPost.Result.VotesCount).Equals(1)
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.AddVote{Post: newPost.Result, User: jonSnow})
+ Expect(err).IsNil()
+
+ getPost = &query.GetPostByID{PostID: newPost.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, getPost)
+ Expect(err).IsNil()
+ Expect(getPost.Result.HasVoted).IsTrue()
+ Expect(getPost.Result.VotesCount).Equals(2)
+}
+
+func TestPostStorage_AddVote_Twice(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(
+ jonSnowCtx,
+ &cmd.AddVote{Post: newPost.Result, User: jonSnow},
+ &cmd.AddVote{Post: newPost.Result, User: jonSnow},
+ )
+ Expect(err).IsNil()
+
+ getPost := &query.GetPostByID{PostID: newPost.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, getPost)
+ Expect(err).IsNil()
+ Expect(getPost.Result.HasVoted).IsTrue()
+ Expect(getPost.Result.VotesCount).Equals(1)
+}
+
+func TestPostStorage_RemoveVote(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(
+ jonSnowCtx,
+ &cmd.AddVote{Post: newPost.Result, User: jonSnow},
+ &cmd.RemoveVote{Post: newPost.Result, User: jonSnow},
+ )
+ Expect(err).IsNil()
+
+ getPost := &query.GetPostByID{PostID: newPost.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, getPost)
+ Expect(err).IsNil()
+ Expect(getPost.Result.HasVoted).IsFalse()
+ Expect(getPost.Result.VotesCount).Equals(0)
+}
+
+func TestPostStorage_RemoveVote_Twice(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(
+ jonSnowCtx,
+ &cmd.AddVote{Post: newPost.Result, User: jonSnow},
+ &cmd.RemoveVote{Post: newPost.Result, User: jonSnow},
+ &cmd.RemoveVote{Post: newPost.Result, User: jonSnow},
+ )
+ Expect(err).IsNil()
+
+ getPost := &query.GetPostByID{PostID: newPost.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, getPost)
+ Expect(err).IsNil()
+ Expect(getPost.Result.HasVoted).IsFalse()
+ Expect(getPost.Result.VotesCount).Equals(0)
+}
+
+func TestPostStorage_SetResponse(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "We liked this post", Status: enum.PostStarted})
+ Expect(err).IsNil()
+
+ getPost := &query.GetPostByID{PostID: newPost.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, getPost)
+ Expect(err).IsNil()
+ Expect(getPost.Result.Response.Text).Equals("We liked this post")
+ Expect(getPost.Result.Status).Equals(enum.PostStarted)
+ Expect(getPost.Result.Response.User.ID).Equals(1)
+}
+
+func TestPostStorage_SetResponse_KeepOpen(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "We liked this post", Status: enum.PostOpen})
+ Expect(err).IsNil()
+}
+
+func TestPostStorage_SetResponse_ChangeText(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ getPost := &query.GetPostByID{PostID: newPost.Result.ID}
+
+ bus.Dispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "We liked this post", Status: enum.PostStarted})
+ bus.Dispatch(jonSnowCtx, getPost)
+ firstResponseAt := getPost.Result.Response.RespondedAt
+
+ bus.Dispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "We liked this post and we'll work on it", Status: enum.PostStarted})
+ bus.Dispatch(jonSnowCtx, getPost)
+ Expect(getPost.Result.Response.RespondedAt).Equals(firstResponseAt)
+
+ bus.Dispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "We finished it", Status: enum.PostCompleted})
+ bus.Dispatch(jonSnowCtx, getPost)
+ Expect(getPost.Result.Response.RespondedAt).TemporarilySimilar(firstResponseAt, time.Second)
+}
+
+func TestPostStorage_SetResponse_AsDuplicate(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost1 := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost1)
+ Expect(err).IsNil()
+
+ newPost2 := &cmd.AddNewPost{Title: "My other post", Description: "with similar description"}
+ err = bus.Dispatch(aryaStarkCtx, newPost2)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(
+ jonSnowCtx,
+ &cmd.AddVote{Post: newPost1.Result, User: jonSnow},
+ &cmd.AddVote{Post: newPost2.Result, User: aryaStark},
+ &cmd.MarkPostAsDuplicate{Post: newPost2.Result, Original: newPost1.Result},
+ )
+ Expect(err).IsNil()
+
+ getPost1 := &query.GetPostByID{PostID: newPost1.Result.ID}
+ getPost2 := &query.GetPostByID{PostID: newPost2.Result.ID}
+ err = bus.Dispatch(aryaStarkCtx, getPost1, getPost2)
+ Expect(err).IsNil()
+
+ Expect(getPost1.Result.VotesCount).Equals(2)
+ Expect(getPost1.Result.Status).Equals(enum.PostOpen)
+ Expect(getPost1.Result.Response).IsNil()
+
+ Expect(getPost2.Result.Response.Text).Equals("")
+ Expect(getPost2.Result.VotesCount).Equals(1)
+ Expect(getPost2.Result.Status).Equals(enum.PostDuplicate)
+ Expect(getPost2.Result.Response.User.ID).Equals(1)
+ Expect(getPost2.Result.Response.Original.Number).Equals(newPost1.Result.Number)
+ Expect(getPost2.Result.Response.Original.Title).Equals(newPost1.Result.Title)
+ Expect(getPost2.Result.Response.Original.Slug).Equals(newPost1.Result.Slug)
+ Expect(getPost2.Result.Response.Original.Status).Equals(newPost1.Result.Status)
+}
+
+func TestPostStorage_SetResponse_AsDeleted(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ bus.Dispatch(jonSnowCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "Spam!", Status: enum.PostDeleted})
+
+ postByID := &query.GetPostByID{PostID: newPost.Result.ID}
+ err = bus.Dispatch(aryaStarkCtx, postByID)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(postByID.Result).IsNil()
+
+ postByNumber := &query.GetPostByNumber{Number: newPost.Result.Number}
+ err = bus.Dispatch(aryaStarkCtx, postByNumber)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(postByNumber.Result).IsNil()
+}
+
+func TestPostStorage_AddVote_ClosedPost(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx,
+ &cmd.SetPostResponse{Post: newPost.Result, Text: "We liked this post", Status: enum.PostCompleted},
+ &cmd.AddVote{Post: newPost.Result, User: jonSnow},
+ )
+ Expect(err).IsNil()
+
+ getPost := &query.GetPostByNumber{Number: newPost.Result.Number}
+ err = bus.Dispatch(aryaStarkCtx, getPost)
+ Expect(err).IsNil()
+ Expect(getPost.Result.VotesCount).Equals(0)
+}
+
+func TestPostStorage_RemoveVote_ClosedPost(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ bus.Dispatch(
+ jonSnowCtx,
+ &cmd.AddVote{Post: newPost.Result, User: jonSnow},
+ &cmd.SetPostResponse{Post: newPost.Result, Text: "We liked this post", Status: enum.PostCompleted},
+ &cmd.RemoveVote{Post: newPost.Result, User: jonSnow},
+ )
+
+ getPost := &query.GetPostByNumber{Number: newPost.Result.Number}
+ err = bus.Dispatch(jonSnowCtx, getPost)
+ Expect(err).IsNil()
+ Expect(getPost.Result.VotesCount).Equals(1)
+}
+
+func TestPostStorage_WithTags(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(aryaStarkCtx, newPost)
+ Expect(err).IsNil()
+
+ addBug := &cmd.AddNewTag{Name: "Bug", Color: "FF0000", IsPublic: true}
+ addFeatureRequest := &cmd.AddNewTag{Name: "Feature Request", Color: "00FF00", IsPublic: false}
+ bus.Dispatch(jonSnowCtx, addBug, addFeatureRequest)
+ bus.Dispatch(jonSnowCtx, &cmd.AssignTag{Tag: addBug.Result, Post: newPost.Result})
+ bus.Dispatch(jonSnowCtx, &cmd.AssignTag{Tag: addFeatureRequest.Result, Post: newPost.Result})
+
+ getPost := &query.GetPostByNumber{Number: newPost.Result.Number}
+ err = bus.Dispatch(aryaStarkCtx, getPost)
+ Expect(err).IsNil()
+ Expect(getPost.Result.Tags).HasLen(1)
+ Expect(getPost.Result.Tags[0]).Equals(addBug.Result.Slug)
+
+ err = bus.Dispatch(jonSnowCtx, getPost)
+ Expect(err).IsNil()
+ Expect(getPost.Result.Tags).HasLen(2)
+ Expect(getPost.Result.Tags[0]).Equals(addBug.Result.Slug)
+ Expect(getPost.Result.Tags[1]).Equals(addFeatureRequest.Result.Slug)
+}
+
+func TestPostStorage_IsReferenced(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost1 := &cmd.AddNewPost{Title: "My first post", Description: "with this description"}
+ newPost2 := &cmd.AddNewPost{Title: "My second post", Description: "with this description"}
+ newPost3 := &cmd.AddNewPost{Title: "My third post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost1, newPost2, newPost3)
+ Expect(err).IsNil()
+
+ bus.Dispatch(jonSnowCtx, &cmd.MarkPostAsDuplicate{Post: newPost2.Result, Original: newPost3.Result})
+ bus.Dispatch(jonSnowCtx, &cmd.MarkPostAsDuplicate{Post: newPost3.Result, Original: newPost1.Result})
+
+ isReferenced1 := &query.PostIsReferenced{PostID: newPost1.Result.ID}
+ isReferenced2 := &query.PostIsReferenced{PostID: newPost2.Result.ID}
+ isReferenced3 := &query.PostIsReferenced{PostID: newPost3.Result.ID}
+
+ err = bus.Dispatch(jonSnowCtx, isReferenced1, isReferenced2, isReferenced3)
+ Expect(err).IsNil()
+ Expect(isReferenced1.Result).IsTrue()
+ Expect(isReferenced2.Result).IsFalse()
+ Expect(isReferenced3.Result).IsTrue()
+}
+
+func TestPostStorage_ListVotesOfPost(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ bus.Dispatch(jonSnowCtx, &cmd.AddVote{Post: newPost.Result, User: jonSnow})
+ bus.Dispatch(jonSnowCtx, &cmd.AddVote{Post: newPost.Result, User: aryaStark})
+
+ listVotes := &query.ListPostVotes{PostID: newPost.Result.ID}
+ err = bus.Dispatch(jonSnowCtx, listVotes)
+ Expect(err).IsNil()
+ Expect(listVotes.Result).HasLen(2)
+
+ Expect(listVotes.Result[0].CreatedAt).TemporarilySimilar(time.Now(), 5*time.Second)
+ Expect(listVotes.Result[0].User.Name).Equals("Jon Snow")
+ Expect(listVotes.Result[0].User.Email).Equals("[email protected]")
+
+ Expect(listVotes.Result[1].CreatedAt).TemporarilySimilar(time.Now(), 5*time.Second)
+ Expect(listVotes.Result[1].User.Name).Equals("Arya Stark")
+ Expect(listVotes.Result[1].User.Email).Equals("[email protected]")
+}
+
+func TestPostStorage_Attachments(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost1 := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ newPost2 := &cmd.AddNewPost{Title: "My other post", Description: "with another description"}
+ err := bus.Dispatch(jonSnowCtx, newPost1, newPost2)
+ Expect(err).IsNil()
+
+ getAttachments1 := &query.GetAttachments{Post: newPost1.Result}
+ getAttachments2 := &query.GetAttachments{Post: newPost2.Result}
+
+ err = bus.Dispatch(jonSnowCtx, getAttachments1)
+ Expect(err).IsNil()
+ Expect(getAttachments1.Result).HasLen(0)
+
+ bytes, err := ioutil.ReadFile(env.Path("favicon.png"))
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.SetAttachments{
+ Post: newPost1.Result,
+ Attachments: []*models.ImageUpload{
+ &models.ImageUpload{
+ BlobKey: "12345-test.png",
+ Upload: &models.ImageUploadData{
+ FileName: "test.png",
+ ContentType: "image/png",
+ Content: bytes,
+ },
+ },
+ },
+ })
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, getAttachments1, getAttachments2)
+ Expect(err).IsNil()
+ Expect(getAttachments1.Result).HasLen(1)
+ Expect(getAttachments1.Result[0]).Equals("12345-test.png")
+ Expect(getAttachments2.Result).HasLen(0)
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.SetAttachments{
+ Post: newPost2.Result,
+ Attachments: []*models.ImageUpload{
+ &models.ImageUpload{
+ BlobKey: "12345-test.png",
+ Remove: true,
+ },
+ &models.ImageUpload{
+ BlobKey: "67890-test2.png",
+ Upload: &models.ImageUploadData{
+ FileName: "test2.png",
+ ContentType: "image/png",
+ Content: bytes,
+ },
+ },
+ &models.ImageUpload{
+ BlobKey: "67890-test6.png",
+ Upload: &models.ImageUploadData{
+ FileName: "test6.png",
+ ContentType: "image/png",
+ Content: bytes,
+ },
+ },
+ },
+ })
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, getAttachments1, getAttachments2)
+ Expect(err).IsNil()
+ Expect(getAttachments1.Result).HasLen(1)
+ Expect(getAttachments1.Result[0]).Equals("12345-test.png")
+ Expect(getAttachments2.Result).HasLen(2)
+ Expect(getAttachments2.Result[0]).Equals("67890-test2.png")
+ Expect(getAttachments2.Result[1]).Equals("67890-test6.png")
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.SetAttachments{
+ Post: newPost1.Result,
+ Attachments: []*models.ImageUpload{
+ &models.ImageUpload{
+ BlobKey: "12345-test.png",
+ Remove: true,
+ },
+ },
+ })
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, getAttachments1)
+ Expect(err).IsNil()
+ Expect(getAttachments1.Result).HasLen(0)
+}
diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.go
new file mode 100644
index 000000000..8e0e74bcc
--- /dev/null
+++ b/app/services/sqlstore/postgres/postgres.go
@@ -0,0 +1,129 @@
+package postgres
+
+import (
+ "context"
+
+ "github.com/getfider/fider/app"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/stripe/stripe-go/client"
+)
+
+var stripeClient *client.API
+
+func init() {
+ bus.Register(Service{})
+}
+
+type Service struct{}
+
+func (s Service) Name() string {
+ return "PostgreSQL"
+}
+
+func (s Service) Category() string {
+ return "sqlstore"
+}
+
+func (s Service) Enabled() bool {
+ return true
+}
+
+func (s Service) Init() {
+ bus.AddHandler(storeEvent)
+
+ bus.AddHandler(markAllNotificationsAsRead)
+ bus.AddHandler(markNotificationAsRead)
+ bus.AddHandler(countUnreadNotifications)
+ bus.AddHandler(getNotificationByID)
+ bus.AddHandler(getActiveNotifications)
+ bus.AddHandler(addNewNotification)
+ bus.AddHandler(addSubscriber)
+ bus.AddHandler(removeSubscriber)
+ bus.AddHandler(getActiveSubscribers)
+
+ bus.AddHandler(getTagBySlug)
+ bus.AddHandler(getAssignedTags)
+ bus.AddHandler(getAllTags)
+ bus.AddHandler(addNewTag)
+ bus.AddHandler(updateTag)
+ bus.AddHandler(deleteTag)
+ bus.AddHandler(assignTag)
+ bus.AddHandler(unassignTag)
+
+ bus.AddHandler(addVote)
+ bus.AddHandler(removeVote)
+ bus.AddHandler(listPostVotes)
+
+ bus.AddHandler(addNewPost)
+ bus.AddHandler(updatePost)
+ bus.AddHandler(getPostByID)
+ bus.AddHandler(getPostBySlug)
+ bus.AddHandler(getPostByNumber)
+ bus.AddHandler(searchPosts)
+ bus.AddHandler(getAllPosts)
+ bus.AddHandler(countPostPerStatus)
+ bus.AddHandler(markPostAsDuplicate)
+ bus.AddHandler(setPostResponse)
+ bus.AddHandler(postIsReferenced)
+
+ bus.AddHandler(setAttachments)
+ bus.AddHandler(getAttachments)
+ bus.AddHandler(uploadImage)
+ bus.AddHandler(uploadImages)
+
+ bus.AddHandler(addNewComment)
+ bus.AddHandler(updateComment)
+ bus.AddHandler(deleteComment)
+ bus.AddHandler(getCommentByID)
+ bus.AddHandler(getCommentsByPost)
+
+ bus.AddHandler(countUsers)
+ bus.AddHandler(blockUser)
+ bus.AddHandler(unblockUser)
+ bus.AddHandler(regenerateAPIKey)
+ bus.AddHandler(userSubscribedTo)
+ bus.AddHandler(deleteCurrentUser)
+ bus.AddHandler(changeUserEmail)
+ bus.AddHandler(changeUserRole)
+ bus.AddHandler(updateCurrentUserSettings)
+ bus.AddHandler(getCurrentUserSettings)
+ bus.AddHandler(registerUser)
+ bus.AddHandler(registerUserProvider)
+ bus.AddHandler(updateCurrentUser)
+ bus.AddHandler(getUserByAPIKey)
+ bus.AddHandler(getUserByEmail)
+ bus.AddHandler(getUserByID)
+ bus.AddHandler(getUserByProvider)
+ bus.AddHandler(getAllUsers)
+
+ bus.AddHandler(createTenant)
+ bus.AddHandler(getFirstTenant)
+ bus.AddHandler(getTenantByDomain)
+ bus.AddHandler(activateTenant)
+ bus.AddHandler(isSubdomainAvailable)
+ bus.AddHandler(isCNAMEAvailable)
+ bus.AddHandler(updateTenantSettings)
+ bus.AddHandler(updateTenantPrivacySettings)
+ bus.AddHandler(updateTenantAdvancedSettings)
+ bus.AddHandler(updateTenantBillingSettings)
+
+ bus.AddHandler(getVerificationByKey)
+ bus.AddHandler(saveVerificationKey)
+ bus.AddHandler(setKeyAsVerified)
+
+ bus.AddHandler(listCustomOAuthConfig)
+ bus.AddHandler(getCustomOAuthConfigByProvider)
+ bus.AddHandler(saveCustomOAuthConfig)
+}
+
+type SqlHandler func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error
+
+func using(ctx context.Context, handler SqlHandler) error {
+ trx := ctx.Value(app.TransactionCtxKey).(*dbx.Trx)
+ tenant, _ := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ user, _ := ctx.Value(app.UserCtxKey).(*models.User)
+ return handler(trx, tenant, user)
+}
diff --git a/app/services/sqlstore/postgres/setup_test.go b/app/services/sqlstore/postgres/setup_test.go
new file mode 100644
index 000000000..f5da5ca06
--- /dev/null
+++ b/app/services/sqlstore/postgres/setup_test.go
@@ -0,0 +1,92 @@
+package postgres_test
+
+import (
+ "context"
+ "net/url"
+ "os"
+ "testing"
+
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/services/sqlstore/postgres"
+
+ "github.com/getfider/fider/app/pkg/bus"
+
+ "github.com/getfider/fider/app"
+
+ "github.com/getfider/fider/app/models"
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/web"
+)
+
+var trx *dbx.Trx
+
+var demoTenant *models.Tenant
+var avengersTenant *models.Tenant
+var gotTenant *models.Tenant
+var jonSnow *models.User
+var aryaStark *models.User
+var sansaStark *models.User
+var tonyStark *models.User
+
+var demoTenantCtx context.Context
+var avengersTenantCtx context.Context
+var gotTenantCtx context.Context
+
+var jonSnowCtx context.Context
+var aryaStarkCtx context.Context
+var sansaStarkCtx context.Context
+var tonyStarkCtx context.Context
+
+func SetupDatabaseTest(t *testing.T) context.Context {
+ RegisterT(t)
+ bus.Init(postgres.Service{})
+
+ u, _ := url.Parse("http://cdn.test.fider.io")
+ req := web.Request{URL: u}
+ ctx := context.WithValue(context.Background(), app.RequestCtxKey, req)
+
+ trx, _ = dbx.BeginTx(ctx)
+ trxCtx := context.WithValue(ctx, app.TransactionCtxKey, trx)
+
+ getDemo := &query.GetTenantByDomain{Domain: "demo"}
+ getAvengers := &query.GetTenantByDomain{Domain: "avengers"}
+ getGameOfThrones := &query.GetTenantByDomain{Domain: "got"}
+ bus.Dispatch(trxCtx, getDemo, getAvengers, getGameOfThrones)
+ demoTenant = getDemo.Result
+ avengersTenant = getAvengers.Result
+ gotTenant = getGameOfThrones.Result
+
+ demoTenantCtx = withTenant(trxCtx, demoTenant)
+ avengersTenantCtx = withTenant(trxCtx, avengersTenant)
+ gotTenantCtx = withTenant(trxCtx, gotTenant)
+
+ getJonSnow := &query.GetUserByEmail{Email: "[email protected]"}
+ getAryaStark := &query.GetUserByEmail{Email: "[email protected]"}
+ getSansaStark := &query.GetUserByEmail{Email: "[email protected]"}
+ bus.Dispatch(demoTenantCtx, getJonSnow, getSansaStark, getAryaStark)
+ jonSnow = getJonSnow.Result
+ aryaStark = getAryaStark.Result
+ sansaStark = getSansaStark.Result
+
+ getTonyStark := &query.GetUserByEmail{Email: "[email protected]"}
+ bus.Dispatch(avengersTenantCtx, getTonyStark)
+ tonyStark = getTonyStark.Result
+
+ jonSnowCtx = withUser(trxCtx, jonSnow)
+ aryaStarkCtx = withUser(trxCtx, aryaStark)
+ sansaStarkCtx = withUser(trxCtx, sansaStark)
+ tonyStarkCtx = withUser(trxCtx, tonyStark)
+ return trxCtx
+}
+
+func TeardownDatabaseTest() {
+ trx.Rollback()
+}
+
+func TestMain(m *testing.M) {
+ dbx.Seed()
+
+ code := m.Run()
+ os.Exit(code)
+}
diff --git a/app/services/sqlstore/postgres/subscription_test.go b/app/services/sqlstore/postgres/subscription_test.go
new file mode 100644
index 000000000..27f990c49
--- /dev/null
+++ b/app/services/sqlstore/postgres/subscription_test.go
@@ -0,0 +1,317 @@
+package postgres_test
+
+import (
+ "strconv"
+ "testing"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+)
+
+func TestSubscription_NoSettings(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(aryaStarkCtx, newPost)
+ Expect(err).IsNil()
+
+ newPostSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewPost}
+ newCommentSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewComment}
+ changeStatusSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventChangeStatus}
+ err = bus.Dispatch(aryaStarkCtx, newPostSubscribers, newCommentSubscribers, changeStatusSubscribers)
+ Expect(err).IsNil()
+
+ Expect(newPostSubscribers.Result).HasLen(1)
+ Expect(newPostSubscribers.Result[0].ID).Equals(jonSnow.ID)
+
+ Expect(newCommentSubscribers.Result).HasLen(2)
+ Expect(newCommentSubscribers.Result[0].ID).Equals(jonSnow.ID)
+ Expect(newCommentSubscribers.Result[1].ID).Equals(aryaStark.ID)
+
+ Expect(changeStatusSubscribers.Result).HasLen(2)
+ Expect(changeStatusSubscribers.Result[0].ID).Equals(jonSnow.ID)
+ Expect(changeStatusSubscribers.Result[1].ID).Equals(aryaStark.ID)
+
+ subscribed := &query.UserSubscribedTo{PostID: newPost.Result.ID}
+
+ err = bus.Dispatch(ctx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsFalse()
+
+ err = bus.Dispatch(jonSnowCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsTrue()
+
+ err = bus.Dispatch(aryaStarkCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsTrue()
+
+ err = bus.Dispatch(sansaStarkCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsFalse()
+}
+
+func TestSubscription_RemoveSubscriber(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "Post #1", Description: "Description #1"}
+ err := bus.Dispatch(aryaStarkCtx, newPost)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(aryaStarkCtx, &cmd.RemoveSubscriber{Post: newPost.Result, User: aryaStark})
+ Expect(err).IsNil()
+
+ newPostSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewPost}
+ newCommentSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewComment}
+ changeStatusSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventChangeStatus}
+ err = bus.Dispatch(aryaStarkCtx, newPostSubscribers, newCommentSubscribers, changeStatusSubscribers)
+ Expect(err).IsNil()
+
+ Expect(newPostSubscribers.Result).HasLen(1)
+ Expect(newPostSubscribers.Result[0].ID).Equals(jonSnow.ID)
+
+ Expect(newCommentSubscribers.Result).HasLen(1)
+ Expect(newCommentSubscribers.Result[0].ID).Equals(jonSnow.ID)
+
+ Expect(changeStatusSubscribers.Result).HasLen(1)
+ Expect(changeStatusSubscribers.Result[0].ID).Equals(jonSnow.ID)
+
+ subscribed := &query.UserSubscribedTo{PostID: newPost.Result.ID}
+
+ err = bus.Dispatch(jonSnowCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsTrue()
+
+ err = bus.Dispatch(aryaStarkCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsFalse()
+
+ err = bus.Dispatch(sansaStarkCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsFalse()
+}
+
+func TestSubscription_AdminSubmitted(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "Post #1", Description: "Description #1"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ newPostSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewPost}
+ newCommentSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewComment}
+ changeStatusSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventChangeStatus}
+ err = bus.Dispatch(jonSnowCtx, newPostSubscribers, newCommentSubscribers, changeStatusSubscribers)
+ Expect(err).IsNil()
+
+ Expect(newPostSubscribers.Result).HasLen(1)
+ Expect(newPostSubscribers.Result[0].ID).Equals(jonSnow.ID)
+
+ Expect(newCommentSubscribers.Result).HasLen(1)
+ Expect(newCommentSubscribers.Result[0].ID).Equals(jonSnow.ID)
+
+ Expect(changeStatusSubscribers.Result).HasLen(1)
+ Expect(changeStatusSubscribers.Result[0].ID).Equals(jonSnow.ID)
+
+ subscribed := &query.UserSubscribedTo{PostID: newPost.Result.ID}
+
+ err = bus.Dispatch(jonSnowCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsTrue()
+
+ err = bus.Dispatch(aryaStarkCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsFalse()
+
+ err = bus.Dispatch(sansaStarkCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsFalse()
+}
+
+func TestSubscription_AdminUnsubscribed(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "Post #1", Description: "Description #1"}
+ err := bus.Dispatch(aryaStarkCtx, newPost)
+ Expect(err).IsNil()
+
+ bus.Dispatch(aryaStarkCtx, &cmd.RemoveSubscriber{Post: newPost.Result, User: aryaStark})
+ bus.Dispatch(aryaStarkCtx, &cmd.RemoveSubscriber{Post: newPost.Result, User: jonSnow})
+
+ newCommentSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewComment}
+ err = bus.Dispatch(aryaStarkCtx, newCommentSubscribers)
+ Expect(err).IsNil()
+ Expect(newCommentSubscribers.Result).HasLen(0)
+
+ subscribed := &query.UserSubscribedTo{PostID: newPost.Result.ID}
+
+ err = bus.Dispatch(jonSnowCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsFalse()
+
+ err = bus.Dispatch(aryaStarkCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsFalse()
+
+ err = bus.Dispatch(sansaStarkCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsFalse()
+}
+
+func TestSubscription_DisabledEmail(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "Post #1", Description: "Description #1"}
+ err := bus.Dispatch(aryaStarkCtx, newPost)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(aryaStarkCtx, &cmd.UpdateCurrentUserSettings{
+ Settings: map[string]string{
+ enum.NotificationEventNewComment.UserSettingsKeyName: strconv.Itoa(int(enum.NotificationChannelWeb)),
+ },
+ })
+ Expect(err).IsNil()
+
+ newCommentWebSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewComment}
+ newCommentEmailSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelEmail, Event: enum.NotificationEventNewComment}
+ changeStatusSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventChangeStatus}
+ err = bus.Dispatch(aryaStarkCtx, newCommentWebSubscribers, newCommentEmailSubscribers, changeStatusSubscribers)
+ Expect(err).IsNil()
+
+ Expect(newCommentWebSubscribers.Result).HasLen(2)
+ Expect(newCommentWebSubscribers.Result[0].ID).Equals(jonSnow.ID)
+ Expect(newCommentWebSubscribers.Result[1].ID).Equals(aryaStark.ID)
+
+ Expect(newCommentEmailSubscribers.Result).HasLen(1)
+ Expect(newCommentEmailSubscribers.Result[0].ID).Equals(jonSnow.ID)
+
+ Expect(changeStatusSubscribers.Result).HasLen(2)
+ Expect(changeStatusSubscribers.Result[0].ID).Equals(jonSnow.ID)
+ Expect(changeStatusSubscribers.Result[1].ID).Equals(aryaStark.ID)
+
+ subscribed := &query.UserSubscribedTo{PostID: newPost.Result.ID}
+
+ err = bus.Dispatch(jonSnowCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsTrue()
+
+ err = bus.Dispatch(aryaStarkCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsTrue()
+
+ err = bus.Dispatch(sansaStarkCtx, subscribed)
+ Expect(err).IsNil()
+ Expect(subscribed.Result).IsFalse()
+}
+
+func TestSubscription_VisitorEnabledNewPost(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "Post #1", Description: "Description #1"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(aryaStarkCtx, &cmd.UpdateCurrentUserSettings{
+ Settings: map[string]string{
+ enum.NotificationEventNewPost.UserSettingsKeyName: strconv.Itoa(int(enum.NotificationChannelEmail | enum.NotificationChannelWeb)),
+ },
+ })
+ Expect(err).IsNil()
+
+ newPostWebSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewPost}
+ newPostEmailSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelEmail, Event: enum.NotificationEventNewPost}
+ err = bus.Dispatch(aryaStarkCtx, newPostWebSubscribers, newPostEmailSubscribers)
+ Expect(err).IsNil()
+
+ Expect(newPostWebSubscribers.Result).HasLen(2)
+ Expect(newPostWebSubscribers.Result[0].ID).Equals(jonSnow.ID)
+ Expect(newPostWebSubscribers.Result[1].ID).Equals(aryaStark.ID)
+
+ Expect(newPostEmailSubscribers.Result).HasLen(2)
+ Expect(newPostEmailSubscribers.Result[0].ID).Equals(jonSnow.ID)
+ Expect(newPostEmailSubscribers.Result[1].ID).Equals(aryaStark.ID)
+}
+
+func TestSubscription_DisabledEverything(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "Post #1", Description: "Description #1"}
+ err := bus.Dispatch(jonSnowCtx, newPost)
+ Expect(err).IsNil()
+
+ disableAll := map[string]string{
+ enum.NotificationEventNewPost.UserSettingsKeyName: "0",
+ enum.NotificationEventNewComment.UserSettingsKeyName: "0",
+ enum.NotificationEventChangeStatus.UserSettingsKeyName: "0",
+ }
+
+ err = bus.Dispatch(aryaStarkCtx, &cmd.UpdateCurrentUserSettings{Settings: disableAll})
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.UpdateCurrentUserSettings{Settings: disableAll})
+ Expect(err).IsNil()
+
+ newPostWebSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewPost}
+ newPostEmailSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelEmail, Event: enum.NotificationEventNewPost}
+ newCommentWebSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewComment}
+ newCommentEmailSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelEmail, Event: enum.NotificationEventNewComment}
+ changeStatusWebSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventChangeStatus}
+ changeStatusEmailSubscribers := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelEmail, Event: enum.NotificationEventChangeStatus}
+ err = bus.Dispatch(aryaStarkCtx, newPostWebSubscribers, newPostEmailSubscribers, newCommentWebSubscribers, newCommentEmailSubscribers, changeStatusWebSubscribers, changeStatusEmailSubscribers)
+ Expect(err).IsNil()
+
+ Expect(newPostWebSubscribers.Result).HasLen(0)
+ Expect(newPostEmailSubscribers.Result).HasLen(0)
+ Expect(newCommentWebSubscribers.Result).HasLen(0)
+ Expect(newCommentEmailSubscribers.Result).HasLen(0)
+ Expect(changeStatusWebSubscribers.Result).HasLen(0)
+ Expect(changeStatusEmailSubscribers.Result).HasLen(0)
+}
+
+func TestSubscription_DeletedPost(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "Post #1", Description: "Description #1"}
+ err := bus.Dispatch(aryaStarkCtx, newPost)
+ Expect(err).IsNil()
+
+ bus.Dispatch(aryaStarkCtx, &cmd.SetPostResponse{Post: newPost.Result, Text: "Invalid Post!", Status: enum.PostDeleted})
+
+ q := &query.GetActiveSubscribers{Number: newPost.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewComment}
+ err = bus.Dispatch(aryaStarkCtx, q)
+ Expect(err).IsNil()
+ Expect(q.Result).HasLen(2)
+ Expect(q.Result[0].ID).Equals(jonSnow.ID)
+ Expect(q.Result[1].ID).Equals(aryaStark.ID)
+}
+
+func TestSubscription_SubscribedToDifferentPost(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost1 := &cmd.AddNewPost{Title: "Post #1", Description: "Description #1"}
+ newPost2 := &cmd.AddNewPost{Title: "Post #2", Description: "Description #2"}
+ err := bus.Dispatch(jonSnowCtx, newPost1, newPost2)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.AddSubscriber{Post: newPost2.Result, User: aryaStark})
+ Expect(err).IsNil()
+
+ q := &query.GetActiveSubscribers{Number: newPost1.Result.Number, Channel: enum.NotificationChannelWeb, Event: enum.NotificationEventNewComment}
+ err = bus.Dispatch(jonSnowCtx, q)
+ Expect(err).IsNil()
+ Expect(q.Result).HasLen(1)
+ Expect(q.Result[0].ID).Equals(jonSnow.ID)
+}
diff --git a/app/services/sqlstore/postgres/tag.go b/app/services/sqlstore/postgres/tag.go
new file mode 100644
index 000000000..848f4f59f
--- /dev/null
+++ b/app/services/sqlstore/postgres/tag.go
@@ -0,0 +1,201 @@
+package postgres
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/gosimple/slug"
+)
+
+type dbTag struct {
+ ID int `db:"id"`
+ Name string `db:"name"`
+ Slug string `db:"slug"`
+ Color string `db:"color"`
+ IsPublic bool `db:"is_public"`
+}
+
+func (t *dbTag) toModel() *models.Tag {
+ return &models.Tag{
+ ID: t.ID,
+ Name: t.Name,
+ Slug: t.Slug,
+ Color: t.Color,
+ IsPublic: t.IsPublic,
+ }
+}
+
+func getTagBySlug(ctx context.Context, q *query.GetTagBySlug) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ tag, err := queryTagBySlug(trx, tenant, q.Slug)
+ q.Result = tag
+ return err
+ })
+}
+
+func getAssignedTags(ctx context.Context, q *query.GetAssignedTags) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ q.Result = make([]*models.Tag, 0)
+
+ tags, err := queryTags(trx, `
+ SELECT t.id, t.name, t.slug, t.color, t.is_public
+ FROM tags t
+ INNER JOIN post_tags pt
+ ON pt.tag_id = t.id
+ AND pt.tenant_id = t.tenant_id
+ WHERE pt.post_id = $1 AND t.tenant_id = $2
+ ORDER BY t.name
+ `, q.Post.ID, tenant.ID)
+
+ if err != nil {
+ return errors.Wrap(err, "failed get assigned tags")
+ }
+
+ q.Result = tags
+ return nil
+ })
+}
+
+func getAllTags(ctx context.Context, q *query.GetAllTags) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ q.Result = make([]*models.Tag, 0)
+
+ condition := `AND t.is_public = true`
+ if user != nil && user.IsCollaborator() {
+ condition = ``
+ }
+
+ query := fmt.Sprintf(`
+ SELECT t.id, t.name, t.slug, t.color, t.is_public
+ FROM tags t
+ WHERE t.tenant_id = $1 %s
+ ORDER BY t.name
+ `, condition)
+ tags, err := queryTags(trx, query, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed get all tags")
+ }
+
+ q.Result = tags
+ return nil
+ })
+}
+
+func addNewTag(ctx context.Context, c *cmd.AddNewTag) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ c.Result = nil
+ newSlug := slug.Make(c.Name)
+
+ _, err := trx.Execute(`
+ INSERT INTO tags (name, slug, color, is_public, created_at, tenant_id)
+ VALUES ($1, $2, $3, $4, $5, $6) RETURNING id
+ `, c.Name, newSlug, c.Color, c.IsPublic, time.Now(), tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to add new tag")
+ }
+
+ tag, err := queryTagBySlug(trx, tenant, newSlug)
+ c.Result = tag
+ return err
+ })
+}
+
+func updateTag(ctx context.Context, c *cmd.UpdateTag) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ c.Result = nil
+ newSlug := slug.Make(c.Name)
+
+ _, err := trx.Execute(`UPDATE tags SET name = $1, slug = $2, color = $3, is_public = $4
+ WHERE id = $5 AND tenant_id = $6`, c.Name, newSlug, c.Color, c.IsPublic, c.TagID, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to update tag")
+ }
+
+ tag, err := queryTagBySlug(trx, tenant, newSlug)
+ c.Result = tag
+ return err
+ })
+}
+
+func deleteTag(ctx context.Context, c *cmd.DeleteTag) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ _, err := trx.Execute(`DELETE FROM post_tags WHERE tag_id = $1 AND tenant_id = $2`, c.Tag.ID, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to remove tag with id '%d' from all posts", c.Tag.ID)
+ }
+
+ _, err = trx.Execute(`DELETE FROM tags WHERE id = $1 AND tenant_id = $2`, c.Tag.ID, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to delete tag with id '%d'", c.Tag.ID)
+ }
+ return nil
+ })
+}
+
+func assignTag(ctx context.Context, c *cmd.AssignTag) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ alreadyAssigned, err := trx.Exists("SELECT 1 FROM post_tags WHERE post_id = $1 AND tag_id = $2 AND tenant_id = $3", c.Post.ID, c.Tag.ID, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to check if tag is already assigned")
+ }
+
+ if alreadyAssigned {
+ return nil
+ }
+
+ _, err = trx.Execute(
+ `INSERT INTO post_tags (tag_id, post_id, created_at, created_by_id, tenant_id) VALUES ($1, $2, $3, $4, $5)`,
+ c.Tag.ID, c.Post.ID, time.Now(), user.ID, tenant.ID,
+ )
+
+ if err != nil {
+ return errors.Wrap(err, "failed to assign tag to post")
+ }
+ return nil
+ })
+}
+
+func unassignTag(ctx context.Context, c *cmd.UnassignTag) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ _, err := trx.Execute(
+ `DELETE FROM post_tags WHERE tag_id = $1 AND post_id = $2 AND tenant_id = $3`,
+ c.Tag.ID, c.Post.ID, tenant.ID,
+ )
+
+ if err != nil {
+ return errors.Wrap(err, "failed to unassign tag from post")
+ }
+ return nil
+ })
+}
+
+func queryTagBySlug(trx *dbx.Trx, tenant *models.Tenant, slug string) (*models.Tag, error) {
+ tag := dbTag{}
+
+ err := trx.Get(&tag, "SELECT id, name, slug, color, is_public FROM tags WHERE tenant_id = $1 AND slug = $2", tenant.ID, slug)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get tag with slug '%s'", slug)
+ }
+
+ return tag.toModel(), nil
+}
+
+func queryTags(trx *dbx.Trx, query string, args ...interface{}) ([]*models.Tag, error) {
+ tags := []*dbTag{}
+ err := trx.Select(&tags, query, args...)
+ if err != nil {
+ return nil, err
+ }
+
+ var result = make([]*models.Tag, len(tags))
+ for i, tag := range tags {
+ result[i] = tag.toModel()
+ }
+ return result, nil
+}
diff --git a/app/services/sqlstore/postgres/tag_test.go b/app/services/sqlstore/postgres/tag_test.go
new file mode 100644
index 000000000..91a17172b
--- /dev/null
+++ b/app/services/sqlstore/postgres/tag_test.go
@@ -0,0 +1,162 @@
+package postgres_test
+
+import (
+ "testing"
+
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app/models/cmd"
+
+ "github.com/getfider/fider/app"
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+func TestTagStorage_AddAndGet(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ addNewTag := &cmd.AddNewTag{Name: "Feature Request", Color: "FF0000", IsPublic: true}
+ err := bus.Dispatch(demoTenantCtx, addNewTag)
+ Expect(err).IsNil()
+ Expect(addNewTag.Result.Slug).Equals("feature-request")
+
+ getTag := &query.GetTagBySlug{Slug: addNewTag.Result.Slug}
+ err = bus.Dispatch(demoTenantCtx, getTag)
+ Expect(err).IsNil()
+ Expect(getTag.Result.ID).NotEquals(0)
+ Expect(getTag.Result.Name).Equals("Feature Request")
+ Expect(getTag.Result.Slug).Equals("feature-request")
+ Expect(getTag.Result.Color).Equals("FF0000")
+ Expect(getTag.Result.IsPublic).IsTrue()
+}
+
+func TestTagStorage_AddUpdateAndGet(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ addNewTag := &cmd.AddNewTag{Name: "Feature Request", Color: "FF0000", IsPublic: true}
+ err := bus.Dispatch(demoTenantCtx, addNewTag)
+ Expect(err).IsNil()
+
+ updateTag := &cmd.UpdateTag{TagID: addNewTag.Result.ID, Name: "Bug", Color: "000000", IsPublic: false}
+ err = bus.Dispatch(demoTenantCtx, updateTag)
+ Expect(err).IsNil()
+
+ getTag := &query.GetTagBySlug{Slug: updateTag.Result.Slug}
+ err = bus.Dispatch(demoTenantCtx, getTag)
+ Expect(err).IsNil()
+ Expect(getTag.Result.ID).Equals(addNewTag.Result.ID)
+ Expect(getTag.Result.Name).Equals("Bug")
+ Expect(getTag.Result.Slug).Equals("bug")
+ Expect(getTag.Result.Color).Equals("000000")
+ Expect(getTag.Result.IsPublic).IsFalse()
+}
+
+func TestTagStorage_AddDeleteAndGet(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ addNewTag := &cmd.AddNewTag{Name: "Bug", Color: "FFFFFF", IsPublic: true}
+ err := bus.Dispatch(demoTenantCtx, addNewTag)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(demoTenantCtx, &cmd.DeleteTag{Tag: addNewTag.Result})
+ Expect(err).IsNil()
+
+ getTag := &query.GetTagBySlug{Slug: addNewTag.Result.Slug}
+ err = bus.Dispatch(demoTenantCtx, getTag)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(getTag.Result).IsNil()
+}
+
+func TestTagStorage_Assign_Unassign(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(aryaStarkCtx, newPost)
+ Expect(err).IsNil()
+
+ addNewTag := &cmd.AddNewTag{Name: "Bug", Color: "FFFFFF", IsPublic: true}
+ err = bus.Dispatch(jonSnowCtx, addNewTag)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.AssignTag{Tag: addNewTag.Result, Post: newPost.Result})
+ Expect(err).IsNil()
+
+ assignedTags := &query.GetAssignedTags{Post: newPost.Result}
+ err = bus.Dispatch(demoTenantCtx, assignedTags)
+ Expect(err).IsNil()
+ Expect(assignedTags.Result).HasLen(1)
+ Expect(assignedTags.Result[0].ID).Equals(addNewTag.Result.ID)
+ Expect(assignedTags.Result[0].Name).Equals("Bug")
+ Expect(assignedTags.Result[0].Slug).Equals("bug")
+ Expect(assignedTags.Result[0].Color).Equals("FFFFFF")
+ Expect(assignedTags.Result[0].IsPublic).IsTrue()
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.UnassignTag{Tag: addNewTag.Result, Post: newPost.Result})
+ Expect(err).IsNil()
+
+ assignedTags = &query.GetAssignedTags{Post: newPost.Result}
+ err = bus.Dispatch(jonSnowCtx, assignedTags)
+ Expect(err).IsNil()
+ Expect(assignedTags.Result).HasLen(0)
+}
+
+func TestTagStorage_Assign_DeleteTag(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}
+ err := bus.Dispatch(aryaStarkCtx, newPost)
+ Expect(err).IsNil()
+
+ addNewTag := &cmd.AddNewTag{Name: "Bug", Color: "FFFFFF", IsPublic: true}
+ err = bus.Dispatch(jonSnowCtx, addNewTag)
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.AssignTag{Tag: addNewTag.Result, Post: newPost.Result})
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(jonSnowCtx, &cmd.DeleteTag{Tag: addNewTag.Result})
+ Expect(err).IsNil()
+
+ assignedTags := &query.GetAssignedTags{Post: newPost.Result}
+ err = bus.Dispatch(jonSnowCtx, assignedTags)
+ Expect(err).IsNil()
+ Expect(assignedTags.Result).HasLen(0)
+}
+
+func TestTagStorage_GetAll(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ err := bus.Dispatch(demoTenantCtx, &cmd.AddNewTag{Name: "Feature Request", Color: "FF0000", IsPublic: true})
+ Expect(err).IsNil()
+ err = bus.Dispatch(demoTenantCtx, &cmd.AddNewTag{Name: "Bug", Color: "0F0F0F", IsPublic: false})
+ Expect(err).IsNil()
+
+ getAllTags := &query.GetAllTags{}
+ err = bus.Dispatch(jonSnowCtx, getAllTags)
+ Expect(err).IsNil()
+ Expect(getAllTags.Result).HasLen(2)
+
+ Expect(getAllTags.Result[0].ID).NotEquals(0)
+ Expect(getAllTags.Result[0].Name).Equals("Bug")
+ Expect(getAllTags.Result[0].Slug).Equals("bug")
+ Expect(getAllTags.Result[0].Color).Equals("0F0F0F")
+ Expect(getAllTags.Result[0].IsPublic).IsFalse()
+
+ Expect(getAllTags.Result[1].ID).NotEquals(0)
+ Expect(getAllTags.Result[1].Name).Equals("Feature Request")
+ Expect(getAllTags.Result[1].Slug).Equals("feature-request")
+ Expect(getAllTags.Result[1].Color).Equals("FF0000")
+ Expect(getAllTags.Result[1].IsPublic).IsTrue()
+
+ err = bus.Dispatch(aryaStarkCtx, getAllTags)
+ Expect(err).IsNil()
+ Expect(getAllTags.Result).HasLen(1)
+ Expect(getAllTags.Result[0].Name).Equals("Feature Request")
+}
diff --git a/app/services/sqlstore/postgres/tenant.go b/app/services/sqlstore/postgres/tenant.go
new file mode 100644
index 000000000..0ea501cad
--- /dev/null
+++ b/app/services/sqlstore/postgres/tenant.go
@@ -0,0 +1,332 @@
+package postgres
+
+import (
+ "context"
+ "time"
+
+ "github.com/getfider/fider/app/pkg/bus"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+type dbTenant struct {
+ ID int `db:"id"`
+ Name string `db:"name"`
+ Subdomain string `db:"subdomain"`
+ CNAME string `db:"cname"`
+ Invitation string `db:"invitation"`
+ WelcomeMessage string `db:"welcome_message"`
+ Status int `db:"status"`
+ IsPrivate bool `db:"is_private"`
+ LogoBlobKey string `db:"logo_bkey"`
+ CustomCSS string `db:"custom_css"`
+ Billing *dbTenantBilling `db:"billing"`
+}
+
+func (t *dbTenant) toModel() *models.Tenant {
+ if t == nil {
+ return nil
+ }
+
+ tenant := &models.Tenant{
+ ID: t.ID,
+ Name: t.Name,
+ Subdomain: t.Subdomain,
+ CNAME: t.CNAME,
+ Invitation: t.Invitation,
+ WelcomeMessage: t.WelcomeMessage,
+ Status: t.Status,
+ IsPrivate: t.IsPrivate,
+ LogoBlobKey: t.LogoBlobKey,
+ CustomCSS: t.CustomCSS,
+ }
+
+ if t.Billing != nil && t.Billing.TrialEndsAt.Valid {
+ tenant.Billing = &models.TenantBilling{
+ TrialEndsAt: t.Billing.TrialEndsAt.Time,
+ StripeCustomerID: t.Billing.StripeCustomerID.String,
+ StripeSubscriptionID: t.Billing.StripeSubscriptionID.String,
+ StripePlanID: t.Billing.StripePlanID.String,
+ }
+ if t.Billing.SubscriptionEndsAt.Valid {
+ tenant.Billing.SubscriptionEndsAt = &t.Billing.SubscriptionEndsAt.Time
+ }
+ }
+
+ return tenant
+}
+
+type dbTenantBilling struct {
+ StripeCustomerID dbx.NullString `db:"stripe_customer_id"`
+ StripeSubscriptionID dbx.NullString `db:"stripe_subscription_id"`
+ StripePlanID dbx.NullString `db:"stripe_plan_id"`
+ TrialEndsAt dbx.NullTime `db:"trial_ends_at"`
+ SubscriptionEndsAt dbx.NullTime `db:"subscription_ends_at"`
+}
+
+type dbEmailVerification struct {
+ ID int `db:"id"`
+ Name string `db:"name"`
+ Email string `db:"email"`
+ Key string `db:"key"`
+ Kind enum.EmailVerificationKind `db:"kind"`
+ UserID dbx.NullInt `db:"user_id"`
+ CreatedAt time.Time `db:"created_at"`
+ ExpiresAt time.Time `db:"expires_at"`
+ VerifiedAt dbx.NullTime `db:"verified_at"`
+}
+
+func (t *dbEmailVerification) toModel() *models.EmailVerification {
+ model := &models.EmailVerification{
+ Name: t.Name,
+ Email: t.Email,
+ Key: t.Key,
+ Kind: t.Kind,
+ CreatedAt: t.CreatedAt,
+ ExpiresAt: t.ExpiresAt,
+ VerifiedAt: nil,
+ }
+
+ if t.VerifiedAt.Valid {
+ model.VerifiedAt = &t.VerifiedAt.Time
+ }
+
+ if t.UserID.Valid {
+ model.UserID = int(t.UserID.Int64)
+ }
+
+ return model
+}
+
+func isCNAMEAvailable(ctx context.Context, q *query.IsCNAMEAvailable) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ exists, err := trx.Exists("SELECT id FROM tenants WHERE cname = $1 AND id <> $2", q.CNAME, tenant.ID)
+ if err != nil {
+ q.Result = false
+ return errors.Wrap(err, "failed to check if tenant exists with CNAME '%s'", q.CNAME)
+ }
+ q.Result = !exists
+ return nil
+ })
+}
+
+func isSubdomainAvailable(ctx context.Context, q *query.IsSubdomainAvailable) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ exists, err := trx.Exists("SELECT id FROM tenants WHERE subdomain = $1", q.Subdomain)
+ if err != nil {
+ q.Result = false
+ return errors.Wrap(err, "failed to check if tenant exists with subdomain '%s'", q.Subdomain)
+ }
+ q.Result = !exists
+ return nil
+ })
+}
+
+func updateTenantPrivacySettings(ctx context.Context, c *cmd.UpdateTenantPrivacySettings) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ _, err := trx.Execute("UPDATE tenants SET is_private = $1 WHERE id = $2", c.Settings.IsPrivate, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed update tenant privacy settings")
+ }
+ return nil
+ })
+}
+
+func updateTenantSettings(ctx context.Context, c *cmd.UpdateTenantSettings) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if c.Settings.Logo.Remove {
+ c.Settings.Logo.BlobKey = ""
+ }
+
+ query := "UPDATE tenants SET name = $1, invitation = $2, welcome_message = $3, cname = $4, logo_bkey = $5 WHERE id = $6"
+ _, err := trx.Execute(query, c.Settings.Title, c.Settings.Invitation, c.Settings.WelcomeMessage, c.Settings.CNAME, c.Settings.Logo.BlobKey, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed update tenant settings")
+ }
+
+ tenant.Name = c.Settings.Title
+ tenant.Invitation = c.Settings.Invitation
+ tenant.CNAME = c.Settings.CNAME
+ tenant.WelcomeMessage = c.Settings.WelcomeMessage
+
+ return nil
+ })
+}
+
+func updateTenantBillingSettings(ctx context.Context, c *cmd.UpdateTenantBillingSettings) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ _, err := trx.Execute(`
+ UPDATE tenants_billing
+ SET stripe_customer_id = $1,
+ stripe_plan_id = $2,
+ stripe_subscription_id = $3,
+ subscription_ends_at = $4
+ WHERE tenant_id = $5
+ `,
+ c.Settings.StripeCustomerID,
+ c.Settings.StripePlanID,
+ c.Settings.StripeSubscriptionID,
+ c.Settings.SubscriptionEndsAt,
+ tenant.ID,
+ )
+ if err != nil {
+ return errors.Wrap(err, "failed update tenant billing settings")
+ }
+ return nil
+ })
+}
+
+func updateTenantAdvancedSettings(ctx context.Context, c *cmd.UpdateTenantAdvancedSettings) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ query := "UPDATE tenants SET custom_css = $1 WHERE id = $2"
+ _, err := trx.Execute(query, c.Settings.CustomCSS, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed update tenant advanced settings")
+ }
+
+ tenant.CustomCSS = c.Settings.CustomCSS
+ return nil
+ })
+}
+
+func activateTenant(ctx context.Context, c *cmd.ActivateTenant) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ query := "UPDATE tenants SET status = $1 WHERE id = $2"
+ _, err := trx.Execute(query, enum.TenantActive, c.TenantID)
+ if err != nil {
+ return errors.Wrap(err, "failed to activate tenant with id '%d'", c.TenantID)
+ }
+ return nil
+ })
+}
+
+func getVerificationByKey(ctx context.Context, q *query.GetVerificationByKey) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ verification := dbEmailVerification{}
+
+ query := "SELECT id, email, name, key, created_at, verified_at, expires_at, kind, user_id FROM email_verifications WHERE key = $1 AND kind = $2 LIMIT 1"
+ err := trx.Get(&verification, query, q.Key, q.Kind)
+ if err != nil {
+ return errors.Wrap(err, "failed to get email verification by its key")
+ }
+
+ q.Result = verification.toModel()
+ return nil
+ })
+}
+
+func saveVerificationKey(ctx context.Context, c *cmd.SaveVerificationKey) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ var userID interface{}
+ if c.Request.GetUser() != nil {
+ userID = c.Request.GetUser().ID
+ }
+
+ query := "INSERT INTO email_verifications (tenant_id, email, created_at, expires_at, key, name, kind, user_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)"
+ _, err := trx.Execute(query, tenant.ID, c.Request.GetEmail(), time.Now(), time.Now().Add(c.Duration), c.Key, c.Request.GetName(), c.Request.GetKind(), userID)
+ if err != nil {
+ return errors.Wrap(err, "failed to save verification key for kind '%d'", c.Request.GetKind())
+ }
+ return nil
+ })
+}
+
+func setKeyAsVerified(ctx context.Context, c *cmd.SetKeyAsVerified) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ query := "UPDATE email_verifications SET verified_at = $1 WHERE tenant_id = $2 AND key = $3"
+ _, err := trx.Execute(query, time.Now(), tenant.ID, c.Key)
+ if err != nil {
+ return errors.Wrap(err, "failed to update verified date of email verification request")
+ }
+ return nil
+ })
+}
+
+func createTenant(ctx context.Context, c *cmd.CreateTenant) error {
+ return using(ctx, func(trx *dbx.Trx, _ *models.Tenant, _ *models.User) error {
+ now := time.Now()
+
+ var id int
+ err := trx.Get(&id,
+ `INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey)
+ VALUES ($1, $2, $3, '', '', '', $4, false, '', '')
+ RETURNING id`, c.Name, c.Subdomain, now, c.Status)
+ if err != nil {
+ return err
+ }
+
+ if env.IsBillingEnabled() {
+ _, err = trx.Execute(
+ `INSERT INTO tenants_billing (tenant_id, trial_ends_at) VALUES ($1, $2)`,
+ id, now.Add(30*24*time.Hour),
+ )
+ if err != nil {
+ return err
+ }
+ }
+
+ byDomain := &query.GetTenantByDomain{Domain: c.Subdomain}
+ err = bus.Dispatch(ctx, byDomain)
+ c.Result = byDomain.Result
+ return err
+ })
+}
+
+func getFirstTenant(ctx context.Context, q *query.GetFirstTenant) error {
+ return using(ctx, func(trx *dbx.Trx, _ *models.Tenant, _ *models.User) error {
+ tenant := dbTenant{}
+
+ err := trx.Get(&tenant, `
+ SELECT t.id, t.name, t.subdomain, t.cname, t.invitation, t.welcome_message, t.status, t.is_private, t.logo_bkey, t.custom_css,
+ tb.trial_ends_at AS billing_trial_ends_at,
+ tb.subscription_ends_at AS billing_subscription_ends_at,
+ tb.stripe_customer_id AS billing_stripe_customer_id,
+ tb.stripe_plan_id AS billing_stripe_plan_id,
+ tb.stripe_subscription_id AS billing_stripe_subscription_id
+ FROM tenants t
+ LEFT JOIN tenants_billing tb
+ ON tb.tenant_id = t.id
+ ORDER BY t.id LIMIT 1
+ `)
+
+ if err != nil {
+ return errors.Wrap(err, "failed to get first tenant")
+ }
+
+ q.Result = tenant.toModel()
+ return nil
+ })
+}
+
+func getTenantByDomain(ctx context.Context, q *query.GetTenantByDomain) error {
+ return using(ctx, func(trx *dbx.Trx, _ *models.Tenant, _ *models.User) error {
+ tenant := dbTenant{}
+
+ err := trx.Get(&tenant, `
+ SELECT t.id, t.name, t.subdomain, t.cname, t.invitation, t.welcome_message, t.status, t.is_private, t.logo_bkey, t.custom_css,
+ tb.trial_ends_at AS billing_trial_ends_at,
+ tb.subscription_ends_at AS billing_subscription_ends_at,
+ tb.stripe_customer_id AS billing_stripe_customer_id,
+ tb.stripe_plan_id AS billing_stripe_plan_id,
+ tb.stripe_subscription_id AS billing_stripe_subscription_id
+ FROM tenants t
+ LEFT JOIN tenants_billing tb
+ ON tb.tenant_id = t.id
+ WHERE t.subdomain = $1 OR t.subdomain = $2 OR t.cname = $3
+ ORDER BY t.cname DESC
+ `, env.Subdomain(q.Domain), q.Domain, q.Domain)
+ if err != nil {
+ return errors.Wrap(err, "failed to get tenant with domain '%s'", q.Domain)
+ }
+
+ q.Result = tenant.toModel()
+ return nil
+ })
+}
diff --git a/app/services/sqlstore/postgres/tenant_test.go b/app/services/sqlstore/postgres/tenant_test.go
new file mode 100644
index 000000000..910fb18a4
--- /dev/null
+++ b/app/services/sqlstore/postgres/tenant_test.go
@@ -0,0 +1,411 @@
+package postgres_test
+
+import (
+ "testing"
+ "time"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
+
+ . "github.com/getfider/fider/app/pkg/assert"
+)
+
+func TestTenantStorage_Add_Activate(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ env.Config.Stripe.SecretKey = ""
+ createTenant := &cmd.CreateTenant{
+ Name: "My Domain Inc.",
+ Subdomain: "mydomain",
+ Status: enum.TenantPending,
+ }
+
+ err := bus.Dispatch(ctx, createTenant)
+ Expect(err).IsNil()
+ Expect(createTenant.Result).IsNotNil()
+
+ getByDomain := &query.GetTenantByDomain{Domain: "mydomain"}
+ err = bus.Dispatch(ctx, getByDomain)
+ Expect(err).IsNil()
+ Expect(getByDomain.Result.Name).Equals("My Domain Inc.")
+ Expect(getByDomain.Result.Subdomain).Equals("mydomain")
+ Expect(getByDomain.Result.Status).Equals(enum.TenantPending)
+ Expect(getByDomain.Result.IsPrivate).IsFalse()
+
+ err = bus.Dispatch(ctx, &cmd.ActivateTenant{TenantID: createTenant.Result.ID})
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(ctx, getByDomain)
+ Expect(err).IsNil()
+ Expect(getByDomain.Result.Name).Equals("My Domain Inc.")
+ Expect(getByDomain.Result.Subdomain).Equals("mydomain")
+ Expect(getByDomain.Result.Status).Equals(enum.TenantActive)
+ Expect(getByDomain.Result.IsPrivate).IsFalse()
+ Expect(getByDomain.Result.Billing).IsNil()
+}
+
+func TestTenantStorage_Add_WithBillingEnabled(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ env.Config.Stripe.SecretKey = "sk_1"
+ err := bus.Dispatch(ctx, &cmd.CreateTenant{
+ Name: "My Domain Inc.",
+ Subdomain: "mydomain",
+ Status: enum.TenantPending,
+ })
+ Expect(err).IsNil()
+
+ getByDomain := &query.GetTenantByDomain{Domain: "mydomain"}
+ err = bus.Dispatch(ctx, getByDomain)
+ Expect(err).IsNil()
+
+ Expect(getByDomain.Result.Name).Equals("My Domain Inc.")
+ Expect(getByDomain.Result.Subdomain).Equals("mydomain")
+ Expect(getByDomain.Result.Status).Equals(enum.TenantPending)
+ Expect(getByDomain.Result.IsPrivate).IsFalse()
+ Expect(getByDomain.Result.Billing).IsNotNil()
+ Expect(getByDomain.Result.Billing.TrialEndsAt).TemporarilySimilar(time.Now().Add(30*24*time.Hour), 5*time.Second)
+}
+
+func TestTenantStorage_SingleTenant_Add(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ env.Config.HostMode = "single"
+
+ createTenant := &cmd.CreateTenant{
+ Name: "My Domain Inc.",
+ Subdomain: "mydomain",
+ Status: enum.TenantPending,
+ }
+ err := bus.Dispatch(ctx, createTenant)
+ Expect(err).IsNil()
+ Expect(createTenant.Result).IsNotNil()
+}
+
+func TestTenantStorage_First(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ getFirst := &query.GetFirstTenant{}
+ err := bus.Dispatch(ctx, getFirst)
+ Expect(err).IsNil()
+ Expect(getFirst.Result.ID).Equals(1)
+ Expect(getFirst.Result.Name).Equals("Demonstration")
+}
+
+func TestTenantStorage_Empty_First(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ trx.Execute("TRUNCATE tenants CASCADE")
+
+ getFirst := &query.GetFirstTenant{}
+ err := bus.Dispatch(ctx, getFirst)
+
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(getFirst.Result).IsNil()
+}
+
+func TestTenantStorage_UpdatePrivacy(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ setPrivate := &cmd.UpdateTenantPrivacySettings{
+ Settings: &models.UpdateTenantPrivacy{IsPrivate: true},
+ }
+ getByDomain := &query.GetTenantByDomain{
+ Domain: "demo",
+ }
+ err := bus.Dispatch(demoTenantCtx, setPrivate, getByDomain)
+ Expect(err).IsNil()
+ Expect(getByDomain.Result.IsPrivate).IsTrue()
+}
+
+func TestTenantStorage_GetByDomain_NotFound(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ getByDomain := &query.GetTenantByDomain{
+ Domain: "unknown",
+ }
+ err := bus.Dispatch(ctx, getByDomain)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(getByDomain.Result).IsNil()
+}
+
+func TestTenantStorage_GetByDomain_CNAME(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ err := bus.Dispatch(demoTenantCtx, &cmd.UpdateTenantSettings{
+ Settings: &models.UpdateTenantSettings{
+ Title: "My Domain Inc.",
+ CNAME: "feedback.mycompany.com",
+ Logo: &models.ImageUpload{},
+ },
+ })
+ Expect(err).IsNil()
+
+ getByDomain := &query.GetTenantByDomain{Domain: "feedback.mycompany.com"}
+ err = bus.Dispatch(demoTenantCtx, getByDomain)
+ Expect(err).IsNil()
+ Expect(getByDomain.Result.ID).NotEquals(0)
+ Expect(getByDomain.Result.Name).Equals("My Domain Inc.")
+ Expect(getByDomain.Result.Subdomain).Equals("demo")
+ Expect(getByDomain.Result.CNAME).Equals("feedback.mycompany.com")
+ Expect(getByDomain.Result.Status).Equals(enum.TenantActive)
+}
+
+func TestTenantStorage_IsSubdomainAvailable_ExistingDomain(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ isAvailable := &query.IsSubdomainAvailable{Subdomain: "demo"}
+ err := bus.Dispatch(ctx, isAvailable)
+ Expect(err).IsNil()
+ Expect(isAvailable.Result).IsFalse()
+}
+
+func TestTenantStorage_IsSubdomainAvailable_NewDomain(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ isAvailable := &query.IsSubdomainAvailable{Subdomain: "thisisanewdomain"}
+ err := bus.Dispatch(ctx, isAvailable)
+ Expect(err).IsNil()
+ Expect(isAvailable.Result).IsTrue()
+}
+
+func TestTenantStorage_UpdateSettings(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ settings := &models.UpdateTenantSettings{
+ Logo: &models.ImageUpload{
+ BlobKey: "some-logo-key.png",
+ },
+ Title: "New Demonstration",
+ Invitation: "Leave us your suggestion",
+ WelcomeMessage: "Welcome!",
+ CNAME: "demo.company.com",
+ }
+ err := bus.Dispatch(demoTenantCtx, &cmd.UpdateTenantSettings{Settings: settings})
+ Expect(err).IsNil()
+
+ getByDomain := &query.GetTenantByDomain{Domain: "demo"}
+ err = bus.Dispatch(demoTenantCtx, getByDomain)
+ Expect(err).IsNil()
+ Expect(getByDomain.Result.ID).Equals(1)
+ Expect(getByDomain.Result.Name).Equals("New Demonstration")
+ Expect(getByDomain.Result.Invitation).Equals("Leave us your suggestion")
+ Expect(getByDomain.Result.WelcomeMessage).Equals("Welcome!")
+ Expect(getByDomain.Result.CNAME).Equals("demo.company.com")
+ Expect(getByDomain.Result.LogoBlobKey).Equals("some-logo-key.png")
+}
+
+func TestTenantStorage_AdvancedSettings(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ settings := &models.UpdateTenantAdvancedSettings{
+ CustomCSS: ".primary { color: red; }",
+ }
+ err := bus.Dispatch(demoTenantCtx, &cmd.UpdateTenantAdvancedSettings{Settings: settings})
+ Expect(err).IsNil()
+
+ getByDomain := &query.GetTenantByDomain{Domain: "demo"}
+ err = bus.Dispatch(demoTenantCtx, getByDomain)
+ Expect(err).IsNil()
+ Expect(getByDomain.Result.CustomCSS).Equals(".primary { color: red; }")
+}
+
+func TestTenantStorage_SaveFindSet_VerificationKey(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ //Save new Key
+ err := bus.Dispatch(demoTenantCtx, &cmd.SaveVerificationKey{
+ Key: "s3cr3tk3y",
+ Duration: 15 * time.Minute,
+ Request: &models.CreateTenant{
+ Email: "[email protected]",
+ Name: "Jon Snow",
+ },
+ })
+ Expect(err).IsNil()
+
+ //Find and check values
+ getKey := &query.GetVerificationByKey{Kind: enum.EmailVerificationKindSignUp, Key: "s3cr3tk3y"}
+
+ err = bus.Dispatch(demoTenantCtx, getKey)
+ Expect(err).IsNil()
+ Expect(getKey.Result.CreatedAt).TemporarilySimilar(time.Now(), 1*time.Second)
+ Expect(getKey.Result.VerifiedAt).IsNil()
+ Expect(getKey.Result.Email).Equals("[email protected]")
+ Expect(getKey.Result.Name).Equals("Jon Snow")
+ Expect(getKey.Result.Kind).Equals(enum.EmailVerificationKindSignUp)
+ Expect(getKey.Result.Key).Equals("s3cr3tk3y")
+ Expect(getKey.Result.UserID).Equals(0)
+ Expect(getKey.Result.ExpiresAt).TemporarilySimilar(getKey.Result.CreatedAt.Add(15*time.Minute), 1*time.Second)
+
+ //Set as verified check values
+ err = bus.Dispatch(demoTenantCtx, &cmd.SetKeyAsVerified{Key: "s3cr3tk3y"})
+ Expect(err).IsNil()
+
+ //Find and check that VerifiedAt is now set
+ err = bus.Dispatch(demoTenantCtx, getKey)
+
+ Expect(err).IsNil()
+ Expect(time.Now().After(getKey.Result.CreatedAt)).IsTrue()
+ Expect(getKey.Result.VerifiedAt.After(getKey.Result.CreatedAt)).IsTrue()
+ Expect(getKey.Result.Email).Equals("[email protected]")
+ Expect(getKey.Result.Name).Equals("Jon Snow")
+ Expect(getKey.Result.Key).Equals("s3cr3tk3y")
+ Expect(getKey.Result.UserID).Equals(0)
+ Expect(getKey.Result.ExpiresAt).TemporarilySimilar(getKey.Result.CreatedAt.Add(15*time.Minute), 1*time.Second)
+
+ //Wrong kind should not find it
+ getKeyWithWrongKind := &query.GetVerificationByKey{Kind: enum.EmailVerificationKindSignIn, Key: "s3cr3tk3y"}
+ err = bus.Dispatch(demoTenantCtx, getKeyWithWrongKind)
+
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(getKeyWithWrongKind.Result).IsNil()
+}
+
+func TestTenantStorage_SaveFindSet_ChangeEmailVerificationKey(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ //Save new Key
+ err := bus.Dispatch(demoTenantCtx, &cmd.SaveVerificationKey{
+ Key: "th3-s3cr3t",
+ Duration: 15 * time.Minute,
+ Request: &models.ChangeUserEmail{
+ Email: "[email protected]",
+ Requestor: jonSnow,
+ },
+ })
+ Expect(err).IsNil()
+
+ //Find and check values
+ getKey := &query.GetVerificationByKey{Kind: enum.EmailVerificationKindChangeEmail, Key: "th3-s3cr3t"}
+ err = bus.Dispatch(demoTenantCtx, getKey)
+ Expect(err).IsNil()
+ Expect(getKey.Result.CreatedAt).TemporarilySimilar(time.Now(), 1*time.Second)
+ Expect(getKey.Result.VerifiedAt).IsNil()
+ Expect(getKey.Result.Email).Equals("[email protected]")
+ Expect(getKey.Result.Name).Equals("")
+ Expect(getKey.Result.Kind).Equals(enum.EmailVerificationKindChangeEmail)
+ Expect(getKey.Result.Key).Equals("th3-s3cr3t")
+ Expect(getKey.Result.UserID).Equals(jonSnow.ID)
+ Expect(getKey.Result.ExpiresAt).TemporarilySimilar(getKey.Result.CreatedAt.Add(15*time.Minute), 1*time.Second)
+}
+
+func TestTenantStorage_FindUnknownVerificationKey(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ //Find and check values
+ getKey := &query.GetVerificationByKey{Kind: enum.EmailVerificationKindSignIn, Key: "blahblahblah"}
+ err := bus.Dispatch(demoTenantCtx, getKey)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(getKey.Result).IsNil()
+}
+
+func TestTenantStorage_Save_Get_ListOAuthConfig(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ getConfig := &query.GetCustomOAuthConfigByProvider{Provider: "_TEST"}
+ err := bus.Dispatch(demoTenantCtx, getConfig)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(getConfig.Result).IsNil()
+
+ err = bus.Dispatch(demoTenantCtx, &cmd.SaveCustomOAuthConfig{
+ Config: &models.CreateEditOAuthConfig{
+ Logo: &models.ImageUpload{
+ BlobKey: "uploads/my-logo-key.png",
+ },
+ Provider: "_TEST",
+ DisplayName: "My Provider",
+ ClientID: "823187ahjjfdha8fds7yfdashfjkdsa",
+ ClientSecret: "jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij",
+ AuthorizeURL: "http://provider/oauth/authorize",
+ TokenURL: "http://provider/oauth/token",
+ Scope: "profile email",
+ ProfileURL: "http://provider/profile/me",
+ JSONUserIDPath: "user.id",
+ JSONUserNamePath: "user.name",
+ JSONUserEmailPath: "user.email",
+ },
+ })
+ Expect(err).IsNil()
+
+ err = bus.Dispatch(demoTenantCtx, getConfig)
+ Expect(err).IsNil()
+ Expect(getConfig.Result.ID).Equals(1)
+ Expect(getConfig.Result.LogoBlobKey).Equals("uploads/my-logo-key.png")
+ Expect(getConfig.Result.Provider).Equals("_TEST")
+ Expect(getConfig.Result.DisplayName).Equals("My Provider")
+ Expect(getConfig.Result.ClientID).Equals("823187ahjjfdha8fds7yfdashfjkdsa")
+ Expect(getConfig.Result.ClientSecret).Equals("jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij")
+ Expect(getConfig.Result.AuthorizeURL).Equals("http://provider/oauth/authorize")
+ Expect(getConfig.Result.TokenURL).Equals("http://provider/oauth/token")
+ Expect(getConfig.Result.Scope).Equals("profile email")
+ Expect(getConfig.Result.Status).Equals(0)
+ Expect(getConfig.Result.ProfileURL).Equals("http://provider/profile/me")
+ Expect(getConfig.Result.JSONUserIDPath).Equals("user.id")
+ Expect(getConfig.Result.JSONUserNamePath).Equals("user.name")
+ Expect(getConfig.Result.JSONUserEmailPath).Equals("user.email")
+
+ err = bus.Dispatch(demoTenantCtx, &cmd.SaveCustomOAuthConfig{
+ Config: &models.CreateEditOAuthConfig{
+ ID: getConfig.Result.ID,
+ Logo: &models.ImageUpload{
+ BlobKey: "",
+ },
+ Provider: "_TEST2222", //this has to be ignored
+ DisplayName: "New My Provider",
+ ClientID: "New 823187ahjjfdha8fds7yfdashfjkdsa",
+ ClientSecret: "New jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij",
+ AuthorizeURL: "New http://provider/oauth/authorize",
+ TokenURL: "New http://provider/oauth/token",
+ Scope: "New profile email",
+ ProfileURL: "New http://provider/profile/me",
+ JSONUserIDPath: "New user.id",
+ JSONUserNamePath: "New user.name",
+ JSONUserEmailPath: "New user.email",
+ },
+ })
+ Expect(err).IsNil()
+
+ customConfigs := &query.ListCustomOAuthConfig{}
+ err = bus.Dispatch(demoTenantCtx, customConfigs)
+ Expect(err).IsNil()
+
+ Expect(customConfigs.Result).HasLen(1)
+ Expect(customConfigs.Result[0].ID).Equals(1)
+ Expect(customConfigs.Result[0].LogoBlobKey).Equals("")
+ Expect(customConfigs.Result[0].Provider).Equals("_TEST")
+ Expect(customConfigs.Result[0].DisplayName).Equals("New My Provider")
+ Expect(customConfigs.Result[0].ClientID).Equals("New 823187ahjjfdha8fds7yfdashfjkdsa")
+ Expect(customConfigs.Result[0].ClientSecret).Equals("New jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij")
+ Expect(customConfigs.Result[0].AuthorizeURL).Equals("New http://provider/oauth/authorize")
+ Expect(customConfigs.Result[0].TokenURL).Equals("New http://provider/oauth/token")
+ Expect(customConfigs.Result[0].Scope).Equals("New profile email")
+ Expect(customConfigs.Result[0].Status).Equals(0)
+ Expect(customConfigs.Result[0].ProfileURL).Equals("New http://provider/profile/me")
+ Expect(customConfigs.Result[0].JSONUserIDPath).Equals("New user.id")
+ Expect(customConfigs.Result[0].JSONUserNamePath).Equals("New user.name")
+ Expect(customConfigs.Result[0].JSONUserEmailPath).Equals("New user.email")
+}
diff --git a/app/services/sqlstore/postgres/user.go b/app/services/sqlstore/postgres/user.go
new file mode 100644
index 000000000..f2e1efdc0
--- /dev/null
+++ b/app/services/sqlstore/postgres/user.go
@@ -0,0 +1,399 @@
+package postgres
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+type dbUser struct {
+ ID sql.NullInt64 `db:"id"`
+ Name sql.NullString `db:"name"`
+ Email sql.NullString `db:"email"`
+ Tenant *dbTenant `db:"tenant"`
+ Role sql.NullInt64 `db:"role"`
+ Status sql.NullInt64 `db:"status"`
+ AvatarType sql.NullInt64 `db:"avatar_type"`
+ AvatarBlobKey sql.NullString `db:"avatar_bkey"`
+ Providers []*dbUserProvider
+}
+
+type dbUserProvider struct {
+ Name sql.NullString `db:"provider"`
+ UID sql.NullString `db:"provider_uid"`
+}
+
+func (u *dbUser) toModel(ctx context.Context) *models.User {
+ if u == nil {
+ return nil
+ }
+
+ avatarType := enum.AvatarType(u.AvatarType.Int64)
+ user := &models.User{
+ ID: int(u.ID.Int64),
+ Name: u.Name.String,
+ Email: u.Email.String,
+ Tenant: u.Tenant.toModel(),
+ Role: enum.Role(u.Role.Int64),
+ Providers: make([]*models.UserProvider, len(u.Providers)),
+ Status: enum.UserStatus(u.Status.Int64),
+ AvatarType: avatarType,
+ AvatarBlobKey: u.AvatarBlobKey.String,
+ AvatarURL: buildAvatarURL(ctx, avatarType, int(u.ID.Int64), u.Name.String, u.AvatarBlobKey.String),
+ }
+
+ for i, p := range u.Providers {
+ user.Providers[i] = &models.UserProvider{
+ Name: p.Name.String,
+ UID: p.UID.String,
+ }
+ }
+
+ return user
+}
+
+type dbUserSetting struct {
+ Key string `db:"key"`
+ Value string `db:"value"`
+}
+
+func countUsers(ctx context.Context, q *query.CountUsers) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ var count int
+ err := trx.Scalar(&count, "SELECT COUNT(*) FROM users WHERE tenant_id = $1", tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to count users")
+ }
+ q.Result = count
+ return nil
+ })
+}
+
+func blockUser(ctx context.Context, c *cmd.BlockUser) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if _, err := trx.Execute(
+ "UPDATE users SET status = $3 WHERE id = $1 AND tenant_id = $2",
+ c.UserID, tenant.ID, enum.UserBlocked,
+ ); err != nil {
+ return errors.Wrap(err, "failed to block user")
+ }
+ return nil
+ })
+}
+
+func unblockUser(ctx context.Context, c *cmd.UnblockUser) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if _, err := trx.Execute(
+ "UPDATE users SET status = $3 WHERE id = $1 AND tenant_id = $2",
+ c.UserID, tenant.ID, enum.UserActive,
+ ); err != nil {
+ return errors.Wrap(err, "failed to unblock user")
+ }
+ return nil
+ })
+}
+
+func deleteCurrentUser(ctx context.Context, c *cmd.DeleteCurrentUser) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if _, err := trx.Execute(
+ "UPDATE users SET role = $3, status = $4, name = '', email = '', api_key = null, api_key_date = null WHERE id = $1 AND tenant_id = $2",
+ user.ID, tenant.ID, enum.RoleVisitor, enum.UserDeleted,
+ ); err != nil {
+ return errors.Wrap(err, "failed to delete current user")
+ }
+
+ var tables = []struct {
+ name string
+ userColumn string
+ }{
+ {"user_providers", "user_id"},
+ {"user_settings", "user_id"},
+ {"notifications", "user_id"},
+ {"notifications", "author_id"},
+ {"post_votes", "user_id"},
+ {"post_subscribers", "user_id"},
+ {"email_verifications", "user_id"},
+ }
+
+ for _, table := range tables {
+ if _, err := trx.Execute(
+ fmt.Sprintf("DELETE FROM %s WHERE %s = $1 AND tenant_id = $2", table.name, table.userColumn),
+ user.ID, tenant.ID,
+ ); err != nil {
+ return errors.Wrap(err, "failed to delete current user's %s records", table)
+ }
+ }
+
+ return nil
+ })
+}
+
+func regenerateAPIKey(ctx context.Context, c *cmd.RegenerateAPIKey) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ apiKey := models.GenerateSecretKey()
+
+ if _, err := trx.Execute(
+ "UPDATE users SET api_key = $3, api_key_date = $4 WHERE id = $1 AND tenant_id = $2",
+ user.ID, tenant.ID, apiKey, time.Now(),
+ ); err != nil {
+ return errors.Wrap(err, "failed to update current user's API Key")
+ }
+
+ c.Result = apiKey
+ return nil
+ })
+}
+
+func getUserByAPIKey(ctx context.Context, q *query.GetUserByAPIKey) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ result, err := queryUser(ctx, trx, "api_key = $1 AND tenant_id = $2", q.APIKey, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to get user with API Key '%s'", q.APIKey)
+ }
+ q.Result = result
+ return nil
+ })
+}
+
+func userSubscribedTo(ctx context.Context, q *query.UserSubscribedTo) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if user == nil {
+ q.Result = false
+ return nil
+ }
+
+ var status int
+ err := trx.Scalar(&status, "SELECT status FROM post_subscribers WHERE user_id = $1 AND post_id = $2", user.ID, q.PostID)
+ if err != nil && errors.Cause(err) != app.ErrNotFound {
+ return errors.Wrap(err, "failed to get subscription status")
+ }
+
+ if errors.Cause(err) == app.ErrNotFound {
+ for _, e := range enum.AllNotificationEvents {
+ for _, r := range e.RequiresSubscriptionUserRoles {
+ if r == user.Role {
+ q.Result = false
+ return nil
+ }
+ }
+ }
+ q.Result = true
+ return nil
+ }
+
+ if status == 1 {
+ q.Result = true
+ return nil
+ }
+
+ q.Result = false
+ return nil
+ })
+}
+
+func changeUserRole(ctx context.Context, c *cmd.ChangeUserRole) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ cmd := "UPDATE users SET role = $3 WHERE id = $1 AND tenant_id = $2"
+ _, err := trx.Execute(cmd, c.UserID, tenant.ID, c.Role)
+ if err != nil {
+ return errors.Wrap(err, "failed to change user's role")
+ }
+ return nil
+ })
+}
+
+func changeUserEmail(ctx context.Context, c *cmd.ChangeUserEmail) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ cmd := "UPDATE users SET email = $3 WHERE id = $1 AND tenant_id = $2"
+ _, err := trx.Execute(cmd, c.UserID, tenant.ID, strings.ToLower(c.Email))
+ if err != nil {
+ return errors.Wrap(err, "failed to update user's email")
+ }
+ return nil
+ })
+}
+
+func updateCurrentUserSettings(ctx context.Context, c *cmd.UpdateCurrentUserSettings) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if user != nil && c.Settings != nil && len(c.Settings) > 0 {
+ query := `
+ INSERT INTO user_settings (tenant_id, user_id, key, value)
+ VALUES ($1, $2, $3, $4) ON CONFLICT (user_id, key) DO UPDATE SET value = $4
+ `
+
+ for key, value := range c.Settings {
+ _, err := trx.Execute(query, tenant.ID, user.ID, key, value)
+ if err != nil {
+ return errors.Wrap(err, "failed to update user settings")
+ }
+ }
+ }
+
+ return nil
+ })
+}
+
+func getCurrentUserSettings(ctx context.Context, q *query.GetCurrentUserSettings) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ q.Result = make(map[string]string)
+
+ var settings []*dbUserSetting
+ err := trx.Select(&settings, "SELECT key, value FROM user_settings WHERE user_id = $1 AND tenant_id = $2", user.ID, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to get user settings")
+ }
+
+ for _, e := range enum.AllNotificationEvents {
+ for _, r := range e.DefaultEnabledUserRoles {
+ if r == user.Role {
+ q.Result[e.UserSettingsKeyName] = e.DefaultSettingValue
+ }
+ }
+ }
+
+ for _, s := range settings {
+ q.Result[s.Key] = s.Value
+ }
+
+ return nil
+ })
+}
+
+func registerUser(ctx context.Context, c *cmd.RegisterUser) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, _ *models.User) error {
+ now := time.Now()
+ c.User.Status = enum.UserActive
+ c.User.Email = strings.ToLower(strings.TrimSpace(c.User.Email))
+ if err := trx.Get(&c.User.ID,
+ "INSERT INTO users (name, email, created_at, tenant_id, role, status, avatar_type, avatar_bkey) VALUES ($1, $2, $3, $4, $5, $6, $7, '') RETURNING id",
+ c.User.Name, c.User.Email, now, tenant.ID, c.User.Role, enum.UserActive, enum.AvatarTypeGravatar); err != nil {
+ return errors.Wrap(err, "failed to register new user")
+ }
+
+ for _, provider := range c.User.Providers {
+ cmd := "INSERT INTO user_providers (tenant_id, user_id, provider, provider_uid, created_at) VALUES ($1, $2, $3, $4, $5)"
+ if _, err := trx.Execute(cmd, tenant.ID, c.User.ID, provider.Name, provider.UID, now); err != nil {
+ return errors.Wrap(err, "failed to add provider to new user")
+ }
+ }
+
+ return nil
+ })
+}
+
+func registerUserProvider(ctx context.Context, c *cmd.RegisterUserProvider) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ cmd := "INSERT INTO user_providers (tenant_id, user_id, provider, provider_uid, created_at) VALUES ($1, $2, $3, $4, $5)"
+ _, err := trx.Execute(cmd, tenant.ID, c.UserID, c.ProviderName, c.ProviderUID, time.Now())
+ if err != nil {
+ return errors.Wrap(err, "failed to add provider '%s:%s' to user with id '%d'", c.ProviderName, c.ProviderUID, c.UserID)
+ }
+ return nil
+ })
+}
+
+func updateCurrentUser(ctx context.Context, c *cmd.UpdateCurrentUser) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if c.Avatar.Remove {
+ c.Avatar.BlobKey = ""
+ }
+ cmd := "UPDATE users SET name = $3, avatar_type = $4, avatar_bkey = $5 WHERE id = $1 AND tenant_id = $2"
+ _, err := trx.Execute(cmd, user.ID, tenant.ID, c.Name, c.AvatarType, c.Avatar.BlobKey)
+ if err != nil {
+ return errors.Wrap(err, "failed to update user")
+ }
+ return nil
+ })
+}
+
+func getUserByID(ctx context.Context, q *query.GetUserByID) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ user, err := queryUser(ctx, trx, "id = $1", q.UserID)
+ if err != nil {
+ return errors.Wrap(err, "failed to get user with id '%d'", q.UserID)
+ }
+ q.Result = user
+ return nil
+ })
+}
+
+func getUserByEmail(ctx context.Context, q *query.GetUserByEmail) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ email := strings.ToLower(q.Email)
+ user, err := queryUser(ctx, trx, "email = $1 AND tenant_id = $2", email, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to get user with email '%s'", email)
+ }
+ q.Result = user
+ return nil
+ })
+}
+
+func getUserByProvider(ctx context.Context, q *query.GetUserByProvider) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ var userID int
+ if err := trx.Scalar(&userID, `
+ SELECT user_id
+ FROM user_providers up
+ INNER JOIN users u
+ ON u.id = up.user_id
+ AND u.tenant_id = up.tenant_id
+ WHERE up.provider = $1
+ AND up.provider_uid = $2
+ AND u.tenant_id = $3`, q.Provider, q.UID, tenant.ID); err != nil {
+ return errors.Wrap(err, "failed to get user by provider '%s' and uid '%s'", q.Provider, q.UID)
+ }
+
+ byID := &query.GetUserByID{UserID: userID}
+ err := getUserByID(ctx, byID)
+ q.Result = byID.Result
+ return err
+ })
+}
+
+func getAllUsers(ctx context.Context, q *query.GetAllUsers) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ var users []*dbUser
+ err := trx.Select(&users, `
+ SELECT id, name, email, tenant_id, role, status, avatar_type, avatar_bkey
+ FROM users
+ WHERE tenant_id = $1
+ AND status != $2
+ ORDER BY id`, tenant.ID, enum.UserDeleted)
+ if err != nil {
+ return errors.Wrap(err, "failed to get all users")
+ }
+
+ q.Result = make([]*models.User, len(users))
+ for i, user := range users {
+ q.Result[i] = user.toModel(ctx)
+ }
+ return nil
+ })
+}
+
+func queryUser(ctx context.Context, trx *dbx.Trx, filter string, args ...interface{}) (*models.User, error) {
+ user := dbUser{}
+ sql := fmt.Sprintf("SELECT id, name, email, tenant_id, role, status, avatar_type, avatar_bkey FROM users WHERE status != %d AND ", enum.UserDeleted)
+ err := trx.Get(&user, sql+filter, args...)
+ if err != nil {
+ return nil, err
+ }
+
+ err = trx.Select(&user.Providers, "SELECT provider_uid, provider FROM user_providers WHERE user_id = $1", user.ID.Int64)
+ if err != nil {
+ return nil, err
+ }
+
+ return user.toModel(ctx), nil
+}
diff --git a/app/services/sqlstore/postgres/user_test.go b/app/services/sqlstore/postgres/user_test.go
new file mode 100644
index 000000000..93932a66d
--- /dev/null
+++ b/app/services/sqlstore/postgres/user_test.go
@@ -0,0 +1,422 @@
+package postgres_test
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/pkg/bus"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models"
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+func TestUserStorage_GetByID(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ userByID := &query.GetUserByID{UserID: 1}
+ err := bus.Dispatch(ctx, userByID)
+ Expect(err).IsNil()
+ Expect(userByID.Result.ID).Equals(int(1))
+ Expect(userByID.Result.Tenant.ID).Equals(1)
+ Expect(userByID.Result.Name).Equals("Jon Snow")
+ Expect(userByID.Result.Email).Equals("[email protected]")
+ Expect(userByID.Result.AvatarURL).Equals("http://cdn.test.fider.io/avatars/gravatar/1/Jon%20Snow")
+ Expect(userByID.Result.Providers).HasLen(1)
+ Expect(userByID.Result.Providers[0].UID).Equals("FB1234")
+ Expect(userByID.Result.Providers[0].Name).Equals("facebook")
+}
+
+func TestUserStorage_GetByEmail_Error(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ userByEmail := &query.GetUserByEmail{Email: "[email protected]"}
+ err := bus.Dispatch(demoTenantCtx, userByEmail)
+ Expect(err).IsNotNil()
+ Expect(userByEmail.Result).IsNil()
+}
+
+func TestUserStorage_GetByEmail(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ userByEmail := &query.GetUserByEmail{Email: "[email protected]"}
+ userByUpperCaseEmail := &query.GetUserByEmail{Email: "[email protected]"}
+ err := bus.Dispatch(demoTenantCtx, userByEmail, userByUpperCaseEmail)
+ Expect(err).IsNil()
+
+ Expect(userByEmail.Result.ID).Equals(int(1))
+ Expect(userByEmail.Result.Tenant.ID).Equals(1)
+ Expect(userByEmail.Result.Name).Equals("Jon Snow")
+ Expect(userByEmail.Result.Email).Equals("[email protected]")
+ Expect(userByEmail.Result.Providers).HasLen(1)
+ Expect(userByEmail.Result.Providers[0].UID).Equals("FB1234")
+ Expect(userByEmail.Result.Providers[0].Name).Equals("facebook")
+
+ Expect(userByUpperCaseEmail.Result.ID).Equals(int(1))
+}
+
+func TestUserStorage_GetByProvider(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ getUser := &query.GetUserByProvider{Provider: "facebook", UID: "FB1234"}
+ err := bus.Dispatch(demoTenantCtx, getUser)
+ Expect(err).IsNil()
+
+ Expect(getUser.Result.ID).Equals(int(1))
+ Expect(getUser.Result.Tenant.ID).Equals(1)
+ Expect(getUser.Result.Name).Equals("Jon Snow")
+ Expect(getUser.Result.Email).Equals("[email protected]")
+ Expect(getUser.Result.Providers).HasLen(1)
+ Expect(getUser.Result.Providers[0].UID).Equals("FB1234")
+ Expect(getUser.Result.Providers[0].Name).Equals("facebook")
+}
+
+func TestUserStorage_GetByProvider_WrongTenant(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ getUser := &query.GetUserByProvider{Provider: "facebook", UID: "FB1234"}
+ err := bus.Dispatch(avengersTenantCtx, getUser)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(getUser.Result).IsNil()
+}
+
+func TestUserStorage_GetByEmail_WrongTenant(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ getUser := &query.GetUserByEmail{Email: "[email protected]"}
+ err := bus.Dispatch(avengersTenantCtx, getUser)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(getUser.Result).IsNil()
+}
+
+func TestUserStorage_Register(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ user := &models.User{
+ Name: "Rob Stark",
+ Email: "[email protected]",
+ Role: enum.RoleCollaborator,
+ Providers: []*models.UserProvider{
+ {
+ UID: "123123123",
+ Name: app.FacebookProvider,
+ },
+ },
+ }
+ err := bus.Dispatch(demoTenantCtx, &cmd.RegisterUser{User: user})
+ Expect(err).IsNil()
+
+ getUser := &query.GetUserByEmail{Email: "[email protected]"}
+ err = bus.Dispatch(demoTenantCtx, getUser)
+ Expect(err).IsNil()
+
+ Expect(getUser.Result.ID).Equals(int(6))
+ Expect(getUser.Result.Role).Equals(enum.RoleCollaborator)
+ Expect(getUser.Result.Name).Equals("Rob Stark")
+ Expect(getUser.Result.Email).Equals("[email protected]")
+ Expect(getUser.Result.Status).Equals(enum.UserActive)
+}
+
+func TestUserStorage_Register_WhiteSpaceEmail(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ user := &models.User{
+ Name: "Rob Stark",
+ Email: " ",
+ Role: enum.RoleCollaborator,
+ }
+ err := bus.Dispatch(demoTenantCtx, &cmd.RegisterUser{User: user})
+ Expect(err).IsNil()
+
+ getUser := &query.GetUserByID{UserID: user.ID}
+ err = bus.Dispatch(demoTenantCtx, getUser)
+ Expect(err).IsNil()
+
+ Expect(getUser.Result.Role).Equals(enum.RoleCollaborator)
+ Expect(getUser.Result.Name).Equals("Rob Stark")
+ Expect(getUser.Result.Email).Equals("")
+ Expect(getUser.Result.Status).Equals(enum.UserActive)
+}
+
+func TestUserStorage_Register_MultipleProviders(t *testing.T) {
+ ctx := SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ var tenantID int
+ trx.Get(&tenantID, `
+ INSERT INTO tenants (name, subdomain, created_at, status, is_private, custom_css, logo_bkey)
+ VALUES ('My Domain Inc.','mydomain', now(), 1, false, '', '')
+ RETURNING id
+ `)
+
+ newTenantCtx := context.WithValue(ctx, app.TenantCtxKey, &models.Tenant{ID: tenantID})
+
+ user := &models.User{
+ Name: "Jon Snow",
+ Email: "[email protected]",
+ Role: enum.RoleCollaborator,
+ Providers: []*models.UserProvider{
+ {
+ UID: "123123123",
+ Name: app.FacebookProvider,
+ },
+ {
+ UID: "456456456",
+ Name: app.GoogleProvider,
+ },
+ },
+ }
+
+ err := bus.Dispatch(newTenantCtx, &cmd.RegisterUser{User: user})
+ Expect(err).IsNil()
+ Expect(user.ID).NotEquals(0)
+ Expect(user.Name).Equals("Jon Snow")
+ Expect(user.Email).Equals("[email protected]")
+ Expect(user.Status).Equals(enum.UserActive)
+}
+
+func TestUserStorage_RegisterProvider(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ err := bus.Dispatch(demoTenantCtx, &cmd.RegisterUserProvider{
+ UserID: 1,
+ ProviderName: "google",
+ ProviderUID: "GO1234",
+ })
+ Expect(err).IsNil()
+
+ getUser := &query.GetUserByID{UserID: 1}
+ err = bus.Dispatch(demoTenantCtx, getUser)
+ Expect(err).IsNil()
+
+ Expect(getUser.Result.ID).Equals(int(1))
+ Expect(getUser.Result.Name).Equals("Jon Snow")
+ Expect(getUser.Result.Email).Equals("[email protected]")
+ Expect(getUser.Result.Tenant.ID).Equals(1)
+ Expect(getUser.Result.Status).Equals(enum.UserActive)
+
+ Expect(getUser.Result.Providers).HasLen(2)
+ Expect(getUser.Result.Providers[0].UID).Equals("FB1234")
+ Expect(getUser.Result.Providers[0].Name).Equals("facebook")
+ Expect(getUser.Result.Providers[1].UID).Equals("GO1234")
+ Expect(getUser.Result.Providers[1].Name).Equals("google")
+}
+
+func TestUserStorage_UpdateSettings(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ err := bus.Dispatch(jonSnowCtx, &cmd.UpdateCurrentUser{
+ Name: "Jon Stark",
+ Avatar: &models.ImageUpload{
+ BlobKey: "jon.png",
+ },
+ })
+ Expect(err).IsNil()
+
+ getUser := &query.GetUserByEmail{Email: "[email protected]"}
+ err = bus.Dispatch(jonSnowCtx, getUser)
+ Expect(err).IsNil()
+ Expect(getUser.Result.Name).Equals("Jon Stark")
+ Expect(getUser.Result.AvatarBlobKey).Equals("jon.png")
+}
+
+func TestUserStorage_ChangeRole(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ err := bus.Dispatch(demoTenantCtx, &cmd.ChangeUserRole{
+ UserID: jonSnow.ID,
+ Role: enum.RoleVisitor,
+ })
+ Expect(err).IsNil()
+
+ getUser := &query.GetUserByEmail{Email: "[email protected]"}
+ err = bus.Dispatch(demoTenantCtx, getUser)
+ Expect(err).IsNil()
+ Expect(getUser.Result.Role).Equals(enum.RoleVisitor)
+}
+
+func TestUserStorage_ChangeEmail(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ err := bus.Dispatch(demoTenantCtx, &cmd.ChangeUserEmail{
+ UserID: jonSnow.ID,
+ Email: "[email protected]",
+ })
+ Expect(err).IsNil()
+
+ getByNewEmail := &query.GetUserByEmail{Email: "[email protected]"}
+ err = bus.Dispatch(demoTenantCtx, getByNewEmail)
+ Expect(err).IsNil()
+ Expect(getByNewEmail.Result.Email).Equals("[email protected]")
+
+ getByOldEmail := &query.GetUserByEmail{Email: "[email protected]"}
+ err = bus.Dispatch(demoTenantCtx, getByOldEmail)
+ Expect(getByOldEmail.Result).IsNil()
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+}
+
+func TestUserStorage_GetAll(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ allUsers := &query.GetAllUsers{}
+ err := bus.Dispatch(demoTenantCtx, allUsers)
+ Expect(err).IsNil()
+
+ Expect(allUsers.Result).HasLen(3)
+ Expect(allUsers.Result[0].Name).Equals("Jon Snow")
+ Expect(allUsers.Result[0].Status).Equals(enum.UserActive)
+ Expect(allUsers.Result[1].Name).Equals("Arya Stark")
+ Expect(allUsers.Result[1].Status).Equals(enum.UserActive)
+ Expect(allUsers.Result[2].Name).Equals("Sansa Stark")
+ Expect(allUsers.Result[2].Status).Equals(enum.UserActive)
+}
+
+func TestUserStorage_DefaultUserSettings(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ getSettings := &query.GetCurrentUserSettings{}
+
+ err := bus.Dispatch(jonSnowCtx, getSettings)
+ Expect(err).IsNil()
+
+ Expect(getSettings.Result).Equals(map[string]string{
+ enum.NotificationEventNewPost.UserSettingsKeyName: enum.NotificationEventNewPost.DefaultSettingValue,
+ enum.NotificationEventNewComment.UserSettingsKeyName: enum.NotificationEventNewComment.DefaultSettingValue,
+ enum.NotificationEventChangeStatus.UserSettingsKeyName: enum.NotificationEventChangeStatus.DefaultSettingValue,
+ })
+
+ err = bus.Dispatch(aryaStarkCtx, getSettings)
+ Expect(err).IsNil()
+ Expect(getSettings.Result).Equals(map[string]string{
+ enum.NotificationEventNewComment.UserSettingsKeyName: enum.NotificationEventNewComment.DefaultSettingValue,
+ enum.NotificationEventChangeStatus.UserSettingsKeyName: enum.NotificationEventChangeStatus.DefaultSettingValue,
+ })
+}
+
+func TestUserStorage_SaveGetUserSettings(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ disableAll := map[string]string{
+ enum.NotificationEventNewPost.UserSettingsKeyName: "0",
+ enum.NotificationEventChangeStatus.UserSettingsKeyName: "0",
+ }
+
+ err := bus.Dispatch(aryaStarkCtx, &cmd.UpdateCurrentUserSettings{Settings: disableAll})
+ Expect(err).IsNil()
+
+ firstSettings := &query.GetCurrentUserSettings{}
+ err = bus.Dispatch(aryaStarkCtx, firstSettings)
+ Expect(err).IsNil()
+
+ Expect(firstSettings.Result).Equals(map[string]string{
+ enum.NotificationEventNewPost.UserSettingsKeyName: "0",
+ enum.NotificationEventNewComment.UserSettingsKeyName: enum.NotificationEventNewComment.DefaultSettingValue,
+ enum.NotificationEventChangeStatus.UserSettingsKeyName: "0",
+ })
+
+ err = bus.Dispatch(aryaStarkCtx, &cmd.UpdateCurrentUserSettings{Settings: nil})
+ Expect(err).IsNil()
+
+ secondSettings := &query.GetCurrentUserSettings{}
+ err = bus.Dispatch(aryaStarkCtx, secondSettings)
+ Expect(err).IsNil()
+
+ Expect(secondSettings.Result).Equals(firstSettings.Result)
+}
+
+func TestUserStorage_Delete(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ err := bus.Dispatch(jonSnowCtx, &cmd.DeleteCurrentUser{})
+ Expect(err).IsNil()
+
+ getByEmail := &query.GetUserByEmail{Email: "[email protected]"}
+ err = bus.Dispatch(jonSnowCtx, getByEmail)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(getByEmail.Result).IsNil()
+
+ getByID := &query.GetUserByID{UserID: jonSnow.ID}
+ err = bus.Dispatch(jonSnowCtx, getByID)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(getByID.Result).IsNil()
+}
+
+func TestUserStorage_APIKey(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ regenerateAPIKey := &cmd.RegenerateAPIKey{}
+ err := bus.Dispatch(jonSnowCtx, regenerateAPIKey)
+ Expect(err).IsNil()
+ Expect(regenerateAPIKey.Result).HasLen(64)
+
+ firstKey := regenerateAPIKey.Result
+
+ getByKey := &query.GetUserByAPIKey{APIKey: firstKey}
+ err = bus.Dispatch(jonSnowCtx, getByKey)
+ Expect(getByKey.Result).Equals(jonSnow)
+ Expect(err).IsNil()
+
+ //try to get by uppercase key
+ getByKey = &query.GetUserByAPIKey{APIKey: strings.ToUpper(firstKey)}
+ err = bus.Dispatch(jonSnowCtx, getByKey)
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+ Expect(getByKey.Result).IsNil()
+
+ //regenerate and try to get again using old key
+ err = bus.Dispatch(jonSnowCtx, regenerateAPIKey)
+ Expect(err).IsNil()
+
+ getByKey = &query.GetUserByAPIKey{APIKey: firstKey}
+ err = bus.Dispatch(jonSnowCtx, getByKey)
+ Expect(getByKey.Result).IsNil()
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+
+ //try to get by some unknown key
+ getByKey = &query.GetUserByAPIKey{APIKey: "SOME-INVALID-KEY"}
+ err = bus.Dispatch(jonSnowCtx, getByKey)
+ Expect(getByKey.Result).IsNil()
+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)
+}
+
+func TestUserStorage_BlockUser(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ userID := 1
+ getUser := &query.GetUserByID{UserID: userID}
+
+ err := bus.Dispatch(demoTenantCtx, getUser)
+ Expect(err).IsNil()
+ Expect(getUser.Result.Status).Equals(enum.UserActive)
+
+ err = bus.Dispatch(demoTenantCtx, &cmd.BlockUser{UserID: userID}, getUser)
+ Expect(err).IsNil()
+ Expect(getUser.Result.Status).Equals(enum.UserBlocked)
+
+ err = bus.Dispatch(demoTenantCtx, &cmd.UnblockUser{UserID: userID}, getUser)
+ Expect(err).IsNil()
+ Expect(getUser.Result.Status).Equals(enum.UserActive)
+}
diff --git a/app/services/sqlstore/postgres/vote.go b/app/services/sqlstore/postgres/vote.go
new file mode 100644
index 000000000..33ab70911
--- /dev/null
+++ b/app/services/sqlstore/postgres/vote.go
@@ -0,0 +1,110 @@
+package postgres
+
+import (
+ "context"
+ "strconv"
+ "time"
+
+ "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
+)
+
+type dbVote struct {
+ User *struct {
+ ID int `db:"id"`
+ Name string `db:"name"`
+ Email string `db:"email"`
+ AvatarType int64 `db:"avatar_type"`
+ AvatarBlobKey string `db:"avatar_bkey"`
+ } `db:"user"`
+ CreatedAt time.Time `db:"created_at"`
+}
+
+func (v *dbVote) toModel(ctx context.Context) *models.Vote {
+ vote := &models.Vote{
+ CreatedAt: v.CreatedAt,
+ User: &models.VoteUser{
+ ID: v.User.ID,
+ Name: v.User.Name,
+ Email: v.User.Email,
+ AvatarURL: buildAvatarURL(ctx, enum.AvatarType(v.User.AvatarType), v.User.ID, v.User.Name, v.User.AvatarBlobKey),
+ },
+ }
+ return vote
+}
+
+func addVote(ctx context.Context, c *cmd.AddVote) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if !c.Post.CanBeVoted() {
+ return nil
+ }
+
+ _, err := trx.Execute(
+ `INSERT INTO post_votes (tenant_id, user_id, post_id, created_at) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING`,
+ tenant.ID, c.User.ID, c.Post.ID, time.Now(),
+ )
+
+ if err != nil {
+ return errors.Wrap(err, "failed add vote to post")
+ }
+
+ return internalAddSubscriber(trx, c.Post, tenant, c.User, false)
+ })
+}
+
+func removeVote(ctx context.Context, c *cmd.RemoveVote) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ if !c.Post.CanBeVoted() {
+ return nil
+ }
+
+ _, err := trx.Execute(`DELETE FROM post_votes WHERE user_id = $1 AND post_id = $2 AND tenant_id = $3`, c.User.ID, c.Post.ID, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to remove vote from post")
+ }
+
+ return err
+ })
+}
+
+func listPostVotes(ctx context.Context, q *query.ListPostVotes) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ q.Result = make([]*models.Vote, 0)
+ sqlLimit := "ALL"
+ if q.Limit > 0 {
+ sqlLimit = strconv.Itoa(q.Limit)
+ }
+
+ votes := []*dbVote{}
+ err := trx.Select(&votes, `
+ SELECT
+ pv.created_at,
+ u.id AS user_id,
+ u.name AS user_name,
+ u.email AS user_email,
+ u.avatar_type AS user_avatar_type,
+ u.avatar_bkey AS user_avatar_bkey
+ FROM post_votes pv
+ INNER JOIN users u
+ ON u.id = pv.user_id
+ AND u.tenant_id = pv.tenant_id
+ WHERE pv.post_id = $1
+ AND pv.tenant_id = $2
+ ORDER BY pv.created_at
+ LIMIT `+sqlLimit, q.PostID, tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to get votes of post")
+ }
+
+ q.Result = make([]*models.Vote, len(votes))
+ for i, vote := range votes {
+ q.Result[i] = vote.toModel(ctx)
+ }
+
+ return nil
+ })
+}
diff --git a/app/storage/inmemory/event.go b/app/storage/inmemory/event.go
deleted file mode 100644
index 761d3e2b3..000000000
--- a/app/storage/inmemory/event.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package inmemory
-
-import (
- "time"
-
- "github.com/getfider/fider/app/models"
-)
-
-// EventStorage contains read and write operations for Audit Events
-type EventStorage struct {
- lastID int
- user *models.User
- tenant *models.Tenant
- events map[int]*models.Event
-}
-
-// NewEventStorage creates a new inmemory EventStorage
-func NewEventStorage() *EventStorage {
- return &EventStorage{}
-}
-
-// SetCurrentTenant to current context
-func (e *EventStorage) SetCurrentTenant(tenant *models.Tenant) {
- e.tenant = tenant
-}
-
-// SetCurrentUser to current context
-func (e *EventStorage) SetCurrentUser(user *models.User) {
- e.user = user
-}
-
-// Add stores a new event
-func (e *EventStorage) Add(clientIP, name string) (*models.Event, error) {
- e.lastID++
- event := &models.Event{
- ID: e.lastID,
- ClientIP: clientIP,
- Name: name,
- CreatedAt: time.Now(),
- }
- e.events[event.ID] = event
-
- return event, nil
-}
-
-// GetByID returns the event with the specified id
-func (e *EventStorage) GetByID(id int) (*models.Event, error) {
- event := e.events[id]
- return event, nil
-}
diff --git a/app/storage/inmemory/notifications.go b/app/storage/inmemory/notifications.go
deleted file mode 100644
index dcaecdc91..000000000
--- a/app/storage/inmemory/notifications.go
+++ /dev/null
@@ -1,114 +0,0 @@
-package inmemory
-
-import (
- "time"
-
- "github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
-)
-
-// NotificationStorage contains read and write operations for notifications
-type NotificationStorage struct {
- lastID int
- tenant *models.Tenant
- user *models.User
- notifications map[*models.User][]*models.Notification
-}
-
-// NewNotificationStorage creates a new NotificationStorage
-func NewNotificationStorage() *NotificationStorage {
- return &NotificationStorage{
- lastID: 0,
- notifications: make(map[*models.User][]*models.Notification, 0),
- }
-}
-
-// SetCurrentTenant to current context
-func (s *NotificationStorage) SetCurrentTenant(tenant *models.Tenant) {
- s.tenant = tenant
-}
-
-// SetCurrentUser to current context
-func (s *NotificationStorage) SetCurrentUser(user *models.User) {
- s.user = user
-}
-
-// Insert notification for given user
-func (s *NotificationStorage) Insert(user *models.User, title, link string, postID int) (*models.Notification, error) {
- s.lastID = s.lastID + 1
- newNotification := &models.Notification{
- ID: s.lastID,
- Title: title,
- Link: link,
- Read: false,
- CreatedAt: time.Now(),
- }
- all, ok := s.notifications[user]
- if !ok {
- all = make([]*models.Notification, 0)
- }
- s.notifications[user] = append(all, newNotification)
- return newNotification, nil
-}
-
-// TotalUnread returns the number of unread notifications for current user
-func (s *NotificationStorage) TotalUnread() (int, error) {
- all, ok := s.notifications[s.user]
- if !ok {
- return 0, nil
- }
- return len(all), nil
-}
-
-// MarkAsRead given id of current user
-func (s *NotificationStorage) MarkAsRead(id int) error {
- all, ok := s.notifications[s.user]
- if !ok {
- return nil
- }
-
- for _, notification := range all {
- if notification.ID == id {
- notification.Read = true
- }
- }
- return nil
-}
-
-// MarkAllAsRead of current user
-func (s *NotificationStorage) MarkAllAsRead() error {
- all, ok := s.notifications[s.user]
- if !ok {
- return nil
- }
-
- for _, notification := range all {
- notification.Read = true
- }
-
- return nil
-}
-
-// GetActiveNotifications returns all unread notifications and last 30 days of read notifications
-func (s *NotificationStorage) GetActiveNotifications() ([]*models.Notification, error) {
- all, ok := s.notifications[s.user]
- if !ok {
- return make([]*models.Notification, 0), nil
- }
- return all, nil
-}
-
-// GetNotification returns notification by id
-func (s *NotificationStorage) GetNotification(id int) (*models.Notification, error) {
- all, ok := s.notifications[s.user]
- if !ok {
- return nil, app.ErrNotFound
- }
-
- for _, notification := range all {
- if notification.ID == id {
- return notification, nil
- }
- }
- return nil, app.ErrNotFound
-}
diff --git a/app/storage/inmemory/post.go b/app/storage/inmemory/post.go
deleted file mode 100644
index bbcde7050..000000000
--- a/app/storage/inmemory/post.go
+++ /dev/null
@@ -1,291 +0,0 @@
-package inmemory
-
-import (
- "time"
-
- "github.com/gosimple/slug"
-
- "github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
-)
-
-// PostStorage contains read and write operations for posts
-type PostStorage struct {
- lastID int
- lastCommentID int
- posts []*models.Post
- postsVotedBy map[int][]int
- postSubscribers map[int][]*models.User
- postComments map[int][]*models.Comment
- tenant *models.Tenant
- user *models.User
-}
-
-// NewPostStorage creates a new PostStorage
-func NewPostStorage() *PostStorage {
- return &PostStorage{
- posts: make([]*models.Post, 0),
- postsVotedBy: make(map[int][]int, 0),
- postSubscribers: make(map[int][]*models.User, 0),
- postComments: make(map[int][]*models.Comment, 0),
- }
-}
-
-// SetCurrentTenant to current context
-func (s *PostStorage) SetCurrentTenant(tenant *models.Tenant) {
- s.tenant = tenant
-}
-
-// SetCurrentUser to current context
-func (s *PostStorage) SetCurrentUser(user *models.User) {
- s.user = user
-}
-
-// GetByID returns post by given id
-func (s *PostStorage) GetByID(postID int) (*models.Post, error) {
- for _, post := range s.posts {
- if post.ID == postID {
- return post, nil
- }
- }
- return nil, app.ErrNotFound
-}
-
-// Update given post
-func (s *PostStorage) Update(post *models.Post, title, description string) (*models.Post, error) {
- post.Title = title
- post.Description = description
- return post, nil
-}
-
-// GetByNumber returns post by tenant and number
-func (s *PostStorage) GetByNumber(number int) (*models.Post, error) {
- for _, post := range s.posts {
- if post.Number == number && post.Status != models.PostDeleted {
- return post, nil
- }
- }
- return nil, app.ErrNotFound
-}
-
-// GetBySlug returns post by tenant and slug
-func (s *PostStorage) GetBySlug(slug string) (*models.Post, error) {
- for _, post := range s.posts {
- if post.Slug == slug && post.Status != models.PostDeleted {
- return post, nil
- }
- }
- return nil, app.ErrNotFound
-}
-
-// GetAll returns all tenant posts
-func (s *PostStorage) GetAll() ([]*models.Post, error) {
- return s.posts, nil
-}
-
-// CountPerStatus returns total number of posts per status
-func (s *PostStorage) CountPerStatus() (map[models.PostStatus]int, error) {
- return make(map[models.PostStatus]int, 0), nil
-}
-
-// Search existing posts based on input
-func (s *PostStorage) Search(query, view, limit string, tags []string) ([]*models.Post, error) {
- return s.posts, nil
-}
-
-// GetCommentsByPost returns all comments from given post
-func (s *PostStorage) GetCommentsByPost(post *models.Post) ([]*models.Comment, error) {
- return s.postComments[post.ID], nil
-}
-
-// Add a new post in the database
-func (s *PostStorage) Add(title, description string) (*models.Post, error) {
- s.lastID = s.lastID + 1
- post := &models.Post{
- ID: s.lastID,
- Number: s.lastID,
- Title: title,
- Slug: slug.Make(title),
- Description: description,
- User: s.user,
- }
- s.posts = append(s.posts, post)
- s.postsVotedBy[s.user.ID] = append(s.postsVotedBy[s.user.ID], post.ID)
- s.AddSubscriber(post, s.user)
- return post, nil
-}
-
-// AddComment places a new comment on an post
-func (s *PostStorage) AddComment(post *models.Post, content string) (int, error) {
- s.lastCommentID++
- s.postComments[post.ID] = append(s.postComments[post.ID], &models.Comment{
- ID: s.lastCommentID,
- Content: content,
- CreatedAt: time.Now(),
- User: s.user,
- })
-
- return s.lastCommentID, nil
-}
-
-// DeleteComment by its id
-func (s *PostStorage) DeleteComment(id int) error {
- for _, p := range s.posts {
- if comments, ok := s.postComments[p.ID]; ok {
- for idx, comment := range comments {
- if comment.ID == id {
- s.postComments[p.ID] = append(comments[:idx], comments[idx+1:]...)
- }
- }
- }
- }
-
- return nil
-}
-
-// GetCommentByID returns a comment by given ID
-func (s *PostStorage) GetCommentByID(id int) (*models.Comment, error) {
- for _, comments := range s.postComments {
- for _, comment := range comments {
- if comment.ID == id && comment.User.Tenant == s.tenant {
- return comment, nil
- }
- }
- }
- return nil, app.ErrNotFound
-}
-
-// UpdateComment with given ID and content
-func (s *PostStorage) UpdateComment(id int, content string) error {
- now := time.Now()
- comment, err := s.GetCommentByID(id)
- if err != nil {
- return err
- }
- comment.Content = content
- comment.EditedAt = &now
- comment.EditedBy = s.user
- return nil
-}
-
-// AddVote adds user to post list of votes
-func (s *PostStorage) AddVote(post *models.Post, user *models.User) error {
- s.postsVotedBy[user.ID] = append(s.postsVotedBy[user.ID], post.ID)
- post.VotesCount = post.VotesCount + 1
- return nil
-}
-
-// RemoveVote removes user from post list of votes
-func (s *PostStorage) RemoveVote(post *models.Post, user *models.User) error {
- for i, id := range s.postsVotedBy[user.ID] {
- if id == post.ID {
- s.postsVotedBy[user.ID] = append(s.postsVotedBy[user.ID][:i], s.postsVotedBy[user.ID][i+1:]...)
- break
- }
- }
- post.VotesCount = post.VotesCount - 1
- return nil
-}
-
-// SetResponse changes current post response
-func (s *PostStorage) SetResponse(post *models.Post, text string, status models.PostStatus) error {
- for _, storedPost := range s.posts {
- if storedPost.Number == post.Number {
- storedPost.Status = status
- storedPost.Response = &models.PostResponse{
- Text: text,
- User: s.user,
- RespondedAt: time.Now(),
- }
- }
- }
- return nil
-}
-
-// MarkAsDuplicate set post as a duplicate of another post
-func (s *PostStorage) MarkAsDuplicate(post *models.Post, original *models.Post) error {
- post.Status = models.PostDuplicate
- post.Response = &models.PostResponse{
- Original: &models.OriginalPost{
- Number: original.Number,
- Title: original.Title,
- Slug: original.Slug,
- Status: original.Status,
- },
- Text: "",
- User: s.user,
- RespondedAt: time.Now(),
- }
- return nil
-}
-
-// IsReferenced returns true if another post is referencing given post
-func (s *PostStorage) IsReferenced(post *models.Post) (bool, error) {
- for _, i := range s.posts {
- if i.Status == models.PostDuplicate && i.Response.Original.Number == post.Number {
- return true, nil
- }
- }
- return false, nil
-}
-
-// VotedBy returns a list of Post ID voted by given user
-func (s *PostStorage) VotedBy() ([]int, error) {
- return s.postsVotedBy[s.user.ID], nil
-}
-
-// ListVotes returns a list of all votes on given post
-func (s *PostStorage) ListVotes(post *models.Post, limit int) ([]*models.Vote, error) {
- return make([]*models.Vote, 0), nil
-}
-
-// AddSubscriber adds user to the post list of subscribers
-func (s *PostStorage) AddSubscriber(post *models.Post, user *models.User) error {
- s.postSubscribers[post.ID] = append(s.postSubscribers[post.ID], user)
- return nil
-}
-
-// RemoveSubscriber removes user from post list of subscribers
-func (s *PostStorage) RemoveSubscriber(post *models.Post, user *models.User) error {
- for i, u := range s.postSubscribers[post.ID] {
- if u.ID == user.ID {
- s.postSubscribers[post.ID] = append(s.postSubscribers[post.ID][:i], s.postSubscribers[post.ID][i+1:]...)
- break
- }
- }
- return nil
-}
-
-// GetActiveSubscribers based on input and settings
-func (s *PostStorage) GetActiveSubscribers(number int, channel models.NotificationChannel, event models.NotificationEvent) ([]*models.User, error) {
- var post *models.Post
- for _, p := range s.posts {
- if p.Number == number {
- post = p
- }
- }
-
- if post == nil {
- return nil, app.ErrNotFound
- }
-
- subscribers, ok := s.postSubscribers[post.ID]
- if ok {
- users := make([]*models.User, len(subscribers))
- for i, user := range subscribers {
- users[i] = user
- }
- return users, nil
- }
- return make([]*models.User, 0), nil
-}
-
-// GetAttachments for given post or comment
-func (s *PostStorage) GetAttachments(post *models.Post, comment *models.Comment) ([]string, error) {
- return make([]string, 0), nil
-}
-
-// SetAttachments on given post or comment
-func (s *PostStorage) SetAttachments(post *models.Post, comment *models.Comment, attachments []*models.ImageUpload) error {
- return nil
-}
diff --git a/app/storage/inmemory/tag.go b/app/storage/inmemory/tag.go
deleted file mode 100644
index 3874c64c3..000000000
--- a/app/storage/inmemory/tag.go
+++ /dev/null
@@ -1,135 +0,0 @@
-package inmemory
-
-import (
- "github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
- "github.com/gosimple/slug"
-)
-
-// TagStorage contains read and write operations for tags
-type TagStorage struct {
- lastID int
- tags []*models.Tag
- user *models.User
- tenant *models.Tenant
- assigned map[int][]*models.Tag
-}
-
-// NewTagStorage creates a new TagStorage
-func NewTagStorage() *TagStorage {
- return &TagStorage{
- tags: make([]*models.Tag, 0),
- assigned: make(map[int][]*models.Tag),
- }
-}
-
-// SetCurrentTenant to current context
-func (s *TagStorage) SetCurrentTenant(tenant *models.Tenant) {
- s.tenant = tenant
-}
-
-// SetCurrentUser to current context
-func (s *TagStorage) SetCurrentUser(user *models.User) {
- s.user = user
-}
-
-// Add creates a new tag with given input
-func (s *TagStorage) Add(name, color string, isPublic bool) (*models.Tag, error) {
- s.lastID = s.lastID + 1
- tag := &models.Tag{
- ID: s.lastID,
- Name: name,
- Slug: slug.Make(name),
- Color: color,
- IsPublic: isPublic,
- }
- s.tags = append(s.tags, tag)
- return tag, nil
-}
-
-// GetBySlug returns tag by given slug
-func (s *TagStorage) GetBySlug(slug string) (*models.Tag, error) {
- for _, tag := range s.tags {
- if tag.Slug == slug {
- return tag, nil
- }
- }
- return nil, app.ErrNotFound
-}
-
-// Update a tag with given input
-func (s *TagStorage) Update(tag *models.Tag, name, color string, isPublic bool) (*models.Tag, error) {
- for _, storedTag := range s.tags {
- if storedTag.ID == tag.ID {
- storedTag.Name = name
- storedTag.Slug = slug.Make(name)
- storedTag.Color = color
- storedTag.IsPublic = isPublic
- return tag, nil
- }
- }
- return nil, app.ErrNotFound
-}
-
-// Delete a tag by its id
-func (s *TagStorage) Delete(tag *models.Tag) error {
- for i, storedTag := range s.tags {
- if storedTag.ID == tag.ID {
- s.tags = append(s.tags[:i], s.tags[i+1:]...)
- break
- }
- }
- return nil
-}
-
-// AssignTag adds a tag to an post
-func (s *TagStorage) AssignTag(tag *models.Tag, post *models.Post) error {
- assigned := s.assigned[post.ID]
- if assigned != nil {
- for _, assignedTag := range assigned {
- if assignedTag.ID == tag.ID {
- return nil
- }
- }
- }
-
- s.assigned[post.ID] = append(s.assigned[post.ID], tag)
- return nil
-}
-
-// UnassignTag removes a tag from an post
-func (s *TagStorage) UnassignTag(tag *models.Tag, post *models.Post) error {
- assigned := s.assigned[post.ID]
- if assigned != nil {
- for i, assignedTag := range assigned {
- if assignedTag.ID == tag.ID {
- s.assigned[post.ID] = append(s.assigned[post.ID][:i], s.assigned[post.ID][i+1:]...)
- return nil
- }
- }
- }
- return nil
-}
-
-// GetAssigned returns all tags assigned to given post
-func (s *TagStorage) GetAssigned(post *models.Post) ([]*models.Tag, error) {
- assigned := s.assigned[post.ID]
- if assigned != nil {
- return assigned, nil
- }
- return make([]*models.Tag, 0), nil
-}
-
-// GetAll returns all tags
-func (s *TagStorage) GetAll() ([]*models.Tag, error) {
- if s.user != nil && s.user.IsCollaborator() {
- return s.tags, nil
- }
- tags := make([]*models.Tag, 0)
- for _, tag := range s.tags {
- if tag.IsPublic {
- tags = append(tags, tag)
- }
- }
- return tags, nil
-}
diff --git a/app/storage/inmemory/tenant.go b/app/storage/inmemory/tenant.go
deleted file mode 100644
index 8d8cdc888..000000000
--- a/app/storage/inmemory/tenant.go
+++ /dev/null
@@ -1,245 +0,0 @@
-package inmemory
-
-import (
- "time"
-
- "github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/env"
-)
-
-// TenantStorage contains read and write operations for tenants
-type TenantStorage struct {
- lastID int
- tenants []*models.Tenant
- current *models.Tenant
- user *models.User
- verifications []*models.EmailVerification
- oauthConfigs []*models.OAuthConfig
-}
-
-//NewTenantStorage creates a new TenantStorage
-func NewTenantStorage() *TenantStorage {
- return &TenantStorage{
- tenants: make([]*models.Tenant, 0),
- verifications: make([]*models.EmailVerification, 0),
- oauthConfigs: make([]*models.OAuthConfig, 0),
- }
-}
-
-// SetCurrentTenant tenant
-func (s *TenantStorage) SetCurrentTenant(tenant *models.Tenant) {
- s.current = tenant
-}
-
-// SetCurrentUser to current context
-func (s *TenantStorage) SetCurrentUser(user *models.User) {
- s.user = user
-}
-
-// Current returns current context tenant
-func (s *TenantStorage) Current() *models.Tenant {
- return s.current
-}
-
-// Add given tenant to tenant list
-func (s *TenantStorage) Add(name string, subdomain string, status int) (*models.Tenant, error) {
- s.lastID = s.lastID + 1
- tenant := &models.Tenant{ID: s.lastID, Name: name, Subdomain: subdomain, Status: status}
- s.tenants = append(s.tenants, tenant)
- return tenant, nil
-}
-
-// First returns first tenant
-func (s *TenantStorage) First() (*models.Tenant, error) {
- for _, tenant := range s.tenants {
- return tenant, nil
- }
-
- return nil, app.ErrNotFound
-}
-
-// GetByDomain returns a tenant based on its domain
-func (s *TenantStorage) GetByDomain(domain string) (*models.Tenant, error) {
- for _, tenant := range s.tenants {
- if tenant.Subdomain == env.Subdomain(domain) || tenant.Subdomain == domain || tenant.CNAME == domain {
- return tenant, nil
- }
- }
-
- return nil, app.ErrNotFound
-}
-
-// IsSubdomainAvailable returns true if subdomain is available to use
-func (s *TenantStorage) IsSubdomainAvailable(subdomain string) (bool, error) {
- for _, tenant := range s.tenants {
- if tenant.Subdomain == subdomain {
- return false, nil
- }
- }
- return true, nil
-}
-
-// IsCNAMEAvailable returns true if cname is available to use
-func (s *TenantStorage) IsCNAMEAvailable(cname string) (bool, error) {
- for _, tenant := range s.tenants {
- if tenant.CNAME == cname {
- return false, nil
- }
- }
- return true, nil
-}
-
-// UpdateSettings of current tenant
-func (s *TenantStorage) UpdateSettings(settings *models.UpdateTenantSettings) error {
- if settings.Logo.Remove {
- settings.Logo.BlobKey = ""
- }
-
- for _, tenant := range s.tenants {
- if tenant.ID == s.current.ID {
- tenant.Invitation = settings.Invitation
- tenant.WelcomeMessage = settings.WelcomeMessage
- tenant.Name = settings.Title
- tenant.CNAME = settings.CNAME
- tenant.LogoBlobKey = settings.Logo.BlobKey
- return nil
- }
- }
- return nil
-}
-
-// UpdateBillingSettings of current tenant
-func (s *TenantStorage) UpdateBillingSettings(billing *models.TenantBilling) error {
- s.current.Billing = billing
- return nil
-}
-
-// UpdateAdvancedSettings of current tenant
-func (s *TenantStorage) UpdateAdvancedSettings(settings *models.UpdateTenantAdvancedSettings) error {
- for _, tenant := range s.tenants {
- if tenant.ID == s.current.ID {
- tenant.CustomCSS = settings.CustomCSS
- return nil
- }
- }
- return nil
-}
-
-// UpdatePrivacy settings of current tenant
-func (s *TenantStorage) UpdatePrivacy(settings *models.UpdateTenantPrivacy) error {
- for _, tenant := range s.tenants {
- if tenant.ID == s.current.ID {
- tenant.IsPrivate = settings.IsPrivate
- return nil
- }
- }
- return nil
-}
-
-// Activate given tenant
-func (s *TenantStorage) Activate(id int) error {
- for _, tenant := range s.tenants {
- if tenant.ID == id {
- tenant.Status = models.TenantActive
- return nil
- }
- }
- return app.ErrNotFound
-}
-
-// SaveVerificationKey used by email verification
-func (s *TenantStorage) SaveVerificationKey(key string, duration time.Duration, request models.NewEmailVerification) error {
- userID := 0
- if request.GetUser() != nil {
- userID = request.GetUser().ID
- }
- s.verifications = append(s.verifications, &models.EmailVerification{
- Email: request.GetEmail(),
- Name: request.GetName(),
- Kind: request.GetKind(),
- Key: key,
- UserID: userID,
- CreatedAt: time.Now(),
- ExpiresAt: time.Now().Add(duration),
- VerifiedAt: nil,
- })
- return nil
-}
-
-// FindVerificationByKey based on current tenant
-func (s *TenantStorage) FindVerificationByKey(kind models.EmailVerificationKind, key string) (*models.EmailVerification, error) {
- for _, verification := range s.verifications {
- if verification.Key == key && verification.Kind == kind {
- return verification, nil
- }
- }
- return nil, app.ErrNotFound
-}
-
-// SetKeyAsVerified so that it cannot be used anymore
-func (s *TenantStorage) SetKeyAsVerified(key string) error {
- for _, verification := range s.verifications {
- if verification.Key == key {
- now := time.Now()
- verification.VerifiedAt = &now
- }
- }
- return nil
-}
-
-// SaveOAuthConfig saves given config into database
-func (s *TenantStorage) SaveOAuthConfig(config *models.CreateEditOAuthConfig) error {
- bkey := ""
- if config.Logo != nil {
- bkey = config.Logo.BlobKey
- }
- for _, c := range s.oauthConfigs {
- if c.ID == config.ID {
- c.Provider = config.Provider
- c.DisplayName = config.DisplayName
- c.ClientID = config.ClientID
- c.ClientSecret = config.ClientSecret
- c.AuthorizeURL = config.AuthorizeURL
- c.TokenURL = config.TokenURL
- c.Scope = config.Scope
- c.ProfileURL = config.ProfileURL
- c.JSONUserIDPath = config.JSONUserIDPath
- c.JSONUserNamePath = config.JSONUserNamePath
- c.JSONUserEmailPath = config.JSONUserEmailPath
- c.LogoBlobKey = bkey
- return nil
- }
- }
- s.oauthConfigs = append(s.oauthConfigs, &models.OAuthConfig{
- ID: config.ID,
- Provider: config.Provider,
- DisplayName: config.DisplayName,
- LogoBlobKey: bkey,
- ClientID: config.ClientID,
- ClientSecret: config.ClientSecret,
- AuthorizeURL: config.AuthorizeURL,
- TokenURL: config.TokenURL,
- Scope: config.Scope,
- ProfileURL: config.ProfileURL,
- JSONUserIDPath: config.JSONUserIDPath,
- JSONUserNamePath: config.JSONUserNamePath,
- JSONUserEmailPath: config.JSONUserEmailPath,
- })
- return nil
-}
-
-// GetOAuthConfigByProvider returns a custom OAuth configuration by provider name
-func (s *TenantStorage) GetOAuthConfigByProvider(provider string) (*models.OAuthConfig, error) {
- for _, c := range s.oauthConfigs {
- if c.Provider == provider {
- return c, nil
- }
- }
- return nil, app.ErrNotFound
-}
-
-// ListOAuthConfig returns a list of all custom OAuth provider for current tenant
-func (s *TenantStorage) ListOAuthConfig() ([]*models.OAuthConfig, error) {
- return s.oauthConfigs, nil
-}
diff --git a/app/storage/inmemory/user.go b/app/storage/inmemory/user.go
deleted file mode 100644
index 506420b7b..000000000
--- a/app/storage/inmemory/user.go
+++ /dev/null
@@ -1,209 +0,0 @@
-package inmemory
-
-import (
- "github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/errors"
-)
-
-// UserStorage is used for user operations
-type UserStorage struct {
- user *models.User
- tenant *models.Tenant
- users []*models.User
- lastID int
- settingsPerUser map[int]map[string]string
- userByAPIKey map[string]*models.User
-}
-
-// GetByID returns a user based on given id
-func (s *UserStorage) GetByID(userID int) (*models.User, error) {
- for _, user := range s.users {
- if user.ID == userID {
- return user, nil
- }
- }
- return nil, app.ErrNotFound
-}
-
-// SetCurrentTenant tenant
-func (s *UserStorage) SetCurrentTenant(tenant *models.Tenant) {
- s.tenant = tenant
-}
-
-// SetCurrentUser to current context
-func (s *UserStorage) SetCurrentUser(user *models.User) {
- s.user = user
-}
-
-// GetByEmail returns a user based on given email
-func (s *UserStorage) GetByEmail(email string) (*models.User, error) {
- for _, user := range s.users {
- if user.Email == email && user.Tenant.ID == s.tenant.ID {
- return user, nil
- }
- }
- return nil, app.ErrNotFound
-}
-
-// GetByProvider returns a user based on provider details
-func (s *UserStorage) GetByProvider(provider string, uid string) (*models.User, error) {
- for _, user := range s.users {
- for _, item := range user.Providers {
- if item.Name == provider && item.UID == uid {
- return user, nil
- }
- }
- }
- return nil, app.ErrNotFound
-}
-
-// Register creates a new user based on given information
-func (s *UserStorage) Register(user *models.User) error {
- user.Status = models.UserActive
- if user.ID == 0 {
- s.lastID = s.lastID + 1
- user.ID = s.lastID
- }
- _, err := s.GetByEmail(user.Email)
- if errors.Cause(err) == app.ErrNotFound || user.Email == "" {
- s.users = append(s.users, user)
- return nil
- }
- return errors.New("User already registered")
-}
-
-// RegisterProvider adds given provider to userID
-func (s *UserStorage) RegisterProvider(userID int, provider *models.UserProvider) error {
- user, err := s.GetByID(userID)
- if err == nil {
- user.Providers = append(user.Providers, provider)
- }
- return err
-}
-
-// Update user settings
-func (s *UserStorage) Update(settings *models.UpdateUserSettings) error {
- user, err := s.GetByID(s.user.ID)
- if err == nil {
- user.Name = settings.Name
- }
- return err
-}
-
-// ChangeRole of given user
-func (s *UserStorage) ChangeRole(userID int, role models.Role) error {
- user, err := s.GetByID(userID)
- if err == nil {
- user.Role = role
- }
- return err
-}
-
-// ChangeEmail of given user
-func (s *UserStorage) ChangeEmail(userID int, email string) error {
- user, err := s.GetByID(userID)
- if err == nil {
- user.Email = email
- }
- return err
-}
-
-// GetAll return all users of current tenant
-func (s *UserStorage) GetAll() ([]*models.User, error) {
- return s.users, nil
-}
-
-// UpdateSettings of given user
-func (s *UserStorage) UpdateSettings(settings map[string]string) error {
- if s.user == nil {
- return nil
- }
- if s.settingsPerUser == nil {
- s.settingsPerUser = make(map[int]map[string]string, 0)
- }
- s.settingsPerUser[s.user.ID] = settings
- return nil
-}
-
-// GetUserSettings returns current user's settings
-func (s *UserStorage) GetUserSettings() (map[string]string, error) {
- if s.settingsPerUser == nil || s.user == nil {
- return make(map[string]string, 0), nil
- }
- settings, ok := s.settingsPerUser[s.user.ID]
- if ok {
- return settings, nil
- }
- return make(map[string]string, 0), nil
-}
-
-// HasSubscribedTo returns true if current user is receiving notification from specific post
-func (s *UserStorage) HasSubscribedTo(postID int) (bool, error) {
- return false, nil
-}
-
-// Delete removes current user personal data and mark it as deleted
-func (s *UserStorage) Delete() error {
- s.user.Name = ""
- s.user.Email = ""
- s.user.Role = models.RoleVisitor
- s.user.Status = models.UserDeleted
- s.user.Providers = make([]*models.UserProvider, 0)
- return nil
-}
-
-// RegenerateAPIKey generates a new API Key and returns it
-func (s *UserStorage) RegenerateAPIKey() (string, error) {
- apiKey := models.GenerateSecretKey()
- if s.userByAPIKey == nil {
- s.userByAPIKey = make(map[string]*models.User)
- }
- s.userByAPIKey[apiKey] = s.user
- return apiKey, nil
-}
-
-// GetByAPIKey returns a user based on its API key
-func (s *UserStorage) GetByAPIKey(apiKey string) (*models.User, error) {
- if s.userByAPIKey == nil {
- s.userByAPIKey = make(map[string]*models.User)
- }
-
- for userAPIKey, user := range s.userByAPIKey {
- if userAPIKey == apiKey {
- return user, nil
- }
- }
- return nil, app.ErrNotFound
-}
-
-// Block a given user from using Fider
-func (s *UserStorage) Block(userID int) error {
- user, err := s.GetByID(userID)
- if err != nil {
- return err
- }
-
- if user.Status == models.UserActive {
- user.Status = models.UserBlocked
- }
- return nil
-}
-
-// Unblock a given user so that they can use Fider again
-func (s *UserStorage) Unblock(userID int) error {
- user, err := s.GetByID(userID)
- if err != nil {
- return err
- }
-
- if user.Status == models.UserBlocked {
- user.Status = models.UserActive
- }
- return nil
-}
-
-// Count returns the total number of registered users
-func (s *UserStorage) Count() (int, error) {
- return len(s.users), nil
-}
diff --git a/app/storage/postgres/event.go b/app/storage/postgres/event.go
deleted file mode 100644
index ddc1af6e0..000000000
--- a/app/storage/postgres/event.go
+++ /dev/null
@@ -1,92 +0,0 @@
-package postgres
-
-import (
- "database/sql"
- "time"
-
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/dbx"
- "github.com/getfider/fider/app/pkg/errors"
-)
-
-type dbEvent struct {
- ID int `db:"id"`
- TenantID int `db:"tenant_id"`
- ClientIP sql.NullString `db:"client_ip"`
- Name string `db:"name"`
- CreatedAt time.Time `db:"created_at"`
-}
-
-func (d *dbEvent) toModel() *models.Event {
- return &models.Event{
- ID: d.ID,
- ClientIP: d.ClientIP.String,
- Name: d.Name,
- CreatedAt: d.CreatedAt,
- }
-}
-
-// EventStorage contains read and write operations for Audit Events
-type EventStorage struct {
- trx *dbx.Trx
- user *models.User
- tenant *models.Tenant
-}
-
-// NewEventStorage creates a new inmemory EventStorage
-func NewEventStorage(trx *dbx.Trx) *EventStorage {
- return &EventStorage{
- trx: trx,
- }
-}
-
-// SetCurrentTenant to current context
-func (e *EventStorage) SetCurrentTenant(tenant *models.Tenant) {
- e.tenant = tenant
-}
-
-// SetCurrentUser to current context
-func (e *EventStorage) SetCurrentUser(user *models.User) {
- e.user = user
-}
-
-// Add stores a new event
-func (e *EventStorage) Add(clientIP, name string) (*models.Event, error) {
- event := &models.Event{
- ClientIP: clientIP,
- Name: name,
- CreatedAt: time.Now(),
- }
- dbClientIP := sql.NullString{
- String: clientIP,
- Valid: len(clientIP) > 0,
- }
-
- err := e.trx.Get(&event.ID, `
- INSERT INTO events (tenant_id, client_ip, name, created_at)
- VALUES ($1, $2, $3, $4)
- RETURNING id
- `, e.tenant.ID, dbClientIP, event.Name, event.CreatedAt)
-
- if err != nil {
- return nil, errors.Wrap(err, "failed to insert event")
- }
-
- return event, nil
-}
-
-// GetByID returns the event with the specified id
-func (e *EventStorage) GetByID(id int) (*models.Event, error) {
- event := &dbEvent{}
- err := e.trx.Get(event, `
- SELECT id, tenant_id, client_ip, name, created_at
- FROM events
- WHERE id = $1 AND tenant_id = $2
- `, id, e.tenant.ID)
-
- if err != nil {
- return nil, errors.Wrap(err, "failed to find event with id %d", id)
- }
-
- return event.toModel(), nil
-}
diff --git a/app/storage/postgres/event_test.go b/app/storage/postgres/event_test.go
deleted file mode 100644
index 945543cfe..000000000
--- a/app/storage/postgres/event_test.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package postgres_test
-
-import (
- "testing"
-
- . "github.com/getfider/fider/app/pkg/assert"
-)
-
-func TestEventStorage_AddAndGet(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- events.SetCurrentTenant(demoTenant)
-
- clientIP := "127.0.0.1"
- name := "posts.create"
- event, err := events.Add(clientIP, name)
- Expect(err).IsNil()
-
- event, err = events.GetByID(event.ID)
- Expect(err).IsNil()
- Expect(event.ClientIP).Equals(clientIP)
- Expect(event.Name).Equals(name)
-}
-
-func TestEventStorage_AddAndGetWithNullClientIP(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- events.SetCurrentTenant(demoTenant)
-
- clientIP := ""
- name := "tenant.register"
- event, err := events.Add(clientIP, name)
- Expect(err).IsNil()
-
- event, err = events.GetByID(event.ID)
- Expect(err).IsNil()
- Expect(event.ClientIP).Equals(clientIP)
- Expect(event.Name).Equals(name)
-}
diff --git a/app/storage/postgres/notifications.go b/app/storage/postgres/notifications.go
deleted file mode 100644
index 8487c8d77..000000000
--- a/app/storage/postgres/notifications.go
+++ /dev/null
@@ -1,128 +0,0 @@
-package postgres
-
-import (
- "time"
-
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/dbx"
- "github.com/getfider/fider/app/pkg/errors"
-)
-
-// NotificationStorage contains read and write operations for notifications
-type NotificationStorage struct {
- trx *dbx.Trx
- tenant *models.Tenant
- user *models.User
-}
-
-// NewNotificationStorage creates a new NotificationStorage
-func NewNotificationStorage(trx *dbx.Trx) *NotificationStorage {
- return &NotificationStorage{
- trx: trx,
- }
-}
-
-// SetCurrentTenant to current context
-func (s *NotificationStorage) SetCurrentTenant(tenant *models.Tenant) {
- s.tenant = tenant
-}
-
-// SetCurrentUser to current context
-func (s *NotificationStorage) SetCurrentUser(user *models.User) {
- s.user = user
-}
-
-// Insert notification for given user
-func (s *NotificationStorage) Insert(user *models.User, title, link string, postID int) (*models.Notification, error) {
- if user.ID == s.user.ID {
- return nil, nil
- }
-
- now := time.Now()
- notification := &models.Notification{
- Title: title,
- Link: link,
- CreatedAt: now,
- Read: false,
- }
- err := s.trx.Get(&notification.ID, `
- INSERT INTO notifications (tenant_id, user_id, title, link, read, post_id, author_id, created_at, updated_at)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $8)
- RETURNING id
- `, s.tenant.ID, user.ID, title, link, false, postID, s.user.ID, now)
- if err != nil {
- return nil, errors.Wrap(err, "failed to insert notification")
- }
- return notification, nil
-}
-
-// TotalUnread returns the number of unread notifications for current user
-func (s *NotificationStorage) TotalUnread() (int, error) {
- total := 0
- if s.user != nil {
- err := s.trx.Scalar(&total, "SELECT COUNT(*) FROM notifications WHERE tenant_id = $1 AND user_id = $2 AND read = false", s.tenant.ID, s.user.ID)
- if err != nil {
- return 0, errors.Wrap(err, "failed count total unread notifications")
- }
- }
- return total, nil
-}
-
-// MarkAsRead given id of current user
-func (s *NotificationStorage) MarkAsRead(id int) error {
- if s.user == nil {
- return nil
- }
- _, err := s.trx.Execute(`
- UPDATE notifications SET read = true, updated_at = $1
- WHERE id = $2 AND tenant_id = $3 AND user_id = $4 AND read = false
- `, time.Now(), id, s.tenant.ID, s.user.ID)
- if err != nil {
- return errors.Wrap(err, "failed to mark notification as read")
- }
- return nil
-}
-
-// MarkAllAsRead of current user
-func (s *NotificationStorage) MarkAllAsRead() error {
- if s.user == nil {
- return nil
- }
- _, err := s.trx.Execute(`
- UPDATE notifications SET read = true, updated_at = $1
- WHERE tenant_id = $2 AND user_id = $3 AND read = false
- `, time.Now(), s.tenant.ID, s.user.ID)
- if err != nil {
- return errors.Wrap(err, "failed to mark all notifications as read")
- }
- return nil
-}
-
-// GetActiveNotifications returns all unread notifications and last 30 days of read notifications
-func (s *NotificationStorage) GetActiveNotifications() ([]*models.Notification, error) {
- notifications := []*models.Notification{}
- err := s.trx.Select(&notifications, `
- SELECT id, title, link, read, created_at
- FROM notifications
- WHERE tenant_id = $1 AND user_id = $2
- AND (read = false OR updated_at > CURRENT_DATE - INTERVAL '30 days')
- `, s.tenant.ID, s.user.ID)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get active notifications")
- }
- return notifications, nil
-}
-
-// GetNotification returns notification by id
-func (s *NotificationStorage) GetNotification(id int) (*models.Notification, error) {
- notification := &models.Notification{}
- err := s.trx.Get(notification, `
- SELECT id, title, link, read, created_at
- FROM notifications
- WHERE id = $1 AND tenant_id = $2 AND user_id = $3
- `, id, s.tenant.ID, s.user.ID)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get notifications with id '%d'", id)
- }
- return notification, nil
-}
diff --git a/app/storage/postgres/notifications_test.go b/app/storage/postgres/notifications_test.go
deleted file mode 100644
index 129d32d5a..000000000
--- a/app/storage/postgres/notifications_test.go
+++ /dev/null
@@ -1,155 +0,0 @@
-package postgres_test
-
-import (
- "testing"
- "time"
-
- "github.com/getfider/fider/app"
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/errors"
-)
-
-func TestNotificationStorage_TotalCount(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- notifications.SetCurrentTenant(demoTenant)
-
- notifications.SetCurrentUser(jonSnow)
- total, err := notifications.TotalUnread()
- Expect(err).IsNil()
- Expect(total).Equals(0)
-
- notifications.SetCurrentUser(nil)
- total, err = notifications.TotalUnread()
- Expect(err).IsNil()
- Expect(total).Equals(0)
-}
-
-func TestNotificationStorage_Insert_Read_Count(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- notifications.SetCurrentTenant(demoTenant)
- notifications.SetCurrentUser(jonSnow)
- post, _ := posts.Add("Title", "Description")
-
- not1, err := notifications.Insert(aryaStark, "Hello World", "http://www.google.com.br", post.ID)
- Expect(err).IsNil()
- not2, err := notifications.Insert(aryaStark, "Another thing happened", "http://www.google.com.br", post.ID)
- Expect(err).IsNil()
-
- notifications.SetCurrentUser(aryaStark)
- total, err := notifications.TotalUnread()
- Expect(err).IsNil()
- Expect(total).Equals(2)
-
- Expect(notifications.MarkAsRead(not1.ID)).IsNil()
- total, err = notifications.TotalUnread()
- Expect(err).IsNil()
- Expect(total).Equals(1)
-
- Expect(notifications.MarkAsRead(not2.ID)).IsNil()
- total, err = notifications.TotalUnread()
- Expect(err).IsNil()
- Expect(total).Equals(0)
-}
-
-func TestNotificationStorage_GetActiveNotifications(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- notifications.SetCurrentTenant(demoTenant)
- notifications.SetCurrentUser(jonSnow)
- post, _ := posts.Add("Title", "Description")
-
- notifications.Insert(aryaStark, "Hello World", "http://www.google.com.br", post.ID)
- notifications.Insert(aryaStark, "Another thing happened", "http://www.google.com.br", post.ID)
-
- notifications.SetCurrentUser(aryaStark)
-
- allNotifications, err := notifications.GetActiveNotifications()
- Expect(err).IsNil()
- Expect(allNotifications).HasLen(2)
-
- notifications.MarkAsRead(allNotifications[0].ID)
- notifications.MarkAsRead(allNotifications[1].ID)
- trx.Execute("UPDATE notifications SET updated_at = $1 WHERE id = $2", time.Now().AddDate(0, 0, -31), allNotifications[0].ID)
-
- allNotifications, err = notifications.GetActiveNotifications()
- Expect(err).IsNil()
- Expect(allNotifications).HasLen(1)
- Expect(allNotifications[0].Read).IsTrue()
-}
-
-func TestNotificationStorage_ReadAll(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- notifications.SetCurrentTenant(demoTenant)
- notifications.SetCurrentUser(jonSnow)
-
- post, _ := posts.Add("Title", "Description")
-
- notifications.Insert(aryaStark, "Hello World", "http://www.google.com.br", post.ID)
- notifications.Insert(aryaStark, "Another thing happened", "http://www.google.com.br", post.ID)
-
- notifications.SetCurrentUser(aryaStark)
-
- allNotifications, err := notifications.GetActiveNotifications()
- Expect(err).IsNil()
- Expect(allNotifications).HasLen(2)
-
- notifications.MarkAllAsRead()
-
- allNotifications, err = notifications.GetActiveNotifications()
- Expect(err).IsNil()
- Expect(allNotifications).HasLen(2)
- Expect(allNotifications[0].Read).IsTrue()
- Expect(allNotifications[1].Read).IsTrue()
-}
-
-func TestNotificationStorage_GetNotificationByID(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- notifications.SetCurrentTenant(demoTenant)
- notifications.SetCurrentUser(jonSnow)
- post, _ := posts.Add("Title", "Description")
-
- not1, err := notifications.Insert(aryaStark, "Hello World", "http://www.google.com.br", post.ID)
- Expect(err).IsNil()
-
- notifications.SetCurrentUser(aryaStark)
- not1, err = notifications.GetNotification(not1.ID)
- Expect(err).IsNil()
- Expect(not1.Title).Equals("Hello World")
- Expect(not1.Link).Equals("http://www.google.com.br")
- Expect(not1.Read).IsFalse()
-}
-
-func TestNotificationStorage_GetNotificationByID_OtherUser(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- post, _ := posts.Add("Title", "Description")
-
- notifications.SetCurrentTenant(demoTenant)
- notifications.SetCurrentUser(aryaStark)
- not1, err := notifications.Insert(jonSnow, "Hello World", "http://www.google.com.br", post.ID)
- Expect(err).IsNil()
-
- not1, err = notifications.GetNotification(not1.ID)
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(not1).IsNil()
-}
diff --git a/app/storage/postgres/post.go b/app/storage/postgres/post.go
deleted file mode 100644
index e64c1cdf5..000000000
--- a/app/storage/postgres/post.go
+++ /dev/null
@@ -1,875 +0,0 @@
-package postgres
-
-import (
- "fmt"
- "strconv"
- "time"
-
- "database/sql"
-
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/dbx"
- "github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/storage"
- "github.com/gosimple/slug"
- "github.com/lib/pq"
-)
-
-type dbPost struct {
- ID int `db:"id"`
- Number int `db:"number"`
- Title string `db:"title"`
- Slug string `db:"slug"`
- Description string `db:"description"`
- CreatedAt time.Time `db:"created_at"`
- User *dbUser `db:"user"`
- HasVoted bool `db:"has_voted"`
- VotesCount int `db:"votes_count"`
- CommentsCount int `db:"comments_count"`
- RecentVotes int `db:"recent_votes_count"`
- RecentComments int `db:"recent_comments_count"`
- Status int `db:"status"`
- Response sql.NullString `db:"response"`
- RespondedAt dbx.NullTime `db:"response_date"`
- ResponseUser *dbUser `db:"response_user"`
- OriginalNumber sql.NullInt64 `db:"original_number"`
- OriginalTitle sql.NullString `db:"original_title"`
- OriginalSlug sql.NullString `db:"original_slug"`
- OriginalStatus sql.NullInt64 `db:"original_status"`
- Tags []string `db:"tags"`
-}
-
-func (i *dbPost) toModel(ctx storage.Context) *models.Post {
- post := &models.Post{
- ID: i.ID,
- Number: i.Number,
- Title: i.Title,
- Slug: i.Slug,
- Description: i.Description,
- CreatedAt: i.CreatedAt,
- HasVoted: i.HasVoted,
- VotesCount: i.VotesCount,
- CommentsCount: i.CommentsCount,
- Status: models.PostStatus(i.Status),
- User: i.User.toModel(ctx),
- Tags: i.Tags,
- }
-
- if i.Response.Valid {
- post.Response = &models.PostResponse{
- Text: i.Response.String,
- RespondedAt: i.RespondedAt.Time,
- User: i.ResponseUser.toModel(ctx),
- }
- if post.Status == models.PostDuplicate && i.OriginalNumber.Valid {
- post.Response.Original = &models.OriginalPost{
- Number: int(i.OriginalNumber.Int64),
- Slug: i.OriginalSlug.String,
- Title: i.OriginalTitle.String,
- Status: models.PostStatus(i.OriginalStatus.Int64),
- }
- }
- }
- return post
-}
-
-type dbComment struct {
- ID int `db:"id"`
- Content string `db:"content"`
- CreatedAt time.Time `db:"created_at"`
- User *dbUser `db:"user"`
- Attachments []string `db:"attachment_bkeys"`
- EditedAt dbx.NullTime `db:"edited_at"`
- EditedBy *dbUser `db:"edited_by"`
-}
-
-func (c *dbComment) toModel(ctx storage.Context) *models.Comment {
- comment := &models.Comment{
- ID: c.ID,
- Content: c.Content,
- CreatedAt: c.CreatedAt,
- User: c.User.toModel(ctx),
- Attachments: c.Attachments,
- }
- if c.EditedAt.Valid {
- comment.EditedBy = c.EditedBy.toModel(ctx)
- comment.EditedAt = &c.EditedAt.Time
- }
- return comment
-}
-
-type dbStatusCount struct {
- Status models.PostStatus `db:"status"`
- Count int `db:"count"`
-}
-
-type dbVote struct {
- User *struct {
- ID int `db:"id"`
- Name string `db:"name"`
- Email string `db:"email"`
- AvatarType int64 `db:"avatar_type"`
- AvatarBlobKey string `db:"avatar_bkey"`
- } `db:"user"`
- CreatedAt time.Time `db:"created_at"`
-}
-
-func (v *dbVote) toModel(ctx storage.Context) *models.Vote {
- vote := &models.Vote{
- CreatedAt: v.CreatedAt,
- User: &models.VoteUser{
- ID: v.User.ID,
- Name: v.User.Name,
- Email: v.User.Email,
- AvatarURL: buildAvatarURL(ctx, models.AvatarType(v.User.AvatarType), v.User.ID, v.User.Name, v.User.AvatarBlobKey),
- },
- }
- return vote
-}
-
-// PostStorage contains read and write operations for posts
-type PostStorage struct {
- trx *dbx.Trx
- tenant *models.Tenant
- user *models.User
- ctx storage.Context
-}
-
-// NewPostStorage creates a new PostStorage
-func NewPostStorage(trx *dbx.Trx, ctx storage.Context) *PostStorage {
- return &PostStorage{
- trx: trx,
- ctx: ctx,
- }
-}
-
-// SetCurrentTenant to current context
-func (s *PostStorage) SetCurrentTenant(tenant *models.Tenant) {
- s.tenant = tenant
-}
-
-// SetCurrentUser to current context
-func (s *PostStorage) SetCurrentUser(user *models.User) {
- s.user = user
-}
-
-var (
- sqlSelectPostsWhere = ` WITH
- agg_tags AS (
- SELECT
- post_id,
- ARRAY_REMOVE(ARRAY_AGG(tags.slug), NULL) as tags
- FROM post_tags
- INNER JOIN tags
- ON tags.ID = post_tags.TAG_ID
- AND tags.tenant_id = post_tags.tenant_id
- WHERE post_tags.tenant_id = $1
- %s
- GROUP BY post_id
- ),
- agg_comments AS (
- SELECT
- post_id,
- COUNT(CASE WHEN comments.created_at > CURRENT_DATE - INTERVAL '30 days' THEN 1 END) as recent,
- COUNT(*) as all
- FROM comments
- INNER JOIN posts
- ON posts.id = comments.post_id
- AND posts.tenant_id = comments.tenant_id
- WHERE posts.tenant_id = $1
- AND comments.deleted_at IS NULL
- GROUP BY post_id
- ),
- agg_votes AS (
- SELECT
- post_id,
- COUNT(CASE WHEN post_votes.created_at > CURRENT_DATE - INTERVAL '30 days' THEN 1 END) as recent,
- COUNT(*) as all
- FROM post_votes
- INNER JOIN posts
- ON posts.id = post_votes.post_id
- AND posts.tenant_id = post_votes.tenant_id
- WHERE posts.tenant_id = $1
- GROUP BY post_id
- )
- SELECT p.id,
- p.number,
- p.title,
- p.slug,
- p.description,
- p.created_at,
- COALESCE(agg_s.all, 0) as votes_count,
- COALESCE(agg_c.all, 0) as comments_count,
- COALESCE(agg_s.recent, 0) AS recent_votes_count,
- COALESCE(agg_c.recent, 0) AS recent_comments_count,
- p.status,
- u.id AS user_id,
- u.name AS user_name,
- u.email AS user_email,
- u.role AS user_role,
- u.status AS user_status,
- u.avatar_type AS user_avatar_type,
- u.avatar_bkey AS user_avatar_bkey,
- p.response,
- p.response_date,
- r.id AS response_user_id,
- r.name AS response_user_name,
- r.email AS response_user_email,
- r.role AS response_user_role,
- r.status AS response_user_status,
- r.avatar_type AS response_user_avatar_type,
- r.avatar_bkey AS response_user_avatar_bkey,
- d.number AS original_number,
- d.title AS original_title,
- d.slug AS original_slug,
- d.status AS original_status,
- COALESCE(agg_t.tags, ARRAY[]::text[]) AS tags,
- COALESCE(%s, false) AS has_voted
- FROM posts p
- INNER JOIN users u
- ON u.id = p.user_id
- AND u.tenant_id = $1
- LEFT JOIN users r
- ON r.id = p.response_user_id
- AND r.tenant_id = $1
- LEFT JOIN posts d
- ON d.id = p.original_id
- AND d.tenant_id = $1
- LEFT JOIN agg_comments agg_c
- ON agg_c.post_id = p.id
- LEFT JOIN agg_votes agg_s
- ON agg_s.post_id = p.id
- LEFT JOIN agg_tags agg_t
- ON agg_t.post_id = p.id
- WHERE p.status != ` + strconv.Itoa(int(models.PostDeleted)) + ` AND %s`
-)
-
-func (s *PostStorage) getPostQuery(filter string) string {
- tagCondition := `AND tags.is_public = true`
- if s.user != nil && s.user.IsCollaborator() {
- tagCondition = ``
- }
- hasVotedSubQuery := "null"
- if s.user != nil {
- hasVotedSubQuery = fmt.Sprintf("(SELECT true FROM post_votes WHERE post_id = p.id AND user_id = %d)", s.user.ID)
- }
- return fmt.Sprintf(sqlSelectPostsWhere, tagCondition, hasVotedSubQuery, filter)
-}
-
-func (s *PostStorage) getSingle(query string, args ...interface{}) (*models.Post, error) {
- post := dbPost{}
-
- if err := s.trx.Get(&post, query, args...); err != nil {
- return nil, err
- }
-
- return post.toModel(s.ctx), nil
-}
-
-// GetByID returns post by given id
-func (s *PostStorage) GetByID(postID int) (*models.Post, error) {
- post, err := s.getSingle(s.getPostQuery("p.tenant_id = $1 AND p.id = $2"), s.tenant.ID, postID)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get post with id '%d'", postID)
- }
- return post, nil
-}
-
-// GetBySlug returns post by tenant and slug
-func (s *PostStorage) GetBySlug(slug string) (*models.Post, error) {
- post, err := s.getSingle(s.getPostQuery("p.tenant_id = $1 AND p.slug = $2"), s.tenant.ID, slug)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get post with slug '%s'", slug)
- }
- return post, nil
-}
-
-// GetByNumber returns post by tenant and number
-func (s *PostStorage) GetByNumber(number int) (*models.Post, error) {
- post, err := s.getSingle(s.getPostQuery("p.tenant_id = $1 AND p.number = $2"), s.tenant.ID, number)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get post with number '%d'", number)
- }
- return post, nil
-}
-
-// GetAll returns all tenant posts
-func (s *PostStorage) GetAll() ([]*models.Post, error) {
- posts, err := s.Search("", "all", "all", []string{})
- if err != nil {
- return nil, errors.Wrap(err, "failed to get all posts")
- }
- return posts, nil
-}
-
-// CountPerStatus returns total number of posts per status
-func (s *PostStorage) CountPerStatus() (map[models.PostStatus]int, error) {
- stats := []*dbStatusCount{}
- err := s.trx.Select(&stats, "SELECT status, COUNT(*) AS count FROM posts WHERE tenant_id = $1 GROUP BY status", s.tenant.ID)
- if err != nil {
- return nil, errors.Wrap(err, "failed to count posts per status")
- }
- result := make(map[models.PostStatus]int, len(stats))
- for _, v := range stats {
- result[v.Status] = v.Count
- }
- return result, nil
-}
-
-// Search existing posts based on input
-func (s *PostStorage) Search(query, view, limit string, tags []string) ([]*models.Post, error) {
- innerQuery := s.getPostQuery("p.tenant_id = $1 AND p.status = ANY($2)")
-
- if limit != "all" {
- if _, err := strconv.Atoi(limit); err != nil {
- limit = "30"
- }
- }
-
- var (
- posts []*dbPost
- err error
- )
- if query != "" {
- scoreField := "ts_rank(setweight(to_tsvector(title), 'A') || setweight(to_tsvector(description), 'B'), to_tsquery('english', $3)) + similarity(title, $4) + similarity(description, $4)"
- sql := fmt.Sprintf(`
- SELECT * FROM (%s) AS q
- WHERE %s > 0.1
- ORDER BY %s DESC
- LIMIT %s
- `, innerQuery, scoreField, scoreField, limit)
- err = s.trx.Select(&posts, sql, s.tenant.ID, pq.Array([]models.PostStatus{
- models.PostOpen,
- models.PostStarted,
- models.PostPlanned,
- models.PostCompleted,
- models.PostDeclined,
- }), ToTSQuery(query), query)
- } else {
- condition, statuses, sort := getViewData(view)
- sql := fmt.Sprintf(`
- SELECT * FROM (%s) AS q
- WHERE tags @> $3 %s
- ORDER BY %s DESC
- LIMIT %s
- `, innerQuery, condition, sort, limit)
- err = s.trx.Select(&posts, sql, s.tenant.ID, pq.Array(statuses), pq.Array(tags))
- }
-
- if err != nil {
- return nil, errors.Wrap(err, "failed to search posts")
- }
-
- var result = make([]*models.Post, len(posts))
- for i, post := range posts {
- result[i] = post.toModel(s.ctx)
- }
- return result, nil
-}
-
-// GetCommentsByPost returns all comments from given post
-func (s *PostStorage) GetCommentsByPost(post *models.Post) ([]*models.Comment, error) {
- comments := []*dbComment{}
- err := s.trx.Select(&comments,
- `WITH agg_attachments AS (
- SELECT
- c.id as comment_id,
- ARRAY_REMOVE(ARRAY_AGG(at.attachment_bkey), NULL) as attachment_bkeys
- FROM attachments at
- INNER JOIN comments c
- ON at.tenant_id = c.tenant_id
- AND at.post_id = c.post_id
- AND at.comment_id = c.id
- WHERE at.post_id = $1
- AND at.tenant_id = $2
- AND at.comment_id IS NOT NULL
- GROUP BY c.id
- )
- SELECT c.id,
- c.content,
- c.created_at,
- c.edited_at,
- u.id AS user_id,
- u.name AS user_name,
- u.email AS user_email,
- u.role AS user_role,
- u.status AS user_status,
- u.avatar_type AS user_avatar_type,
- u.avatar_bkey AS user_avatar_bkey,
- e.id AS edited_by_id,
- e.name AS edited_by_name,
- e.email AS edited_by_email,
- e.role AS edited_by_role,
- e.status AS edited_by_status,
- e.avatar_type AS edited_by_avatar_type,
- e.avatar_bkey AS edited_by_avatar_bkey,
- at.attachment_bkeys
- FROM comments c
- INNER JOIN posts p
- ON p.id = c.post_id
- AND p.tenant_id = c.tenant_id
- INNER JOIN users u
- ON u.id = c.user_id
- AND u.tenant_id = c.tenant_id
- LEFT JOIN users e
- ON e.id = c.edited_by_id
- AND e.tenant_id = c.tenant_id
- LEFT JOIN agg_attachments at
- ON at.comment_id = c.id
- WHERE p.id = $1
- AND p.tenant_id = $2
- AND c.deleted_at IS NULL
- ORDER BY c.created_at ASC`, post.ID, s.tenant.ID)
- if err != nil {
- return nil, errors.Wrap(err, "failed get comments of post with id '%d'", post.ID)
- }
-
- var result = make([]*models.Comment, len(comments))
- for i, comment := range comments {
- result[i] = comment.toModel(s.ctx)
- }
- return result, nil
-}
-
-// Update given post
-func (s *PostStorage) Update(post *models.Post, title, description string) (*models.Post, error) {
- _, err := s.trx.Execute(`UPDATE posts SET title = $1, slug = $2, description = $3
- WHERE id = $4 AND tenant_id = $5`, title, slug.Make(title), description, post.ID, s.tenant.ID)
- if err != nil {
- return nil, errors.Wrap(err, "failed update post")
- }
-
- post.Slug = slug.Make(title)
- post.Title = title
- post.Description = description
-
- return post, nil
-}
-
-// Add a new post in the database
-func (s *PostStorage) Add(title, description string) (*models.Post, error) {
- var id int
- err := s.trx.Get(&id,
- `INSERT INTO posts (title, slug, number, description, tenant_id, user_id, created_at, status)
- VALUES ($1, $2, (SELECT COALESCE(MAX(number), 0) + 1 FROM posts p WHERE p.tenant_id = $4), $3, $4, $5, $6, 0)
- RETURNING id`, title, slug.Make(title), description, s.tenant.ID, s.user.ID, time.Now())
- if err != nil {
- return nil, errors.Wrap(err, "failed add new post")
- }
-
- post, err := s.GetByID(id)
- if err != nil {
- return nil, err
- }
-
- if err := s.internalAddSubscriber(post, s.user, false); err != nil {
- return nil, err
- }
-
- return post, nil
-}
-
-// AddComment places a new comment on an post
-func (s *PostStorage) AddComment(post *models.Post, content string) (int, error) {
- var id int
- if err := s.trx.Get(&id, `
- INSERT INTO comments (tenant_id, post_id, content, user_id, created_at)
- VALUES ($1, $2, $3, $4, $5)
- RETURNING id
- `, s.tenant.ID, post.ID, content, s.user.ID, time.Now()); err != nil {
- return 0, errors.Wrap(err, "failed add new comment")
- }
-
- if err := s.internalAddSubscriber(post, s.user, false); err != nil {
- return 0, err
- }
-
- return id, nil
-}
-
-// DeleteComment by its id
-func (s *PostStorage) DeleteComment(id int) error {
- if _, err := s.trx.Execute(
- "UPDATE comments SET deleted_at = $1, deleted_by_id = $2 WHERE id = $3 AND tenant_id = $4",
- time.Now(), s.user.ID, id, s.tenant.ID,
- ); err != nil {
- return errors.Wrap(err, "failed delete comment")
- }
- return nil
-}
-
-// GetCommentByID returns a comment by given ID
-func (s *PostStorage) GetCommentByID(id int) (*models.Comment, error) {
- comment := dbComment{}
- err := s.trx.Get(&comment,
- `SELECT c.id,
- c.content,
- c.created_at,
- c.edited_at,
- u.id AS user_id,
- u.name AS user_name,
- u.email AS user_email,
- u.role AS user_role,
- u.status AS user_status,
- u.avatar_type AS user_avatar_type,
- u.avatar_bkey AS user_avatar_bkey,
- e.id AS edited_by_id,
- e.name AS edited_by_name,
- e.email AS edited_by_email,
- e.role AS edited_by_role,
- e.status AS edited_by_status,
- e.avatar_type AS edited_by_avatar_type,
- e.avatar_bkey AS edited_by_avatar_bkey
- FROM comments c
- INNER JOIN users u
- ON u.id = c.user_id
- AND u.tenant_id = c.tenant_id
- LEFT JOIN users e
- ON e.id = c.edited_by_id
- AND e.tenant_id = c.tenant_id
- WHERE c.id = $1
- AND c.tenant_id = $2
- AND c.deleted_at IS NULL`, id, s.tenant.ID)
-
- if err != nil {
- return nil, err
- }
-
- return comment.toModel(s.ctx), nil
-}
-
-// UpdateComment with given ID and content
-func (s *PostStorage) UpdateComment(id int, content string) error {
- _, err := s.trx.Execute(`
- UPDATE comments SET content = $1, edited_at = $2, edited_by_id = $3
- WHERE id = $4 AND tenant_id = $5`, content, time.Now(), s.user.ID, id, s.tenant.ID)
- if err != nil {
- return errors.Wrap(err, "failed update comment")
- }
- return nil
-}
-
-// AddVote adds user to post list of votes
-func (s *PostStorage) AddVote(post *models.Post, user *models.User) error {
- if !post.CanBeVoted() {
- return nil
- }
-
- _, err := s.trx.Execute(
- `INSERT INTO post_votes (tenant_id, user_id, post_id, created_at) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING`,
- s.tenant.ID, user.ID, post.ID, time.Now())
-
- if err != nil {
- return errors.Wrap(err, "failed add vote to post")
- }
-
- return s.internalAddSubscriber(post, user, false)
-}
-
-// RemoveVote removes user from post list of votes
-func (s *PostStorage) RemoveVote(post *models.Post, user *models.User) error {
- if !post.CanBeVoted() {
- return nil
- }
-
- _, err := s.trx.Execute(`DELETE FROM post_votes WHERE user_id = $1 AND post_id = $2 AND tenant_id = $3`, user.ID, post.ID, s.tenant.ID)
- if err != nil {
- return errors.Wrap(err, "failed to remove vote from post")
- }
-
- return err
-}
-
-// AddSubscriber adds user to the post list of subscribers
-func (s *PostStorage) AddSubscriber(post *models.Post, user *models.User) error {
- return s.internalAddSubscriber(post, user, true)
-}
-
-func (s *PostStorage) internalAddSubscriber(post *models.Post, user *models.User, force bool) error {
- conflict := " DO NOTHING"
- if force {
- conflict = "(user_id, post_id) DO UPDATE SET status = $5, updated_at = $4"
- }
-
- _, err := s.trx.Execute(fmt.Sprintf(`
- INSERT INTO post_subscribers (tenant_id, user_id, post_id, created_at, updated_at, status)
- VALUES ($1, $2, $3, $4, $4, $5) ON CONFLICT %s`, conflict),
- s.tenant.ID, user.ID, post.ID, time.Now(), models.SubscriberActive,
- )
- if err != nil {
- return errors.Wrap(err, "failed insert post subscriber")
- }
- return nil
-}
-
-// RemoveSubscriber removes user from post list of subscribers
-func (s *PostStorage) RemoveSubscriber(post *models.Post, user *models.User) error {
- _, err := s.trx.Execute(`
- INSERT INTO post_subscribers (tenant_id, user_id, post_id, created_at, updated_at, status)
- VALUES ($1, $2, $3, $4, $4, 0) ON CONFLICT (user_id, post_id)
- DO UPDATE SET status = 0, updated_at = $4`,
- s.tenant.ID, user.ID, post.ID, time.Now(),
- )
- if err != nil {
- return errors.Wrap(err, "failed remove post subscriber")
- }
- return nil
-}
-
-// GetActiveSubscribers based on input and settings
-func (s *PostStorage) GetActiveSubscribers(number int, channel models.NotificationChannel, event models.NotificationEvent) ([]*models.User, error) {
- var (
- users []*dbUser
- err error
- )
-
- if len(event.RequiresSubscriptionUserRoles) == 0 {
- err = s.trx.Select(&users, `
- SELECT DISTINCT u.id, u.name, u.email, u.tenant_id, u.role, u.status
- FROM users u
- LEFT JOIN user_settings set
- ON set.user_id = u.id
- AND set.tenant_id = u.tenant_id
- AND set.key = $1
- WHERE u.tenant_id = $2
- AND u.status = $5
- AND (
- (set.value IS NULL AND u.role = ANY($3))
- OR CAST(set.value AS integer) & $4 > 0
- )
- ORDER by u.id`,
- event.UserSettingsKeyName,
- s.tenant.ID,
- pq.Array(event.DefaultEnabledUserRoles),
- channel,
- models.UserActive,
- )
- } else {
- err = s.trx.Select(&users, `
- SELECT DISTINCT u.id, u.name, u.email, u.tenant_id, u.role, u.status
- FROM users u
- LEFT JOIN post_subscribers sub
- ON sub.user_id = u.id
- AND sub.post_id = (SELECT id FROM posts p WHERE p.tenant_id = $4 and p.number = $1 LIMIT 1)
- AND sub.tenant_id = u.tenant_id
- LEFT JOIN user_settings set
- ON set.user_id = u.id
- AND set.key = $3
- AND set.tenant_id = u.tenant_id
- WHERE u.tenant_id = $4
- AND u.status = $8
- AND ( sub.status = $2 OR (sub.status IS NULL AND NOT u.role = ANY($7)) )
- AND (
- (set.value IS NULL AND u.role = ANY($5))
- OR CAST(set.value AS integer) & $6 > 0
- )
- ORDER by u.id`,
- number,
- models.SubscriberActive,
- event.UserSettingsKeyName,
- s.tenant.ID,
- pq.Array(event.DefaultEnabledUserRoles),
- channel,
- pq.Array(event.RequiresSubscriptionUserRoles),
- models.UserActive,
- )
- }
-
- if err != nil {
- return nil, errors.Wrap(err, "failed to get post number '%d' subscribers", number)
- }
-
- var result = make([]*models.User, len(users))
- for i, user := range users {
- result[i] = user.toModel(s.ctx)
- }
- return result, nil
-}
-
-// SetResponse changes current post response
-func (s *PostStorage) SetResponse(post *models.Post, text string, status models.PostStatus) error {
- if status == models.PostDuplicate {
- return errors.New("Use MarkAsDuplicate to change an post status to Duplicate")
- }
-
- respondedAt := time.Now()
- if post.Status == status && post.Response != nil {
- respondedAt = post.Response.RespondedAt
- }
-
- _, err := s.trx.Execute(`
- UPDATE posts
- SET response = $3, original_id = NULL, response_date = $4, response_user_id = $5, status = $6
- WHERE id = $1 and tenant_id = $2
- `, post.ID, s.tenant.ID, text, respondedAt, s.user.ID, status)
- if err != nil {
- return errors.Wrap(err, "failed to update post's response")
- }
-
- post.Status = status
- post.Response = &models.PostResponse{
- Text: text,
- RespondedAt: respondedAt,
- User: s.user,
- }
- return nil
-}
-
-// MarkAsDuplicate set post as a duplicate of another post
-func (s *PostStorage) MarkAsDuplicate(post *models.Post, original *models.Post) error {
- respondedAt := time.Now()
- if post.Status == models.PostDuplicate && post.Response != nil {
- respondedAt = post.Response.RespondedAt
- }
-
- var users []*dbUser
- err := s.trx.Select(&users, "SELECT user_id AS id FROM post_votes WHERE post_id = $1 AND tenant_id = $2", post.ID, s.tenant.ID)
- if err != nil {
- return errors.Wrap(err, "failed to get votes of post with id '%d'", post.ID)
- }
-
- for _, u := range users {
- if err := s.AddVote(original, u.toModel(s.ctx)); err != nil {
- return err
- }
- }
-
- _, err = s.trx.Execute(`
- UPDATE posts
- SET response = '', original_id = $3, response_date = $4, response_user_id = $5, status = $6
- WHERE id = $1 and tenant_id = $2
- `, post.ID, s.tenant.ID, original.ID, respondedAt, s.user.ID, models.PostDuplicate)
- if err != nil {
- return errors.Wrap(err, "failed to update post's response")
- }
-
- post.Status = models.PostDuplicate
- post.Response = &models.PostResponse{
- RespondedAt: respondedAt,
- User: s.user,
- Original: &models.OriginalPost{
- Number: original.Number,
- Title: original.Title,
- Slug: original.Slug,
- Status: original.Status,
- },
- }
- return nil
-}
-
-// IsReferenced returns true if another post is referencing given post
-func (s *PostStorage) IsReferenced(post *models.Post) (bool, error) {
- exists, err := s.trx.Exists(`
- SELECT 1 FROM posts p
- INNER JOIN posts o
- ON o.tenant_id = p.tenant_id
- AND o.id = p.original_id
- WHERE p.tenant_id = $1
- AND o.id = $2`, s.tenant.ID, post.ID)
- if err != nil {
- return false, errors.Wrap(err, "failed to check if post is referenced")
- }
- return exists, nil
-}
-
-// VotedBy returns a list of Post ID voted by given user
-func (s *PostStorage) VotedBy() ([]int, error) {
- posts, err := s.trx.QueryIntArray("SELECT post_id FROM post_votes WHERE user_id = $1 AND tenant_id = $2", s.user.ID, s.tenant.ID)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get user's voted posts")
- }
- return posts, nil
-}
-
-// ListVotes returns a list of all votes on given post
-func (s *PostStorage) ListVotes(post *models.Post, limit int) ([]*models.Vote, error) {
- sqlLimit := "ALL"
- if limit > 0 {
- sqlLimit = strconv.Itoa(limit)
- }
-
- votes := []*dbVote{}
- err := s.trx.Select(&votes, `
- SELECT
- pv.created_at,
- u.id AS user_id,
- u.name AS user_name,
- u.email AS user_email,
- u.avatar_type AS user_avatar_type,
- u.avatar_bkey AS user_avatar_bkey
- FROM post_votes pv
- INNER JOIN users u
- ON u.id = pv.user_id
- AND u.tenant_id = pv.tenant_id
- WHERE pv.post_id = $1
- AND pv.tenant_id = $2
- ORDER BY pv.created_at
- LIMIT `+sqlLimit, post.ID, s.tenant.ID)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get votes of post")
- }
-
- var result = make([]*models.Vote, len(votes))
- for i, vote := range votes {
- result[i] = vote.toModel(s.ctx)
- }
- return result, nil
-}
-
-// GetAttachments for given post or comment
-func (s *PostStorage) GetAttachments(post *models.Post, comment *models.Comment) ([]string, error) {
- postID := post.ID
- var commentID sql.NullInt64
- if comment != nil {
- commentID.Scan(comment.ID)
- }
-
- type entry struct {
- BlobKey string `db:"attachment_bkey"`
- }
-
- entries := []*entry{}
- err := s.trx.Select(&entries, `
- SELECT attachment_bkey
- FROM attachments
- WHERE tenant_id = $1 AND post_id = $2 AND (comment_id = $3 OR ($3 IS NULL AND comment_id IS NULL))
- `, s.tenant.ID, postID, commentID)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get attachments")
- }
-
- var result = make([]string, len(entries))
- for i, entry := range entries {
- result[i] = entry.BlobKey
- }
- return result, nil
-}
-
-// SetAttachments on given post or comment
-func (s *PostStorage) SetAttachments(post *models.Post, comment *models.Comment, attachments []*models.ImageUpload) error {
- postID := post.ID
- var commentID sql.NullInt64
- if comment != nil {
- commentID.Scan(comment.ID)
- }
-
- for _, attachment := range attachments {
- if attachment.Remove {
- if _, err := s.trx.Execute(
- "DELETE FROM attachments WHERE tenant_id = $1 AND post_id = $2 AND (comment_id = $3 OR ($3 IS NULL AND comment_id IS NULL)) AND attachment_bkey = $4",
- s.tenant.ID, postID, commentID, attachment.BlobKey,
- ); err != nil {
- return errors.Wrap(err, "failed to delete attachment")
- }
- } else {
- if _, err := s.trx.Execute(
- "INSERT INTO attachments (tenant_id, post_id, comment_id, user_id, attachment_bkey) VALUES ($1, $2, $3, $4, $5)",
- s.tenant.ID, postID, commentID, s.user.ID, attachment.BlobKey,
- ); err != nil {
- return errors.Wrap(err, "failed to insert attachment")
- }
- }
- }
-
- return nil
-}
diff --git a/app/storage/postgres/post_test.go b/app/storage/postgres/post_test.go
deleted file mode 100644
index 36fae140f..000000000
--- a/app/storage/postgres/post_test.go
+++ /dev/null
@@ -1,638 +0,0 @@
-package postgres_test
-
-import (
- "io/ioutil"
- "testing"
- "time"
-
- "github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/errors"
-)
-
-func TestPostStorage_GetAll(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- now := time.Now()
-
- trx.Execute("INSERT INTO posts (title, slug, number, description, created_at, tenant_id, user_id, status) VALUES ('add twitter integration', 'add-twitter-integration', 1, 'Would be great to see it integrated with twitter', $1, 1, 1, 1)", now)
- trx.Execute("INSERT INTO posts (title, slug, number, description, created_at, tenant_id, user_id, status) VALUES ('this is my post', 'this-is-my-post', 2, 'no description', $1, 1, 2, 2)", now)
-
- posts.SetCurrentTenant(demoTenant)
-
- dbPosts, err := posts.GetAll()
- Expect(err).IsNil()
- Expect(dbPosts).HasLen(2)
-
- Expect(dbPosts[0].Title).Equals("this is my post")
- Expect(dbPosts[0].Slug).Equals("this-is-my-post")
- Expect(dbPosts[0].Number).Equals(2)
- Expect(dbPosts[0].Description).Equals("no description")
- Expect(dbPosts[0].User.Name).Equals("Arya Stark")
- Expect(dbPosts[0].VotesCount).Equals(0)
- Expect(dbPosts[0].Status).Equals(models.PostCompleted)
-
- Expect(dbPosts[1].Title).Equals("add twitter integration")
- Expect(dbPosts[1].Slug).Equals("add-twitter-integration")
- Expect(dbPosts[1].Number).Equals(1)
- Expect(dbPosts[1].Description).Equals("Would be great to see it integrated with twitter")
- Expect(dbPosts[1].User.Name).Equals("Jon Snow")
- Expect(dbPosts[1].VotesCount).Equals(0)
- Expect(dbPosts[1].Status).Equals(models.PostStarted)
-
- dbPosts, err = posts.Search("twitter", "trending", "10", []string{})
- Expect(err).IsNil()
- Expect(dbPosts).HasLen(1)
- Expect(dbPosts[0].Slug).Equals("add-twitter-integration")
-
- dbPosts, err = posts.Search("twitter", "trending", "0", []string{})
- Expect(err).IsNil()
- Expect(dbPosts).HasLen(0)
-}
-
-func TestPostStorage_AddAndGet(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- post, err := posts.Add("My new post", "with this description")
- Expect(err).IsNil()
-
- dbPostByID, err := posts.GetByID(post.ID)
- Expect(err).IsNil()
- Expect(dbPostByID.ID).Equals(post.ID)
- Expect(dbPostByID.Number).Equals(1)
- Expect(dbPostByID.HasVoted).IsFalse()
- Expect(dbPostByID.VotesCount).Equals(0)
- Expect(dbPostByID.Status).Equals(models.PostOpen)
- Expect(dbPostByID.Title).Equals("My new post")
- Expect(dbPostByID.Description).Equals("with this description")
- Expect(dbPostByID.User.ID).Equals(1)
- Expect(dbPostByID.User.Name).Equals("Jon Snow")
- Expect(dbPostByID.User.Email).Equals("[email protected]")
-
- dbPostBySlug, err := posts.GetBySlug("my-new-post")
-
- Expect(err).IsNil()
- Expect(dbPostBySlug.ID).Equals(post.ID)
- Expect(dbPostBySlug.Number).Equals(1)
- Expect(dbPostBySlug.HasVoted).IsFalse()
- Expect(dbPostBySlug.VotesCount).Equals(0)
- Expect(dbPostBySlug.Status).Equals(models.PostOpen)
- Expect(dbPostBySlug.Title).Equals("My new post")
- Expect(dbPostBySlug.Description).Equals("with this description")
- Expect(dbPostBySlug.User.ID).Equals(1)
- Expect(dbPostBySlug.User.Name).Equals("Jon Snow")
- Expect(dbPostBySlug.User.Email).Equals("[email protected]")
-}
-
-func TestPostStorage_GetInvalid(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
-
- dbPost, err := posts.GetByID(1)
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(dbPost).IsNil()
-}
-
-func TestPostStorage_AddAndReturnComments(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- post, err := posts.Add("My new post", "with this description")
- Expect(err).IsNil()
-
- posts.SetCurrentUser(jonSnow)
- posts.AddComment(post, "Comment #1")
- posts.SetCurrentUser(aryaStark)
- posts.AddComment(post, "Comment #2")
-
- comments, err := posts.GetCommentsByPost(post)
- Expect(err).IsNil()
- Expect(comments).HasLen(2)
-
- Expect(comments[0].Content).Equals("Comment #1")
- Expect(comments[0].User.Name).Equals("Jon Snow")
- Expect(comments[1].Content).Equals("Comment #2")
- Expect(comments[1].User.Name).Equals("Arya Stark")
-}
-
-func TestPostStorage_AddGetUpdateComment(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- post, err := posts.Add("My new post", "with this description")
- Expect(err).IsNil()
-
- commentID, err := posts.AddComment(post, "Comment #1")
- Expect(err).IsNil()
-
- comment, err := posts.GetCommentByID(commentID)
- Expect(err).IsNil()
- Expect(comment.ID).Equals(commentID)
- Expect(comment.Content).Equals("Comment #1")
- Expect(comment.User.ID).Equals(jonSnow.ID)
- Expect(comment.EditedAt).IsNil()
- Expect(comment.EditedBy).IsNil()
-
- posts.SetCurrentUser(aryaStark)
- err = posts.UpdateComment(commentID, "Comment #1 with edit")
- Expect(err).IsNil()
-
- comment, err = posts.GetCommentByID(commentID)
- Expect(err).IsNil()
- Expect(comment.ID).Equals(commentID)
- Expect(comment.Content).Equals("Comment #1 with edit")
- Expect(comment.User.ID).Equals(jonSnow.ID)
- Expect(comment.EditedAt).IsNotNil()
- Expect(comment.EditedBy.ID).Equals(aryaStark.ID)
-}
-
-func TestPostStorage_AddDeleteComment(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- post, err := posts.Add("My new post", "with this description")
- Expect(err).IsNil()
-
- commentID, err := posts.AddComment(post, "Comment #1")
- Expect(err).IsNil()
-
- err = posts.DeleteComment(commentID)
- Expect(err).IsNil()
-
- comment, err := posts.GetCommentByID(commentID)
- Expect(err).Equals(app.ErrNotFound)
- Expect(comment).IsNil()
-}
-
-func TestPostStorage_AddAndGet_DifferentTenants(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- demoPost, err := posts.Add("My new post", "with this description")
- Expect(err).IsNil()
-
- posts.SetCurrentTenant(avengersTenant)
- posts.SetCurrentUser(tonyStark)
- avengersPost, err := posts.Add("My other post", "with other description")
- Expect(err).IsNil()
-
- posts.SetCurrentTenant(demoTenant)
- dbPost, err := posts.GetByNumber(1)
-
- Expect(err).IsNil()
- Expect(dbPost.ID).Equals(demoPost.ID)
- Expect(dbPost.Number).Equals(1)
- Expect(dbPost.Title).Equals("My new post")
- Expect(dbPost.Slug).Equals("my-new-post")
-
- posts.SetCurrentTenant(avengersTenant)
- dbPost, err = posts.GetByNumber(1)
-
- Expect(err).IsNil()
- Expect(dbPost.ID).Equals(avengersPost.ID)
- Expect(dbPost.Number).Equals(1)
- Expect(dbPost.Title).Equals("My other post")
- Expect(dbPost.Slug).Equals("my-other-post")
-}
-
-func TestPostStorage_Update(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
-
- post, err := posts.Add("My new post", "with this description")
- Expect(err).IsNil()
-
- post, err = posts.Update(post, "The new comment", "With the new description")
- Expect(err).IsNil()
- Expect(post.Title).Equals("The new comment")
- Expect(post.Description).Equals("With the new description")
- Expect(post.Slug).Equals("the-new-comment")
-}
-
-func TestPostStorage_AddVote(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
-
- post, err := posts.Add("My new post", "with this description")
- Expect(err).IsNil()
-
- err = posts.AddVote(post, aryaStark)
- Expect(err).IsNil()
-
- dbPost, err := posts.GetByNumber(1)
- Expect(dbPost.HasVoted).IsFalse()
- Expect(dbPost.VotesCount).Equals(1)
-
- err = posts.AddVote(post, jonSnow)
- Expect(err).IsNil()
-
- dbPost, err = posts.GetByNumber(1)
- Expect(err).IsNil()
- Expect(dbPost.HasVoted).IsTrue()
- Expect(dbPost.VotesCount).Equals(2)
-}
-
-func TestPostStorage_AddVote_Twice(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
-
- post, _ := posts.Add("My new post", "with this description")
-
- err := posts.AddVote(post, jonSnow)
- Expect(err).IsNil()
-
- err = posts.AddVote(post, jonSnow)
- Expect(err).IsNil()
-
- dbPost, err := posts.GetByNumber(1)
- Expect(err).IsNil()
- Expect(dbPost.VotesCount).Equals(1)
-}
-
-func TestPostStorage_RemoveVote(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
-
- post, _ := posts.Add("My new post", "with this description")
-
- err := posts.AddVote(post, jonSnow)
- Expect(err).IsNil()
-
- err = posts.RemoveVote(post, jonSnow)
- Expect(err).IsNil()
-
- dbPost, err := posts.GetByNumber(1)
- Expect(err).IsNil()
- Expect(dbPost.VotesCount).Equals(0)
-}
-
-func TestPostStorage_RemoveVote_Twice(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
-
- post, _ := posts.Add("My new post", "with this description")
-
- err := posts.AddVote(post, jonSnow)
- Expect(err).IsNil()
-
- err = posts.RemoveVote(post, jonSnow)
- Expect(err).IsNil()
-
- err = posts.RemoveVote(post, jonSnow)
- Expect(err).IsNil()
-
- dbPost, err := posts.GetByNumber(1)
- Expect(err).IsNil()
- Expect(dbPost.VotesCount).Equals(0)
-}
-
-func TestPostStorage_SetResponse(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
-
- post, _ := posts.Add("My new post", "with this description")
- err := posts.SetResponse(post, "We liked this post", models.PostStarted)
-
- Expect(err).IsNil()
-
- post, _ = posts.GetByID(post.ID)
- Expect(post.Response.Text).Equals("We liked this post")
- Expect(post.Status).Equals(models.PostStarted)
- Expect(post.Response.User.ID).Equals(1)
-}
-
-func TestPostStorage_SetResponse_KeepOpen(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
-
- post, _ := posts.Add("My new post", "with this description")
- err := posts.SetResponse(post, "We liked this post", models.PostOpen)
- Expect(err).IsNil()
-}
-
-func TestPostStorage_SetResponse_ChangeText(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
-
- post, _ := posts.Add("My new post", "with this description")
- posts.SetResponse(post, "We liked this post", models.PostStarted)
- post, _ = posts.GetByID(post.ID)
- respondedAt := post.Response.RespondedAt
-
- posts.SetResponse(post, "We liked this post and we'll work on it", models.PostStarted)
- post, _ = posts.GetByID(post.ID)
- Expect(post.Response.RespondedAt).Equals(respondedAt)
-
- posts.SetResponse(post, "We finished it", models.PostCompleted)
- post, _ = posts.GetByID(post.ID)
- Expect(post.Response.RespondedAt).TemporarilySimilar(respondedAt, time.Second)
-}
-
-func TestPostStorage_SetResponse_AsDuplicate(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
-
- post1, _ := posts.Add("My new post", "with this description")
- posts.AddVote(post1, jonSnow)
-
- posts.SetCurrentUser(aryaStark)
- post2, _ := posts.Add("My other post", "with similar description")
- posts.AddVote(post2, aryaStark)
-
- posts.SetCurrentUser(jonSnow)
- posts.MarkAsDuplicate(post2, post1)
- post1, _ = posts.GetByID(post1.ID)
-
- Expect(post1.VotesCount).Equals(2)
- Expect(post1.Status).Equals(models.PostOpen)
- Expect(post1.Response).IsNil()
-
- post2, _ = posts.GetByID(post2.ID)
-
- Expect(post2.Response.Text).Equals("")
- Expect(post2.VotesCount).Equals(1)
- Expect(post2.Status).Equals(models.PostDuplicate)
- Expect(post2.Response.User.ID).Equals(1)
- Expect(post2.Response.Original.Number).Equals(post1.Number)
- Expect(post2.Response.Original.Title).Equals(post1.Title)
- Expect(post2.Response.Original.Slug).Equals(post1.Slug)
- Expect(post2.Response.Original.Status).Equals(post1.Status)
-}
-
-func TestPostStorage_SetResponse_AsDeleted(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- post, err := posts.Add("My new post", "with this description")
- Expect(err).IsNil()
-
- posts.SetResponse(post, "Spam!", models.PostDeleted)
-
- post1, err := posts.GetByNumber(post.Number)
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(post1).IsNil()
-
- post2, err := posts.GetByID(post.ID)
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(post2).IsNil()
-}
-
-func TestPostStorage_AddVote_ClosedPost(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- post, _ := posts.Add("My new post", "with this description")
- posts.SetResponse(post, "We liked this post", models.PostCompleted)
- posts.AddVote(post, jonSnow)
-
- dbPost, err := posts.GetByNumber(post.Number)
- Expect(err).IsNil()
- Expect(dbPost.VotesCount).Equals(0)
-}
-
-func TestPostStorage_RemoveVote_ClosedPost(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- post, _ := posts.Add("My new post", "with this description")
- posts.AddVote(post, jonSnow)
- posts.SetResponse(post, "We liked this post", models.PostCompleted)
- posts.RemoveVote(post, jonSnow)
-
- dbPost, err := posts.GetByNumber(post.Number)
- Expect(err).IsNil()
- Expect(dbPost.VotesCount).Equals(1)
-}
-
-func TestPostStorage_ListVotedPosts(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- post1, _ := posts.Add("My new post", "with this description")
- post2, _ := posts.Add("My other post", "with better description")
- posts.AddVote(post1, aryaStark)
- posts.AddVote(post2, aryaStark)
-
- posts.SetCurrentUser(jonSnow)
- arr, err := posts.VotedBy()
- Expect(err).IsNil()
- Expect(arr).Equals([]int{})
-
- posts.SetCurrentUser(aryaStark)
- arr, err = posts.VotedBy()
- Expect(err).IsNil()
- Expect(arr).Equals([]int{post1.ID, post2.ID})
-}
-
-func TestPostStorage_WithTags(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(aryaStark)
- tags.SetCurrentTenant(demoTenant)
- tags.SetCurrentUser(jonSnow)
-
- post, _ := posts.Add("My new post", "with this description")
- bug, _ := tags.Add("Bug", "FF0000", true)
- featureRequest, _ := tags.Add("Feature Request", "00FF00", false)
-
- tags.AssignTag(bug, post)
- tags.AssignTag(featureRequest, post)
-
- post, _ = posts.GetByID(post.ID)
- Expect(post.Tags).HasLen(1)
- Expect(post.Tags[0]).Equals(bug.Slug)
-
- posts.SetCurrentUser(jonSnow)
- post, _ = posts.GetByID(post.ID)
- Expect(post.Tags).HasLen(2)
- Expect(post.Tags[0]).Equals(bug.Slug)
- Expect(post.Tags[1]).Equals(featureRequest.Slug)
-}
-
-func TestPostStorage_IsReferenced(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- post1, _ := posts.Add("My first post", "with this description")
- post2, _ := posts.Add("My second post", "with this description")
- post3, _ := posts.Add("My third post", "with this description")
-
- posts.MarkAsDuplicate(post2, post3)
- posts.MarkAsDuplicate(post3, post1)
-
- referenced, err := posts.IsReferenced(post1)
- Expect(referenced).IsTrue()
- Expect(err).IsNil()
-
- referenced, err = posts.IsReferenced(post2)
- Expect(referenced).IsFalse()
- Expect(err).IsNil()
-
- referenced, err = posts.IsReferenced(post3)
- Expect(referenced).IsTrue()
- Expect(err).IsNil()
-}
-
-func TestPostStorage_ListVotesOfPost(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- post1, _ := posts.Add("My new post", "with this description")
- posts.AddVote(post1, jonSnow)
- posts.AddVote(post1, aryaStark)
-
- users, err := posts.ListVotes(post1, -1)
- Expect(err).IsNil()
- Expect(users).HasLen(2)
-
- Expect(users[0].CreatedAt).TemporarilySimilar(time.Now(), 5*time.Second)
- Expect(users[0].User.Name).Equals("Jon Snow")
- Expect(users[0].User.Email).Equals("[email protected]")
-
- Expect(users[1].CreatedAt).TemporarilySimilar(time.Now(), 5*time.Second)
- Expect(users[1].User.Name).Equals("Arya Stark")
- Expect(users[1].User.Email).Equals("[email protected]")
-}
-
-func TestPostStorage_Attachments(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- post1, _ := posts.Add("My new post", "with this description")
- post2, _ := posts.Add("My other post", "with another description")
-
- attachments, err := posts.GetAttachments(post1, nil)
- Expect(err).IsNil()
- Expect(attachments).HasLen(0)
-
- bytes, err := ioutil.ReadFile(env.Path("favicon.png"))
- Expect(err).IsNil()
-
- err = posts.SetAttachments(post1, nil, []*models.ImageUpload{
- &models.ImageUpload{
- BlobKey: "12345-test.png",
- Upload: &models.ImageUploadData{
- FileName: "test.png",
- ContentType: "image/png",
- Content: bytes,
- },
- },
- })
- Expect(err).IsNil()
-
- attachments, err = posts.GetAttachments(post1, nil)
- Expect(err).IsNil()
- Expect(attachments).HasLen(1)
- Expect(attachments[0]).Equals("12345-test.png")
-
- attachments, err = posts.GetAttachments(post2, nil)
- Expect(err).IsNil()
- Expect(attachments).HasLen(0)
-
- err = posts.SetAttachments(post2, nil, []*models.ImageUpload{
- &models.ImageUpload{
- BlobKey: "12345-test.png",
- Remove: true,
- },
- &models.ImageUpload{
- BlobKey: "67890-test2.png",
- Upload: &models.ImageUploadData{
- FileName: "test2.png",
- ContentType: "image/png",
- Content: bytes,
- },
- },
- &models.ImageUpload{
- BlobKey: "67890-test6.png",
- Upload: &models.ImageUploadData{
- FileName: "test6.png",
- ContentType: "image/png",
- Content: bytes,
- },
- },
- })
- Expect(err).IsNil()
-
- attachments, err = posts.GetAttachments(post1, nil)
- Expect(err).IsNil()
- Expect(attachments).HasLen(1)
- Expect(attachments[0]).Equals("12345-test.png")
-
- attachments, err = posts.GetAttachments(post2, nil)
- Expect(err).IsNil()
- Expect(attachments).HasLen(2)
- Expect(attachments[0]).Equals("67890-test2.png")
- Expect(attachments[1]).Equals("67890-test6.png")
-
- err = posts.SetAttachments(post1, nil, []*models.ImageUpload{
- &models.ImageUpload{
- BlobKey: "12345-test.png",
- Remove: true,
- },
- })
- Expect(err).IsNil()
-
- attachments, err = posts.GetAttachments(post1, nil)
- Expect(err).IsNil()
- Expect(attachments).HasLen(0)
-}
diff --git a/app/storage/postgres/setup_test.go b/app/storage/postgres/setup_test.go
deleted file mode 100644
index 06f141fad..000000000
--- a/app/storage/postgres/setup_test.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package postgres_test
-
-import (
- "fmt"
- "os"
- "testing"
-
- "github.com/getfider/fider/app/models"
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/dbx"
- "github.com/getfider/fider/app/storage/postgres"
-)
-
-var db *dbx.Database
-var trx *dbx.Trx
-
-var tenants *postgres.TenantStorage
-var users *postgres.UserStorage
-var posts *postgres.PostStorage
-var tags *postgres.TagStorage
-var notifications *postgres.NotificationStorage
-var events *postgres.EventStorage
-
-var demoTenant *models.Tenant
-var avengersTenant *models.Tenant
-var gotTenant *models.Tenant
-var jonSnow *models.User
-var aryaStark *models.User
-var sansaStark *models.User
-var tonyStark *models.User
-
-type Context struct{}
-
-func (c Context) TenantAssetsURL(path string, a ...interface{}) string {
- return "http://cdn.test.fider.io" + fmt.Sprintf(path, a...)
-}
-
-func SetupDatabaseTest(t *testing.T) {
- RegisterT(t)
- trx, _ = db.Begin()
- ctx := &Context{}
-
- tenants = postgres.NewTenantStorage(trx)
- users = postgres.NewUserStorage(trx, ctx)
- posts = postgres.NewPostStorage(trx, ctx)
- tags = postgres.NewTagStorage(trx)
- notifications = postgres.NewNotificationStorage(trx)
- events = postgres.NewEventStorage(trx)
-
- demoTenant, _ = tenants.GetByDomain("demo")
- avengersTenant, _ = tenants.GetByDomain("avengers")
-
- users.SetCurrentTenant(demoTenant)
- jonSnow, _ = users.GetByID(1)
- aryaStark, _ = users.GetByID(2)
- sansaStark, _ = users.GetByID(3)
-
- users.SetCurrentTenant(avengersTenant)
- tonyStark, _ = users.GetByID(4)
-}
-
-func TeardownDatabaseTest() {
- trx.Rollback()
-}
-
-func TestMain(m *testing.M) {
- db = dbx.New()
- db.Seed()
- defer db.Close()
-
- code := m.Run()
- os.Exit(code)
-}
diff --git a/app/storage/postgres/subscription_test.go b/app/storage/postgres/subscription_test.go
deleted file mode 100644
index e6f990d66..000000000
--- a/app/storage/postgres/subscription_test.go
+++ /dev/null
@@ -1,324 +0,0 @@
-package postgres_test
-
-import (
- "strconv"
- "testing"
-
- "github.com/getfider/fider/app/models"
- . "github.com/getfider/fider/app/pkg/assert"
-)
-
-func TestSubscription_NoSettings(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(aryaStark)
- post1, _ := posts.Add("Post #1", "Description #1")
-
- subscribers, err := posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewPost)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(1)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewComment)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(2)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
- Expect(subscribers[1].ID).Equals(aryaStark.ID)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventChangeStatus)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(2)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
- Expect(subscribers[1].ID).Equals(aryaStark.ID)
-
- users.SetCurrentUser(nil)
- subscribed, err := users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsFalse()
-
- users.SetCurrentUser(jonSnow)
- subscribed, err = users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsTrue()
-
- users.SetCurrentUser(aryaStark)
- subscribed, err = users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsTrue()
-
- users.SetCurrentUser(sansaStark)
- subscribed, err = users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsFalse()
-}
-
-func TestSubscription_RemoveSubscriber(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(aryaStark)
- post1, _ := posts.Add("Post #1", "Description #1")
- err := posts.RemoveSubscriber(post1, aryaStark)
- Expect(err).IsNil()
-
- subscribers, err := posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewPost)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(1)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewComment)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(1)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventChangeStatus)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(1)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
-
- users.SetCurrentUser(jonSnow)
- subscribed, err := users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsTrue()
-
- users.SetCurrentUser(aryaStark)
- subscribed, err = users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsFalse()
-
- users.SetCurrentUser(sansaStark)
- subscribed, err = users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsFalse()
-}
-
-func TestSubscription_AdminSubmitted(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
-
- post1, _ := posts.Add("Post #1", "Description #1")
-
- subscribers, err := posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewPost)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(1)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewComment)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(1)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventChangeStatus)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(1)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
-
- users.SetCurrentUser(jonSnow)
- subscribed, err := users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsTrue()
-
- users.SetCurrentUser(aryaStark)
- subscribed, err = users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsFalse()
-
- users.SetCurrentUser(sansaStark)
- subscribed, err = users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsFalse()
-}
-
-func TestSubscription_AdminUnsubscribed(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(aryaStark)
-
- post1, _ := posts.Add("Post #1", "Description #1")
- posts.RemoveSubscriber(post1, aryaStark)
- posts.RemoveSubscriber(post1, jonSnow)
-
- subscribers, err := posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewComment)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(0)
-
- users.SetCurrentUser(jonSnow)
- subscribed, err := users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsFalse()
-
- users.SetCurrentUser(aryaStark)
- subscribed, err = users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsFalse()
-
- users.SetCurrentUser(sansaStark)
- subscribed, err = users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsFalse()
-}
-
-func TestSubscription_DisabledEmail(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(aryaStark)
- users.SetCurrentTenant(demoTenant)
- users.SetCurrentUser(aryaStark)
-
- err := users.UpdateSettings(map[string]string{
- models.NotificationEventNewComment.UserSettingsKeyName: strconv.Itoa(int(models.NotificationChannelWeb)),
- })
- Expect(err).IsNil()
-
- post1, _ := posts.Add("Post #1", "Description #1")
-
- subscribers, err := posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewComment)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(2)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
- Expect(subscribers[1].ID).Equals(aryaStark.ID)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelEmail, models.NotificationEventNewComment)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(1)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventChangeStatus)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(2)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
- Expect(subscribers[1].ID).Equals(aryaStark.ID)
-
- users.SetCurrentUser(jonSnow)
- subscribed, err := users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsTrue()
-
- users.SetCurrentUser(aryaStark)
- subscribed, err = users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsTrue()
-
- users.SetCurrentUser(sansaStark)
- subscribed, err = users.HasSubscribedTo(post1.ID)
- Expect(err).IsNil()
- Expect(subscribed).IsFalse()
-}
-
-func TestSubscription_VisitorEnabledNewPost(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- users.SetCurrentTenant(demoTenant)
- users.SetCurrentUser(aryaStark)
-
- err := users.UpdateSettings(map[string]string{
- models.NotificationEventNewPost.UserSettingsKeyName: strconv.Itoa(int(models.NotificationChannelEmail | models.NotificationChannelWeb)),
- })
- Expect(err).IsNil()
-
- post1, _ := posts.Add("Post #1", "Description #1")
-
- subscribers, err := posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewPost)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(2)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
- Expect(subscribers[1].ID).Equals(aryaStark.ID)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelEmail, models.NotificationEventNewPost)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(2)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
- Expect(subscribers[1].ID).Equals(aryaStark.ID)
-}
-
-func TestSubscription_DisabledEverything(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
- users.SetCurrentTenant(demoTenant)
- disableAll := map[string]string{
- models.NotificationEventNewPost.UserSettingsKeyName: "0",
- models.NotificationEventNewComment.UserSettingsKeyName: "0",
- models.NotificationEventChangeStatus.UserSettingsKeyName: "0",
- }
- users.SetCurrentUser(jonSnow)
- Expect(users.UpdateSettings(disableAll)).IsNil()
- users.SetCurrentUser(aryaStark)
- Expect(users.UpdateSettings(disableAll)).IsNil()
-
- post1, _ := posts.Add("Post #1", "Description #1")
-
- subscribers, err := posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewPost)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(0)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewComment)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(0)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventChangeStatus)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(0)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelEmail, models.NotificationEventNewPost)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(0)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelEmail, models.NotificationEventNewComment)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(0)
-
- subscribers, err = posts.GetActiveSubscribers(post1.Number, models.NotificationChannelEmail, models.NotificationEventChangeStatus)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(0)
-}
-
-func TestSubscription_DeletedPost(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(aryaStark)
-
- post1, _ := posts.Add("Post #1", "Description #1")
- posts.SetResponse(post1, "Invalid Post!", models.PostDeleted)
-
- subscribers, err := posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewComment)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(2)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
- Expect(subscribers[1].ID).Equals(aryaStark.ID)
-}
-
-func TestSubscription_SubscribedToDifferentPost(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(jonSnow)
-
- post1, _ := posts.Add("Post #1", "Description #1")
- post2, _ := posts.Add("Post #2", "Description #2")
- err := posts.AddSubscriber(post2, aryaStark)
- Expect(err).IsNil()
-
- subscribers, err := posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewComment)
- Expect(err).IsNil()
- Expect(subscribers).HasLen(1)
- Expect(subscribers[0].ID).Equals(jonSnow.ID)
-}
diff --git a/app/storage/postgres/tag.go b/app/storage/postgres/tag.go
deleted file mode 100644
index 0e9762d40..000000000
--- a/app/storage/postgres/tag.go
+++ /dev/null
@@ -1,196 +0,0 @@
-package postgres
-
-import (
- "fmt"
- "time"
-
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/dbx"
- "github.com/getfider/fider/app/pkg/errors"
- "github.com/gosimple/slug"
-)
-
-type dbTag struct {
- ID int `db:"id"`
- Name string `db:"name"`
- Slug string `db:"slug"`
- Color string `db:"color"`
- IsPublic bool `db:"is_public"`
-}
-
-func (t *dbTag) toModel() *models.Tag {
- return &models.Tag{
- ID: t.ID,
- Name: t.Name,
- Slug: t.Slug,
- Color: t.Color,
- IsPublic: t.IsPublic,
- }
-}
-
-// TagStorage contains read and write operations for tags
-type TagStorage struct {
- trx *dbx.Trx
- tenant *models.Tenant
- user *models.User
-}
-
-// NewTagStorage creates a new TagStorage
-func NewTagStorage(trx *dbx.Trx) *TagStorage {
- return &TagStorage{
- trx: trx,
- }
-}
-
-// SetCurrentTenant to current context
-func (s *TagStorage) SetCurrentTenant(tenant *models.Tenant) {
- s.tenant = tenant
-}
-
-// SetCurrentUser to current context
-func (s *TagStorage) SetCurrentUser(user *models.User) {
- s.user = user
-}
-
-// Add creates a new tag with given input
-func (s *TagStorage) Add(name, color string, isPublic bool) (*models.Tag, error) {
- tagSlug := slug.Make(name)
-
- var id int
- err := s.trx.Get(&id, `
- INSERT INTO tags (name, slug, color, is_public, created_at, tenant_id)
- VALUES ($1, $2, $3, $4, $5, $6) RETURNING id
- `, name, tagSlug, color, isPublic, time.Now(), s.tenant.ID)
- if err != nil {
- return nil, errors.Wrap(err, "failed to add new tag")
- }
-
- return s.GetBySlug(tagSlug)
-}
-
-// GetBySlug returns tag by given slug
-func (s *TagStorage) GetBySlug(slug string) (*models.Tag, error) {
- tag := dbTag{}
-
- err := s.trx.Get(&tag, "SELECT id, name, slug, color, is_public FROM tags WHERE tenant_id = $1 AND slug = $2", s.tenant.ID, slug)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get tag with slug '%s'", slug)
- }
-
- return tag.toModel(), nil
-}
-
-// Update a tag with given input
-func (s *TagStorage) Update(tag *models.Tag, name, color string, isPublic bool) (*models.Tag, error) {
- tagSlug := slug.Make(name)
-
- _, err := s.trx.Execute(`UPDATE tags SET name = $1, slug = $2, color = $3, is_public = $4
- WHERE id = $5 AND tenant_id = $6`, name, tagSlug, color, isPublic, tag.ID, s.tenant.ID)
- if err != nil {
- return nil, errors.Wrap(err, "failed to update tag")
- }
-
- return s.GetBySlug(tagSlug)
-}
-
-// Delete a tag by its id
-func (s *TagStorage) Delete(tag *models.Tag) error {
- _, err := s.trx.Execute(`DELETE FROM post_tags WHERE tag_id = $1 AND tenant_id = $2`, tag.ID, s.tenant.ID)
- if err != nil {
- return errors.Wrap(err, "failed to remove tag with id '%d' from all posts", tag.ID)
- }
-
- _, err = s.trx.Execute(`DELETE FROM tags WHERE id = $1 AND tenant_id = $2`, tag.ID, s.tenant.ID)
- if err != nil {
- return errors.Wrap(err, "failed to delete tag with id '%d'", tag.ID)
- }
- return nil
-}
-
-// AssignTag adds a tag to an post
-func (s *TagStorage) AssignTag(tag *models.Tag, post *models.Post) error {
- alreadyAssigned, err := s.trx.Exists("SELECT 1 FROM post_tags WHERE post_id = $1 AND tag_id = $2 AND tenant_id = $3", post.ID, tag.ID, s.tenant.ID)
- if err != nil {
- return errors.Wrap(err, "failed to check if tag is already assigned")
- }
-
- if alreadyAssigned {
- return nil
- }
-
- _, err = s.trx.Execute(
- `INSERT INTO post_tags (tag_id, post_id, created_at, created_by_id, tenant_id) VALUES ($1, $2, $3, $4, $5)`,
- tag.ID, post.ID, time.Now(), s.user.ID, s.tenant.ID,
- )
-
- if err != nil {
- return errors.Wrap(err, "failed to assign tag to post")
- }
- return nil
-}
-
-// UnassignTag removes a tag from an post
-func (s *TagStorage) UnassignTag(tag *models.Tag, post *models.Post) error {
- _, err := s.trx.Execute(
- `DELETE FROM post_tags WHERE tag_id = $1 AND post_id = $2 AND tenant_id = $3`,
- tag.ID, post.ID, s.tenant.ID,
- )
-
- if err != nil {
- return errors.Wrap(err, "failed to unassign tag from post")
- }
- return nil
-}
-
-// GetAssigned returns all tags assigned to given post
-func (s *TagStorage) GetAssigned(post *models.Post) ([]*models.Tag, error) {
- tags, err := s.getTags(`
- SELECT t.id, t.name, t.slug, t.color, t.is_public
- FROM tags t
- INNER JOIN post_tags pt
- ON pt.tag_id = t.id
- AND pt.tenant_id = t.tenant_id
- WHERE pt.post_id = $1 AND t.tenant_id = $2
- ORDER BY t.name
- `, post.ID, s.tenant.ID)
-
- if err != nil {
- return nil, errors.Wrap(err, "failed get assigned tags")
- }
- return tags, nil
-}
-
-// GetAll returns all tags
-func (s *TagStorage) GetAll() ([]*models.Tag, error) {
- condition := `AND t.is_public = true`
- if s.user != nil && s.user.IsCollaborator() {
- condition = ``
- }
-
- query := fmt.Sprintf(`
- SELECT t.id, t.name, t.slug, t.color, t.is_public
- FROM tags t
- WHERE t.tenant_id = $1 %s
- ORDER BY t.name
- `, condition)
- tags, err := s.getTags(query, s.tenant.ID)
- if err != nil {
- return nil, errors.Wrap(err, "failed get all tags")
- }
- return tags, nil
-}
-
-// GetAll returns all tags
-func (s *TagStorage) getTags(query string, args ...interface{}) ([]*models.Tag, error) {
- tags := []*dbTag{}
- err := s.trx.Select(&tags, query, args...)
- if err != nil {
- return nil, err
- }
-
- var result = make([]*models.Tag, len(tags))
- for i, tag := range tags {
- result[i] = tag.toModel()
- }
- return result, nil
-}
diff --git a/app/storage/postgres/tag_test.go b/app/storage/postgres/tag_test.go
deleted file mode 100644
index de77bb59f..000000000
--- a/app/storage/postgres/tag_test.go
+++ /dev/null
@@ -1,153 +0,0 @@
-package postgres_test
-
-import (
- "testing"
-
- "github.com/getfider/fider/app"
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/errors"
-)
-
-func TestTagStorage_AddAndGet(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tags.SetCurrentTenant(demoTenant)
- tag, err := tags.Add("Feature Request", "FF0000", true)
- Expect(err).IsNil()
- Expect(tag.ID).NotEquals(0)
-
- dbTag, err := tags.GetBySlug("feature-request")
-
- Expect(err).IsNil()
- Expect(dbTag.ID).NotEquals(0)
- Expect(dbTag.Name).Equals("Feature Request")
- Expect(dbTag.Slug).Equals("feature-request")
- Expect(dbTag.Color).Equals("FF0000")
- Expect(dbTag.IsPublic).IsTrue()
-}
-
-func TestTagStorage_AddUpdateAndGet(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tags.SetCurrentTenant(demoTenant)
- tag, err := tags.Add("Feature Request", "FF0000", true)
- tag, err = tags.Update(tag, "Bug", "000000", false)
-
- dbTag, err := tags.GetBySlug("bug")
-
- Expect(err).IsNil()
- Expect(dbTag.ID).Equals(tag.ID)
- Expect(dbTag.Name).Equals("Bug")
- Expect(dbTag.Slug).Equals("bug")
- Expect(dbTag.Color).Equals("000000")
- Expect(dbTag.IsPublic).IsFalse()
-}
-
-func TestTagStorage_AddDeleteAndGet(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tags.SetCurrentTenant(demoTenant)
- tag, err := tags.Add("Bug", "FFFFFF", true)
-
- err = tags.Delete(tag)
- Expect(err).IsNil()
-
- dbTag, err := tags.GetBySlug("bug")
-
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(dbTag).IsNil()
-}
-
-func TestTagStorage_Assign_Unassign(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(aryaStark)
- tags.SetCurrentTenant(demoTenant)
- tags.SetCurrentUser(aryaStark)
-
- post, _ := posts.Add("My great post", "with a great description")
- tag, _ := tags.Add("Bug", "FFFFFF", true)
-
- err := tags.AssignTag(tag, post)
- Expect(err).IsNil()
-
- assigned, err := tags.GetAssigned(post)
- Expect(err).IsNil()
- Expect(assigned).HasLen(1)
- Expect(assigned[0].ID).Equals(tag.ID)
- Expect(assigned[0].Name).Equals("Bug")
- Expect(assigned[0].Slug).Equals("bug")
- Expect(assigned[0].Color).Equals("FFFFFF")
- Expect(assigned[0].IsPublic).IsTrue()
-
- err = tags.UnassignTag(tag, post)
- Expect(err).IsNil()
-
- assigned, err = tags.GetAssigned(post)
- Expect(err).IsNil()
- Expect(assigned).HasLen(0)
-}
-
-func TestTagStorage_Assign_DeleteTag(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- posts.SetCurrentTenant(demoTenant)
- posts.SetCurrentUser(aryaStark)
- tags.SetCurrentTenant(demoTenant)
- tags.SetCurrentUser(aryaStark)
-
- post, _ := posts.Add("My great post", "with a great description")
- tag, _ := tags.Add("Bug", "FFFFFF", true)
-
- err := tags.AssignTag(tag, post)
- Expect(err).IsNil()
-
- err = tags.Delete(tag)
- Expect(err).IsNil()
-
- assigned, err := tags.GetAssigned(post)
- Expect(err).IsNil()
- Expect(assigned).HasLen(0)
-}
-
-func TestTagStorage_GetAll(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- tags.SetCurrentTenant(demoTenant)
- tags.SetCurrentUser(jonSnow)
-
- tags.Add("Feature Request", "FF0000", true)
- tags.Add("Bug", "0F0F0F", false)
-
- allTags, err := tags.GetAll()
-
- Expect(err).IsNil()
- Expect(allTags).HasLen(2)
-
- Expect(allTags[0].ID).NotEquals(0)
- Expect(allTags[0].Name).Equals("Bug")
- Expect(allTags[0].Slug).Equals("bug")
- Expect(allTags[0].Color).Equals("0F0F0F")
- Expect(allTags[0].IsPublic).IsFalse()
-
- Expect(allTags[1].ID).NotEquals(0)
- Expect(allTags[1].Name).Equals("Feature Request")
- Expect(allTags[1].Slug).Equals("feature-request")
- Expect(allTags[1].Color).Equals("FF0000")
- Expect(allTags[1].IsPublic).IsTrue()
-
- tags.SetCurrentUser(aryaStark)
-
- visitorTags, err := tags.GetAll()
- Expect(err).IsNil()
- Expect(visitorTags).HasLen(1)
- Expect(visitorTags[0].Name).Equals("Feature Request")
-}
diff --git a/app/storage/postgres/tenant.go b/app/storage/postgres/tenant.go
deleted file mode 100644
index 6feef6885..000000000
--- a/app/storage/postgres/tenant.go
+++ /dev/null
@@ -1,449 +0,0 @@
-package postgres
-
-import (
- "time"
-
- "github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/dbx"
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/errors"
-)
-
-type dbTenant struct {
- ID int `db:"id"`
- Name string `db:"name"`
- Subdomain string `db:"subdomain"`
- CNAME string `db:"cname"`
- Invitation string `db:"invitation"`
- WelcomeMessage string `db:"welcome_message"`
- Status int `db:"status"`
- IsPrivate bool `db:"is_private"`
- LogoBlobKey string `db:"logo_bkey"`
- CustomCSS string `db:"custom_css"`
- Billing *dbTenantBilling `db:"billing"`
-}
-
-func (t *dbTenant) toModel() *models.Tenant {
- if t == nil {
- return nil
- }
-
- tenant := &models.Tenant{
- ID: t.ID,
- Name: t.Name,
- Subdomain: t.Subdomain,
- CNAME: t.CNAME,
- Invitation: t.Invitation,
- WelcomeMessage: t.WelcomeMessage,
- Status: t.Status,
- IsPrivate: t.IsPrivate,
- LogoBlobKey: t.LogoBlobKey,
- CustomCSS: t.CustomCSS,
- }
-
- if t.Billing != nil && t.Billing.TrialEndsAt.Valid {
- tenant.Billing = &models.TenantBilling{
- TrialEndsAt: t.Billing.TrialEndsAt.Time,
- StripeCustomerID: t.Billing.StripeCustomerID.String,
- StripeSubscriptionID: t.Billing.StripeSubscriptionID.String,
- StripePlanID: t.Billing.StripePlanID.String,
- }
- if t.Billing.SubscriptionEndsAt.Valid {
- tenant.Billing.SubscriptionEndsAt = &t.Billing.SubscriptionEndsAt.Time
- }
- }
-
- return tenant
-}
-
-type dbTenantBilling struct {
- StripeCustomerID dbx.NullString `db:"stripe_customer_id"`
- StripeSubscriptionID dbx.NullString `db:"stripe_subscription_id"`
- StripePlanID dbx.NullString `db:"stripe_plan_id"`
- TrialEndsAt dbx.NullTime `db:"trial_ends_at"`
- SubscriptionEndsAt dbx.NullTime `db:"subscription_ends_at"`
-}
-
-type dbEmailVerification struct {
- ID int `db:"id"`
- Name string `db:"name"`
- Email string `db:"email"`
- Key string `db:"key"`
- Kind models.EmailVerificationKind `db:"kind"`
- UserID dbx.NullInt `db:"user_id"`
- CreatedAt time.Time `db:"created_at"`
- ExpiresAt time.Time `db:"expires_at"`
- VerifiedAt dbx.NullTime `db:"verified_at"`
-}
-
-func (t *dbEmailVerification) toModel() *models.EmailVerification {
- model := &models.EmailVerification{
- Name: t.Name,
- Email: t.Email,
- Key: t.Key,
- Kind: t.Kind,
- CreatedAt: t.CreatedAt,
- ExpiresAt: t.ExpiresAt,
- VerifiedAt: nil,
- }
-
- if t.VerifiedAt.Valid {
- model.VerifiedAt = &t.VerifiedAt.Time
- }
-
- if t.UserID.Valid {
- model.UserID = int(t.UserID.Int64)
- }
-
- return model
-}
-
-type dbOAuthConfig struct {
- ID int `db:"id"`
- Provider string `db:"provider"`
- DisplayName string `db:"display_name"`
- LogoBlobKey string `db:"logo_bkey"`
- Status int `db:"status"`
- ClientID string `db:"client_id"`
- ClientSecret string `db:"client_secret"`
- AuthorizeURL string `db:"authorize_url"`
- TokenURL string `db:"token_url"`
- Scope string `db:"scope"`
- ProfileURL string `db:"profile_url"`
- JSONUserIDPath string `db:"json_user_id_path"`
- JSONUserNamePath string `db:"json_user_name_path"`
- JSONUserEmailPath string `db:"json_user_email_path"`
-}
-
-func (m *dbOAuthConfig) toModel() *models.OAuthConfig {
- return &models.OAuthConfig{
- ID: m.ID,
- Provider: m.Provider,
- DisplayName: m.DisplayName,
- Status: m.Status,
- LogoBlobKey: m.LogoBlobKey,
- ClientID: m.ClientID,
- ClientSecret: m.ClientSecret,
- AuthorizeURL: m.AuthorizeURL,
- TokenURL: m.TokenURL,
- ProfileURL: m.ProfileURL,
- Scope: m.Scope,
- JSONUserIDPath: m.JSONUserIDPath,
- JSONUserNamePath: m.JSONUserNamePath,
- JSONUserEmailPath: m.JSONUserEmailPath,
- }
-}
-
-// TenantStorage contains read and write operations for tenants
-type TenantStorage struct {
- trx *dbx.Trx
- current *models.Tenant
- user *models.User
-}
-
-// NewTenantStorage creates a new TenantStorage
-func NewTenantStorage(trx *dbx.Trx) *TenantStorage {
- return &TenantStorage{trx: trx}
-}
-
-// SetCurrentTenant to current context
-func (s *TenantStorage) SetCurrentTenant(tenant *models.Tenant) {
- s.current = tenant
-}
-
-// SetCurrentUser to current context
-func (s *TenantStorage) SetCurrentUser(user *models.User) {
- s.user = user
-}
-
-// Current returns current context tenant
-func (s *TenantStorage) Current() *models.Tenant {
- return s.current
-}
-
-// Add given tenant to tenant list
-func (s *TenantStorage) Add(name string, subdomain string, status int) (*models.Tenant, error) {
- now := time.Now()
-
- var id int
- err := s.trx.Get(&id,
- `INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey)
- VALUES ($1, $2, $3, '', '', '', $4, false, '', '')
- RETURNING id`, name, subdomain, now, status)
- if err != nil {
- return nil, err
- }
-
- if env.IsBillingEnabled() {
- _, err = s.trx.Execute(
- `INSERT INTO tenants_billing (tenant_id, trial_ends_at) VALUES ($1, $2)`,
- id, now.Add(30*24*time.Hour),
- )
- if err != nil {
- return nil, err
- }
- }
-
- return s.GetByDomain(subdomain)
-}
-
-// First returns first tenant
-func (s *TenantStorage) First() (*models.Tenant, error) {
- tenant := dbTenant{}
-
- err := s.trx.Get(&tenant, `
- SELECT t.id, t.name, t.subdomain, t.cname, t.invitation, t.welcome_message, t.status, t.is_private, t.logo_bkey, t.custom_css,
- tb.trial_ends_at AS billing_trial_ends_at,
- tb.subscription_ends_at AS billing_subscription_ends_at,
- tb.stripe_customer_id AS billing_stripe_customer_id,
- tb.stripe_plan_id AS billing_stripe_plan_id,
- tb.stripe_subscription_id AS billing_stripe_subscription_id
- FROM tenants t
- LEFT JOIN tenants_billing tb
- ON tb.tenant_id = t.id
- ORDER BY t.id LIMIT 1
- `)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get first tenant")
- }
-
- return tenant.toModel(), nil
-}
-
-// GetByDomain returns a tenant based on its domain
-func (s *TenantStorage) GetByDomain(domain string) (*models.Tenant, error) {
- tenant := dbTenant{}
-
- err := s.trx.Get(&tenant, `
- SELECT t.id, t.name, t.subdomain, t.cname, t.invitation, t.welcome_message, t.status, t.is_private, t.logo_bkey, t.custom_css,
- tb.trial_ends_at AS billing_trial_ends_at,
- tb.subscription_ends_at AS billing_subscription_ends_at,
- tb.stripe_customer_id AS billing_stripe_customer_id,
- tb.stripe_plan_id AS billing_stripe_plan_id,
- tb.stripe_subscription_id AS billing_stripe_subscription_id
- FROM tenants t
- LEFT JOIN tenants_billing tb
- ON tb.tenant_id = t.id
- WHERE t.subdomain = $1 OR t.subdomain = $2 OR t.cname = $3
- ORDER BY t.cname DESC
- `, env.Subdomain(domain), domain, domain)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get tenant with domain '%s'", domain)
- }
-
- return tenant.toModel(), nil
-}
-
-// UpdateSettings of current tenant
-func (s *TenantStorage) UpdateSettings(settings *models.UpdateTenantSettings) error {
- if settings.Logo.Remove {
- settings.Logo.BlobKey = ""
- }
-
- query := "UPDATE tenants SET name = $1, invitation = $2, welcome_message = $3, cname = $4, logo_bkey = $5 WHERE id = $6"
- _, err := s.trx.Execute(query, settings.Title, settings.Invitation, settings.WelcomeMessage, settings.CNAME, settings.Logo.BlobKey, s.current.ID)
- if err != nil {
- return errors.Wrap(err, "failed update tenant settings")
- }
-
- s.current.Name = settings.Title
- s.current.Invitation = settings.Invitation
- s.current.CNAME = settings.CNAME
- s.current.WelcomeMessage = settings.WelcomeMessage
-
- return nil
-}
-
-// UpdateBillingSettings of current tenant
-func (s *TenantStorage) UpdateBillingSettings(billing *models.TenantBilling) error {
- _, err := s.trx.Execute(`
- UPDATE tenants_billing
- SET stripe_customer_id = $1, stripe_plan_id = $2, stripe_subscription_id = $3,
- subscription_ends_at = $4
- WHERE tenant_id = $5
- `, billing.StripeCustomerID, billing.StripePlanID, billing.StripeSubscriptionID,
- billing.SubscriptionEndsAt, s.current.ID)
- if err != nil {
- return errors.Wrap(err, "failed update tenant billing settings")
- }
- return nil
-}
-
-// UpdateAdvancedSettings of current tenant
-func (s *TenantStorage) UpdateAdvancedSettings(settings *models.UpdateTenantAdvancedSettings) error {
- query := "UPDATE tenants SET custom_css = $1 WHERE id = $2"
- _, err := s.trx.Execute(query, settings.CustomCSS, s.current.ID)
- if err != nil {
- return errors.Wrap(err, "failed update tenant advanced settings")
- }
- s.current.CustomCSS = settings.CustomCSS
- return nil
-}
-
-// UpdatePrivacy settings of current tenant
-func (s *TenantStorage) UpdatePrivacy(settings *models.UpdateTenantPrivacy) error {
- query := "UPDATE tenants SET is_private = $1 WHERE id = $2"
- _, err := s.trx.Execute(query, settings.IsPrivate, s.current.ID)
- if err != nil {
- return errors.Wrap(err, "failed update tenant privacy settings")
- }
- return nil
-}
-
-// IsSubdomainAvailable returns true if subdomain is available to use
-func (s *TenantStorage) IsSubdomainAvailable(subdomain string) (bool, error) {
- exists, err := s.trx.Exists("SELECT id FROM tenants WHERE subdomain = $1", subdomain)
- if err != nil {
- return false, errors.Wrap(err, "failed to check if tenant exists with subdomain '%s'", subdomain)
- }
- return !exists, nil
-}
-
-// IsCNAMEAvailable returns true if cname is available to use
-func (s *TenantStorage) IsCNAMEAvailable(cname string) (bool, error) {
- exists, err := s.trx.Exists("SELECT id FROM tenants WHERE cname = $1 AND id <> $2", cname, s.current.ID)
- if err != nil {
- return false, errors.Wrap(err, "failed to check if tenant exists with CNAME '%s'", cname)
- }
- return !exists, nil
-}
-
-// Activate given tenant
-func (s *TenantStorage) Activate(id int) error {
- query := "UPDATE tenants SET status = $1 WHERE id = $2"
- _, err := s.trx.Execute(query, models.TenantActive, id)
- if err != nil {
- return errors.Wrap(err, "failed to activate tenant with id '%d'", id)
- }
- return nil
-}
-
-// SaveVerificationKey used by email verification process
-func (s *TenantStorage) SaveVerificationKey(key string, duration time.Duration, request models.NewEmailVerification) error {
- var userID interface{}
- if request.GetUser() != nil {
- userID = request.GetUser().ID
- }
-
- query := "INSERT INTO email_verifications (tenant_id, email, created_at, expires_at, key, name, kind, user_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)"
- _, err := s.trx.Execute(query, s.current.ID, request.GetEmail(), time.Now(), time.Now().Add(duration), key, request.GetName(), request.GetKind(), userID)
- if err != nil {
- return errors.Wrap(err, "failed to save verification key for kind '%d'", request.GetKind())
- }
- return nil
-}
-
-// FindVerificationByKey based on current tenant
-func (s *TenantStorage) FindVerificationByKey(kind models.EmailVerificationKind, key string) (*models.EmailVerification, error) {
- verification := dbEmailVerification{}
-
- query := "SELECT id, email, name, key, created_at, verified_at, expires_at, kind, user_id FROM email_verifications WHERE key = $1 AND kind = $2 LIMIT 1"
- err := s.trx.Get(&verification, query, key, kind)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get email verification by its key")
- }
-
- return verification.toModel(), nil
-}
-
-// SetKeyAsVerified so that it cannot be used anymore
-func (s *TenantStorage) SetKeyAsVerified(key string) error {
- query := "UPDATE email_verifications SET verified_at = $1 WHERE tenant_id = $2 AND key = $3"
- _, err := s.trx.Execute(query, time.Now(), s.current.ID, key)
- if err != nil {
- return errors.Wrap(err, "failed to update verified date of email verification request")
- }
- return nil
-}
-
-// SaveOAuthConfig saves given config into database
-func (s *TenantStorage) SaveOAuthConfig(config *models.CreateEditOAuthConfig) error {
- var err error
-
- if config.Logo.Remove {
- config.Logo.BlobKey = ""
- }
-
- if config.ID == 0 {
- query := `INSERT INTO oauth_providers (
- tenant_id, provider, display_name, status,
- client_id, client_secret, authorize_url,
- profile_url, token_url, scope, json_user_id_path,
- json_user_name_path, json_user_email_path, logo_bkey
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
- RETURNING id`
-
- err = s.trx.Get(&config.ID, query, s.current.ID, config.Provider,
- config.DisplayName, config.Status, config.ClientID, config.ClientSecret,
- config.AuthorizeURL, config.ProfileURL, config.TokenURL,
- config.Scope, config.JSONUserIDPath, config.JSONUserNamePath,
- config.JSONUserEmailPath, config.Logo.BlobKey)
- } else {
- query := `
- UPDATE oauth_providers
- SET display_name = $3, status = $4, client_id = $5, client_secret = $6,
- authorize_url = $7, profile_url = $8, token_url = $9, scope = $10,
- json_user_id_path = $11, json_user_name_path = $12, json_user_email_path = $13,
- logo_bkey = $14
- WHERE tenant_id = $1 AND id = $2`
-
- _, err = s.trx.Execute(query, s.current.ID, config.ID,
- config.DisplayName, config.Status, config.ClientID, config.ClientSecret,
- config.AuthorizeURL, config.ProfileURL, config.TokenURL,
- config.Scope, config.JSONUserIDPath, config.JSONUserNamePath,
- config.JSONUserEmailPath, config.Logo.BlobKey)
- }
-
- if err != nil {
- return errors.Wrap(err, "failed to save OAuth Provider")
- }
-
- return nil
-}
-
-// GetOAuthConfigByProvider returns a custom OAuth configuration by provider name
-func (s *TenantStorage) GetOAuthConfigByProvider(provider string) (*models.OAuthConfig, error) {
- if s.current == nil {
- return nil, app.ErrNotFound
- }
-
- config := &dbOAuthConfig{}
- err := s.trx.Get(config, `
- SELECT id, provider, display_name, status, logo_bkey,
- client_id, client_secret, authorize_url,
- profile_url, token_url, scope, json_user_id_path,
- json_user_name_path, json_user_email_path
- FROM oauth_providers
- WHERE tenant_id = $1 AND provider = $2
- `, s.current.ID, provider)
- if err != nil {
- return nil, err
- }
- return config.toModel(), nil
-}
-
-// ListOAuthConfig returns a list of all custom OAuth provider for current tenant
-func (s *TenantStorage) ListOAuthConfig() ([]*models.OAuthConfig, error) {
- configs := []*dbOAuthConfig{}
- if s.current != nil {
- err := s.trx.Select(&configs, `
- SELECT id, provider, display_name, status, logo_bkey,
- client_id, client_secret, authorize_url,
- profile_url, token_url, scope, json_user_id_path,
- json_user_name_path, json_user_email_path
- FROM oauth_providers
- WHERE tenant_id = $1
- ORDER BY id
- `, s.current.ID)
- if err != nil {
- return nil, err
- }
- }
-
- var result = make([]*models.OAuthConfig, len(configs))
- for i, config := range configs {
- result[i] = config.toModel()
- }
- return result, nil
-}
diff --git a/app/storage/postgres/tenant_test.go b/app/storage/postgres/tenant_test.go
deleted file mode 100644
index ca842ea2f..000000000
--- a/app/storage/postgres/tenant_test.go
+++ /dev/null
@@ -1,393 +0,0 @@
-package postgres_test
-
-import (
- "testing"
- "time"
-
- "github.com/getfider/fider/app/models"
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/errors"
-
- "github.com/getfider/fider/app"
-)
-
-func TestTenantStorage_Add_Activate(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- env.Config.Stripe.SecretKey = ""
- tenant, err := tenants.Add("My Domain Inc.", "mydomain", models.TenantPending)
-
- Expect(err).IsNil()
- Expect(tenant).IsNotNil()
-
- tenant, err = tenants.GetByDomain("mydomain")
- Expect(err).IsNil()
- Expect(tenant.Name).Equals("My Domain Inc.")
- Expect(tenant.Subdomain).Equals("mydomain")
- Expect(tenant.Status).Equals(models.TenantPending)
- Expect(tenant.IsPrivate).IsFalse()
-
- err = tenants.Activate(tenant.ID)
- Expect(err).IsNil()
-
- tenant, err = tenants.GetByDomain("mydomain")
- Expect(err).IsNil()
- Expect(tenant.Name).Equals("My Domain Inc.")
- Expect(tenant.Subdomain).Equals("mydomain")
- Expect(tenant.Status).Equals(models.TenantActive)
- Expect(tenant.IsPrivate).IsFalse()
- Expect(tenant.Billing).IsNil()
-}
-
-func TestTenantStorage_Add_WithBillingEnabled(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- env.Config.Stripe.SecretKey = "sk_1"
- tenant, err := tenants.Add("My Domain Inc.", "mydomain", models.TenantPending)
-
- Expect(err).IsNil()
- Expect(tenant).IsNotNil()
-
- tenant, err = tenants.GetByDomain("mydomain")
- Expect(err).IsNil()
- Expect(tenant.Name).Equals("My Domain Inc.")
- Expect(tenant.Subdomain).Equals("mydomain")
- Expect(tenant.Status).Equals(models.TenantPending)
- Expect(tenant.IsPrivate).IsFalse()
- Expect(tenant.Billing).IsNotNil()
- Expect(tenant.Billing.TrialEndsAt).TemporarilySimilar(time.Now().Add(30*24*time.Hour), 5*time.Second)
-}
-
-func TestTenantStorage_SingleTenant_Add(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- env.Config.HostMode = "single"
-
- tenant, err := tenants.Add("My Domain Inc.", "mydomain", models.TenantPending)
- Expect(err).IsNil()
- Expect(tenant).IsNotNil()
-}
-
-func TestTenantStorage_First(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tenant, err := tenants.First()
- Expect(err).IsNil()
- Expect(tenant.ID).Equals(1)
-}
-
-func TestTenantStorage_Empty_First(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- trx.Execute("TRUNCATE tenants CASCADE")
-
- tenant, err := tenants.First()
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(tenant).IsNil()
-}
-
-func TestTenantStorage_UpdatePrivacy(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tenant, _ := tenants.GetByDomain("demo")
- tenants.SetCurrentTenant(tenant)
- Expect(tenant.IsPrivate).IsFalse()
-
- tenants.UpdatePrivacy(&models.UpdateTenantPrivacy{IsPrivate: true})
- tenant, _ = tenants.GetByDomain("demo")
- Expect(tenant.IsPrivate).IsTrue()
-}
-
-func TestTenantStorage_GetByDomain_NotFound(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tenant, err := tenants.GetByDomain("mydomain")
-
- Expect(tenant).IsNil()
- Expect(err).IsNotNil()
-}
-
-func TestTenantStorage_GetByDomain_Subdomain(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tenant, err := tenants.Add("My Domain Inc.", "mydomain", models.TenantActive)
- Expect(err).IsNil()
-
- tenant, err = tenants.GetByDomain("mydomain")
- Expect(err).IsNil()
- Expect(tenant.ID).NotEquals(0)
- Expect(tenant.Name).Equals("My Domain Inc.")
- Expect(tenant.Subdomain).Equals("mydomain")
- Expect(tenant.CNAME).Equals("")
- Expect(tenant.Status).Equals(models.TenantActive)
-}
-
-func TestTenantStorage_GetByDomain_CNAME(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tenant, err := tenants.Add("My Domain Inc.", "mydomain", models.TenantActive)
- Expect(err).IsNil()
- tenants.SetCurrentTenant(tenant)
- tenants.UpdateSettings(&models.UpdateTenantSettings{
- Title: "My Domain Inc.",
- CNAME: "feedback.mycompany.com",
- Logo: &models.ImageUpload{},
- })
-
- tenant, err = tenants.GetByDomain("feedback.mycompany.com")
- Expect(err).IsNil()
- Expect(tenant.ID).NotEquals(0)
- Expect(tenant.Name).Equals("My Domain Inc.")
- Expect(tenant.Subdomain).Equals("mydomain")
- Expect(tenant.CNAME).Equals("feedback.mycompany.com")
- Expect(tenant.Status).Equals(models.TenantActive)
-}
-
-func TestTenantStorage_IsSubdomainAvailable_ExistingDomain(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- available, err := tenants.IsSubdomainAvailable("demo")
- Expect(available).IsFalse()
- Expect(err).IsNil()
-}
-
-func TestTenantStorage_IsSubdomainAvailable_NewDomain(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- available, err := tenants.IsSubdomainAvailable("thisisanewdomain")
- Expect(available).IsTrue()
- Expect(err).IsNil()
-}
-
-func TestTenantStorage_UpdateSettings(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tenant, _ := tenants.GetByDomain("demo")
- tenants.SetCurrentTenant(tenant)
-
- settings := &models.UpdateTenantSettings{
- Logo: &models.ImageUpload{
- BlobKey: "some-logo-key.png",
- },
- Title: "New Demonstration",
- Invitation: "Leave us your suggestion",
- WelcomeMessage: "Welcome!",
- CNAME: "demo.company.com",
- }
- err := tenants.UpdateSettings(settings)
- Expect(err).IsNil()
-
- tenant, err = tenants.GetByDomain("demo")
- Expect(err).IsNil()
- Expect(tenant.ID).Equals(1)
- Expect(tenant.Name).Equals("New Demonstration")
- Expect(tenant.Invitation).Equals("Leave us your suggestion")
- Expect(tenant.WelcomeMessage).Equals("Welcome!")
- Expect(tenant.CNAME).Equals("demo.company.com")
- Expect(tenant.LogoBlobKey).Equals("some-logo-key.png")
-}
-
-func TestTenantStorage_AdvancedSettings(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tenant, _ := tenants.GetByDomain("demo")
- tenants.SetCurrentTenant(tenant)
-
- settings := &models.UpdateTenantAdvancedSettings{
- CustomCSS: ".primary { color: red; }",
- }
- err := tenants.UpdateAdvancedSettings(settings)
- Expect(err).IsNil()
-
- tenant, err = tenants.GetByDomain("demo")
- Expect(err).IsNil()
- Expect(tenant.CustomCSS).Equals(".primary { color: red; }")
-}
-
-func TestTenantStorage_SaveFindSet_VerificationKey(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tenant, _ := tenants.GetByDomain("demo")
- tenants.SetCurrentTenant(tenant)
-
- //Save new Key
- request := &models.CreateTenant{
- Email: "[email protected]",
- Name: "Jon Snow",
- }
- err := tenants.SaveVerificationKey("s3cr3tk3y", 15*time.Minute, request)
- Expect(err).IsNil()
-
- //Find and check values
- result, err := tenants.FindVerificationByKey(models.EmailVerificationKindSignUp, "s3cr3tk3y")
- Expect(err).IsNil()
- Expect(result.CreatedAt).TemporarilySimilar(time.Now(), 1*time.Second)
- Expect(result.VerifiedAt).IsNil()
- Expect(result.Email).Equals("[email protected]")
- Expect(result.Name).Equals("Jon Snow")
- Expect(result.Kind).Equals(models.EmailVerificationKindSignUp)
- Expect(result.Key).Equals("s3cr3tk3y")
- Expect(result.UserID).Equals(0)
- Expect(result.ExpiresAt).TemporarilySimilar(result.CreatedAt.Add(15*time.Minute), 1*time.Second)
-
- //Set as verified check values
- err = tenants.SetKeyAsVerified("s3cr3tk3y")
- Expect(err).IsNil()
-
- //Find and check that VerifiedAt is now set
- result, err = tenants.FindVerificationByKey(models.EmailVerificationKindSignUp, "s3cr3tk3y")
- Expect(err).IsNil()
- Expect(time.Now().After(result.CreatedAt)).IsTrue()
- Expect(result.VerifiedAt.After(result.CreatedAt)).IsTrue()
- Expect(result.Email).Equals("[email protected]")
- Expect(result.Name).Equals("Jon Snow")
- Expect(result.Key).Equals("s3cr3tk3y")
- Expect(result.UserID).Equals(0)
- Expect(result.ExpiresAt).TemporarilySimilar(result.CreatedAt.Add(15*time.Minute), 1*time.Second)
-
- //Wrong kind should not find it
- result, err = tenants.FindVerificationByKey(models.EmailVerificationKindSignIn, "s3cr3tk3y")
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(result).IsNil()
-}
-
-func TestTenantStorage_SaveFindSet_ChangeEmailVerificationKey(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tenant, _ := tenants.GetByDomain("demo")
- tenants.SetCurrentTenant(tenant)
-
- //Save new Key
- request := &models.ChangeUserEmail{
- Email: "[email protected]",
- Requestor: jonSnow,
- }
- err := tenants.SaveVerificationKey("th3-s3cr3t", 15*time.Minute, request)
- Expect(err).IsNil()
-
- //Find and check values
- result, err := tenants.FindVerificationByKey(models.EmailVerificationKindChangeEmail, "th3-s3cr3t")
- Expect(err).IsNil()
- Expect(result.CreatedAt).TemporarilySimilar(time.Now(), 1*time.Second)
- Expect(result.VerifiedAt).IsNil()
- Expect(result.Email).Equals("[email protected]")
- Expect(result.Name).Equals("")
- Expect(result.Kind).Equals(models.EmailVerificationKindChangeEmail)
- Expect(result.Key).Equals("th3-s3cr3t")
- Expect(result.UserID).Equals(jonSnow.ID)
- Expect(result.ExpiresAt).TemporarilySimilar(result.CreatedAt.Add(15*time.Minute), 1*time.Second)
-}
-
-func TestTenantStorage_FindUnknownVerificationKey(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tenant, _ := tenants.GetByDomain("demo")
- tenants.SetCurrentTenant(tenant)
-
- //Find and check values
- result, err := tenants.FindVerificationByKey(models.EmailVerificationKindSignIn, "blahblahblah")
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(result).IsNil()
-}
-
-func TestTenantStorage_Save_Get_ListOAuthConfig(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- tenant, _ := tenants.GetByDomain("demo")
- tenants.SetCurrentTenant(tenant)
-
- config, err := tenants.GetOAuthConfigByProvider("_TEST")
- Expect(config).IsNil()
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
-
- err = tenants.SaveOAuthConfig(&models.CreateEditOAuthConfig{
- ID: 0,
- Logo: &models.ImageUpload{
- BlobKey: "uploads/my-logo-key.png",
- },
- Provider: "_TEST",
- DisplayName: "My Provider",
- ClientID: "823187ahjjfdha8fds7yfdashfjkdsa",
- ClientSecret: "jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij",
- AuthorizeURL: "http://provider/oauth/authorize",
- TokenURL: "http://provider/oauth/token",
- Scope: "profile email",
- ProfileURL: "http://provider/profile/me",
- JSONUserIDPath: "user.id",
- JSONUserNamePath: "user.name",
- JSONUserEmailPath: "user.email",
- })
- Expect(err).IsNil()
-
- config, err = tenants.GetOAuthConfigByProvider("_TEST")
- Expect(err).IsNil()
- Expect(config.ID).Equals(1)
- Expect(config.LogoBlobKey).Equals("uploads/my-logo-key.png")
- Expect(config.Provider).Equals("_TEST")
- Expect(config.DisplayName).Equals("My Provider")
- Expect(config.ClientID).Equals("823187ahjjfdha8fds7yfdashfjkdsa")
- Expect(config.ClientSecret).Equals("jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij")
- Expect(config.AuthorizeURL).Equals("http://provider/oauth/authorize")
- Expect(config.TokenURL).Equals("http://provider/oauth/token")
- Expect(config.Scope).Equals("profile email")
- Expect(config.Status).Equals(0)
- Expect(config.ProfileURL).Equals("http://provider/profile/me")
- Expect(config.JSONUserIDPath).Equals("user.id")
- Expect(config.JSONUserNamePath).Equals("user.name")
- Expect(config.JSONUserEmailPath).Equals("user.email")
-
- err = tenants.SaveOAuthConfig(&models.CreateEditOAuthConfig{
- ID: config.ID,
- Logo: &models.ImageUpload{
- BlobKey: "",
- },
- Provider: "_TEST2222", //this has to be ignored
- DisplayName: "New My Provider",
- ClientID: "New 823187ahjjfdha8fds7yfdashfjkdsa",
- ClientSecret: "New jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij",
- AuthorizeURL: "New http://provider/oauth/authorize",
- TokenURL: "New http://provider/oauth/token",
- Scope: "New profile email",
- ProfileURL: "New http://provider/profile/me",
- JSONUserIDPath: "New user.id",
- JSONUserNamePath: "New user.name",
- JSONUserEmailPath: "New user.email",
- })
- Expect(err).IsNil()
-
- configs, err := tenants.ListOAuthConfig()
- Expect(err).IsNil()
- Expect(configs).HasLen(1)
- Expect(configs[0].ID).Equals(1)
- Expect(configs[0].LogoBlobKey).Equals("")
- Expect(configs[0].Provider).Equals("_TEST")
- Expect(configs[0].DisplayName).Equals("New My Provider")
- Expect(configs[0].ClientID).Equals("New 823187ahjjfdha8fds7yfdashfjkdsa")
- Expect(configs[0].ClientSecret).Equals("New jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij")
- Expect(configs[0].AuthorizeURL).Equals("New http://provider/oauth/authorize")
- Expect(configs[0].TokenURL).Equals("New http://provider/oauth/token")
- Expect(configs[0].Scope).Equals("New profile email")
- Expect(configs[0].Status).Equals(0)
- Expect(configs[0].ProfileURL).Equals("New http://provider/profile/me")
- Expect(configs[0].JSONUserIDPath).Equals("New user.id")
- Expect(configs[0].JSONUserNamePath).Equals("New user.name")
- Expect(configs[0].JSONUserEmailPath).Equals("New user.email")
-}
diff --git a/app/storage/postgres/user.go b/app/storage/postgres/user.go
deleted file mode 100644
index 6ec8446ba..000000000
--- a/app/storage/postgres/user.go
+++ /dev/null
@@ -1,392 +0,0 @@
-package postgres
-
-import (
- "fmt"
- "strings"
- "time"
-
- "database/sql"
-
- "github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/dbx"
- "github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/storage"
-)
-
-type dbUser struct {
- ID sql.NullInt64 `db:"id"`
- Name sql.NullString `db:"name"`
- Email sql.NullString `db:"email"`
- Tenant *dbTenant `db:"tenant"`
- Role sql.NullInt64 `db:"role"`
- Status sql.NullInt64 `db:"status"`
- AvatarType sql.NullInt64 `db:"avatar_type"`
- AvatarBlobKey sql.NullString `db:"avatar_bkey"`
- Providers []*dbUserProvider
-}
-
-type dbUserProvider struct {
- Name sql.NullString `db:"provider"`
- UID sql.NullString `db:"provider_uid"`
-}
-
-func (u *dbUser) toModel(ctx storage.Context) *models.User {
- if u == nil {
- return nil
- }
-
- avatarType := models.AvatarType(u.AvatarType.Int64)
- user := &models.User{
- ID: int(u.ID.Int64),
- Name: u.Name.String,
- Email: u.Email.String,
- Tenant: u.Tenant.toModel(),
- Role: models.Role(u.Role.Int64),
- Providers: make([]*models.UserProvider, len(u.Providers)),
- Status: models.UserStatus(u.Status.Int64),
- AvatarType: avatarType,
- AvatarBlobKey: u.AvatarBlobKey.String,
- AvatarURL: buildAvatarURL(ctx, avatarType, int(u.ID.Int64), u.Name.String, u.AvatarBlobKey.String),
- }
-
- for i, p := range u.Providers {
- user.Providers[i] = &models.UserProvider{
- Name: p.Name.String,
- UID: p.UID.String,
- }
- }
-
- return user
-}
-
-type dbUserSetting struct {
- Key string `db:"key"`
- Value string `db:"value"`
-}
-
-// UserStorage is used for user operations using a Postgres database
-type UserStorage struct {
- tenant *models.Tenant
- user *models.User
- trx *dbx.Trx
- ctx storage.Context
-}
-
-// NewUserStorage creates a new UserStorage
-func NewUserStorage(trx *dbx.Trx, ctx storage.Context) *UserStorage {
- return &UserStorage{trx: trx, ctx: ctx}
-}
-
-// SetCurrentTenant to current context
-func (s *UserStorage) SetCurrentTenant(tenant *models.Tenant) {
- s.tenant = tenant
-}
-
-// SetCurrentUser to current context
-func (s *UserStorage) SetCurrentUser(user *models.User) {
- s.user = user
-}
-
-// GetByID returns a user based on given id
-func (s *UserStorage) GetByID(userID int) (*models.User, error) {
- user, err := s.getUser(s.trx, "id = $1", userID)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get user with id '%d'", userID)
- }
- return user, nil
-}
-
-// GetByEmail returns a user based on given email
-func (s *UserStorage) GetByEmail(email string) (*models.User, error) {
- email = strings.ToLower(email)
- user, err := s.getUser(s.trx, "email = $1 AND tenant_id = $2", email, s.tenant.ID)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get user with email '%s'", email)
- }
- return user, nil
-}
-
-// GetByProvider returns a user based on provider details
-func (s *UserStorage) GetByProvider(provider string, uid string) (*models.User, error) {
- var userID int
- query := `
- SELECT user_id
- FROM user_providers up
- INNER JOIN users u
- ON u.id = up.user_id
- AND u.tenant_id = up.tenant_id
- WHERE up.provider = $1
- AND up.provider_uid = $2
- AND u.tenant_id = $3`
- if err := s.trx.Scalar(&userID, query, provider, uid, s.tenant.ID); err != nil {
- return nil, errors.Wrap(err, "failed to get user by provider '%s' and uid '%s'", provider, uid)
- }
- return s.GetByID(userID)
-}
-
-// Register creates a new user based on given information
-func (s *UserStorage) Register(user *models.User) error {
- now := time.Now()
- user.Status = models.UserActive
- user.Email = strings.ToLower(strings.TrimSpace(user.Email))
- if err := s.trx.Get(&user.ID,
- "INSERT INTO users (name, email, created_at, tenant_id, role, status, avatar_type, avatar_bkey) VALUES ($1, $2, $3, $4, $5, $6, $7, '') RETURNING id",
- user.Name, user.Email, now, s.tenant.ID, user.Role, models.UserActive, models.AvatarTypeGravatar); err != nil {
- return errors.Wrap(err, "failed to register new user")
- }
-
- for _, provider := range user.Providers {
- if _, err := s.trx.Execute("INSERT INTO user_providers (tenant_id, user_id, provider, provider_uid, created_at) VALUES ($1, $2, $3, $4, $5)", s.tenant.ID, user.ID, provider.Name, provider.UID, now); err != nil {
- return errors.Wrap(err, "failed to add provider to new user")
- }
- }
-
- return nil
-}
-
-// RegisterProvider adds given provider to userID
-func (s *UserStorage) RegisterProvider(userID int, provider *models.UserProvider) error {
- cmd := "INSERT INTO user_providers (tenant_id, user_id, provider, provider_uid, created_at) VALUES ($1, $2, $3, $4, $5)"
- _, err := s.trx.Execute(cmd, s.tenant.ID, userID, provider.Name, provider.UID, time.Now())
- if err != nil {
- return errors.Wrap(err, "failed to add provider '%s' to user with id '%d'", provider.Name, userID)
- }
- return nil
-}
-
-// Update user profile
-func (s *UserStorage) Update(settings *models.UpdateUserSettings) error {
- if settings.Avatar.Remove {
- settings.Avatar.BlobKey = ""
- }
- cmd := "UPDATE users SET name = $3, avatar_type = $4, avatar_bkey = $5 WHERE id = $1 AND tenant_id = $2"
- _, err := s.trx.Execute(cmd, s.user.ID, s.tenant.ID, settings.Name, settings.AvatarType, settings.Avatar.BlobKey)
- if err != nil {
- return errors.Wrap(err, "failed to update user")
- }
- return nil
-}
-
-// UpdateSettings of given user
-func (s *UserStorage) UpdateSettings(settings map[string]string) error {
- if s.user != nil && settings != nil && len(settings) > 0 {
- query := `
- INSERT INTO user_settings (tenant_id, user_id, key, value)
- VALUES ($1, $2, $3, $4) ON CONFLICT (user_id, key) DO UPDATE SET value = $4
- `
-
- for key, value := range settings {
- _, err := s.trx.Execute(query, s.tenant.ID, s.user.ID, key, value)
- if err != nil {
- return errors.Wrap(err, "failed to update user settings")
- }
- }
- }
-
- return nil
-}
-
-// GetUserSettings returns current user's settings
-func (s *UserStorage) GetUserSettings() (map[string]string, error) {
- if s.user == nil {
- return make(map[string]string, 0), nil
- }
-
- var settings []*dbUserSetting
- err := s.trx.Select(&settings, "SELECT key, value FROM user_settings WHERE user_id = $1 AND tenant_id = $2", s.user.ID, s.tenant.ID)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get user settings")
- }
-
- var result = make(map[string]string, len(settings))
-
- for _, e := range models.AllNotificationEvents {
- for _, r := range e.DefaultEnabledUserRoles {
- if r == s.user.Role {
- result[e.UserSettingsKeyName] = e.DefaultSettingValue
- }
- }
- }
-
- for _, s := range settings {
- result[s.Key] = s.Value
- }
- return result, nil
-}
-
-// ChangeRole of given user
-func (s *UserStorage) ChangeRole(userID int, role models.Role) error {
- cmd := "UPDATE users SET role = $3 WHERE id = $1 AND tenant_id = $2"
- _, err := s.trx.Execute(cmd, userID, s.tenant.ID, role)
- if err != nil {
- return errors.Wrap(err, "failed to change user's role")
- }
- return nil
-}
-
-// ChangeEmail of given user
-func (s *UserStorage) ChangeEmail(userID int, email string) error {
- cmd := "UPDATE users SET email = $3 WHERE id = $1 AND tenant_id = $2"
- _, err := s.trx.Execute(cmd, userID, s.tenant.ID, strings.ToLower(email))
- if err != nil {
- return errors.Wrap(err, "failed to update user's email")
- }
- return nil
-}
-
-// GetByID returns a user based on given id
-func (s *UserStorage) getUser(trx *dbx.Trx, filter string, args ...interface{}) (*models.User, error) {
- user := dbUser{}
- sql := fmt.Sprintf("SELECT id, name, email, tenant_id, role, status, avatar_type, avatar_bkey FROM users WHERE status != %d AND ", models.UserDeleted)
- err := trx.Get(&user, sql+filter, args...)
- if err != nil {
- return nil, err
- }
-
- err = trx.Select(&user.Providers, "SELECT provider_uid, provider FROM user_providers WHERE user_id = $1", user.ID.Int64)
- if err != nil {
- return nil, err
- }
-
- return user.toModel(s.ctx), nil
-}
-
-// GetAll return all users of current tenant
-func (s *UserStorage) GetAll() ([]*models.User, error) {
- var users []*dbUser
- err := s.trx.Select(&users, `
- SELECT id, name, email, tenant_id, role, status, avatar_type, avatar_bkey
- FROM users
- WHERE tenant_id = $1
- AND status != $2
- ORDER BY id`, s.tenant.ID, models.UserDeleted)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get all users")
- }
-
- var result = make([]*models.User, len(users))
- for i, user := range users {
- result[i] = user.toModel(s.ctx)
- }
- return result, nil
-}
-
-// HasSubscribedTo returns true if current user is receiving notification from specific post
-func (s *UserStorage) HasSubscribedTo(postID int) (bool, error) {
- if s.user == nil {
- return false, nil
- }
-
- var status int
- err := s.trx.Scalar(&status, "SELECT status FROM post_subscribers WHERE user_id = $1 AND post_id = $2", s.user.ID, postID)
- if err != nil && errors.Cause(err) != app.ErrNotFound {
- return false, errors.Wrap(err, "failed to get subscription status")
- }
-
- if errors.Cause(err) == app.ErrNotFound {
- for _, e := range models.AllNotificationEvents {
- for _, r := range e.RequiresSubscriptionUserRoles {
- if r == s.user.Role {
- return false, nil
- }
- }
- }
- return true, nil
- }
-
- if status == 1 {
- return true, nil
- }
-
- return false, nil
-}
-
-// Delete removes current user personal data and mark it as deleted
-func (s *UserStorage) Delete() error {
- if _, err := s.trx.Execute(
- "UPDATE users SET role = $3, status = $4, name = '', email = '', api_key = null, api_key_date = null WHERE id = $1 AND tenant_id = $2",
- s.user.ID, s.tenant.ID, models.RoleVisitor, models.UserDeleted,
- ); err != nil {
- return errors.Wrap(err, "failed to delete current user")
- }
-
- var tables = []struct {
- name string
- userColumn string
- }{
- {"user_providers", "user_id"},
- {"user_settings", "user_id"},
- {"notifications", "user_id"},
- {"notifications", "author_id"},
- {"post_votes", "user_id"},
- {"post_subscribers", "user_id"},
- {"email_verifications", "user_id"},
- }
-
- for _, table := range tables {
- if _, err := s.trx.Execute(
- fmt.Sprintf("DELETE FROM %s WHERE %s = $1 AND tenant_id = $2", table.name, table.userColumn),
- s.user.ID, s.tenant.ID,
- ); err != nil {
- return errors.Wrap(err, "failed to delete current user's %s records", table)
- }
- }
-
- return nil
-}
-
-// RegenerateAPIKey generates a new API Key and returns it
-func (s *UserStorage) RegenerateAPIKey() (string, error) {
- apiKey := models.GenerateSecretKey()
-
- if _, err := s.trx.Execute(
- "UPDATE users SET api_key = $3, api_key_date = $4 WHERE id = $1 AND tenant_id = $2",
- s.user.ID, s.tenant.ID, apiKey, time.Now(),
- ); err != nil {
- return "", errors.Wrap(err, "failed to update current user's API Key")
- }
-
- return apiKey, nil
-}
-
-// GetByAPIKey returns a user based on its API key
-func (s *UserStorage) GetByAPIKey(apiKey string) (*models.User, error) {
- user, err := s.getUser(s.trx, "api_key = $1 AND tenant_id = $2", apiKey, s.tenant.ID)
- if err != nil {
- return nil, errors.Wrap(err, "failed to get user with API Key '%s'", apiKey)
- }
- return user, nil
-}
-
-// Block a given user from using Fider
-func (s *UserStorage) Block(userID int) error {
- if _, err := s.trx.Execute(
- "UPDATE users SET status = $3 WHERE id = $1 AND tenant_id = $2",
- userID, s.tenant.ID, models.UserBlocked,
- ); err != nil {
- return errors.Wrap(err, "failed to block user")
- }
- return nil
-}
-
-// Unblock a given user so that they can use Fider again
-func (s *UserStorage) Unblock(userID int) error {
- if _, err := s.trx.Execute(
- "UPDATE users SET status = $3 WHERE id = $1 AND tenant_id = $2",
- userID, s.tenant.ID, models.UserActive,
- ); err != nil {
- return errors.Wrap(err, "failed to unblock user")
- }
- return nil
-}
-
-// Count returns the total number of registered users
-func (s *UserStorage) Count() (int, error) {
- var count int
- err := s.trx.Scalar(&count, "SELECT COUNT(*) FROM users WHERE tenant_id = $1", s.tenant.ID)
- if err != nil {
- return 0, errors.Wrap(err, "failed to count users")
- }
- return count, nil
-}
diff --git a/app/storage/postgres/user_test.go b/app/storage/postgres/user_test.go
deleted file mode 100644
index a1f794fa8..000000000
--- a/app/storage/postgres/user_test.go
+++ /dev/null
@@ -1,394 +0,0 @@
-package postgres_test
-
-import (
- "strings"
- "testing"
-
- "github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/oauth"
-)
-
-func TestUserStorage_GetByID(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- user, err := users.GetByID(1)
- Expect(err).IsNil()
- Expect(user.ID).Equals(int(1))
- Expect(user.Tenant.ID).Equals(1)
- Expect(user.Name).Equals("Jon Snow")
- Expect(user.Email).Equals("[email protected]")
- Expect(user.AvatarURL).Equals("http://cdn.test.fider.io/avatars/gravatar/1/Jon%20Snow")
- Expect(user.Providers).HasLen(1)
- Expect(user.Providers[0].UID).Equals("FB1234")
- Expect(user.Providers[0].Name).Equals("facebook")
-}
-
-func TestUserStorage_GetByEmail_Error(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- user, err := users.GetByEmail("[email protected]")
- Expect(user).IsNil()
- Expect(err).IsNotNil()
-}
-
-func TestUserStorage_GetByEmail(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- user, err := users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.ID).Equals(int(1))
- Expect(user.Tenant.ID).Equals(1)
- Expect(user.Name).Equals("Jon Snow")
- Expect(user.Email).Equals("[email protected]")
- Expect(user.Providers).HasLen(1)
- Expect(user.Providers[0].UID).Equals("FB1234")
- Expect(user.Providers[0].Name).Equals("facebook")
-
- user, err = users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.ID).Equals(int(1))
-}
-
-func TestUserStorage_GetByProvider(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- user, err := users.GetByProvider("facebook", "FB1234")
- Expect(err).IsNil()
- Expect(user.ID).Equals(int(1))
- Expect(user.Tenant.ID).Equals(1)
- Expect(user.Name).Equals("Jon Snow")
- Expect(user.Email).Equals("[email protected]")
- Expect(user.Providers).HasLen(1)
- Expect(user.Providers[0].UID).Equals("FB1234")
- Expect(user.Providers[0].Name).Equals("facebook")
-}
-
-func TestUserStorage_GetByProvider_WrongTenant(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(avengersTenant)
- user, err := users.GetByProvider("facebook", "FB1234")
- Expect(user).IsNil()
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
-}
-
-func TestUserStorage_GetByEmail_WrongTenant(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(avengersTenant)
- user, err := users.GetByEmail("[email protected]")
- Expect(user).IsNil()
- Expect(err).IsNotNil()
-}
-
-func TestUserStorage_Register(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- user := &models.User{
- Name: "Rob Stark",
- Email: "[email protected]",
- Role: models.RoleCollaborator,
- Providers: []*models.UserProvider{
- {
- UID: "123123123",
- Name: oauth.FacebookProvider,
- },
- },
- }
- err := users.Register(user)
- Expect(err).IsNil()
-
- user, err = users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.ID).Equals(int(6))
- Expect(user.Role).Equals(models.RoleCollaborator)
- Expect(user.Name).Equals("Rob Stark")
- Expect(user.Email).Equals("[email protected]")
- Expect(user.Status).Equals(models.UserActive)
-}
-
-func TestUserStorage_Register_WhiteSpaceEmail(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- user := &models.User{
- Name: "Rob Stark",
- Email: " ",
- Role: models.RoleCollaborator,
- }
- err := users.Register(user)
- Expect(err).IsNil()
-
- user, err = users.GetByID(user.ID)
- Expect(err).IsNil()
- Expect(user.Role).Equals(models.RoleCollaborator)
- Expect(user.Name).Equals("Rob Stark")
- Expect(user.Email).Equals("")
- Expect(user.Status).Equals(models.UserActive)
-}
-
-func TestUserStorage_Register_MultipleProviders(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- var tenantID int
- trx.Get(&tenantID, `
- INSERT INTO tenants (name, subdomain, created_at, status, is_private, custom_css, logo_bkey)
- VALUES ('My Domain Inc.','mydomain', now(), 1, false, '', '')
- RETURNING id
- `)
- users.SetCurrentTenant(&models.Tenant{
- ID: tenantID,
- })
-
- user := &models.User{
- Name: "Jon Snow",
- Email: "[email protected]",
- Role: models.RoleCollaborator,
- Providers: []*models.UserProvider{
- {
- UID: "123123123",
- Name: oauth.FacebookProvider,
- },
- {
- UID: "456456456",
- Name: oauth.GoogleProvider,
- },
- },
- }
-
- err := users.Register(user)
- Expect(err).IsNil()
- Expect(user.ID).NotEquals(0)
- Expect(user.Name).Equals("Jon Snow")
- Expect(user.Email).Equals("[email protected]")
- Expect(user.Status).Equals(models.UserActive)
-}
-
-func TestUserStorage_RegisterProvider(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- users.RegisterProvider(1, &models.UserProvider{
- UID: "GO1234",
- Name: "google",
- })
- user, err := users.GetByID(1)
-
- Expect(err).IsNil()
- Expect(user.ID).Equals(int(1))
- Expect(user.Name).Equals("Jon Snow")
- Expect(user.Email).Equals("[email protected]")
- Expect(user.Tenant.ID).Equals(1)
- Expect(user.Status).Equals(models.UserActive)
-
- Expect(user.Providers).HasLen(2)
- Expect(user.Providers[0].UID).Equals("FB1234")
- Expect(user.Providers[0].Name).Equals("facebook")
- Expect(user.Providers[1].UID).Equals("GO1234")
- Expect(user.Providers[1].Name).Equals("google")
-}
-
-func TestUserStorage_UpdateSettings(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- users.SetCurrentUser(jonSnow)
- err := users.Update(&models.UpdateUserSettings{
- Name: "Jon Stark",
- Avatar: &models.ImageUpload{
- BlobKey: "jon.png",
- },
- })
- Expect(err).IsNil()
-
- user, err := users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.Name).Equals("Jon Stark")
- Expect(user.AvatarBlobKey).Equals("jon.png")
-}
-
-func TestUserStorage_ChangeRole(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- err := users.ChangeRole(jonSnow.ID, models.RoleVisitor)
- Expect(err).IsNil()
-
- user, err := users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.Role).Equals(models.RoleVisitor)
-}
-
-func TestUserStorage_ChangeEmail(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- err := users.ChangeEmail(jonSnow.ID, "[email protected]")
- Expect(err).IsNil()
-
- user, err := users.GetByEmail("[email protected]")
- Expect(err).IsNil()
- Expect(user.Email).Equals("[email protected]")
-
- user, err = users.GetByEmail("[email protected]")
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(user).IsNil()
-}
-
-func TestUserStorage_GetAll(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
-
- all, err := users.GetAll()
- Expect(err).IsNil()
- Expect(all).HasLen(3)
- Expect(all[0].Name).Equals("Jon Snow")
- Expect(all[0].Status).Equals(models.UserActive)
- Expect(all[1].Name).Equals("Arya Stark")
- Expect(all[1].Status).Equals(models.UserActive)
- Expect(all[2].Name).Equals("Sansa Stark")
- Expect(all[2].Status).Equals(models.UserActive)
-}
-
-func TestUserStorage_DefaultUserSettings(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentUser(jonSnow)
- settings, _ := users.GetUserSettings()
- Expect(settings).Equals(map[string]string{
- models.NotificationEventNewPost.UserSettingsKeyName: models.NotificationEventNewPost.DefaultSettingValue,
- models.NotificationEventNewComment.UserSettingsKeyName: models.NotificationEventNewComment.DefaultSettingValue,
- models.NotificationEventChangeStatus.UserSettingsKeyName: models.NotificationEventChangeStatus.DefaultSettingValue,
- })
-
- users.SetCurrentUser(aryaStark)
- settings, _ = users.GetUserSettings()
- Expect(settings).Equals(map[string]string{
- models.NotificationEventNewComment.UserSettingsKeyName: models.NotificationEventNewComment.DefaultSettingValue,
- models.NotificationEventChangeStatus.UserSettingsKeyName: models.NotificationEventChangeStatus.DefaultSettingValue,
- })
-}
-
-func TestUserStorage_SaveGetUserSettings(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- users.SetCurrentUser(aryaStark)
- disableAll := map[string]string{
- models.NotificationEventNewPost.UserSettingsKeyName: "0",
- models.NotificationEventChangeStatus.UserSettingsKeyName: "0",
- }
-
- users.UpdateSettings(disableAll)
- settings, _ := users.GetUserSettings()
- Expect(settings).Equals(map[string]string{
- models.NotificationEventNewPost.UserSettingsKeyName: "0",
- models.NotificationEventNewComment.UserSettingsKeyName: models.NotificationEventNewComment.DefaultSettingValue,
- models.NotificationEventChangeStatus.UserSettingsKeyName: "0",
- })
-
- users.UpdateSettings(nil)
- newSettings, _ := users.GetUserSettings()
- Expect(newSettings).Equals(settings)
-}
-
-func TestUserStorage_Delete(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- users.SetCurrentUser(jonSnow)
-
- err := users.Delete()
- Expect(err).IsNil()
-
- user, err := users.GetByEmail("[email protected]")
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(user).IsNil()
-
- user, err = users.GetByID(jonSnow.ID)
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
- Expect(user).IsNil()
-}
-
-func TestUserStorage_APIKey(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- users.SetCurrentUser(jonSnow)
-
- apiKey, err := users.RegenerateAPIKey()
- Expect(apiKey).HasLen(64)
- Expect(err).IsNil()
-
- user, err := users.GetByAPIKey(apiKey)
- Expect(user).Equals(jonSnow)
- Expect(err).IsNil()
-
- //try to get by uppercase key
- user, err = users.GetByAPIKey(strings.ToUpper(apiKey))
- Expect(user).IsNil()
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
-
- //regenerate and try to get again
- users.RegenerateAPIKey()
- user, err = users.GetByAPIKey(apiKey)
- Expect(user).IsNil()
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
-
- //try to get by some unknown key
- user, err = users.GetByAPIKey("SOME-INVALID-KEY")
- Expect(user).IsNil()
- Expect(errors.Cause(err)).Equals(app.ErrNotFound)
-}
-
-func TestUserStorage_BlockUser(t *testing.T) {
- SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- users.SetCurrentTenant(demoTenant)
- userID := 1
-
- user, err := users.GetByID(userID)
- Expect(err).IsNil()
- Expect(user.Status).Equals(models.UserActive)
-
- err = users.Block(userID)
- Expect(err).IsNil()
-
- user, err = users.GetByID(userID)
- Expect(err).IsNil()
- Expect(user.Status).Equals(models.UserBlocked)
-
- err = users.Unblock(userID)
- Expect(err).IsNil()
-
- user, err = users.GetByID(userID)
- Expect(err).IsNil()
- Expect(user.Status).Equals(models.UserActive)
-}
diff --git a/app/storage/storage.go b/app/storage/storage.go
deleted file mode 100644
index ba61f2a8e..000000000
--- a/app/storage/storage.go
+++ /dev/null
@@ -1,124 +0,0 @@
-package storage
-
-import (
- "time"
-
- "github.com/getfider/fider/app/models"
-)
-
-// Context holds everything storages need to know about execution context
-type Context interface {
- TenantAssetsURL(path string, a ...interface{}) string
-}
-
-// Base is a generic storage base interface
-type Base interface {
- SetCurrentTenant(*models.Tenant)
- SetCurrentUser(*models.User)
-}
-
-// Post contains read and write operations for posts
-type Post interface {
- Base
- GetByID(postID int) (*models.Post, error)
- GetBySlug(slug string) (*models.Post, error)
- GetByNumber(number int) (*models.Post, error)
- GetCommentsByPost(post *models.Post) ([]*models.Comment, error)
- Search(query, view, limit string, tags []string) ([]*models.Post, error)
- GetAll() ([]*models.Post, error)
- CountPerStatus() (map[models.PostStatus]int, error)
- Add(title, description string) (*models.Post, error)
- Update(post *models.Post, title, description string) (*models.Post, error)
- AddComment(post *models.Post, content string) (int, error)
- GetCommentByID(id int) (*models.Comment, error)
- UpdateComment(id int, content string) error
- DeleteComment(id int) error
- AddVote(post *models.Post, user *models.User) error
- RemoveVote(post *models.Post, user *models.User) error
- AddSubscriber(post *models.Post, user *models.User) error
- RemoveSubscriber(post *models.Post, user *models.User) error
- GetActiveSubscribers(number int, channel models.NotificationChannel, event models.NotificationEvent) ([]*models.User, error)
- SetResponse(post *models.Post, text string, status models.PostStatus) error
- MarkAsDuplicate(post *models.Post, original *models.Post) error
- IsReferenced(post *models.Post) (bool, error)
- VotedBy() ([]int, error)
- ListVotes(post *models.Post, limit int) ([]*models.Vote, error)
- GetAttachments(post *models.Post, comment *models.Comment) ([]string, error)
- SetAttachments(post *models.Post, comment *models.Comment, attachments []*models.ImageUpload) error
-}
-
-// User is used for user operations
-type User interface {
- Base
- GetByID(userID int) (*models.User, error)
- GetByEmail(email string) (*models.User, error)
- GetByProvider(provider string, uid string) (*models.User, error)
- Register(user *models.User) error
- RegisterProvider(userID int, provider *models.UserProvider) error
- Update(settings *models.UpdateUserSettings) error
- Delete() error
- ChangeEmail(userID int, email string) error
- ChangeRole(userID int, role models.Role) error
- GetAll() ([]*models.User, error)
- GetUserSettings() (map[string]string, error)
- UpdateSettings(settings map[string]string) error
- HasSubscribedTo(postID int) (bool, error)
- GetByAPIKey(apiKey string) (*models.User, error)
- RegenerateAPIKey() (string, error)
- Block(userID int) error
- Unblock(userID int) error
- Count() (int, error)
-}
-
-// Tenant contains read and write operations for tenants
-type Tenant interface {
- Base
- Current() *models.Tenant
- Add(name string, subdomain string, status int) (*models.Tenant, error)
- First() (*models.Tenant, error)
- Activate(id int) error
- GetByDomain(domain string) (*models.Tenant, error)
- UpdateSettings(settings *models.UpdateTenantSettings) error
- UpdateBillingSettings(billing *models.TenantBilling) error
- UpdateAdvancedSettings(settings *models.UpdateTenantAdvancedSettings) error
- UpdatePrivacy(settings *models.UpdateTenantPrivacy) error
- IsSubdomainAvailable(subdomain string) (bool, error)
- IsCNAMEAvailable(cname string) (bool, error)
- SaveVerificationKey(key string, duration time.Duration, request models.NewEmailVerification) error
- FindVerificationByKey(kind models.EmailVerificationKind, key string) (*models.EmailVerification, error)
- SetKeyAsVerified(key string) error
- SaveOAuthConfig(config *models.CreateEditOAuthConfig) error
- GetOAuthConfigByProvider(provider string) (*models.OAuthConfig, error)
- ListOAuthConfig() ([]*models.OAuthConfig, error)
-}
-
-// Tag contains read and write operations for tags
-type Tag interface {
- Base
- Add(name, color string, isPublic bool) (*models.Tag, error)
- GetBySlug(slug string) (*models.Tag, error)
- Update(tag *models.Tag, name, color string, isPublic bool) (*models.Tag, error)
- Delete(tag *models.Tag) error
- GetAssigned(post *models.Post) ([]*models.Tag, error)
- AssignTag(tag *models.Tag, post *models.Post) error
- UnassignTag(tag *models.Tag, post *models.Post) error
- GetAll() ([]*models.Tag, error)
-}
-
-// Notification contains read and write operations for notifications
-type Notification interface {
- Base
- Insert(user *models.User, title, link string, postID int) (*models.Notification, error)
- MarkAsRead(id int) error
- MarkAllAsRead() error
- TotalUnread() (int, error)
- GetActiveNotifications() ([]*models.Notification, error)
- GetNotification(id int) (*models.Notification, error)
-}
-
-// Event contains read and write operations for Audit Events
-type Event interface {
- Base
- Add(clientIP, name string) (*models.Event, error)
- GetByID(id int) (*models.Event, error)
-}
diff --git a/app/tasks/tasks.go b/app/tasks/tasks.go
index 17a6509c4..d4ae046c2 100644
--- a/app/tasks/tasks.go
+++ b/app/tasks/tasks.go
@@ -1,6 +1,7 @@
package tasks
import (
+ "context"
"fmt"
"html/template"
"strings"
@@ -8,8 +9,13 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/email"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
+ "github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/markdown"
+ "github.com/getfider/fider/app/pkg/web"
"github.com/getfider/fider/app/pkg/worker"
)
@@ -28,22 +34,41 @@ func linkWithText(text, baseURL, path string, args ...interface{}) template.HTML
//SendSignUpEmail is used to send the sign up email to requestor
func SendSignUpEmail(model *models.CreateTenant, baseURL string) worker.Task {
return describe("Send sign up email", func(c *worker.Context) error {
- to := email.NewRecipient(model.Name, model.Email, email.Params{
- "logo": "https://getfider.com/images/logo-100x100.png",
+ to := dto.NewRecipient(model.Name, model.Email, dto.Props{
"link": link(baseURL, "/signup/verify?k=%s", model.VerificationKey),
})
- return c.Services().Emailer.Send(c, "signup_email", email.Params{}, "Fider", to)
+
+ bus.Publish(c, &cmd.SendMail{
+ From: "Fider",
+ To: []dto.Recipient{to},
+ TemplateName: "signup_email",
+ Props: dto.Props{
+ "logo": web.LogoURL(c),
+ },
+ })
+
+ return nil
})
}
//SendSignInEmail is used to send the sign in email to requestor
func SendSignInEmail(model *models.SignInByEmail) worker.Task {
return describe("Send sign in email", func(c *worker.Context) error {
- to := email.NewRecipient("", model.Email, email.Params{
+ to := dto.NewRecipient("", model.Email, dto.Props{
"tenantName": c.Tenant().Name,
- "link": link(c.BaseURL(), "/signin/verify?k=%s", model.VerificationKey),
+ "link": link(web.BaseURL(c), "/signin/verify?k=%s", model.VerificationKey),
})
- return c.Services().Emailer.Send(c, "signin_email", email.Params{}, c.Tenant().Name, to)
+
+ bus.Publish(c, &cmd.SendMail{
+ From: c.Tenant().Name,
+ To: []dto.Recipient{to},
+ TemplateName: "signin_email",
+ Props: dto.Props{
+ "logo": web.LogoURL(c),
+ },
+ })
+
+ return nil
})
}
@@ -55,13 +80,23 @@ func SendChangeEmailConfirmation(model *models.ChangeUserEmail) worker.Task {
previous = "(empty)"
}
- to := email.NewRecipient(model.Requestor.Name, model.Email, email.Params{
+ to := dto.NewRecipient(model.Requestor.Name, model.Email, dto.Props{
"name": c.User().Name,
"oldEmail": previous,
"newEmail": model.Email,
- "link": link(c.BaseURL(), "/change-email/verify?k=%s", model.VerificationKey),
+ "link": link(web.BaseURL(c), "/change-email/verify?k=%s", model.VerificationKey),
})
- return c.Services().Emailer.Send(c, "change_emailaddress_email", email.Params{}, c.Tenant().Name, to)
+
+ bus.Publish(c, &cmd.SendMail{
+ From: c.Tenant().Name,
+ To: []dto.Recipient{to},
+ TemplateName: "change_emailaddress_email",
+ Props: dto.Props{
+ "logo": web.LogoURL(c),
+ },
+ })
+
+ return nil
})
}
@@ -69,7 +104,7 @@ func SendChangeEmailConfirmation(model *models.ChangeUserEmail) worker.Task {
func NotifyAboutNewPost(post *models.Post) worker.Task {
return describe("Notify about new post", func(c *worker.Context) error {
// Web notification
- users, err := c.Services().Posts.GetActiveSubscribers(post.Number, models.NotificationChannelWeb, models.NotificationEventNewPost)
+ users, err := getActiveSubscribers(c, post, enum.NotificationChannelWeb, enum.NotificationEventNewPost)
if err != nil {
return c.Failure(err)
}
@@ -78,36 +113,50 @@ func NotifyAboutNewPost(post *models.Post) worker.Task {
link := fmt.Sprintf("/posts/%d/%s", post.Number, post.Slug)
for _, user := range users {
if user.ID != c.User().ID {
- if _, err = c.Services().Notifications.Insert(user, title, link, post.ID); err != nil {
+ err = bus.Dispatch(c, &cmd.AddNewNotification{
+ User: user,
+ Title: title,
+ Link: link,
+ PostID: post.ID,
+ })
+ if err != nil {
return c.Failure(err)
}
}
}
// Email notification
- users, err = c.Services().Posts.GetActiveSubscribers(post.Number, models.NotificationChannelEmail, models.NotificationEventNewPost)
+ users, err = getActiveSubscribers(c, post, enum.NotificationChannelEmail, enum.NotificationEventNewPost)
if err != nil {
return c.Failure(err)
}
- to := make([]email.Recipient, 0)
+ to := make([]dto.Recipient, 0)
for _, user := range users {
if user.ID != c.User().ID {
- to = append(to, email.NewRecipient(user.Name, user.Email, email.Params{}))
+ to = append(to, dto.NewRecipient(user.Name, user.Email, dto.Props{}))
}
}
- params := email.Params{
+ props := dto.Props{
"title": post.Title,
"tenantName": c.Tenant().Name,
"userName": c.User().Name,
"content": markdown.Simple(post.Description),
- "postLink": linkWithText(fmt.Sprintf("#%d", post.Number), c.BaseURL(), "/posts/%d/%s", post.Number, post.Slug),
- "view": linkWithText("View it on your browser", c.BaseURL(), "/posts/%d/%s", post.Number, post.Slug),
- "change": linkWithText("change your notification settings", c.BaseURL(), "/settings"),
+ "postLink": linkWithText(fmt.Sprintf("#%d", post.Number), web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),
+ "view": linkWithText("View it on your browser", web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),
+ "change": linkWithText("change your notification settings", web.BaseURL(c), "/settings"),
+ "logo": web.LogoURL(c),
}
- return c.Services().Emailer.BatchSend(c, "new_post", params, c.User().Name, to)
+ bus.Publish(c, &cmd.SendMail{
+ From: c.User().Name,
+ To: to,
+ TemplateName: "new_post",
+ Props: props,
+ })
+
+ return nil
})
}
@@ -115,7 +164,7 @@ func NotifyAboutNewPost(post *models.Post) worker.Task {
func NotifyAboutNewComment(post *models.Post, comment *models.NewComment) worker.Task {
return describe("Notify about new comment", func(c *worker.Context) error {
// Web notification
- users, err := c.Services().Posts.GetActiveSubscribers(post.Number, models.NotificationChannelWeb, models.NotificationEventNewComment)
+ users, err := getActiveSubscribers(c, post, enum.NotificationChannelWeb, enum.NotificationEventNewComment)
if err != nil {
return c.Failure(err)
}
@@ -124,42 +173,56 @@ func NotifyAboutNewComment(post *models.Post, comment *models.NewComment) worker
link := fmt.Sprintf("/posts/%d/%s", post.Number, post.Slug)
for _, user := range users {
if user.ID != c.User().ID {
- if _, err = c.Services().Notifications.Insert(user, title, link, post.ID); err != nil {
+ err = bus.Dispatch(c, &cmd.AddNewNotification{
+ User: user,
+ Title: title,
+ Link: link,
+ PostID: post.ID,
+ })
+ if err != nil {
return c.Failure(err)
}
}
}
// Email notification
- users, err = c.Services().Posts.GetActiveSubscribers(post.Number, models.NotificationChannelEmail, models.NotificationEventNewComment)
+ users, err = getActiveSubscribers(c, post, enum.NotificationChannelEmail, enum.NotificationEventNewComment)
if err != nil {
return c.Failure(err)
}
- to := make([]email.Recipient, 0)
+ to := make([]dto.Recipient, 0)
for _, user := range users {
if user.ID != c.User().ID {
- to = append(to, email.NewRecipient(user.Name, user.Email, email.Params{}))
+ to = append(to, dto.NewRecipient(user.Name, user.Email, dto.Props{}))
}
}
- params := email.Params{
+ props := dto.Props{
"title": post.Title,
"tenantName": c.Tenant().Name,
"userName": c.User().Name,
"content": markdown.Simple(comment.Content),
- "postLink": linkWithText(fmt.Sprintf("#%d", post.Number), c.BaseURL(), "/posts/%d/%s", post.Number, post.Slug),
- "view": linkWithText("View it on your browser", c.BaseURL(), "/posts/%d/%s", post.Number, post.Slug),
- "unsubscribe": linkWithText("unsubscribe from it", c.BaseURL(), "/posts/%d/%s", post.Number, post.Slug),
- "change": linkWithText("change your notification settings", c.BaseURL(), "/settings"),
+ "postLink": linkWithText(fmt.Sprintf("#%d", post.Number), web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),
+ "view": linkWithText("View it on your browser", web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),
+ "unsubscribe": linkWithText("unsubscribe from it", web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),
+ "change": linkWithText("change your notification settings", web.BaseURL(c), "/settings"),
+ "logo": web.LogoURL(c),
}
- return c.Services().Emailer.BatchSend(c, "new_comment", params, c.User().Name, to)
+ bus.Publish(c, &cmd.SendMail{
+ From: c.User().Name,
+ To: to,
+ TemplateName: "new_comment",
+ Props: props,
+ })
+
+ return nil
})
}
//NotifyAboutStatusChange sends a notification (web and email) to subscribers
-func NotifyAboutStatusChange(post *models.Post, prevStatus models.PostStatus) worker.Task {
+func NotifyAboutStatusChange(post *models.Post, prevStatus enum.PostStatus) worker.Task {
return describe("Notify about post status change", func(c *worker.Context) error {
//Don't notify if previous status is the same
if prevStatus == post.Status {
@@ -167,7 +230,7 @@ func NotifyAboutStatusChange(post *models.Post, prevStatus models.PostStatus) wo
}
// Web notification
- users, err := c.Services().Posts.GetActiveSubscribers(post.Number, models.NotificationChannelWeb, models.NotificationEventChangeStatus)
+ users, err := getActiveSubscribers(c, post, enum.NotificationChannelWeb, enum.NotificationEventChangeStatus)
if err != nil {
return c.Failure(err)
}
@@ -176,47 +239,57 @@ func NotifyAboutStatusChange(post *models.Post, prevStatus models.PostStatus) wo
link := fmt.Sprintf("/posts/%d/%s", post.Number, post.Slug)
for _, user := range users {
if user.ID != c.User().ID {
- if _, err = c.Services().Notifications.Insert(user, title, link, post.ID); err != nil {
+ err = bus.Dispatch(c, &cmd.AddNewNotification{
+ User: user,
+ Title: title,
+ Link: link,
+ PostID: post.ID,
+ })
+ if err != nil {
return c.Failure(err)
}
}
}
// Email notification
- users, err = c.Services().Posts.GetActiveSubscribers(post.Number, models.NotificationChannelEmail, models.NotificationEventChangeStatus)
+ users, err = getActiveSubscribers(c, post, enum.NotificationChannelEmail, enum.NotificationEventChangeStatus)
if err != nil {
return c.Failure(err)
}
var duplicate template.HTML
- if post.Status == models.PostDuplicate {
- originalPost, err := c.Services().Posts.GetByNumber(post.Response.Original.Number)
- if err != nil {
- return c.Failure(err)
- }
- duplicate = linkWithText(originalPost.Title, c.BaseURL(), "/posts/%d/%s", originalPost.Number, originalPost.Slug)
+ if post.Status == enum.PostDuplicate {
+ duplicate = linkWithText(post.Response.Original.Title, web.BaseURL(c), "/posts/%d/%s", post.Response.Original.Number, post.Response.Original.Slug)
}
- to := make([]email.Recipient, 0)
+ to := make([]dto.Recipient, 0)
for _, user := range users {
if user.ID != c.User().ID {
- to = append(to, email.NewRecipient(user.Name, user.Email, email.Params{}))
+ to = append(to, dto.NewRecipient(user.Name, user.Email, dto.Props{}))
}
}
- params := email.Params{
+ props := dto.Props{
"title": post.Title,
- "postLink": linkWithText(fmt.Sprintf("#%d", post.Number), c.BaseURL(), "/posts/%d/%s", post.Number, post.Slug),
+ "postLink": linkWithText(fmt.Sprintf("#%d", post.Number), web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),
"tenantName": c.Tenant().Name,
"content": markdown.Simple(post.Response.Text),
"status": post.Status.Name(),
"duplicate": duplicate,
- "view": linkWithText("View it on your browser", c.BaseURL(), "/posts/%d/%s", post.Number, post.Slug),
- "unsubscribe": linkWithText("unsubscribe from it", c.BaseURL(), "/posts/%d/%s", post.Number, post.Slug),
- "change": linkWithText("change your notification settings", c.BaseURL(), "/settings"),
+ "view": linkWithText("View it on your browser", web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),
+ "unsubscribe": linkWithText("unsubscribe from it", web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),
+ "change": linkWithText("change your notification settings", web.BaseURL(c), "/settings"),
+ "logo": web.LogoURL(c),
}
- return c.Services().Emailer.BatchSend(c, "change_status", params, c.User().Name, to)
+ bus.Publish(c, &cmd.SendMail{
+ From: c.User().Name,
+ To: to,
+ TemplateName: "change_status",
+ Props: props,
+ })
+
+ return nil
})
}
@@ -225,7 +298,7 @@ func NotifyAboutDeletedPost(post *models.Post) worker.Task {
return describe("Notify about deleted post", func(c *worker.Context) error {
// Web notification
- users, err := c.Services().Posts.GetActiveSubscribers(post.Number, models.NotificationChannelWeb, models.NotificationEventChangeStatus)
+ users, err := getActiveSubscribers(c, post, enum.NotificationChannelWeb, enum.NotificationEventChangeStatus)
if err != nil {
return c.Failure(err)
}
@@ -233,54 +306,90 @@ func NotifyAboutDeletedPost(post *models.Post) worker.Task {
title := fmt.Sprintf("**%s** deleted **%s**", c.User().Name, post.Title)
for _, user := range users {
if user.ID != c.User().ID {
- if _, err = c.Services().Notifications.Insert(user, title, "", post.ID); err != nil {
+ err = bus.Dispatch(c, &cmd.AddNewNotification{
+ User: user,
+ Title: title,
+ PostID: post.ID,
+ })
+ if err != nil {
return c.Failure(err)
}
}
}
// Email notification
- users, err = c.Services().Posts.GetActiveSubscribers(post.Number, models.NotificationChannelEmail, models.NotificationEventChangeStatus)
+ users, err = getActiveSubscribers(c, post, enum.NotificationChannelEmail, enum.NotificationEventChangeStatus)
if err != nil {
return c.Failure(err)
}
- to := make([]email.Recipient, 0)
+ to := make([]dto.Recipient, 0)
for _, user := range users {
if user.ID != c.User().ID {
- to = append(to, email.NewRecipient(user.Name, user.Email, email.Params{}))
+ to = append(to, dto.NewRecipient(user.Name, user.Email, dto.Props{}))
}
}
- params := email.Params{
+ props := dto.Props{
"title": post.Title,
"tenantName": c.Tenant().Name,
"content": markdown.Simple(post.Response.Text),
- "change": linkWithText("change your notification settings", c.BaseURL(), "/settings"),
+ "change": linkWithText("change your notification settings", web.BaseURL(c), "/settings"),
+ "logo": web.LogoURL(c),
}
- return c.Services().Emailer.BatchSend(c, "delete_post", params, c.User().Name, to)
+ bus.Publish(c, &cmd.SendMail{
+ From: c.User().Name,
+ To: to,
+ TemplateName: "delete_post",
+ Props: props,
+ })
+
+ return nil
})
}
//SendInvites sends one email to each invited recipient
func SendInvites(subject, message string, invitations []*models.UserInvitation) worker.Task {
return describe("Send invites", func(c *worker.Context) error {
- to := make([]email.Recipient, len(invitations))
+ to := make([]dto.Recipient, len(invitations))
for i, invite := range invitations {
- err := c.Services().Tenants.SaveVerificationKey(invite.VerificationKey, 15*24*time.Hour, invite)
+ err := bus.Dispatch(c, &cmd.SaveVerificationKey{
+ Key: invite.VerificationKey,
+ Duration: 15 * 24 * time.Hour,
+ Request: invite,
+ })
if err != nil {
return c.Failure(err)
}
- url := fmt.Sprintf("%s/invite/verify?k=%s", c.BaseURL(), invite.VerificationKey)
+ url := fmt.Sprintf("%s/invite/verify?k=%s", web.BaseURL(c), invite.VerificationKey)
toMessage := strings.Replace(message, app.InvitePlaceholder, string(url), -1)
- to[i] = email.NewRecipient("", invite.Email, email.Params{
+ to[i] = dto.NewRecipient("", invite.Email, dto.Props{
"message": markdown.Full(toMessage),
})
}
- return c.Services().Emailer.BatchSend(c, "invite_email", email.Params{
- "subject": subject,
- }, c.User().Name, to)
+
+ bus.Publish(c, &cmd.SendMail{
+ From: c.User().Name,
+ To: to,
+ TemplateName: "invite_email",
+ Props: dto.Props{
+ "subject": subject,
+ "logo": web.LogoURL(c),
+ },
+ })
+
+ return nil
})
}
+
+func getActiveSubscribers(ctx context.Context, post *models.Post, channel enum.NotificationChannel, event enum.NotificationEvent) ([]*models.User, error) {
+ q := &query.GetActiveSubscribers{
+ Number: post.Number,
+ Channel: channel,
+ Event: event,
+ }
+ err := bus.Dispatch(ctx, q)
+ return q.Result, err
+}
diff --git a/app/tasks/tasks_test.go b/app/tasks/tasks_test.go
index ccd4cf32d..6f7d2d206 100644
--- a/app/tasks/tasks_test.go
+++ b/app/tasks/tasks_test.go
@@ -1,25 +1,29 @@
package tasks_test
import (
+ "context"
"html/template"
"testing"
"time"
- "github.com/getfider/fider/app/pkg/email"
-
- "github.com/getfider/fider/app/pkg/email/noop"
- "github.com/getfider/fider/app/pkg/mock"
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
. "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/mock"
+ "github.com/getfider/fider/app/services/email/emailmock"
"github.com/getfider/fider/app/tasks"
)
func TestSendSignUpEmailTask(t *testing.T) {
RegisterT(t)
+ bus.Init(emailmock.Service{})
- worker, services := mock.NewWorker()
- emailer := services.Emailer.(*noop.Sender)
+ worker := mock.NewWorker()
task := tasks.SendSignUpEmail(&models.CreateTenant{
VerificationKey: "1234",
}, "http://domain.com")
@@ -29,15 +33,16 @@ func TestSendSignUpEmailTask(t *testing.T) {
Execute(task)
Expect(err).IsNil()
- Expect(emailer.Requests).HasLen(1)
- Expect(emailer.Requests[0].TemplateName).Equals("signup_email")
- Expect(emailer.Requests[0].Context.Tenant()).IsNil()
- Expect(emailer.Requests[0].Params).Equals(email.Params{})
- Expect(emailer.Requests[0].From).Equals("Fider")
- Expect(emailer.Requests[0].To).HasLen(1)
- Expect(emailer.Requests[0].To[0]).Equals(email.Recipient{
- Params: email.Params{
- "logo": "https://getfider.com/images/logo-100x100.png",
+ Expect(emailmock.MessageHistory).HasLen(1)
+ Expect(emailmock.MessageHistory[0].TemplateName).Equals("signup_email")
+ Expect(emailmock.MessageHistory[0].Tenant).IsNil()
+ Expect(emailmock.MessageHistory[0].Props).Equals(dto.Props{
+ "logo": "https://getfider.com/images/logo-100x100.png",
+ })
+ Expect(emailmock.MessageHistory[0].From).Equals("Fider")
+ Expect(emailmock.MessageHistory[0].To).HasLen(1)
+ Expect(emailmock.MessageHistory[0].To[0]).Equals(dto.Recipient{
+ Props: dto.Props{
"link": template.HTML("<a href='http://domain.com/signup/verify?k=1234'>http://domain.com/signup/verify?k=1234</a>"),
},
})
@@ -45,9 +50,9 @@ func TestSendSignUpEmailTask(t *testing.T) {
func TestSendSignInEmailTask(t *testing.T) {
RegisterT(t)
+ bus.Init(emailmock.Service{})
- worker, services := mock.NewWorker()
- emailer := services.Emailer.(*noop.Sender)
+ worker := mock.NewWorker()
task := tasks.SendSignInEmail(&models.SignInByEmail{
VerificationKey: "9876",
})
@@ -59,14 +64,16 @@ func TestSendSignInEmailTask(t *testing.T) {
Execute(task)
Expect(err).IsNil()
- Expect(emailer.Requests).HasLen(1)
- Expect(emailer.Requests[0].TemplateName).Equals("signin_email")
- Expect(emailer.Requests[0].Context.Tenant()).Equals(mock.DemoTenant)
- Expect(emailer.Requests[0].Params).Equals(email.Params{})
- Expect(emailer.Requests[0].From).Equals(mock.DemoTenant.Name)
- Expect(emailer.Requests[0].To).HasLen(1)
- Expect(emailer.Requests[0].To[0]).Equals(email.Recipient{
- Params: email.Params{
+ Expect(emailmock.MessageHistory).HasLen(1)
+ Expect(emailmock.MessageHistory[0].TemplateName).Equals("signin_email")
+ Expect(emailmock.MessageHistory[0].Tenant).Equals(mock.DemoTenant)
+ Expect(emailmock.MessageHistory[0].Props).Equals(dto.Props{
+ "logo": "https://getfider.com/images/logo-100x100.png",
+ })
+ Expect(emailmock.MessageHistory[0].From).Equals(mock.DemoTenant.Name)
+ Expect(emailmock.MessageHistory[0].To).HasLen(1)
+ Expect(emailmock.MessageHistory[0].To[0]).Equals(dto.Recipient{
+ Props: dto.Props{
"tenantName": mock.DemoTenant.Name,
"link": template.HTML("<a href='http://domain.com/signin/verify?k=9876'>http://domain.com/signin/verify?k=9876</a>"),
},
@@ -75,9 +82,9 @@ func TestSendSignInEmailTask(t *testing.T) {
func TestSendChangeEmailConfirmationTask(t *testing.T) {
RegisterT(t)
+ bus.Init(emailmock.Service{})
- worker, services := mock.NewWorker()
- emailer := services.Emailer.(*noop.Sender)
+ worker := mock.NewWorker()
task := tasks.SendChangeEmailConfirmation(&models.ChangeUserEmail{
VerificationKey: "13579",
@@ -91,16 +98,18 @@ func TestSendChangeEmailConfirmationTask(t *testing.T) {
Execute(task)
Expect(err).IsNil()
- Expect(emailer.Requests).HasLen(1)
- Expect(emailer.Requests[0].TemplateName).Equals("change_emailaddress_email")
- Expect(emailer.Requests[0].Context.Tenant()).Equals(mock.DemoTenant)
- Expect(emailer.Requests[0].Params).Equals(email.Params{})
- Expect(emailer.Requests[0].From).Equals(mock.DemoTenant.Name)
- Expect(emailer.Requests[0].To).HasLen(1)
- Expect(emailer.Requests[0].To[0]).Equals(email.Recipient{
+ Expect(emailmock.MessageHistory).HasLen(1)
+ Expect(emailmock.MessageHistory[0].TemplateName).Equals("change_emailaddress_email")
+ Expect(emailmock.MessageHistory[0].Tenant).Equals(mock.DemoTenant)
+ Expect(emailmock.MessageHistory[0].Props).Equals(dto.Props{
+ "logo": "https://getfider.com/images/logo-100x100.png",
+ })
+ Expect(emailmock.MessageHistory[0].From).Equals(mock.DemoTenant.Name)
+ Expect(emailmock.MessageHistory[0].To).HasLen(1)
+ Expect(emailmock.MessageHistory[0].To[0]).Equals(dto.Recipient{
Name: "Jon Snow",
Address: "[email protected]",
- Params: email.Params{
+ Props: dto.Props{
"name": "Jon Snow",
"oldEmail": "[email protected]",
"newEmail": "[email protected]",
@@ -111,13 +120,29 @@ func TestSendChangeEmailConfirmationTask(t *testing.T) {
func TestNotifyAboutNewPostTask(t *testing.T) {
RegisterT(t)
+ bus.Init(emailmock.Service{})
- worker, services := mock.NewWorker()
- services.SetCurrentUser(mock.JonSnow)
- post, _ := services.Posts.Add("Add support for TypeScript", "TypeScript is great, please add support for it")
+ var addNewNotification *cmd.AddNewNotification
+ bus.AddHandler(func(ctx context.Context, c *cmd.AddNewNotification) error {
+ addNewNotification = c
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {
+ q.Result = []*models.User{
+ mock.AryaStark,
+ }
+ return nil
+ })
- services.Posts.AddSubscriber(post, mock.AryaStark)
- emailer := services.Emailer.(*noop.Sender)
+ worker := mock.NewWorker()
+ post := &models.Post{
+ ID: 1,
+ Number: 1,
+ Title: "Add support for TypeScript",
+ Slug: "add-support-for-typescript",
+ Description: "TypeScript is great, please add support for it",
+ }
task := tasks.NotifyAboutNewPost(post)
err := worker.
@@ -127,10 +152,10 @@ func TestNotifyAboutNewPostTask(t *testing.T) {
Execute(task)
Expect(err).IsNil()
- Expect(emailer.Requests).HasLen(1)
- Expect(emailer.Requests[0].TemplateName).Equals("new_post")
- Expect(emailer.Requests[0].Context.Tenant()).Equals(mock.DemoTenant)
- Expect(emailer.Requests[0].Params).Equals(email.Params{
+ Expect(emailmock.MessageHistory).HasLen(1)
+ Expect(emailmock.MessageHistory[0].TemplateName).Equals("new_post")
+ Expect(emailmock.MessageHistory[0].Tenant).Equals(mock.DemoTenant)
+ Expect(emailmock.MessageHistory[0].Props).Equals(dto.Props{
"title": "Add support for TypeScript",
"postLink": template.HTML("<a href='http://domain.com/posts/1/add-support-for-typescript'>#1</a>"),
"tenantName": "Demonstration",
@@ -138,38 +163,53 @@ func TestNotifyAboutNewPostTask(t *testing.T) {
"content": template.HTML("<p>TypeScript is great, please add support for it</p>"),
"view": template.HTML("<a href='http://domain.com/posts/1/add-support-for-typescript'>View it on your browser</a>"),
"change": template.HTML("<a href='http://domain.com/settings'>change your notification settings</a>"),
+ "logo": "https://getfider.com/images/logo-100x100.png",
})
- Expect(emailer.Requests[0].From).Equals("Jon Snow")
- Expect(emailer.Requests[0].To).HasLen(1)
- Expect(emailer.Requests[0].To[0]).Equals(email.Recipient{
+ Expect(emailmock.MessageHistory[0].From).Equals("Jon Snow")
+ Expect(emailmock.MessageHistory[0].To).HasLen(1)
+ Expect(emailmock.MessageHistory[0].To[0]).Equals(dto.Recipient{
Name: "Arya Stark",
Address: "[email protected]",
- Params: email.Params{},
+ Props: dto.Props{},
})
- services.SetCurrentUser(mock.AryaStark)
- notifications, err := services.Notifications.GetActiveNotifications()
- Expect(err).IsNil()
- Expect(notifications).HasLen(1)
- Expect(notifications[0].ID).Equals(1)
- Expect(notifications[0].CreatedAt).TemporarilySimilar(time.Now(), 5*time.Second)
- Expect(notifications[0].Link).Equals("/posts/1/add-support-for-typescript")
- Expect(notifications[0].Read).IsFalse()
- Expect(notifications[0].Title).Equals("New post: **Add support for TypeScript**")
+ Expect(addNewNotification).IsNotNil()
+ Expect(addNewNotification.PostID).Equals(post.ID)
+ Expect(addNewNotification.Link).Equals("/posts/1/add-support-for-typescript")
+ Expect(addNewNotification.Title).Equals("New post: **Add support for TypeScript**")
+ Expect(addNewNotification.User).Equals(mock.AryaStark)
}
func TestNotifyAboutNewCommentTask(t *testing.T) {
RegisterT(t)
+ bus.Init(emailmock.Service{})
- worker, services := mock.NewWorker()
- services.SetCurrentUser(mock.JonSnow)
- post, _ := services.Posts.Add("Add support for TypeScript", "TypeScript is great, please add support for it")
+ var addNewNotification *cmd.AddNewNotification
+ bus.AddHandler(func(ctx context.Context, c *cmd.AddNewNotification) error {
+ addNewNotification = c
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {
+ q.Result = []*models.User{
+ mock.JonSnow,
+ }
+ return nil
+ })
+
+ worker := mock.NewWorker()
+ post := &models.Post{
+ ID: 1,
+ Number: 1,
+ Title: "Add support for TypeScript",
+ Slug: "add-support-for-typescript",
+ Description: "TypeScript is great, please add support for it",
+ }
comment := &models.NewComment{
Number: post.Number,
Content: "I agree",
}
- emailer := services.Emailer.(*noop.Sender)
task := tasks.NotifyAboutNewComment(post, comment)
err := worker.
@@ -179,10 +219,10 @@ func TestNotifyAboutNewCommentTask(t *testing.T) {
Execute(task)
Expect(err).IsNil()
- Expect(emailer.Requests).HasLen(1)
- Expect(emailer.Requests[0].TemplateName).Equals("new_comment")
- Expect(emailer.Requests[0].Context.Tenant()).Equals(mock.DemoTenant)
- Expect(emailer.Requests[0].Params).Equals(email.Params{
+ Expect(emailmock.MessageHistory).HasLen(1)
+ Expect(emailmock.MessageHistory[0].TemplateName).Equals("new_comment")
+ Expect(emailmock.MessageHistory[0].Tenant).Equals(mock.DemoTenant)
+ Expect(emailmock.MessageHistory[0].Props).Equals(dto.Props{
"title": "Add support for TypeScript",
"postLink": template.HTML("<a href='http://domain.com/posts/1/add-support-for-typescript'>#1</a>"),
"tenantName": "Demonstration",
@@ -191,36 +231,56 @@ func TestNotifyAboutNewCommentTask(t *testing.T) {
"view": template.HTML("<a href='http://domain.com/posts/1/add-support-for-typescript'>View it on your browser</a>"),
"change": template.HTML("<a href='http://domain.com/settings'>change your notification settings</a>"),
"unsubscribe": template.HTML("<a href='http://domain.com/posts/1/add-support-for-typescript'>unsubscribe from it</a>"),
+ "logo": "https://getfider.com/images/logo-100x100.png",
})
- Expect(emailer.Requests[0].From).Equals("Arya Stark")
- Expect(emailer.Requests[0].To).HasLen(1)
- Expect(emailer.Requests[0].To[0]).Equals(email.Recipient{
+ Expect(emailmock.MessageHistory[0].From).Equals("Arya Stark")
+ Expect(emailmock.MessageHistory[0].To).HasLen(1)
+ Expect(emailmock.MessageHistory[0].To[0]).Equals(dto.Recipient{
Name: "Jon Snow",
Address: "[email protected]",
- Params: email.Params{},
+ Props: dto.Props{},
})
- services.SetCurrentUser(mock.JonSnow)
- notifications, err := services.Notifications.GetActiveNotifications()
- Expect(err).IsNil()
- Expect(notifications).HasLen(1)
- Expect(notifications[0].ID).Equals(1)
- Expect(notifications[0].CreatedAt).TemporarilySimilar(time.Now(), 5*time.Second)
- Expect(notifications[0].Link).Equals("/posts/1/add-support-for-typescript")
- Expect(notifications[0].Read).IsFalse()
- Expect(notifications[0].Title).Equals("**Arya Stark** left a comment on **Add support for TypeScript**")
+ Expect(addNewNotification).IsNotNil()
+ Expect(addNewNotification.PostID).Equals(post.ID)
+ Expect(addNewNotification.Link).Equals("/posts/1/add-support-for-typescript")
+ Expect(addNewNotification.Title).Equals("**Arya Stark** left a comment on **Add support for TypeScript**")
+ Expect(addNewNotification.User).Equals(mock.JonSnow)
}
func TestNotifyAboutStatusChangeTask(t *testing.T) {
RegisterT(t)
+ bus.Init(emailmock.Service{})
- worker, services := mock.NewWorker()
- services.SetCurrentUser(mock.AryaStark)
- post, _ := services.Posts.Add("Add support for TypeScript", "TypeScript is great, please add support for it")
- services.Posts.SetResponse(post, "Planned for next release.", models.PostPlanned)
+ var addNewNotification *cmd.AddNewNotification
+ bus.AddHandler(func(ctx context.Context, c *cmd.AddNewNotification) error {
+ addNewNotification = c
+ return nil
+ })
- emailer := services.Emailer.(*noop.Sender)
- task := tasks.NotifyAboutStatusChange(post, models.PostOpen)
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {
+ q.Result = []*models.User{
+ mock.AryaStark,
+ }
+ return nil
+ })
+
+ worker := mock.NewWorker()
+ post := &models.Post{
+ ID: 1,
+ Number: 1,
+ Title: "Add support for TypeScript",
+ Slug: "add-support-for-typescript",
+ Description: "TypeScript is great, please add support for it",
+ Status: enum.PostPlanned,
+ Response: &models.PostResponse{
+ RespondedAt: time.Now(),
+ Text: "Planned for next release.",
+ User: mock.JonSnow,
+ },
+ }
+
+ task := tasks.NotifyAboutStatusChange(post, enum.PostOpen)
err := worker.
OnTenant(mock.DemoTenant).
@@ -229,10 +289,10 @@ func TestNotifyAboutStatusChangeTask(t *testing.T) {
Execute(task)
Expect(err).IsNil()
- Expect(emailer.Requests).HasLen(1)
- Expect(emailer.Requests[0].TemplateName).Equals("change_status")
- Expect(emailer.Requests[0].Context.Tenant()).Equals(mock.DemoTenant)
- Expect(emailer.Requests[0].Params).Equals(email.Params{
+ Expect(emailmock.MessageHistory).HasLen(1)
+ Expect(emailmock.MessageHistory[0].TemplateName).Equals("change_status")
+ Expect(emailmock.MessageHistory[0].Tenant).Equals(mock.DemoTenant)
+ Expect(emailmock.MessageHistory[0].Props).Equals(dto.Props{
"title": "Add support for TypeScript",
"postLink": template.HTML("<a href='http://domain.com/posts/1/add-support-for-typescript'>#1</a>"),
"tenantName": "Demonstration",
@@ -242,35 +302,55 @@ func TestNotifyAboutStatusChangeTask(t *testing.T) {
"view": template.HTML("<a href='http://domain.com/posts/1/add-support-for-typescript'>View it on your browser</a>"),
"change": template.HTML("<a href='http://domain.com/settings'>change your notification settings</a>"),
"unsubscribe": template.HTML("<a href='http://domain.com/posts/1/add-support-for-typescript'>unsubscribe from it</a>"),
+ "logo": "https://getfider.com/images/logo-100x100.png",
})
- Expect(emailer.Requests[0].From).Equals("Jon Snow")
- Expect(emailer.Requests[0].To).HasLen(1)
- Expect(emailer.Requests[0].To[0]).Equals(email.Recipient{
+ Expect(emailmock.MessageHistory[0].From).Equals("Jon Snow")
+ Expect(emailmock.MessageHistory[0].To).HasLen(1)
+ Expect(emailmock.MessageHistory[0].To[0]).Equals(dto.Recipient{
Name: "Arya Stark",
Address: "[email protected]",
- Params: email.Params{},
+ Props: dto.Props{},
})
- services.SetCurrentUser(mock.AryaStark)
- notifications, err := services.Notifications.GetActiveNotifications()
- Expect(err).IsNil()
- Expect(notifications).HasLen(1)
- Expect(notifications[0].ID).Equals(1)
- Expect(notifications[0].CreatedAt).TemporarilySimilar(time.Now(), 5*time.Second)
- Expect(notifications[0].Link).Equals("/posts/1/add-support-for-typescript")
- Expect(notifications[0].Read).IsFalse()
- Expect(notifications[0].Title).Equals("**Jon Snow** changed status of **Add support for TypeScript** to **planned**")
+ Expect(addNewNotification).IsNotNil()
+ Expect(addNewNotification.PostID).Equals(post.ID)
+ Expect(addNewNotification.Link).Equals("/posts/1/add-support-for-typescript")
+ Expect(addNewNotification.Title).Equals("**Jon Snow** changed status of **Add support for TypeScript** to **planned**")
+ Expect(addNewNotification.User).Equals(mock.AryaStark)
}
func TestNotifyAboutDeletePostTask(t *testing.T) {
RegisterT(t)
+ bus.Init(emailmock.Service{})
+
+ var addNewNotification *cmd.AddNewNotification
+ bus.AddHandler(func(ctx context.Context, c *cmd.AddNewNotification) error {
+ addNewNotification = c
+ return nil
+ })
- worker, services := mock.NewWorker()
- services.SetCurrentUser(mock.AryaStark)
- post, _ := services.Posts.Add("Add support for TypeScript", "TypeScript is great, please add support for it")
- services.Posts.SetResponse(post, "Invalid post!", models.PostDeleted)
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {
+ q.Result = []*models.User{
+ mock.AryaStark,
+ }
+ return nil
+ })
+
+ worker := mock.NewWorker()
+ post := &models.Post{
+ ID: 1,
+ Number: 1,
+ Title: "Add support for TypeScript",
+ Slug: "add-support-for-typescript",
+ Description: "TypeScript is great, please add support for it",
+ Status: enum.PostDeleted,
+ Response: &models.PostResponse{
+ RespondedAt: time.Now(),
+ Text: "Invalid post!",
+ User: mock.JonSnow,
+ },
+ }
- emailer := services.Emailer.(*noop.Sender)
task := tasks.NotifyAboutDeletedPost(post)
err := worker.
@@ -280,45 +360,68 @@ func TestNotifyAboutDeletePostTask(t *testing.T) {
Execute(task)
Expect(err).IsNil()
- Expect(emailer.Requests).HasLen(1)
- Expect(emailer.Requests[0].TemplateName).Equals("delete_post")
- Expect(emailer.Requests[0].Context.Tenant()).Equals(mock.DemoTenant)
- Expect(emailer.Requests[0].Params).Equals(email.Params{
+ Expect(emailmock.MessageHistory).HasLen(1)
+ Expect(emailmock.MessageHistory[0].TemplateName).Equals("delete_post")
+ Expect(emailmock.MessageHistory[0].Tenant).Equals(mock.DemoTenant)
+ Expect(emailmock.MessageHistory[0].Props).Equals(dto.Props{
"title": "Add support for TypeScript",
"tenantName": "Demonstration",
"content": template.HTML("<p>Invalid post!</p>"),
"change": template.HTML("<a href='http://domain.com/settings'>change your notification settings</a>"),
+ "logo": "https://getfider.com/images/logo-100x100.png",
})
- Expect(emailer.Requests[0].From).Equals("Jon Snow")
- Expect(emailer.Requests[0].To).HasLen(1)
- Expect(emailer.Requests[0].To[0]).Equals(email.Recipient{
+ Expect(emailmock.MessageHistory[0].From).Equals("Jon Snow")
+ Expect(emailmock.MessageHistory[0].To).HasLen(1)
+ Expect(emailmock.MessageHistory[0].To[0]).Equals(dto.Recipient{
Name: "Arya Stark",
Address: "[email protected]",
- Params: email.Params{},
+ Props: dto.Props{},
})
- services.SetCurrentUser(mock.AryaStark)
- notifications, err := services.Notifications.GetActiveNotifications()
- Expect(err).IsNil()
- Expect(notifications).HasLen(1)
- Expect(notifications[0].ID).Equals(1)
- Expect(notifications[0].CreatedAt).TemporarilySimilar(time.Now(), 5*time.Second)
- Expect(notifications[0].Link).Equals("")
- Expect(notifications[0].Read).IsFalse()
- Expect(notifications[0].Title).Equals("**Jon Snow** deleted **Add support for TypeScript**")
+ Expect(addNewNotification).IsNotNil()
+ Expect(addNewNotification.PostID).Equals(post.ID)
+ Expect(addNewNotification.Link).Equals("")
+ Expect(addNewNotification.Title).Equals("**Jon Snow** deleted **Add support for TypeScript**")
+ Expect(addNewNotification.User).Equals(mock.AryaStark)
}
func TestNotifyAboutStatusChangeTask_Duplicate(t *testing.T) {
RegisterT(t)
+ bus.Init(emailmock.Service{})
- worker, services := mock.NewWorker()
- services.SetCurrentUser(mock.AryaStark)
- post1, _ := services.Posts.Add("Add support for TypeScript", "TypeScript is great, please add support for it")
- post2, _ := services.Posts.Add("I need TypeScript", "")
- services.Posts.MarkAsDuplicate(post2, post1)
+ var addNewNotification *cmd.AddNewNotification
+ bus.AddHandler(func(ctx context.Context, c *cmd.AddNewNotification) error {
+ addNewNotification = c
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {
+ q.Result = []*models.User{
+ mock.AryaStark,
+ }
+ return nil
+ })
+
+ worker := mock.NewWorker()
+ post := &models.Post{
+ ID: 2,
+ Number: 2,
+ Title: "I need TypeScript",
+ Slug: "i-need-typescript",
+ Status: enum.PostDuplicate,
+ Response: &models.PostResponse{
+ RespondedAt: time.Now(),
+ User: mock.JonSnow,
+ Original: &models.OriginalPost{
+ Number: 1,
+ Title: "Add support for TypeScript",
+ Slug: "add-support-for-typescript",
+ Status: enum.PostOpen,
+ },
+ },
+ }
- emailer := services.Emailer.(*noop.Sender)
- task := tasks.NotifyAboutStatusChange(post2, models.PostOpen)
+ task := tasks.NotifyAboutStatusChange(post, enum.PostOpen)
err := worker.
OnTenant(mock.DemoTenant).
@@ -327,10 +430,10 @@ func TestNotifyAboutStatusChangeTask_Duplicate(t *testing.T) {
Execute(task)
Expect(err).IsNil()
- Expect(emailer.Requests).HasLen(1)
- Expect(emailer.Requests[0].TemplateName).Equals("change_status")
- Expect(emailer.Requests[0].Context.Tenant()).Equals(mock.DemoTenant)
- Expect(emailer.Requests[0].Params).Equals(email.Params{
+ Expect(emailmock.MessageHistory).HasLen(1)
+ Expect(emailmock.MessageHistory[0].TemplateName).Equals("change_status")
+ Expect(emailmock.MessageHistory[0].Tenant).Equals(mock.DemoTenant)
+ Expect(emailmock.MessageHistory[0].Props).Equals(dto.Props{
"title": "I need TypeScript",
"postLink": template.HTML("<a href='http://domain.com/posts/2/i-need-typescript'>#2</a>"),
"tenantName": "Demonstration",
@@ -340,31 +443,34 @@ func TestNotifyAboutStatusChangeTask_Duplicate(t *testing.T) {
"view": template.HTML("<a href='http://domain.com/posts/2/i-need-typescript'>View it on your browser</a>"),
"change": template.HTML("<a href='http://domain.com/settings'>change your notification settings</a>"),
"unsubscribe": template.HTML("<a href='http://domain.com/posts/2/i-need-typescript'>unsubscribe from it</a>"),
+ "logo": "https://getfider.com/images/logo-100x100.png",
})
- Expect(emailer.Requests[0].From).Equals("Jon Snow")
- Expect(emailer.Requests[0].To).HasLen(1)
- Expect(emailer.Requests[0].To[0]).Equals(email.Recipient{
+ Expect(emailmock.MessageHistory[0].From).Equals("Jon Snow")
+ Expect(emailmock.MessageHistory[0].To).HasLen(1)
+ Expect(emailmock.MessageHistory[0].To[0]).Equals(dto.Recipient{
Name: "Arya Stark",
Address: "[email protected]",
- Params: email.Params{},
+ Props: dto.Props{},
})
- services.SetCurrentUser(mock.AryaStark)
- notifications, err := services.Notifications.GetActiveNotifications()
- Expect(err).IsNil()
- Expect(notifications).HasLen(1)
- Expect(notifications[0].ID).Equals(1)
- Expect(notifications[0].CreatedAt).TemporarilySimilar(time.Now(), 5*time.Second)
- Expect(notifications[0].Link).Equals("/posts/2/i-need-typescript")
- Expect(notifications[0].Read).IsFalse()
- Expect(notifications[0].Title).Equals("**Jon Snow** changed status of **I need TypeScript** to **duplicate**")
+ Expect(addNewNotification).IsNotNil()
+ Expect(addNewNotification.PostID).Equals(post.ID)
+ Expect(addNewNotification.Link).Equals("/posts/2/i-need-typescript")
+ Expect(addNewNotification.Title).Equals("**Jon Snow** changed status of **I need TypeScript** to **duplicate**")
+ Expect(addNewNotification.User).Equals(mock.AryaStark)
}
func TestSendInvites(t *testing.T) {
RegisterT(t)
+ bus.Init(emailmock.Service{})
- worker, services := mock.NewWorker()
- emailer := services.Emailer.(*noop.Sender)
+ savedKeys := make([]*cmd.SaveVerificationKey, 0)
+ bus.AddHandler(func(ctx context.Context, c *cmd.SaveVerificationKey) error {
+ savedKeys = append(savedKeys, c)
+ return nil
+ })
+
+ worker := mock.NewWorker()
task := tasks.SendInvites("My Subject", "Click here: %invite%", []*models.UserInvitation{
&models.UserInvitation{Email: "[email protected]", VerificationKey: "1234"},
&models.UserInvitation{Email: "[email protected]", VerificationKey: "5678"},
@@ -377,24 +483,31 @@ func TestSendInvites(t *testing.T) {
Execute(task)
Expect(err).IsNil()
- Expect(emailer.Requests).HasLen(1)
- Expect(emailer.Requests[0].TemplateName).Equals("invite_email")
- Expect(emailer.Requests[0].Context.Tenant()).Equals(mock.DemoTenant)
- Expect(emailer.Requests[0].Params).Equals(email.Params{
+ Expect(emailmock.MessageHistory).HasLen(1)
+ Expect(emailmock.MessageHistory[0].TemplateName).Equals("invite_email")
+ Expect(emailmock.MessageHistory[0].Tenant).Equals(mock.DemoTenant)
+ Expect(emailmock.MessageHistory[0].Props).Equals(dto.Props{
"subject": "My Subject",
+ "logo": "https://getfider.com/images/logo-100x100.png",
})
- Expect(emailer.Requests[0].From).Equals("Jon Snow")
- Expect(emailer.Requests[0].To).HasLen(2)
- Expect(emailer.Requests[0].To[0]).Equals(email.Recipient{
+ Expect(emailmock.MessageHistory[0].From).Equals("Jon Snow")
+ Expect(emailmock.MessageHistory[0].To).HasLen(2)
+ Expect(emailmock.MessageHistory[0].To[0]).Equals(dto.Recipient{
Address: "[email protected]",
- Params: email.Params{
+ Props: dto.Props{
"message": template.HTML(`<p>Click here: <a href="http://domain.com/invite/verify?k=1234">http://domain.com/invite/verify?k=1234</a></p>`),
},
})
- Expect(emailer.Requests[0].To[1]).Equals(email.Recipient{
+ Expect(emailmock.MessageHistory[0].To[1]).Equals(dto.Recipient{
Address: "[email protected]",
- Params: email.Params{
+ Props: dto.Props{
"message": template.HTML(`<p>Click here: <a href="http://domain.com/invite/verify?k=5678">http://domain.com/invite/verify?k=5678</a></p>`),
},
})
+
+ Expect(savedKeys).HasLen(2)
+ Expect(savedKeys[0].Key).Equals("1234")
+ Expect(savedKeys[0].Request.GetEmail()).Equals("[email protected]")
+ Expect(savedKeys[1].Key).Equals("5678")
+ Expect(savedKeys[1].Request.GetEmail()).Equals("[email protected]")
}
diff --git a/magefile.go b/magefile.go
index 54a4669c7..54961ddef 100644
--- a/magefile.go
+++ b/magefile.go
@@ -54,6 +54,10 @@ func Run() error {
return sh.Run("godotenv", "-f", ".env", "./"+exeName)
}
+func Migrate() error {
+ return sh.Run("godotenv", "-f", ".env", "./"+exeName, "migrate")
+}
+
func Lint() error {
return sh.Run("npx", "tslint", "-c", "tslint.json", "'public/**/*.{ts,tsx}'", "'tests/**/*.{ts,tsx}'")
}