Open platform to collect and prioritize feedback
adjustments after code review
Kevin Papst082512bef309
diff --git a/app/actions/signin.go b/app/actions/signin.goindex 28efb1eac..c5f4bf61f 100644--- a/app/actions/signin.go+++ b/app/actions/signin.go@@ -133,8 +133,8 @@ func NewSignInByEmailWithName() *SignInByEmailWithName {// IsAuthorized returns true if current user is authorized to perform this actionfunc (action *SignInByEmailWithName) IsAuthorized(ctx context.Context, user *entity.User) bool {tenant := ctx.Value(app.TenantCtxKey).(*entity.Tenant)- // New users can only sign in if tenant allows email auth or is not private- return tenant.IsEmailAuthAllowed || !tenant.IsPrivate+ // Reject before any user lookup, so the response doesn't reveal which emails are registered+ return tenant.IsSignUpAllowed()}// Validate if current model is valid@@ -203,5 +203,10 @@ func (action *CompleteProfile) Validate(ctx context.Context, user *entity.User)result.AddFieldFailure("key", propertyIsRequired(ctx, "key"))}+ // Only sign in and invitation keys can be used to create a new account+ if action.Kind != enum.EmailVerificationKindSignIn && action.Kind != enum.EmailVerificationKindUserInvitation {+ result.AddFieldFailure("kind", "Invalid verification kind")+ }+return result}diff --git a/app/actions/signin_test.go b/app/actions/signin_test.goindex 35b81f772..f3188823d 100644--- a/app/actions/signin_test.go+++ b/app/actions/signin_test.go@@ -6,6 +6,7 @@ import ("testing""github.com/getfider/fider/app/actions"+ "github.com/getfider/fider/app/models/enum". "github.com/getfider/fider/app/pkg/assert")@@ -76,7 +77,7 @@ func TestSignInByEmailWithName_VerificationCodeNotOverwrittenByJSON(t *testing.Tfunc TestCompleteProfile_EmptyNameAndKey(t *testing.T) {RegisterT(t)- action := actions.CompleteProfile{}+ action := actions.CompleteProfile{Kind: enum.EmailVerificationKindSignIn}result := action.Validate(context.Background(), nil)ExpectFailed(result, "name", "key")}@@ -85,12 +86,23 @@ func TestCompleteProfile_LongName(t *testing.T) {RegisterT(t)action := actions.CompleteProfile{+ Kind: enum.EmailVerificationKindSignIn,Name: "123456789012345678901234567890123456789012345678901", // 51 chars}result := action.Validate(context.Background(), nil)ExpectFailed(result, "name", "key")}+func TestCompleteProfile_InvalidKind(t *testing.T) {+ RegisterT(t)++ for _, kind := range []enum.EmailVerificationKind{0, enum.EmailVerificationKindSignUp, enum.EmailVerificationKindChangeEmail} {+ action := actions.CompleteProfile{Kind: kind, Key: "1234567890", Name: "Hot Pie"}+ result := action.Validate(context.Background(), nil)+ ExpectFailed(result, "kind")+ }+}+func TestVerifySignInCode_EmptyEmail(t *testing.T) {RegisterT(t)diff --git a/app/actions/tenant.go b/app/actions/tenant.goindex ce2f56630..41f25360f 100644--- a/app/actions/tenant.go+++ b/app/actions/tenant.go@@ -290,7 +290,7 @@ type UpdateTenantPrivacySettings struct {IsPrivate bool `json:"isPrivate"`IsFeedEnabled bool `json:"isFeedEnabled"`IsModerationEnabled bool `json:"isModerationEnabled"`- IsSignUpDisabled bool `json:"isSignUpDisabled"`+ IsSignUpDisabled *bool `json:"isSignUpDisabled"`}// IsAuthorized returns true if current user is authorized to perform this actiondiff --git a/app/handlers/admin.go b/app/handlers/admin.goindex 1c5d2de37..5a6655ce7 100644--- a/app/handlers/admin.go+++ b/app/handlers/admin.go@@ -104,11 +104,17 @@ func UpdatePrivacySettings() web.HandlerFunc {return c.HandleValidation(result)}+ // Keep the current value if the field is missing, e.g. from an outdated frontend+ isSignUpDisabled := c.Tenant().IsSignUpDisabled+ if action.IsSignUpDisabled != nil {+ isSignUpDisabled = *action.IsSignUpDisabled+ }+updateSettings := &cmd.UpdateTenantPrivacySettings{IsPrivate: action.IsPrivate,IsFeedEnabled: action.IsFeedEnabled,IsModerationEnabled: action.IsModerationEnabled,- IsSignUpDisabled: action.IsSignUpDisabled,+ IsSignUpDisabled: isSignUpDisabled,}if err := bus.Dispatch(c, updateSettings); err != nil {return c.Failure(err)diff --git a/app/handlers/admin_test.go b/app/handlers/admin_test.goindex 5aa678050..a4d344fea 100644--- a/app/handlers/admin_test.go+++ b/app/handlers/admin_test.go@@ -221,6 +221,31 @@ func TestUpdatePrivacySettingsHandler_SignUpDisabled(t *testing.T) {Expect(updateCmd.IsSignUpDisabled).IsTrue()}+func TestUpdatePrivacySettingsHandler_SignUpDisabled_MissingField(t *testing.T) {+ RegisterT(t)++ var updateCmd *cmd.UpdateTenantPrivacySettings+ bus.AddHandler(func(ctx context.Context, c *cmd.UpdateTenantPrivacySettings) error {+ updateCmd = c+ return nil+ })++ server := mock.NewServer()+ mock.DemoTenant.IsSignUpDisabled = true++ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ ExecutePost(+ handlers.UpdatePrivacySettings(),+ `{ "isPrivate": false, "isFeedEnabled": true }`,+ )++ // Requests without the field (e.g. from an outdated frontend) keep the current value+ Expect(code).Equals(http.StatusOK)+ Expect(updateCmd.IsSignUpDisabled).IsTrue()+}+func TestManageMembersHandler(t *testing.T) {RegisterT(t)diff --git a/app/handlers/oauth.go b/app/handlers/oauth.goindex c6730e3d0..62e550f44 100644--- a/app/handlers/oauth.go+++ b/app/handlers/oauth.go@@ -273,7 +273,7 @@ func OAuthToken() web.HandlerFunc {if err != nil {if errors.Cause(err) == app.ErrNotFound {isTrusted := customConfig != nil && customConfig.IsTrusted- if !c.Tenant().IsSignUpAllowed() && !isTrusted {+ if !canCreateAccount(c, isTrusted) {return c.Redirect("/not-invited")}diff --git a/app/handlers/signin.go b/app/handlers/signin.goindex a77060705..e633483c7 100644--- a/app/handlers/signin.go+++ b/app/handlers/signin.go@@ -70,6 +70,13 @@ func AccessDeniedPage() web.HandlerFunc {}}+// canCreateAccount is the single rule for every self-service account creation.+// Invited users and users from trusted OAuth providers can always create an account,+// everyone else only if the site allows sign-ups (see entity.Tenant.IsSignUpAllowed).+func canCreateAccount(c *web.Context, isInvitedOrTrusted bool) bool {+ return isInvitedOrTrusted || c.Tenant().IsSignUpAllowed()+}+// SignInByEmail checks if user exists and sends code only for existing usersfunc SignInByEmail() web.HandlerFunc {return func(c *web.Context) error {@@ -128,11 +135,6 @@ func SignInByEmailWithName() web.HandlerFunc {})}- // Check if new users are allowed to sign up (not on private sites or when sign up is disabled)- if !c.Tenant().IsSignUpAllowed() {- return c.Forbidden()- }-// Invalidate any previous active verification codes for this email_ = bus.Dispatch(c, &cmd.InvalidateVerificationsByEmail{Email: action.Email,@@ -215,7 +217,7 @@ func VerifySignInCode() web.HandlerFunc {if err != nil {if errors.Cause(err) == app.ErrNotFound {// User doesn't exist- if !c.Tenant().IsSignUpAllowed() {+ if !canCreateAccount(c, false) {return c.Forbidden()}@@ -278,6 +280,16 @@ func ResendSignInCode() web.HandlerFunc {return c.Forbidden()}+ // Unknown email addresses only get a code if they are allowed to create an account+ if !canCreateAccount(c, false) {+ if err := bus.Dispatch(c, &query.GetUserByEmail{Email: action.Email}); err != nil {+ if errors.Cause(err) == app.ErrNotFound {+ return c.Ok(web.Map{})+ }+ return c.Failure(err)+ }+ }+// Invalidate any previous active verification codes for this email_ = bus.Dispatch(c, &cmd.InvalidateVerificationsByEmail{Email: action.Email,@@ -315,7 +327,7 @@ func VerifySignInKey(kind enum.EmailVerificationKind) web.HandlerFunc {err = bus.Dispatch(c, userByEmail)if err != nil {if errors.Cause(err) == app.ErrNotFound {- if kind == enum.EmailVerificationKindSignIn && !c.Tenant().IsSignUpAllowed() {+ if !canCreateAccount(c, kind == enum.EmailVerificationKindUserInvitation) {return NotInvitedPage()(c)}@@ -387,8 +399,7 @@ func CompleteSignInProfile() web.HandlerFunc {return c.BadRequest(web.Map{})}- // Only invited users can create an account when sign up is not allowed- if action.Kind == enum.EmailVerificationKindSignIn && !c.Tenant().IsSignUpAllowed() {+ if !canCreateAccount(c, action.Kind == enum.EmailVerificationKindUserInvitation) {return c.Forbidden()}diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.goindex 20f960a17..5b1a961ce 100644--- a/app/handlers/signin_test.go+++ b/app/handlers/signin_test.go@@ -1289,3 +1289,112 @@ func TestCompleteSignInProfileHandler_SignUpDisabled_Invitation(t *testing.T) {Expect(code).Equals(http.StatusOK)ExpectFiderAuthCookie(response, newUser)}++func TestSignInByEmailWithNameHandler_SignUpDisabled_ExistingUser(t *testing.T) {+ RegisterT(t)++ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {+ q.Result = mock.JonSnow+ return nil+ })++ server := mock.NewServer()+ mock.DemoTenant.IsSignUpDisabled = true++ code, _ := server.+ OnTenant(mock.DemoTenant).+ ExecutePost(handlers.SignInByEmailWithName(), `{ "email": "[email protected]", "name": "Jon Snow" }`)++ // Same response as for unknown emails, the user lookup must not happen+ Expect(code).Equals(http.StatusForbidden)+ ExpectHandler(&query.GetUserByEmail{}).CalledTimes(0)+}++func TestResendSignInCodeHandler_SignUpDisabled_UnknownEmail(t *testing.T) {+ RegisterT(t)++ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {+ return app.ErrNotFound+ })++ bus.AddHandler(func(ctx context.Context, c *cmd.SaveVerificationKey) error {+ return nil+ })++ server := mock.NewServer()+ mock.DemoTenant.IsSignUpDisabled = true++ code, _ := server.+ OnTenant(mock.DemoTenant).+ ExecutePost(handlers.ResendSignInCode(), `{ "email": "[email protected]" }`)++ Expect(code).Equals(http.StatusOK)+ ExpectHandler(&cmd.SaveVerificationKey{}).CalledTimes(0)+}++func TestResendSignInCodeHandler_SignUpDisabled_ExistingUser(t *testing.T) {+ RegisterT(t)++ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {+ q.Result = mock.JonSnow+ return nil+ })++ bus.AddHandler(func(ctx context.Context, c *cmd.InvalidateVerificationsByEmail) error {+ return nil+ })++ var saveKeyCmd *cmd.SaveVerificationKey+ bus.AddHandler(func(ctx context.Context, c *cmd.SaveVerificationKey) error {+ saveKeyCmd = c+ return nil+ })++ server := mock.NewServer()+ mock.DemoTenant.IsSignUpDisabled = true++ code, _ := server.+ OnTenant(mock.DemoTenant).+ ExecutePost(handlers.ResendSignInCode(), `{ "email": "[email protected]" }`)++ Expect(code).Equals(http.StatusOK)+ Expect(saveKeyCmd.Request.GetEmail()).Equals("[email protected]")+}++func TestCompleteSignInProfileHandler_OtherVerificationKinds(t *testing.T) {+ for _, kind := range []enum.EmailVerificationKind{enum.EmailVerificationKindSignUp, enum.EmailVerificationKindChangeEmail} {+ RegisterT(t)++ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {+ q.Result = &entity.EmailVerification{+ Key: q.Key,+ Kind: q.Kind,+ ExpiresAt: time.Now().Add(5 * time.Minute),+ Email: "[email protected]",+ }+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {+ return app.ErrNotFound+ })++ bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {+ return nil+ })++ server := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ WithURL("http://demo.test.fider.io/signin/complete").+ ExecutePost(handlers.CompleteSignInProfile(), fmt.Sprintf(`+ {+ "name": "Hot Pie",+ "kind": %d,+ "key": "1234567890"+ }`, kind))++ Expect(code).Equals(http.StatusBadRequest)+ ExpectHandler(&cmd.RegisterUser{}).CalledTimes(0)+ }+}diff --git a/app/services/sqlstore/postgres/tenant.go b/app/services/sqlstore/postgres/tenant.goindex fb7e720f6..f2bf85f0c 100644--- a/app/services/sqlstore/postgres/tenant.go+++ b/app/services/sqlstore/postgres/tenant.go@@ -48,21 +48,14 @@ func isSubdomainAvailable(ctx context.Context, q *query.IsSubdomainAvailable) erfunc updateTenantPrivacySettings(ctx context.Context, c *cmd.UpdateTenantPrivacySettings) error {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 setting")- }- _, err = trx.Execute("UPDATE tenants SET is_feed_enabled = $1 WHERE id = $2", c.IsFeedEnabled, tenant.ID)- if err != nil {- return errors.Wrap(err, "failed update tenant feed setting")- }- _, err = trx.Execute("UPDATE tenants SET is_moderation_enabled = $1 WHERE id = $2", c.IsModerationEnabled, tenant.ID)- if err != nil {- return errors.Wrap(err, "failed update tenant moderation setting")- }- _, err = trx.Execute("UPDATE tenants SET is_signup_disabled = $1 WHERE id = $2", c.IsSignUpDisabled, tenant.ID)+ _, err := trx.Execute(`+ UPDATE tenants+ SET is_private = $1, is_feed_enabled = $2, is_moderation_enabled = $3, is_signup_disabled = $4+ WHERE id = $5`,+ c.IsPrivate, c.IsFeedEnabled, c.IsModerationEnabled, c.IsSignUpDisabled, tenant.ID,+ )if err != nil {- return errors.Wrap(err, "failed update tenant sign up setting")+ return errors.Wrap(err, "failed update tenant privacy settings")}return nil})diff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsxindex f4de52d90..519990a02 100644--- a/public/components/common/SignInControl.tsx+++ b/public/components/common/SignInControl.tsx@@ -63,7 +63,8 @@ export const SignInControl: React.FunctionComponent<SignInControlProps> = (propssetError(undefined)const data = result.data as { userExists?: boolean } | undefinedif (data && data.userExists === false) {- if (fider.session.tenant.isPrivate || fider.session.tenant.isSignUpDisabled) {+ const tenant = fider.session.tenant+ if (tenant && (tenant.isPrivate || tenant.isSignUpDisabled)) {// New users are not allowed to create an account on their ownsetError({errors: [diff --git a/public/pages/Administration/pages/PrivacySettings.page.tsx b/public/pages/Administration/pages/PrivacySettings.page.tsxindex a535e5118..3cfda3372 100644--- a/public/pages/Administration/pages/PrivacySettings.page.tsx+++ b/public/pages/Administration/pages/PrivacySettings.page.tsx@@ -27,13 +27,12 @@ export default class PrivacySettingsPage extends AdminBasePage<any, PrivacySetti}}- private updatePrivacySettings = async (isPrivate: boolean, isFeedEnabled: boolean, isModerationEnabled?: boolean, isSignUpDisabled?: boolean) => {+ private updatePrivacySettings = async (changes: Partial<PrivacySettingsPageState>) => {+ const settings = { ...this.state, ...changes }this.setState({- isPrivate,- isFeedEnabled: isPrivate ? false : isFeedEnabled, // Disable feed if site is private- isModerationEnabled: isModerationEnabled !== undefined ? isModerationEnabled : this.state.isModerationEnabled,- isSignUpDisabled: isSignUpDisabled !== undefined ? isSignUpDisabled : this.state.isSignUpDisabled,+ ...settings,+ isFeedEnabled: settings.isPrivate ? false : settings.isFeedEnabled, // Disable feed if site is private},async () => {const response = await actions.updateTenantPrivacy(this.state)@@ -45,19 +44,19 @@ export default class PrivacySettingsPage extends AdminBasePage<any, PrivacySetti}private privacyToggle = async (active: boolean) => {- this.updatePrivacySettings(active, this.state.isFeedEnabled)+ this.updatePrivacySettings({ isPrivate: active })}private atomFeedToggle = async (enabled: boolean) => {- this.updatePrivacySettings(this.state.isPrivate, enabled)+ this.updatePrivacySettings({ isFeedEnabled: enabled })}private moderationToggle = async (enabled: boolean) => {- this.updatePrivacySettings(this.state.isPrivate, this.state.isFeedEnabled, enabled)+ this.updatePrivacySettings({ isModerationEnabled: enabled })}private signUpDisabledToggle = async (disabled: boolean) => {- this.updatePrivacySettings(this.state.isPrivate, this.state.isFeedEnabled, undefined, disabled)+ this.updatePrivacySettings({ isSignUpDisabled: disabled })}public content() {