Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

refactor: remove models base pkg (#953)

Guilherme Oenningb3cedf3cac4c
diff --git a/Makefile b/Makefile
index e778d1ae1..6397d4153 100644
--- a/Makefile
+++ b/Makefile
@@ -2,8 +2,7 @@
##
## For more information, refer to https://suva.sh/posts/well-documented-makefiles/
-LDFLAGS += -X main.buildtime=$(shell date -u "+%Y-%m-%dT%H:%M:%S")
-LDFLAGS += -X main.buildnumber=${BUILDNUMBER}
+LDFLAGS += -X github.com/getfider/fider/app/pkg/env.buildnumber=${BUILDNUMBER}
##@ Running
diff --git a/app/actions/actions.go b/app/actions/actions.go
index 24f8798af..0fb493071 100644
--- a/app/actions/actions.go
+++ b/app/actions/actions.go
@@ -3,13 +3,12 @@ package actions
import (
"context"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/pkg/validate"
)
// Actionable is any action that the user can perform using the web app
type Actionable interface {
- Initialize() interface{}
- IsAuthorized(ctx context.Context, user *models.User) bool
- Validate(ctx context.Context, user *models.User) *validate.Result
+ IsAuthorized(ctx context.Context, user *entity.User) bool
+ Validate(ctx context.Context, user *entity.User) *validate.Result
}
diff --git a/app/actions/invite.go b/app/actions/invite.go
index 8a53f4358..fbff682a4 100644
--- a/app/actions/invite.go
+++ b/app/actions/invite.go
@@ -5,60 +5,58 @@ import (
"fmt"
"strings"
+ "github.com/getfider/fider/app/models/entity"
+ "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/validate"
)
// InviteUsers is used to invite new users into Fider
type InviteUsers struct {
+ Subject string `json:"subject"`
+ Message string `json:"message"`
+ Recipients []string `json:"recipients" format:"lower"`
IsSampleInvite bool
- Model *models.InviteUsers
- Invitations []*models.UserInvitation
-}
-// Initialize the model
-func (input *InviteUsers) Initialize() interface{} {
- input.Model = new(models.InviteUsers)
- return input.Model
+ Invitations []*UserInvitation
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *InviteUsers) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *InviteUsers) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil && user.IsCollaborator()
}
// Validate if current model is valid
-func (input *InviteUsers) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *InviteUsers) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Subject == "" {
+ if action.Subject == "" {
result.AddFieldFailure("subject", "Subject is required.")
- } else if len(input.Model.Subject) > 70 {
+ } else if len(action.Subject) > 70 {
result.AddFieldFailure("subject", "Subject must have less than 70 characters.")
}
- if input.Model.Message == "" {
+ if action.Message == "" {
result.AddFieldFailure("message", "Message is required.")
- } else if !strings.Contains(input.Model.Message, app.InvitePlaceholder) {
+ } else if !strings.Contains(action.Message, app.InvitePlaceholder) {
msg := fmt.Sprintf("Your message is missing the invitation link placeholder. Please add '%s' to your message.", app.InvitePlaceholder)
result.AddFieldFailure("message", msg)
}
//When it's a sample invite, we skip recipients validation
- if !input.IsSampleInvite {
+ if !action.IsSampleInvite {
- if len(input.Model.Recipients) == 0 {
+ if len(action.Recipients) == 0 {
result.AddFieldFailure("recipients", "At least one recipient is required.")
- } else if len(input.Model.Recipients) > 30 {
+ } else if len(action.Recipients) > 30 {
result.AddFieldFailure("recipients", "Too many recipients. We limit at 30 recipients per invite.")
}
- for _, email := range input.Model.Recipients {
+ for _, email := range action.Recipients {
if email != "" {
messages := validate.Email(email)
result.AddFieldFailure("recipients", messages...)
@@ -66,20 +64,20 @@ func (input *InviteUsers) Validate(ctx context.Context, user *models.User) *vali
}
if result.Ok {
- input.Invitations = make([]*models.UserInvitation, 0)
- for _, email := range input.Model.Recipients {
+ action.Invitations = make([]*UserInvitation, 0)
+ for _, email := range action.Recipients {
if email != "" {
err := bus.Dispatch(ctx, &query.GetUserByEmail{Email: email})
if errors.Cause(err) == app.ErrNotFound {
- input.Invitations = append(input.Invitations, &models.UserInvitation{
+ action.Invitations = append(action.Invitations, &UserInvitation{
Email: email,
- VerificationKey: models.GenerateSecretKey(),
+ VerificationKey: entity.GenerateEmailVerificationKey(),
})
}
}
}
- if len(input.Invitations) == 0 {
+ if len(action.Invitations) == 0 {
result.AddFieldFailure("recipients", "All these addresses have already been registered on this site.")
}
}
@@ -88,3 +86,29 @@ func (input *InviteUsers) Validate(ctx context.Context, user *models.User) *vali
return result
}
+
+//UserInvitation is the model used to register an invite sent to an user
+type UserInvitation struct {
+ Email string
+ VerificationKey string
+}
+
+//GetEmail returns the invited user's email
+func (e *UserInvitation) GetEmail() string {
+ return e.Email
+}
+
+//GetName returns empty for this kind of process
+func (e *UserInvitation) GetName() string {
+ return ""
+}
+
+//GetUser returns the current user performing this action
+func (e *UserInvitation) GetUser() *entity.User {
+ return nil
+}
+
+//GetKind returns EmailVerificationKindUserInvitation
+func (e *UserInvitation) GetKind() enum.EmailVerificationKind {
+ return enum.EmailVerificationKindUserInvitation
+}
diff --git a/app/actions/invite_test.go b/app/actions/invite_test.go
index 38df7b806..3788de5ee 100644
--- a/app/actions/invite_test.go
+++ b/app/actions/invite_test.go
@@ -7,7 +7,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/bus"
@@ -16,7 +16,7 @@ import (
func TestInviteUsers_Empty(t *testing.T) {
RegisterT(t)
- action := &actions.InviteUsers{Model: &models.InviteUsers{}}
+ action := &actions.InviteUsers{}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "subject", "message", "recipients")
Expect(action.Invitations).IsNil()
@@ -25,11 +25,11 @@ func TestInviteUsers_Empty(t *testing.T) {
func TestInviteUsers_Oversized(t *testing.T) {
RegisterT(t)
- action := &actions.InviteUsers{Model: &models.InviteUsers{
+ action := &actions.InviteUsers{
Subject: "Join us and share your ideas. Because we have a cool website and this subject needs to be very long",
Message: "Use this link to join %invite%",
Recipients: []string{"[email protected]"},
- }}
+ }
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "subject")
Expect(action.Invitations).IsNil()
@@ -38,11 +38,11 @@ func TestInviteUsers_Oversized(t *testing.T) {
func TestInviteUsers_MissingInvite(t *testing.T) {
RegisterT(t)
- action := &actions.InviteUsers{Model: &models.InviteUsers{
+ action := &actions.InviteUsers{
Subject: "Share your feedback.",
Message: "Please!",
Recipients: []string{"[email protected]"},
- }}
+ }
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "message")
Expect(action.Invitations).IsNil()
@@ -56,11 +56,11 @@ func TestInviteUsers_TooManyRecipients(t *testing.T) {
recipients[i] = fmt.Sprintf("jon.snow%[email protected]", i)
}
- action := &actions.InviteUsers{Model: &models.InviteUsers{
+ action := &actions.InviteUsers{
Subject: "Share your feedback.",
Message: "Use this link to join %invite%",
Recipients: recipients,
- }}
+ }
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "recipients")
Expect(action.Invitations).IsNil()
@@ -69,14 +69,14 @@ func TestInviteUsers_TooManyRecipients(t *testing.T) {
func TestInviteUsers_InvalidRecipient(t *testing.T) {
RegisterT(t)
- action := &actions.InviteUsers{Model: &models.InviteUsers{
+ action := &actions.InviteUsers{
Subject: "Share your feedback.",
Message: "Use this link to join our community: %invite%",
Recipients: []string{
"jon.snow",
"@got.com",
},
- }}
+ }
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "recipients")
Expect(action.Invitations).IsNil()
@@ -89,7 +89,7 @@ func TestInviteUsers_Valid(t *testing.T) {
return app.ErrNotFound
})
- action := &actions.InviteUsers{Model: &models.InviteUsers{
+ action := &actions.InviteUsers{
Subject: "Share your feedback.",
Message: "Use this link to join our community: %invite%",
Recipients: []string{
@@ -97,7 +97,7 @@ func TestInviteUsers_Valid(t *testing.T) {
},
- }}
+ }
ExpectSuccess(action.Validate(context.Background(), nil))
@@ -115,13 +115,13 @@ func TestInviteUsers_IgnoreAlreadyRegistered(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
if q.Email == "[email protected]" {
- q.Result = &models.User{Email: q.Email}
+ q.Result = &entity.User{Email: q.Email}
return nil
}
return app.ErrNotFound
})
- action := &actions.InviteUsers{Model: &models.InviteUsers{
+ action := &actions.InviteUsers{
Subject: "Share your feedback.",
Message: "Use this link to join our community: %invite%",
Recipients: []string{
@@ -129,7 +129,7 @@ func TestInviteUsers_IgnoreAlreadyRegistered(t *testing.T) {
},
- }}
+ }
ExpectSuccess(action.Validate(context.Background(), nil))
@@ -146,17 +146,17 @@ func TestInviteUsers_ShouldFail_WhenAllRecipientsIgnored(t *testing.T) {
RegisterT(t)
bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
- q.Result = &models.User{Email: q.Email}
+ q.Result = &entity.User{Email: q.Email}
return nil
})
- action := &actions.InviteUsers{Model: &models.InviteUsers{
+ action := &actions.InviteUsers{
Subject: "Share your feedback.",
Message: "Use this link to join our community: %invite%",
Recipients: []string{
},
- }}
+ }
ExpectFailed(action.Validate(context.Background(), nil), "recipients")
}
@@ -166,10 +166,8 @@ func TestInviteUsers_SampleInvite_IgnoreRecipients(t *testing.T) {
action := &actions.InviteUsers{
IsSampleInvite: true,
- Model: &models.InviteUsers{
- Subject: "Share your feedback.",
- Message: "Use this link to join our community: %invite%",
- },
+ Subject: "Share your feedback.",
+ Message: "Use this link to join our community: %invite%",
}
ExpectSuccess(action.Validate(context.Background(), nil))
diff --git a/app/actions/oauth.go b/app/actions/oauth.go
index c839f828a..debeedd16 100644
--- a/app/actions/oauth.go
+++ b/app/actions/oauth.go
@@ -4,53 +4,66 @@ import (
"context"
"strings"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
"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"
)
// CreateEditOAuthConfig is used to create/edit OAuth config
type CreateEditOAuthConfig struct {
- Model *models.CreateEditOAuthConfig
+ ID int
+ Logo *dto.ImageUpload `json:"logo"`
+ Provider string `json:"provider"`
+ Status int `json:"status"`
+ DisplayName string `json:"displayName"`
+ ClientID string `json:"clientID"`
+ ClientSecret string `json:"clientSecret"`
+ AuthorizeURL string `json:"authorizeURL" format:"lower"`
+ TokenURL string `json:"tokenURL" format:"lower"`
+ Scope string `json:"scope"`
+ ProfileURL string `json:"profileURL" format:"lower"`
+ JSONUserIDPath string `json:"jsonUserIDPath"`
+ JSONUserNamePath string `json:"jsonUserNamePath"`
+ JSONUserEmailPath string `json:"jsonUserEmailPath"`
}
-// Initialize the model
-func (input *CreateEditOAuthConfig) Initialize() interface{} {
- input.Model = new(models.CreateEditOAuthConfig)
- input.Model.Logo = &models.ImageUpload{}
- return input.Model
+func NewCreateEditOAuthConfig() *CreateEditOAuthConfig {
+ return &CreateEditOAuthConfig{
+ Logo: &dto.ImageUpload{},
+ }
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateEditOAuthConfig) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *CreateEditOAuthConfig) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil && user.IsAdministrator()
}
// Validate if current model is valid
-func (input *CreateEditOAuthConfig) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *CreateEditOAuthConfig) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Provider != "" {
- getConfig := &query.GetCustomOAuthConfigByProvider{Provider: input.Model.Provider}
+ if action.Provider != "" {
+ getConfig := &query.GetCustomOAuthConfigByProvider{Provider: action.Provider}
err := bus.Dispatch(ctx, getConfig)
if err != nil {
return validate.Error(err)
}
- input.Model.ID = getConfig.Result.ID
- input.Model.Logo.BlobKey = getConfig.Result.LogoBlobKey
- if input.Model.ClientSecret == "" {
- input.Model.ClientSecret = getConfig.Result.ClientSecret
+ action.ID = getConfig.Result.ID
+ action.Logo.BlobKey = getConfig.Result.LogoBlobKey
+ if action.ClientSecret == "" {
+ action.ClientSecret = getConfig.Result.ClientSecret
}
} else {
- input.Model.Provider = "_" + strings.ToLower(rand.String(10))
+ action.Provider = "_" + strings.ToLower(rand.String(10))
}
- messages, err := validate.ImageUpload(input.Model.Logo, validate.ImageUploadOpts{
+ messages, err := validate.ImageUpload(action.Logo, validate.ImageUploadOpts{
IsRequired: false,
MinHeight: 24,
MinWidth: 24,
@@ -62,64 +75,64 @@ func (input *CreateEditOAuthConfig) Validate(ctx context.Context, user *models.U
}
result.AddFieldFailure("logo", messages...)
- if input.Model.Status != enum.OAuthConfigEnabled &&
- input.Model.Status != enum.OAuthConfigDisabled {
+ if action.Status != enum.OAuthConfigEnabled &&
+ action.Status != enum.OAuthConfigDisabled {
result.AddFieldFailure("status", "Invalid status.")
}
- if input.Model.DisplayName == "" {
+ if action.DisplayName == "" {
result.AddFieldFailure("displayName", "Display Name is required.")
- } else if len(input.Model.DisplayName) > 50 {
+ } else if len(action.DisplayName) > 50 {
result.AddFieldFailure("displayName", "Display Name must have less than 50 characters.")
}
- if input.Model.ClientID == "" {
+ if action.ClientID == "" {
result.AddFieldFailure("clientID", "Client ID is required.")
- } else if len(input.Model.ClientID) > 100 {
+ } else if len(action.ClientID) > 100 {
result.AddFieldFailure("clientID", "Client ID must have less than 100 characters.")
}
- if input.Model.ClientSecret == "" {
+ if action.ClientSecret == "" {
result.AddFieldFailure("clientSecret", "Client Secret is required.")
- } else if len(input.Model.ClientSecret) > 500 {
+ } else if len(action.ClientSecret) > 500 {
result.AddFieldFailure("clientSecret", "Client Secret must have less than 500 characters.")
}
- if input.Model.Scope == "" {
+ if action.Scope == "" {
result.AddFieldFailure("scope", "Scope is required.")
- } else if len(input.Model.Scope) > 100 {
+ } else if len(action.Scope) > 100 {
result.AddFieldFailure("scope", "Scope must have less than 100 characters.")
}
- if input.Model.AuthorizeURL == "" {
+ if action.AuthorizeURL == "" {
result.AddFieldFailure("authorizeURL", "Authorize URL is required.")
- } else if messages := validate.URL(input.Model.AuthorizeURL); len(messages) > 0 {
+ } else if messages := validate.URL(action.AuthorizeURL); len(messages) > 0 {
result.AddFieldFailure("authorizeURL", messages...)
}
- if input.Model.TokenURL == "" {
+ if action.TokenURL == "" {
result.AddFieldFailure("tokenURL", "Token URL is required.")
- } else if messages := validate.URL(input.Model.TokenURL); len(messages) > 0 {
+ } else if messages := validate.URL(action.TokenURL); len(messages) > 0 {
result.AddFieldFailure("tokenURL", messages...)
}
- if input.Model.ProfileURL != "" {
- if messages := validate.URL(input.Model.ProfileURL); len(messages) > 0 {
+ if action.ProfileURL != "" {
+ if messages := validate.URL(action.ProfileURL); len(messages) > 0 {
result.AddFieldFailure("profileURL", messages...)
}
}
- if input.Model.JSONUserIDPath == "" {
+ if action.JSONUserIDPath == "" {
result.AddFieldFailure("jsonUserIDPath", "JSON User ID Path is required.")
- } else if len(input.Model.JSONUserIDPath) > 100 {
+ } else if len(action.JSONUserIDPath) > 100 {
result.AddFieldFailure("jsonUserIDPath", "JSON User ID Path must have less than 100 characters.")
}
- if len(input.Model.JSONUserNamePath) > 100 {
+ if len(action.JSONUserNamePath) > 100 {
result.AddFieldFailure("jsonUserNamePath", "JSON User Name Path must have less than 100 characters.")
}
- if len(input.Model.JSONUserEmailPath) > 100 {
+ if len(action.JSONUserEmailPath) > 100 {
result.AddFieldFailure("jsonUserEmailPath", "JSON User Email Path must have less than 100 characters.")
}
diff --git a/app/actions/oauth_test.go b/app/actions/oauth_test.go
index 45e2439c0..c90b728f7 100644
--- a/app/actions/oauth_test.go
+++ b/app/actions/oauth_test.go
@@ -6,7 +6,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
@@ -19,15 +19,15 @@ func TestCreateEditOAuthConfig_InvalidInput(t *testing.T) {
testCases := []struct {
expected []string
- input *models.CreateEditOAuthConfig
+ action *actions.CreateEditOAuthConfig
}{
{
expected: []string{"displayName", "status", "tokenURL", "clientID", "clientSecret", "scope", "authorizeURL", "tokenURL", "jsonUserIDPath"},
- input: &models.CreateEditOAuthConfig{},
+ action: &actions.CreateEditOAuthConfig{},
},
{
expected: []string{"displayName", "status", "tokenURL", "clientID", "clientSecret", "scope", "authorizeURL", "tokenURL", "profileURL", "jsonUserIDPath", "jsonUserNamePath", "jsonUserEmailPath"},
- input: &models.CreateEditOAuthConfig{
+ action: &actions.CreateEditOAuthConfig{
DisplayName: rand.String(51),
ClientID: rand.String(101),
Status: 0,
@@ -44,26 +44,22 @@ func TestCreateEditOAuthConfig_InvalidInput(t *testing.T) {
}
for _, testCase := range testCases {
- action := &actions.CreateEditOAuthConfig{
- Model: testCase.input,
- }
- result := action.Validate(context.Background(), nil)
+ result := testCase.action.Validate(context.Background(), nil)
ExpectFailed(result, testCase.expected...)
}
}
-func TestCreateEditOAuthConfig_Initialize(t *testing.T) {
+func TestCreateEditOAuthConfig_DefaultValues(t *testing.T) {
RegisterT(t)
- action := &actions.CreateEditOAuthConfig{}
- action.Initialize()
- Expect(action.Model.Logo.BlobKey).Equals("")
+ action := actions.NewCreateEditOAuthConfig()
+ Expect(action.Logo.BlobKey).Equals("")
}
func TestCreateEditOAuthConfig_AddNew_ValidInput(t *testing.T) {
RegisterT(t)
- input := &models.CreateEditOAuthConfig{
+ action := &actions.CreateEditOAuthConfig{
DisplayName: "My Provider",
Status: enum.OAuthConfigEnabled,
ClientID: "823187ahjjfdha8fds7yfdashfjkdsa",
@@ -76,14 +72,11 @@ func TestCreateEditOAuthConfig_AddNew_ValidInput(t *testing.T) {
JSONUserNamePath: "user.name",
JSONUserEmailPath: "user.email",
}
- action := &actions.CreateEditOAuthConfig{
- Model: input,
- }
result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
- Expect(input.ID).Equals(0)
- Expect(input.Provider).HasLen(11)
- Expect(string(input.Provider[0])).Equals("_")
+ Expect(action.ID).Equals(0)
+ Expect(action.Provider).HasLen(11)
+ Expect(string(action.Provider[0])).Equals("_")
}
func TestCreateEditOAuthConfig_EditExisting_NewSecret(t *testing.T) {
@@ -91,7 +84,7 @@ func TestCreateEditOAuthConfig_EditExisting_NewSecret(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
if q.Provider == "_NAME" {
- q.Result = &models.OAuthConfig{
+ q.Result = &entity.OAuthConfig{
ID: 4,
Provider: q.Provider,
LogoBlobKey: "hello-world.png",
@@ -101,26 +94,25 @@ func TestCreateEditOAuthConfig_EditExisting_NewSecret(t *testing.T) {
return app.ErrNotFound
})
- action := &actions.CreateEditOAuthConfig{}
- action.Initialize()
- action.Model.Provider = "_NAME"
- action.Model.DisplayName = "My Provider"
- action.Model.Status = enum.OAuthConfigDisabled
- action.Model.ClientID = "823187ahjjfdha8fds7yfdashfjkdsa"
- action.Model.ClientSecret = "jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij"
- action.Model.AuthorizeURL = "http://provider/oauth/authorize"
- action.Model.TokenURL = "http://provider/oauth/token"
- action.Model.Scope = "profile email"
- action.Model.ProfileURL = "http://provider/profile/me"
- action.Model.JSONUserIDPath = "user.id"
- action.Model.JSONUserNamePath = "user.name"
- action.Model.JSONUserEmailPath = "user.email"
+ action := actions.NewCreateEditOAuthConfig()
+ action.Provider = "_NAME"
+ action.DisplayName = "My Provider"
+ action.Status = enum.OAuthConfigDisabled
+ action.ClientID = "823187ahjjfdha8fds7yfdashfjkdsa"
+ action.ClientSecret = "jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij"
+ action.AuthorizeURL = "http://provider/oauth/authorize"
+ action.TokenURL = "http://provider/oauth/token"
+ action.Scope = "profile email"
+ action.ProfileURL = "http://provider/profile/me"
+ action.JSONUserIDPath = "user.id"
+ action.JSONUserNamePath = "user.name"
+ action.JSONUserEmailPath = "user.email"
result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
- Expect(action.Model.ID).Equals(4)
- Expect(action.Model.Logo.BlobKey).Equals("hello-world.png")
- Expect(action.Model.ClientSecret).Equals("jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij")
+ Expect(action.ID).Equals(4)
+ Expect(action.Logo.BlobKey).Equals("hello-world.png")
+ Expect(action.ClientSecret).Equals("jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij")
}
func TestCreateEditOAuthConfig_EditExisting_OmitSecret(t *testing.T) {
@@ -128,7 +120,7 @@ func TestCreateEditOAuthConfig_EditExisting_OmitSecret(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
if q.Provider == "_NAME2" {
- q.Result = &models.OAuthConfig{
+ q.Result = &entity.OAuthConfig{
ID: 5,
Provider: q.Provider,
DisplayName: "My Provider",
@@ -139,24 +131,23 @@ func TestCreateEditOAuthConfig_EditExisting_OmitSecret(t *testing.T) {
return app.ErrNotFound
})
- action := &actions.CreateEditOAuthConfig{}
- action.Initialize()
- action.Model.Provider = "_NAME2"
- action.Model.DisplayName = "My Provider"
- action.Model.Status = enum.OAuthConfigDisabled
- action.Model.ClientID = "823187ahjjfdha8fds7yfdashfjkdsa"
- action.Model.AuthorizeURL = "http://provider/oauth/authorize"
- action.Model.TokenURL = "http://provider/oauth/token"
- action.Model.Scope = "profile email"
- action.Model.ProfileURL = "http://provider/profile/me"
- action.Model.JSONUserIDPath = "user.id"
- action.Model.JSONUserNamePath = "user.name"
- action.Model.JSONUserEmailPath = "user.email"
+ action := actions.NewCreateEditOAuthConfig()
+ action.Provider = "_NAME2"
+ action.DisplayName = "My Provider"
+ action.Status = enum.OAuthConfigDisabled
+ action.ClientID = "823187ahjjfdha8fds7yfdashfjkdsa"
+ action.AuthorizeURL = "http://provider/oauth/authorize"
+ action.TokenURL = "http://provider/oauth/token"
+ action.Scope = "profile email"
+ action.ProfileURL = "http://provider/profile/me"
+ action.JSONUserIDPath = "user.id"
+ action.JSONUserNamePath = "user.name"
+ action.JSONUserEmailPath = "user.email"
result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
- Expect(action.Model.ID).Equals(5)
- Expect(action.Model.ClientSecret).Equals("MY_OLD_SECRET")
+ Expect(action.ID).Equals(5)
+ Expect(action.ClientSecret).Equals("MY_OLD_SECRET")
}
func TestCreateEditOAuthConfig_EditNonExisting(t *testing.T) {
@@ -166,19 +157,18 @@ func TestCreateEditOAuthConfig_EditNonExisting(t *testing.T) {
return app.ErrNotFound
})
- action := &actions.CreateEditOAuthConfig{}
- action.Initialize()
- action.Model.Provider = "_MY_NEW_PROVIDER"
- action.Model.DisplayName = "My Provider"
- action.Model.Status = enum.OAuthConfigDisabled
- action.Model.ClientID = "823187ahjjfdha8fds7yfdashfjkdsa"
- action.Model.AuthorizeURL = "http://provider/oauth/authorize"
- action.Model.TokenURL = "http://provider/oauth/token"
- action.Model.Scope = "profile email"
- action.Model.ProfileURL = "http://provider/profile/me"
- action.Model.JSONUserIDPath = "user.id"
- action.Model.JSONUserNamePath = "user.name"
- action.Model.JSONUserEmailPath = "user.email"
+ action := actions.NewCreateEditOAuthConfig()
+ action.Provider = "_MY_NEW_PROVIDER"
+ action.DisplayName = "My Provider"
+ action.Status = enum.OAuthConfigDisabled
+ action.ClientID = "823187ahjjfdha8fds7yfdashfjkdsa"
+ action.AuthorizeURL = "http://provider/oauth/authorize"
+ action.TokenURL = "http://provider/oauth/token"
+ action.Scope = "profile email"
+ action.ProfileURL = "http://provider/profile/me"
+ action.JSONUserIDPath = "user.id"
+ action.JSONUserNamePath = "user.name"
+ action.JSONUserEmailPath = "user.email"
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 ff981c38f..e4f26dd30 100644
--- a/app/actions/post.go
+++ b/app/actions/post.go
@@ -3,45 +3,42 @@ package actions
import (
"context"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
"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"
- "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/validate"
)
// CreateNewPost is used to create a new post
type CreateNewPost struct {
- Model *models.NewPost
-}
-
-// Initialize the model
-func (input *CreateNewPost) Initialize() interface{} {
- input.Model = new(models.NewPost)
- return input.Model
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Attachments []*dto.ImageUpload `json:"attachments"`
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateNewPost) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *CreateNewPost) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil
}
// Validate if current model is valid
-func (input *CreateNewPost) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *CreateNewPost) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Title == "" {
+ if action.Title == "" {
result.AddFieldFailure("title", "Title is required.")
- } else if len(input.Model.Title) < 10 {
+ } else if len(action.Title) < 10 {
result.AddFieldFailure("title", "Title needs to be more descriptive.")
- } else if len(input.Model.Title) > 100 {
+ } else if len(action.Title) > 100 {
result.AddFieldFailure("title", "Title must have less than 100 characters.")
} else {
- err := bus.Dispatch(ctx, &query.GetPostBySlug{Slug: slug.Make(input.Model.Title)})
+ err := bus.Dispatch(ctx, &query.GetPostBySlug{Slug: slug.Make(action.Title)})
if err != nil && errors.Cause(err) != app.ErrNotFound {
return validate.Error(err)
} else if err == nil {
@@ -49,7 +46,7 @@ func (input *CreateNewPost) Validate(ctx context.Context, user *models.User) *va
}
}
- messages, err := validate.MultiImageUpload(nil, input.Model.Attachments, validate.MultiImageUploadOpts{
+ messages, err := validate.MultiImageUpload(nil, action.Attachments, validate.MultiImageUploadOpts{
MaxUploads: 3,
MaxKilobytes: 5120,
ExactRatio: false,
@@ -64,58 +61,56 @@ func (input *CreateNewPost) Validate(ctx context.Context, user *models.User) *va
// UpdatePost is used to edit an existing new post
type UpdatePost struct {
- Model *models.UpdatePost
- Post *models.Post
-}
+ Number int `route:"number"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Attachments []*dto.ImageUpload `json:"attachments"`
-// Initialize the model
-func (input *UpdatePost) Initialize() interface{} {
- input.Model = new(models.UpdatePost)
- return input.Model
+ Post *entity.Post
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *UpdatePost) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *UpdatePost) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil && user.IsCollaborator()
}
// Validate if current model is valid
-func (input *UpdatePost) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *UpdatePost) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Title == "" {
+ if action.Title == "" {
result.AddFieldFailure("title", "Title is required.")
- } else if len(input.Model.Title) < 10 {
+ } else if len(action.Title) < 10 {
result.AddFieldFailure("title", "Title needs to be more descriptive.")
}
- if len(input.Model.Title) > 100 {
+ if len(action.Title) > 100 {
result.AddFieldFailure("title", "Title must have less than 100 characters.")
}
- postByNumber := &query.GetPostByNumber{Number: input.Model.Number}
+ postByNumber := &query.GetPostByNumber{Number: action.Number}
if err := bus.Dispatch(ctx, postByNumber); err != nil {
return validate.Error(err)
}
- input.Post = postByNumber.Result
+ action.Post = postByNumber.Result
- postBySlug := &query.GetPostBySlug{Slug: slug.Make(input.Model.Title)}
+ postBySlug := &query.GetPostBySlug{Slug: slug.Make(action.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 {
+ } else if err == nil && postBySlug.Result.ID != action.Post.ID {
result.AddFieldFailure("title", "This has already been posted before.")
}
- if len(input.Model.Attachments) > 0 {
- getAttachments := &query.GetAttachments{Post: input.Post}
+ if len(action.Attachments) > 0 {
+ getAttachments := &query.GetAttachments{Post: action.Post}
err = bus.Dispatch(ctx, getAttachments)
if err != nil {
return validate.Error(err)
}
- messages, err := validate.MultiImageUpload(getAttachments.Result, input.Model.Attachments, validate.MultiImageUploadOpts{
+ messages, err := validate.MultiImageUpload(getAttachments.Result, action.Attachments, validate.MultiImageUploadOpts{
MaxUploads: 3,
MaxKilobytes: 5120,
ExactRatio: false,
@@ -131,29 +126,25 @@ func (input *UpdatePost) Validate(ctx context.Context, user *models.User) *valid
// AddNewComment represents a new comment to be added
type AddNewComment struct {
- Model *models.NewComment
-}
-
-// Initialize the model
-func (input *AddNewComment) Initialize() interface{} {
- input.Model = new(models.NewComment)
- return input.Model
+ Number int `route:"number"`
+ Content string `json:"content"`
+ Attachments []*dto.ImageUpload `json:"attachments"`
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *AddNewComment) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *AddNewComment) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil
}
// Validate if current model is valid
-func (input *AddNewComment) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *AddNewComment) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Content == "" {
+ if action.Content == "" {
result.AddFieldFailure("content", "Comment is required.")
}
- messages, err := validate.MultiImageUpload(nil, input.Model.Attachments, validate.MultiImageUploadOpts{
+ messages, err := validate.MultiImageUpload(nil, action.Attachments, validate.MultiImageUploadOpts{
MaxUploads: 2,
MaxKilobytes: 5120,
ExactRatio: false,
@@ -168,35 +159,33 @@ func (input *AddNewComment) Validate(ctx context.Context, user *models.User) *va
// SetResponse represents the action to update an post response
type SetResponse struct {
- Model *models.SetResponse
- Original *models.Post
-}
+ Number int `route:"number"`
+ Status enum.PostStatus `json:"status"`
+ Text string `json:"text"`
+ OriginalNumber int `json:"originalNumber"`
-// Initialize the model
-func (input *SetResponse) Initialize() interface{} {
- input.Model = new(models.SetResponse)
- return input.Model
+ Original *entity.Post
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *SetResponse) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *SetResponse) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil && user.IsCollaborator()
}
// Validate if current model is valid
-func (input *SetResponse) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *SetResponse) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Status < enum.PostOpen || input.Model.Status > enum.PostDuplicate {
+ if action.Status < enum.PostOpen || action.Status > enum.PostDuplicate {
result.AddFieldFailure("status", "Status is invalid.")
}
- if input.Model.Status == enum.PostDuplicate {
- if input.Model.OriginalNumber == input.Model.Number {
+ if action.Status == enum.PostDuplicate {
+ if action.OriginalNumber == action.Number {
result.AddFieldFailure("originalNumber", "Cannot be a duplicate of itself")
}
- getOriginaPost := &query.GetPostByNumber{Number: input.Model.OriginalNumber}
+ getOriginaPost := &query.GetPostByNumber{Number: action.OriginalNumber}
err := bus.Dispatch(ctx, getOriginaPost)
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
@@ -207,7 +196,7 @@ func (input *SetResponse) Validate(ctx context.Context, user *models.User) *vali
}
if getOriginaPost.Result != nil {
- input.Original = getOriginaPost.Result
+ action.Original = getOriginaPost.Result
}
}
@@ -216,31 +205,27 @@ func (input *SetResponse) Validate(ctx context.Context, user *models.User) *vali
// DeletePost represents the action of an administrator deleting an existing Post
type DeletePost struct {
- Model *models.DeletePost
- Post *models.Post
-}
+ Number int `route:"number"`
+ Text string `json:"text"`
-// Initialize the model
-func (input *DeletePost) Initialize() interface{} {
- input.Model = new(models.DeletePost)
- return input.Model
+ Post *entity.Post
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *DeletePost) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *DeletePost) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil && user.IsAdministrator()
}
// Validate if current model is valid
-func (input *DeletePost) Validate(ctx context.Context, user *models.User) *validate.Result {
- getPost := &query.GetPostByNumber{Number: input.Model.Number}
+func (action *DeletePost) Validate(ctx context.Context, user *entity.User) *validate.Result {
+ getPost := &query.GetPostByNumber{Number: action.Number}
if err := bus.Dispatch(ctx, getPost); err != nil {
return validate.Error(err)
}
- input.Post = getPost.Result
+ action.Post = getPost.Result
- isReferencedQuery := &query.PostIsReferenced{PostID: input.Post.ID}
+ isReferencedQuery := &query.PostIsReferenced{PostID: action.Post.ID}
if err := bus.Dispatch(ctx, isReferencedQuery); err != nil {
return validate.Error(err)
}
@@ -254,46 +239,44 @@ func (input *DeletePost) Validate(ctx context.Context, user *models.User) *valid
// EditComment represents the action to update an existing comment
type EditComment struct {
- Model *models.EditComment
- Post *models.Post
- Comment *models.Comment
-}
+ PostNumber int `route:"number"`
+ ID int `route:"id"`
+ Content string `json:"content"`
+ Attachments []*dto.ImageUpload `json:"attachments"`
-// Initialize the model
-func (input *EditComment) Initialize() interface{} {
- input.Model = new(models.EditComment)
- return input.Model
+ Post *entity.Post
+ Comment *entity.Comment
}
// IsAuthorized returns true if current user is authorized to perform this action
-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}
+func (action *EditComment) IsAuthorized(ctx context.Context, user *entity.User) bool {
+ postByNumber := &query.GetPostByNumber{Number: action.PostNumber}
+ commentByID := &query.GetCommentByID{CommentID: action.ID}
if err := bus.Dispatch(ctx, postByNumber, commentByID); err != nil {
return false
}
- input.Post = postByNumber.Result
- input.Comment = commentByID.Result
- return user.ID == input.Comment.User.ID || user.IsCollaborator()
+ action.Post = postByNumber.Result
+ action.Comment = commentByID.Result
+ return user.ID == action.Comment.User.ID || user.IsCollaborator()
}
// Validate if current model is valid
-func (input *EditComment) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *EditComment) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Content == "" {
+ if action.Content == "" {
result.AddFieldFailure("content", "Comment is required.")
}
- if len(input.Model.Attachments) > 0 {
- getAttachments := &query.GetAttachments{Post: input.Post, Comment: input.Comment}
+ if len(action.Attachments) > 0 {
+ getAttachments := &query.GetAttachments{Post: action.Post, Comment: action.Comment}
err := bus.Dispatch(ctx, getAttachments)
if err != nil {
return validate.Error(err)
}
- messages, err := validate.MultiImageUpload(getAttachments.Result, input.Model.Attachments, validate.MultiImageUploadOpts{
+ messages, err := validate.MultiImageUpload(getAttachments.Result, action.Attachments, validate.MultiImageUploadOpts{
MaxUploads: 2,
MaxKilobytes: 5120,
ExactRatio: false,
@@ -309,18 +292,13 @@ func (input *EditComment) Validate(ctx context.Context, user *models.User) *vali
// DeleteComment represents the action of deleting an existing comment
type DeleteComment struct {
- Model *models.DeleteComment
-}
-
-// Initialize the model
-func (input *DeleteComment) Initialize() interface{} {
- input.Model = new(models.DeleteComment)
- return input.Model
+ PostNumber int `route:"number"`
+ CommentID int `route:"id"`
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *DeleteComment) IsAuthorized(ctx context.Context, user *models.User) bool {
- commentByID := &query.GetCommentByID{CommentID: input.Model.CommentID}
+func (action *DeleteComment) IsAuthorized(ctx context.Context, user *entity.User) bool {
+ commentByID := &query.GetCommentByID{CommentID: action.CommentID}
if err := bus.Dispatch(ctx, commentByID); err != nil {
return false
}
@@ -329,6 +307,6 @@ func (input *DeleteComment) IsAuthorized(ctx context.Context, user *models.User)
}
// Validate if current model is valid
-func (input *DeleteComment) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *DeleteComment) Validate(ctx context.Context, user *entity.User) *validate.Result {
return validate.Success()
}
diff --git a/app/actions/post_test.go b/app/actions/post_test.go
index c44b4c2d9..68f7fd49b 100644
--- a/app/actions/post_test.go
+++ b/app/actions/post_test.go
@@ -5,11 +5,11 @@ import (
"testing"
"github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/entity"
"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"
)
@@ -19,7 +19,7 @@ func TestCreateNewPost_InvalidPostTitles(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetPostBySlug) error {
if q.Slug == "my-great-post" {
- q.Result = &models.Post{Slug: q.Slug}
+ q.Result = &entity.Post{Slug: q.Slug}
return nil
}
return app.ErrNotFound
@@ -33,7 +33,7 @@ func TestCreateNewPost_InvalidPostTitles(t *testing.T) {
"My great great great great great great great great great great great great great great great great great post.",
"my GREAT post",
} {
- action := &actions.CreateNewPost{Model: &models.NewPost{Title: title}}
+ action := &actions.CreateNewPost{Title: title}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "title")
}
@@ -50,7 +50,7 @@ func TestCreateNewPost_ValidPostTitles(t *testing.T) {
"this is my new post",
"this post is very descriptive",
} {
- action := &actions.CreateNewPost{Model: &models.NewPost{Title: title}}
+ action := &actions.CreateNewPost{Title: title}
result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
}
@@ -59,10 +59,10 @@ func TestCreateNewPost_ValidPostTitles(t *testing.T) {
func TestSetResponse_InvalidStatus(t *testing.T) {
RegisterT(t)
- action := &actions.SetResponse{Model: &models.SetResponse{
+ action := &actions.SetResponse{
Status: enum.PostDeleted,
Text: "Spam!",
- }}
+ }
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "status")
}
@@ -70,8 +70,8 @@ func TestSetResponse_InvalidStatus(t *testing.T) {
func TestDeletePost_WhenIsBeingReferenced(t *testing.T) {
RegisterT(t)
- post1 := &models.Post{ID: 1, Number: 1, Title: "Post 1"}
- post2 := &models.Post{ID: 2, Number: 2, Title: "Post 2"}
+ post1 := &entity.Post{ID: 1, Number: 1, Title: "Post 1"}
+ post2 := &entity.Post{ID: 2, Number: 2, Title: "Post 2"}
bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
if q.Number == post1.Number {
@@ -92,21 +92,21 @@ func TestDeletePost_WhenIsBeingReferenced(t *testing.T) {
return nil
})
- action := &actions.DeletePost{Model: &models.DeletePost{}}
- action.Model.Number = post1.Number
+ action := &actions.DeletePost{}
+ action.Number = post1.Number
ExpectSuccess(action.Validate(context.Background(), nil))
- action.Model.Number = post2.Number
+ action.Number = post2.Number
ExpectFailed(action.Validate(context.Background(), nil))
}
func TestDeleteComment(t *testing.T) {
RegisterT(t)
- 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{
+ author := &entity.User{ID: 1, Role: enum.RoleVisitor}
+ notAuthor := &entity.User{ID: 2, Role: enum.RoleVisitor}
+ administrator := &entity.User{ID: 3, Role: enum.RoleAdministrator}
+ comment := &entity.Comment{
ID: 1,
User: author,
Content: "Comment #1",
@@ -121,9 +121,7 @@ func TestDeleteComment(t *testing.T) {
})
action := &actions.DeleteComment{
- Model: &models.DeleteComment{
- CommentID: comment.ID,
- },
+ CommentID: comment.ID,
}
authorized := action.IsAuthorized(context.Background(), notAuthor)
diff --git a/app/actions/settings.go b/app/actions/settings.go
index f15c8f75e..62e52990a 100644
--- a/app/actions/settings.go
+++ b/app/actions/settings.go
@@ -4,47 +4,50 @@ import (
"context"
"fmt"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/pkg/validate"
)
// UpdateUserSettings happens when users updates their settings
type UpdateUserSettings struct {
- Model *models.UpdateUserSettings
+ Name string `json:"name"`
+ AvatarType enum.AvatarType `json:"avatarType"`
+ Avatar *dto.ImageUpload `json:"avatar"`
+ Settings map[string]string `json:"settings"`
}
-// Initialize the model
-func (input *UpdateUserSettings) Initialize() interface{} {
- input.Model = new(models.UpdateUserSettings)
- input.Model.Avatar = &models.ImageUpload{}
- return input.Model
+func NewUpdateUserSettings() *UpdateUserSettings {
+ return &UpdateUserSettings{
+ Avatar: &dto.ImageUpload{},
+ }
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *UpdateUserSettings) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *UpdateUserSettings) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil
}
// Validate if current model is valid
-func (input *UpdateUserSettings) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *UpdateUserSettings) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Name == "" {
+ if action.Name == "" {
result.AddFieldFailure("name", "Name is required.")
}
- if input.Model.AvatarType < 1 || input.Model.AvatarType > 3 {
+ if action.AvatarType < 1 || action.AvatarType > 3 {
result.AddFieldFailure("avatarType", "Invalid avatar type.")
}
- if len(input.Model.Name) > 50 {
+ if len(action.Name) > 50 {
result.AddFieldFailure("name", "Name must have less than 50 characters.")
}
- input.Model.Avatar.BlobKey = user.AvatarBlobKey
- messages, err := validate.ImageUpload(input.Model.Avatar, validate.ImageUploadOpts{
- IsRequired: input.Model.AvatarType == enum.AvatarTypeCustom,
+ action.Avatar.BlobKey = user.AvatarBlobKey
+ messages, err := validate.ImageUpload(action.Avatar, validate.ImageUploadOpts{
+ IsRequired: action.AvatarType == enum.AvatarTypeCustom,
MinHeight: 50,
MinWidth: 50,
ExactRatio: true,
@@ -55,8 +58,8 @@ func (input *UpdateUserSettings) Validate(ctx context.Context, user *models.User
}
result.AddFieldFailure("avatar", messages...)
- if input.Model.Settings != nil {
- for k, v := range input.Model.Settings {
+ if action.Settings != nil {
+ for k, v := range action.Settings {
ok := false
for _, e := range enum.AllNotificationEvents {
if e.UserSettingsKeyName == k {
diff --git a/app/actions/settings_test.go b/app/actions/settings_test.go
index 5c395c7a1..a31d29d56 100644
--- a/app/actions/settings_test.go
+++ b/app/actions/settings_test.go
@@ -5,7 +5,7 @@ import (
"testing"
"github.com/getfider/fider/app/actions"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
. "github.com/getfider/fider/app/pkg/assert"
)
@@ -18,11 +18,10 @@ func TestInvalidUserNames(t *testing.T) {
"123456789012345678901234567890123456789012345678901", // 51 chars
} {
- action := actions.UpdateUserSettings{}
- action.Initialize()
- action.Model.Name = name
- action.Model.AvatarType = enum.AvatarTypeGravatar
- result := action.Validate(context.Background(), &models.User{})
+ action := actions.NewUpdateUserSettings()
+ action.Name = name
+ action.AvatarType = enum.AvatarTypeGravatar
+ result := action.Validate(context.Background(), &entity.User{})
ExpectFailed(result, "name")
}
}
@@ -34,11 +33,10 @@ func TestValidUserNames(t *testing.T) {
"Jon Snow",
"Arya",
} {
- action := actions.UpdateUserSettings{}
- action.Initialize()
- action.Model.Name = name
- action.Model.AvatarType = enum.AvatarTypeGravatar
- result := action.Validate(context.Background(), &models.User{})
+ action := actions.NewUpdateUserSettings()
+ action.Name = name
+ action.AvatarType = enum.AvatarTypeGravatar
+ result := action.Validate(context.Background(), &entity.User{})
ExpectSuccess(result)
}
}
@@ -47,18 +45,17 @@ func TestInvalidSettings(t *testing.T) {
RegisterT(t)
for _, settings := range []map[string]string{
- map[string]string{
+ {
"bad_name": "3",
},
- map[string]string{
+ {
enum.NotificationEventNewComment.UserSettingsKeyName: "4",
},
} {
- action := actions.UpdateUserSettings{}
- action.Initialize()
- action.Model.Name = "John Snow"
- action.Model.Settings = settings
- result := action.Validate(context.Background(), &models.User{})
+ action := actions.NewUpdateUserSettings()
+ action.Name = "John Snow"
+ action.Settings = settings
+ result := action.Validate(context.Background(), &entity.User{})
ExpectFailed(result, "settings", "avatarType")
}
}
@@ -68,26 +65,25 @@ func TestValidSettings(t *testing.T) {
for _, settings := range []map[string]string{
nil,
- map[string]string{
+ {
enum.NotificationEventNewPost.UserSettingsKeyName: enum.NotificationEventNewPost.DefaultSettingValue,
enum.NotificationEventNewComment.UserSettingsKeyName: enum.NotificationEventNewComment.DefaultSettingValue,
enum.NotificationEventChangeStatus.UserSettingsKeyName: enum.NotificationEventChangeStatus.DefaultSettingValue,
},
- map[string]string{
+ {
enum.NotificationEventNewComment.UserSettingsKeyName: enum.NotificationEventNewComment.DefaultSettingValue,
},
} {
- action := actions.UpdateUserSettings{}
- action.Initialize()
- action.Model.Name = "John Snow"
- action.Model.Settings = settings
- action.Model.AvatarType = enum.AvatarTypeGravatar
+ action := actions.NewUpdateUserSettings()
+ action.Name = "John Snow"
+ action.Settings = settings
+ action.AvatarType = enum.AvatarTypeGravatar
- result := action.Validate(context.Background(), &models.User{
+ result := action.Validate(context.Background(), &entity.User{
AvatarBlobKey: "jon.png",
})
ExpectSuccess(result)
- Expect(action.Model.Avatar.BlobKey).Equals("jon.png")
+ Expect(action.Avatar.BlobKey).Equals("jon.png")
}
}
diff --git a/app/actions/signin.go b/app/actions/signin.go
index 43f753b04..07a132586 100644
--- a/app/actions/signin.go
+++ b/app/actions/signin.go
@@ -3,7 +3,7 @@ package actions
import (
"context"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
@@ -12,81 +12,97 @@ import (
// SignInByEmail happens when user request to sign in by email
type SignInByEmail struct {
- Model *models.SignInByEmail
+ Email string `json:"email" format:"lower"`
+ VerificationKey string
}
-// Initialize the model
-func (input *SignInByEmail) Initialize() interface{} {
- input.Model = new(models.SignInByEmail)
- input.Model.VerificationKey = models.GenerateSecretKey()
- return input.Model
+func NewSignInByEmail() *SignInByEmail {
+ return &SignInByEmail{
+ VerificationKey: entity.GenerateEmailVerificationKey(),
+ }
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *SignInByEmail) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *SignInByEmail) IsAuthorized(ctx context.Context, user *entity.User) bool {
return true
}
// Validate if current model is valid
-func (input *SignInByEmail) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *SignInByEmail) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Email == "" {
+ if action.Email == "" {
result.AddFieldFailure("email", "Email is required.")
return result
}
- if len(input.Model.Email) > 200 {
+ if len(action.Email) > 200 {
result.AddFieldFailure("email", "Email must have less than 200 characters.")
}
- messages := validate.Email(input.Model.Email)
+ messages := validate.Email(action.Email)
result.AddFieldFailure("email", messages...)
return result
}
-// CompleteProfile happens when users completes their profile during first time sign in
-type CompleteProfile struct {
- Model *models.CompleteProfile
+//GetEmail returns the email being verified
+func (action *SignInByEmail) GetEmail() string {
+ return action.Email
}
-// Initialize the model
-func (input *CompleteProfile) Initialize() interface{} {
- input.Model = new(models.CompleteProfile)
- return input.Model
+//GetName returns empty for this kind of process
+func (action *SignInByEmail) GetName() string {
+ return ""
+}
+
+//GetUser returns the current user performing this action
+func (action *SignInByEmail) GetUser() *entity.User {
+ return nil
+}
+
+//GetKind returns EmailVerificationKindSignIn
+func (action *SignInByEmail) GetKind() enum.EmailVerificationKind {
+ return enum.EmailVerificationKindSignIn
+}
+
+// CompleteProfile happens when users completes their profile during first time sign in
+type CompleteProfile struct {
+ Key string `json:"key"`
+ Name string `json:"name"`
+ Email string
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CompleteProfile) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *CompleteProfile) IsAuthorized(ctx context.Context, user *entity.User) bool {
return true
}
// Validate if current model is valid
-func (input *CompleteProfile) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *CompleteProfile) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Name == "" {
+ if action.Name == "" {
result.AddFieldFailure("name", "Name is required.")
}
- if len(input.Model.Name) > 50 {
+ if len(action.Name) > 50 {
result.AddFieldFailure("name", "Name must have less than 50 characters.")
}
- if input.Model.Key == "" {
+ if action.Key == "" {
result.AddFieldFailure("key", "Key is required.")
} else {
- findBySignIn := &query.GetVerificationByKey{Kind: enum.EmailVerificationKindSignIn, Key: input.Model.Key}
+ findBySignIn := &query.GetVerificationByKey{Kind: enum.EmailVerificationKindSignIn, Key: action.Key}
err1 := bus.Dispatch(ctx, findBySignIn)
- findByUserInvitation := &query.GetVerificationByKey{Kind: enum.EmailVerificationKindUserInvitation, Key: input.Model.Key}
+ findByUserInvitation := &query.GetVerificationByKey{Kind: enum.EmailVerificationKindUserInvitation, Key: action.Key}
err2 := bus.Dispatch(ctx, findByUserInvitation)
if err1 == nil {
- input.Model.Email = findBySignIn.Result.Email
+ action.Email = findBySignIn.Result.Email
} else if err2 == nil {
- input.Model.Email = findByUserInvitation.Result.Email
+ action.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 ded3e036b..75caec163 100644
--- a/app/actions/signin_test.go
+++ b/app/actions/signin_test.go
@@ -4,12 +4,12 @@ import (
"context"
"testing"
+ "github.com/getfider/fider/app/models/entity"
"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"
)
@@ -17,7 +17,7 @@ import (
func TestSignInByEmail_EmptyEmail(t *testing.T) {
RegisterT(t)
- action := actions.SignInByEmail{Model: &models.SignInByEmail{Email: " "}}
+ action := actions.SignInByEmail{Email: " "}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "email")
}
@@ -25,7 +25,7 @@ func TestSignInByEmail_EmptyEmail(t *testing.T) {
func TestSignInByEmail_InvalidEmail(t *testing.T) {
RegisterT(t)
- action := actions.SignInByEmail{Model: &models.SignInByEmail{Email: "Hi :)"}}
+ action := actions.SignInByEmail{Email: "Hi :)"}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "email")
}
@@ -33,19 +33,18 @@ func TestSignInByEmail_InvalidEmail(t *testing.T) {
func TestSignInByEmail_ShouldHaveVerificationKey(t *testing.T) {
RegisterT(t)
- action := actions.SignInByEmail{}
- action.Initialize()
- action.Model.Email = "[email protected]"
+ action := actions.NewSignInByEmail()
+ action.Email = "[email protected]"
result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
- Expect(action.Model.VerificationKey).IsNotEmpty()
+ Expect(action.VerificationKey).IsNotEmpty()
}
func TestCompleteProfile_EmptyNameAndKey(t *testing.T) {
RegisterT(t)
- action := actions.CompleteProfile{Model: &models.CompleteProfile{}}
+ action := actions.CompleteProfile{}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "name", "key")
}
@@ -53,9 +52,9 @@ func TestCompleteProfile_EmptyNameAndKey(t *testing.T) {
func TestCompleteProfile_LongName(t *testing.T) {
RegisterT(t)
- action := actions.CompleteProfile{Model: &models.CompleteProfile{
+ action := actions.CompleteProfile{
Name: "123456789012345678901234567890123456789012345678901", // 51 chars
- }}
+ }
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "name", "key")
}
@@ -67,7 +66,7 @@ func TestCompleteProfile_UnknownKey(t *testing.T) {
return app.ErrNotFound
})
- action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: "1234567890"}}
+ action := actions.CompleteProfile{Name: "Jon Snow", Key: "1234567890"}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "key")
}
@@ -78,7 +77,7 @@ func TestCompleteProfile_ValidKey(t *testing.T) {
key := "1234567890"
bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
- q.Result = &models.EmailVerification{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
@@ -88,11 +87,11 @@ func TestCompleteProfile_ValidKey(t *testing.T) {
return app.ErrNotFound
})
- action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: key}}
+ action := actions.CompleteProfile{Name: "Jon Snow", Key: key}
result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
- Expect(action.Model.Email).Equals("[email protected]")
+ Expect(action.Email).Equals("[email protected]")
}
func TestCompleteProfile_UserInvitation_ValidKey(t *testing.T) {
@@ -101,7 +100,7 @@ func TestCompleteProfile_UserInvitation_ValidKey(t *testing.T) {
key := "1234567890"
bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
if q.Key == key && q.Kind == enum.EmailVerificationKindUserInvitation {
- q.Result = &models.EmailVerification{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
@@ -111,9 +110,9 @@ func TestCompleteProfile_UserInvitation_ValidKey(t *testing.T) {
return app.ErrNotFound
})
- action := actions.CompleteProfile{Model: &models.CompleteProfile{Name: "Jon Snow", Key: key}}
+ action := actions.CompleteProfile{Name: "Jon Snow", Key: key}
result := action.Validate(context.Background(), nil)
ExpectSuccess(result)
- Expect(action.Model.Email).Equals("[email protected]")
+ Expect(action.Email).Equals("[email protected]")
}
diff --git a/app/actions/tag.go b/app/actions/tag.go
index 462eba4ac..78628b954 100644
--- a/app/actions/tag.go
+++ b/app/actions/tag.go
@@ -4,10 +4,10 @@ import (
"context"
"regexp"
+ "github.com/getfider/fider/app/models/entity"
"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"
@@ -18,53 +18,51 @@ var colorRegex = regexp.MustCompile(`^([A-Fa-f0-9]{6})$`)
// CreateEditTag is used to create a new tag or edit existing
type CreateEditTag struct {
- Tag *models.Tag
- Model *models.CreateEditTag
-}
+ Slug string `route:"slug"`
+ Name string `json:"name"`
+ Color string `json:"color" format:"upper"`
+ IsPublic bool `json:"isPublic"`
-// Initialize the model
-func (input *CreateEditTag) Initialize() interface{} {
- input.Model = new(models.CreateEditTag)
- return input.Model
+ Tag *entity.Tag
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateEditTag) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *CreateEditTag) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil && user.IsAdministrator()
}
// Validate if current model is valid
-func (input *CreateEditTag) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *CreateEditTag) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Slug != "" {
- getSlug := &query.GetTagBySlug{Slug: input.Model.Slug}
+ if action.Slug != "" {
+ getSlug := &query.GetTagBySlug{Slug: action.Slug}
err := bus.Dispatch(ctx, getSlug)
if err != nil {
return validate.Error(err)
}
- input.Tag = getSlug.Result
+ action.Tag = getSlug.Result
}
- if input.Model.Name == "" {
+ if action.Name == "" {
result.AddFieldFailure("name", "Name is required.")
- } else if len(input.Model.Name) > 30 {
+ } else if len(action.Name) > 30 {
result.AddFieldFailure("name", "Name must have less than 30 characters.")
} else {
- getDuplicateSlug := &query.GetTagBySlug{Slug: slug.Make(input.Model.Name)}
+ getDuplicateSlug := &query.GetTagBySlug{Slug: slug.Make(action.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 != getDuplicateSlug.Result.ID) {
+ } else if err == nil && (action.Tag == nil || action.Tag.ID != getDuplicateSlug.Result.ID) {
result.AddFieldFailure("name", "This tag name is already in use.")
}
}
- if input.Model.Color == "" {
+ if action.Color == "" {
result.AddFieldFailure("color", "Color is required.")
- } else if len(input.Model.Color) != 6 {
+ } else if len(action.Color) != 6 {
result.AddFieldFailure("color", "Color must be exactly 6 characters.")
- } else if !colorRegex.MatchString(input.Model.Color) {
+ } else if !colorRegex.MatchString(action.Color) {
result.AddFieldFailure("color", "Color is invalid.")
}
@@ -73,60 +71,51 @@ func (input *CreateEditTag) Validate(ctx context.Context, user *models.User) *va
// DeleteTag is used to delete an existing tag
type DeleteTag struct {
- Tag *models.Tag
- Model *models.DeleteTag
-}
+ Slug string `route:"slug"`
-// Initialize the model
-func (input *DeleteTag) Initialize() interface{} {
- input.Model = new(models.DeleteTag)
- return input.Model
+ Tag *entity.Tag
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *DeleteTag) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *DeleteTag) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil && user.IsAdministrator()
}
// 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}
+func (action *DeleteTag) Validate(ctx context.Context, user *entity.User) *validate.Result {
+ getSlug := &query.GetTagBySlug{Slug: action.Slug}
err := bus.Dispatch(ctx, getSlug)
if err != nil {
return validate.Error(err)
}
- input.Tag = getSlug.Result
+ action.Tag = getSlug.Result
return validate.Success()
}
// AssignUnassignTag is used to assign or remove a tag to/from an post
type AssignUnassignTag struct {
- Tag *models.Tag
- Post *models.Post
- Model *models.AssignUnassignTag
-}
+ Slug string `route:"slug"`
+ Number int `route:"number"`
-// Initialize the model
-func (input *AssignUnassignTag) Initialize() interface{} {
- input.Model = new(models.AssignUnassignTag)
- return input.Model
+ Tag *entity.Tag
+ Post *entity.Post
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *AssignUnassignTag) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *AssignUnassignTag) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil && user.IsCollaborator()
}
// 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}
+func (action *AssignUnassignTag) Validate(ctx context.Context, user *entity.User) *validate.Result {
+ getPost := &query.GetPostByNumber{Number: action.Number}
+ getSlug := &query.GetTagBySlug{Slug: action.Slug}
if err := bus.Dispatch(ctx, getPost, getSlug); err != nil {
return validate.Error(err)
}
- input.Post = getPost.Result
- input.Tag = getSlug.Result
+ action.Post = getPost.Result
+ action.Tag = getSlug.Result
return validate.Success()
}
diff --git a/app/actions/tag_test.go b/app/actions/tag_test.go
index a0a1f969d..fae785de0 100644
--- a/app/actions/tag_test.go
+++ b/app/actions/tag_test.go
@@ -6,11 +6,11 @@ import (
"github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/entity"
"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"
"github.com/getfider/fider/app/pkg/rand"
)
@@ -19,7 +19,7 @@ func TestCreateEditTag_InvalidName(t *testing.T) {
RegisterT(t)
bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
- q.Result = &models.Tag{Slug: "feature-request", Name: "Feature Request", Color: "000000"}
+ q.Result = &entity.Tag{Slug: "feature-request", Name: "Feature Request", Color: "000000"}
return nil
})
@@ -28,7 +28,7 @@ func TestCreateEditTag_InvalidName(t *testing.T) {
"Feature Request",
rand.String(31),
} {
- action := &actions.CreateEditTag{Model: &models.CreateEditTag{Name: name, Color: "FFFFFF"}}
+ action := &actions.CreateEditTag{Name: name, Color: "FFFFFF"}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "name")
}
@@ -48,7 +48,7 @@ func TestCreateEditTag_InvalidColor(t *testing.T) {
"FFF",
"000000X",
} {
- action := &actions.CreateEditTag{Model: &models.CreateEditTag{Name: "Bug", Color: color}}
+ action := &actions.CreateEditTag{Name: "Bug", Color: color}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "color")
}
@@ -57,7 +57,7 @@ func TestCreateEditTag_InvalidColor(t *testing.T) {
func TestCreateEditTag_ValidInput(t *testing.T) {
RegisterT(t)
- tag := &models.Tag{Slug: "to-discuss", Name: "To Discuss", Color: "000000"}
+ tag := &entity.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
@@ -68,12 +68,12 @@ func TestCreateEditTag_ValidInput(t *testing.T) {
}
})
- action := &actions.CreateEditTag{Model: &models.CreateEditTag{Name: "Bug", Color: "FF0000"}}
+ action := &actions.CreateEditTag{Name: "Bug", Color: "FF0000"}
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"}}
+ action = &actions.CreateEditTag{Name: "New Name", Slug: "to-discuss", Color: "FF0000"}
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 bcebc7a48..c7a96d8d5 100644
--- a/app/actions/tenant.go
+++ b/app/actions/tenant.go
@@ -4,7 +4,8 @@ import (
"context"
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/jwt"
@@ -13,99 +14,128 @@ import (
//CreateTenant is the input model used to create a tenant
type CreateTenant struct {
- Model *models.CreateTenant
-}
-
-// Initialize the model
-func (input *CreateTenant) Initialize() interface{} {
- input.Model = new(models.CreateTenant)
- input.Model.VerificationKey = models.GenerateSecretKey()
- return input.Model
+ Token string `json:"token"`
+ Name string `json:"name"`
+ Email string `json:"email" format:"lower"`
+ VerificationKey string
+ TenantName string `json:"tenantName"`
+ LegalAgreement bool `json:"legalAgreement"`
+ Subdomain string `json:"subdomain" format:"lower"`
+ UserClaims *jwt.OAuthClaims
+}
+
+func NewCreateTenant() *CreateTenant {
+ return &CreateTenant{
+ VerificationKey: entity.GenerateEmailVerificationKey(),
+ }
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateTenant) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *CreateTenant) IsAuthorized(ctx context.Context, user *entity.User) bool {
return true
}
// Validate if current model is valid
-func (input *CreateTenant) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *CreateTenant) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
var err error
- if input.Model.Name == "" && input.Model.Email == "" {
- if input.Model.Token == "" {
+ if action.Name == "" && action.Email == "" {
+ if action.Token == "" {
result.AddFieldFailure("token", "Please identify yourself before proceeding.")
} else {
- if input.Model.UserClaims, err = jwt.DecodeOAuthClaims(input.Model.Token); err != nil {
+ if action.UserClaims, err = jwt.DecodeOAuthClaims(action.Token); err != nil {
return validate.Error(err)
}
}
} else {
- if input.Model.Email == "" {
+ if action.Email == "" {
result.AddFieldFailure("email", "Email is required.")
} else {
- messages := validate.Email(input.Model.Email)
+ messages := validate.Email(action.Email)
result.AddFieldFailure("email", messages...)
}
- if input.Model.Name == "" {
+ if action.Name == "" {
result.AddFieldFailure("name", "Name is required.")
}
- if len(input.Model.Name) > 60 {
+ if len(action.Name) > 60 {
result.AddFieldFailure("name", "Name must have less than 60 characters.")
}
}
if env.IsSingleHostMode() {
- input.Model.Subdomain = "default"
+ action.Subdomain = "default"
}
- if input.Model.TenantName == "" {
+ if action.TenantName == "" {
result.AddFieldFailure("tenantName", "Name is required.")
}
- messages, err := validate.Subdomain(ctx, input.Model.Subdomain)
+ messages, err := validate.Subdomain(ctx, action.Subdomain)
if err != nil {
return validate.Error(err)
}
result.AddFieldFailure("subdomain", messages...)
- if env.HasLegal() && !input.Model.LegalAgreement {
+ if env.HasLegal() && !action.LegalAgreement {
result.AddFieldFailure("legalAgreement", "You must agree before proceeding.")
}
return result
}
+//GetEmail returns the email being verified
+func (action *CreateTenant) GetEmail() string {
+ return action.Email
+}
+
+//GetName returns the name of the email owner
+func (action *CreateTenant) GetName() string {
+ return action.Name
+}
+
+//GetUser returns the current user performing this action
+func (action *CreateTenant) GetUser() *entity.User {
+ return nil
+}
+
+//GetKind returns EmailVerificationKindSignUp
+func (action *CreateTenant) GetKind() enum.EmailVerificationKind {
+ return enum.EmailVerificationKindSignUp
+}
+
//UpdateTenantSettings is the input model used to update tenant settings
type UpdateTenantSettings struct {
- Model *models.UpdateTenantSettings
+ Logo *dto.ImageUpload `json:"logo"`
+ Title string `json:"title"`
+ Invitation string `json:"invitation"`
+ WelcomeMessage string `json:"welcomeMessage"`
+ CNAME string `json:"cname" format:"lower"`
}
-// Initialize the model
-func (input *UpdateTenantSettings) Initialize() interface{} {
- input.Model = new(models.UpdateTenantSettings)
- input.Model.Logo = &models.ImageUpload{}
- return input.Model
+func NewUpdateTenantSettings() *UpdateTenantSettings {
+ return &UpdateTenantSettings{
+ Logo: &dto.ImageUpload{},
+ }
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *UpdateTenantSettings) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *UpdateTenantSettings) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil && user.Role == enum.RoleAdministrator
}
// Validate if current model is valid
-func (input *UpdateTenantSettings) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *UpdateTenantSettings) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- tenant, hasTenant := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ tenant, hasTenant := ctx.Value(app.TenantCtxKey).(*entity.Tenant)
if hasTenant {
- input.Model.Logo.BlobKey = tenant.LogoBlobKey
+ action.Logo.BlobKey = tenant.LogoBlobKey
}
- messages, err := validate.ImageUpload(input.Model.Logo, validate.ImageUploadOpts{
+ messages, err := validate.ImageUpload(action.Logo, validate.ImageUploadOpts{
IsRequired: false,
MinHeight: 200,
MinWidth: 200,
@@ -117,20 +147,20 @@ func (input *UpdateTenantSettings) Validate(ctx context.Context, user *models.Us
}
result.AddFieldFailure("logo", messages...)
- if input.Model.Title == "" {
+ if action.Title == "" {
result.AddFieldFailure("title", "Title is required.")
}
- if len(input.Model.Title) > 60 {
+ if len(action.Title) > 60 {
result.AddFieldFailure("title", "Title must have less than 60 characters.")
}
- if len(input.Model.Invitation) > 60 {
+ if len(action.Invitation) > 60 {
result.AddFieldFailure("invitation", "Invitation must have less than 60 characters.")
}
- if input.Model.CNAME != "" {
- messages := validate.CNAME(ctx, input.Model.CNAME)
+ if action.CNAME != "" {
+ messages := validate.CNAME(ctx, action.CNAME)
result.AddFieldFailure("cname", messages...)
}
@@ -139,42 +169,30 @@ func (input *UpdateTenantSettings) Validate(ctx context.Context, user *models.Us
//UpdateTenantAdvancedSettings is the input model used to update tenant advanced settings
type UpdateTenantAdvancedSettings struct {
- Model *models.UpdateTenantAdvancedSettings
-}
-
-// Initialize the model
-func (input *UpdateTenantAdvancedSettings) Initialize() interface{} {
- input.Model = new(models.UpdateTenantAdvancedSettings)
- return input.Model
+ CustomCSS string `json:"customCSS"`
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *UpdateTenantAdvancedSettings) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *UpdateTenantAdvancedSettings) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil && user.Role == enum.RoleAdministrator
}
// Validate if current model is valid
-func (input *UpdateTenantAdvancedSettings) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *UpdateTenantAdvancedSettings) Validate(ctx context.Context, user *entity.User) *validate.Result {
return validate.Success()
}
//UpdateTenantPrivacy is the input model used to update tenant privacy settings
type UpdateTenantPrivacy struct {
- Model *models.UpdateTenantPrivacy
-}
-
-// Initialize the model
-func (input *UpdateTenantPrivacy) Initialize() interface{} {
- input.Model = new(models.UpdateTenantPrivacy)
- return input.Model
+ IsPrivate bool `json:"isPrivate"`
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *UpdateTenantPrivacy) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *UpdateTenantPrivacy) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil && user.Role == enum.RoleAdministrator
}
// Validate if current model is valid
-func (input *UpdateTenantPrivacy) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *UpdateTenantPrivacy) Validate(ctx context.Context, user *entity.User) *validate.Result {
return validate.Success()
}
diff --git a/app/actions/tenant_test.go b/app/actions/tenant_test.go
index 9b27e17bc..d3f61daaa 100644
--- a/app/actions/tenant_test.go
+++ b/app/actions/tenant_test.go
@@ -7,7 +7,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
@@ -18,20 +18,16 @@ import (
func TestCreateTenant_ShouldHaveVerificationKey(t *testing.T) {
RegisterT(t)
- action := actions.CreateTenant{}
- action.Initialize()
-
- Expect(action.Model.VerificationKey).IsNotEmpty()
+ action := actions.NewCreateTenant()
+ Expect(action.VerificationKey).IsNotEmpty()
}
func TestCreateTenant_EmptyToken(t *testing.T) {
RegisterT(t)
action := actions.CreateTenant{
- Model: &models.CreateTenant{
- Token: "",
- LegalAgreement: true,
- },
+ Token: "",
+ LegalAgreement: true,
}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "token", "tenantName", "subdomain")
@@ -41,11 +37,9 @@ func TestCreateTenant_EmptyTenantName(t *testing.T) {
RegisterT(t)
action := actions.CreateTenant{
- Model: &models.CreateTenant{
- Token: jonSnowToken,
- TenantName: "",
- LegalAgreement: true,
- },
+ Token: jonSnowToken,
+ TenantName: "",
+ LegalAgreement: true,
}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "tenantName", "subdomain")
@@ -55,11 +49,9 @@ func TestCreateTenant_EmptyEmail(t *testing.T) {
RegisterT(t)
action := actions.CreateTenant{
- Model: &models.CreateTenant{
- Name: "Jon Snow",
- Email: "",
- LegalAgreement: true,
- },
+ Name: "Jon Snow",
+ Email: "",
+ LegalAgreement: true,
}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "email", "tenantName", "subdomain")
@@ -69,11 +61,9 @@ func TestCreateTenant_InvalidEmail(t *testing.T) {
RegisterT(t)
action := actions.CreateTenant{
- Model: &models.CreateTenant{
- Name: "Jon Snow",
- Email: "jonsnow",
- LegalAgreement: true,
- },
+ Name: "Jon Snow",
+ Email: "jonsnow",
+ LegalAgreement: true,
}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "email", "tenantName", "subdomain")
@@ -88,13 +78,11 @@ func TestCreateTenant_NoAgreement(t *testing.T) {
})
action := actions.CreateTenant{
- Model: &models.CreateTenant{
- Name: "Jon",
- Email: "[email protected]",
- TenantName: "My Company",
- Subdomain: "company",
- LegalAgreement: false,
- },
+ Name: "Jon",
+ Email: "[email protected]",
+ TenantName: "My Company",
+ Subdomain: "company",
+ LegalAgreement: false,
}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "legalAgreement")
@@ -104,11 +92,9 @@ func TestCreateTenant_EmptyName(t *testing.T) {
RegisterT(t)
action := actions.CreateTenant{
- Model: &models.CreateTenant{
- Name: "",
- Email: "[email protected]",
- LegalAgreement: true,
- },
+ Name: "",
+ Email: "[email protected]",
+ LegalAgreement: true,
}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "name", "tenantName", "subdomain")
@@ -118,11 +104,9 @@ func TestCreateTenant_EmptySubdomain(t *testing.T) {
RegisterT(t)
action := actions.CreateTenant{
- Model: &models.CreateTenant{
- Token: jonSnowToken,
- TenantName: "My Company",
- LegalAgreement: true,
- },
+ Token: jonSnowToken,
+ TenantName: "My Company",
+ LegalAgreement: true,
}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "subdomain")
@@ -131,11 +115,10 @@ func TestCreateTenant_EmptySubdomain(t *testing.T) {
func TestUpdateTenantSettings_Unauthorized(t *testing.T) {
RegisterT(t)
- admin := &models.User{ID: 1, Role: enum.RoleAdministrator}
- collaborator := &models.User{ID: 2, Role: enum.RoleCollaborator}
+ admin := &entity.User{ID: 1, Role: enum.RoleAdministrator}
+ collaborator := &entity.User{ID: 2, Role: enum.RoleCollaborator}
- action := actions.UpdateTenantSettings{}
- action.Initialize()
+ action := actions.NewUpdateTenantSettings()
Expect(action.IsAuthorized(context.Background(), admin)).IsTrue()
Expect(action.IsAuthorized(context.Background(), collaborator)).IsFalse()
@@ -145,8 +128,7 @@ func TestUpdateTenantSettings_Unauthorized(t *testing.T) {
func TestUpdateTenantSettings_EmptyTitle(t *testing.T) {
RegisterT(t)
- action := actions.UpdateTenantSettings{}
- action.Initialize()
+ action := actions.NewUpdateTenantSettings()
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "title")
}
@@ -154,7 +136,7 @@ func TestUpdateTenantSettings_EmptyTitle(t *testing.T) {
func TestUpdateTenantSettings_InvalidCNAME(t *testing.T) {
RegisterT(t)
- action := actions.UpdateTenantSettings{Model: &models.UpdateTenantSettings{Title: "Ok", CNAME: "bla"}}
+ action := actions.UpdateTenantSettings{Title: "Ok", CNAME: "bla"}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "cname")
}
@@ -162,7 +144,7 @@ func TestUpdateTenantSettings_InvalidCNAME(t *testing.T) {
func TestUpdateTenantSettings_LargeTitle(t *testing.T) {
RegisterT(t)
- action := actions.UpdateTenantSettings{Model: &models.UpdateTenantSettings{Title: "123456789012345678901234567890123456789012345678901234567890123"}}
+ action := actions.UpdateTenantSettings{Title: "123456789012345678901234567890123456789012345678901234567890123"}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "title")
}
@@ -170,7 +152,7 @@ func TestUpdateTenantSettings_LargeTitle(t *testing.T) {
func TestUpdateTenantSettings_LargeInvitation(t *testing.T) {
RegisterT(t)
- action := actions.UpdateTenantSettings{Model: &models.UpdateTenantSettings{Title: "Ok", Invitation: "123456789012345678901234567890123456789012345678901234567890123"}}
+ action := actions.UpdateTenantSettings{Title: "Ok", Invitation: "123456789012345678901234567890123456789012345678901234567890123"}
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "invitation")
}
@@ -178,16 +160,15 @@ func TestUpdateTenantSettings_LargeInvitation(t *testing.T) {
func TestUpdateTenantSettings_ExistingTenant_WithLogo(t *testing.T) {
RegisterT(t)
- ctx := context.WithValue(context.Background(), app.TenantCtxKey, &models.Tenant{
+ ctx := context.WithValue(context.Background(), app.TenantCtxKey, &entity.Tenant{
ID: 1,
LogoBlobKey: "hello-world.png",
})
- action := actions.UpdateTenantSettings{}
- action.Initialize()
- action.Model.Title = "OK"
- action.Model.Invitation = "Share your ideas!"
+ action := actions.NewUpdateTenantSettings()
+ action.Title = "OK"
+ action.Invitation = "Share your ideas!"
result := action.Validate(ctx, nil)
ExpectSuccess(result)
- Expect(action.Model.Logo.BlobKey).Equals("hello-world.png")
+ Expect(action.Logo.BlobKey).Equals("hello-world.png")
}
diff --git a/app/actions/user.go b/app/actions/user.go
index be3e60950..321098477 100644
--- a/app/actions/user.go
+++ b/app/actions/user.go
@@ -4,7 +4,7 @@ import (
"context"
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
@@ -14,41 +14,37 @@ import (
//CreateUser is the action to create a new user
type CreateUser struct {
- Model *models.CreateUser
-}
-
-// Initialize the model
-func (input *CreateUser) Initialize() interface{} {
- input.Model = new(models.CreateUser)
- return input.Model
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Reference string `json:"reference"`
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateUser) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *CreateUser) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil && user.IsAdministrator()
}
// Validate if current model is valid
-func (input *CreateUser) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *CreateUser) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Name == "" {
+ if action.Name == "" {
result.AddFieldFailure("name", "Name is required.")
- } else if len(input.Model.Name) > 100 {
+ } else if len(action.Name) > 100 {
result.AddFieldFailure("name", "Name must have less than 100 characters.")
}
- if input.Model.Email == "" && input.Model.Reference == "" {
+ if action.Email == "" && action.Reference == "" {
result.AddFieldFailure("", "Either email or reference is required")
} else {
- if input.Model.Email != "" {
- messages := validate.Email(input.Model.Email)
+ if action.Email != "" {
+ messages := validate.Email(action.Email)
if len(messages) > 0 {
result.AddFieldFailure("email", messages...)
}
}
- if len(input.Model.Reference) > 100 {
+ if len(action.Reference) > 100 {
result.AddFieldFailure("reference", "Reference must have less than 100 characters.")
}
}
@@ -58,35 +54,30 @@ func (input *CreateUser) Validate(ctx context.Context, user *models.User) *valid
//ChangeUserRole is the input model change role of an user
type ChangeUserRole struct {
- Model *models.ChangeUserRole
-}
-
-// Initialize the model
-func (input *ChangeUserRole) Initialize() interface{} {
- input.Model = new(models.ChangeUserRole)
- return input.Model
+ Role enum.Role `route:"role"`
+ UserID int `json:"userID"`
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *ChangeUserRole) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *ChangeUserRole) IsAuthorized(ctx context.Context, user *entity.User) bool {
if user == nil {
return false
}
- return user.IsAdministrator() && user.ID != input.Model.UserID
+ return user.IsAdministrator() && user.ID != action.UserID
}
// Validate if current model is valid
-func (input *ChangeUserRole) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *ChangeUserRole) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Role < enum.RoleVisitor || input.Model.Role > enum.RoleAdministrator {
+ if action.Role < enum.RoleVisitor || action.Role > enum.RoleAdministrator {
return validate.Error(app.ErrNotFound)
}
- if user.ID == input.Model.UserID {
+ if user.ID == action.UserID {
result.AddFieldFailure("userID", "It is not allowed to change your own Role.")
}
- userByID := &query.GetUserByID{UserID: input.Model.UserID}
+ userByID := &query.GetUserByID{UserID: action.UserID}
err := bus.Dispatch(ctx, userByID)
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
@@ -102,47 +93,48 @@ func (input *ChangeUserRole) Validate(ctx context.Context, user *models.User) *v
//ChangeUserEmail is the action used to change current user's email
type ChangeUserEmail struct {
- Model *models.ChangeUserEmail
+ Email string `json:"email" format:"lower"`
+ VerificationKey string
+ Requestor *entity.User
}
-// Initialize the model
-func (input *ChangeUserEmail) Initialize() interface{} {
- input.Model = new(models.ChangeUserEmail)
- input.Model.VerificationKey = models.GenerateSecretKey()
- return input.Model
+func NewChangeUserEmail() *ChangeUserEmail {
+ return &ChangeUserEmail{
+ VerificationKey: entity.GenerateEmailVerificationKey(),
+ }
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *ChangeUserEmail) IsAuthorized(ctx context.Context, user *models.User) bool {
+func (action *ChangeUserEmail) IsAuthorized(ctx context.Context, user *entity.User) bool {
return user != nil
}
// Validate if current model is valid
-func (input *ChangeUserEmail) Validate(ctx context.Context, user *models.User) *validate.Result {
+func (action *ChangeUserEmail) Validate(ctx context.Context, user *entity.User) *validate.Result {
result := validate.Success()
- if input.Model.Email == "" {
+ if action.Email == "" {
result.AddFieldFailure("email", "Email is required.")
return result
}
- if len(input.Model.Email) > 200 {
+ if len(action.Email) > 200 {
result.AddFieldFailure("email", "Email must have less than 200 characters.")
return result
}
- if user.Email == input.Model.Email {
+ if user.Email == action.Email {
result.AddFieldFailure("email", "Choose a different email.")
return result
}
- messages := validate.Email(input.Model.Email)
+ messages := validate.Email(action.Email)
if len(messages) > 0 {
result.AddFieldFailure("email", messages...)
return result
}
- userByEmail := &query.GetUserByEmail{Email: input.Model.Email}
+ userByEmail := &query.GetUserByEmail{Email: action.Email}
err := bus.Dispatch(ctx, userByEmail)
if err != nil && errors.Cause(err) != app.ErrNotFound {
return validate.Error(err)
@@ -151,6 +143,26 @@ func (input *ChangeUserEmail) Validate(ctx context.Context, user *models.User) *
result.AddFieldFailure("email", "This email is already in use by someone else")
return result
}
- input.Model.Requestor = user
+ action.Requestor = user
return result
}
+
+//GetEmail returns the email being verified
+func (action *ChangeUserEmail) GetEmail() string {
+ return action.Email
+}
+
+//GetName returns empty for this kind of process
+func (action *ChangeUserEmail) GetName() string {
+ return ""
+}
+
+//GetUser returns the current user performing this action
+func (action *ChangeUserEmail) GetUser() *entity.User {
+ return action.Requestor
+}
+
+//GetKind returns EmailVerificationKindSignIn
+func (action *ChangeUserEmail) GetKind() enum.EmailVerificationKind {
+ return enum.EmailVerificationKindChangeEmail
+}
diff --git a/app/actions/user_test.go b/app/actions/user_test.go
index a85294e2c..2e95c7bdc 100644
--- a/app/actions/user_test.go
+++ b/app/actions/user_test.go
@@ -6,7 +6,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
@@ -20,23 +20,23 @@ func TestCreateUser_InvalidInput(t *testing.T) {
testCases := []struct {
expected []string
message string
- input *models.CreateUser
+ action *actions.CreateUser
}{
{
expected: []string{"name"},
message: "Either email or reference is required",
- input: &models.CreateUser{},
+ action: &actions.CreateUser{},
},
{
expected: []string{"email"},
- input: &models.CreateUser{
+ action: &actions.CreateUser{
Name: "Jon Snow",
Email: "helloworld",
},
},
{
expected: []string{"name", "email", "reference"},
- input: &models.CreateUser{
+ action: &actions.CreateUser{
Name: rand.String(101),
Email: rand.String(201),
Reference: rand.String(101),
@@ -45,10 +45,7 @@ func TestCreateUser_InvalidInput(t *testing.T) {
}
for _, testCase := range testCases {
- action := &actions.CreateUser{
- Model: testCase.input,
- }
- result := action.Validate(context.Background(), nil)
+ result := testCase.action.Validate(context.Background(), nil)
ExpectFailed(result, testCase.expected...)
if testCase.message != "" {
for k, v := range result.Errors {
@@ -64,23 +61,23 @@ func TestCreateUser_ValidInput(t *testing.T) {
RegisterT(t)
testCases := []struct {
- input *models.CreateUser
+ action *actions.CreateUser
}{
{
- input: &models.CreateUser{
+ action: &actions.CreateUser{
Name: "John Snow",
Reference: "812747824",
},
},
{
- input: &models.CreateUser{
+ action: &actions.CreateUser{
Name: "John Snow",
},
},
{
- input: &models.CreateUser{
+ action: &actions.CreateUser{
Name: "John Snow",
Reference: "812747824",
},
@@ -88,10 +85,7 @@ func TestCreateUser_ValidInput(t *testing.T) {
}
for _, testCase := range testCases {
- action := &actions.CreateUser{
- Model: testCase.input,
- }
- result := action.Validate(context.Background(), nil)
+ result := testCase.action.Validate(context.Background(), nil)
ExpectSuccess(result)
}
}
@@ -99,12 +93,12 @@ func TestCreateUser_ValidInput(t *testing.T) {
func TestChangeUserRole_Unauthorized(t *testing.T) {
RegisterT(t)
- for _, user := range []*models.User{
- &models.User{ID: 1, Role: enum.RoleVisitor},
- &models.User{ID: 1, Role: enum.RoleCollaborator},
- &models.User{ID: 2, Role: enum.RoleAdministrator},
+ for _, user := range []*entity.User{
+ {ID: 1, Role: enum.RoleVisitor},
+ {ID: 1, Role: enum.RoleCollaborator},
+ {ID: 2, Role: enum.RoleAdministrator},
} {
- action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: 2}}
+ action := actions.ChangeUserRole{UserID: 2}
Expect(action.IsAuthorized(context.Background(), user)).IsFalse()
}
}
@@ -112,18 +106,18 @@ func TestChangeUserRole_Unauthorized(t *testing.T) {
func TestChangeUserRole_Authorized(t *testing.T) {
RegisterT(t)
- user := &models.User{ID: 2, Role: enum.RoleAdministrator}
- action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: 1}}
+ user := &entity.User{ID: 2, Role: enum.RoleAdministrator}
+ action := actions.ChangeUserRole{UserID: 1}
Expect(action.IsAuthorized(context.Background(), user)).IsTrue()
}
func TestChangeUserRole_InvalidRole(t *testing.T) {
RegisterT(t)
- targetUser := &models.User{Role: enum.RoleVisitor}
- currentUser := &models.User{Role: enum.RoleAdministrator}
+ targetUser := &entity.User{Role: enum.RoleVisitor}
+ currentUser := &entity.User{Role: enum.RoleAdministrator}
- action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: targetUser.ID, Role: 4}}
+ action := actions.ChangeUserRole{UserID: targetUser.ID, Role: 4}
action.IsAuthorized(context.Background(), currentUser)
result := action.Validate(context.Background(), currentUser)
Expect(result.Err).Equals(app.ErrNotFound)
@@ -136,13 +130,13 @@ func TestChangeUserRole_InvalidUser(t *testing.T) {
return app.ErrNotFound
})
- currentUser := &models.User{
- Tenant: &models.Tenant{ID: 1},
+ currentUser := &entity.User{
+ Tenant: &entity.Tenant{ID: 1},
Role: enum.RoleAdministrator,
}
ctx := context.Background()
- action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: 999, Role: enum.RoleAdministrator}}
+ action := actions.ChangeUserRole{UserID: 999, Role: enum.RoleAdministrator}
action.IsAuthorized(ctx, currentUser)
result := action.Validate(ctx, currentUser)
ExpectFailed(result, "userID")
@@ -151,12 +145,12 @@ func TestChangeUserRole_InvalidUser(t *testing.T) {
func TestChangeUserRole_InvalidUser_Tenant(t *testing.T) {
RegisterT(t)
- targetUser := &models.User{
- Tenant: &models.Tenant{ID: 1},
+ targetUser := &entity.User{
+ Tenant: &entity.Tenant{ID: 1},
}
- currentUser := &models.User{
- Tenant: &models.Tenant{ID: 2},
+ currentUser := &entity.User{
+ Tenant: &entity.Tenant{ID: 2},
Role: enum.RoleAdministrator,
}
@@ -168,7 +162,7 @@ func TestChangeUserRole_InvalidUser_Tenant(t *testing.T) {
return app.ErrNotFound
})
- action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: targetUser.ID, Role: enum.RoleAdministrator}}
+ action := actions.ChangeUserRole{UserID: targetUser.ID, Role: enum.RoleAdministrator}
action.IsAuthorized(context.Background(), currentUser)
result := action.Validate(context.Background(), currentUser)
ExpectFailed(result, "userID")
@@ -177,8 +171,8 @@ func TestChangeUserRole_InvalidUser_Tenant(t *testing.T) {
func TestChangeUserRole_CurrentUser(t *testing.T) {
RegisterT(t)
- currentUser := &models.User{
- Tenant: &models.Tenant{ID: 2},
+ currentUser := &entity.User{
+ Tenant: &entity.Tenant{ID: 2},
Role: enum.RoleAdministrator,
}
@@ -190,7 +184,7 @@ func TestChangeUserRole_CurrentUser(t *testing.T) {
return app.ErrNotFound
})
- action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: currentUser.ID, Role: enum.RoleVisitor}}
+ action := actions.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/routes_test.go b/app/cmd/routes_test.go
index 44a212126..01a644339 100644
--- a/app/cmd/routes_test.go
+++ b/app/cmd/routes_test.go
@@ -10,6 +10,6 @@ import (
func TestGetMainEngine(t *testing.T) {
RegisterT(t)
- r := routes(web.New(nil))
+ r := routes(web.New())
Expect(r).IsNotNil()
}
diff --git a/app/cmd/server.go b/app/cmd/server.go
index 7a2c6df88..300b504dc 100644
--- a/app/cmd/server.go
+++ b/app/cmd/server.go
@@ -6,7 +6,6 @@ import (
"os/signal"
"syscall"
- "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"
@@ -28,7 +27,7 @@ import (
//RunServer starts the Fider Server
//Returns an exitcode, 0 for OK and 1 for ERROR
-func RunServer(settings *models.SystemSettings) int {
+func RunServer() int {
svcs := bus.Init()
ctx := log.WithProperty(context.Background(), log.PropertyKeyTag, "BOOTSTRAP")
for _, s := range svcs {
@@ -40,13 +39,13 @@ func RunServer(settings *models.SystemSettings) int {
bus.Publish(ctx, &cmd.PurgeExpiredNotifications{})
- e := routes(web.New(settings))
+ e := routes(web.New())
go e.Start(":" + env.Config.Port)
- return listenSignals(e, settings)
+ return listenSignals(e)
}
-func listenSignals(e *web.Engine, settings *models.SystemSettings) int {
+func listenSignals(e *web.Engine) int {
signals := make(chan os.Signal, 1)
signal.Notify(signals, append([]os.Signal{syscall.SIGTERM, syscall.SIGINT}, extraSignals...)...)
for {
@@ -59,7 +58,7 @@ func listenSignals(e *web.Engine, settings *models.SystemSettings) int {
}
return 0
default:
- ret := handleExtraSignal(s, e, settings)
+ ret := handleExtraSignal(s, e)
if ret >= 0 {
return ret
}
diff --git a/app/cmd/signals_unix.go b/app/cmd/signals_unix.go
index 96876fa8c..cf0079ac1 100644
--- a/app/cmd/signals_unix.go
+++ b/app/cmd/signals_unix.go
@@ -10,13 +10,12 @@ import (
"runtime/pprof"
"syscall"
- "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/web"
)
var extraSignals = []os.Signal{syscall.SIGUSR1}
-func handleExtraSignal(s os.Signal, e *web.Engine, settings *models.SystemSettings) int {
+func handleExtraSignal(s os.Signal, e *web.Engine) int {
switch s {
case syscall.SIGUSR1:
println("SIGUSR1 received")
@@ -25,10 +24,6 @@ func handleExtraSignal(s os.Signal, e *web.Engine, settings *models.SystemSettin
_ = 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))
- buf.WriteString(fmt.Sprintf("# Compiler: %s\n", settings.Compiler))
- 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()))
println(buf.String())
diff --git a/app/handlers/admin.go b/app/handlers/admin.go
index 3e861c2cd..f844204f4 100644
--- a/app/handlers/admin.go
+++ b/app/handlers/admin.go
@@ -34,18 +34,22 @@ func AdvancedSettingsPage() web.HandlerFunc {
// UpdateSettings update current tenant' settings
func UpdateSettings() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.UpdateTenantSettings)
- if result := c.BindTo(input); !result.Ok {
+ action := actions.NewUpdateTenantSettings()
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
if err := bus.Dispatch(c,
&cmd.UploadImage{
- Image: input.Model.Logo,
+ Image: action.Logo,
Folder: "logos",
},
&cmd.UpdateTenantSettings{
- Settings: input.Model,
+ Logo: action.Logo,
+ Title: action.Title,
+ Invitation: action.Invitation,
+ WelcomeMessage: action.WelcomeMessage,
+ CNAME: action.CNAME,
},
); err != nil {
return c.Failure(err)
@@ -58,12 +62,14 @@ func UpdateSettings() web.HandlerFunc {
// UpdateAdvancedSettings update current tenant' advanced settings
func UpdateAdvancedSettings() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.UpdateTenantAdvancedSettings)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.UpdateTenantAdvancedSettings)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
- if err := bus.Dispatch(c, &cmd.UpdateTenantAdvancedSettings{Settings: input.Model}); err != nil {
+ if err := bus.Dispatch(c, &cmd.UpdateTenantAdvancedSettings{
+ CustomCSS: action.CustomCSS,
+ }); err != nil {
return c.Failure(err)
}
@@ -74,12 +80,14 @@ func UpdateAdvancedSettings() web.HandlerFunc {
// UpdatePrivacy update current tenant's privacy settings
func UpdatePrivacy() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.UpdateTenantPrivacy)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.UpdateTenantPrivacy)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
- updateSettings := &cmd.UpdateTenantPrivacySettings{Settings: input.Model}
+ updateSettings := &cmd.UpdateTenantPrivacySettings{
+ IsPrivate: action.IsPrivate,
+ }
if err := bus.Dispatch(c, updateSettings); err != nil {
return c.Failure(err)
}
@@ -141,18 +149,31 @@ func GetOAuthConfig() web.HandlerFunc {
// SaveOAuthConfig is used to create/edit OAuth configurations
func SaveOAuthConfig() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.CreateEditOAuthConfig)
- if result := c.BindTo(input); !result.Ok {
+ action := actions.NewCreateEditOAuthConfig()
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
if err := bus.Dispatch(c,
&cmd.UploadImage{
- Image: input.Model.Logo,
+ Image: action.Logo,
Folder: "logos",
},
&cmd.SaveCustomOAuthConfig{
- Config: input.Model,
+ ID: action.ID,
+ Logo: action.Logo,
+ Provider: action.Provider,
+ Status: action.Status,
+ DisplayName: action.DisplayName,
+ ClientID: action.ClientID,
+ ClientSecret: action.ClientSecret,
+ AuthorizeURL: action.AuthorizeURL,
+ TokenURL: action.TokenURL,
+ Scope: action.Scope,
+ ProfileURL: action.ProfileURL,
+ JSONUserIDPath: action.JSONUserIDPath,
+ JSONUserNamePath: action.JSONUserNamePath,
+ JSONUserEmailPath: action.JSONUserEmailPath,
},
); err != nil {
return c.Failure(err)
diff --git a/app/handlers/admin_test.go b/app/handlers/admin_test.go
index cbd86c348..9d6de8d9f 100644
--- a/app/handlers/admin_test.go
+++ b/app/handlers/admin_test.go
@@ -44,10 +44,10 @@ func TestUpdateSettingsHandler(t *testing.T) {
)
Expect(code).Equals(http.StatusOK)
- 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")
+ Expect(updateCmd.Title).Equals("GoT")
+ Expect(updateCmd.Invitation).Equals("Join us!")
+ Expect(updateCmd.WelcomeMessage).Equals("Welcome to GoT Feedback Forum")
+ Expect(updateCmd.Logo.BlobKey).Equals("logos/hello-world.png")
}
func TestUpdateSettingsHandler_NewLogo(t *testing.T) {
@@ -87,10 +87,10 @@ func TestUpdateSettingsHandler_NewLogo(t *testing.T) {
}`)
Expect(code).Equals(http.StatusOK)
- 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")
+ Expect(updateCmd.Title).Equals("GoT")
+ Expect(updateCmd.Invitation).Equals("Join us!")
+ Expect(updateCmd.WelcomeMessage).Equals("Welcome to GoT Feedback Forum")
+ Expect(updateCmd.Logo.BlobKey).Equals("logos/picture.png")
}
func TestUpdateSettingsHandler_RemoveLogo(t *testing.T) {
@@ -123,10 +123,10 @@ func TestUpdateSettingsHandler_RemoveLogo(t *testing.T) {
}`)
Expect(code).Equals(http.StatusOK)
- 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()
+ Expect(updateCmd.Title).Equals("GoT")
+ Expect(updateCmd.Invitation).Equals("Join us!")
+ Expect(updateCmd.WelcomeMessage).Equals("Welcome to GoT Feedback Forum")
+ Expect(updateCmd.Logo.Remove).IsTrue()
}
func TestUpdatePrivacyHandler(t *testing.T) {
@@ -148,7 +148,7 @@ func TestUpdatePrivacyHandler(t *testing.T) {
)
Expect(code).Equals(http.StatusOK)
- Expect(updateCmd.Settings.IsPrivate).IsTrue()
+ Expect(updateCmd.IsPrivate).IsTrue()
}
func TestManageMembersHandler(t *testing.T) {
diff --git a/app/handlers/apiv1/invite.go b/app/handlers/apiv1/invite.go
index 4e2c9af76..2c31277f4 100644
--- a/app/handlers/apiv1/invite.go
+++ b/app/handlers/apiv1/invite.go
@@ -17,16 +17,16 @@ import (
// SendSampleInvite to current user's email
func SendSampleInvite() web.HandlerFunc {
return func(c *web.Context) error {
- input := &actions.InviteUsers{IsSampleInvite: true}
- if result := c.BindTo(input); !result.Ok {
+ action := &actions.InviteUsers{IsSampleInvite: true}
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
if c.User().Email != "" {
- input.Model.Message = strings.Replace(input.Model.Message, app.InvitePlaceholder, "*the link to accept invitation will be here*", -1)
+ action.Message = strings.Replace(action.Message, app.InvitePlaceholder, "*the link to accept invitation will be here*", -1)
to := dto.NewRecipient(c.User().Name, c.User().Email, dto.Props{
- "subject": input.Model.Subject,
- "message": markdown.Full(input.Model.Message),
+ "subject": action.Subject,
+ "message": markdown.Full(action.Message),
})
bus.Publish(c, &cmd.SendMail{
@@ -46,16 +46,16 @@ func SendSampleInvite() web.HandlerFunc {
// SendInvites sends an email to each recipient
func SendInvites() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.InviteUsers)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.InviteUsers)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
log.Warnf(c, "Sending @{TotalInvites:magenta} invites by @{ClientIP:magenta}", dto.Props{
- "TotalInvites": len(input.Invitations),
+ "TotalInvites": len(action.Invitations),
"ClientIP": c.Request.ClientIP,
})
- c.Enqueue(tasks.SendInvites(input.Model.Subject, input.Model.Message, input.Invitations))
+ c.Enqueue(tasks.SendInvites(action.Subject, action.Message, action.Invitations))
return c.Ok(web.Map{})
}
diff --git a/app/handlers/apiv1/post.go b/app/handlers/apiv1/post.go
index 46dfddd20..61d32aa87 100644
--- a/app/handlers/apiv1/post.go
+++ b/app/handlers/apiv1/post.go
@@ -2,8 +2,8 @@ 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/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
@@ -31,25 +31,25 @@ func SearchPosts() web.HandlerFunc {
// CreatePost creates a new post on current tenant
func CreatePost() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.CreateNewPost)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.CreateNewPost)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
- if err := bus.Dispatch(c, &cmd.UploadImages{Images: input.Model.Attachments, Folder: "attachments"}); err != nil {
+ if err := bus.Dispatch(c, &cmd.UploadImages{Images: action.Attachments, Folder: "attachments"}); err != nil {
return c.Failure(err)
}
newPost := &cmd.AddNewPost{
- Title: input.Model.Title,
- Description: input.Model.Description,
+ Title: action.Title,
+ Description: action.Description,
}
err := bus.Dispatch(c, newPost)
if err != nil {
return c.Failure(err)
}
- setAttachments := &cmd.SetAttachments{Post: newPost.Result, Attachments: input.Model.Attachments}
+ setAttachments := &cmd.SetAttachments{Post: newPost.Result, Attachments: action.Attachments}
addVote := &cmd.AddVote{Post: newPost.Result, User: c.User()}
if err = bus.Dispatch(c, setAttachments, addVote); err != nil {
return c.Failure(err)
@@ -86,24 +86,24 @@ func GetPost() web.HandlerFunc {
// UpdatePost updates an existing post of current tenant
func UpdatePost() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.UpdatePost)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.UpdatePost)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
err := bus.Dispatch(c,
&cmd.UploadImages{
- Images: input.Model.Attachments,
+ Images: action.Attachments,
Folder: "attachments",
},
&cmd.UpdatePost{
- Post: input.Post,
- Title: input.Model.Title,
- Description: input.Model.Description,
+ Post: action.Post,
+ Title: action.Title,
+ Description: action.Description,
},
&cmd.SetAttachments{
- Post: input.Post,
- Attachments: input.Model.Attachments,
+ Post: action.Post,
+ Attachments: action.Attachments,
},
)
if err != nil {
@@ -117,12 +117,12 @@ func UpdatePost() web.HandlerFunc {
// SetResponse changes current post staff response
func SetResponse() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.SetResponse)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.SetResponse)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
- getPost := &query.GetPostByNumber{Number: input.Model.Number}
+ getPost := &query.GetPostByNumber{Number: action.Number}
if err := bus.Dispatch(c, getPost); err != nil {
return c.Failure(err)
}
@@ -130,13 +130,13 @@ func SetResponse() web.HandlerFunc {
prevStatus := getPost.Result.Status
var command bus.Msg
- if input.Model.Status == enum.PostDuplicate {
- command = &cmd.MarkPostAsDuplicate{Post: getPost.Result, Original: input.Original}
+ if action.Status == enum.PostDuplicate {
+ command = &cmd.MarkPostAsDuplicate{Post: getPost.Result, Original: action.Original}
} else {
command = &cmd.SetPostResponse{
Post: getPost.Result,
- Text: input.Model.Text,
- Status: input.Model.Status,
+ Text: action.Text,
+ Status: action.Status,
}
}
@@ -153,23 +153,23 @@ func SetResponse() web.HandlerFunc {
// DeletePost deletes an existing post of current tenant
func DeletePost() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.DeletePost)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.DeletePost)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
err := bus.Dispatch(c, &cmd.SetPostResponse{
- Post: input.Post,
- Text: input.Model.Text,
+ Post: action.Post,
+ Text: action.Text,
Status: enum.PostDeleted,
})
if err != nil {
return c.Failure(err)
}
- if input.Model.Text != "" {
+ if action.Text != "" {
// Only send notification if user wrote a comment.
- c.Enqueue(tasks.NotifyAboutDeletedPost(input.Post))
+ c.Enqueue(tasks.NotifyAboutDeletedPost(action.Post))
}
return c.Ok(web.Map{})
@@ -218,23 +218,23 @@ func GetComment() web.HandlerFunc {
// PostComment creates a new comment on given post
func PostComment() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.AddNewComment)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.AddNewComment)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
- getPost := &query.GetPostByNumber{Number: input.Model.Number}
+ getPost := &query.GetPostByNumber{Number: action.Number}
if err := bus.Dispatch(c, getPost); err != nil {
return c.Failure(err)
}
- if err := bus.Dispatch(c, &cmd.UploadImages{Images: input.Model.Attachments, Folder: "attachments"}); err != nil {
+ if err := bus.Dispatch(c, &cmd.UploadImages{Images: action.Attachments, Folder: "attachments"}); err != nil {
return c.Failure(err)
}
addNewComment := &cmd.AddNewComment{
Post: getPost.Result,
- Content: input.Model.Content,
+ Content: action.Content,
}
if err := bus.Dispatch(c, addNewComment); err != nil {
return c.Failure(err)
@@ -243,12 +243,12 @@ func PostComment() web.HandlerFunc {
if err := bus.Dispatch(c, &cmd.SetAttachments{
Post: getPost.Result,
Comment: addNewComment.Result,
- Attachments: input.Model.Attachments,
+ Attachments: action.Attachments,
}); err != nil {
return c.Failure(err)
}
- c.Enqueue(tasks.NotifyAboutNewComment(getPost.Result, input.Model))
+ c.Enqueue(tasks.NotifyAboutNewComment(getPost.Result, action.Content))
return c.Ok(web.Map{
"id": addNewComment.Result.ID,
@@ -259,24 +259,24 @@ func PostComment() web.HandlerFunc {
// UpdateComment changes an existing comment with new content
func UpdateComment() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.EditComment)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.EditComment)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
err := bus.Dispatch(c,
&cmd.UploadImages{
- Images: input.Model.Attachments,
+ Images: action.Attachments,
Folder: "attachments",
},
&cmd.UpdateComment{
- CommentID: input.Model.ID,
- Content: input.Model.Content,
+ CommentID: action.ID,
+ Content: action.Content,
},
&cmd.SetAttachments{
- Post: input.Post,
- Comment: input.Comment,
- Attachments: input.Model.Attachments,
+ Post: action.Post,
+ Comment: action.Comment,
+ Attachments: action.Attachments,
},
)
if err != nil {
@@ -290,13 +290,13 @@ func UpdateComment() web.HandlerFunc {
// DeleteComment deletes an existing comment by its ID
func DeleteComment() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.DeleteComment)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.DeleteComment)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
err := bus.Dispatch(c, &cmd.DeleteComment{
- CommentID: input.Model.CommentID,
+ CommentID: action.CommentID,
})
if err != nil {
return c.Failure(err)
@@ -309,7 +309,7 @@ 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, func(post *models.Post, user *models.User) bus.Msg {
+ return addOrRemove(c, func(post *entity.Post, user *entity.User) bus.Msg {
return &cmd.AddVote{Post: post, User: user}
})
}
@@ -318,7 +318,7 @@ func AddVote() web.HandlerFunc {
// RemoveVote removes current user from given post list of votes
func RemoveVote() web.HandlerFunc {
return func(c *web.Context) error {
- return addOrRemove(c, func(post *models.Post, user *models.User) bus.Msg {
+ return addOrRemove(c, func(post *entity.Post, user *entity.User) bus.Msg {
return &cmd.RemoveVote{Post: post, User: user}
})
}
@@ -327,7 +327,7 @@ func RemoveVote() web.HandlerFunc {
// Subscribe adds current user to list of subscribers of given post
func Subscribe() web.HandlerFunc {
return func(c *web.Context) error {
- return addOrRemove(c, func(post *models.Post, user *models.User) bus.Msg {
+ return addOrRemove(c, func(post *entity.Post, user *entity.User) bus.Msg {
return &cmd.AddSubscriber{Post: post, User: user}
})
}
@@ -336,7 +336,7 @@ func Subscribe() web.HandlerFunc {
// Unsubscribe removes current user from list of subscribers of given post
func Unsubscribe() web.HandlerFunc {
return func(c *web.Context) error {
- return addOrRemove(c, func(post *models.Post, user *models.User) bus.Msg {
+ return addOrRemove(c, func(post *entity.Post, user *entity.User) bus.Msg {
return &cmd.RemoveSubscriber{Post: post, User: user}
})
}
@@ -365,7 +365,7 @@ func ListVotes() web.HandlerFunc {
}
}
-func addOrRemove(c *web.Context, getCommand func(post *models.Post, user *models.User) bus.Msg) error {
+func addOrRemove(c *web.Context, getCommand func(post *entity.Post, user *entity.User) bus.Msg) error {
number, err := c.ParamAsInt("number")
if err != nil {
return c.NotFound()
diff --git a/app/handlers/apiv1/post_test.go b/app/handlers/apiv1/post_test.go
index 9f17814be..8ace4a619 100644
--- a/app/handlers/apiv1/post_test.go
+++ b/app/handlers/apiv1/post_test.go
@@ -6,9 +6,8 @@ import (
"net/http"
"testing"
- "github.com/getfider/fider/app/models"
-
"github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
@@ -26,7 +25,7 @@ func TestCreatePostHandler(t *testing.T) {
var newPost *cmd.AddNewPost
bus.AddHandler(func(ctx context.Context, c *cmd.AddNewPost) error {
newPost = c
- c.Result = &models.Post{
+ c.Result = &entity.Post{
ID: 1,
Title: c.Title,
Description: c.Description,
@@ -66,7 +65,7 @@ func TestCreatePostHandler_WithoutTitle(t *testing.T) {
func TestGetPostHandler(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 5, Number: 5, Title: "My First Post", Description: "Such an amazing description"}
+ post := &entity.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
@@ -89,7 +88,7 @@ func TestGetPostHandler(t *testing.T) {
func TestUpdatePostHandler_TenantStaff(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 5, Number: 5, Title: "My First Post", Description: "With a description"}
+ post := &entity.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
@@ -137,7 +136,7 @@ func TestUpdatePostHandler_NonAuthorized(t *testing.T) {
func TestUpdatePostHandler_InvalidTitle(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 5, Number: 5, Title: "My First Post", Description: "Such an amazing description"}
+ post := &entity.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
@@ -160,7 +159,7 @@ func TestUpdatePostHandler_InvalidTitle(t *testing.T) {
func TestUpdatePostHandler_InvalidPost(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 5, Number: 5, Title: "My First Post", Description: "Such an amazing description"}
+ post := &entity.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
@@ -184,8 +183,8 @@ func TestUpdatePostHandler_InvalidPost(t *testing.T) {
func TestUpdatePostHandler_DuplicateTitle(t *testing.T) {
RegisterT(t)
- 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"}
+ post1 := &entity.Post{ID: 1, Number: 1, Title: "My First Post", Slug: "my-first-post"}
+ post2 := &entity.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
@@ -222,7 +221,7 @@ func TestUpdatePostHandler_DuplicateTitle(t *testing.T) {
func TestSetResponseHandler(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 1, Number: 1, Title: "My First Post", Slug: "my-first-post"}
+ post := &entity.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
@@ -270,8 +269,8 @@ func TestSetResponseHandler_Duplicate(t *testing.T) {
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"}
+ post1 := &entity.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ post2 := &entity.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
@@ -299,7 +298,7 @@ func TestSetResponseHandler_Duplicate(t *testing.T) {
func TestSetResponseHandler_Duplicate_NotFound(t *testing.T) {
RegisterT(t)
- post1 := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ post1 := &entity.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
@@ -321,7 +320,7 @@ func TestSetResponseHandler_Duplicate_NotFound(t *testing.T) {
func TestSetResponseHandler_Duplicate_Itself(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ post := &entity.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
@@ -343,7 +342,7 @@ func TestSetResponseHandler_Duplicate_Itself(t *testing.T) {
func TestAddVoteHandler(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ post := &entity.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
@@ -385,7 +384,7 @@ func TestAddVoteHandler_InvalidPost(t *testing.T) {
func TestRemoveVoteHandler(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ post := &entity.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
@@ -411,7 +410,7 @@ func TestRemoveVoteHandler(t *testing.T) {
func TestDeletePostHandler_Authorized(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ post := &entity.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
@@ -443,7 +442,7 @@ func TestDeletePostHandler_Authorized(t *testing.T) {
func TestPostCommentHandler(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ post := &entity.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
@@ -452,7 +451,7 @@ func TestPostCommentHandler(t *testing.T) {
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}
+ c.Result = &entity.Comment{ID: 1, Content: c.Content}
return nil
})
@@ -473,7 +472,7 @@ func TestPostCommentHandler(t *testing.T) {
func TestPostCommentHandler_WithoutContent(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ post := &entity.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
@@ -493,13 +492,13 @@ func TestUpdateCommentHandler_Authorized(t *testing.T) {
server := mock.NewServer()
- post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ post := &entity.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.AryaStark}
+ comment := &entity.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
@@ -531,13 +530,13 @@ func TestUpdateCommentHandler_Unauthorized(t *testing.T) {
server := mock.NewServer()
- post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ post := &entity.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}
+ comment := &entity.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
@@ -556,16 +555,16 @@ func TestUpdateCommentHandler_Unauthorized(t *testing.T) {
func TestListCommentHandler(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 1, Number: 1, Title: "The Post #1", Description: "The Description #1"}
+ post := &entity.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"},
+ q.Result = []*entity.Comment{
+ {ID: 1, Content: "First Comment"},
+ {ID: 2, Content: "First Comment"},
}
return nil
})
diff --git a/app/handlers/apiv1/tag.go b/app/handlers/apiv1/tag.go
index 2cfc15d51..52c43d819 100644
--- a/app/handlers/apiv1/tag.go
+++ b/app/handlers/apiv1/tag.go
@@ -23,12 +23,12 @@ func ListTags() web.HandlerFunc {
// AssignTag to existing dea
func AssignTag() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.AssignUnassignTag)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.AssignUnassignTag)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
- err := bus.Dispatch(c, &cmd.AssignTag{Tag: input.Tag, Post: input.Post})
+ err := bus.Dispatch(c, &cmd.AssignTag{Tag: action.Tag, Post: action.Post})
if err != nil {
return c.Failure(err)
}
@@ -40,12 +40,12 @@ func AssignTag() web.HandlerFunc {
// UnassignTag from existing dea
func UnassignTag() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.AssignUnassignTag)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.AssignUnassignTag)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
- err := bus.Dispatch(c, &cmd.UnassignTag{Tag: input.Tag, Post: input.Post})
+ err := bus.Dispatch(c, &cmd.UnassignTag{Tag: action.Tag, Post: action.Post})
if err != nil {
return c.Failure(err)
}
@@ -57,17 +57,17 @@ func UnassignTag() web.HandlerFunc {
// CreateEditTag creates a new tag on current tenant
func CreateEditTag() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.CreateEditTag)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.CreateEditTag)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
- if input.Model.Slug != "" {
+ if action.Slug != "" {
updateTag := &cmd.UpdateTag{
- TagID: input.Tag.ID,
- Name: input.Model.Name,
- Color: input.Model.Color,
- IsPublic: input.Model.IsPublic,
+ TagID: action.Tag.ID,
+ Name: action.Name,
+ Color: action.Color,
+ IsPublic: action.IsPublic,
}
if err := bus.Dispatch(c, updateTag); err != nil {
return c.Failure(err)
@@ -76,9 +76,9 @@ func CreateEditTag() web.HandlerFunc {
}
addNewTag := &cmd.AddNewTag{
- Name: input.Model.Name,
- Color: input.Model.Color,
- IsPublic: input.Model.IsPublic,
+ Name: action.Name,
+ Color: action.Color,
+ IsPublic: action.IsPublic,
}
if err := bus.Dispatch(c, addNewTag); err != nil {
return c.Failure(err)
@@ -90,12 +90,12 @@ func CreateEditTag() web.HandlerFunc {
// DeleteTag deletes an existing tag
func DeleteTag() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.DeleteTag)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.DeleteTag)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
- err := bus.Dispatch(c, &cmd.DeleteTag{Tag: input.Tag})
+ err := bus.Dispatch(c, &cmd.DeleteTag{Tag: action.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 62aedde2c..879f705ed 100644
--- a/app/handlers/apiv1/tag_test.go
+++ b/app/handlers/apiv1/tag_test.go
@@ -7,8 +7,8 @@ import (
"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/entity"
"github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/bus"
@@ -73,7 +73,7 @@ func TestCreateTagHandler_InvalidRequests(t *testing.T) {
func TestCreateTagHandler_AlreadyInUse(t *testing.T) {
RegisterT(t)
- tag := &models.Tag{Name: "Bug", Slug: "bug"}
+ tag := &entity.Tag{Name: "Bug", Slug: "bug"}
bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {
q.Result = tag
return nil
@@ -127,7 +127,7 @@ func TestEditInvalidTagHandler(t *testing.T) {
func TestEditExistingTagHandler(t *testing.T) {
RegisterT(t)
- tag := &models.Tag{ID: 5, Name: "Bug", Slug: "bug", Color: "0000FF", IsPublic: true}
+ tag := &entity.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
@@ -174,7 +174,7 @@ func TestDeleteInvalidTagHandler(t *testing.T) {
func TestDeleteExistingTagHandler(t *testing.T) {
RegisterT(t)
- tag := &models.Tag{ID: 5, Name: "Bug", Slug: "bug", Color: "0000FF", IsPublic: true}
+ tag := &entity.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
@@ -198,7 +198,7 @@ func TestDeleteExistingTagHandler(t *testing.T) {
func TestDeleteExistingTagHandler_Collaborator(t *testing.T) {
RegisterT(t)
- tag := &models.Tag{ID: 5, Name: "Bug", Slug: "bug", Color: "0000FF", IsPublic: true}
+ tag := &entity.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
@@ -215,8 +215,8 @@ func TestDeleteExistingTagHandler_Collaborator(t *testing.T) {
func TestAssignTagHandler_Success(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 2, Number: 2}
- tag := &models.Tag{ID: 5, Slug: "bug"}
+ post := &entity.Post{ID: 2, Number: 2}
+ tag := &entity.Tag{ID: 5, Slug: "bug"}
bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
q.Result = post
return nil
@@ -247,7 +247,7 @@ func TestAssignTagHandler_Success(t *testing.T) {
func TestAssignTagHandler_UnknownTag(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 2, Number: 2}
+ post := &entity.Post{ID: 2, Number: 2}
bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
q.Result = post
return nil
@@ -288,8 +288,8 @@ func TestAssignOrUnassignTagHandler_Unauthorized(t *testing.T) {
func TestUnassignTagHandler_Success(t *testing.T) {
RegisterT(t)
- post := &models.Post{ID: 2, Number: 2}
- tag := &models.Tag{ID: 5, Slug: "bug"}
+ post := &entity.Post{ID: 2, Number: 2}
+ tag := &entity.Tag{ID: 5, Slug: "bug"}
bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
q.Result = post
return nil
@@ -320,10 +320,10 @@ func TestUnassignTagHandler_Success(t *testing.T) {
func TestListTagsHandler(t *testing.T) {
RegisterT(t)
- 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}
+ tag1 := &entity.Tag{ID: 2, Name: "Bug", Slug: "bug", Color: "0000FF", IsPublic: true}
+ tag2 := &entity.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}
+ q.Result = []*entity.Tag{tag1, tag2}
return nil
})
diff --git a/app/handlers/apiv1/user.go b/app/handlers/apiv1/user.go
index 78abe6ff3..b75ed64b0 100644
--- a/app/handlers/apiv1/user.go
+++ b/app/handlers/apiv1/user.go
@@ -3,8 +3,8 @@ package apiv1
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/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
@@ -26,28 +26,28 @@ func ListUsers() web.HandlerFunc {
// CreateUser is used to create new users
func CreateUser() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.CreateUser)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.CreateUser)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
- var user *models.User
+ var user *entity.User
- getByReference := &query.GetUserByProvider{Provider: "reference", UID: input.Model.Reference}
+ getByReference := &query.GetUserByProvider{Provider: "reference", UID: action.Reference}
err := bus.Dispatch(c, getByReference)
user = getByReference.Result
if err != nil && errors.Cause(err) == app.ErrNotFound {
- if input.Model.Email != "" {
- getByEmail := &query.GetUserByEmail{Email: input.Model.Email}
+ if action.Email != "" {
+ getByEmail := &query.GetUserByEmail{Email: action.Email}
err = bus.Dispatch(c, getByEmail)
user = getByEmail.Result
}
if err != nil && errors.Cause(err) == app.ErrNotFound {
- user = &models.User{
+ user = &entity.User{
Tenant: c.Tenant(),
- Name: input.Model.Name,
- Email: input.Model.Email,
+ Name: action.Name,
+ Email: action.Email,
Role: enum.RoleVisitor,
}
err = bus.Dispatch(c, &cmd.RegisterUser{User: user})
@@ -58,11 +58,11 @@ func CreateUser() web.HandlerFunc {
return c.Failure(err)
}
- if input.Model.Reference != "" && !user.HasProvider("reference") {
+ if action.Reference != "" && !user.HasProvider("reference") {
if err := bus.Dispatch(c, &cmd.RegisterUserProvider{
UserID: user.ID,
ProviderName: "reference",
- ProviderUID: input.Model.Reference,
+ ProviderUID: action.Reference,
}); err != nil {
return c.Failure(err)
}
diff --git a/app/handlers/apiv1/user_test.go b/app/handlers/apiv1/user_test.go
index ccc5bdf5b..3a3510b22 100644
--- a/app/handlers/apiv1/user_test.go
+++ b/app/handlers/apiv1/user_test.go
@@ -8,8 +8,8 @@ import (
"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/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
@@ -21,9 +21,9 @@ func TestListUsersHandler(t *testing.T) {
RegisterT(t)
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"},
+ q.Result = []*entity.User{
+ {ID: 1, Name: "User 1"},
+ {ID: 2, Name: "User 2"},
}
return nil
})
@@ -115,7 +115,7 @@ func TestCreateUser_NewUser(t *testing.T) {
server := mock.NewServer()
- var newUser *models.User
+ var newUser *entity.User
bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error {
if newUser != nil {
@@ -143,7 +143,7 @@ func TestCreateUser_NewUser(t *testing.T) {
bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUserProvider) error {
if c.UserID == newUser.ID {
- newUser.Providers = append(newUser.Providers, &models.UserProvider{
+ newUser.Providers = append(newUser.Providers, &entity.UserProvider{
Name: c.ProviderName,
UID: c.ProviderUID,
})
diff --git a/app/handlers/common.go b/app/handlers/common.go
index 831d92e82..e8974d713 100644
--- a/app/handlers/common.go
+++ b/app/handlers/common.go
@@ -8,12 +8,12 @@ import (
"time"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/entity"
"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"
@@ -112,19 +112,19 @@ type NewLogError struct {
//LogError logs an error coming from the UI
func LogError() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(NewLogError)
- err := c.Bind(input)
+ action := new(NewLogError)
+ err := c.Bind(action)
if err != nil {
return c.Failure(err)
}
- log.Debugf(c, input.Message, dto.Props{
- "Data": input.Data,
+ log.Debugf(c, action.Message, dto.Props{
+ "Data": action.Data,
})
return c.Ok(web.Map{})
}
}
-func validateKey(kind enum.EmailVerificationKind, c *web.Context) (*models.EmailVerification, error) {
+func validateKey(kind enum.EmailVerificationKind, c *web.Context) (*entity.EmailVerification, error) {
key := c.QueryParam("k")
//If key has been used, return NotFound
diff --git a/app/handlers/common_test.go b/app/handlers/common_test.go
index 7239c4b90..0e076538c 100644
--- a/app/handlers/common_test.go
+++ b/app/handlers/common_test.go
@@ -6,7 +6,7 @@ import (
"net/http"
"testing"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
@@ -79,7 +79,7 @@ func TestSitemap(t *testing.T) {
RegisterT(t)
bus.AddHandler(func(ctx context.Context, q *query.GetAllPosts) error {
- q.Result = []*models.Post{}
+ q.Result = []*entity.Post{}
return nil
})
@@ -98,7 +98,7 @@ func TestSitemap_WithPosts(t *testing.T) {
RegisterT(t)
bus.AddHandler(func(ctx context.Context, q *query.GetAllPosts) error {
- q.Result = []*models.Post{
+ q.Result = []*entity.Post{
{Number: 1, Slug: "my-new-idea-1", Title: "My new idea 1"},
{Number: 2, Slug: "the-other-idea", Title: "The other idea"},
}
diff --git a/app/handlers/images_test.go b/app/handlers/images_test.go
index e90b74b5a..971745708 100644
--- a/app/handlers/images_test.go
+++ b/app/handlers/images_test.go
@@ -7,11 +7,11 @@ import (
"testing"
"github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/entity"
"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"
"github.com/getfider/fider/app/handlers"
@@ -24,7 +24,7 @@ func TestGravatarHandler(t *testing.T) {
server := mock.NewServer()
- user := &models.User{
+ user := &entity.User{
ID: 3,
Name: "Darth Vader",
@@ -57,7 +57,7 @@ func TestGravatarNotFound_LetterAvatarHandler(t *testing.T) {
server := mock.NewServer()
- user := &models.User{
+ user := &entity.User{
ID: 3,
Name: "Darth Vader",
diff --git a/app/handlers/notification_test.go b/app/handlers/notification_test.go
index 9dfed435f..3bdbab3dc 100644
--- a/app/handlers/notification_test.go
+++ b/app/handlers/notification_test.go
@@ -5,8 +5,8 @@ import (
"net/http"
"testing"
- "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
@@ -51,8 +51,8 @@ func TestNotificationsHandler(t *testing.T) {
func TestReadNotificationHandler(t *testing.T) {
RegisterT(t)
- not1 := &models.Notification{ID: 1, Link: "/abc"}
- not2 := &models.Notification{ID: 2, Link: "/def"}
+ not1 := &entity.Notification{ID: 1, Link: "/abc"}
+ not2 := &entity.Notification{ID: 2, Link: "/def"}
bus.AddHandler(func(ctx context.Context, q *query.GetNotificationByID) error {
if q.ID == 1 {
diff --git a/app/handlers/oauth.go b/app/handlers/oauth.go
index 6655d27c9..dfbc6674c 100644
--- a/app/handlers/oauth.go
+++ b/app/handlers/oauth.go
@@ -7,13 +7,13 @@ import (
"time"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/entity"
"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"
@@ -88,7 +88,7 @@ func OAuthToken() web.HandlerFunc {
return c.Failure(err)
}
- var user *models.User
+ var user *entity.User
userByProvider := &query.GetUserByProvider{Provider: provider, UID: oauthUser.Result.ID}
err := bus.Dispatch(c, userByProvider)
@@ -105,12 +105,12 @@ func OAuthToken() web.HandlerFunc {
return c.Redirect("/not-invited")
}
- user = &models.User{
+ user = &entity.User{
Name: oauthUser.Result.Name,
Tenant: c.Tenant(),
Email: oauthUser.Result.Email,
Role: enum.RoleVisitor,
- Providers: []*models.UserProvider{
+ Providers: []*entity.UserProvider{
{
UID: oauthUser.Result.ID,
Name: provider,
diff --git a/app/handlers/oauth_test.go b/app/handlers/oauth_test.go
index 67cf82722..1da5e4797 100644
--- a/app/handlers/oauth_test.go
+++ b/app/handlers/oauth_test.go
@@ -5,6 +5,7 @@ import (
"testing"
"github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/services/oauth"
@@ -15,7 +16,6 @@ import (
"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"
@@ -220,7 +220,7 @@ func TestOAuthTokenHandler_ExistingUserAndProvider(t *testing.T) {
func TestOAuthTokenHandler_NewUser(t *testing.T) {
RegisterT(t)
- var registeredUser *models.User
+ var registeredUser *entity.User
bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
registeredUser = c.User
return nil
@@ -267,7 +267,7 @@ func TestOAuthTokenHandler_NewUserWithoutEmail(t *testing.T) {
RegisterT(t)
server := mock.NewServer()
- var newUser *models.User
+ var newUser *entity.User
bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
c.User.ID = 1
newUser = c.User
@@ -305,7 +305,7 @@ func TestOAuthTokenHandler_NewUserWithoutEmail(t *testing.T) {
Expect(code).Equals(http.StatusTemporaryRedirect)
Expect(response.Header().Get("Location")).Equals("/")
- ExpectFiderAuthCookie(response, &models.User{
+ ExpectFiderAuthCookie(response, &entity.User{
ID: 1,
Name: "Mark",
})
@@ -314,12 +314,12 @@ func TestOAuthTokenHandler_NewUserWithoutEmail(t *testing.T) {
func TestOAuthTokenHandler_ExistingUser_WithoutEmail(t *testing.T) {
RegisterT(t)
- user := &models.User{
+ user := &entity.User{
ID: 3,
Name: "Some Facebook Guy",
Email: "",
Tenant: mock.DemoTenant,
- Providers: []*models.UserProvider{
+ Providers: []*entity.UserProvider{
{UID: "FB456", Name: app.FacebookProvider},
},
}
@@ -357,7 +357,7 @@ func TestOAuthTokenHandler_ExistingUser_WithoutEmail(t *testing.T) {
Expect(code).Equals(http.StatusTemporaryRedirect)
Expect(response.Header().Get("Location")).Equals("/")
- ExpectFiderAuthCookie(response, &models.User{
+ ExpectFiderAuthCookie(response, &entity.User{
ID: 3,
Name: "Some Facebook Guy",
Email: "",
@@ -367,9 +367,9 @@ func TestOAuthTokenHandler_ExistingUser_WithoutEmail(t *testing.T) {
func TestOAuthTokenHandler_ExistingUser_NewProvider(t *testing.T) {
RegisterT(t)
- var newProvider *models.UserProvider
+ var newProvider *entity.UserProvider
bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUserProvider) error {
- newProvider = &models.UserProvider{
+ newProvider = &entity.UserProvider{
Name: c.ProviderName,
UID: c.ProviderUID,
}
diff --git a/app/handlers/post_test.go b/app/handlers/post_test.go
index d28b2dc93..59733b1a4 100644
--- a/app/handlers/post_test.go
+++ b/app/handlers/post_test.go
@@ -7,7 +7,7 @@ import (
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
@@ -42,7 +42,7 @@ func TestIndexHandler(t *testing.T) {
func TestDetailsHandler(t *testing.T) {
RegisterT(t)
- post := &models.Post{Number: 1, Title: "My Post Title", Slug: "my-post-title"}
+ post := &entity.Post{Number: 1, Title: "My Post Title", Slug: "my-post-title"}
bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
q.Result = post
@@ -84,7 +84,7 @@ func TestDetailsHandler(t *testing.T) {
func TestDetailsHandler_RedirectOnDifferentSlu(t *testing.T) {
RegisterT(t)
- post := &models.Post{Number: 1, Title: "My Post Title", Slug: "my-post-title"}
+ post := &entity.Post{Number: 1, Title: "My Post Title", Slug: "my-post-title"}
bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {
q.Result = post
diff --git a/app/handlers/settings.go b/app/handlers/settings.go
index 90ec01f7d..73d46d4b2 100644
--- a/app/handlers/settings.go
+++ b/app/handlers/settings.go
@@ -18,21 +18,21 @@ import (
// ChangeUserEmail register the intent of changing user email
func ChangeUserEmail() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.ChangeUserEmail)
- if result := c.BindTo(input); !result.Ok {
+ action := actions.NewChangeUserEmail()
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
err := bus.Dispatch(c, &cmd.SaveVerificationKey{
- Key: input.Model.VerificationKey,
+ Key: action.VerificationKey,
Duration: 24 * time.Hour,
- Request: input.Model,
+ Request: action,
})
if err != nil {
return c.Failure(err)
}
- c.Enqueue(tasks.SendChangeEmailConfirmation(input.Model))
+ c.Enqueue(tasks.SendChangeEmailConfirmation(action))
return c.Ok(web.Map{})
}
@@ -87,23 +87,23 @@ func UserSettings() web.HandlerFunc {
// UpdateUserSettings updates current user settings
func UpdateUserSettings() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.UpdateUserSettings)
- if result := c.BindTo(input); !result.Ok {
+ action := actions.NewUpdateUserSettings()
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
if err := bus.Dispatch(c,
&cmd.UploadImage{
- Image: input.Model.Avatar,
+ Image: action.Avatar,
Folder: "avatars",
},
&cmd.UpdateCurrentUser{
- Name: input.Model.Name,
- Avatar: input.Model.Avatar,
- AvatarType: input.Model.AvatarType,
+ Name: action.Name,
+ Avatar: action.Avatar,
+ AvatarType: action.AvatarType,
},
&cmd.UpdateCurrentUserSettings{
- Settings: input.Model.Settings,
+ Settings: action.Settings,
},
); err != nil {
return c.Failure(err)
@@ -116,14 +116,14 @@ func UpdateUserSettings() web.HandlerFunc {
// ChangeUserRole changes given user role
func ChangeUserRole() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.ChangeUserRole)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.ChangeUserRole)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
changeRole := &cmd.ChangeUserRole{
- UserID: input.Model.UserID,
- Role: input.Model.Role,
+ UserID: action.UserID,
+ Role: action.Role,
}
if err := bus.Dispatch(c, changeRole); err != nil {
diff --git a/app/handlers/settings_test.go b/app/handlers/settings_test.go
index 92a3bdc15..fc63a42d8 100644
--- a/app/handlers/settings_test.go
+++ b/app/handlers/settings_test.go
@@ -9,13 +9,12 @@ import (
"github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/models/entity"
"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/bus"
@@ -222,7 +221,7 @@ func TestVerifyChangeEmailKeyHandler_Success(t *testing.T) {
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{
+ q.Result = &entity.EmailVerification{
UserID: mock.JonSnow.ID,
Key: q.Key,
Kind: q.Kind,
@@ -266,7 +265,7 @@ func TestVerifyChangeEmailKeyHandler_DifferentUser(t *testing.T) {
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{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
ExpiresAt: time.Now().Add(10 * time.Minute),
diff --git a/app/handlers/signin.go b/app/handlers/signin.go
index 725e5f839..744b21647 100644
--- a/app/handlers/signin.go
+++ b/app/handlers/signin.go
@@ -5,11 +5,11 @@ import (
"time"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/entity"
"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"
@@ -46,21 +46,21 @@ func NotInvitedPage() web.HandlerFunc {
// SignInByEmail sends a new email with verification key
func SignInByEmail() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.SignInByEmail)
- if result := c.BindTo(input); !result.Ok {
+ action := actions.NewSignInByEmail()
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
err := bus.Dispatch(c, &cmd.SaveVerificationKey{
- Key: input.Model.VerificationKey,
+ Key: action.VerificationKey,
Duration: 30 * time.Minute,
- Request: input.Model,
+ Request: action,
})
if err != nil {
return c.Failure(err)
}
- c.Enqueue(tasks.SendSignInEmail(input.Model))
+ c.Enqueue(tasks.SendSignInEmail(action.Email, action.VerificationKey))
return c.Ok(web.Map{})
}
@@ -74,13 +74,13 @@ func VerifySignInKey(kind enum.EmailVerificationKind) web.HandlerFunc {
return err
}
- var user *models.User
+ var user *entity.User
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)
}
- user = &models.User{
+ user = &entity.User{
Name: result.Name,
Email: result.Email,
Tenant: c.Tenant(),
@@ -134,19 +134,19 @@ func VerifySignInKey(kind enum.EmailVerificationKind) web.HandlerFunc {
// CompleteSignInProfile handles the action to update user profile
func CompleteSignInProfile() web.HandlerFunc {
return func(c *web.Context) error {
- input := new(actions.CompleteProfile)
- if result := c.BindTo(input); !result.Ok {
+ action := new(actions.CompleteProfile)
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
- err := bus.Dispatch(c, &query.GetUserByEmail{Email: input.Model.Email})
+ err := bus.Dispatch(c, &query.GetUserByEmail{Email: action.Email})
if errors.Cause(err) != app.ErrNotFound {
return c.Ok(web.Map{})
}
- user := &models.User{
- Name: input.Model.Name,
- Email: input.Model.Email,
+ user := &entity.User{
+ Name: action.Name,
+ Email: action.Email,
Tenant: c.Tenant(),
Role: enum.RoleVisitor,
}
@@ -155,7 +155,7 @@ func CompleteSignInProfile() web.HandlerFunc {
return c.Failure(err)
}
- err = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: input.Model.Key})
+ err = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: action.Key})
if err != nil {
return c.Failure(err)
}
diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.go
index cdad37321..63588e933 100644
--- a/app/handlers/signin_test.go
+++ b/app/handlers/signin_test.go
@@ -11,8 +11,8 @@ import (
"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/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
@@ -78,7 +78,7 @@ func TestVerifySignInKeyHandler_UsedKey(t *testing.T) {
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{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
VerifiedAt: &now,
@@ -106,7 +106,7 @@ func TestVerifySignInKeyHandler_ExpiredKey(t *testing.T) {
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{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
ExpiresAt: now,
@@ -143,7 +143,7 @@ func TestVerifySignInKeyHandler_CorrectKey_ExistingUser(t *testing.T) {
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{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
ExpiresAt: expiresAt,
@@ -205,7 +205,7 @@ func TestVerifySignInKeyHandler_CorrectKey_NewUser(t *testing.T) {
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{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
ExpiresAt: expiresAt,
@@ -233,7 +233,7 @@ func TestVerifySignInKeyHandler_PrivateTenant_SignInRequest_NonInviteNewUser(t *
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{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
ExpiresAt: expiresAt,
@@ -269,7 +269,7 @@ func TestVerifySignInKeyHandler_PrivateTenant_SignInRequest_RegisteredUser(t *te
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{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
ExpiresAt: expiresAt,
@@ -280,7 +280,7 @@ func TestVerifySignInKeyHandler_PrivateTenant_SignInRequest_RegisteredUser(t *te
return app.ErrNotFound
})
- user := &models.User{
+ user := &entity.User{
Name: "Hot Pie",
Tenant: mock.DemoTenant,
@@ -318,7 +318,7 @@ func TestVerifySignInKeyHandler_PrivateTenant_InviteRequest_ExistingUser(t *test
server := mock.NewServer()
mock.DemoTenant.IsPrivate = true
- user := &models.User{
+ user := &entity.User{
Name: "Hot Pie",
Tenant: mock.DemoTenant,
@@ -328,7 +328,7 @@ func TestVerifySignInKeyHandler_PrivateTenant_InviteRequest_ExistingUser(t *test
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{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
ExpiresAt: expiresAt,
@@ -375,7 +375,7 @@ func TestVerifySignInKeyHandler_PrivateTenant_InviteRequest_NewUser(t *testing.T
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{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
ExpiresAt: expiresAt,
@@ -404,7 +404,7 @@ func TestVerifySignUpKeyHandler_PendingTenant(t *testing.T) {
server := mock.NewServer()
mock.DemoTenant.Status = enum.TenantPending
- var newUser *models.User
+ var newUser *entity.User
bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
newUser = c.User
return nil
@@ -420,7 +420,7 @@ func TestVerifySignUpKeyHandler_PendingTenant(t *testing.T) {
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{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
ExpiresAt: expiresAt,
@@ -483,7 +483,7 @@ func TestCompleteSignInProfileHandler_ExistingUser_CorrectKey(t *testing.T) {
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{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
ExpiresAt: expiresAt,
@@ -507,7 +507,7 @@ func TestCompleteSignInProfileHandler_CorrectKey(t *testing.T) {
server := mock.NewServer()
- var newUser *models.User
+ var newUser *entity.User
bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
newUser = c.User
return nil
@@ -521,7 +521,7 @@ func TestCompleteSignInProfileHandler_CorrectKey(t *testing.T) {
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{
+ q.Result = &entity.EmailVerification{
Key: q.Key,
Kind: q.Kind,
ExpiresAt: expiresAt,
@@ -594,7 +594,7 @@ func TestSignInPageHandler_PrivateTenant_UnauthenticatedUser(t *testing.T) {
Expect(code).Equals(http.StatusOK)
}
-func ExpectFiderAuthCookie(response *httptest.ResponseRecorder, expected *models.User) {
+func ExpectFiderAuthCookie(response *httptest.ResponseRecorder, expected *entity.User) {
cookies := response.Header()["Set-Cookie"]
if expected == nil {
for _, c := range cookies {
@@ -617,7 +617,7 @@ func ExpectFiderAuthCookie(response *httptest.ResponseRecorder, expected *models
}
}
-func ExpectFiderToken(token string, expected *models.User) {
+func ExpectFiderToken(token string, expected *entity.User) {
user, err := jwt.DecodeFiderClaims(token)
Expect(err).IsNil()
Expect(user.UserID).Equals(expected.ID)
diff --git a/app/handlers/signup.go b/app/handlers/signup.go
index 1ead12e96..9ca6d4212 100644
--- a/app/handlers/signup.go
+++ b/app/handlers/signup.go
@@ -3,6 +3,7 @@ package handlers
import (
"time"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
@@ -17,7 +18,6 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
- "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/pkg/validate"
@@ -47,12 +47,12 @@ func CreateTenant() web.HandlerFunc {
return c.NotFound()
}
- input := new(actions.CreateTenant)
- if result := c.BindTo(input); !result.Ok {
+ action := actions.NewCreateTenant()
+ if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
- socialSignUp := input.Model.Token != ""
+ socialSignUp := action.Token != ""
status := enum.TenantPending
if socialSignUp {
@@ -60,8 +60,8 @@ func CreateTenant() web.HandlerFunc {
}
createTenant := &cmd.CreateTenant{
- Name: input.Model.TenantName,
- Subdomain: input.Model.Subdomain,
+ Name: action.TenantName,
+ Subdomain: action.Subdomain,
Status: status,
}
err := bus.Dispatch(c, createTenant)
@@ -71,16 +71,19 @@ func CreateTenant() web.HandlerFunc {
c.SetTenant(createTenant.Result)
- user := &models.User{
+ user := &entity.User{
Tenant: createTenant.Result,
Role: enum.RoleAdministrator,
}
if socialSignUp {
- user.Name = input.Model.UserClaims.OAuthName
- user.Email = input.Model.UserClaims.OAuthEmail
- user.Providers = []*models.UserProvider{
- {UID: input.Model.UserClaims.OAuthID, Name: input.Model.UserClaims.OAuthProvider},
+ user.Name = action.UserClaims.OAuthName
+ user.Email = action.UserClaims.OAuthEmail
+ user.Providers = []*entity.UserProvider{
+ {
+ UID: action.UserClaims.OAuthID,
+ Name: action.UserClaims.OAuthProvider,
+ },
}
if err := bus.Dispatch(c, &cmd.RegisterUser{User: user}); err != nil {
@@ -94,19 +97,19 @@ func CreateTenant() web.HandlerFunc {
}
} else {
- user.Name = input.Model.Name
- user.Email = input.Model.Email
+ user.Name = action.Name
+ user.Email = action.Email
err := bus.Dispatch(c, &cmd.SaveVerificationKey{
- Key: input.Model.VerificationKey,
+ Key: action.VerificationKey,
Duration: 48 * time.Hour,
- Request: input.Model,
+ Request: action,
})
if err != nil {
return c.Failure(err)
}
- c.Enqueue(tasks.SendSignUpEmail(input.Model, web.TenantBaseURL(c, createTenant.Result)))
+ c.Enqueue(tasks.SendSignUpEmail(action, web.TenantBaseURL(c, createTenant.Result)))
}
return c.Ok(web.Map{})
diff --git a/app/handlers/signup_test.go b/app/handlers/signup_test.go
index 40f84b0f8..4f3666118 100644
--- a/app/handlers/signup_test.go
+++ b/app/handlers/signup_test.go
@@ -9,8 +9,8 @@ import (
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
@@ -62,7 +62,7 @@ func TestSignUpHandler_SingleTenant_WithTenants(t *testing.T) {
RegisterT(t)
bus.AddHandler(func(ctx context.Context, q *query.GetFirstTenant) error {
- q.Result = &models.Tenant{ID: 2, Name: "MyCompany"}
+ q.Result = &entity.Tenant{ID: 2, Name: "MyCompany"}
return nil
})
@@ -124,7 +124,7 @@ func TestCreateTenantHandler_EmptyInput(t *testing.T) {
func TestCreateTenantHandler_WithSocialAccount(t *testing.T) {
RegisterT(t)
- var newUser *models.User
+ var newUser *entity.User
bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
newUser = c.User
return nil
@@ -180,7 +180,7 @@ func TestCreateTenantHandler_WithSocialAccount(t *testing.T) {
func TestCreateTenantHandler_SingleHost_WithSocialAccount(t *testing.T) {
RegisterT(t)
- var newUser *models.User
+ var newUser *entity.User
bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
c.User.ID = 1
newUser = c.User
@@ -224,7 +224,7 @@ func TestCreateTenantHandler_SingleHost_WithSocialAccount(t *testing.T) {
Expect(newUser.Email).Equals("[email protected]")
Expect(newUser.Role).Equals(enum.RoleAdministrator)
- ExpectFiderAuthCookie(response, &models.User{
+ ExpectFiderAuthCookie(response, &entity.User{
ID: 1,
Name: "Jon Snow",
@@ -246,7 +246,7 @@ func TestCreateTenantHandler_WithEmailAndName(t *testing.T) {
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}
+ c.Result = &entity.Tenant{ID: 1, Name: c.Name, Subdomain: c.Subdomain, Status: c.Status}
return nil
})
diff --git a/app/middlewares/tenant_test.go b/app/middlewares/tenant_test.go
index 08213623b..701a4b482 100644
--- a/app/middlewares/tenant_test.go
+++ b/app/middlewares/tenant_test.go
@@ -8,7 +8,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/middlewares"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
@@ -233,7 +233,7 @@ func TestSingleTenant_WithTenants_ShouldSetFirstToContext(t *testing.T) {
RegisterT(t)
bus.AddHandler(func(ctx context.Context, q *query.GetFirstTenant) error {
- q.Result = &models.Tenant{Name: "MyCompany", Subdomain: "mycompany", Status: enum.TenantActive}
+ q.Result = &entity.Tenant{Name: "MyCompany", Subdomain: "mycompany", Status: enum.TenantActive}
return nil
})
@@ -257,7 +257,7 @@ func TestSingleTenant_HostMismatch(t *testing.T) {
env.Config.HostDomain = "yoursite.com"
bus.AddHandler(func(ctx context.Context, q *query.GetFirstTenant) error {
- q.Result = &models.Tenant{Name: "MyCompany", Status: enum.TenantActive}
+ q.Result = &entity.Tenant{Name: "MyCompany", Status: enum.TenantActive}
return nil
})
diff --git a/app/middlewares/user.go b/app/middlewares/user.go
index cd77164fa..a8a93f4a7 100644
--- a/app/middlewares/user.go
+++ b/app/middlewares/user.go
@@ -5,14 +5,13 @@ import (
"strconv"
"strings"
+ "github.com/getfider/fider/app/models/entity"
"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"
-
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/jwt"
@@ -26,7 +25,7 @@ func User() web.MiddlewareFunc {
return func(c *web.Context) error {
var (
token string
- user *models.User
+ user *entity.User
)
cookie, err := c.Request.Cookie(web.CookieAuthName)
diff --git a/app/middlewares/user_test.go b/app/middlewares/user_test.go
index b8219e303..c2847952f 100644
--- a/app/middlewares/user_test.go
+++ b/app/middlewares/user_test.go
@@ -10,7 +10,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/middlewares"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
@@ -339,7 +339,7 @@ func TestUser_Impersonation_Collaborator(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetUserByAPIKey) error {
if q.APIKey == "12345" {
- q.Result = &models.User{
+ q.Result = &entity.User{
Name: "The Collaborator",
Role: enum.RoleCollaborator,
Status: enum.UserActive,
diff --git a/app/models/cmd/attachment.go b/app/models/cmd/attachment.go
index 43c95cd7e..dbd55505c 100644
--- a/app/models/cmd/attachment.go
+++ b/app/models/cmd/attachment.go
@@ -1,19 +1,22 @@
package cmd
-import "github.com/getfider/fider/app/models"
+import (
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
+)
type SetAttachments struct {
- Post *models.Post
- Comment *models.Comment
- Attachments []*models.ImageUpload
+ Post *entity.Post
+ Comment *entity.Comment
+ Attachments []*dto.ImageUpload
}
type UploadImage struct {
- Image *models.ImageUpload
+ Image *dto.ImageUpload
Folder string
}
type UploadImages struct {
- Images []*models.ImageUpload
+ Images []*dto.ImageUpload
Folder string
}
diff --git a/app/models/cmd/comment.go b/app/models/cmd/comment.go
index f03763255..24e39e598 100644
--- a/app/models/cmd/comment.go
+++ b/app/models/cmd/comment.go
@@ -1,12 +1,14 @@
package cmd
-import "github.com/getfider/fider/app/models"
+import (
+ "github.com/getfider/fider/app/models/entity"
+)
type AddNewComment struct {
- Post *models.Post
+ Post *entity.Post
Content string
- Result *models.Comment
+ Result *entity.Comment
}
type UpdateComment struct {
diff --git a/app/models/cmd/notification.go b/app/models/cmd/notification.go
index 3abd37545..baf7cf3f3 100644
--- a/app/models/cmd/notification.go
+++ b/app/models/cmd/notification.go
@@ -1,6 +1,8 @@
package cmd
-import "github.com/getfider/fider/app/models"
+import (
+ "github.com/getfider/fider/app/models/entity"
+)
type MarkAllNotificationsAsRead struct{}
@@ -13,20 +15,20 @@ type MarkNotificationAsRead struct {
}
type AddNewNotification struct {
- User *models.User
+ User *entity.User
Title string
Link string
PostID int
- Result *models.Notification
+ Result *entity.Notification
}
type AddSubscriber struct {
- Post *models.Post
- User *models.User
+ Post *entity.Post
+ User *entity.User
}
type RemoveSubscriber struct {
- Post *models.Post
- User *models.User
+ Post *entity.Post
+ User *entity.User
}
diff --git a/app/models/cmd/oauth.go b/app/models/cmd/oauth.go
index 2dfd922a1..f80fa1e19 100644
--- a/app/models/cmd/oauth.go
+++ b/app/models/cmd/oauth.go
@@ -1,12 +1,24 @@
package cmd
import (
- "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/models/dto"
)
type SaveCustomOAuthConfig struct {
- Config *models.CreateEditOAuthConfig
+ ID int
+ Logo *dto.ImageUpload
+ Provider string
+ Status int
+ DisplayName string
+ ClientID string
+ ClientSecret string
+ AuthorizeURL string
+ TokenURL string
+ Scope string
+ ProfileURL string
+ JSONUserIDPath string
+ JSONUserNamePath string
+ JSONUserEmailPath string
}
type ParseOAuthRawProfile struct {
diff --git a/app/models/cmd/post.go b/app/models/cmd/post.go
index 2ae401b27..d3f024bf1 100644
--- a/app/models/cmd/post.go
+++ b/app/models/cmd/post.go
@@ -1,7 +1,7 @@
package cmd
import (
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
)
@@ -9,19 +9,19 @@ type AddNewPost struct {
Title string
Description string
- Result *models.Post
+ Result *entity.Post
}
type UpdatePost struct {
- Post *models.Post
+ Post *entity.Post
Title string
Description string
- Result *models.Post
+ Result *entity.Post
}
type SetPostResponse struct {
- Post *models.Post
+ Post *entity.Post
Text string
Status enum.PostStatus
}
diff --git a/app/models/cmd/tag.go b/app/models/cmd/tag.go
index be3ff2c2c..c6bea0a7c 100644
--- a/app/models/cmd/tag.go
+++ b/app/models/cmd/tag.go
@@ -1,13 +1,15 @@
package cmd
-import "github.com/getfider/fider/app/models"
+import (
+ "github.com/getfider/fider/app/models/entity"
+)
type AddNewTag struct {
Name string
Color string
IsPublic bool
- Result *models.Tag
+ Result *entity.Tag
}
type UpdateTag struct {
@@ -16,19 +18,19 @@ type UpdateTag struct {
Color string
IsPublic bool
- Result *models.Tag
+ Result *entity.Tag
}
type DeleteTag struct {
- Tag *models.Tag
+ Tag *entity.Tag
}
type AssignTag struct {
- Tag *models.Tag
- Post *models.Post
+ Tag *entity.Tag
+ Post *entity.Post
}
type UnassignTag struct {
- Tag *models.Tag
- Post *models.Post
+ Tag *entity.Tag
+ Post *entity.Post
}
diff --git a/app/models/cmd/tenant.go b/app/models/cmd/tenant.go
index a726ca506..e3d6fb7b4 100644
--- a/app/models/cmd/tenant.go
+++ b/app/models/cmd/tenant.go
@@ -3,7 +3,9 @@ package cmd
import (
"time"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
+ "github.com/getfider/fider/app/models/enum"
)
type CreateTenant struct {
@@ -11,19 +13,23 @@ type CreateTenant struct {
Subdomain string
Status int
- Result *models.Tenant
+ Result *entity.Tenant
}
type UpdateTenantPrivacySettings struct {
- Settings *models.UpdateTenantPrivacy
+ IsPrivate bool
}
type UpdateTenantSettings struct {
- Settings *models.UpdateTenantSettings
+ Logo *dto.ImageUpload
+ Title string
+ Invitation string
+ WelcomeMessage string
+ CNAME string
}
type UpdateTenantAdvancedSettings struct {
- Settings *models.UpdateTenantAdvancedSettings
+ CustomCSS string
}
type ActivateTenant struct {
@@ -33,7 +39,15 @@ type ActivateTenant struct {
type SaveVerificationKey struct {
Key string
Duration time.Duration
- Request models.NewEmailVerification
+ Request NewEmailVerification
+}
+
+//NewEmailVerification is used to define an email verification process
+type NewEmailVerification interface {
+ GetEmail() string
+ GetName() string
+ GetUser() *entity.User
+ GetKind() enum.EmailVerificationKind
}
type SetKeyAsVerified struct {
diff --git a/app/models/cmd/user.go b/app/models/cmd/user.go
index 3efc7ed3f..136c16e4e 100644
--- a/app/models/cmd/user.go
+++ b/app/models/cmd/user.go
@@ -1,7 +1,8 @@
package cmd
import (
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
)
@@ -35,7 +36,7 @@ type UpdateCurrentUserSettings struct {
}
type RegisterUser struct {
- User *models.User
+ User *entity.User
}
type RegisterUserProvider struct {
@@ -47,5 +48,5 @@ type RegisterUserProvider struct {
type UpdateCurrentUser struct {
Name string
AvatarType enum.AvatarType
- Avatar *models.ImageUpload
+ Avatar *dto.ImageUpload
}
diff --git a/app/models/cmd/vote.go b/app/models/cmd/vote.go
index 25b68176c..6d6d331a2 100644
--- a/app/models/cmd/vote.go
+++ b/app/models/cmd/vote.go
@@ -1,18 +1,20 @@
package cmd
-import "github.com/getfider/fider/app/models"
+import (
+ "github.com/getfider/fider/app/models/entity"
+)
type AddVote struct {
- Post *models.Post
- User *models.User
+ Post *entity.Post
+ User *entity.User
}
type RemoveVote struct {
- Post *models.Post
- User *models.User
+ Post *entity.Post
+ User *entity.User
}
type MarkPostAsDuplicate struct {
- Post *models.Post
- Original *models.Post
+ Post *entity.Post
+ Original *entity.Post
}
diff --git a/app/models/dto/upload.go b/app/models/dto/upload.go
new file mode 100644
index 000000000..e6251f59e
--- /dev/null
+++ b/app/models/dto/upload.go
@@ -0,0 +1,15 @@
+package dto
+
+//ImageUpload is the input model used to upload/remove an image
+type ImageUpload struct {
+ BlobKey string `json:"bkey"`
+ Upload *ImageUploadData `json:"upload"`
+ Remove bool `json:"remove"`
+}
+
+//ImageUploadData is the input model used to upload a new logo
+type ImageUploadData struct {
+ FileName string `json:"fileName"`
+ ContentType string `json:"contentType"`
+ Content []byte `json:"content"`
+}
diff --git a/app/models/entity/comment.go b/app/models/entity/comment.go
new file mode 100644
index 000000000..43be67fdd
--- /dev/null
+++ b/app/models/entity/comment.go
@@ -0,0 +1,14 @@
+package entity
+
+import "time"
+
+//Comment represents an user comment on an post
+type Comment struct {
+ ID int `json:"id"`
+ Content string `json:"content"`
+ CreatedAt time.Time `json:"createdAt"`
+ User *User `json:"user"`
+ Attachments []string `json:"attachments,omitempty"`
+ EditedAt *time.Time `json:"editedAt,omitempty"`
+ EditedBy *User `json:"editedBy,omitempty"`
+}
diff --git a/app/models/entity/email_verification.go b/app/models/entity/email_verification.go
new file mode 100644
index 000000000..639f6707b
--- /dev/null
+++ b/app/models/entity/email_verification.go
@@ -0,0 +1,25 @@
+package entity
+
+import (
+ "time"
+
+ "github.com/getfider/fider/app/models/enum"
+ "github.com/getfider/fider/app/pkg/rand"
+)
+
+//EmailVerification is the model used by email verification process
+type EmailVerification struct {
+ Email string
+ Name string
+ Key string
+ UserID int
+ Kind enum.EmailVerificationKind
+ CreatedAt time.Time
+ ExpiresAt time.Time
+ VerifiedAt *time.Time
+}
+
+// GenerateEmailVerificationKey returns a 64 chars key
+func GenerateEmailVerificationKey() string {
+ return rand.String(64)
+}
diff --git a/app/models/entity/notification.go b/app/models/entity/notification.go
new file mode 100644
index 000000000..385876920
--- /dev/null
+++ b/app/models/entity/notification.go
@@ -0,0 +1,12 @@
+package entity
+
+import "time"
+
+// Notification is the system generated notification entity
+type Notification struct {
+ ID int `json:"id" db:"id"`
+ Title string `json:"title" db:"title"`
+ Link string `json:"link" db:"link"`
+ Read bool `json:"read" db:"read"`
+ CreatedAt time.Time `json:"createdAt" db:"created_at"`
+}
diff --git a/app/models/entity/oauth.go b/app/models/entity/oauth.go
new file mode 100644
index 000000000..c731502d5
--- /dev/null
+++ b/app/models/entity/oauth.go
@@ -0,0 +1,45 @@
+package entity
+
+import "encoding/json"
+
+// OAuthConfig is the configuration of a custom OAuth provider
+type OAuthConfig struct {
+ ID int
+ Provider string
+ DisplayName string
+ LogoBlobKey string
+ Status int
+ ClientID string
+ ClientSecret string
+ AuthorizeURL string
+ TokenURL string
+ ProfileURL string
+ Scope string
+ JSONUserIDPath string
+ JSONUserNamePath string
+ JSONUserEmailPath string
+}
+
+// MarshalJSON returns the JSON encoding of OAuthConfig
+func (o OAuthConfig) MarshalJSON() ([]byte, error) {
+ secret := "..."
+ if len(o.ClientSecret) >= 10 {
+ secret = o.ClientSecret[0:3] + "..." + o.ClientSecret[len(o.ClientSecret)-3:]
+ }
+ return json.Marshal(map[string]interface{}{
+ "id": o.ID,
+ "provider": o.Provider,
+ "displayName": o.DisplayName,
+ "logoBlobKey": o.LogoBlobKey,
+ "status": o.Status,
+ "clientID": o.ClientID,
+ "clientSecret": secret,
+ "authorizeURL": o.AuthorizeURL,
+ "tokenURL": o.TokenURL,
+ "profileURL": o.ProfileURL,
+ "scope": o.Scope,
+ "jsonUserIDPath": o.JSONUserIDPath,
+ "jsonUserNamePath": o.JSONUserNamePath,
+ "jsonUserEmailPath": o.JSONUserEmailPath,
+ })
+}
diff --git a/app/models/entity/post.go b/app/models/entity/post.go
new file mode 100644
index 000000000..763004b47
--- /dev/null
+++ b/app/models/entity/post.go
@@ -0,0 +1,45 @@
+package entity
+
+import (
+ "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 enum.PostStatus `json:"status"`
+ Response *PostResponse `json:"response,omitempty"`
+ Tags []string `json:"tags"`
+}
+
+// CanBeVoted returns true if this post can have its vote changed
+func (i *Post) CanBeVoted() bool {
+ return i.Status != enum.PostCompleted && i.Status != enum.PostDeclined && i.Status != enum.PostDuplicate
+}
+
+//PostResponse is a staff response to a given post
+type PostResponse struct {
+ Text string `json:"text"`
+ RespondedAt time.Time `json:"respondedAt"`
+ User *User `json:"user"`
+ Original *OriginalPost `json:"original"`
+}
+
+//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 enum.PostStatus `json:"status"`
+}
diff --git a/app/models/entity/tag.go b/app/models/entity/tag.go
new file mode 100644
index 000000000..3e61eb59e
--- /dev/null
+++ b/app/models/entity/tag.go
@@ -0,0 +1,10 @@
+package entity
+
+//Tag represents a simple tag
+type Tag struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Slug string `json:"slug"`
+ Color string `json:"color"`
+ IsPublic bool `json:"isPublic"`
+}
diff --git a/app/models/entity/tenant.go b/app/models/entity/tenant.go
new file mode 100644
index 000000000..a10843c6b
--- /dev/null
+++ b/app/models/entity/tenant.go
@@ -0,0 +1,15 @@
+package entity
+
+//Tenant represents a tenant
+type Tenant struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Subdomain string `json:"subdomain"`
+ Invitation string `json:"invitation"`
+ WelcomeMessage string `json:"welcomeMessage"`
+ CNAME string `json:"cname"`
+ Status int `json:"status"`
+ IsPrivate bool `json:"isPrivate"`
+ LogoBlobKey string `json:"logoBlobKey"`
+ CustomCSS string `json:"-"`
+}
diff --git a/app/models/entity/user.go b/app/models/entity/user.go
new file mode 100644
index 000000000..bcf37e02b
--- /dev/null
+++ b/app/models/entity/user.go
@@ -0,0 +1,43 @@
+package entity
+
+import "github.com/getfider/fider/app/models/enum"
+
+//User represents an user inside our application
+type User struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Tenant *Tenant `json:"-"`
+ Email string `json:"-"`
+ Role enum.Role `json:"role"`
+ Providers []*UserProvider `json:"-"`
+ AvatarBlobKey string `json:"-"`
+ AvatarType enum.AvatarType `json:"-"`
+ AvatarURL string `json:"avatarURL,omitempty"`
+ Status enum.UserStatus `json:"status"`
+}
+
+//HasProvider returns true if current user has registered with given provider
+func (u *User) HasProvider(provider string) bool {
+ for _, p := range u.Providers {
+ if p.Name == provider {
+ return true
+ }
+ }
+ return false
+}
+
+// IsCollaborator returns true if user has special permissions
+func (u *User) IsCollaborator() bool {
+ return u.Role == enum.RoleCollaborator || u.Role == enum.RoleAdministrator
+}
+
+// IsAdministrator returns true if user is administrator
+func (u *User) IsAdministrator() bool {
+ return u.Role == enum.RoleAdministrator
+}
+
+//UserProvider represents the relationship between an User and an Authentication provide
+type UserProvider struct {
+ Name string
+ UID string
+}
diff --git a/app/models/entity/vote.go b/app/models/entity/vote.go
new file mode 100644
index 000000000..4f958351a
--- /dev/null
+++ b/app/models/entity/vote.go
@@ -0,0 +1,19 @@
+package entity
+
+import (
+ "time"
+)
+
+//VoteUser represents a user that voted on a post
+type VoteUser struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email,omitempty"`
+ AvatarURL string `json:"avatarURL,omitempty"`
+}
+
+//Vote represents a vote given by a user on a post
+type Vote struct {
+ User *VoteUser `json:"user"`
+ CreatedAt time.Time `json:"createdAt"`
+}
diff --git a/app/models/feedback.go b/app/models/feedback.go
deleted file mode 100644
index 4ba993b6e..000000000
--- a/app/models/feedback.go
+++ /dev/null
@@ -1,148 +0,0 @@
-package models
-
-import (
- "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 enum.PostStatus `json:"status"`
- Response *PostResponse `json:"response,omitempty"`
- Tags []string `json:"tags"`
-}
-
-//VoteUser represents a user that voted on a post
-type VoteUser struct {
- ID int `json:"id"`
- Name string `json:"name"`
- Email string `json:"email,omitempty"`
- AvatarURL string `json:"avatarURL,omitempty"`
-}
-
-//Vote represents a vote given by a user on a post
-type Vote struct {
- User *VoteUser `json:"user"`
- CreatedAt time.Time `json:"createdAt"`
-}
-
-// CanBeVoted returns true if this post can have its vote changed
-func (i *Post) CanBeVoted() bool {
- return i.Status != enum.PostCompleted && i.Status != enum.PostDeclined && i.Status != enum.PostDuplicate
-}
-
-// NewPost represents a new post
-type NewPost struct {
- Title string `json:"title"`
- Description string `json:"description"`
- Attachments []*ImageUpload `json:"attachments"`
-}
-
-// UpdatePost represents a request to edit an existing post
-type UpdatePost struct {
- Number int `route:"number"`
- Title string `json:"title"`
- Description string `json:"description"`
- Attachments []*ImageUpload `json:"attachments"`
-}
-
-// DeletePost represents a request to delete an existing post
-type DeletePost struct {
- Number int `route:"number"`
- Text string `json:"text"`
-}
-
-// NewComment represents a new comment
-type NewComment struct {
- Number int `route:"number"`
- Content string `json:"content"`
- Attachments []*ImageUpload `json:"attachments"`
-}
-
-// EditComment represents a request to edit existing comment
-type EditComment struct {
- PostNumber int `route:"number"`
- ID int `route:"id"`
- Content string `json:"content"`
- Attachments []*ImageUpload `json:"attachments"`
-}
-
-// DeleteComment represents a request to delete an existing comment
-type DeleteComment struct {
- PostNumber int `route:"number"`
- CommentID int `route:"id"`
-}
-
-// SetResponse represents the action to update an post response
-type SetResponse struct {
- 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
-type PostResponse struct {
- Text string `json:"text"`
- RespondedAt time.Time `json:"respondedAt"`
- User *User `json:"user"`
- Original *OriginalPost `json:"original"`
-}
-
-//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 enum.PostStatus `json:"status"`
-}
-
-//Comment represents an user comment on an post
-type Comment struct {
- ID int `json:"id"`
- Content string `json:"content"`
- CreatedAt time.Time `json:"createdAt"`
- User *User `json:"user"`
- Attachments []string `json:"attachments,omitempty"`
- EditedAt *time.Time `json:"editedAt,omitempty"`
- EditedBy *User `json:"editedBy,omitempty"`
-}
-
-//Tag represents a simple tag
-type Tag struct {
- ID int `json:"id"`
- Name string `json:"name"`
- Slug string `json:"slug"`
- Color string `json:"color"`
- IsPublic bool `json:"isPublic"`
-}
-
-//CreateEditTag is used to create a new tag or edit existing
-type CreateEditTag struct {
- Slug string `route:"slug"`
- Name string `json:"name"`
- Color string `json:"color" format:"upper"`
- IsPublic bool `json:"isPublic"`
-}
-
-// DeleteTag is used to delete an existing tag
-type DeleteTag struct {
- Slug string `route:"slug"`
-}
-
-// AssignUnassignTag is used to assign or remove a tag to/from an post
-type AssignUnassignTag struct {
- Slug string `route:"slug"`
- Number int `route:"number"`
-}
diff --git a/app/models/identity.go b/app/models/identity.go
deleted file mode 100644
index a8ae48f09..000000000
--- a/app/models/identity.go
+++ /dev/null
@@ -1,274 +0,0 @@
-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"
-)
-
-//Tenant represents a tenant
-type Tenant struct {
- ID int `json:"id"`
- Name string `json:"name"`
- Subdomain string `json:"subdomain"`
- Invitation string `json:"invitation"`
- WelcomeMessage string `json:"welcomeMessage"`
- CNAME string `json:"cname"`
- Status int `json:"status"`
- IsPrivate bool `json:"isPrivate"`
- LogoBlobKey string `json:"logoBlobKey"`
- CustomCSS string `json:"-"`
-}
-
-//Upload represents a file that has been uploaded to Fider
-type Upload struct {
- ContentType string `db:"content_type"`
- Size int `db:"size"`
- Content []byte `db:"file"`
-}
-
-//User represents an user inside our application
-type User struct {
- ID int `json:"id"`
- Name string `json:"name"`
- Tenant *Tenant `json:"-"`
- Email string `json:"-"`
- Role enum.Role `json:"role"`
- Providers []*UserProvider `json:"-"`
- AvatarBlobKey string `json:"-"`
- AvatarType enum.AvatarType `json:"-"`
- AvatarURL string `json:"avatarURL,omitempty"`
- Status enum.UserStatus `json:"status"`
-}
-
-//HasProvider returns true if current user has registered with given provider
-func (u *User) HasProvider(provider string) bool {
- for _, p := range u.Providers {
- if p.Name == provider {
- return true
- }
- }
- return false
-}
-
-// IsCollaborator returns true if user has special permissions
-func (u *User) IsCollaborator() bool {
- return u.Role == enum.RoleCollaborator || u.Role == enum.RoleAdministrator
-}
-
-// IsAdministrator returns true if user is administrator
-func (u *User) IsAdministrator() bool {
- return u.Role == enum.RoleAdministrator
-}
-
-//UserProvider represents the relationship between an User and an Authentication provide
-type UserProvider struct {
- Name string
- UID string
-}
-
-//CreateTenant is the input model used to create a tenant
-type CreateTenant struct {
- Token string `json:"token"`
- Name string `json:"name"`
- Email string `json:"email" format:"lower"`
- VerificationKey string
- TenantName string `json:"tenantName"`
- LegalAgreement bool `json:"legalAgreement"`
- Subdomain string `json:"subdomain" format:"lower"`
- UserClaims *jwt.OAuthClaims
-}
-
-//GetEmail returns the email being verified
-func (e *CreateTenant) GetEmail() string {
- return e.Email
-}
-
-//GetName returns the name of the email owner
-func (e *CreateTenant) GetName() string {
- return e.Name
-}
-
-//GetUser returns the current user performing this action
-func (e *CreateTenant) GetUser() *User {
- return nil
-}
-
-//GetKind returns EmailVerificationKindSignUp
-func (e *CreateTenant) GetKind() enum.EmailVerificationKind {
- return enum.EmailVerificationKindSignUp
-}
-
-//UpdateTenantSettings is the input model used to update tenant general settings
-type UpdateTenantSettings struct {
- Logo *ImageUpload `json:"logo"`
- Title string `json:"title"`
- Invitation string `json:"invitation"`
- WelcomeMessage string `json:"welcomeMessage"`
- CNAME string `json:"cname" format:"lower"`
-}
-
-//UpdateTenantAdvancedSettings is the input model used to update tenant advanced settings
-type UpdateTenantAdvancedSettings struct {
- CustomCSS string `json:"customCSS"`
-}
-
-//ImageUpload is the input model used to upload/remove an image
-type ImageUpload struct {
- BlobKey string `json:"bkey"`
- Upload *ImageUploadData `json:"upload"`
- Remove bool `json:"remove"`
-}
-
-//ImageUploadData is the input model used to upload a new logo
-type ImageUploadData struct {
- FileName string `json:"fileName"`
- ContentType string `json:"contentType"`
- Content []byte `json:"content"`
-}
-
-//UpdateTenantPrivacy is the input model used to update tenant privacy settings
-type UpdateTenantPrivacy struct {
- IsPrivate bool `json:"isPrivate"`
-}
-
-//SignInByEmail is the input model when user request to sign in by email
-type SignInByEmail struct {
- Email string `json:"email" format:"lower"`
- VerificationKey string
-}
-
-//GetEmail returns the email being verified
-func (e *SignInByEmail) GetEmail() string {
- return e.Email
-}
-
-//GetName returns empty for this kind of process
-func (e *SignInByEmail) GetName() string {
- return ""
-}
-
-//GetUser returns the current user performing this action
-func (e *SignInByEmail) GetUser() *User {
- return nil
-}
-
-//GetKind returns EmailVerificationKindSignIn
-func (e *SignInByEmail) GetKind() enum.EmailVerificationKind {
- return enum.EmailVerificationKindSignIn
-}
-
-//ChangeUserEmail is the input model used to change current user's email
-type ChangeUserEmail struct {
- Email string `json:"email" format:"lower"`
- VerificationKey string
- Requestor *User
-}
-
-//GetEmail returns the email being verified
-func (e *ChangeUserEmail) GetEmail() string {
- return e.Email
-}
-
-//GetName returns empty for this kind of process
-func (e *ChangeUserEmail) GetName() string {
- return ""
-}
-
-//GetUser returns the current user performing this action
-func (e *ChangeUserEmail) GetUser() *User {
- return e.Requestor
-}
-
-//GetKind returns EmailVerificationKindSignIn
-func (e *ChangeUserEmail) GetKind() enum.EmailVerificationKind {
- return enum.EmailVerificationKindChangeEmail
-}
-
-//UserInvitation is the model used to register an invite sent to an user
-type UserInvitation struct {
- Email string
- VerificationKey string
-}
-
-//GetEmail returns the invited user's email
-func (e *UserInvitation) GetEmail() string {
- return e.Email
-}
-
-//GetName returns empty for this kind of process
-func (e *UserInvitation) GetName() string {
- return ""
-}
-
-//GetUser returns the current user performing this action
-func (e *UserInvitation) GetUser() *User {
- return nil
-}
-
-//GetKind returns EmailVerificationKindUserInvitation
-func (e *UserInvitation) GetKind() enum.EmailVerificationKind {
- return enum.EmailVerificationKindUserInvitation
-}
-
-//NewEmailVerification is used to register a new email verification process
-type NewEmailVerification interface {
- GetEmail() string
- GetName() string
- GetUser() *User
- GetKind() enum.EmailVerificationKind
-}
-
-//EmailVerification is the model used by email verification process
-type EmailVerification struct {
- Email string
- Name string
- Key string
- UserID int
- Kind enum.EmailVerificationKind
- CreatedAt time.Time
- ExpiresAt time.Time
- VerifiedAt *time.Time
-}
-
-// CompleteProfile is the model used to complete user profile during email sign in
-type CompleteProfile struct {
- Key string `json:"key"`
- Name string `json:"name"`
- Email string
-}
-
-// UpdateUserSettings is the model used to update user's settings
-type UpdateUserSettings struct {
- Name string `json:"name"`
- AvatarType enum.AvatarType `json:"avatarType"`
- Avatar *ImageUpload `json:"avatar"`
- Settings map[string]string `json:"settings"`
-}
-
-// CreateUser is the input model to create a new user
-type CreateUser struct {
- Name string `json:"name"`
- Email string `json:"email"`
- Reference string `json:"reference"`
-}
-
-// ChangeUserRole is the input model change role of an user
-type ChangeUserRole struct {
- Role enum.Role `route:"role"`
- UserID int `json:"userID"`
-}
-
-// InviteUsers is used to invite new users into Fider
-type InviteUsers struct {
- Subject string `json:"subject"`
- Message string `json:"message"`
- Recipients []string `json:"recipients" format:"lower"`
-}
-
-// GenerateSecretKey returns a 64 chars key
-func GenerateSecretKey() string {
- return rand.String(64)
-}
diff --git a/app/models/infra.go b/app/models/infra.go
deleted file mode 100644
index 040bd41f4..000000000
--- a/app/models/infra.go
+++ /dev/null
@@ -1,100 +0,0 @@
-package models
-
-import (
- "encoding/json"
- "time"
-)
-
-// SystemSettings is the system-wide settings
-type SystemSettings struct {
- Mode string
- BuildTime string
- Version string
- Environment string
- GoogleAnalytics string
- Compiler string
- Domain string
- HasLegal bool
-}
-
-// Notification is the system generated notification entity
-type Notification struct {
- ID int `json:"id" db:"id"`
- Title string `json:"title" db:"title"`
- Link string `json:"link" db:"link"`
- Read bool `json:"read" db:"read"`
- CreatedAt time.Time `json:"createdAt" db:"created_at"`
-}
-
-// CreateEditOAuthConfig is used to create/edit an OAuth Configuration
-type CreateEditOAuthConfig struct {
- ID int
- Logo *ImageUpload `json:"logo"`
- Provider string `json:"provider"`
- Status int `json:"status"`
- DisplayName string `json:"displayName"`
- ClientID string `json:"clientID"`
- ClientSecret string `json:"clientSecret"`
- AuthorizeURL string `json:"authorizeURL" format:"lower"`
- TokenURL string `json:"tokenURL" format:"lower"`
- Scope string `json:"scope"`
- ProfileURL string `json:"profileURL" format:"lower"`
- JSONUserIDPath string `json:"jsonUserIDPath"`
- JSONUserNamePath string `json:"jsonUserNamePath"`
- JSONUserEmailPath string `json:"jsonUserEmailPath"`
-}
-
-// OAuthConfig is the configuration of a custom OAuth provider
-type OAuthConfig struct {
- ID int
- Provider string
- DisplayName string
- LogoBlobKey string
- Status int
- ClientID string
- ClientSecret string
- AuthorizeURL string
- TokenURL string
- ProfileURL string
- Scope string
- JSONUserIDPath string
- JSONUserNamePath string
- JSONUserEmailPath string
-}
-
-// MarshalJSON returns the JSON encoding of OAuthConfig
-func (o OAuthConfig) MarshalJSON() ([]byte, error) {
- secret := "..."
- if len(o.ClientSecret) >= 10 {
- secret = o.ClientSecret[0:3] + "..." + o.ClientSecret[len(o.ClientSecret)-3:]
- }
- return json.Marshal(map[string]interface{}{
- "id": o.ID,
- "provider": o.Provider,
- "displayName": o.DisplayName,
- "logoBlobKey": o.LogoBlobKey,
- "status": o.Status,
- "clientID": o.ClientID,
- "clientSecret": secret,
- "authorizeURL": o.AuthorizeURL,
- "tokenURL": o.TokenURL,
- "profileURL": o.ProfileURL,
- "scope": o.Scope,
- "jsonUserIDPath": o.JSONUserIDPath,
- "jsonUserNamePath": o.JSONUserNamePath,
- "jsonUserEmailPath": o.JSONUserEmailPath,
- })
-}
-
-// APIAuthorize is used during API Authorize process
-type APIAuthorize struct {
- APIKey string `json:"apiKey"`
-}
-
-// Event is used for tracking client audit events and actions
-type Event struct {
- ID int `json:"id"`
- ClientIP string `json:"clientIP"`
- Name string `json:"name"`
- CreatedAt time.Time `json:"createdAt"`
-}
diff --git a/app/models/query/attachment.go b/app/models/query/attachment.go
index 53749a69f..2519dc852 100644
--- a/app/models/query/attachment.go
+++ b/app/models/query/attachment.go
@@ -1,10 +1,12 @@
package query
-import "github.com/getfider/fider/app/models"
+import (
+ "github.com/getfider/fider/app/models/entity"
+)
type GetAttachments struct {
- Post *models.Post
- Comment *models.Comment
+ Post *entity.Post
+ Comment *entity.Comment
Result []string
}
diff --git a/app/models/query/comment.go b/app/models/query/comment.go
index 86c02b851..7ae389b0d 100644
--- a/app/models/query/comment.go
+++ b/app/models/query/comment.go
@@ -1,15 +1,17 @@
package query
-import "github.com/getfider/fider/app/models"
+import (
+ "github.com/getfider/fider/app/models/entity"
+)
type GetCommentByID struct {
CommentID int
- Result *models.Comment
+ Result *entity.Comment
}
type GetCommentsByPost struct {
- Post *models.Post
+ Post *entity.Post
- Result []*models.Comment
+ Result []*entity.Comment
}
diff --git a/app/models/query/notification.go b/app/models/query/notification.go
index 3cd2f62b3..eac7410dc 100644
--- a/app/models/query/notification.go
+++ b/app/models/query/notification.go
@@ -1,7 +1,7 @@
package query
import (
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
)
@@ -11,11 +11,11 @@ type CountUnreadNotifications struct {
type GetNotificationByID struct {
ID int
- Result *models.Notification
+ Result *entity.Notification
}
type GetActiveNotifications struct {
- Result []*models.Notification
+ Result []*entity.Notification
}
type GetActiveSubscribers struct {
@@ -23,5 +23,5 @@ type GetActiveSubscribers struct {
Channel enum.NotificationChannel
Event enum.NotificationEvent
- Result []*models.User
+ Result []*entity.User
}
diff --git a/app/models/query/oauth.go b/app/models/query/oauth.go
index c81c80220..892bd6af6 100644
--- a/app/models/query/oauth.go
+++ b/app/models/query/oauth.go
@@ -1,18 +1,18 @@
package query
import (
- "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
)
type GetCustomOAuthConfigByProvider struct {
Provider string
- Result *models.OAuthConfig
+ Result *entity.OAuthConfig
}
type ListCustomOAuthConfig struct {
- Result []*models.OAuthConfig
+ Result []*entity.OAuthConfig
}
type GetOAuthAuthorizationURL struct {
diff --git a/app/models/query/post.go b/app/models/query/post.go
index 5d0f13233..7210bd9c5 100644
--- a/app/models/query/post.go
+++ b/app/models/query/post.go
@@ -1,7 +1,7 @@
package query
import (
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
)
@@ -18,19 +18,19 @@ type CountPostPerStatus struct {
type GetPostByID struct {
PostID int
- Result *models.Post
+ Result *entity.Post
}
type GetPostBySlug struct {
Slug string
- Result *models.Post
+ Result *entity.Post
}
type GetPostByNumber struct {
Number int
- Result *models.Post
+ Result *entity.Post
}
type SearchPosts struct {
@@ -39,9 +39,9 @@ type SearchPosts struct {
Limit string
Tags []string
- Result []*models.Post
+ Result []*entity.Post
}
type GetAllPosts struct {
- Result []*models.Post
+ Result []*entity.Post
}
diff --git a/app/models/query/tag.go b/app/models/query/tag.go
index 6fb147737..85b062ca3 100644
--- a/app/models/query/tag.go
+++ b/app/models/query/tag.go
@@ -1,19 +1,21 @@
package query
-import "github.com/getfider/fider/app/models"
+import (
+ "github.com/getfider/fider/app/models/entity"
+)
type GetTagBySlug struct {
Slug string
- Result *models.Tag
+ Result *entity.Tag
}
type GetAssignedTags struct {
- Post *models.Post
+ Post *entity.Post
- Result []*models.Tag
+ Result []*entity.Tag
}
type GetAllTags struct {
- Result []*models.Tag
+ Result []*entity.Tag
}
diff --git a/app/models/query/tenant.go b/app/models/query/tenant.go
index 416752d36..b7e501bb0 100644
--- a/app/models/query/tenant.go
+++ b/app/models/query/tenant.go
@@ -1,7 +1,7 @@
package query
import (
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
)
@@ -21,15 +21,15 @@ type GetVerificationByKey struct {
Kind enum.EmailVerificationKind
Key string
- Result *models.EmailVerification
+ Result *entity.EmailVerification
}
type GetFirstTenant struct {
- Result *models.Tenant
+ Result *entity.Tenant
}
type GetTenantByDomain struct {
Domain string
- Result *models.Tenant
+ Result *entity.Tenant
}
diff --git a/app/models/query/user.go b/app/models/query/user.go
index b44111b72..c44304bba 100644
--- a/app/models/query/user.go
+++ b/app/models/query/user.go
@@ -1,6 +1,6 @@
package query
-import "github.com/getfider/fider/app/models"
+import "github.com/getfider/fider/app/models/entity"
type CountUsers struct {
Result int
@@ -15,7 +15,7 @@ type UserSubscribedTo struct {
type GetUserByAPIKey struct {
APIKey string
- Result *models.User
+ Result *entity.User
}
type GetCurrentUserSettings struct {
@@ -25,22 +25,22 @@ type GetCurrentUserSettings struct {
type GetUserByID struct {
UserID int
- Result *models.User
+ Result *entity.User
}
type GetUserByEmail struct {
Email string
- Result *models.User
+ Result *entity.User
}
type GetUserByProvider struct {
Provider string
UID string
- Result *models.User
+ Result *entity.User
}
type GetAllUsers struct {
- Result []*models.User
+ Result []*entity.User
}
diff --git a/app/models/query/vote.go b/app/models/query/vote.go
index 291748c6e..d10dbe89d 100644
--- a/app/models/query/vote.go
+++ b/app/models/query/vote.go
@@ -1,11 +1,11 @@
package query
-import "github.com/getfider/fider/app/models"
+import "github.com/getfider/fider/app/models/entity"
type ListPostVotes struct {
PostID int
Limit int
IncludeEmail bool
- Result []*models.Vote
+ Result []*entity.Vote
}
diff --git a/app/pkg/backup/export.go b/app/pkg/backup/export.go
index b7b306de7..58dd995a4 100644
--- a/app/pkg/backup/export.go
+++ b/app/pkg/backup/export.go
@@ -8,13 +8,13 @@ import (
"strconv"
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/pkg/dbx"
)
func exportTable(ctx context.Context, tableName string) ([]byte, error) {
trx := ctx.Value(app.TransactionCtxKey).(*dbx.Trx)
- tenant, _ := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ tenant, _ := ctx.Value(app.TenantCtxKey).(*entity.Tenant)
columnName := "tenant_id"
if tableName == "tenants" {
columnName = "id"
diff --git a/app/pkg/csv/csv.go b/app/pkg/csv/csv.go
index 7afbbb89b..dd98d2b45 100644
--- a/app/pkg/csv/csv.go
+++ b/app/pkg/csv/csv.go
@@ -7,11 +7,11 @@ import (
"strings"
"time"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
)
//FromPosts return a byte array of CSV file containing all posts
-func FromPosts(posts []*models.Post) ([]byte, error) {
+func FromPosts(posts []*entity.Post) ([]byte, error) {
buffer := &bytes.Buffer{}
writer := gocsv.NewWriter(buffer)
diff --git a/app/pkg/csv/csv_test.go b/app/pkg/csv/csv_test.go
index 503b2ebc3..fbbc1b80d 100644
--- a/app/pkg/csv/csv_test.go
+++ b/app/pkg/csv/csv_test.go
@@ -5,7 +5,7 @@ import (
"testing"
"time"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/csv"
@@ -14,7 +14,7 @@ import (
func TestExportPostsToCSV_Empty(t *testing.T) {
RegisterT(t)
- posts := []*models.Post{}
+ posts := []*entity.Post{}
expected, err := ioutil.ReadFile("./testdata/empty.csv")
Expect(err).IsNil()
actual, err := csv.FromPosts(posts)
@@ -25,7 +25,7 @@ func TestExportPostsToCSV_Empty(t *testing.T) {
func TestExportPostsToCSV_OnePost(t *testing.T) {
RegisterT(t)
- posts := []*models.Post{
+ posts := []*entity.Post{
declinedPost,
}
@@ -39,7 +39,7 @@ func TestExportPostsToCSV_OnePost(t *testing.T) {
func TestExportPostsToCSV_MorePosts(t *testing.T) {
RegisterT(t)
- posts := []*models.Post{
+ posts := []*entity.Post{
declinedPost,
openPost,
duplicatePost,
@@ -52,33 +52,33 @@ func TestExportPostsToCSV_MorePosts(t *testing.T) {
Expect(actual).Equals(expected)
}
-var declinedPost = &models.Post{
+var declinedPost = &entity.Post{
Number: 10,
Title: "Go is fast",
Description: "Very tiny description",
CreatedAt: time.Date(2018, 3, 23, 19, 33, 22, 0, time.UTC),
- User: &models.User{
+ User: &entity.User{
Name: "Faceless",
},
VotesCount: 4,
CommentsCount: 2,
Status: enum.PostDeclined,
- Response: &models.PostResponse{
+ Response: &entity.PostResponse{
Text: "Nothing we need to do",
RespondedAt: time.Date(2018, 4, 4, 19, 48, 10, 0, time.UTC),
- User: &models.User{
+ User: &entity.User{
Name: "John Snow",
},
},
Tags: []string{"easy", "ignored"},
}
-var openPost = &models.Post{
+var openPost = &entity.Post{
Number: 15,
Title: "Go is great",
Description: "",
CreatedAt: time.Date(2018, 2, 21, 15, 51, 35, 0, time.UTC),
- User: &models.User{
+ User: &entity.User{
Name: "Someone else",
},
VotesCount: 4,
@@ -86,24 +86,24 @@ var openPost = &models.Post{
Status: enum.PostOpen,
}
-var duplicatePost = &models.Post{
+var duplicatePost = &entity.Post{
Number: 20,
Title: "Go is easy",
Description: "",
CreatedAt: time.Date(2018, 1, 12, 1, 46, 59, 0, time.UTC),
- User: &models.User{
+ User: &entity.User{
Name: "Faceless",
},
VotesCount: 4,
CommentsCount: 2,
Status: enum.PostDuplicate,
- Response: &models.PostResponse{
+ Response: &entity.PostResponse{
Text: "This has already been suggested",
RespondedAt: time.Date(2018, 3, 17, 10, 15, 42, 0, time.UTC),
- User: &models.User{
+ User: &entity.User{
Name: "Arya Stark",
},
- Original: &models.OriginalPost{
+ Original: &entity.OriginalPost{
Number: 99,
Title: "Go is very easy",
},
diff --git a/app/pkg/env/env.go b/app/pkg/env/env.go
index d25be8d51..353955912 100644
--- a/app/pkg/env/env.go
+++ b/app/pkg/env/env.go
@@ -13,6 +13,20 @@ import (
"github.com/joeshaw/envdecode"
)
+var (
+ // these values are replaced during CI build
+ buildnumber = ""
+ version = "0.18.1"
+)
+
+func Version() string {
+ if buildnumber == "" {
+ return version
+ }
+
+ return fmt.Sprintf("%s-%s", version, buildnumber)
+}
+
type config struct {
Environment string `env:"GO_ENV,default=production"`
SignUpDisabled bool `env:"SIGNUP_DISABLED,default=false"`
@@ -62,11 +76,11 @@ type config struct {
Region string `env:"EMAIL_MAILGUN_REGION,default=US"`
}
SMTP struct {
- Host string `env:"EMAIL_SMTP_HOST"`
- Port string `env:"EMAIL_SMTP_PORT"`
- Username string `env:"EMAIL_SMTP_USERNAME"`
- Password string `env:"EMAIL_SMTP_PASSWORD"`
- EnableStartTLS bool `env:"EMAIL_SMTP_ENABLE_STARTTLS,default=true"`
+ Host string `env:"EMAIL_SMTP_HOST"`
+ Port string `env:"EMAIL_SMTP_PORT"`
+ Username string `env:"EMAIL_SMTP_USERNAME"`
+ Password string `env:"EMAIL_SMTP_PASSWORD"`
+ EnableStartTLS bool `env:"EMAIL_SMTP_ENABLE_STARTTLS,default=true"`
}
}
BlobStorage struct {
diff --git a/app/pkg/mock/server.go b/app/pkg/mock/server.go
index ccf0312a5..1af05a68d 100644
--- a/app/pkg/mock/server.go
+++ b/app/pkg/mock/server.go
@@ -8,7 +8,7 @@ import (
"net/http/httptest"
"net/url"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/jsonq"
@@ -28,8 +28,7 @@ func createServer() *Server {
return nil
})
- settings := &models.SystemSettings{}
- engine := web.New(settings)
+ engine := web.New()
request, _ := http.NewRequest("GET", "/", nil)
recorder := httptest.NewRecorder()
@@ -55,13 +54,13 @@ func (s *Server) Use(middleware web.MiddlewareFunc) *Server {
}
// OnTenant set current context tenant
-func (s *Server) OnTenant(tenant *models.Tenant) *Server {
+func (s *Server) OnTenant(tenant *entity.Tenant) *Server {
s.context.SetTenant(tenant)
return s
}
// AsUser set current context user
-func (s *Server) AsUser(user *models.User) *Server {
+func (s *Server) AsUser(user *entity.User) *Server {
s.context.SetUser(user)
return s
}
diff --git a/app/pkg/mock/setup.go b/app/pkg/mock/setup.go
index c18f65d0b..092fbeb9d 100644
--- a/app/pkg/mock/setup.go
+++ b/app/pkg/mock/setup.go
@@ -2,22 +2,22 @@ package mock
import (
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/pkg/env"
)
// DemoTenant is a mocked tenant
-var DemoTenant *models.Tenant
+var DemoTenant *entity.Tenant
// AvengersTenant is a mocked tenant
-var AvengersTenant *models.Tenant
+var AvengersTenant *entity.Tenant
// JonSnow is a mocked user
-var JonSnow *models.User
+var JonSnow *entity.User
// AryaStark is a mocked user
-var AryaStark *models.User
+var AryaStark *entity.User
// NewSingleTenantServer creates a new multitenant test server
func NewSingleTenantServer() *Server {
@@ -42,13 +42,13 @@ func NewWorker() *Worker {
}
func seed() {
- DemoTenant = &models.Tenant{
+ DemoTenant = &entity.Tenant{
ID: 1,
Name: "Demonstration",
Subdomain: "demo",
Status: enum.TenantActive,
}
- AvengersTenant = &models.Tenant{
+ AvengersTenant = &entity.Tenant{
ID: 2,
Name: "Avengers",
Subdomain: "avengers",
@@ -56,19 +56,19 @@ func seed() {
CNAME: "feedback.theavengers.com",
}
- JonSnow = &models.User{
+ JonSnow = &entity.User{
ID: 1,
Name: "Jon Snow",
Tenant: DemoTenant,
Status: enum.UserActive,
Role: enum.RoleAdministrator,
- Providers: []*models.UserProvider{
+ Providers: []*entity.UserProvider{
{UID: "FB1234", Name: app.FacebookProvider},
},
}
- AryaStark = &models.User{
+ AryaStark = &entity.User{
ID: 2,
Name: "Arya Stark",
diff --git a/app/pkg/mock/worker.go b/app/pkg/mock/worker.go
index 198d7924c..9eef4a092 100644
--- a/app/pkg/mock/worker.go
+++ b/app/pkg/mock/worker.go
@@ -5,16 +5,16 @@ import (
"net/url"
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/pkg/web"
"github.com/getfider/fider/app/pkg/worker"
)
// Worker is fake wrapper for background worker
type Worker struct {
- tenant *models.Tenant
- user *models.User
- baseURL string
+ tenant *entity.Tenant
+ user *entity.User
+ baseURL string
}
func createWorker() *Worker {
@@ -22,13 +22,13 @@ func createWorker() *Worker {
}
// OnTenant set current context tenant
-func (w *Worker) OnTenant(tenant *models.Tenant) *Worker {
+func (w *Worker) OnTenant(tenant *entity.Tenant) *Worker {
w.tenant = tenant
return w
}
// AsUser set current context user
-func (w *Worker) AsUser(user *models.User) *Worker {
+func (w *Worker) AsUser(user *entity.User) *Worker {
w.user = user
return w
}
diff --git a/app/pkg/validate/upload.go b/app/pkg/validate/upload.go
index 2ecf9bf9e..361744c1a 100644
--- a/app/pkg/validate/upload.go
+++ b/app/pkg/validate/upload.go
@@ -3,7 +3,7 @@ package validate
import (
"fmt"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/dto"
"github.com/goenning/imagic"
)
@@ -30,7 +30,7 @@ type ImageUploadOpts struct {
}
//MultiImageUpload validates multiple image uploads
-func MultiImageUpload(currentAttachments []string, uploads []*models.ImageUpload, opts MultiImageUploadOpts) ([]string, error) {
+func MultiImageUpload(currentAttachments []string, uploads []*dto.ImageUpload, opts MultiImageUploadOpts) ([]string, error) {
if currentAttachments == nil {
currentAttachments = []string{}
}
@@ -71,7 +71,7 @@ func MultiImageUpload(currentAttachments []string, uploads []*models.ImageUpload
}
//ImageUpload validates given image upload
-func ImageUpload(upload *models.ImageUpload, opts ImageUploadOpts) ([]string, error) {
+func ImageUpload(upload *dto.ImageUpload, opts ImageUploadOpts) ([]string, error) {
messages := []string{}
if opts.IsRequired {
diff --git a/app/pkg/validate/upload_test.go b/app/pkg/validate/upload_test.go
index 33765bcd0..58b8bf682 100644
--- a/app/pkg/validate/upload_test.go
+++ b/app/pkg/validate/upload_test.go
@@ -4,7 +4,7 @@ import (
"io/ioutil"
"testing"
- "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/env"
"github.com/getfider/fider/app/pkg/validate"
@@ -29,8 +29,8 @@ func TestValidateImageUpload(t *testing.T) {
for _, testCase := range testCases {
img, _ := ioutil.ReadFile(env.Path(testCase.fileName))
- upload := &models.ImageUpload{
- Upload: &models.ImageUploadData{
+ upload := &dto.ImageUpload{
+ Upload: &dto.ImageUploadData{
Content: img,
},
}
@@ -54,8 +54,8 @@ func TestValidateImageUpload_ExactRatio(t *testing.T) {
MaxKilobytes: 200,
}
- upload := &models.ImageUpload{
- Upload: &models.ImageUploadData{
+ upload := &dto.ImageUpload{
+ Upload: &dto.ImageUploadData{
Content: img,
},
}
@@ -83,7 +83,7 @@ func TestValidateImageUpload_Nil(t *testing.T) {
Expect(messages).HasLen(0)
Expect(err).IsNil()
- messages, err = validate.ImageUpload(&models.ImageUpload{}, validate.ImageUploadOpts{
+ messages, err = validate.ImageUpload(&dto.ImageUpload{}, validate.ImageUploadOpts{
IsRequired: false,
MinHeight: 200,
MinWidth: 200,
@@ -98,12 +98,12 @@ func TestValidateImageUpload_Required(t *testing.T) {
RegisterT(t)
var testCases = []struct {
- upload *models.ImageUpload
+ upload *dto.ImageUpload
count int
}{
{nil, 1},
- {&models.ImageUpload{}, 1},
- {&models.ImageUpload{
+ {&dto.ImageUpload{}, 1},
+ {&dto.ImageUpload{
BlobKey: "some-file.png",
Remove: true,
}, 1},
@@ -127,19 +127,19 @@ func TestValidateMultiImageUpload(t *testing.T) {
img, _ := ioutil.ReadFile(env.Path("/app/pkg/web/testdata/logo3-200w.gif"))
- uploads := []*models.ImageUpload{
- &models.ImageUpload{
- Upload: &models.ImageUploadData{
+ uploads := []*dto.ImageUpload{
+ {
+ Upload: &dto.ImageUploadData{
Content: img,
},
},
- &models.ImageUpload{
- Upload: &models.ImageUploadData{
+ {
+ Upload: &dto.ImageUploadData{
Content: img,
},
},
- &models.ImageUpload{
- Upload: &models.ImageUploadData{
+ {
+ Upload: &dto.ImageUploadData{
Content: img,
},
},
@@ -158,22 +158,22 @@ func TestValidateMultiImageUpload_Existing(t *testing.T) {
img, _ := ioutil.ReadFile(env.Path("/app/pkg/web/testdata/logo3-200w.gif"))
- uploads := []*models.ImageUpload{
- &models.ImageUpload{
+ uploads := []*dto.ImageUpload{
+ {
BlobKey: "attachments/file1.png",
Remove: true,
},
- &models.ImageUpload{
+ {
BlobKey: "attachments/file2.png",
Remove: true,
},
- &models.ImageUpload{
- Upload: &models.ImageUploadData{
+ {
+ Upload: &dto.ImageUploadData{
Content: img,
},
},
- &models.ImageUpload{
- Upload: &models.ImageUploadData{
+ {
+ Upload: &dto.ImageUploadData{
Content: img,
},
},
diff --git a/app/pkg/validate/validation.go b/app/pkg/validate/validation.go
index d98f5abb6..a71cb123b 100644
--- a/app/pkg/validate/validation.go
+++ b/app/pkg/validate/validation.go
@@ -3,13 +3,13 @@ package validate
import (
"context"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
)
// Validatable defines which models can be validated against context
type Validatable interface {
- Validate(ctx context.Context, user *models.User) *Result
- IsAuthorized(ctx context.Context, user *models.User) bool
+ Validate(ctx context.Context, user *entity.User) *Result
+ IsAuthorized(ctx context.Context, user *entity.User) bool
}
// ErrorItem holds a reference to something that went wrong
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.go
index 4ac71c6eb..58da9690b 100644
--- a/app/pkg/web/context.go
+++ b/app/pkg/web/context.go
@@ -17,9 +17,9 @@ 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/dto"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
@@ -154,8 +154,8 @@ func (c *Context) Enqueue(task worker.Task) {
}
//Tenant returns current tenant
-func (c *Context) Tenant() *models.Tenant {
- tenant, ok := c.Value(app.TenantCtxKey).(*models.Tenant)
+func (c *Context) Tenant() *entity.Tenant {
+ tenant, ok := c.Value(app.TenantCtxKey).(*entity.Tenant)
if ok {
return tenant
}
@@ -163,7 +163,7 @@ func (c *Context) Tenant() *models.Tenant {
}
//SetTenant update HTTP context with current tenant
-func (c *Context) SetTenant(tenant *models.Tenant) {
+func (c *Context) SetTenant(tenant *entity.Tenant) {
if tenant != nil {
c.Context = log.WithProperty(c.Context, log.PropertyKeyTenantID, tenant.ID)
}
@@ -181,7 +181,7 @@ func (c *Context) Bind(i interface{}) error {
//BindTo context values into given model
func (c *Context) BindTo(i actions.Actionable) *validate.Result {
- err := c.engine.binder.Bind(i.Initialize(), c)
+ err := c.engine.binder.Bind(i, c)
if err != nil {
if err == ErrContentTypeNotAllowed {
return validate.Failed(err.Error())
@@ -341,8 +341,8 @@ func (c *Context) AddParam(name, value string) {
}
//User returns authenticated user
-func (c *Context) User() *models.User {
- user, ok := c.Value(app.UserCtxKey).(*models.User)
+func (c *Context) User() *entity.User {
+ user, ok := c.Value(app.UserCtxKey).(*entity.User)
if ok {
return user
}
@@ -350,7 +350,7 @@ func (c *Context) User() *models.User {
}
//SetUser update HTTP context with current user
-func (c *Context) SetUser(user *models.User) {
+func (c *Context) SetUser(user *entity.User) {
if user != nil {
c.Context = log.WithProperty(c.Context, log.PropertyKeyUserID, user.ID)
}
@@ -534,7 +534,7 @@ func GlobalAssetsURL(ctx context.Context, path string, a ...interface{}) string
}
//TenantBaseURL returns base URL for a given tenant
-func TenantBaseURL(ctx context.Context, tenant *models.Tenant) string {
+func TenantBaseURL(ctx context.Context, tenant *entity.Tenant) string {
request := ctx.Value(app.RequestCtxKey).(Request)
if env.IsSingleHostMode() {
@@ -558,7 +558,7 @@ func TenantBaseURL(ctx context.Context, tenant *models.Tenant) string {
// TenantAssetsURL return the full URL to a tenant-specific static asset
func TenantAssetsURL(ctx context.Context, path string, a ...interface{}) string {
request := ctx.Value(app.RequestCtxKey).(Request)
- tenant, hasTenant := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ tenant, hasTenant := ctx.Value(app.TenantCtxKey).(*entity.Tenant)
path = fmt.Sprintf(path, a...)
if env.Config.CDN.Host != "" && hasTenant {
if env.IsSingleHostMode() {
@@ -571,7 +571,7 @@ func TenantAssetsURL(ctx context.Context, path string, a ...interface{}) string
// LogoURL return the full URL to the tenant-specific logo URL
func LogoURL(ctx context.Context) string {
- tenant, hasTenant := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ tenant, hasTenant := ctx.Value(app.TenantCtxKey).(*entity.Tenant)
if hasTenant && tenant.LogoBlobKey != "" {
return TenantAssetsURL(ctx, "/images/%s?size=200", tenant.LogoBlobKey)
}
diff --git a/app/pkg/web/context_test.go b/app/pkg/web/context_test.go
index c60113430..55f2dc15d 100644
--- a/app/pkg/web/context_test.go
+++ b/app/pkg/web/context_test.go
@@ -9,7 +9,7 @@ import (
"testing"
"time"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/web"
@@ -17,7 +17,7 @@ import (
func newGetContext(rawurl string, headers map[string]string) *web.Context {
u, _ := url.Parse(rawurl)
- e := web.New(nil)
+ e := web.New()
res := httptest.NewRecorder()
req := httptest.NewRequest("GET", u.RequestURI(), nil)
req.Host = u.Host
@@ -34,7 +34,7 @@ func newGetContext(rawurl string, headers map[string]string) *web.Context {
}
func newBodyContext(method string, params web.StringMap, body, contentType string) *web.Context {
- e := web.New(nil)
+ e := web.New()
res := httptest.NewRecorder()
req := httptest.NewRequest(method, "/some/resource", strings.NewReader(body))
req.Host = "demo.test.fider.io:3000"
@@ -89,7 +89,7 @@ func TestTenantURL(t *testing.T) {
RegisterT(t)
ctx := newGetContext("http://login.test.fider.io:3000", nil)
- tenant := &models.Tenant{
+ tenant := &entity.Tenant{
ID: 1,
Subdomain: "theavengers",
}
@@ -100,7 +100,7 @@ func TestTenantURL_WithCNAME(t *testing.T) {
RegisterT(t)
ctx := newGetContext("http://demo.test.fider.io:3000", nil)
- tenant := &models.Tenant{
+ tenant := &entity.Tenant{
ID: 1,
Subdomain: "theavengers",
CNAME: "feedback.theavengers.com",
@@ -113,7 +113,7 @@ func TestTenantURL_SingleHostMode(t *testing.T) {
env.Config.HostMode = "single"
ctx := newGetContext("http://demo.test.fider.io:3000", nil)
- tenant := &models.Tenant{
+ tenant := &entity.Tenant{
ID: 1,
Subdomain: "theavengers",
}
@@ -138,7 +138,7 @@ func TestGlobalAssetsURL_MultiHostMode(t *testing.T) {
env.Config.HostMode = "multi"
ctx := newGetContext("http://theavengers.test.fider.io:3000", nil)
- ctx.SetTenant(&models.Tenant{
+ ctx.SetTenant(&entity.Tenant{
ID: 1,
Subdomain: "theavengers",
CNAME: "feedback.theavengers.com",
@@ -157,7 +157,7 @@ func TestTenantAssetsURL_SingleHostMode(t *testing.T) {
env.Config.HostMode = "single"
ctx := newGetContext("http://feedback.theavengers.com:3000", nil)
- ctx.SetTenant(&models.Tenant{
+ ctx.SetTenant(&entity.Tenant{
ID: 1,
Subdomain: "theavengers",
})
@@ -175,7 +175,7 @@ func TestTenantAssetsURL_MultiHostMode(t *testing.T) {
env.Config.HostMode = "multi"
ctx := newGetContext("http://theavengers.test.fider.io:3000", nil)
- ctx.SetTenant(&models.Tenant{
+ ctx.SetTenant(&entity.Tenant{
ID: 1,
Subdomain: "theavengers",
CNAME: "feedback.theavengers.com",
diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.go
index fc9c245de..d556e2564 100644
--- a/app/pkg/web/engine.go
+++ b/app/pkg/web/engine.go
@@ -12,7 +12,6 @@ import (
"strconv"
"time"
- "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/models/dto"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
@@ -71,7 +70,7 @@ type Engine struct {
}
//New creates a new Engine
-func New(settings *models.SystemSettings) *Engine {
+func New() *Engine {
ctx := context.Background()
ctx = log.WithProperties(ctx, dto.Props{
log.PropertyKeyContextID: rand.String(32),
@@ -81,7 +80,7 @@ func New(settings *models.SystemSettings) *Engine {
router := &Engine{
Context: ctx,
mux: httprouter.New(),
- renderer: NewRenderer(settings),
+ renderer: NewRenderer(),
binder: NewDefaultBinder(),
middlewares: make([]MiddlewareFunc, 0),
worker: worker.New(),
@@ -95,7 +94,7 @@ func New(settings *models.SystemSettings) *Engine {
func (e *Engine) Start(address string) {
log.Info(e, "Application is starting")
log.Infof(e, "Version: @{Version}", dto.Props{
- "Version": e.renderer.settings.Version,
+ "Version": env.Version(),
})
log.Infof(e, "Environment: @{Env}", dto.Props{
"Env": env.Config.Environment,
diff --git a/app/pkg/web/engine_test.go b/app/pkg/web/engine_test.go
index 33c264538..e041e4e3c 100644
--- a/app/pkg/web/engine_test.go
+++ b/app/pkg/web/engine_test.go
@@ -5,8 +5,6 @@ import (
"net/http"
"testing"
- "github.com/getfider/fider/app/models"
-
"github.com/getfider/fider/app/pkg/web"
. "github.com/getfider/fider/app/pkg/assert"
@@ -15,7 +13,7 @@ import (
var e *web.Engine
func StartServer() {
- e = web.New(&models.SystemSettings{})
+ e = web.New()
group := e.Group()
{
diff --git a/app/pkg/web/react_test.go b/app/pkg/web/react_test.go
index 761dba0d7..a58f5cdfb 100644
--- a/app/pkg/web/react_test.go
+++ b/app/pkg/web/react_test.go
@@ -4,7 +4,7 @@ import (
"net/url"
"testing"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/web"
)
@@ -25,7 +25,7 @@ func TestReactRenderer_RenderEmptyHomeHTML(t *testing.T) {
r := web.NewReactRenderer("ssr.js")
u, _ := url.Parse("https://demo.test.fider.io")
html, err := r.Render(u, web.Map{
- "tenant": &models.Tenant{},
+ "tenant": &entity.Tenant{},
"settings": web.Map{},
"props": web.Map{
"posts": make([]web.Map, 0),
diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.go
index f478b9543..57e2ad67e 100644
--- a/app/pkg/web/renderer.go
+++ b/app/pkg/web/renderer.go
@@ -17,7 +17,6 @@ import (
"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"
@@ -57,7 +56,6 @@ type assetsFile struct {
//Renderer is the default HTML Render
type Renderer struct {
templates map[string]*template.Template
- settings *models.SystemSettings
assets *clientAssets
chunkedAssets map[string]*clientAssets
mutex sync.RWMutex
@@ -65,10 +63,9 @@ type Renderer struct {
}
// NewRenderer creates a new Renderer
-func NewRenderer(settings *models.SystemSettings) *Renderer {
+func NewRenderer() *Renderer {
return &Renderer{
templates: make(map[string]*template.Template),
- settings: settings,
mutex: sync.RWMutex{},
reactRenderer: NewReactRenderer("ssr.js"),
}
@@ -218,14 +215,11 @@ func (r *Renderer) Render(w io.Writer, statusCode int, templateName string, prop
public["tenant"] = tenant
public["props"] = props.Data
public["settings"] = &Map{
- "mode": r.settings.Mode,
- "buildTime": r.settings.BuildTime,
- "version": r.settings.Version,
- "environment": r.settings.Environment,
- "compiler": r.settings.Compiler,
- "googleAnalytics": r.settings.GoogleAnalytics,
- "domain": r.settings.Domain,
- "hasLegal": r.settings.HasLegal,
+ "mode": env.Config.HostMode,
+ "environment": env.Config.Environment,
+ "googleAnalytics": env.Config.GoogleAnalytics,
+ "domain": env.MultiTenantDomain(),
+ "hasLegal": env.HasLegal(),
"baseURL": ctx.BaseURL(),
"tenantAssetsURL": TenantAssetsURL(ctx, ""),
"globalAssetsURL": GlobalAssetsURL(ctx, ""),
diff --git a/app/pkg/web/renderer_test.go b/app/pkg/web/renderer_test.go
index 502527798..df6a5ec25 100644
--- a/app/pkg/web/renderer_test.go
+++ b/app/pkg/web/renderer_test.go
@@ -10,9 +10,9 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
"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"
@@ -36,7 +36,7 @@ func TestRenderer_Basic(t *testing.T) {
buf := new(bytes.Buffer)
ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
- renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer := web.NewRenderer()
renderer.Render(buf, http.StatusOK, "index.html", web.Props{}, ctx)
compareRendererResponse(buf, "/app/pkg/web/testdata/basic.html", ctx)
}
@@ -50,7 +50,7 @@ func TestRenderer_WithChunkPreload(t *testing.T) {
buf := new(bytes.Buffer)
ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
- renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer := web.NewRenderer()
renderer.Render(buf, http.StatusOK, "index.html", web.Props{ChunkName: "Test.page"}, ctx)
compareRendererResponse(buf, "/app/pkg/web/testdata/chunk.html", ctx)
}
@@ -64,8 +64,8 @@ func TestRenderer_Tenant(t *testing.T) {
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{})
+ ctx.SetTenant(&entity.Tenant{Name: "Game of Thrones"})
+ renderer := web.NewRenderer()
renderer.Render(buf, http.StatusOK, "index.html", web.Props{}, ctx)
compareRendererResponse(buf, "/app/pkg/web/testdata/tenant.html", ctx)
}
@@ -80,7 +80,7 @@ func TestRenderer_WithCanonicalURL(t *testing.T) {
buf := new(bytes.Buffer)
ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
ctx.SetCanonicalURL("http://feedback.demo.org")
- renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer := web.NewRenderer()
renderer.Render(buf, http.StatusOK, "index.html", web.Props{}, ctx)
compareRendererResponse(buf, "/app/pkg/web/testdata/canonical.html", ctx)
}
@@ -94,7 +94,7 @@ func TestRenderer_Home(t *testing.T) {
buf := new(bytes.Buffer)
ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
- renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer := web.NewRenderer()
renderer.Render(buf, http.StatusOK, "index.html", web.Props{
Title: "My Page Title",
Description: "My Page Description",
@@ -120,8 +120,8 @@ func TestRenderer_Home_SSR(t *testing.T) {
ctx := newGetContext("https://demo.test.fider.io:3000/", map[string]string{
"User-Agent": "Googlebot",
})
- ctx.SetTenant(&models.Tenant{})
- renderer := web.NewRenderer(&models.SystemSettings{})
+ ctx.SetTenant(&entity.Tenant{})
+ renderer := web.NewRenderer()
renderer.Render(buf, http.StatusOK, "index.html", web.Props{
Title: "My Page Title",
Description: "My Page Description",
@@ -144,7 +144,7 @@ func TestRenderer_AuthenticatedUser(t *testing.T) {
buf := new(bytes.Buffer)
ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
- ctx.SetUser(&models.User{
+ ctx.SetUser(&entity.User{
ID: 5,
Name: "Jon Snow",
@@ -153,7 +153,7 @@ func TestRenderer_AuthenticatedUser(t *testing.T) {
AvatarType: enum.AvatarTypeGravatar,
AvatarURL: "https://demo.test.fider.io:3000/avatars/gravatar/5/Jon%20Snow",
})
- renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer := web.NewRenderer()
renderer.Render(buf, http.StatusOK, "index.html", web.Props{
Title: "My Page Title",
Description: "My Page Description",
@@ -183,7 +183,7 @@ func TestRenderer_WithOAuth(t *testing.T) {
buf := new(bytes.Buffer)
ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
- renderer := web.NewRenderer(&models.SystemSettings{})
+ renderer := web.NewRenderer()
renderer.Render(buf, http.StatusOK, "index.html", web.Props{}, ctx)
compareRendererResponse(buf, "/app/pkg/web/testdata/oauth.html", ctx)
}
@@ -194,7 +194,7 @@ func TestRenderer_NonOK(t *testing.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 := web.NewRenderer()
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/testdata/basic.html b/app/pkg/web/testdata/basic.html
index fbf958e2a..c367b0401 100755
--- a/app/pkg/web/testdata/basic.html
+++ b/app/pkg/web/testdata/basic.html
@@ -37,7 +37,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","props":{},"sessionID":"","settings":{"baseURL":"https://demo.test.fider.io:3000","buildTime":"","compiler":"","domain":"","environment":"","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":false,"mode":"","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000","version":""},"tenant":null,"title":"Fider"}
+ {"contextID":"CONTEXT_ID","props":{},"sessionID":"","settings":{"baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":true,"mode":"multi","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000"},"tenant":null,"title":"Fider"}
</script>
diff --git a/app/pkg/web/testdata/canonical.html b/app/pkg/web/testdata/canonical.html
index b18f0d787..d266e9dd2 100755
--- a/app/pkg/web/testdata/canonical.html
+++ b/app/pkg/web/testdata/canonical.html
@@ -39,7 +39,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","props":{},"sessionID":"","settings":{"baseURL":"https://demo.test.fider.io:3000","buildTime":"","compiler":"","domain":"","environment":"","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":false,"mode":"","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000","version":""},"tenant":null,"title":"Fider"}
+ {"contextID":"CONTEXT_ID","props":{},"sessionID":"","settings":{"baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":true,"mode":"multi","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000"},"tenant":null,"title":"Fider"}
</script>
diff --git a/app/pkg/web/testdata/chunk.html b/app/pkg/web/testdata/chunk.html
index b163889d6..db9ef62db 100644
--- a/app/pkg/web/testdata/chunk.html
+++ b/app/pkg/web/testdata/chunk.html
@@ -44,7 +44,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","props":{},"sessionID":"","settings":{"baseURL":"https://demo.test.fider.io:3000","buildTime":"","compiler":"","domain":"","environment":"","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":false,"mode":"","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000","version":""},"tenant":null,"title":"Fider"}
+ {"contextID":"CONTEXT_ID","props":{},"sessionID":"","settings":{"baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":true,"mode":"multi","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000"},"tenant":null,"title":"Fider"}
</script>
diff --git a/app/pkg/web/testdata/home.html b/app/pkg/web/testdata/home.html
index e99ffb221..3174ff7ef 100755
--- a/app/pkg/web/testdata/home.html
+++ b/app/pkg/web/testdata/home.html
@@ -37,7 +37,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","description":"My Page Description","props":{"countPerStatus":{},"posts":[],"tags":[]},"sessionID":"","settings":{"baseURL":"https://demo.test.fider.io:3000","buildTime":"","compiler":"","domain":"","environment":"","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":false,"mode":"","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000","version":""},"tenant":null,"title":"My Page Title · Fider"}
+ {"contextID":"CONTEXT_ID","description":"My Page Description","props":{"countPerStatus":{},"posts":[],"tags":[]},"sessionID":"","settings":{"baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":true,"mode":"multi","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000"},"tenant":null,"title":"My Page Title · Fider"}
</script>
diff --git a/app/pkg/web/testdata/oauth.html b/app/pkg/web/testdata/oauth.html
index 00c5740f3..8c83b8c92 100755
--- a/app/pkg/web/testdata/oauth.html
+++ b/app/pkg/web/testdata/oauth.html
@@ -37,7 +37,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","props":{},"sessionID":"","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}],"tenantAssetsURL":"https://demo.test.fider.io:3000","version":""},"tenant":null,"title":"Fider"}
+ {"contextID":"CONTEXT_ID","props":{},"sessionID":"","settings":{"baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":true,"mode":"multi","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}],"tenantAssetsURL":"https://demo.test.fider.io:3000"},"tenant":null,"title":"Fider"}
</script>
diff --git a/app/pkg/web/testdata/tenant.html b/app/pkg/web/testdata/tenant.html
index 2e79dbbc2..dad3f9b4b 100755
--- a/app/pkg/web/testdata/tenant.html
+++ b/app/pkg/web/testdata/tenant.html
@@ -37,7 +37,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","props":{},"sessionID":"","settings":{"baseURL":"https://demo.test.fider.io:3000","buildTime":"","compiler":"","domain":"","environment":"","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":false,"mode":"","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000","version":""},"tenant":{"id":0,"name":"Game of Thrones","subdomain":"","invitation":"","welcomeMessage":"","cname":"","status":0,"isPrivate":false,"logoBlobKey":""},"title":"Game of Thrones"}
+ {"contextID":"CONTEXT_ID","props":{},"sessionID":"","settings":{"baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":true,"mode":"multi","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000"},"tenant":{"id":0,"name":"Game of Thrones","subdomain":"","invitation":"","welcomeMessage":"","cname":"","status":0,"isPrivate":false,"logoBlobKey":""},"title":"Game of Thrones"}
</script>
diff --git a/app/pkg/web/testdata/user.html b/app/pkg/web/testdata/user.html
index ec5eb8c23..0d637e770 100755
--- a/app/pkg/web/testdata/user.html
+++ b/app/pkg/web/testdata/user.html
@@ -37,7 +37,7 @@
<script id="server-data" type="application/json">
- {"contextID":"CONTEXT_ID","description":"My Page Description","props":{},"sessionID":"","settings":{"baseURL":"https://demo.test.fider.io:3000","buildTime":"","compiler":"","domain":"","environment":"","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":false,"mode":"","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000","version":""},"tenant":null,"title":"My Page Title · Fider","user":{"avatarBlobKey":"","avatarType":"gravatar","avatarURL":"https://demo.test.fider.io:3000/avatars/gravatar/5/Jon%20Snow","email":"[email protected]","id":5,"isAdministrator":true,"isCollaborator":true,"name":"Jon Snow","role":"administrator","status":"active"}}
+ {"contextID":"CONTEXT_ID","description":"My Page Description","props":{},"sessionID":"","settings":{"baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":true,"mode":"multi","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000"},"tenant":null,"title":"My Page Title · Fider","user":{"avatarBlobKey":"","avatarType":"gravatar","avatarURL":"https://demo.test.fider.io:3000/avatars/gravatar/5/Jon%20Snow","email":"[email protected]","id":5,"isAdministrator":true,"isCollaborator":true,"name":"Jon Snow","role":"administrator","status":"active"}}
</script>
diff --git a/app/pkg/web/util/webutil.go b/app/pkg/web/util/webutil.go
index 6ad3903ab..75189787f 100644
--- a/app/pkg/web/util/webutil.go
+++ b/app/pkg/web/util/webutil.go
@@ -4,14 +4,14 @@ import (
"net/http"
"time"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"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/web"
)
-func encode(user *models.User) string {
+func encode(user *entity.User) string {
token, err := jwt.Encode(jwt.FiderClaims{
UserID: user.ID,
UserName: user.Name,
@@ -30,7 +30,7 @@ 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 *entity.User) {
AddAuthTokenCookie(ctx, encode(user))
}
@@ -41,7 +41,7 @@ func AddAuthTokenCookie(ctx *web.Context, token string) {
}
//SetSignUpAuthCookie sets a temporary domain-wide Auth Token
-func SetSignUpAuthCookie(ctx *web.Context, user *models.User) {
+func SetSignUpAuthCookie(ctx *web.Context, user *entity.User) {
http.SetCookie(ctx.Response, &http.Cookie{
Name: web.CookieSignUpAuthName,
Domain: env.MultiTenantDomain(),
diff --git a/app/pkg/worker/context.go b/app/pkg/worker/context.go
index 696382412..2826f81bf 100644
--- a/app/pkg/worker/context.go
+++ b/app/pkg/worker/context.go
@@ -4,8 +4,8 @@ import (
"context"
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/rand"
@@ -57,8 +57,8 @@ func (c *Context) Set(key interface{}, val interface{}) {
}
//User from current context
-func (c *Context) User() *models.User {
- user, ok := c.Value(app.UserCtxKey).(*models.User)
+func (c *Context) User() *entity.User {
+ user, ok := c.Value(app.UserCtxKey).(*entity.User)
if ok {
return user
}
@@ -66,8 +66,8 @@ func (c *Context) User() *models.User {
}
//Tenant from current context
-func (c *Context) Tenant() *models.Tenant {
- tenant, ok := c.Value(app.TenantCtxKey).(*models.Tenant)
+func (c *Context) Tenant() *entity.Tenant {
+ tenant, ok := c.Value(app.TenantCtxKey).(*entity.Tenant)
if ok {
return tenant
}
diff --git a/app/services/blob/blob_test.go b/app/services/blob/blob_test.go
index b7374ba8e..7195d1a30 100644
--- a/app/services/blob/blob_test.go
+++ b/app/services/blob/blob_test.go
@@ -10,14 +10,13 @@ import (
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/entity"
"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"
@@ -27,8 +26,8 @@ import (
"github.com/getfider/fider/app/services/blob"
)
-var tenant1 = &models.Tenant{ID: 1}
-var tenant2 = &models.Tenant{ID: 2}
+var tenant1 = &entity.Tenant{ID: 1}
+var tenant2 = &entity.Tenant{ID: 2}
func setupS3(t *testing.T) {
RegisterT(t)
diff --git a/app/services/blob/fs/fs.go b/app/services/blob/fs/fs.go
index 66ca362ad..22a32fc65 100644
--- a/app/services/blob/fs/fs.go
+++ b/app/services/blob/fs/fs.go
@@ -12,9 +12,9 @@ import (
"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/entity"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
@@ -131,7 +131,7 @@ func keyFullPath(ctx context.Context, key string) string {
func basePath(ctx context.Context) string {
startPath := env.Config.BlobStorage.FS.Path
- tenant, ok := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ tenant, ok := ctx.Value(app.TenantCtxKey).(*entity.Tenant)
if ok {
return path.Join(startPath, "tenants", strconv.Itoa(tenant.ID))
}
diff --git a/app/services/blob/s3/s3.go b/app/services/blob/s3/s3.go
index 75aea2b19..0a186dc8e 100644
--- a/app/services/blob/s3/s3.go
+++ b/app/services/blob/s3/s3.go
@@ -17,9 +17,9 @@ import (
"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/entity"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
@@ -74,7 +74,7 @@ func (s Service) Init() {
}
func listBlobs(ctx context.Context, q *query.ListBlobs) error {
- tenant := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ tenant := ctx.Value(app.TenantCtxKey).(*entity.Tenant)
basePath := fmt.Sprintf("tenants/%d/", tenant.ID)
response, err := DefaultClient.ListObjectsWithContext(ctx, &s3.ListObjectsInput{
Bucket: aws.String(env.Config.BlobStorage.S3.BucketName),
@@ -153,7 +153,7 @@ func deleteBlob(ctx context.Context, c *cmd.DeleteBlob) error {
}
func keyFullPathURL(ctx context.Context, key string) string {
- tenant, ok := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ tenant, ok := ctx.Value(app.TenantCtxKey).(*entity.Tenant)
if ok {
return path.Join("tenants", strconv.Itoa(tenant.ID), key)
}
diff --git a/app/services/blob/sql/sql.go b/app/services/blob/sql/sql.go
index afbc16397..3b9839592 100644
--- a/app/services/blob/sql/sql.go
+++ b/app/services/blob/sql/sql.go
@@ -8,12 +8,12 @@ import (
"github.com/getfider/fider/app/models/cmd"
"github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
"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"
@@ -54,7 +54,7 @@ type dbBlob struct {
}
func listBlobs(ctx context.Context, q *query.ListBlobs) error {
- return using(ctx, func(tenant *models.Tenant) error {
+ return using(ctx, func(tenant *entity.Tenant) error {
trx, err := dbx.BeginTx(ctx)
if err != nil {
return errors.Wrap(err, "failed to open transaction")
@@ -79,7 +79,7 @@ func listBlobs(ctx context.Context, q *query.ListBlobs) error {
}
func getBlobByKey(ctx context.Context, q *query.GetBlobByKey) error {
- return using(ctx, func(tenant *models.Tenant) error {
+ return using(ctx, func(tenant *entity.Tenant) error {
var tenantID sql.NullInt64
if tenant != nil {
err := tenantID.Scan(tenant.ID)
@@ -117,7 +117,7 @@ func storeBlob(ctx context.Context, c *cmd.StoreBlob) error {
return errors.Wrap(err, "failed to validate blob key '%s'", c.Key)
}
- return using(ctx, func(tenant *models.Tenant) error {
+ return using(ctx, func(tenant *entity.Tenant) error {
var tenantID sql.NullInt64
if tenant != nil {
err := tenantID.Scan(tenant.ID)
@@ -151,7 +151,7 @@ func storeBlob(ctx context.Context, c *cmd.StoreBlob) error {
}
func deleteBlob(ctx context.Context, c *cmd.DeleteBlob) error {
- return using(ctx, func(tenant *models.Tenant) error {
+ return using(ctx, func(tenant *entity.Tenant) error {
var tenantID sql.NullInt64
if tenant != nil {
err := tenantID.Scan(tenant.ID)
@@ -179,7 +179,7 @@ func deleteBlob(ctx context.Context, c *cmd.DeleteBlob) error {
})
}
-func using(ctx context.Context, handler func(tenant *models.Tenant) error) error {
- tenant, _ := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+func using(ctx context.Context, handler func(tenant *entity.Tenant) error) error {
+ tenant, _ := ctx.Value(app.TenantCtxKey).(*entity.Tenant)
return handler(tenant)
}
diff --git a/app/services/email/emailmock/emailmock.go b/app/services/email/emailmock/emailmock.go
index 0f3cb5fe0..2b3360367 100644
--- a/app/services/email/emailmock/emailmock.go
+++ b/app/services/email/emailmock/emailmock.go
@@ -5,9 +5,9 @@ import (
"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/entity"
"github.com/getfider/fider/app/pkg/bus"
)
@@ -18,7 +18,7 @@ type HistoryItem struct {
To []dto.Recipient
TemplateName string
Props dto.Props
- Tenant *models.Tenant
+ Tenant *entity.Tenant
}
func init() {
@@ -55,7 +55,7 @@ func sendMail(ctx context.Context, c *cmd.SendMail) {
Props: c.Props,
}
- tenant, ok := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ tenant, ok := ctx.Value(app.TenantCtxKey).(*entity.Tenant)
if ok {
item.Tenant = tenant
}
diff --git a/app/services/email/mailgun/mailgun.go b/app/services/email/mailgun/mailgun.go
index 2d180061d..5354150ee 100644
--- a/app/services/email/mailgun/mailgun.go
+++ b/app/services/email/mailgun/mailgun.go
@@ -9,9 +9,9 @@ import (
"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/entity"
"github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
@@ -104,7 +104,7 @@ func sendMail(ctx context.Context, c *cmd.SendMail) {
form.Add("html", message.Body)
form.Add("o:tag", fmt.Sprintf("template:%s", c.TemplateName))
- tenant, ok := ctx.Value(app.TenantCtxKey).(*models.Tenant)
+ tenant, ok := ctx.Value(app.TenantCtxKey).(*entity.Tenant)
if ok && !env.IsSingleHostMode() {
form.Add("o:tag", fmt.Sprintf("tenant:%s", tenant.Subdomain))
}
diff --git a/app/services/email/mailgun/mailgun_test.go b/app/services/email/mailgun/mailgun_test.go
index f71a63936..adfbb039e 100644
--- a/app/services/email/mailgun/mailgun_test.go
+++ b/app/services/email/mailgun/mailgun_test.go
@@ -9,13 +9,12 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models/cmd"
"github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/env"
"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/services/email"
. "github.com/getfider/fider/app/pkg/assert"
@@ -24,7 +23,7 @@ import (
var ctx context.Context
func reset() {
- ctx = context.WithValue(context.Background(), app.TenantCtxKey, &models.Tenant{
+ ctx = context.WithValue(context.Background(), app.TenantCtxKey, &entity.Tenant{
Subdomain: "got",
})
bus.Init(mailgun.Service{}, httpclientmock.Service{})
diff --git a/app/services/email/smtp/smtp_test.go b/app/services/email/smtp/smtp_test.go
index 19f612fda..a9574a2d3 100644
--- a/app/services/email/smtp/smtp_test.go
+++ b/app/services/email/smtp/smtp_test.go
@@ -8,9 +8,9 @@ import (
"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/entity"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/services/email"
@@ -35,7 +35,7 @@ func mockSend(localname, servername string, enableStartTLS bool, auth gosmtp.Aut
}
func reset() {
- ctx = context.WithValue(context.Background(), app.TenantCtxKey, &models.Tenant{
+ ctx = context.WithValue(context.Background(), app.TenantCtxKey, &entity.Tenant{
Subdomain: "got",
})
smtp.Send = mockSend
diff --git a/app/services/oauth/oauth.go b/app/services/oauth/oauth.go
index d53b057dc..8f18287e9 100644
--- a/app/services/oauth/oauth.go
+++ b/app/services/oauth/oauth.go
@@ -8,9 +8,9 @@ import (
"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/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
@@ -59,7 +59,7 @@ func getProviderStatus(key string) int {
}
var (
- systemProviders = []*models.OAuthConfig{
+ systemProviders = []*entity.OAuthConfig{
{
Provider: app.FacebookProvider,
DisplayName: "Facebook",
@@ -284,7 +284,7 @@ func listAllOAuthProviders(ctx context.Context, q *query.ListAllOAuthProviders)
return nil
}
-func getConfig(ctx context.Context, provider string) (*models.OAuthConfig, error) {
+func getConfig(ctx context.Context, provider string) (*entity.OAuthConfig, error) {
for _, config := range systemProviders {
if config.Status == enum.OAuthConfigEnabled && config.Provider == provider {
return config, nil
diff --git a/app/services/oauth/oauth_test.go b/app/services/oauth/oauth_test.go
index c39fe12d3..56f7c46ee 100644
--- a/app/services/oauth/oauth_test.go
+++ b/app/services/oauth/oauth_test.go
@@ -9,9 +9,9 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/entity"
"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"
@@ -24,7 +24,7 @@ import (
func newGetContext(rawurl string) *web.Context {
u, _ := url.Parse(rawurl)
- e := web.New(nil)
+ e := web.New()
res := httptest.NewRecorder()
req := httptest.NewRequest("GET", u.RequestURI(), nil)
req.Host = u.Host
@@ -91,7 +91,7 @@ func TestGetAuthURL_Custom(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
if q.Provider == "_custom" {
- q.Result = &models.OAuthConfig{
+ q.Result = &entity.OAuthConfig{
Provider: q.Provider,
ClientID: "CU_CL_ID",
Scope: "profile email",
@@ -119,7 +119,7 @@ func TestGetAuthURL_Twitch(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
if q.Provider == "_custom" {
- q.Result = &models.OAuthConfig{
+ q.Result = &entity.OAuthConfig{
Provider: q.Provider,
ClientID: "CU_CL_ID",
Scope: "openid",
@@ -147,7 +147,7 @@ func TestParseProfileResponse_AllFields(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
if q.Provider == "_test1" {
- q.Result = &models.OAuthConfig{
+ q.Result = &entity.OAuthConfig{
Provider: q.Provider,
JSONUserIDPath: "id",
JSONUserNamePath: "name",
@@ -177,7 +177,7 @@ func TestParseProfileResponse_WithoutEmail(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
if q.Provider == "_test1" {
- q.Result = &models.OAuthConfig{
+ q.Result = &entity.OAuthConfig{
Provider: q.Provider,
JSONUserIDPath: "id",
JSONUserNamePath: "name",
@@ -206,7 +206,7 @@ func TestParseProfileResponse_NestedData(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
if q.Provider == "_test1" {
- q.Result = &models.OAuthConfig{
+ q.Result = &entity.OAuthConfig{
Provider: q.Provider,
JSONUserIDPath: "id",
JSONUserNamePath: "profile.name",
@@ -241,7 +241,7 @@ func TestParseProfileResponse_WithFallback(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
if q.Provider == "_test1" {
- q.Result = &models.OAuthConfig{
+ q.Result = &entity.OAuthConfig{
Provider: q.Provider,
JSONUserIDPath: "id",
JSONUserNamePath: "profile.name, profile.login",
@@ -276,7 +276,7 @@ func TestParseProfileResponse_UseEmailWhenNameIsEmpty(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
if q.Provider == "_test1" {
- q.Result = &models.OAuthConfig{
+ q.Result = &entity.OAuthConfig{
Provider: q.Provider,
JSONUserIDPath: "id",
JSONUserNamePath: "profile.name",
@@ -310,7 +310,7 @@ func TestParseProfileResponse_InvalidEmail(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
if q.Provider == "_test1" {
- q.Result = &models.OAuthConfig{
+ q.Result = &entity.OAuthConfig{
Provider: q.Provider,
JSONUserIDPath: "id",
JSONUserNamePath: "profile.name",
@@ -345,7 +345,7 @@ func TestParseProfileResponse_EmptyID(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
if q.Provider == "_test1" {
- q.Result = &models.OAuthConfig{
+ q.Result = &entity.OAuthConfig{
Provider: q.Provider,
JSONUserIDPath: "id",
JSONUserNamePath: "name",
@@ -372,7 +372,7 @@ func TestParseProfileResponse_EmptyName(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
if q.Provider == "_test1" {
- q.Result = &models.OAuthConfig{
+ q.Result = &entity.OAuthConfig{
Provider: q.Provider,
JSONUserIDPath: "id",
JSONUserNamePath: "name",
@@ -400,7 +400,7 @@ func TestCustomOAuth_Disabled(t *testing.T) {
bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
if q.Provider == "_test1" {
- q.Result = &models.OAuthConfig{
+ q.Result = &entity.OAuthConfig{
Provider: q.Provider,
JSONUserIDPath: "id",
JSONUserNamePath: "name",
diff --git a/app/services/sqlstore/postgres/attachment.go b/app/services/sqlstore/postgres/attachment.go
index 86db24110..bac0a74db 100644
--- a/app/services/sqlstore/postgres/attachment.go
+++ b/app/services/sqlstore/postgres/attachment.go
@@ -5,8 +5,8 @@ import (
"database/sql"
"fmt"
- "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/dbx"
@@ -16,7 +16,7 @@ import (
)
func setAttachments(ctx context.Context, c *cmd.SetAttachments) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
postID := c.Post.ID
var commentID sql.NullInt64
if c.Comment != nil {
@@ -49,7 +49,7 @@ func setAttachments(ctx context.Context, c *cmd.SetAttachments) error {
}
func getAttachments(ctx context.Context, q *query.GetAttachments) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
q.Result = make([]string, 0)
postID := q.Post.ID
diff --git a/app/services/sqlstore/postgres/attachment_test.go b/app/services/sqlstore/postgres/attachment_test.go
index 38daf69ec..f11159c34 100644
--- a/app/services/sqlstore/postgres/attachment_test.go
+++ b/app/services/sqlstore/postgres/attachment_test.go
@@ -4,8 +4,8 @@ import (
"context"
"testing"
- "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"
@@ -20,8 +20,8 @@ func TestUploadImage(t *testing.T) {
})
uploadImage := &cmd.UploadImage{
- Image: &models.ImageUpload{
- Upload: &models.ImageUploadData{
+ Image: &dto.ImageUpload{
+ Upload: &dto.ImageUploadData{
Content: []byte("Hello World"),
ContentType: "text/plain",
},
@@ -43,8 +43,8 @@ func TestUploadImage_NoContent(t *testing.T) {
})
uploadImage := &cmd.UploadImage{
- Image: &models.ImageUpload{
- Upload: &models.ImageUploadData{
+ Image: &dto.ImageUpload{
+ Upload: &dto.ImageUploadData{
Content: []byte(""),
},
},
@@ -64,15 +64,15 @@ func TestUploadMultipleImages(t *testing.T) {
})
uploadImages := &cmd.UploadImages{
- Images: []*models.ImageUpload{
- &models.ImageUpload{
- Upload: &models.ImageUploadData{
+ Images: []*dto.ImageUpload{
+ {
+ Upload: &dto.ImageUploadData{
Content: []byte("Hello World 1"),
ContentType: "text/plain",
},
},
- &models.ImageUpload{
- Upload: &models.ImageUploadData{
+ {
+ Upload: &dto.ImageUploadData{
Content: []byte("Hello World 2"),
ContentType: "text/plain",
},
diff --git a/app/services/sqlstore/postgres/comment.go b/app/services/sqlstore/postgres/comment.go
index da02cca0a..a4baab122 100644
--- a/app/services/sqlstore/postgres/comment.go
+++ b/app/services/sqlstore/postgres/comment.go
@@ -4,8 +4,8 @@ import (
"context"
"time"
- "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/dbx"
"github.com/getfider/fider/app/pkg/errors"
@@ -21,8 +21,8 @@ type dbComment struct {
EditedBy *dbUser `db:"edited_by"`
}
-func (c *dbComment) toModel(ctx context.Context) *models.Comment {
- comment := &models.Comment{
+func (c *dbComment) toModel(ctx context.Context) *entity.Comment {
+ comment := &entity.Comment{
ID: c.ID,
Content: c.Content,
CreatedAt: c.CreatedAt,
@@ -37,7 +37,7 @@ func (c *dbComment) toModel(ctx context.Context) *models.Comment {
}
func addNewComment(ctx context.Context, c *cmd.AddNewComment) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
var id int
if err := trx.Get(&id, `
INSERT INTO comments (tenant_id, post_id, content, user_id, created_at)
@@ -62,7 +62,7 @@ func addNewComment(ctx context.Context, c *cmd.AddNewComment) error {
}
func updateComment(ctx context.Context, c *cmd.UpdateComment) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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)
@@ -74,7 +74,7 @@ func updateComment(ctx context.Context, c *cmd.UpdateComment) error {
}
func deleteComment(ctx context.Context, c *cmd.DeleteComment) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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,
@@ -86,7 +86,7 @@ func deleteComment(ctx context.Context, c *cmd.DeleteComment) error {
}
func getCommentByID(ctx context.Context, q *query.GetCommentByID) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
q.Result = nil
comment := dbComment{}
@@ -130,8 +130,8 @@ func getCommentByID(ctx context.Context, q *query.GetCommentByID) error {
}
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)
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ q.Result = make([]*entity.Comment, 0)
comments := []*dbComment{}
err := trx.Select(&comments,
@@ -188,7 +188,7 @@ func getCommentsByPost(ctx context.Context, q *query.GetCommentsByPost) error {
return errors.Wrap(err, "failed get comments of post with id '%d'", q.Post.ID)
}
- q.Result = make([]*models.Comment, len(comments))
+ q.Result = make([]*entity.Comment, len(comments))
for i, comment := range comments {
q.Result[i] = comment.toModel(ctx)
}
diff --git a/app/services/sqlstore/postgres/common_test.go b/app/services/sqlstore/postgres/common_test.go
index 155a2e9a0..15ffee531 100644
--- a/app/services/sqlstore/postgres/common_test.go
+++ b/app/services/sqlstore/postgres/common_test.go
@@ -6,7 +6,7 @@ import (
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/services/sqlstore/postgres"
)
@@ -36,11 +36,11 @@ func TestToTSQuery(t *testing.T) {
}
}
-func withTenant(ctx context.Context, tenant *models.Tenant) context.Context {
+func withTenant(ctx context.Context, tenant *entity.Tenant) context.Context {
return context.WithValue(ctx, app.TenantCtxKey, tenant)
}
-func withUser(ctx context.Context, user *models.User) context.Context {
+func withUser(ctx context.Context, user *entity.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
index 4ea0e4f81..ee6dd27ca 100644
--- a/app/services/sqlstore/postgres/event.go
+++ b/app/services/sqlstore/postgres/event.go
@@ -5,14 +5,14 @@ import (
"database/sql"
"time"
- "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/entity"
"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 {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
dbClientIP := sql.NullString{
String: c.ClientIP,
Valid: len(c.ClientIP) > 0,
diff --git a/app/services/sqlstore/postgres/notification.go b/app/services/sqlstore/postgres/notification.go
index ed6eca145..c489f9912 100644
--- a/app/services/sqlstore/postgres/notification.go
+++ b/app/services/sqlstore/postgres/notification.go
@@ -5,9 +5,9 @@ import (
"fmt"
"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/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/dbx"
@@ -42,7 +42,7 @@ func purgeExpiredNotifications(ctx context.Context, c *cmd.PurgeExpiredNotificat
}
func markAllNotificationsAsRead(ctx context.Context, c *cmd.MarkAllNotificationsAsRead) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
if user == nil {
return nil
}
@@ -58,7 +58,7 @@ func markAllNotificationsAsRead(ctx context.Context, c *cmd.MarkAllNotifications
}
func countUnreadNotifications(ctx context.Context, q *query.CountUnreadNotifications) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
q.Result = 0
if user != nil {
@@ -72,7 +72,7 @@ func countUnreadNotifications(ctx context.Context, q *query.CountUnreadNotificat
}
func markNotificationAsRead(ctx context.Context, c *cmd.MarkNotificationAsRead) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
if user == nil {
return nil
}
@@ -89,9 +89,9 @@ func markNotificationAsRead(ctx context.Context, c *cmd.MarkNotificationAsRead)
}
func getNotificationByID(ctx context.Context, q *query.GetNotificationByID) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
q.Result = nil
- notification := &models.Notification{}
+ notification := &entity.Notification{}
err := trx.Get(notification, `
SELECT id, title, link, read, created_at
@@ -108,8 +108,8 @@ func getNotificationByID(ctx context.Context, q *query.GetNotificationByID) erro
}
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{}
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ q.Result = []*entity.Notification{}
err := trx.Select(&q.Result, `
SELECT id, title, link, read, created_at
FROM notifications
@@ -124,14 +124,14 @@ func getActiveNotifications(ctx context.Context, q *query.GetActiveNotifications
}
func addNewNotification(ctx context.Context, c *cmd.AddNewNotification) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
c.Result = nil
if user.ID == c.User.ID {
return nil
}
now := time.Now()
- notification := &models.Notification{
+ notification := &entity.Notification{
Title: c.Title,
Link: c.Link,
CreatedAt: now,
@@ -152,13 +152,13 @@ func addNewNotification(ctx context.Context, c *cmd.AddNewNotification) error {
}
func addSubscriber(ctx context.Context, c *cmd.AddSubscriber) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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 {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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)
@@ -173,8 +173,8 @@ func removeSubscriber(ctx context.Context, c *cmd.RemoveSubscriber) error {
}
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)
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ q.Result = make([]*entity.User, 0)
var (
users []*dbUser
@@ -237,7 +237,7 @@ func getActiveSubscribers(ctx context.Context, q *query.GetActiveSubscribers) er
return errors.Wrap(err, "failed to get post number '%d' subscribers", q.Number)
}
- q.Result = make([]*models.User, len(users))
+ q.Result = make([]*entity.User, len(users))
for i, user := range users {
q.Result[i] = user.toModel(ctx)
}
@@ -245,7 +245,7 @@ func getActiveSubscribers(ctx context.Context, q *query.GetActiveSubscribers) er
})
}
-func internalAddSubscriber(trx *dbx.Trx, post *models.Post, tenant *models.Tenant, user *models.User, force bool) error {
+func internalAddSubscriber(trx *dbx.Trx, post *entity.Post, tenant *entity.Tenant, user *entity.User, force bool) error {
conflict := " DO NOTHING"
if force {
conflict = "(user_id, post_id) DO UPDATE SET status = $5, updated_at = $4"
diff --git a/app/services/sqlstore/postgres/oauth.go b/app/services/sqlstore/postgres/oauth.go
index c6ac4bcae..44c12dfb9 100644
--- a/app/services/sqlstore/postgres/oauth.go
+++ b/app/services/sqlstore/postgres/oauth.go
@@ -5,8 +5,8 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/entity"
- "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"
@@ -29,8 +29,8 @@ type dbOAuthConfig struct {
JSONUserEmailPath string `db:"json_user_email_path"`
}
-func (m *dbOAuthConfig) toModel() *models.OAuthConfig {
- return &models.OAuthConfig{
+func (m *dbOAuthConfig) toModel() *entity.OAuthConfig {
+ return &entity.OAuthConfig{
ID: m.ID,
Provider: m.Provider,
DisplayName: m.DisplayName,
@@ -49,7 +49,7 @@ func (m *dbOAuthConfig) toModel() *models.OAuthConfig {
}
func getCustomOAuthConfigByProvider(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
if tenant == nil {
return app.ErrNotFound
}
@@ -73,7 +73,7 @@ func getCustomOAuthConfigByProvider(ctx context.Context, q *query.GetCustomOAuth
}
func listCustomOAuthConfig(ctx context.Context, q *query.ListCustomOAuthConfig) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
configs := []*dbOAuthConfig{}
if tenant != nil {
err := trx.Select(&configs, `
@@ -89,7 +89,7 @@ func listCustomOAuthConfig(ctx context.Context, q *query.ListCustomOAuthConfig)
}
}
- q.Result = make([]*models.OAuthConfig, len(configs))
+ q.Result = make([]*entity.OAuthConfig, len(configs))
for i, config := range configs {
q.Result[i] = config.toModel()
}
@@ -98,14 +98,14 @@ func listCustomOAuthConfig(ctx context.Context, q *query.ListCustomOAuthConfig)
}
func saveCustomOAuthConfig(ctx context.Context, c *cmd.SaveCustomOAuthConfig) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
var err error
- if c.Config.Logo.Remove {
- c.Config.Logo.BlobKey = ""
+ if c.Logo.Remove {
+ c.Logo.BlobKey = ""
}
- if c.Config.ID == 0 {
+ if c.ID == 0 {
query := `INSERT INTO oauth_providers (
tenant_id, provider, display_name, status,
client_id, client_secret, authorize_url,
@@ -114,11 +114,11 @@ func saveCustomOAuthConfig(ctx context.Context, c *cmd.SaveCustomOAuthConfig) er
) 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)
+ err = trx.Get(&c.ID, query, tenant.ID, c.Provider,
+ c.DisplayName, c.Status, c.ClientID, c.ClientSecret,
+ c.AuthorizeURL, c.ProfileURL, c.TokenURL,
+ c.Scope, c.JSONUserIDPath, c.JSONUserNamePath,
+ c.JSONUserEmailPath, c.Logo.BlobKey)
} else {
query := `
UPDATE oauth_providers
@@ -128,11 +128,11 @@ func saveCustomOAuthConfig(ctx context.Context, c *cmd.SaveCustomOAuthConfig) er
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)
+ _, err = trx.Execute(query, tenant.ID, c.ID,
+ c.DisplayName, c.Status, c.ClientID, c.ClientSecret,
+ c.AuthorizeURL, c.ProfileURL, c.TokenURL,
+ c.Scope, c.JSONUserIDPath, c.JSONUserNamePath,
+ c.JSONUserEmailPath, c.Logo.BlobKey)
}
if err != nil {
diff --git a/app/services/sqlstore/postgres/post.go b/app/services/sqlstore/postgres/post.go
index 71804d82f..57ef850f8 100644
--- a/app/services/sqlstore/postgres/post.go
+++ b/app/services/sqlstore/postgres/post.go
@@ -7,6 +7,7 @@ import (
"strconv"
"time"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/gosimple/slug"
@@ -14,7 +15,6 @@ import (
"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"
@@ -44,8 +44,8 @@ type dbPost struct {
Tags []string `db:"tags"`
}
-func (i *dbPost) toModel(ctx context.Context) *models.Post {
- post := &models.Post{
+func (i *dbPost) toModel(ctx context.Context) *entity.Post {
+ post := &entity.Post{
ID: i.ID,
Number: i.Number,
Title: i.Title,
@@ -61,13 +61,13 @@ func (i *dbPost) toModel(ctx context.Context) *models.Post {
}
if i.Response.Valid {
- post.Response = &models.PostResponse{
+ post.Response = &entity.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{
+ post.Response.Original = &entity.OriginalPost{
Number: int(i.OriginalNumber.Int64),
Slug: i.OriginalSlug.String,
Title: i.OriginalTitle.String,
@@ -170,7 +170,7 @@ var (
)
func postIsReferenced(ctx context.Context, q *query.PostIsReferenced) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
q.Result = false
exists, err := trx.Exists(`
@@ -190,7 +190,7 @@ func postIsReferenced(ctx context.Context, q *query.PostIsReferenced) error {
}
func setPostResponse(ctx context.Context, c *cmd.SetPostResponse) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
if c.Status == enum.PostDuplicate {
return errors.New("Use MarkAsDuplicate to change an post status to Duplicate")
}
@@ -210,7 +210,7 @@ func setPostResponse(ctx context.Context, c *cmd.SetPostResponse) error {
}
c.Post.Status = c.Status
- c.Post.Response = &models.PostResponse{
+ c.Post.Response = &entity.PostResponse{
Text: c.Text,
RespondedAt: respondedAt,
User: user,
@@ -220,7 +220,7 @@ func setPostResponse(ctx context.Context, c *cmd.SetPostResponse) error {
}
func markPostAsDuplicate(ctx context.Context, c *cmd.MarkPostAsDuplicate) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
respondedAt := time.Now()
if c.Post.Status == enum.PostDuplicate && c.Post.Response != nil {
respondedAt = c.Post.Response.RespondedAt
@@ -249,10 +249,10 @@ func markPostAsDuplicate(ctx context.Context, c *cmd.MarkPostAsDuplicate) error
}
c.Post.Status = enum.PostDuplicate
- c.Post.Response = &models.PostResponse{
+ c.Post.Response = &entity.PostResponse{
RespondedAt: respondedAt,
User: user,
- Original: &models.OriginalPost{
+ Original: &entity.OriginalPost{
Number: c.Original.Number,
Title: c.Original.Title,
Slug: c.Original.Slug,
@@ -264,7 +264,7 @@ func markPostAsDuplicate(ctx context.Context, c *cmd.MarkPostAsDuplicate) error
}
func countPostPerStatus(ctx context.Context, q *query.CountPostPerStatus) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
type dbStatusCount struct {
Status enum.PostStatus `db:"status"`
@@ -286,7 +286,7 @@ func countPostPerStatus(ctx context.Context, q *query.CountPostPerStatus) error
}
func addNewPost(ctx context.Context, c *cmd.AddNewPost) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
var id int
err := trx.Get(&id,
`INSERT INTO posts (title, slug, number, description, tenant_id, user_id, created_at, status)
@@ -311,7 +311,7 @@ func addNewPost(ctx context.Context, c *cmd.AddNewPost) error {
}
func updatePost(ctx context.Context, c *cmd.UpdatePost) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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 {
@@ -328,7 +328,7 @@ func updatePost(ctx context.Context, c *cmd.UpdatePost) error {
}
func getPostByID(ctx context.Context, q *query.GetPostByID) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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)
@@ -339,7 +339,7 @@ func getPostByID(ctx context.Context, q *query.GetPostByID) error {
}
func getPostBySlug(ctx context.Context, q *query.GetPostBySlug) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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)
@@ -350,7 +350,7 @@ func getPostBySlug(ctx context.Context, q *query.GetPostBySlug) error {
}
func getPostByNumber(ctx context.Context, q *query.GetPostByNumber) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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)
@@ -361,7 +361,7 @@ func getPostByNumber(ctx context.Context, q *query.GetPostByNumber) error {
}
func searchPosts(ctx context.Context, q *query.SearchPosts) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
innerQuery := buildPostQuery(user, "p.tenant_id = $1 AND p.status = ANY($2)")
if q.Tags == nil {
@@ -408,7 +408,7 @@ func searchPosts(ctx context.Context, q *query.SearchPosts) error {
return errors.Wrap(err, "failed to search posts")
}
- q.Result = make([]*models.Post, len(posts))
+ q.Result = make([]*entity.Post, len(posts))
for i, post := range posts {
q.Result[i] = post.toModel(ctx)
}
@@ -417,7 +417,7 @@ func searchPosts(ctx context.Context, q *query.SearchPosts) error {
}
func getAllPosts(ctx context.Context, q *query.GetAllPosts) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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")
@@ -427,7 +427,7 @@ func getAllPosts(ctx context.Context, q *query.GetAllPosts) error {
})
}
-func querySinglePost(ctx context.Context, trx *dbx.Trx, query string, args ...interface{}) (*models.Post, error) {
+func querySinglePost(ctx context.Context, trx *dbx.Trx, query string, args ...interface{}) (*entity.Post, error) {
post := dbPost{}
if err := trx.Get(&post, query, args...); err != nil {
@@ -437,7 +437,7 @@ func querySinglePost(ctx context.Context, trx *dbx.Trx, query string, args ...in
return post.toModel(ctx), nil
}
-func buildPostQuery(user *models.User, filter string) string {
+func buildPostQuery(user *entity.User, filter string) string {
tagCondition := `AND tags.is_public = true`
if user != nil && user.IsCollaborator() {
tagCondition = ``
diff --git a/app/services/sqlstore/postgres/post_test.go b/app/services/sqlstore/postgres/post_test.go
index 0cb3ed5ed..dccd2ab02 100644
--- a/app/services/sqlstore/postgres/post_test.go
+++ b/app/services/sqlstore/postgres/post_test.go
@@ -5,11 +5,11 @@ import (
"testing"
"time"
+ "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"
- "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"
@@ -582,10 +582,10 @@ func TestPostStorage_Attachments(t *testing.T) {
err = bus.Dispatch(jonSnowCtx, &cmd.SetAttachments{
Post: newPost1.Result,
- Attachments: []*models.ImageUpload{
- &models.ImageUpload{
+ Attachments: []*dto.ImageUpload{
+ {
BlobKey: "12345-test.png",
- Upload: &models.ImageUploadData{
+ Upload: &dto.ImageUploadData{
FileName: "test.png",
ContentType: "image/png",
Content: bytes,
@@ -603,22 +603,22 @@ func TestPostStorage_Attachments(t *testing.T) {
err = bus.Dispatch(jonSnowCtx, &cmd.SetAttachments{
Post: newPost2.Result,
- Attachments: []*models.ImageUpload{
- &models.ImageUpload{
+ Attachments: []*dto.ImageUpload{
+ {
BlobKey: "12345-test.png",
Remove: true,
},
- &models.ImageUpload{
+ {
BlobKey: "67890-test2.png",
- Upload: &models.ImageUploadData{
+ Upload: &dto.ImageUploadData{
FileName: "test2.png",
ContentType: "image/png",
Content: bytes,
},
},
- &models.ImageUpload{
+ {
BlobKey: "67890-test6.png",
- Upload: &models.ImageUploadData{
+ Upload: &dto.ImageUploadData{
FileName: "test6.png",
ContentType: "image/png",
Content: bytes,
@@ -638,8 +638,8 @@ func TestPostStorage_Attachments(t *testing.T) {
err = bus.Dispatch(jonSnowCtx, &cmd.SetAttachments{
Post: newPost1.Result,
- Attachments: []*models.ImageUpload{
- &models.ImageUpload{
+ Attachments: []*dto.ImageUpload{
+ {
BlobKey: "12345-test.png",
Remove: true,
},
diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.go
index 3e72c5c02..fffab4a1b 100644
--- a/app/services/sqlstore/postgres/postgres.go
+++ b/app/services/sqlstore/postgres/postgres.go
@@ -5,7 +5,7 @@ import (
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/dbx"
)
@@ -117,11 +117,11 @@ func (s Service) Init() {
bus.AddHandler(saveCustomOAuthConfig)
}
-type SqlHandler func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error
+type SqlHandler func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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)
+ tenant, _ := ctx.Value(app.TenantCtxKey).(*entity.Tenant)
+ user, _ := ctx.Value(app.UserCtxKey).(*entity.User)
return handler(trx, tenant, user)
}
diff --git a/app/services/sqlstore/postgres/setup_test.go b/app/services/sqlstore/postgres/setup_test.go
index 74738d0dc..f138b71a9 100644
--- a/app/services/sqlstore/postgres/setup_test.go
+++ b/app/services/sqlstore/postgres/setup_test.go
@@ -6,6 +6,7 @@ import (
"os"
"testing"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/services/sqlstore/postgres"
@@ -13,7 +14,6 @@ import (
"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"
@@ -21,13 +21,13 @@ import (
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 demoTenant *entity.Tenant
+var avengersTenant *entity.Tenant
+var gotTenant *entity.Tenant
+var jonSnow *entity.User
+var aryaStark *entity.User
+var sansaStark *entity.User
+var tonyStark *entity.User
var demoTenantCtx context.Context
var avengersTenantCtx context.Context
diff --git a/app/services/sqlstore/postgres/tag.go b/app/services/sqlstore/postgres/tag.go
index 848f4f59f..b5140f8f5 100644
--- a/app/services/sqlstore/postgres/tag.go
+++ b/app/services/sqlstore/postgres/tag.go
@@ -5,8 +5,8 @@ import (
"fmt"
"time"
- "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/dbx"
"github.com/getfider/fider/app/pkg/errors"
@@ -21,8 +21,8 @@ type dbTag struct {
IsPublic bool `db:"is_public"`
}
-func (t *dbTag) toModel() *models.Tag {
- return &models.Tag{
+func (t *dbTag) toModel() *entity.Tag {
+ return &entity.Tag{
ID: t.ID,
Name: t.Name,
Slug: t.Slug,
@@ -32,7 +32,7 @@ func (t *dbTag) toModel() *models.Tag {
}
func getTagBySlug(ctx context.Context, q *query.GetTagBySlug) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
tag, err := queryTagBySlug(trx, tenant, q.Slug)
q.Result = tag
return err
@@ -40,8 +40,8 @@ func getTagBySlug(ctx context.Context, q *query.GetTagBySlug) error {
}
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)
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ q.Result = make([]*entity.Tag, 0)
tags, err := queryTags(trx, `
SELECT t.id, t.name, t.slug, t.color, t.is_public
@@ -63,8 +63,8 @@ func getAssignedTags(ctx context.Context, q *query.GetAssignedTags) error {
}
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)
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ q.Result = make([]*entity.Tag, 0)
condition := `AND t.is_public = true`
if user != nil && user.IsCollaborator() {
@@ -88,7 +88,7 @@ func getAllTags(ctx context.Context, q *query.GetAllTags) error {
}
func addNewTag(ctx context.Context, c *cmd.AddNewTag) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
c.Result = nil
newSlug := slug.Make(c.Name)
@@ -107,7 +107,7 @@ func addNewTag(ctx context.Context, c *cmd.AddNewTag) error {
}
func updateTag(ctx context.Context, c *cmd.UpdateTag) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
c.Result = nil
newSlug := slug.Make(c.Name)
@@ -124,7 +124,7 @@ func updateTag(ctx context.Context, c *cmd.UpdateTag) error {
}
func deleteTag(ctx context.Context, c *cmd.DeleteTag) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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)
@@ -139,7 +139,7 @@ func deleteTag(ctx context.Context, c *cmd.DeleteTag) error {
}
func assignTag(ctx context.Context, c *cmd.AssignTag) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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")
@@ -162,7 +162,7 @@ func assignTag(ctx context.Context, c *cmd.AssignTag) error {
}
func unassignTag(ctx context.Context, c *cmd.UnassignTag) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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,
@@ -175,7 +175,7 @@ func unassignTag(ctx context.Context, c *cmd.UnassignTag) error {
})
}
-func queryTagBySlug(trx *dbx.Trx, tenant *models.Tenant, slug string) (*models.Tag, error) {
+func queryTagBySlug(trx *dbx.Trx, tenant *entity.Tenant, slug string) (*entity.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)
@@ -186,14 +186,14 @@ func queryTagBySlug(trx *dbx.Trx, tenant *models.Tenant, slug string) (*models.T
return tag.toModel(), nil
}
-func queryTags(trx *dbx.Trx, query string, args ...interface{}) ([]*models.Tag, error) {
+func queryTags(trx *dbx.Trx, query string, args ...interface{}) ([]*entity.Tag, error) {
tags := []*dbTag{}
err := trx.Select(&tags, query, args...)
if err != nil {
return nil, err
}
- var result = make([]*models.Tag, len(tags))
+ var result = make([]*entity.Tag, len(tags))
for i, tag := range tags {
result[i] = tag.toModel()
}
diff --git a/app/services/sqlstore/postgres/tenant.go b/app/services/sqlstore/postgres/tenant.go
index 5b1023c89..8ea3d0fef 100644
--- a/app/services/sqlstore/postgres/tenant.go
+++ b/app/services/sqlstore/postgres/tenant.go
@@ -7,10 +7,10 @@ import (
"github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/entity"
"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"
@@ -29,12 +29,12 @@ type dbTenant struct {
CustomCSS string `db:"custom_css"`
}
-func (t *dbTenant) toModel() *models.Tenant {
+func (t *dbTenant) toModel() *entity.Tenant {
if t == nil {
return nil
}
- tenant := &models.Tenant{
+ tenant := &entity.Tenant{
ID: t.ID,
Name: t.Name,
Subdomain: t.Subdomain,
@@ -62,8 +62,8 @@ type dbEmailVerification struct {
VerifiedAt dbx.NullTime `db:"verified_at"`
}
-func (t *dbEmailVerification) toModel() *models.EmailVerification {
- model := &models.EmailVerification{
+func (t *dbEmailVerification) toModel() *entity.EmailVerification {
+ model := &entity.EmailVerification{
Name: t.Name,
Email: t.Email,
Key: t.Key,
@@ -85,7 +85,7 @@ func (t *dbEmailVerification) toModel() *models.EmailVerification {
}
func isCNAMEAvailable(ctx context.Context, q *query.IsCNAMEAvailable) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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
@@ -97,7 +97,7 @@ func isCNAMEAvailable(ctx context.Context, q *query.IsCNAMEAvailable) error {
}
func isSubdomainAvailable(ctx context.Context, q *query.IsSubdomainAvailable) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
exists, err := trx.Exists("SELECT id FROM tenants WHERE subdomain = $1", q.Subdomain)
if err != nil {
q.Result = false
@@ -109,8 +109,8 @@ func isSubdomainAvailable(ctx context.Context, q *query.IsSubdomainAvailable) er
}
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)
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ _, err := trx.Execute("UPDATE tenants SET is_private = $1 WHERE id = $2", c.IsPrivate, tenant.ID)
if err != nil {
return errors.Wrap(err, "failed update tenant privacy settings")
}
@@ -119,41 +119,41 @@ func updateTenantPrivacySettings(ctx context.Context, c *cmd.UpdateTenantPrivacy
}
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 = ""
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ if c.Logo.Remove {
+ c.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)
+ _, err := trx.Execute(query, c.Title, c.Invitation, c.WelcomeMessage, c.CNAME, c.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
+ tenant.Name = c.Title
+ tenant.Invitation = c.Invitation
+ tenant.CNAME = c.CNAME
+ tenant.WelcomeMessage = c.WelcomeMessage
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 {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
query := "UPDATE tenants SET custom_css = $1 WHERE id = $2"
- _, err := trx.Execute(query, c.Settings.CustomCSS, tenant.ID)
+ _, err := trx.Execute(query, c.CustomCSS, tenant.ID)
if err != nil {
return errors.Wrap(err, "failed update tenant advanced settings")
}
- tenant.CustomCSS = c.Settings.CustomCSS
+ tenant.CustomCSS = c.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 {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
query := "UPDATE tenants SET status = $1 WHERE id = $2"
_, err := trx.Execute(query, enum.TenantActive, c.TenantID)
if err != nil {
@@ -164,7 +164,7 @@ func activateTenant(ctx context.Context, c *cmd.ActivateTenant) error {
}
func getVerificationByKey(ctx context.Context, q *query.GetVerificationByKey) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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"
@@ -179,7 +179,7 @@ func getVerificationByKey(ctx context.Context, q *query.GetVerificationByKey) er
}
func saveVerificationKey(ctx context.Context, c *cmd.SaveVerificationKey) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
var userID interface{}
if c.Request.GetUser() != nil {
userID = c.Request.GetUser().ID
@@ -195,7 +195,7 @@ func saveVerificationKey(ctx context.Context, c *cmd.SaveVerificationKey) error
}
func setKeyAsVerified(ctx context.Context, c *cmd.SetKeyAsVerified) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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 {
@@ -206,7 +206,7 @@ func setKeyAsVerified(ctx context.Context, c *cmd.SetKeyAsVerified) error {
}
func createTenant(ctx context.Context, c *cmd.CreateTenant) error {
- return using(ctx, func(trx *dbx.Trx, _ *models.Tenant, _ *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {
now := time.Now()
var id int
@@ -226,7 +226,7 @@ func createTenant(ctx context.Context, c *cmd.CreateTenant) error {
}
func getFirstTenant(ctx context.Context, q *query.GetFirstTenant) error {
- return using(ctx, func(trx *dbx.Trx, _ *models.Tenant, _ *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {
tenant := dbTenant{}
err := trx.Get(&tenant, `
@@ -245,7 +245,7 @@ func getFirstTenant(ctx context.Context, q *query.GetFirstTenant) error {
}
func getTenantByDomain(ctx context.Context, q *query.GetTenantByDomain) error {
- return using(ctx, func(trx *dbx.Trx, _ *models.Tenant, _ *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {
tenant := dbTenant{}
err := trx.Get(&tenant, `
diff --git a/app/services/sqlstore/postgres/tenant_test.go b/app/services/sqlstore/postgres/tenant_test.go
index 5d6ddbf80..d4ba713f3 100644
--- a/app/services/sqlstore/postgres/tenant_test.go
+++ b/app/services/sqlstore/postgres/tenant_test.go
@@ -5,10 +5,11 @@ import (
"time"
"github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/actions"
+ "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/models"
"github.com/getfider/fider/app/models/cmd"
"github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/env"
@@ -95,7 +96,7 @@ func TestTenantStorage_UpdatePrivacy(t *testing.T) {
defer TeardownDatabaseTest()
setPrivate := &cmd.UpdateTenantPrivacySettings{
- Settings: &models.UpdateTenantPrivacy{IsPrivate: true},
+ IsPrivate: true,
}
getByDomain := &query.GetTenantByDomain{
Domain: "demo",
@@ -122,11 +123,9 @@ func TestTenantStorage_GetByDomain_CNAME(t *testing.T) {
defer TeardownDatabaseTest()
err := bus.Dispatch(demoTenantCtx, &cmd.UpdateTenantSettings{
- Settings: &models.UpdateTenantSettings{
- Title: "My Domain Inc.",
- CNAME: "feedback.mycompany.com",
- Logo: &models.ImageUpload{},
- },
+ Title: "My Domain Inc.",
+ CNAME: "feedback.mycompany.com",
+ Logo: &dto.ImageUpload{},
})
Expect(err).IsNil()
@@ -164,16 +163,15 @@ func TestTenantStorage_UpdateSettings(t *testing.T) {
SetupDatabaseTest(t)
defer TeardownDatabaseTest()
- settings := &models.UpdateTenantSettings{
- Logo: &models.ImageUpload{
+ err := bus.Dispatch(demoTenantCtx, &cmd.UpdateTenantSettings{
+ Logo: &dto.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"}
@@ -191,10 +189,9 @@ func TestTenantStorage_AdvancedSettings(t *testing.T) {
SetupDatabaseTest(t)
defer TeardownDatabaseTest()
- settings := &models.UpdateTenantAdvancedSettings{
+ err := bus.Dispatch(demoTenantCtx, &cmd.UpdateTenantAdvancedSettings{
CustomCSS: ".primary { color: red; }",
- }
- err := bus.Dispatch(demoTenantCtx, &cmd.UpdateTenantAdvancedSettings{Settings: settings})
+ })
Expect(err).IsNil()
getByDomain := &query.GetTenantByDomain{Domain: "demo"}
@@ -211,7 +208,7 @@ func TestTenantStorage_SaveFindSet_VerificationKey(t *testing.T) {
err := bus.Dispatch(demoTenantCtx, &cmd.SaveVerificationKey{
Key: "s3cr3tk3y",
Duration: 15 * time.Minute,
- Request: &models.CreateTenant{
+ Request: &actions.CreateTenant{
Name: "Jon Snow",
},
@@ -264,7 +261,7 @@ func TestTenantStorage_SaveFindSet_ChangeEmailVerificationKey(t *testing.T) {
err := bus.Dispatch(demoTenantCtx, &cmd.SaveVerificationKey{
Key: "th3-s3cr3t",
Duration: 15 * time.Minute,
- Request: &models.ChangeUserEmail{
+ Request: &actions.ChangeUserEmail{
Requestor: jonSnow,
},
@@ -306,22 +303,20 @@ func TestTenantStorage_Save_Get_ListOAuthConfig(t *testing.T) {
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",
+ Logo: &dto.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()
@@ -343,23 +338,21 @@ func TestTenantStorage_Save_Get_ListOAuthConfig(t *testing.T) {
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",
+ ID: getConfig.Result.ID,
+ Logo: &dto.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()
diff --git a/app/services/sqlstore/postgres/user.go b/app/services/sqlstore/postgres/user.go
index 4be35cf6c..8f836eab5 100644
--- a/app/services/sqlstore/postgres/user.go
+++ b/app/services/sqlstore/postgres/user.go
@@ -8,8 +8,8 @@ import (
"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/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/dbx"
@@ -33,19 +33,19 @@ type dbUserProvider struct {
UID sql.NullString `db:"provider_uid"`
}
-func (u *dbUser) toModel(ctx context.Context) *models.User {
+func (u *dbUser) toModel(ctx context.Context) *entity.User {
if u == nil {
return nil
}
avatarType := enum.AvatarType(u.AvatarType.Int64)
- user := &models.User{
+ user := &entity.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)),
+ Providers: make([]*entity.UserProvider, len(u.Providers)),
Status: enum.UserStatus(u.Status.Int64),
AvatarType: avatarType,
AvatarBlobKey: u.AvatarBlobKey.String,
@@ -53,7 +53,7 @@ func (u *dbUser) toModel(ctx context.Context) *models.User {
}
for i, p := range u.Providers {
- user.Providers[i] = &models.UserProvider{
+ user.Providers[i] = &entity.UserProvider{
Name: p.Name.String,
UID: p.UID.String,
}
@@ -68,7 +68,7 @@ type dbUserSetting struct {
}
func countUsers(ctx context.Context, q *query.CountUsers) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
var count int
err := trx.Scalar(&count, "SELECT COUNT(*) FROM users WHERE tenant_id = $1", tenant.ID)
if err != nil {
@@ -80,7 +80,7 @@ func countUsers(ctx context.Context, q *query.CountUsers) error {
}
func blockUser(ctx context.Context, c *cmd.BlockUser) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
if _, err := trx.Execute(
"UPDATE users SET status = $3 WHERE id = $1 AND tenant_id = $2",
c.UserID, tenant.ID, enum.UserBlocked,
@@ -92,7 +92,7 @@ func blockUser(ctx context.Context, c *cmd.BlockUser) error {
}
func unblockUser(ctx context.Context, c *cmd.UnblockUser) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
if _, err := trx.Execute(
"UPDATE users SET status = $3 WHERE id = $1 AND tenant_id = $2",
c.UserID, tenant.ID, enum.UserActive,
@@ -104,7 +104,7 @@ func unblockUser(ctx context.Context, c *cmd.UnblockUser) error {
}
func deleteCurrentUser(ctx context.Context, c *cmd.DeleteCurrentUser) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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,
@@ -139,8 +139,8 @@ func deleteCurrentUser(ctx context.Context, c *cmd.DeleteCurrentUser) error {
}
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()
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ apiKey := entity.GenerateEmailVerificationKey()
if _, err := trx.Execute(
"UPDATE users SET api_key = $3, api_key_date = $4 WHERE id = $1 AND tenant_id = $2",
@@ -155,7 +155,7 @@ func regenerateAPIKey(ctx context.Context, c *cmd.RegenerateAPIKey) error {
}
func getUserByAPIKey(ctx context.Context, q *query.GetUserByAPIKey) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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)
@@ -166,7 +166,7 @@ func getUserByAPIKey(ctx context.Context, q *query.GetUserByAPIKey) error {
}
func userSubscribedTo(ctx context.Context, q *query.UserSubscribedTo) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
if user == nil {
q.Result = false
return nil
@@ -202,7 +202,7 @@ func userSubscribedTo(ctx context.Context, q *query.UserSubscribedTo) error {
}
func changeUserRole(ctx context.Context, c *cmd.ChangeUserRole) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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 {
@@ -213,7 +213,7 @@ func changeUserRole(ctx context.Context, c *cmd.ChangeUserRole) error {
}
func changeUserEmail(ctx context.Context, c *cmd.ChangeUserEmail) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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 {
@@ -224,7 +224,7 @@ func changeUserEmail(ctx context.Context, c *cmd.ChangeUserEmail) error {
}
func updateCurrentUserSettings(ctx context.Context, c *cmd.UpdateCurrentUserSettings) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
if user != nil && c.Settings != nil && len(c.Settings) > 0 {
query := `
INSERT INTO user_settings (tenant_id, user_id, key, value)
@@ -244,7 +244,7 @@ func updateCurrentUserSettings(ctx context.Context, c *cmd.UpdateCurrentUserSett
}
func getCurrentUserSettings(ctx context.Context, q *query.GetCurrentUserSettings) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
q.Result = make(map[string]string)
var settings []*dbUserSetting
@@ -270,7 +270,7 @@ func getCurrentUserSettings(ctx context.Context, q *query.GetCurrentUserSettings
}
func registerUser(ctx context.Context, c *cmd.RegisterUser) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, _ *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, _ *entity.User) error {
now := time.Now()
c.User.Status = enum.UserActive
c.User.Email = strings.ToLower(strings.TrimSpace(c.User.Email))
@@ -292,7 +292,7 @@ func registerUser(ctx context.Context, c *cmd.RegisterUser) error {
}
func registerUserProvider(ctx context.Context, c *cmd.RegisterUserProvider) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.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 {
@@ -303,7 +303,7 @@ func registerUserProvider(ctx context.Context, c *cmd.RegisterUserProvider) erro
}
func updateCurrentUser(ctx context.Context, c *cmd.UpdateCurrentUser) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
if c.Avatar.Remove {
c.Avatar.BlobKey = ""
}
@@ -317,7 +317,7 @@ func updateCurrentUser(ctx context.Context, c *cmd.UpdateCurrentUser) error {
}
func getUserByID(ctx context.Context, q *query.GetUserByID) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
u, err := queryUser(ctx, trx, "id = $1", q.UserID)
if err != nil {
return errors.Wrap(err, "failed to get user with id '%d'", q.UserID)
@@ -328,7 +328,7 @@ func getUserByID(ctx context.Context, q *query.GetUserByID) error {
}
func getUserByEmail(ctx context.Context, q *query.GetUserByEmail) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
email := strings.ToLower(q.Email)
u, err := queryUser(ctx, trx, "email = $1 AND tenant_id = $2", email, tenant.ID)
if err != nil {
@@ -340,7 +340,7 @@ func getUserByEmail(ctx context.Context, q *query.GetUserByEmail) error {
}
func getUserByProvider(ctx context.Context, q *query.GetUserByProvider) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
var userID int
if err := trx.Scalar(&userID, `
SELECT user_id
@@ -362,7 +362,7 @@ func getUserByProvider(ctx context.Context, q *query.GetUserByProvider) error {
}
func getAllUsers(ctx context.Context, q *query.GetAllUsers) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
var users []*dbUser
err := trx.Select(&users, `
SELECT id, name, email, tenant_id, role, status, avatar_type, avatar_bkey
@@ -374,7 +374,7 @@ func getAllUsers(ctx context.Context, q *query.GetAllUsers) error {
return errors.Wrap(err, "failed to get all users")
}
- q.Result = make([]*models.User, len(users))
+ q.Result = make([]*entity.User, len(users))
for i, user := range users {
q.Result[i] = user.toModel(ctx)
}
@@ -382,7 +382,7 @@ func getAllUsers(ctx context.Context, q *query.GetAllUsers) error {
})
}
-func queryUser(ctx context.Context, trx *dbx.Trx, filter string, args ...interface{}) (*models.User, error) {
+func queryUser(ctx context.Context, trx *dbx.Trx, filter string, args ...interface{}) (*entity.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...)
diff --git a/app/services/sqlstore/postgres/user_test.go b/app/services/sqlstore/postgres/user_test.go
index 9761f9ae1..98979fb4c 100644
--- a/app/services/sqlstore/postgres/user_test.go
+++ b/app/services/sqlstore/postgres/user_test.go
@@ -5,6 +5,8 @@ import (
"strings"
"testing"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
@@ -12,7 +14,6 @@ import (
"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"
)
@@ -105,11 +106,11 @@ func TestUserStorage_Register(t *testing.T) {
SetupDatabaseTest(t)
defer TeardownDatabaseTest()
- user := &models.User{
+ user := &entity.User{
Name: "Rob Stark",
Role: enum.RoleCollaborator,
- Providers: []*models.UserProvider{
+ Providers: []*entity.UserProvider{
{
UID: "123123123",
Name: app.FacebookProvider,
@@ -134,7 +135,7 @@ func TestUserStorage_Register_WhiteSpaceEmail(t *testing.T) {
SetupDatabaseTest(t)
defer TeardownDatabaseTest()
- user := &models.User{
+ user := &entity.User{
Name: "Rob Stark",
Email: " ",
Role: enum.RoleCollaborator,
@@ -164,13 +165,13 @@ func TestUserStorage_Register_MultipleProviders(t *testing.T) {
`)
Expect(err).IsNil()
- newTenantCtx := context.WithValue(ctx, app.TenantCtxKey, &models.Tenant{ID: tenantID})
+ newTenantCtx := context.WithValue(ctx, app.TenantCtxKey, &entity.Tenant{ID: tenantID})
- user := &models.User{
+ user := &entity.User{
Name: "Jon Snow",
Role: enum.RoleCollaborator,
- Providers: []*models.UserProvider{
+ Providers: []*entity.UserProvider{
{
UID: "123123123",
Name: app.FacebookProvider,
@@ -224,7 +225,7 @@ func TestUserStorage_UpdateSettings(t *testing.T) {
err := bus.Dispatch(jonSnowCtx, &cmd.UpdateCurrentUser{
Name: "Jon Stark",
- Avatar: &models.ImageUpload{
+ Avatar: &dto.ImageUpload{
BlobKey: "jon.png",
},
})
diff --git a/app/services/sqlstore/postgres/vote.go b/app/services/sqlstore/postgres/vote.go
index 14ab6492a..de578f44e 100644
--- a/app/services/sqlstore/postgres/vote.go
+++ b/app/services/sqlstore/postgres/vote.go
@@ -5,8 +5,8 @@ import (
"strconv"
"time"
- "github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/dbx"
@@ -24,10 +24,10 @@ type dbVote struct {
CreatedAt time.Time `db:"created_at"`
}
-func (v *dbVote) toModel(ctx context.Context) *models.Vote {
- vote := &models.Vote{
+func (v *dbVote) toModel(ctx context.Context) *entity.Vote {
+ vote := &entity.Vote{
CreatedAt: v.CreatedAt,
- User: &models.VoteUser{
+ User: &entity.VoteUser{
ID: v.User.ID,
Name: v.User.Name,
Email: v.User.Email,
@@ -38,7 +38,7 @@ func (v *dbVote) toModel(ctx context.Context) *models.Vote {
}
func addVote(ctx context.Context, c *cmd.AddVote) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
if !c.Post.CanBeVoted() {
return nil
}
@@ -57,7 +57,7 @@ func addVote(ctx context.Context, c *cmd.AddVote) error {
}
func removeVote(ctx context.Context, c *cmd.RemoveVote) error {
- return using(ctx, func(trx *dbx.Trx, tenant *models.Tenant, user *models.User) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
if !c.Post.CanBeVoted() {
return nil
}
@@ -72,8 +72,8 @@ func removeVote(ctx context.Context, c *cmd.RemoveVote) error {
}
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)
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ q.Result = make([]*entity.Vote, 0)
sqlLimit := "ALL"
if q.Limit > 0 {
sqlLimit = strconv.Itoa(q.Limit)
@@ -105,7 +105,7 @@ func listPostVotes(ctx context.Context, q *query.ListPostVotes) error {
return errors.Wrap(err, "failed to get votes of post")
}
- q.Result = make([]*models.Vote, len(votes))
+ q.Result = make([]*entity.Vote, len(votes))
for i, vote := range votes {
q.Result[i] = vote.toModel(ctx)
}
diff --git a/app/tasks/tasks.go b/app/tasks/tasks.go
index 05e492edd..1870f79b4 100644
--- a/app/tasks/tasks.go
+++ b/app/tasks/tasks.go
@@ -8,9 +8,10 @@ import (
"time"
"github.com/getfider/fider/app"
- "github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models/cmd"
"github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
@@ -32,10 +33,10 @@ 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 {
+func SendSignUpEmail(action *actions.CreateTenant, baseURL string) worker.Task {
return describe("Send sign up email", func(c *worker.Context) error {
- to := dto.NewRecipient(model.Name, model.Email, dto.Props{
- "link": link(baseURL, "/signup/verify?k=%s", model.VerificationKey),
+ to := dto.NewRecipient(action.Name, action.Email, dto.Props{
+ "link": link(baseURL, "/signup/verify?k=%s", action.VerificationKey),
})
bus.Publish(c, &cmd.SendMail{
@@ -52,11 +53,11 @@ func SendSignUpEmail(model *models.CreateTenant, baseURL string) worker.Task {
}
//SendSignInEmail is used to send the sign in email to requestor
-func SendSignInEmail(model *models.SignInByEmail) worker.Task {
+func SendSignInEmail(email, verificationKey string) worker.Task {
return describe("Send sign in email", func(c *worker.Context) error {
- to := dto.NewRecipient("", model.Email, dto.Props{
+ to := dto.NewRecipient("", email, dto.Props{
"tenantName": c.Tenant().Name,
- "link": link(web.BaseURL(c), "/signin/verify?k=%s", model.VerificationKey),
+ "link": link(web.BaseURL(c), "/signin/verify?k=%s", verificationKey),
})
bus.Publish(c, &cmd.SendMail{
@@ -73,7 +74,7 @@ func SendSignInEmail(model *models.SignInByEmail) worker.Task {
}
//SendChangeEmailConfirmation is used to send the change email confirmation email to requestor
-func SendChangeEmailConfirmation(model *models.ChangeUserEmail) worker.Task {
+func SendChangeEmailConfirmation(action *actions.ChangeUserEmail) worker.Task {
return describe("Send change email confirmation", func(c *worker.Context) error {
previous := c.User().Email
@@ -81,11 +82,11 @@ func SendChangeEmailConfirmation(model *models.ChangeUserEmail) worker.Task {
previous = "(empty)"
}
- to := dto.NewRecipient(model.Requestor.Name, model.Email, dto.Props{
+ to := dto.NewRecipient(action.Requestor.Name, action.Email, dto.Props{
"name": c.User().Name,
"oldEmail": previous,
- "newEmail": model.Email,
- "link": link(web.BaseURL(c), "/change-email/verify?k=%s", model.VerificationKey),
+ "newEmail": action.Email,
+ "link": link(web.BaseURL(c), "/change-email/verify?k=%s", action.VerificationKey),
})
bus.Publish(c, &cmd.SendMail{
@@ -102,7 +103,7 @@ func SendChangeEmailConfirmation(model *models.ChangeUserEmail) worker.Task {
}
//NotifyAboutNewPost sends a notification (web and email) to subscribers
-func NotifyAboutNewPost(post *models.Post) worker.Task {
+func NotifyAboutNewPost(post *entity.Post) worker.Task {
return describe("Notify about new post", func(c *worker.Context) error {
// Web notification
users, err := getActiveSubscribers(c, post, enum.NotificationChannelWeb, enum.NotificationEventNewPost)
@@ -162,7 +163,7 @@ func NotifyAboutNewPost(post *models.Post) worker.Task {
}
//NotifyAboutNewComment sends a notification (web and email) to subscribers
-func NotifyAboutNewComment(post *models.Post, comment *models.NewComment) worker.Task {
+func NotifyAboutNewComment(post *entity.Post, comment string) worker.Task {
return describe("Notify about new comment", func(c *worker.Context) error {
// Web notification
users, err := getActiveSubscribers(c, post, enum.NotificationChannelWeb, enum.NotificationEventNewComment)
@@ -203,7 +204,7 @@ func NotifyAboutNewComment(post *models.Post, comment *models.NewComment) worker
"title": post.Title,
"tenantName": c.Tenant().Name,
"userName": c.User().Name,
- "content": markdown.Full(comment.Content),
+ "content": markdown.Full(comment),
"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),
@@ -223,7 +224,7 @@ func NotifyAboutNewComment(post *models.Post, comment *models.NewComment) worker
}
//NotifyAboutStatusChange sends a notification (web and email) to subscribers
-func NotifyAboutStatusChange(post *models.Post, prevStatus enum.PostStatus) worker.Task {
+func NotifyAboutStatusChange(post *entity.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 {
@@ -295,7 +296,7 @@ func NotifyAboutStatusChange(post *models.Post, prevStatus enum.PostStatus) work
}
//NotifyAboutDeletedPost sends a notification (web and email) to subscribers of the post that has been deleted
-func NotifyAboutDeletedPost(post *models.Post) worker.Task {
+func NotifyAboutDeletedPost(post *entity.Post) worker.Task {
return describe("Notify about deleted post", func(c *worker.Context) error {
// Web notification
@@ -351,7 +352,7 @@ func NotifyAboutDeletedPost(post *models.Post) worker.Task {
}
//SendInvites sends one email to each invited recipient
-func SendInvites(subject, message string, invitations []*models.UserInvitation) worker.Task {
+func SendInvites(subject, message string, invitations []*actions.UserInvitation) worker.Task {
return describe("Send invites", func(c *worker.Context) error {
to := make([]dto.Recipient, len(invitations))
for i, invite := range invitations {
@@ -385,7 +386,7 @@ func SendInvites(subject, message string, invitations []*models.UserInvitation)
})
}
-func getActiveSubscribers(ctx context.Context, post *models.Post, channel enum.NotificationChannel, event enum.NotificationEvent) ([]*models.User, error) {
+func getActiveSubscribers(ctx context.Context, post *entity.Post, channel enum.NotificationChannel, event enum.NotificationEvent) ([]*entity.User, error) {
q := &query.GetActiveSubscribers{
Number: post.Number,
Channel: channel,
diff --git a/app/tasks/tasks_test.go b/app/tasks/tasks_test.go
index 7642e43d3..912348a4c 100644
--- a/app/tasks/tasks_test.go
+++ b/app/tasks/tasks_test.go
@@ -6,10 +6,11 @@ import (
"testing"
"time"
+ "github.com/getfider/fider/app/actions"
+ "github.com/getfider/fider/app/models/entity"
"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"
@@ -24,7 +25,7 @@ func TestSendSignUpEmailTask(t *testing.T) {
bus.Init(emailmock.Service{})
worker := mock.NewWorker()
- task := tasks.SendSignUpEmail(&models.CreateTenant{
+ task := tasks.SendSignUpEmail(&actions.CreateTenant{
VerificationKey: "1234",
}, "http://domain.com")
@@ -53,9 +54,7 @@ func TestSendSignInEmailTask(t *testing.T) {
bus.Init(emailmock.Service{})
worker := mock.NewWorker()
- task := tasks.SendSignInEmail(&models.SignInByEmail{
- VerificationKey: "9876",
- })
+ task := tasks.SendSignInEmail("[email protected]", "9876")
err := worker.
OnTenant(mock.DemoTenant).
@@ -73,6 +72,7 @@ func TestSendSignInEmailTask(t *testing.T) {
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{
+ Address: "[email protected]",
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>"),
@@ -85,7 +85,7 @@ func TestSendChangeEmailConfirmationTask(t *testing.T) {
bus.Init(emailmock.Service{})
worker := mock.NewWorker()
- task := tasks.SendChangeEmailConfirmation(&models.ChangeUserEmail{
+ task := tasks.SendChangeEmailConfirmation(&actions.ChangeUserEmail{
VerificationKey: "13579",
Requestor: mock.JonSnow,
@@ -129,14 +129,14 @@ func TestNotifyAboutNewPostTask(t *testing.T) {
})
bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {
- q.Result = []*models.User{
+ q.Result = []*entity.User{
mock.AryaStark,
}
return nil
})
worker := mock.NewWorker()
- post := &models.Post{
+ post := &entity.Post{
ID: 1,
Number: 1,
Title: "Add support for TypeScript",
@@ -191,26 +191,21 @@ func TestNotifyAboutNewCommentTask(t *testing.T) {
})
bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {
- q.Result = []*models.User{
+ q.Result = []*entity.User{
mock.JonSnow,
}
return nil
})
worker := mock.NewWorker()
- post := &models.Post{
+ post := &entity.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",
- }
-
- task := tasks.NotifyAboutNewComment(post, comment)
+ task := tasks.NotifyAboutNewComment(post, "I agree")
err := worker.
OnTenant(mock.DemoTenant).
@@ -259,21 +254,21 @@ func TestNotifyAboutStatusChangeTask(t *testing.T) {
})
bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {
- q.Result = []*models.User{
+ q.Result = []*entity.User{
mock.AryaStark,
}
return nil
})
worker := mock.NewWorker()
- post := &models.Post{
+ post := &entity.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{
+ Response: &entity.PostResponse{
RespondedAt: time.Now(),
Text: "Planned for next release.",
User: mock.JonSnow,
@@ -330,21 +325,21 @@ func TestNotifyAboutDeletePostTask(t *testing.T) {
})
bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {
- q.Result = []*models.User{
+ q.Result = []*entity.User{
mock.AryaStark,
}
return nil
})
worker := mock.NewWorker()
- post := &models.Post{
+ post := &entity.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{
+ Response: &entity.PostResponse{
RespondedAt: time.Now(),
Text: "Invalid post!",
User: mock.JonSnow,
@@ -396,23 +391,23 @@ func TestNotifyAboutStatusChangeTask_Duplicate(t *testing.T) {
})
bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {
- q.Result = []*models.User{
+ q.Result = []*entity.User{
mock.AryaStark,
}
return nil
})
worker := mock.NewWorker()
- post := &models.Post{
+ post := &entity.Post{
ID: 2,
Number: 2,
Title: "I need TypeScript",
Slug: "i-need-typescript",
Status: enum.PostDuplicate,
- Response: &models.PostResponse{
+ Response: &entity.PostResponse{
RespondedAt: time.Now(),
User: mock.JonSnow,
- Original: &models.OriginalPost{
+ Original: &entity.OriginalPost{
Number: 1,
Title: "Add support for TypeScript",
Slug: "add-support-for-typescript",
@@ -471,7 +466,7 @@ func TestSendInvites(t *testing.T) {
})
worker := mock.NewWorker()
- task := tasks.SendInvites("My Subject", "Click here: %invite%", []*models.UserInvitation{
+ task := tasks.SendInvites("My Subject", "Click here: %invite%", []*actions.UserInvitation{
{Email: "[email protected]", VerificationKey: "1234"},
{Email: "[email protected]", VerificationKey: "5678"},
})
diff --git a/main.go b/main.go
index 9233db8c9..63e000006 100644
--- a/main.go
+++ b/main.go
@@ -2,46 +2,18 @@ package main
import (
"os"
- "runtime"
"github.com/getfider/fider/app/cmd"
- "github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/env"
_ "github.com/lib/pq"
)
-var (
- // replaced during CI build
- buildtime = ""
- // buildnumber = "local"
-
- // Use this for non-stable releases
- // version = "x.y.z-" + buildnumber
-
- // Use this for stable releases
- // version = "x.y.z"
-
- version = "0.18.1"
-)
-
func main() {
- settings := &models.SystemSettings{
- BuildTime: buildtime,
- Version: version,
- Compiler: runtime.Version(),
- Environment: env.Config.Environment,
- GoogleAnalytics: env.Config.GoogleAnalytics,
- Mode: env.Config.HostMode,
- Domain: env.MultiTenantDomain(),
- HasLegal: env.HasLegal(),
- }
-
args := os.Args[1:]
if len(args) > 0 && args[0] == "ping" {
os.Exit(cmd.RunPing())
} else if len(args) > 0 && args[0] == "migrate" {
os.Exit(cmd.RunMigrate())
} else {
- os.Exit(cmd.RunServer(settings))
+ os.Exit(cmd.RunServer())
}
}
diff --git a/public/components/common/FiderVersion.tsx b/public/components/common/FiderVersion.tsx
deleted file mode 100644
index 8d618b052..000000000
--- a/public/components/common/FiderVersion.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import React from "react"
-import { useFider } from "@fider/hooks"
-
-export const FiderVersion = () => {
- const fider = useFider()
-
- return (
- <p className="text-muted mt-2 text-center sm:hidden md:hidden">
- Support our{" "}
- <a className="text-link" rel="noopener" target="_blank" href="http://opencollective.com/fider">
- OpenCollective
- </a>
- <br />
- Fider v{fider.settings.version}
- </p>
- )
-}
diff --git a/public/components/common/index.tsx b/public/components/common/index.tsx
index a7e31c5d8..247275343 100644
--- a/public/components/common/index.tsx
+++ b/public/components/common/index.tsx
@@ -26,7 +26,6 @@ export * from "./UserName"
export * from "./Loader"
export * from "./Logo"
export * from "./Toggle"
-export * from "./FiderVersion"
export * from "./PoweredByFider"
export * from "./PageTitle"
export * from "./Dropdown"
diff --git a/public/models/settings.ts b/public/models/settings.ts
index ee365c842..298970e06 100644
--- a/public/models/settings.ts
+++ b/public/models/settings.ts
@@ -11,10 +11,8 @@ export interface OAuthProviderOption {
export interface SystemSettings {
mode: string
- buildTime: string
version: string
environment: string
- compiler: string
domain: string
hasLegal: boolean
baseURL: string
diff --git a/public/pages/Administration/components/SideMenu.tsx b/public/pages/Administration/components/SideMenu.tsx
index 546dda520..e7e14a6e8 100644
--- a/public/pages/Administration/components/SideMenu.tsx
+++ b/public/pages/Administration/components/SideMenu.tsx
@@ -2,7 +2,7 @@ import "./SideMenu.scss"
import React, { useState } from "react"
import { classSet } from "@fider/services"
-import { FiderVersion, Icon } from "@fider/components"
+import { Icon } from "@fider/components"
import { useFider } from "@fider/hooks"
import IconX from "@fider/assets/images/heroicons-x.svg"
import IconMenu from "@fider/assets/images/heroicons-menu.svg"
@@ -53,7 +53,6 @@ export const SideMenu = (props: SiteMenuProps) => {
</>
)}
</VStack>
- <FiderVersion />
</div>
)
}