Open platform to collect and prioritize feedback
feature: added control over email authentication for admins (#976)
Théo SZANTOd2ae6d6a27d0
diff --git a/app/actions/oauth.go b/app/actions/oauth.goindex 66cfa1ebb..17bb43f6c 100644--- a/app/actions/oauth.go+++ b/app/actions/oauth.go@@ -2,6 +2,7 @@ package actionsimport ("context"+ "github.com/getfider/fider/app""strings""github.com/getfider/fider/app/models/dto"@@ -47,6 +48,18 @@ func (action *CreateEditOAuthConfig) IsAuthorized(ctx context.Context, user *entfunc (action *CreateEditOAuthConfig) Validate(ctx context.Context, user *entity.User) *validate.Result {result := validate.Success()+ if action.Status == enum.OAuthConfigDisabled {+ tenant := ctx.Value(app.TenantCtxKey).(*entity.Tenant)+ activeProviders := &query.ListActiveOAuthProviders{}+ if err := bus.Dispatch(ctx, activeProviders); err != nil {+ return validate.Failed("Cannot retrieve OAuth providers")+ }++ if !tenant.IsEmailAuthAllowed && len(activeProviders.Result) == 1 {+ result.AddFieldFailure("status", "You cannot disable this provider with neither email auth nor any other provider enabled.")+ }+ }+if action.Provider != "" {getConfig := &query.GetCustomOAuthConfigByProvider{Provider: action.Provider}err := bus.Dispatch(ctx, getConfig)diff --git a/app/actions/oauth_test.go b/app/actions/oauth_test.goindex c90b728f7..d93ff6bad 100644--- a/app/actions/oauth_test.go+++ b/app/actions/oauth_test.go@@ -2,6 +2,7 @@ package actions_testimport ("context"+ "github.com/getfider/fider/app/models/dto""testing""github.com/getfider/fider/app"@@ -17,6 +18,11 @@ import (func TestCreateEditOAuthConfig_InvalidInput(t *testing.T) {RegisterT(t)+ bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {+ q.Result = []*dto.OAuthProviderOption{}+ return nil+ })+testCases := []struct {expected []stringaction *actions.CreateEditOAuthConfig@@ -42,9 +48,12 @@ func TestCreateEditOAuthConfig_InvalidInput(t *testing.T) {},},}+ ctx := context.WithValue(context.Background(), app.TenantCtxKey, &entity.Tenant{+ IsEmailAuthAllowed: true,+ })for _, testCase := range testCases {- result := testCase.action.Validate(context.Background(), nil)+ result := testCase.action.Validate(ctx, nil)ExpectFailed(result, testCase.expected...)}}@@ -59,6 +68,11 @@ func TestCreateEditOAuthConfig_DefaultValues(t *testing.T) {func TestCreateEditOAuthConfig_AddNew_ValidInput(t *testing.T) {RegisterT(t)+ bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {+ q.Result = []*dto.OAuthProviderOption{}+ return nil+ })+action := &actions.CreateEditOAuthConfig{DisplayName: "My Provider",Status: enum.OAuthConfigEnabled,@@ -72,7 +86,11 @@ func TestCreateEditOAuthConfig_AddNew_ValidInput(t *testing.T) {JSONUserNamePath: "user.name",JSONUserEmailPath: "user.email",}- result := action.Validate(context.Background(), nil)+ ctx := context.WithValue(context.Background(), app.TenantCtxKey, &entity.Tenant{+ IsEmailAuthAllowed: true,+ })++ result := action.Validate(ctx, nil)ExpectSuccess(result)Expect(action.ID).Equals(0)Expect(action.Provider).HasLen(11)@@ -94,6 +112,11 @@ func TestCreateEditOAuthConfig_EditExisting_NewSecret(t *testing.T) {return app.ErrNotFound})+ bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {+ q.Result = []*dto.OAuthProviderOption{}+ return nil+ })+action := actions.NewCreateEditOAuthConfig()action.Provider = "_NAME"action.DisplayName = "My Provider"@@ -107,8 +130,11 @@ func TestCreateEditOAuthConfig_EditExisting_NewSecret(t *testing.T) {action.JSONUserIDPath = "user.id"action.JSONUserNamePath = "user.name"action.JSONUserEmailPath = "user.email"+ ctx := context.WithValue(context.Background(), app.TenantCtxKey, &entity.Tenant{+ IsEmailAuthAllowed: true,+ })- result := action.Validate(context.Background(), nil)+ result := action.Validate(ctx, nil)ExpectSuccess(result)Expect(action.ID).Equals(4)Expect(action.Logo.BlobKey).Equals("hello-world.png")@@ -131,6 +157,11 @@ func TestCreateEditOAuthConfig_EditExisting_OmitSecret(t *testing.T) {return app.ErrNotFound})+ bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {+ q.Result = []*dto.OAuthProviderOption{}+ return nil+ })+action := actions.NewCreateEditOAuthConfig()action.Provider = "_NAME2"action.DisplayName = "My Provider"@@ -143,8 +174,11 @@ func TestCreateEditOAuthConfig_EditExisting_OmitSecret(t *testing.T) {action.JSONUserIDPath = "user.id"action.JSONUserNamePath = "user.name"action.JSONUserEmailPath = "user.email"+ ctx := context.WithValue(context.Background(), app.TenantCtxKey, &entity.Tenant{+ IsEmailAuthAllowed: true,+ })- result := action.Validate(context.Background(), nil)+ result := action.Validate(ctx, nil)ExpectSuccess(result)Expect(action.ID).Equals(5)Expect(action.ClientSecret).Equals("MY_OLD_SECRET")@@ -157,6 +191,11 @@ func TestCreateEditOAuthConfig_EditNonExisting(t *testing.T) {return app.ErrNotFound})+ bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {+ q.Result = []*dto.OAuthProviderOption{}+ return nil+ })+action := actions.NewCreateEditOAuthConfig()action.Provider = "_MY_NEW_PROVIDER"action.DisplayName = "My Provider"@@ -169,7 +208,11 @@ func TestCreateEditOAuthConfig_EditNonExisting(t *testing.T) {action.JSONUserIDPath = "user.id"action.JSONUserNamePath = "user.name"action.JSONUserEmailPath = "user.email"- result := action.Validate(context.Background(), nil)+ ctx := context.WithValue(context.Background(), app.TenantCtxKey, &entity.Tenant{+ IsEmailAuthAllowed: true,+ })++ result := action.Validate(ctx, nil)Expect(result.Err).Equals(app.ErrNotFound)Expect(result.Ok).IsFalse()}diff --git a/app/actions/signin.go b/app/actions/signin.goindex 0c99d52eb..5d7983ccd 100644--- a/app/actions/signin.go+++ b/app/actions/signin.go@@ -2,6 +2,7 @@ package actionsimport ("context"+ "github.com/getfider/fider/app""github.com/getfider/fider/app/models/entity""github.com/getfider/fider/app/models/enum"@@ -24,7 +25,17 @@ func NewSignInByEmail() *SignInByEmail {// IsAuthorized returns true if current user is authorized to perform this actionfunc (action *SignInByEmail) IsAuthorized(ctx context.Context, user *entity.User) bool {- return true+ tenant := ctx.Value(app.TenantCtxKey).(*entity.Tenant)+ if tenant.IsEmailAuthAllowed {+ return true+ }+ getUser := &query.GetUserByEmail{+ Email: action.Email,+ }+ if err := bus.Dispatch(ctx, getUser); err != nil {+ return false+ }+ return getUser.Result != nil && getUser.Result.IsAdministrator()}// Validate if current model is validdiff --git a/app/actions/tenant.go b/app/actions/tenant.goindex bc3906ca2..a1f340913 100644--- a/app/actions/tenant.go+++ b/app/actions/tenant.go@@ -2,6 +2,8 @@ package actionsimport ("context"+ "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/dto"@@ -202,3 +204,29 @@ func (action *UpdateTenantPrivacy) IsAuthorized(ctx context.Context, user *entitfunc (action *UpdateTenantPrivacy) Validate(ctx context.Context, user *entity.User) *validate.Result {return validate.Success()}++// UpdateTenantEmailAuthAllowed is the input model used to update tenant privacy settings+type UpdateTenantEmailAuthAllowed struct {+ IsEmailAuthAllowed bool `json:"isEmailAuthAllowed"`+}++// IsAuthorized returns true if current user is authorized to perform this action+func (action *UpdateTenantEmailAuthAllowed) IsAuthorized(ctx context.Context, user *entity.User) bool {+ return user != nil && user.Role == enum.RoleAdministrator+}++// Validate if current model is valid+func (action *UpdateTenantEmailAuthAllowed) Validate(ctx context.Context, user *entity.User) *validate.Result {+ result := validate.Success()++ activeProviders := &query.ListActiveOAuthProviders{}+ if err := bus.Dispatch(ctx, activeProviders); err != nil {+ return validate.Failed("Cannot retrieve OAuth providers")+ }++ if len(activeProviders.Result) == 0 {+ result.AddFieldFailure("isEmailAuthAllowed", "You cannot disable email authentication without any other provider enabled.")+ }++ return result+}diff --git a/app/cmd/routes.go b/app/cmd/routes.goindex 62353cf15..9eddfad65 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -158,6 +158,7 @@ func routes(r *web.Engine) *web.Engine {ui.Post("/_api/admin/settings/general", handlers.UpdateSettings())ui.Post("/_api/admin/settings/advanced", handlers.UpdateAdvancedSettings())ui.Post("/_api/admin/settings/privacy", handlers.UpdatePrivacy())+ ui.Post("/_api/admin/settings/emailauth", handlers.UpdateEmailAuthAllowed())ui.Post("/_api/admin/oauth", handlers.SaveOAuthConfig())ui.Post("/_api/admin/roles/:role/users", handlers.ChangeUserRole())ui.Put("/_api/admin/users/:userID/block", handlers.BlockUser())diff --git a/app/handlers/admin.go b/app/handlers/admin.goindex 73e4031d2..c0e2bd614 100644--- a/app/handlers/admin.go+++ b/app/handlers/admin.go@@ -50,7 +50,7 @@ func UpdateSettings() web.HandlerFunc {Invitation: action.Invitation,WelcomeMessage: action.WelcomeMessage,CNAME: action.CNAME,- Locale: action.Locale,+ Locale: action.Locale,},); err != nil {return c.Failure(err)@@ -97,6 +97,25 @@ func UpdatePrivacy() web.HandlerFunc {}}+// UpdateEmailAuthAllowed update current tenant's allow email auth settings+func UpdateEmailAuthAllowed() web.HandlerFunc {+ return func(c *web.Context) error {+ action := new(actions.UpdateTenantEmailAuthAllowed)+ if result := c.BindTo(action); !result.Ok {+ return c.HandleValidation(result)+ }++ updateSettings := &cmd.UpdateTenantEmailAuthAllowedSettings{+ IsEmailAuthAllowed: action.IsEmailAuthAllowed,+ }+ if err := bus.Dispatch(c, updateSettings); err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})+ }+}+// ManageMembers is the page used by administrators to change member's rolefunc ManageMembers() web.HandlerFunc {return func(c *web.Context) error {diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.goindex 63588e933..ed045cc1e 100644--- a/app/handlers/signin_test.go+++ b/app/handlers/signin_test.go@@ -27,6 +27,7 @@ func TestSignInByEmailHandler_WithoutEmail(t *testing.T) {server := mock.NewServer()code, _ := server.+ OnTenant(mock.DemoTenant).ExecutePost(handlers.SignInByEmail(), "{ }")Expect(code).Equals(http.StatusBadRequest)diff --git a/app/models/cmd/tenant.go b/app/models/cmd/tenant.goindex 24b24fed1..18b7e2809 100644--- a/app/models/cmd/tenant.go+++ b/app/models/cmd/tenant.go@@ -20,13 +20,17 @@ type UpdateTenantPrivacySettings struct {IsPrivate bool}+type UpdateTenantEmailAuthAllowedSettings struct {+ IsEmailAuthAllowed bool+}+type UpdateTenantSettings struct {Logo *dto.ImageUploadTitle stringInvitation stringWelcomeMessage stringCNAME string- Locale string+ Locale string}type UpdateTenantAdvancedSettings struct {diff --git a/app/models/entity/tenant.go b/app/models/entity/tenant.goindex fe1ab04ac..1b3afe5f4 100644--- a/app/models/entity/tenant.go+++ b/app/models/entity/tenant.go@@ -2,15 +2,16 @@ package entity//Tenant represents a tenanttype 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"`- Locale string `json:"locale"`- IsPrivate bool `json:"isPrivate"`- LogoBlobKey string `json:"logoBlobKey"`- CustomCSS string `json:"-"`+ 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"`+ Locale string `json:"locale"`+ IsPrivate bool `json:"isPrivate"`+ LogoBlobKey string `json:"logoBlobKey"`+ CustomCSS string `json:"-"`+ IsEmailAuthAllowed bool `json:"isEmailAuthAllowed"`}diff --git a/app/pkg/dbx/setup.sql b/app/pkg/dbx/setup.sqlindex 1a21fddf8..4f1f7185e 100644--- a/app/pkg/dbx/setup.sql+++ b/app/pkg/dbx/setup.sql@@ -2,8 +2,8 @@ TRUNCATE TABLE blobs RESTART IDENTITY CASCADE;TRUNCATE TABLE logs RESTART IDENTITY CASCADE;TRUNCATE TABLE tenants RESTART IDENTITY CASCADE;-INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale)-VALUES ('Demonstration', 'demo', now(), '', '', '', 1, false, '', '', 'en');+INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed)+VALUES ('Demonstration', 'demo', now(), '', '', '', 1, false, '', '', 'en', true);INSERT INTO users (name, email, tenant_id, created_at, role, status, avatar_type, avatar_bkey)VALUES ('Jon Snow', '[email protected]', 1, now(), 3, 1, 2, '');@@ -18,8 +18,8 @@ VALUES (2, 1, 'google', 'GO5678', now());INSERT INTO users (name, email, tenant_id, created_at, role, status, avatar_type, avatar_bkey)VALUES ('Sansa Stark', '[email protected]', 1, now(), 1, 1, 2, '');-INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale)-VALUES ('Avengers', 'avengers', now(), 'feedback.avengers.com', '', '', 1, false, '', '', 'en');+INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed)+VALUES ('Avengers', 'avengers', now(), 'feedback.avengers.com', '', '', 1, false, '', '', 'en', true);INSERT INTO users (name, email, tenant_id, created_at, role, status, avatar_type, avatar_bkey)VALUES ('Tony Stark', '[email protected]', 2, now(), 3, 1, 2, '');diff --git a/app/pkg/mock/setup.go b/app/pkg/mock/setup.goindex 84757d695..cd05bcd6c 100644--- a/app/pkg/mock/setup.go+++ b/app/pkg/mock/setup.go@@ -47,10 +47,11 @@ func NewWorker() *Worker {func seed() {DemoTenant = &entity.Tenant{- ID: 1,- Name: "Demonstration",- Subdomain: "demo",- Status: enum.TenantActive,+ ID: 1,+ Name: "Demonstration",+ Subdomain: "demo",+ Status: enum.TenantActive,+ IsEmailAuthAllowed: true,}AvengersTenant = &entity.Tenant{ID: 2,diff --git a/app/pkg/web/testdata/tenant.html b/app/pkg/web/testdata/tenant.htmlindex d8cb39560..0fd8e2ba4 100755--- a/app/pkg/web/testdata/tenant.html+++ b/app/pkg/web/testdata/tenant.html@@ -44,7 +44,7 @@<script id="server-data" type="application/json">- {"contextID":"CONTEXT_ID","props":{},"sessionID":"","settings":{"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"locale":"en","mode":"multi","oauth":[]},"tenant":{"id":0,"name":"Game of Thrones","subdomain":"","invitation":"","welcomeMessage":"","cname":"","status":0,"locale":"","isPrivate":false,"logoBlobKey":""},"title":"Game of Thrones"}+ {"contextID":"CONTEXT_ID","props":{},"sessionID":"","settings":{"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"locale":"en","mode":"multi","oauth":[]},"tenant":{"id":0,"name":"Game of Thrones","subdomain":"","invitation":"","welcomeMessage":"","cname":"","status":0,"locale":"","isPrivate":false,"logoBlobKey":"","isEmailAuthAllowed":false},"title":"Game of Thrones"}</script>diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.goindex fffab4a1b..03d7fb056 100644--- a/app/services/sqlstore/postgres/postgres.go+++ b/app/services/sqlstore/postgres/postgres.go@@ -106,6 +106,7 @@ func (s Service) Init() {bus.AddHandler(isCNAMEAvailable)bus.AddHandler(updateTenantSettings)bus.AddHandler(updateTenantPrivacySettings)+ bus.AddHandler(updateTenantEmailAuthAllowedSettings)bus.AddHandler(updateTenantAdvancedSettings)bus.AddHandler(getVerificationByKey)diff --git a/app/services/sqlstore/postgres/tenant.go b/app/services/sqlstore/postgres/tenant.goindex 24acd5499..62ed0a78b 100644--- a/app/services/sqlstore/postgres/tenant.go+++ b/app/services/sqlstore/postgres/tenant.go@@ -17,17 +17,18 @@ import ()type dbTenant struct {- ID int `db:"id"`- Name string `db:"name"`- Subdomain string `db:"subdomain"`- CNAME string `db:"cname"`- Invitation string `db:"invitation"`- WelcomeMessage string `db:"welcome_message"`- Status int `db:"status"`- Locale string `db:"locale"`- IsPrivate bool `db:"is_private"`- LogoBlobKey string `db:"logo_bkey"`- CustomCSS string `db:"custom_css"`+ ID int `db:"id"`+ Name string `db:"name"`+ Subdomain string `db:"subdomain"`+ CNAME string `db:"cname"`+ Invitation string `db:"invitation"`+ WelcomeMessage string `db:"welcome_message"`+ Status int `db:"status"`+ Locale string `db:"locale"`+ IsPrivate bool `db:"is_private"`+ LogoBlobKey string `db:"logo_bkey"`+ CustomCSS string `db:"custom_css"`+ IsEmailAuthAllowed bool `db:"is_email_auth_allowed"`}func (t *dbTenant) toModel() *entity.Tenant {@@ -36,17 +37,18 @@ func (t *dbTenant) toModel() *entity.Tenant {}tenant := &entity.Tenant{- ID: t.ID,- Name: t.Name,- Subdomain: t.Subdomain,- CNAME: t.CNAME,- Invitation: t.Invitation,- WelcomeMessage: t.WelcomeMessage,- Status: t.Status,- Locale: t.Locale,- IsPrivate: t.IsPrivate,- LogoBlobKey: t.LogoBlobKey,- CustomCSS: t.CustomCSS,+ ID: t.ID,+ Name: t.Name,+ Subdomain: t.Subdomain,+ CNAME: t.CNAME,+ Invitation: t.Invitation,+ WelcomeMessage: t.WelcomeMessage,+ Status: t.Status,+ Locale: t.Locale,+ IsPrivate: t.IsPrivate,+ LogoBlobKey: t.LogoBlobKey,+ CustomCSS: t.CustomCSS,+ IsEmailAuthAllowed: t.IsEmailAuthAllowed,}return tenant@@ -125,6 +127,16 @@ func updateTenantPrivacySettings(ctx context.Context, c *cmd.UpdateTenantPrivacy})}+func updateTenantEmailAuthAllowedSettings(ctx context.Context, c *cmd.UpdateTenantEmailAuthAllowedSettings) error {+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ _, err := trx.Execute("UPDATE tenants SET is_email_auth_allowed = $1 WHERE id = $2", c.IsEmailAuthAllowed, tenant.ID)+ if err != nil {+ return errors.Wrap(err, "failed update tenant allowing email auth settings")+ }+ return nil+ })+}+func updateTenantSettings(ctx context.Context, c *cmd.UpdateTenantSettings) error {return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {if c.Logo.Remove {@@ -218,8 +230,8 @@ func createTenant(ctx context.Context, c *cmd.CreateTenant) error {var id interr := trx.Get(&id,- `INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale)- VALUES ($1, $2, $3, '', '', '', $4, false, '', '', $5)+ `INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed)+ VALUES ($1, $2, $3, '', '', '', $4, false, '', '', $5, true)RETURNING id`, c.Name, c.Subdomain, now, c.Status, env.Config.Locale)if err != nil {return err@@ -237,7 +249,7 @@ func getFirstTenant(ctx context.Context, q *query.GetFirstTenant) error {tenant := dbTenant{}err := trx.Get(&tenant, `- SELECT id, name, subdomain, cname, invitation, locale, welcome_message, status, is_private, logo_bkey, custom_css+ SELECT id, name, subdomain, cname, invitation, locale, welcome_message, status, is_private, logo_bkey, custom_css, is_email_auth_allowedFROM tenantsORDER BY id LIMIT 1`)@@ -256,7 +268,7 @@ func getTenantByDomain(ctx context.Context, q *query.GetTenantByDomain) error {tenant := dbTenant{}err := trx.Get(&tenant, `- SELECT id, name, subdomain, cname, invitation, locale, welcome_message, status, is_private, logo_bkey, custom_css+ SELECT id, name, subdomain, cname, invitation, locale, welcome_message, status, is_private, logo_bkey, custom_css, is_email_auth_allowedFROM tenants tWHERE subdomain = $1 OR subdomain = $2 OR cname = $3ORDER BY cname DESCdiff --git a/app/services/sqlstore/postgres/user_test.go b/app/services/sqlstore/postgres/user_test.goindex 860ce1ddc..004dc60e5 100644--- a/app/services/sqlstore/postgres/user_test.go+++ b/app/services/sqlstore/postgres/user_test.go@@ -159,8 +159,8 @@ func TestUserStorage_Register_MultipleProviders(t *testing.T) {var tenantID interr := trx.Get(&tenantID, `- INSERT INTO tenants (name, subdomain, created_at, status, is_private, custom_css, logo_bkey, locale)- VALUES ('My Domain Inc.','mydomain', now(), 1, false, '', '', 'en')+ INSERT INTO tenants (name, subdomain, created_at, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed)+ VALUES ('My Domain Inc.','mydomain', now(), 1, false, '', '', 'en', true)RETURNING id`)Expect(err).IsNil()diff --git a/locale/en/client.json b/locale/en/client.jsonindex 317cac10a..6b91f9b7a 100644--- a/locale/en/client.json+++ b/locale/en/client.json@@ -122,9 +122,11 @@"showpost.votespanel.more": "+{extraVotesCount} more","showpost.votespanel.seedetails": "see details","signin.message.email": "Enter your email address to sign in",+ "signin.message.emaildisabled": "Email authentication has been disabled by an administrator. If you have an administrator account and need to bypass this restriction, please <0>click here</0>.","signin.message.emailsent": "We have just sent a confirmation link to <0>{email}</0>. Click the link and you’ll be signed in.","signin.message.locked.text": "To reactivate this site, sign in with an administrator account and update the required settings.","signin.message.locked.title": "<0>{0}</0> is currently locked.",+ "signin.message.onlyadmins": "Currently only allowed to sign in to an administrator account","signin.message.private.text": "If you have an account or an invitation, you may use following options to sign in.","signin.message.private.title": "<0>{0}</0> is a private space and requires an invitation to join it.","{count, plural, one {# tag} other {# tags}}": "{count, plural, one {# tag} other {# tags}}"diff --git a/migrations/202107211126_added_allowing_email_auth.sql b/migrations/202107211126_added_allowing_email_auth.sqlnew file mode 100644index 000000000..c96a08541--- /dev/null+++ b/migrations/202107211126_added_allowing_email_auth.sql@@ -0,0 +1,3 @@+ALTER TABLE tenants ADD COLUMN is_email_auth_allowed BOOLEAN;+UPDATE tenants SET is_email_auth_allowed = TRUE;+ALTER TABLE tenants ALTER COLUMN is_email_auth_allowed SET NOT NULL;\ No newline at end of filediff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsxindex 9f38a34e6..a3d61ab1e 100644--- a/public/components/common/SignInControl.tsx+++ b/public/components/common/SignInControl.tsx@@ -15,9 +15,15 @@ interface SignInControlProps {export const SignInControl: React.FunctionComponent<SignInControlProps> = (props) => {const fider = useFider()+ const [showEmailForm, setShowEmailForm] = useState(fider.session.tenant ? fider.session.tenant.isEmailAuthAllowed : true)const [email, setEmail] = useState("")const [error, setError] = useState<Failure | undefined>(undefined)+ const forceShowEmailForm = (e: React.MouseEvent<HTMLAnchorElement>) => {+ e.preventDefault()+ setShowEmailForm(true)+ }+const signIn = async () => {const result = await actions.signIn(email)if (result.ok) {@@ -53,32 +59,49 @@ export const SignInControl: React.FunctionComponent<SignInControlProps> = (props</React.Fragment>))}</div>+ {props.useEmail && <Divider />}</>)}- {providersLen > 0 && <Divider />}-- {props.useEmail && (- <div>- <p>- <Trans id="signin.message.email">Enter your email address to sign in</Trans>- </p>- <Form error={error}>- <Input- field="email"- value={email}- autoFocus={!device.isTouch()}- onChange={setEmail}- placeholder="[email protected]"- suffix={- <Button type="submit" variant="primary" disabled={email === ""} onClick={signIn}>- <Trans id="action.signin">Sign in</Trans>- </Button>- }- />- </Form>- </div>- )}+ {props.useEmail &&+ (showEmailForm ? (+ <div>+ <p>+ <Trans id="signin.message.email">Enter your email address to sign in</Trans>+ </p>+ <Form error={error}>+ <Input+ field="email"+ value={email}+ autoFocus={!device.isTouch()}+ onChange={setEmail}+ placeholder="[email protected]"+ suffix={+ <Button type="submit" variant="primary" disabled={email === ""} onClick={signIn}>+ <Trans id="action.signin">Sign in</Trans>+ </Button>+ }+ />+ </Form>+ {!fider.session.tenant.isEmailAuthAllowed && (+ <p className="text-red-700 mt-1">+ <Trans id="signin.message.onlyadmins">Currently only allowed to sign in to an administrator account</Trans>+ </p>+ )}+ </div>+ ) : (+ <div>+ <p className="text-muted">+ <Trans id="signin.message.emaildisabled">+ Email authentication has been disabled by an administrator. If you have an administrator account and need to bypass this restriction, please{" "}+ <a href="#" className="text-bold" onClick={forceShowEmailForm}>+ click here+ </a>+ .+ </Trans>+ </p>+ </div>+ ))}</div>)}diff --git a/public/components/common/Toggle.tsx b/public/components/common/Toggle.tsxindex c86d670a2..f6e388a50 100644--- a/public/components/common/Toggle.tsx+++ b/public/components/common/Toggle.tsx@@ -3,8 +3,10 @@ import "./Toggle.scss"import React, { useState } from "react"import { classSet } from "@fider/services"import { HStack } from "../layout"+import { DisplayError, ValidationContext } from "@fider/components"interface ToggleProps {+ field?: stringlabel?: stringactive: booleandisabled?: boolean@@ -33,11 +35,18 @@ export const Toggle: React.FC<ToggleProps> = (props) => {})return (- <HStack spacing={2}>- <button onClick={toggle} type="button" className={className} role="switch">- <span aria-hidden="true" className="shadow"></span>- </button>- {props.label && <span className="text-sm">{props.label}</span>}- </HStack>+ <ValidationContext.Consumer>+ {(ctx) => (+ <>+ <HStack spacing={2}>+ <button onClick={toggle} type="button" className={className} role="switch">+ <span aria-hidden="true" className="shadow"></span>+ </button>+ {props.label && <span className="text-sm">{props.label}</span>}+ </HStack>+ {props.field && <DisplayError fields={[props.field]} error={ctx.error} />}+ </>+ )}+ </ValidationContext.Consumer>)}diff --git a/public/models/identity.ts b/public/models/identity.tsindex b18da5a86..936ee42d6 100644--- a/public/models/identity.ts+++ b/public/models/identity.ts@@ -9,6 +9,7 @@ export interface Tenant {status: TenantStatusisPrivate: booleanlogoBlobKey: string+ isEmailAuthAllowed: boolean}export enum TenantStatus {diff --git a/public/pages/Administration/components/OAuthForm.tsx b/public/pages/Administration/components/OAuthForm.tsxindex b7d29f3e6..1c606030b 100644--- a/public/pages/Administration/components/OAuthForm.tsx+++ b/public/pages/Administration/components/OAuthForm.tsx@@ -8,6 +8,7 @@ import { HStack } from "@fider/components/layout"interface OAuthFormProps {config?: OAuthConfigonCancel: () => void+ cantDisable: boolean}export const OAuthForm: React.FC<OAuthFormProps> = (props) => {@@ -207,15 +208,19 @@ export const OAuthForm: React.FC<OAuthFormProps> = (props) => {</pre><Field label="Status">- <Toggle active={enabled} onToggle={setEnabled} label={enabled ? "Enabled" : "Disabled"} />+ <Toggle field="status" disabled={props.cantDisable} active={enabled} onToggle={setEnabled} label={enabled ? "Enabled" : "Disabled"} /><div className="mt-1">- {enabled && (- <p className="text-muted mt-1">- This provider will be available for everyone to use during the sign in process. It is recommended that you keep it disable and test it before- enabling it. The Test button is available after saving this configuration.- </p>+ {enabled ? (+ <>+ {props.cantDisable && <p className="text-muted my-1">You need to enable email authentication if you want to disable all OAuth providers.</p>}+ <p className="text-muted mt-1">+ This provider will be available for everyone to use during the sign in process. It is recommended that you keep it disable and test it before+ enabling it. The Test button is available after saving this configuration.+ </p>+ </>+ ) : (+ <p className="text-muted">Users won't be able to sign in with this Provider.</p>)}- {!enabled && <p className="text-muted">Users won't be able to sign in with this Provider.</p>}</div></Field>diff --git a/public/pages/Administration/pages/ManageAuthentication.page.tsx b/public/pages/Administration/pages/ManageAuthentication.page.tsxindex 4411b17aa..393b8200a 100644--- a/public/pages/Administration/pages/ManageAuthentication.page.tsx+++ b/public/pages/Administration/pages/ManageAuthentication.page.tsx@@ -1,9 +1,9 @@import React from "react"-import { Button, OAuthProviderLogo, Icon } from "@fider/components"+import { Button, OAuthProviderLogo, Icon, Field, Toggle, Form } from "@fider/components"import { OAuthConfig, OAuthProviderOption } from "@fider/models"import { OAuthForm } from "../components/OAuthForm"-import { actions, notify, Fider } from "@fider/services"+import { actions, notify, Fider, Failure } from "@fider/services"import { AdminBasePage } from "../components/AdminBasePage"import IconPlay from "@fider/assets/images/heroicons-play.svg"@@ -17,7 +17,10 @@ interface ManageAuthenticationPageProps {interface ManageAuthenticationPageState {isAdding: boolean+ isEmailAuthAllowed: boolean+ canDisableEmailAuth: booleanediting?: OAuthConfig+ error?: Failure}export default class ManageAuthenticationPage extends AdminBasePage<ManageAuthenticationPageProps, ManageAuthenticationPageState> {@@ -30,6 +33,8 @@ export default class ManageAuthenticationPage extends AdminBasePage<ManageAuthensuper(props)this.state = {isAdding: false,+ isEmailAuthAllowed: Fider.session.tenant.isEmailAuthAllowed,+ canDisableEmailAuth: props.providers.map((o) => o.isEnabled).reduce((a, b) => a || b, false),}}@@ -55,69 +60,123 @@ export default class ManageAuthenticationPage extends AdminBasePage<ManageAuthenthis.setState({ isAdding: false, editing: undefined })}+ private toggleEmailAuth = async (active: boolean) => {+ this.setState(+ () => ({+ isEmailAuthAllowed: active,+ }),+ async () => {+ const response = await actions.updateTenantEmailAuthAllowed(this.state.isEmailAuthAllowed)+ if (response.ok) {+ notify.success(`You successfully ${this.state.isEmailAuthAllowed ? "allowed" : "disallowed"} email authentication.`)+ } else {+ this.setState(+ () => ({+ isEmailAuthAllowed: !active,+ error: response.error,+ }),+ () => notify.error("Unable to save this setting.")+ )+ }+ }+ )+ }+public content() {+ let enabledProvidersCount = 0+ for (const o of this.props.providers) {+ if (o.isEnabled) {+ enabledProvidersCount+++ }+ }+ const cantDisable = !this.state.isEmailAuthAllowed && enabledProvidersCount == 1+if (this.state.isAdding) {- return <OAuthForm onCancel={this.cancel} />+ return <OAuthForm cantDisable={cantDisable} onCancel={this.cancel} />}if (this.state.editing) {- return <OAuthForm config={this.state.editing} onCancel={this.cancel} />+ return <OAuthForm cantDisable={cantDisable} config={this.state.editing} onCancel={this.cancel} />}const enabled = <span className="text-green-700">Enabled</span>const disabled = <span className="text-red-700">Disabled</span>return (- <>- <h2 className="text-display">OAuth Providers</h2>- <p>- You can use these section to add any authentication provider thats supports the OAuth2 protocol. Additional information is available in our{" "}- <a rel="noopener" className="text-link" target="_blank" href="https://getfider.com/docs/configuring-oauth/">- OAuth Documentation- </a>- .- </p>- <VStack spacing={6}>- {this.props.providers.map((o) => (- <div key={o.provider}>- <HStack justify="between">- <HStack className="h-6">- <OAuthProviderLogo option={o} />- <strong>{o.displayName}</strong>+ <VStack spacing={8}>+ <div>+ <h2 className="text-display">General Authentication</h2>+ <Form error={this.state.error}>+ <Field label="Allow Email Authentication">+ <Toggle+ field="isEmailAuthAllowed"+ label={this.state.isEmailAuthAllowed ? "Allowed" : "Disallowed"}+ disabled={!Fider.session.user.isAdministrator || !this.state.canDisableEmailAuth}+ active={this.state.isEmailAuthAllowed}+ onToggle={this.toggleEmailAuth}+ />+ {!this.state.canDisableEmailAuth && (+ <p className="text-muted my-1">You need to configure another authentication provider before disabling email authentication.</p>+ )}+ <p className="text-muted my-1">+ When email-based authentication is disabled, users will not be allowed to sign in using their email. Thus, they will be forced to use another+ authentication provider, such as your prefered OAuth provider. <strong>Be sure to enable and test one before you turn this setting off!</strong>+ </p>+ <p className="text-muted mt-1">Note: Administrator accounts will still be allowed to sign in using their email.</p>+ </Field>+ </Form>+ </div>+ <div>+ <h2 className="text-display">OAuth Providers</h2>+ <p>+ You can use these section to add any authentication provider thats supports the OAuth2 protocol. Additional information is available in our{" "}+ <a rel="noopener" className="text-link" target="_blank" href="https://getfider.com/docs/configuring-oauth/">+ OAuth Documentation+ </a>+ .+ </p>+ <VStack spacing={6}>+ {this.props.providers.map((o) => (+ <div key={o.provider}>+ <HStack justify="between">+ <HStack className="h-6">+ <OAuthProviderLogo option={o} />+ <strong>{o.displayName}</strong>+ </HStack>+ {o.isCustomProvider && (+ <HStack>+ {Fider.session.user.isAdministrator && (+ <Button onClick={this.edit.bind(this, o.provider)} size="small">+ <Icon sprite={IconPencilAlt} />+ <span>Edit</span>+ </Button>+ )}+ <Button onClick={this.startTest.bind(this, o.provider)} size="small">+ <Icon sprite={IconPlay} />+ <span>Test</span>+ </Button>+ </HStack>+ )}</HStack>+ <div className="text-xs block my-1">{o.isEnabled ? enabled : disabled}</div>{o.isCustomProvider && (- <HStack>- {Fider.session.user.isAdministrator && (- <Button onClick={this.edit.bind(this, o.provider)} size="small">- <Icon sprite={IconPencilAlt} />- <span>Edit</span>- </Button>- )}- <Button onClick={this.startTest.bind(this, o.provider)} size="small">- <Icon sprite={IconPlay} />- <span>Test</span>- </Button>- </HStack>+ <span className="text-muted">+ <strong>Client ID:</strong> {o.clientID} <br />+ <strong>Callback URL:</strong> {o.callbackURL}+ </span>)}- </HStack>- <div className="text-xs block my-1">{o.isEnabled ? enabled : disabled}</div>- {o.isCustomProvider && (- <span className="text-muted">- <strong>Client ID:</strong> {o.clientID} <br />- <strong>Callback URL:</strong> {o.callbackURL}- </span>+ </div>+ ))}+ <div>+ {Fider.session.user.isAdministrator && (+ <Button variant="secondary" onClick={this.addNew}>+ Add new+ </Button>)}</div>- ))}- <div>- {Fider.session.user.isAdministrator && (- <Button variant="secondary" onClick={this.addNew}>- Add new- </Button>- )}- </div>- </VStack>- </>+ </VStack>+ </div>+ </VStack>)}}diff --git a/public/pages/SignUp/SignUp.page.tsx b/public/pages/SignUp/SignUp.page.tsxindex 6036f4895..b29ccc5e5 100644--- a/public/pages/SignUp/SignUp.page.tsx+++ b/public/pages/SignUp/SignUp.page.tsx@@ -1,6 +1,7 @@import React from "react"import { SignInControl, Modal, Button, DisplayError, Form, Input, Message, LegalAgreement } from "@fider/components"import { jwt, actions, Failure, querystring, Fider } from "@fider/services"+import { Divider } from "@fider/components/layout"interface OAuthUser {token: string@@ -156,6 +157,7 @@ export default class SignUpPage extends React.Component<any, SignUpPageState> {<><p>We need to identify you to setup your new Fider account.</p><SignInControl useEmail={false} />+ <Divider /><Form error={this.state.error}><Input field="name" maxLength={100} onChange={this.setName} placeholder="Name" /><Input field="email" maxLength={200} onChange={this.setEmail} placeholder="Email" />diff --git a/public/services/actions/tenant.ts b/public/services/actions/tenant.tsindex f2c9a9f20..e21af42e6 100644--- a/public/services/actions/tenant.ts+++ b/public/services/actions/tenant.ts@@ -45,6 +45,12 @@ export const updateTenantPrivacy = async (isPrivate: boolean): Promise<Result> =})}+export const updateTenantEmailAuthAllowed = async (isEmailAuthAllowed: boolean): Promise<Result> => {+ return await http.post("/_api/admin/settings/emailauth", {+ isEmailAuthAllowed,+ })+}+export const checkAvailability = async (subdomain: string): Promise<Result<CheckAvailabilityResponse>> => {return await http.get<CheckAvailabilityResponse>(`/_api/tenants/${subdomain}/availability`)}