Open platform to collect and prioritize feedback
feature: add OAuth providers via UI (#467)
Guilherme Oenninge962b8b58308
diff --git a/.test.env b/.test.envindex 8aa473f5f..05d29f4d8 100644--- a/.test.env+++ b/.test.env@@ -7,6 +7,15 @@ JWT_SECRET=SOME_RANDOM_TOKEN_JUST_FOR_TESTINGCDN_HOST=+OAUTH_FACEBOOK_APPID=FB_CL_ID+OAUTH_FACEBOOK_SECRET=FB_CL_SECRET++OAUTH_GOOGLE_CLIENTID=GO_CL_ID+OAUTH_GOOGLE_SECRET=GO_CL_SECRET++OAUTH_GITHUB_CLIENTID=GH_CL_ID+OAUTH_GITHUB_SECRET=GH_CL_SECRET+EMAIL_SMTP_HOST=smtp.random.orgdiff --git a/Makefile b/Makefileindex 2b271e877..e752a4d82 100644--- a/Makefile+++ b/Makefile@@ -44,13 +44,16 @@ e2e:./scripts/e2e.sh# Development-watch:+kill-dev:+ ps aux | grep ./fider | grep -v grep | awk '{print $$2}' | xargs kill++watch: kill-devrm -rf ./distmkdir ./distair -c air.conf &npx webpack -w-run:+run: kill-devgodotenv -f .env ./fider.DEFAULT_GOAL := builddiff --git a/app/actions/actions_test.go b/app/actions/actions_test.goindex 8c4aec62d..e47cff853 100644--- a/app/actions/actions_test.go+++ b/app/actions/actions_test.go@@ -16,7 +16,7 @@ var jonSnowToken, _ = jwt.Encode(jwt.OAuthClaims{})var services = &app.Services{- Tenants: &inmemory.TenantStorage{},+ Tenants: inmemory.NewTenantStorage(),Users: &inmemory.UserStorage{},Ideas: inmemory.NewIdeaStorage(),Tags: inmemory.NewTagStorage(),diff --git a/app/actions/oauth.go b/app/actions/oauth.gonew file mode 100644index 000000000..e646d49b4--- /dev/null+++ b/app/actions/oauth.go@@ -0,0 +1,116 @@+package actions++import (+ "strings"++ "github.com/getfider/fider/app"+ "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+}++// Initialize the model+func (input *CreateEditOAuthConfig) Initialize() interface{} {+ input.Model = new(models.CreateEditOAuthConfig)+ return input.Model+}++// IsAuthorized returns true if current user is authorized to perform this action+func (input *CreateEditOAuthConfig) IsAuthorized(user *models.User, services *app.Services) bool {+ return user != nil && user.IsAdministrator()+}++// Validate is current model is valid+func (input *CreateEditOAuthConfig) Validate(user *models.User, services *app.Services) *validate.Result {+ result := validate.Success()++ if input.Model.Provider != "" {+ config, err := services.Tenants.GetOAuthConfigByProvider(input.Model.Provider)+ if err != nil {+ return validate.Error(err)+ }++ input.Model.ID = config.ID+ if input.Model.ClientSecret == "" {+ input.Model.ClientSecret = config.ClientSecret+ }+ } else {+ input.Model.Provider = "_" + strings.ToLower(rand.String(10))+ }++ uploadResult := validate.ImageUpload(input.Model.Logo, 24, 24, 50)+ if !uploadResult.Ok {+ if uploadResult.Error != nil {+ return validate.Error(uploadResult.Error)+ }+ result.AddFieldFailure("logo", uploadResult.Messages...)+ }++ if input.Model.Status != models.OAuthConfigEnabled &&+ input.Model.Status != models.OAuthConfigDisabled {+ result.AddFieldFailure("status", "Invalid status.")+ }++ if input.Model.DisplayName == "" {+ result.AddFieldFailure("displayName", "Display Name is required.")+ } else if len(input.Model.DisplayName) > 50 {+ result.AddFieldFailure("displayName", "Display Name must have less than 50 characters.")+ }++ if input.Model.ClientID == "" {+ result.AddFieldFailure("clientId", "Client ID is required.")+ } else if len(input.Model.ClientID) > 100 {+ result.AddFieldFailure("clientId", "Client ID must have less than 100 characters.")+ }++ if input.Model.ClientSecret == "" {+ result.AddFieldFailure("clientSecret", "Client Secret is required.")+ } else if len(input.Model.ClientSecret) > 500 {+ result.AddFieldFailure("clientSecret", "Client Secret must have less than 500 characters.")+ }++ if input.Model.Scope == "" {+ result.AddFieldFailure("scope", "Scope is required.")+ } else if len(input.Model.Scope) > 100 {+ result.AddFieldFailure("scope", "Scope must have less than 100 characters.")+ }++ if input.Model.AuthorizeURL == "" {+ result.AddFieldFailure("authorizeUrl", "Authorize URL is required.")+ } else if urlResult := validate.URL(input.Model.AuthorizeURL); !urlResult.Ok {+ result.AddFieldFailure("authorizeUrl", urlResult.Messages...)+ }++ if input.Model.TokenURL == "" {+ result.AddFieldFailure("tokenUrl", "Token URL is required.")+ } else if urlResult := validate.URL(input.Model.TokenURL); !urlResult.Ok {+ result.AddFieldFailure("tokenUrl", urlResult.Messages...)+ }++ if input.Model.ProfileURL == "" {+ result.AddFieldFailure("profileUrl", "Profile URL is required.")+ } else if urlResult := validate.URL(input.Model.ProfileURL); !urlResult.Ok {+ result.AddFieldFailure("profileUrl", urlResult.Messages...)+ }++ if input.Model.JSONUserIDPath == "" {+ result.AddFieldFailure("jsonUserIdPath", "JSON User Id Path is required.")+ } else if len(input.Model.JSONUserIDPath) > 100 {+ result.AddFieldFailure("jsonUserIdPath", "JSON User Id Path must have less than 100 characters.")+ }++ if len(input.Model.JSONUserNamePath) > 100 {+ result.AddFieldFailure("jsonUserNamePath", "JSON User Name Path must have less than 100 characters.")+ }++ if len(input.Model.JSONUserEmailPath) > 100 {+ result.AddFieldFailure("jsonUserEmailPath", "JSON User Email Path must have less than 100 characters.")+ }++ return result+}diff --git a/app/actions/oauth_test.go b/app/actions/oauth_test.gonew file mode 100644index 000000000..686a0352d--- /dev/null+++ b/app/actions/oauth_test.go@@ -0,0 +1,164 @@+package actions_test++import (+ "testing"++ "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/rand"+)++func TestCreateEditOAuthConfig_InvalidInput(t *testing.T) {+ RegisterT(t)++ testCases := []struct {+ expected []string+ input *models.CreateEditOAuthConfig+ }{+ {+ expected: []string{"displayName", "status", "tokenUrl", "clientId", "clientSecret", "scope", "authorizeUrl", "tokenUrl", "profileUrl", "jsonUserIdPath"},+ input: &models.CreateEditOAuthConfig{},+ },+ {+ expected: []string{"displayName", "status", "tokenUrl", "clientId", "clientSecret", "scope", "authorizeUrl", "tokenUrl", "profileUrl", "jsonUserIdPath", "jsonUserNamePath", "jsonUserEmailPath"},+ input: &models.CreateEditOAuthConfig{+ DisplayName: rand.String(51),+ ClientID: rand.String(101),+ Status: 0,+ ClientSecret: rand.String(501),+ AuthorizeURL: rand.String(301),+ TokenURL: rand.String(301),+ Scope: rand.String(101),+ ProfileURL: rand.String(301),+ JSONUserIDPath: rand.String(101),+ JSONUserNamePath: rand.String(101),+ JSONUserEmailPath: rand.String(101),+ },+ },+ }++ for _, testCase := range testCases {+ action := &actions.CreateEditOAuthConfig{+ Model: testCase.input,+ }+ result := action.Validate(nil, services)+ ExpectFailed(result, testCase.expected...)+ }+}++func TestCreateEditOAuthConfig_AddNew_ValidInput(t *testing.T) {+ RegisterT(t)++ input := &models.CreateEditOAuthConfig{+ DisplayName: "My Provider",+ Status: models.OAuthConfigEnabled,+ 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",+ }+ action := &actions.CreateEditOAuthConfig{+ Model: input,+ }+ result := action.Validate(nil, services)+ ExpectSuccess(result)+ Expect(input.ID).Equals(0)+ Expect(input.Provider).HasLen(11)+ Expect(string(input.Provider[0])).Equals("_")+}++func TestCreateEditOAuthConfig_EditExisting_NewSecret(t *testing.T) {+ RegisterT(t)++ services.Tenants.SaveOAuthConfig(&models.CreateEditOAuthConfig{+ ID: 4,+ Provider: "_NAME",+ DisplayName: "My Provider",+ ClientSecret: "MY_OLD_SECRET",+ })++ input := &models.CreateEditOAuthConfig{+ Provider: "_NAME",+ DisplayName: "My Provider",+ Status: models.OAuthConfigDisabled,+ 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",+ }+ action := &actions.CreateEditOAuthConfig{+ Model: input,+ }+ result := action.Validate(nil, services)+ ExpectSuccess(result)+ Expect(input.ID).Equals(4)+ Expect(input.ClientSecret).Equals("jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij")+}++func TestCreateEditOAuthConfig_EditExisting_OmitSecret(t *testing.T) {+ RegisterT(t)++ services.Tenants.SaveOAuthConfig(&models.CreateEditOAuthConfig{+ ID: 5,+ Provider: "_NAME2",+ DisplayName: "My Provider",+ ClientSecret: "MY_OLD_SECRET",+ })++ input := &models.CreateEditOAuthConfig{+ Provider: "_NAME2",+ DisplayName: "My Provider",+ Status: models.OAuthConfigDisabled,+ ClientID: "823187ahjjfdha8fds7yfdashfjkdsa",+ 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",+ }+ action := &actions.CreateEditOAuthConfig{+ Model: input,+ }+ result := action.Validate(nil, services)+ ExpectSuccess(result)+ Expect(input.ID).Equals(5)+ Expect(input.ClientSecret).Equals("MY_OLD_SECRET")+}++func TestCreateEditOAuthConfig_EditNonExisting(t *testing.T) {+ RegisterT(t)++ input := &models.CreateEditOAuthConfig{+ Provider: "_MY_NEW_PROVIDER",+ DisplayName: "My Provider",+ Status: models.OAuthConfigDisabled,+ ClientID: "823187ahjjfdha8fds7yfdashfjkdsa",+ 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",+ }+ action := &actions.CreateEditOAuthConfig{+ Model: input,+ }+ result := action.Validate(nil, services)+ Expect(result.Error).Equals(app.ErrNotFound)+ Expect(result.Ok).IsFalse()+}diff --git a/app/actions/tenant.go b/app/actions/tenant.goindex 2d70b566a..f2e6d3535 100644--- a/app/actions/tenant.go+++ b/app/actions/tenant.go@@ -4,7 +4,6 @@ import ("github.com/getfider/fider/app""github.com/getfider/fider/app/models""github.com/getfider/fider/app/pkg/env"- "github.com/getfider/fider/app/pkg/img""github.com/getfider/fider/app/pkg/jwt""github.com/getfider/fider/app/pkg/validate")@@ -101,27 +100,12 @@ func (input *UpdateTenantSettings) IsAuthorized(user *models.User, services *appfunc (input *UpdateTenantSettings) Validate(user *models.User, services *app.Services) *validate.Result {result := validate.Success()- if input.Model.Logo != nil && input.Model.Logo.Upload != nil && len(input.Model.Logo.Upload.Content) > 0 {- logo, err := img.Parse(input.Model.Logo.Upload.Content)- if err != nil {- if err == img.ErrNotSupported {- result.AddFieldFailure("logo", "This file format not supported.")- } else {- return validate.Error(err)- }- } else {- if logo.Width < 200 || logo.Height < 200 {- result.AddFieldFailure("logo", "The image must have minimum dimensions of 200x200 pixels.")- }-- if logo.Width != logo.Height {- result.AddFieldFailure("logo", "The image must have an aspect ratio of 1:1.")- }-- if logo.Size > 102400 {- result.AddFieldFailure("logo", "The image size must be smaller than 100KB.")- }+ uploadResult := validate.ImageUpload(input.Model.Logo, 200, 200, 100)+ if !uploadResult.Ok {+ if uploadResult.Error != nil {+ return validate.Error(uploadResult.Error)}+ result.AddFieldFailure("logo", uploadResult.Messages...)}if input.Model.Title == "" {diff --git a/app/actions/tenant_test.go b/app/actions/tenant_test.goindex 1058b47a8..f805abf98 100644--- a/app/actions/tenant_test.go+++ b/app/actions/tenant_test.go@@ -1,14 +1,12 @@package actions_testimport (- "io/ioutil""testing""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/env")func TestCreateTenant_ShouldHaveVerificationKey(t *testing.T) {@@ -163,41 +161,3 @@ func TestUpdateTenantSettings_LargeInvitation(t *testing.T) {result := action.Validate(nil, services)ExpectFailed(result, "invitation")}--func TestUpdateTenantSettings_LargeLogo(t *testing.T) {- RegisterT(t)-- var testCases = []struct {- fileName string- valid bool- }{- {"/app/pkg/img/testdata/logo1.png", true},- {"/app/pkg/img/testdata/logo2.jpg", false},- {"/app/pkg/img/testdata/logo3.gif", false},- {"/app/pkg/img/testdata/logo4.png", false},- {"/app/pkg/img/testdata/logo5.png", true},- {"/README.md", false},- {"/favicon.ico", false},- }-- for _, testCase := range testCases {- logo, _ := ioutil.ReadFile(env.Path(testCase.fileName))-- action := actions.UpdateTenantSettings{- Model: &models.UpdateTenantSettings{- Title: "Hello World",- Logo: &models.UpdateTenantSettingsLogo{- Upload: &models.UpdateTenantSettingsLogoUpload{- Content: logo,- },- },- },- }- result := action.Validate(nil, services)- if testCase.valid {- ExpectSuccess(result)- } else {- ExpectFailed(result, "logo")- }- }-}diff --git a/app/cmd/routes.go b/app/cmd/routes.goindex 53eda137f..49864b835 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -58,6 +58,7 @@ func routes(r *web.Engine) *web.Engine {open.Get("/-/ui", handlers.Page("UI Toolkit", "A preview of Fider UI elements"))open.Get("/signup/verify", handlers.VerifySignUpKey())open.Get("/oauth/:provider/token", handlers.OAuthToken())+ open.Get("/oauth/:provider/echo", handlers.OAuthEcho())open.Use(middlewares.OnlyActiveTenants())open.Get("/signin", handlers.SignInPage())open.Get("/not-invited", handlers.NotInvitedPage())@@ -116,6 +117,8 @@ func routes(r *web.Engine) *web.Engine {private.Get("/admin/invitations", handlers.Page("Invitations · Site Settings", ""))private.Get("/admin/members", handlers.ManageMembers())private.Get("/admin/tags", handlers.ManageTags())+ private.Get("/admin/authentication", handlers.ManageAuthentication())+ private.Get("/api/admin/oauth/:provider", handlers.GetOAuthConfig())private.Post("/api/admin/invitations/send", handlers.SendInvites())private.Post("/api/admin/invitations/sample", handlers.SendSampleInvite())@@ -130,6 +133,7 @@ func routes(r *web.Engine) *web.Engine {private.Delete("/api/admin/tags/:slug", handlers.DeleteTag())private.Post("/api/admin/tags/:slug", handlers.CreateEditTag())private.Post("/api/admin/tags", handlers.CreateEditTag())+ private.Post("/api/admin/oauth", handlers.SaveOAuthConfig())private.Post("/api/admin/users/:user_id/role", handlers.ChangeUserRole())}}diff --git a/app/handlers/admin.go b/app/handlers/admin.goindex c40d5c91f..945f52b22 100644--- a/app/handlers/admin.go+++ b/app/handlers/admin.go@@ -102,3 +102,49 @@ func ManageMembers() web.HandlerFunc {})}}++// ManageAuthentication is the page used by administrators to change site authentication settings+func ManageAuthentication() web.HandlerFunc {+ return func(c web.Context) error {+ providers, err := c.Services().OAuth.ListAllProviders()+ if err != nil {+ return c.Failure(err)+ }++ return c.Page(web.Props{+ Title: "Authentication · Site Settings",+ Data: web.Map{+ "providers": providers,+ },+ })+ }+}++// GetOAuthConfig returns OAuth config based on given provider+func GetOAuthConfig() web.HandlerFunc {+ return func(c web.Context) error {+ config, err := c.Services().Tenants.GetOAuthConfigByProvider(c.Param("provider"))+ if err != nil {+ return c.Failure(err)+ }++ return c.Ok(config)+ }+}++// 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 {+ return c.HandleValidation(result)+ }++ err := c.Services().Tenants.SaveOAuthConfig(input.Model)+ if err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})+ }+}diff --git a/app/handlers/oauth.go b/app/handlers/oauth.goindex 92fe673ae..b2bf4340e 100644--- a/app/handlers/oauth.go+++ b/app/handlers/oauth.go@@ -15,10 +15,43 @@ import ("github.com/getfider/fider/app/pkg/web/util")-type oauthUserProfile struct {- Name string- ID string- Email string+// OAuthEcho exchanges OAuth Code for a user profile and return directly to the UI, without storing it+func OAuthEcho() web.HandlerFunc {+ return func(c web.Context) error {+ provider := c.Param("provider")++ code := c.QueryParam("code")+ if code == "" {+ return c.Redirect("/")+ }++ identifier := c.QueryParam("identifier")+ cookie, err := c.Request.Cookie(web.CookieOAuthIdentifier)+ if err != nil {+ return c.Failure(errors.Wrap(err, "failed to get oauth identifier cookie"))+ }++ c.RemoveCookie(web.CookieOAuthIdentifier)+ if identifier == "" || cookie.Value == "" || identifier != cookie.Value {+ return c.Redirect("/")+ }++ statusCode, body, err := c.Services().OAuth.GetRawProfile(provider, code)+ if err != nil {+ return c.Failure(err)+ }++ profile, _ := c.Services().OAuth.ParseRawProfile(provider, body)++ return c.Page(web.Props{+ Title: "OAuth Test Page",+ Data: web.Map{+ "statusCode": statusCode,+ "body": body,+ "profile": profile,+ },+ })+ }}// OAuthToken exchanges OAuth Code for a user profile@@ -120,41 +153,55 @@ func OAuthCallback() web.HandlerFunc {return c.Redirect(redirectURL.String())}- //Sign in process- if redirectURL.Path != "/signup" {+ //IDEA! when checking for signup, check if it's echo, if yes, redirect with identifier and code and do everything there, expose method to get raw re++ //TODO: check if echo, then skip user creation just redirect to /echo + send extract info plus raw GET response+ //TODO: else check if config is enabled before looking for users++ //Test OAuth+ if redirectURL.Path == fmt.Sprintf("/oauth/%s/echo", provider) {var query = redirectURL.Query()query.Set("code", code)- query.Set("redirect", redirectURL.RequestURI())query.Set("identifier", parts[1])redirectURL.RawQuery = query.Encode()- redirectURL.Path = fmt.Sprintf("/oauth/%s/token", provider)return c.Redirect(redirectURL.String())}//Sign up process- oauthUser, err := c.Services().OAuth.GetProfile(provider, code)- if err != nil {- return c.Failure(err)- }+ if redirectURL.Path == "/signup" {+ oauthUser, err := c.Services().OAuth.GetProfile(provider, code)+ if err != nil {+ return c.Failure(err)+ }- claims := jwt.OAuthClaims{- OAuthID: oauthUser.ID,- OAuthProvider: provider,- OAuthName: oauthUser.Name,- OAuthEmail: oauthUser.Email,- Metadata: jwt.Metadata{- ExpiresAt: time.Now().Add(10 * time.Minute).Unix(),- },- }+ claims := jwt.OAuthClaims{+ OAuthID: oauthUser.ID,+ OAuthProvider: provider,+ OAuthName: oauthUser.Name,+ OAuthEmail: oauthUser.Email,+ Metadata: jwt.Metadata{+ ExpiresAt: time.Now().Add(10 * time.Minute).Unix(),+ },+ }- token, err := jwt.Encode(claims)- if err != nil {- return c.Failure(err)+ token, err := jwt.Encode(claims)+ if err != nil {+ return c.Failure(err)+ }++ var query = redirectURL.Query()+ query.Set("token", token)+ redirectURL.RawQuery = query.Encode()+ return c.Redirect(redirectURL.String())}+ //Sign in processvar query = redirectURL.Query()- query.Set("token", token)+ query.Set("code", code)+ query.Set("redirect", redirectURL.RequestURI())+ query.Set("identifier", parts[1])redirectURL.RawQuery = query.Encode()+ redirectURL.Path = fmt.Sprintf("/oauth/%s/token", provider)return c.Redirect(redirectURL.String())}}diff --git a/app/middlewares/setup.go b/app/middlewares/setup.goindex e403ef393..117047250 100644--- a/app/middlewares/setup.go+++ b/app/middlewares/setup.go@@ -130,11 +130,12 @@ func WebSetup() web.MiddlewareFunc {trx.SetLogger(c.Logger())oauthBaseURL := webutil.GetOAuthBaseURL(c)+ tenantStorage := postgres.NewTenantStorage(trx)c.SetActiveTransaction(trx)c.SetServices(&app.Services{- Tenants: postgres.NewTenantStorage(trx),- OAuth: web.NewOAuthService(oauthBaseURL),+ Tenants: tenantStorage,+ OAuth: web.NewOAuthService(oauthBaseURL, tenantStorage),Users: postgres.NewUserStorage(trx),Ideas: postgres.NewIdeaStorage(trx),Tags: postgres.NewTagStorage(trx),diff --git a/app/models/identity.go b/app/models/identity.goindex c62b0909b..4304e21c7 100644--- a/app/models/identity.go+++ b/app/models/identity.go@@ -140,11 +140,11 @@ func (e *CreateTenant) GetKind() EmailVerificationKind {//UpdateTenantSettings is the input model used to update tenant general settingstype UpdateTenantSettings struct {- Logo *UpdateTenantSettingsLogo `json:"logo"`- Title string `json:"title"`- Invitation string `json:"invitation"`- WelcomeMessage string `json:"welcomeMessage"`- CNAME string `json:"cname" format:"lower"`+ 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@@ -152,14 +152,14 @@ type UpdateTenantAdvancedSettings struct {CustomCSS string `json:"customCSS"`}-//UpdateTenantSettingsLogo is the input model used to update logo-type UpdateTenantSettingsLogo struct {- Upload *UpdateTenantSettingsLogoUpload `json:"upload"`- Remove bool `json:"remove"`+//ImageUpload is the input model used to upload/remove an image+type ImageUpload struct {+ Upload *ImageUploadData `json:"upload"`+ Remove bool `json:"remove"`}//UpdateTenantSettingsLogoUpload is the input model used to uploade a new logo-type UpdateTenantSettingsLogoUpload struct {+type ImageUploadData struct {ContentType string `json:"contentType"`Content []byte `json:"content"`}diff --git a/app/models/infra.go b/app/models/infra.goindex 3e1b4715b..7b4567877 100644--- a/app/models/infra.go+++ b/app/models/infra.go@@ -1,6 +1,7 @@package modelsimport (+ "encoding/json""time")@@ -25,19 +26,69 @@ type Notification struct {CreatedOn time.Time `json:"createdOn" db:"created_on"`}+// 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 providertype OAuthConfig struct {- ID int `db:"id"`- Provider string `db:"provider"`- DisplayName string `db:"display_name"`- Status int `db:"status"`- ClientID string `db:"client_id"`- ClientSecret string `db:"client_secret"`- AuthorizeURL string `db:"authorize_url"`- TokenURL string `db:"token_url"`- ProfileURL string `db:"profile_url"`- Scope string `db:"scope"`- JSONUserIDPath string `db:"json_user_id_path"`- JSONNamePath string `db:"json_name_path"`- JSONEmailPath string `db:"json_email_path"`+ ID int+ Provider string+ DisplayName string+ LogoID int+ 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,+ "logoId": o.LogoID,+ "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,+ })}++var (+ //OAuthConfigDisabled is used to disable an OAuthConfig for signin+ OAuthConfigDisabled = 1+ //OAuthConfigEnabled is used to enable an OAuthConfig for public use+ OAuthConfigEnabled = 2+)diff --git a/app/pkg/jsonq/jsonq.go b/app/pkg/jsonq/jsonq.goindex 8d223cbaf..a77fa67f6 100644--- a/app/pkg/jsonq/jsonq.go+++ b/app/pkg/jsonq/jsonq.go@@ -36,7 +36,7 @@ func (q *Query) String(selector string) string {var str json.Numbererr := json.Unmarshal(*data, &str)if err != nil {- panic(err)+ return ""}if str != "" {return str.String()@@ -81,6 +81,10 @@ func (q *Query) Contains(selector string) bool {}func (q *Query) get(selector string) *json.RawMessage {+ if selector == "" {+ return nil+ }+parts := strings.Split(selector, ".")var result *json.RawMessage@@ -102,7 +106,10 @@ func (q *Query) get(selector string) *json.RawMessage {json.Unmarshal(bytes, &arr)if len(arr) > idx {bytes, _ = arr[idx].MarshalJSON()- json.Unmarshal(bytes, ¤t)+ err := json.Unmarshal(bytes, ¤t)+ if err != nil {+ return arr[idx]+ }}}} else {diff --git a/app/pkg/jsonq/jsonq_test.go b/app/pkg/jsonq/jsonq_test.goindex 502d095c6..204bc6d42 100644--- a/app/pkg/jsonq/jsonq_test.go+++ b/app/pkg/jsonq/jsonq_test.go@@ -22,6 +22,14 @@ func TestGetNull(t *testing.T) {Expect(query.String("name")).Equals("")}+func TestGet_EmptyKey(t *testing.T) {+ RegisterT(t)++ query := jsonq.New(`{ "name": "Jon Snow", "age": 23 }`)+ Expect(query.String("")).Equals("")+ Expect(query.Int32("")).Equals(0)+}+func TestGet_NumberAsString(t *testing.T) {RegisterT(t)@@ -45,7 +53,7 @@ func TestGetWithFallback(t *testing.T) {Expect(query.String("name, login")).Equals("jonsnow")}-func TestGetValueFromArray(t *testing.T) {+func TestGetValueFromObjectArray(t *testing.T) {RegisterT(t)query := jsonq.New(`{ "data": [{ "name": "Jon Snow" }, { "age": 23 }] }`)@@ -54,6 +62,15 @@ func TestGetValueFromArray(t *testing.T) {Expect(query.String("data[1].age")).Equals("23")}+func TestGetValueFromStringArray(t *testing.T) {+ RegisterT(t)++ query := jsonq.New(`{ "data": ["Jon Snow", "Arya Stark"] }`)+ Expect(query.String("data[0]")).Equals("Jon Snow")+ Expect(query.String("data[1]")).Equals("Arya Stark")+ Expect(query.String("data[2]")).Equals("")+}+func TestGetValueFromEmptyArray(t *testing.T) {RegisterT(t)diff --git a/app/pkg/mock/oauth.go b/app/pkg/mock/oauth.goindex 5fac83665..79f0f31f7 100644--- a/app/pkg/mock/oauth.go+++ b/app/pkg/mock/oauth.go@@ -10,6 +10,16 @@ func (s *OAuthService) GetAuthURL(provider, redirect, identifier string) (stringreturn "http://avengers.test.fider.io/oauth/token?provider=" + provider + "&redirect=" + redirect + "|" + identifier, nil}+//GetRawProfile returns raw JSON response from Profile API+func (s *OAuthService) GetRawProfile(provider string, code string) (int, string, error) {+ return 500, "", nil+}++//ParseRawProfile parses raw profile response into UserProfile model+func (s *OAuthService) ParseRawProfile(provider, body string) (*oauth.UserProfile, error) {+ return nil, nil+}+//GetProfile returns user profile based on provider and codefunc (s *OAuthService) GetProfile(provider string, code string) (*oauth.UserProfile, error) {if provider == "facebook" && code == "123" {@@ -47,7 +57,12 @@ func (s *OAuthService) GetProfile(provider string, code string) (*oauth.UserProfreturn nil, nil}-//ListProviders returns a list of all providers for current tenant-func (s *OAuthService) ListProviders() ([]*oauth.ProviderOption, error) {+//ListActiveProviders returns a list of all providers for current tenant+func (s *OAuthService) ListActiveProviders() ([]*oauth.ProviderOption, error) {+ return []*oauth.ProviderOption{}, nil+}++//ListAllProviders returns a list of all providers for current tenant+func (s *OAuthService) ListAllProviders() ([]*oauth.ProviderOption, error) {return []*oauth.ProviderOption{}, nil}diff --git a/app/pkg/mock/setup.go b/app/pkg/mock/setup.goindex a6ee0ef1f..b523874e2 100644--- a/app/pkg/mock/setup.go+++ b/app/pkg/mock/setup.go@@ -47,7 +47,7 @@ func NewWorker() (*Worker, *app.Services) {func createServices(seed bool) *app.Services {services := &app.Services{- Tenants: &inmemory.TenantStorage{},+ Tenants: inmemory.NewTenantStorage(),Users: &inmemory.UserStorage{},Tags: inmemory.NewTagStorage(),Notifications: inmemory.NewNotificationStorage(),diff --git a/app/pkg/oauth/oauth.go b/app/pkg/oauth/oauth.goindex 947b8f010..a3b1297c2 100644--- a/app/pkg/oauth/oauth.go+++ b/app/pkg/oauth/oauth.go@@ -18,21 +18,29 @@ var ErrUserIDRequired = errors.New("UserID is required during OAuth integration"//UserProfile represents an OAuth user profiletype UserProfile struct {- ID string- Name string- Email string+ ID string `json:"id"`+ Name string `json:"name"`+ Email string `json:"email"`}//ProviderOption represents an OAuth provider that can be used to authenticatetype ProviderOption struct {- Provider string `json:"provider"`- DisplayName string `json:"displayName"`- URL string `json:"url"`+ Provider string `json:"provider"`+ DisplayName string `json:"displayName"`+ ClientID string `json:"clientId"`+ URL string `json:"url"`+ CallbackURL string `json:"callbackUrl"`+ LogoID int `json:"logoId"`+ IsCustomProvider bool `json:"isCustomProvider"`+ IsEnabled bool `json:"isEnabled"`}//Service provides OAuth operationstype Service interface {GetAuthURL(provider, redirect, identifier string) (string, error)GetProfile(provider string, code string) (*UserProfile, error)- ListProviders() ([]*ProviderOption, error)+ GetRawProfile(provider string, code string) (int, string, error)+ ParseRawProfile(provider, body string) (*UserProfile, error)+ ListActiveProviders() ([]*ProviderOption, error)+ ListAllProviders() ([]*ProviderOption, error)}diff --git a/app/pkg/rand/random.go b/app/pkg/rand/random.gonew file mode 100644index 000000000..fc55930e2--- /dev/null+++ b/app/pkg/rand/random.go@@ -0,0 +1,31 @@+package rand++import (+ "math/rand"+ "time"+)++func init() {+ rand.Seed(time.Now().UnixNano())+}++var letterRunes = []byte("123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")++// Int returns a random integer+func Int(min, max int) int {+ return min + rand.Intn(max-min)+}++// String returns a random string of given length+func String(lenght int) string {+ if lenght <= 0 {+ return ""+ }++ bytes := make([]byte, lenght)+ for i := 0; i < lenght; i++ {+ bytes[i] = letterRunes[Int(0, len(letterRunes))]+ }++ return string(bytes)+}diff --git a/app/pkg/rand/random_test.go b/app/pkg/rand/random_test.gonew file mode 100644index 000000000..0407fe11d--- /dev/null+++ b/app/pkg/rand/random_test.go@@ -0,0 +1,19 @@+package rand_test++import (+ "testing"++ . "github.com/getfider/fider/app/pkg/assert"+ "github.com/getfider/fider/app/pkg/rand"+)++var letterRunes = []rune("123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")++func TestRandomString(t *testing.T) {+ RegisterT(t)++ Expect(rand.String(10000)).HasLen(10000)+ Expect(rand.String(10)).HasLen(10)+ Expect(rand.String(0)).HasLen(0)+ Expect(rand.String(-1)).HasLen(0)+}diff --git a/app/pkg/validate/general.go b/app/pkg/validate/general.goindex 16df5d545..413fb68d0 100644--- a/app/pkg/validate/general.go+++ b/app/pkg/validate/general.go@@ -2,6 +2,7 @@ package validateimport ("fmt"+ "net/url""regexp""strings"@@ -27,6 +28,22 @@ func Email(email string) *Result {return Success()}+//URL validates given URL+func URL(rawurl string) *Result {+ rawurl = strings.ToLower(rawurl)++ if len(rawurl) > 300 {+ return Failed([]string{"URL address must have less than 300 characters."})+ }++ _, err := url.ParseRequestURI(rawurl)+ if err != nil {+ return Failed([]string{fmt.Sprintf("'%s' is not a valid URL address.", rawurl)})+ }++ return Success()+}+//CNAME validates given cnamefunc CNAME(tenants storage.Tenant, cname string) *Result {cname = strings.ToLower(cname)diff --git a/app/pkg/validate/general_test.go b/app/pkg/validate/general_test.goindex 9b1236b3f..bee5aa1c7 100644--- a/app/pkg/validate/general_test.go+++ b/app/pkg/validate/general_test.go@@ -5,6 +5,7 @@ import ("github.com/getfider/fider/app/models". "github.com/getfider/fider/app/pkg/assert"+ "github.com/getfider/fider/app/pkg/rand""github.com/getfider/fider/app/pkg/validate""github.com/getfider/fider/app/storage/inmemory")@@ -21,8 +22,8 @@ func TestInvalidEmail(t *testing.T) {"my+company.com","my@[email protected]",- "@gmail.com",- "abc12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890@gmail.com",+ "my@[email protected]",+ rand.String(200) + "@gmail.com",} {result := validate.Email(email)Expect(result.Ok).IsFalse()@@ -46,6 +47,38 @@ func TestValidEmail(t *testing.T) {}}+func TestInvalidURL(t *testing.T) {+ RegisterT(t)++ for _, rawurl := range []string{+ "http//google.com",+ "google.com",+ "google",+ rand.String(301),+ "my@company",+ } {+ result := validate.URL(rawurl)+ Expect(result.Ok).IsFalse()+ Expect(len(result.Messages) > 0).IsTrue()+ Expect(result.Error).IsNil()+ }+}++func TestValidURL(t *testing.T) {+ RegisterT(t)++ for _, rawurl := range []string{+ "http://example.org",+ "https://example.org/oauth",+ "https://example.org/oauth?test=abc",+ } {+ result := validate.URL(rawurl)+ Expect(result.Ok).IsTrue()+ Expect(result.Messages).HasLen(0)+ Expect(result.Error).IsNil()+ }+}+func TestInvalidCNAME(t *testing.T) {RegisterT(t)@@ -59,7 +92,7 @@ func TestInvalidCNAME(t *testing.T) {"test.fider.io","@google.com",} {- result := validate.CNAME(&inmemory.TenantStorage{}, cname)+ result := validate.CNAME(inmemory.NewTenantStorage(), cname)Expect(result.Ok).IsFalse()Expect(len(result.Messages) > 0).IsTrue()Expect(result.Error).IsNil()@@ -76,7 +109,7 @@ func TestValidHostname(t *testing.T) {"got.com","hi.m",} {- result := validate.CNAME(&inmemory.TenantStorage{}, cname)+ result := validate.CNAME(inmemory.NewTenantStorage(), cname)Expect(result.Ok).IsTrue()Expect(result.Messages).HasLen(0)Expect(result.Error).IsNil()@@ -85,7 +118,7 @@ func TestValidHostname(t *testing.T) {func TestValidCNAME_Availability(t *testing.T) {RegisterT(t)- tenants := &inmemory.TenantStorage{}+ tenants := inmemory.NewTenantStorage()tenant, _ := tenants.Add("Footbook", "footbook", models.TenantActive)tenant.CNAME = "footbook.com"tenant, _ = tenants.Add("Your Company", "yourcompany", models.TenantActive)diff --git a/app/pkg/validate/subdomain_test.go b/app/pkg/validate/subdomain_test.goindex 8a67d5f1d..79d46ef17 100644--- a/app/pkg/validate/subdomain_test.go+++ b/app/pkg/validate/subdomain_test.go@@ -33,7 +33,7 @@ func TestInvalidSubdomains(t *testing.T) {func TestValidSubdomains_Availability(t *testing.T) {RegisterT(t)- tenants := &inmemory.TenantStorage{}+ tenants := inmemory.NewTenantStorage()tenants.Add("Footbook", "footbook", models.TenantActive)tenants.Add("Your Company", "yourcompany", models.TenantActive)tenants.Add("New York", "newyork", models.TenantActive)diff --git a/app/pkg/validate/upload.go b/app/pkg/validate/upload.gonew file mode 100644index 000000000..9fe3a3705--- /dev/null+++ b/app/pkg/validate/upload.go@@ -0,0 +1,41 @@+package validate++import (+ "fmt"++ "github.com/getfider/fider/app/models"+ "github.com/getfider/fider/app/pkg/img"+)++//ImageUpload validates given image upload+func ImageUpload(upload *models.ImageUpload, minWidth, minHeight, maxKilobytes int) *Result {+ messages := []string{}++ if upload != nil && upload.Upload != nil && len(upload.Upload.Content) > 0 {+ logo, err := img.Parse(upload.Upload.Content)+ if err != nil {+ if err == img.ErrNotSupported {+ messages = append(messages, "This file format not supported.")+ } else {+ return Error(err)+ }+ } else {+ if logo.Width < minWidth || logo.Height < minHeight {+ messages = append(messages, fmt.Sprintf("The image must have minimum dimensions of %dx%d pixels.", minWidth, minHeight))+ }++ if logo.Width != logo.Height {+ messages = append(messages, "The image must have an aspect ratio of 1:1.")+ }++ if logo.Size > (maxKilobytes * 1024) {+ messages = append(messages, fmt.Sprintf("The image size must be smaller than %dKB.", maxKilobytes))+ }+ }+ }++ if len(messages) > 0 {+ return Failed(messages)+ }+ return Success()+}diff --git a/app/pkg/validate/upload_test.go b/app/pkg/validate/upload_test.gonew file mode 100644index 000000000..536474aaf--- /dev/null+++ b/app/pkg/validate/upload_test.go@@ -0,0 +1,50 @@+package validate_test++import (+ "io/ioutil"+ "testing"++ "github.com/getfider/fider/app/models"+ . "github.com/getfider/fider/app/pkg/assert"+ "github.com/getfider/fider/app/pkg/env"+ "github.com/getfider/fider/app/pkg/validate"+)++func TestValidateImageUpload(t *testing.T) {+ RegisterT(t)++ var testCases = []struct {+ fileName string+ valid bool+ }{+ {"/app/pkg/img/testdata/logo1.png", true},+ {"/app/pkg/img/testdata/logo2.jpg", false},+ {"/app/pkg/img/testdata/logo3.gif", false},+ {"/app/pkg/img/testdata/logo4.png", false},+ {"/app/pkg/img/testdata/logo5.png", true},+ {"/README.md", false},+ {"/favicon.ico", false},+ }++ for _, testCase := range testCases {+ img, _ := ioutil.ReadFile(env.Path(testCase.fileName))++ upload := &models.ImageUpload{+ Upload: &models.ImageUploadData{+ Content: img,+ },+ }+ result := validate.ImageUpload(upload, 200, 200, 100)+ Expect(result.Ok).Equals(testCase.valid)+ }+}++func TestValidateImageUpload_Nil(t *testing.T) {+ RegisterT(t)++ result := validate.ImageUpload(nil, 200, 200, 50)+ Expect(result.Ok).IsTrue()++ result = validate.ImageUpload(&models.ImageUpload{}, 200, 200, 50)+ Expect(result.Ok).IsTrue()+}diff --git a/app/pkg/web/oauth.go b/app/pkg/web/oauth.goindex dc2116ad4..92ebfc028 100644--- a/app/pkg/web/oauth.go+++ b/app/pkg/web/oauth.go@@ -8,8 +8,8 @@ import ("os""strings"- "github.com/getfider/fider/app""github.com/getfider/fider/app/pkg/validate"+ "github.com/getfider/fider/app/storage""github.com/getfider/fider/app/pkg/jsonq"@@ -23,59 +23,75 @@ import ("golang.org/x/oauth2/google")+func getProviderStatus(envKey string) int {+ if os.Getenv(envKey) == "" {+ return models.OAuthConfigDisabled+ }+ return models.OAuthConfigEnabled+}+var (systemProviders = []*models.OAuthConfig{&models.OAuthConfig{- Provider: oauth.FacebookProvider,- DisplayName: "Facebook",- ProfileURL: "https://graph.facebook.com/me?fields=name,email",- ClientID: os.Getenv("OAUTH_FACEBOOK_APPID"),- ClientSecret: os.Getenv("OAUTH_FACEBOOK_SECRET"),- Scope: "public_profile email",- AuthorizeURL: facebook.Endpoint.AuthURL,- TokenURL: facebook.Endpoint.TokenURL,- JSONUserIDPath: "id",- JSONNamePath: "name",- JSONEmailPath: "email",+ Provider: oauth.FacebookProvider,+ DisplayName: "Facebook",+ ProfileURL: "https://graph.facebook.com/me?fields=name,email",+ Status: getProviderStatus("OAUTH_FACEBOOK_APPID"),+ ClientID: os.Getenv("OAUTH_FACEBOOK_APPID"),+ ClientSecret: os.Getenv("OAUTH_FACEBOOK_SECRET"),+ Scope: "public_profile email",+ AuthorizeURL: facebook.Endpoint.AuthURL,+ TokenURL: facebook.Endpoint.TokenURL,+ JSONUserIDPath: "id",+ JSONUserNamePath: "name",+ JSONUserEmailPath: "email",},&models.OAuthConfig{- Provider: oauth.GoogleProvider,- DisplayName: "Google",- ProfileURL: "https://www.googleapis.com/plus/v1/people/me",- ClientID: os.Getenv("OAUTH_GOOGLE_CLIENTID"),- ClientSecret: os.Getenv("OAUTH_GOOGLE_SECRET"),- Scope: "profile email",- AuthorizeURL: google.Endpoint.AuthURL,- TokenURL: google.Endpoint.TokenURL,- JSONUserIDPath: "id",- JSONNamePath: "displayName",- JSONEmailPath: "emails[0].value",+ Provider: oauth.GoogleProvider,+ DisplayName: "Google",+ ProfileURL: "https://www.googleapis.com/plus/v1/people/me",+ Status: getProviderStatus("OAUTH_GOOGLE_CLIENTID"),+ ClientID: os.Getenv("OAUTH_GOOGLE_CLIENTID"),+ ClientSecret: os.Getenv("OAUTH_GOOGLE_SECRET"),+ Scope: "profile email",+ AuthorizeURL: google.Endpoint.AuthURL,+ TokenURL: google.Endpoint.TokenURL,+ JSONUserIDPath: "id",+ JSONUserNamePath: "displayName",+ JSONUserEmailPath: "emails[0].value",},&models.OAuthConfig{- Provider: oauth.GitHubProvider,- DisplayName: "GitHub",- ProfileURL: "https://api.github.com/user",- ClientID: os.Getenv("OAUTH_GITHUB_CLIENTID"),- ClientSecret: os.Getenv("OAUTH_GITHUB_SECRET"),- Scope: "user:email",- AuthorizeURL: github.Endpoint.AuthURL,- TokenURL: github.Endpoint.TokenURL,- JSONUserIDPath: "id",- JSONNamePath: "name, login",- JSONEmailPath: "email",+ Provider: oauth.GitHubProvider,+ DisplayName: "GitHub",+ ProfileURL: "https://api.github.com/user",+ Status: getProviderStatus("OAUTH_GITHUB_CLIENTID"),+ ClientID: os.Getenv("OAUTH_GITHUB_CLIENTID"),+ ClientSecret: os.Getenv("OAUTH_GITHUB_SECRET"),+ Scope: "user:email",+ AuthorizeURL: github.Endpoint.AuthURL,+ TokenURL: github.Endpoint.TokenURL,+ JSONUserIDPath: "id",+ JSONUserNamePath: "name, login",+ JSONUserEmailPath: "email",},})//OAuthService implements real OAuth operations using Golang's oauth2 packagetype OAuthService struct {- oauthBaseURL string+ oauthBaseURL string+ tenantStorage storage.Tenant+ configCache map[string]*models.OAuthConfig}//NewOAuthService creates a new OAuthService-func NewOAuthService(oauthBaseURL string) *OAuthService {+func NewOAuthService(oauthBaseURL string, tenantStorage storage.Tenant) *OAuthService {+ configCache := make(map[string]*models.OAuthConfig, 0)+return &OAuthService{oauthBaseURL,+ tenantStorage,+ configCache,}}@@ -97,13 +113,36 @@ func (s *OAuthService) GetAuthURL(provider, redirect, identifier string) (stringreturn authURL.String(), nil}-//GetProfile returns user profile based on provider and code+//GetProfile returns user profile based on provider (only if enabled) and codefunc (s *OAuthService) GetProfile(provider string, code string) (*oauth.UserProfile, error) {config, err := s.getConfig(provider)if err != nil {return nil, err}+ if config.Status == models.OAuthConfigDisabled {+ return nil, errors.New("Provider %s is disabled", provider)+ }++ statusCode, body, err := s.GetRawProfile(provider, code)+ if err != nil {+ return nil, err+ }++ if statusCode != 200 {+ return nil, errors.New("Failed to request GET profile. Status Code: %d. Body: %s", statusCode, body)+ }++ return s.ParseRawProfile(provider, body)+}++//GetRawProfile returns raw JSON response from Profile API+func (s *OAuthService) GetRawProfile(provider string, code string) (int, string, error) {+ config, err := s.getConfig(provider)+ if err != nil {+ return 0, "", err+ }+exchange := (&oauth2.Config{ClientID: config.ClientID,ClientSecret: config.ClientSecret,@@ -116,24 +155,25 @@ func (s *OAuthService) GetProfile(provider string, code string) (*oauth.UserProfoauthToken, err := exchange(oauth2.NoContext, code)if err != nil {- return nil, errors.Wrap(err, "failed to exchange OAuth2 code with %s", provider)+ rErr := err.(*oauth2.RetrieveError)+ return rErr.Response.StatusCode, string(rErr.Body), nil}- bytes, err := s.doGet(config.ProfileURL, oauthToken.AccessToken)+ return s.doGet(config.ProfileURL, oauthToken.AccessToken)+}++//ParseRawProfile parses raw profile response into UserProfile model+func (s *OAuthService) ParseRawProfile(provider, body string) (*oauth.UserProfile, error) {+ config, err := s.getConfig(provider)if err != nil {return nil, err}- return s.ParseProfileResponse(string(bytes), config)-}--//ParseProfileResponse parses profile response into UserProfile model-func (s *OAuthService) ParseProfileResponse(body string, config *models.OAuthConfig) (*oauth.UserProfile, error) {query := jsonq.New(body)profile := &oauth.UserProfile{ID: strings.TrimSpace(query.String(config.JSONUserIDPath)),- Name: strings.TrimSpace(query.String(config.JSONNamePath)),- Email: strings.TrimSpace(query.String(config.JSONEmailPath)),+ Name: strings.TrimSpace(query.String(config.JSONUserNamePath)),+ Email: strings.TrimSpace(query.String(config.JSONUserEmailPath)),}if profile.ID == "" {@@ -156,51 +196,98 @@ func (s *OAuthService) ParseProfileResponse(body string, config *models.OAuthConreturn profile, nil}-//ListProviders returns a list of all providers for current tenant-func (s *OAuthService) ListProviders() ([]*oauth.ProviderOption, error) {+//ListActiveProviders returns a list of all enabled providers for current tenant+func (s *OAuthService) ListActiveProviders() ([]*oauth.ProviderOption, error) {list := make([]*oauth.ProviderOption, 0)+ providers, err := s.ListAllProviders()+ if err != nil {+ return nil, err+ }- for _, p := range systemProviders {- if p.ClientID != "" {- list = append(list, &oauth.ProviderOption{- Provider: p.Provider,- DisplayName: p.DisplayName,- URL: fmt.Sprintf("/oauth/%s", p.Provider),- })+ for _, p := range providers {+ if p.IsEnabled {+ list = append(list, p)}}+ return list, nil+}++//ListAllProviders returns a list of all providers for current tenant+func (s *OAuthService) ListAllProviders() ([]*oauth.ProviderOption, error) {+ providers, err := s.allOAuthConfigs()+ if err != nil {+ return nil, err+ }++ list := make([]*oauth.ProviderOption, 0)++ for _, p := range providers {+ list = append(list, &oauth.ProviderOption{+ Provider: p.Provider,+ DisplayName: p.DisplayName,+ ClientID: p.ClientID,+ URL: fmt.Sprintf("/oauth/%s", p.Provider),+ CallbackURL: fmt.Sprintf("%s/oauth/%s/callback", s.oauthBaseURL, p.Provider),+ IsCustomProvider: string(p.Provider[0]) == "_",+ LogoID: p.LogoID,+ IsEnabled: p.Status == models.OAuthConfigEnabled,+ })+ }++ return list, nil+}++func (s *OAuthService) allOAuthConfigs() ([]*models.OAuthConfig, error) {+ list := make([]*models.OAuthConfig, 0)++ for _, p := range systemProviders {+ list = append(list, p)+ }++ customProviders, err := s.tenantStorage.ListOAuthConfig()+ if err != nil {+ return nil, errors.Wrap(err, "failed to get list of custom OAuth providers")+ }++ for _, p := range customProviders {+ list = append(list, p)+ }return list, nil}-func (s *OAuthService) doGet(url, accessToken string) ([]byte, error) {+func (s *OAuthService) doGet(url, accessToken string) (int, string, error) {req, _ := http.NewRequest("GET", url, nil)req.Header.Set("Authorization", "Bearer "+accessToken)r, err := http.DefaultClient.Do(req)if err != nil {- return nil, err+ return 0, "", err}defer r.Body.Close()bytes, err := ioutil.ReadAll(r.Body)- if err != nil {- return nil, errors.Wrap(err, "failed to request GET %s", url)- }-- if r.StatusCode != 200 {- return nil, errors.New("failed to request GET %s with status code %d and response %s", url, r.StatusCode, string(bytes))- }-- return bytes, nil+ return r.StatusCode, string(bytes), err}func (s *OAuthService) getConfig(provider string) (*models.OAuthConfig, error) {- for _, p := range systemProviders {- if p.Provider == provider {- return p, nil+ for _, config := range systemProviders {+ if config.Status == models.OAuthConfigEnabled && config.Provider == provider {+ return config, nil}}- return nil, app.ErrNotFound++ var err error+ config, ok := s.configCache[provider]+ if !ok {+ config, err = s.tenantStorage.GetOAuthConfigByProvider(provider)+ if err != nil {+ return nil, err+ }++ s.configCache[provider] = config+ }++ return config, nil}diff --git a/app/pkg/web/oauth_test.go b/app/pkg/web/oauth_test.goindex 0420205ae..efee9ae01 100644--- a/app/pkg/web/oauth_test.go+++ b/app/pkg/web/oauth_test.go@@ -9,49 +9,70 @@ import ("github.com/getfider/fider/app/pkg/errors""github.com/getfider/fider/app/pkg/oauth""github.com/getfider/fider/app/pkg/web"+ "github.com/getfider/fider/app/storage/inmemory")func TestGetAuthURL_Facebook(t *testing.T) {RegisterT(t)- svc := web.NewOAuthService("http://login.test.fider.io:3000")+ svc := web.NewOAuthService("http://login.test.fider.io:3000", inmemory.NewTenantStorage())authURL, err := svc.GetAuthURL(oauth.FacebookProvider, "http://example.org", "456")Expect(err).IsNil()- Expect(authURL).Equals("https://www.facebook.com/dialog/oauth?client_id=&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Ffacebook%2Fcallback&response_type=code&scope=public_profile+email&state=http%3A%2F%2Fexample.org%7C456")+ Expect(authURL).Equals("https://www.facebook.com/dialog/oauth?client_id=FB_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Ffacebook%2Fcallback&response_type=code&scope=public_profile+email&state=http%3A%2F%2Fexample.org%7C456")}func TestGetAuthURL_Google(t *testing.T) {RegisterT(t)- svc := web.NewOAuthService("http://login.test.fider.io:3000")+ svc := web.NewOAuthService("http://login.test.fider.io:3000", inmemory.NewTenantStorage())authURL, err := svc.GetAuthURL(oauth.GoogleProvider, "http://example.org", "123")Expect(err).IsNil()- Expect(authURL).Equals("https://accounts.google.com/o/oauth2/auth?client_id=&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgoogle%2Fcallback&response_type=code&scope=profile+email&state=http%3A%2F%2Fexample.org%7C123")+ Expect(authURL).Equals("https://accounts.google.com/o/oauth2/auth?client_id=GO_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgoogle%2Fcallback&response_type=code&scope=profile+email&state=http%3A%2F%2Fexample.org%7C123")}func TestGetAuthURL_GitHub(t *testing.T) {RegisterT(t)- svc := web.NewOAuthService("http://login.test.fider.io:3000")+ svc := web.NewOAuthService("http://login.test.fider.io:3000", inmemory.NewTenantStorage())authURL, err := svc.GetAuthURL(oauth.GitHubProvider, "http://example.org", "456")Expect(err).IsNil()- Expect(authURL).Equals("https://github.com/login/oauth/authorize?client_id=&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgithub%2Fcallback&response_type=code&scope=user%3Aemail&state=http%3A%2F%2Fexample.org%7C456")+ Expect(authURL).Equals("https://github.com/login/oauth/authorize?client_id=GH_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgithub%2Fcallback&response_type=code&scope=user%3Aemail&state=http%3A%2F%2Fexample.org%7C456")+}++func TestGetAuthURL_Custom(t *testing.T) {+ RegisterT(t)++ tenants := inmemory.NewTenantStorage()+ tenants.SaveOAuthConfig(&models.CreateEditOAuthConfig{+ Provider: "_custom",+ ClientID: "CU_CL_ID",+ Scope: "profile email",+ AuthorizeURL: "https://example.org/oauth/authorize",+ })+ svc := web.NewOAuthService("http://login.test.fider.io:3000", tenants)+ authURL, err := svc.GetAuthURL("_custom", "http://example.org", "456")++ Expect(err).IsNil()+ Expect(authURL).Equals("https://example.org/oauth/authorize?client_id=CU_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2F_custom%2Fcallback&response_type=code&scope=profile+email&state=http%3A%2F%2Fexample.org%7C456")}func TestParseProfileResponse_AllFields(t *testing.T) {RegisterT(t)- svc := web.NewOAuthService("http://login.test.fider.io:3000")- profile, err := svc.ParseProfileResponse(+ storage := inmemory.NewTenantStorage()+ storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{+ Provider: "_test1",+ JSONUserIDPath: "id",+ JSONUserNamePath: "name",+ JSONUserEmailPath: "email",+ })+ svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)+ profile, err := svc.ParseRawProfile(+ "_test1",`{"name":"Jon Snow","email":"jon\u0040got.com","id":"789654"}`,- &models.OAuthConfig{- JSONUserIDPath: "id",- JSONNamePath: "name",- JSONEmailPath: "email",- },)Expect(err).IsNil()@@ -63,14 +84,17 @@ func TestParseProfileResponse_AllFields(t *testing.T) {func TestParseProfileResponse_WithoutEmail(t *testing.T) {RegisterT(t)- svc := web.NewOAuthService("http://login.test.fider.io:3000")- profile, err := svc.ParseProfileResponse(+ storage := inmemory.NewTenantStorage()+ storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{+ Provider: "_test1",+ JSONUserIDPath: "id",+ JSONUserNamePath: "name",+ JSONUserEmailPath: "email",+ })+ svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)+ profile, err := svc.ParseRawProfile(+ "_test1",`{"name":"Jon Snow","id":"1"}`,- &models.OAuthConfig{- JSONUserIDPath: "id",- JSONNamePath: "name",- JSONEmailPath: "email",- },)Expect(err).IsNil()@@ -82,8 +106,16 @@ func TestParseProfileResponse_WithoutEmail(t *testing.T) {func TestParseProfileResponse_NestedData(t *testing.T) {RegisterT(t)- svc := web.NewOAuthService("http://login.test.fider.io:3000")- profile, err := svc.ParseProfileResponse(+ storage := inmemory.NewTenantStorage()+ storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{+ Provider: "_test1",+ JSONUserIDPath: "id",+ JSONUserNamePath: "profile.name",+ JSONUserEmailPath: "profile.email",+ })+ svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)+ profile, err := svc.ParseRawProfile(+ "_test1",`{"id": "123","profile": {@@ -91,11 +123,6 @@ func TestParseProfileResponse_NestedData(t *testing.T) {"email": "[email protected]"}}`,- &models.OAuthConfig{- JSONUserIDPath: "id",- JSONNamePath: "profile.name",- JSONEmailPath: "profile.email",- },)Expect(err).IsNil()@@ -107,8 +134,16 @@ func TestParseProfileResponse_NestedData(t *testing.T) {func TestParseProfileResponse_WithFallback(t *testing.T) {RegisterT(t)- svc := web.NewOAuthService("http://login.test.fider.io:3000")- profile, err := svc.ParseProfileResponse(+ storage := inmemory.NewTenantStorage()+ storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{+ Provider: "_test1",+ JSONUserIDPath: "id",+ JSONUserNamePath: "profile.name, profile.login",+ JSONUserEmailPath: "profile.email",+ })+ svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)+ profile, err := svc.ParseRawProfile(+ "_test1",`{"id": 123,"profile": {@@ -116,11 +151,6 @@ func TestParseProfileResponse_WithFallback(t *testing.T) {"email": "[email protected]"}}`,- &models.OAuthConfig{- JSONUserIDPath: "id",- JSONNamePath: "profile.name, profile.login",- JSONEmailPath: "profile.email",- },)Expect(err).IsNil()@@ -132,19 +162,22 @@ func TestParseProfileResponse_WithFallback(t *testing.T) {func TestParseProfileResponse_UseEmailWhenNameIsEmpty(t *testing.T) {RegisterT(t)- svc := web.NewOAuthService("http://login.test.fider.io:3000")- profile, err := svc.ParseProfileResponse(+ storage := inmemory.NewTenantStorage()+ storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{+ Provider: "_test1",+ JSONUserIDPath: "id",+ JSONUserNamePath: "profile.name",+ JSONUserEmailPath: "profile.email",+ })+ svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)+ profile, err := svc.ParseRawProfile(+ "_test1",`{"id": "123","profile": {"email": "[email protected]"}}`,- &models.OAuthConfig{- JSONUserIDPath: "id",- JSONNamePath: "profile.name",- JSONEmailPath: "profile.email",- },)Expect(err).IsNil()@@ -156,8 +189,16 @@ func TestParseProfileResponse_UseEmailWhenNameIsEmpty(t *testing.T) {func TestParseProfileResponse_InvalidEmail(t *testing.T) {RegisterT(t)- svc := web.NewOAuthService("http://login.test.fider.io:3000")- profile, err := svc.ParseProfileResponse(+ storage := inmemory.NewTenantStorage()+ storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{+ Provider: "_test1",+ JSONUserIDPath: "id",+ JSONUserNamePath: "profile.name",+ JSONUserEmailPath: "profile.email",+ })+ svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)+ profile, err := svc.ParseRawProfile(+ "_test1",`{"id": "AB123","profile": {@@ -165,11 +206,6 @@ func TestParseProfileResponse_InvalidEmail(t *testing.T) {"email": "jon"}}`,- &models.OAuthConfig{- JSONUserIDPath: "id",- JSONNamePath: "profile.name",- JSONEmailPath: "profile.email",- },)Expect(err).IsNil()@@ -181,14 +217,17 @@ func TestParseProfileResponse_InvalidEmail(t *testing.T) {func TestParseProfileResponse_EmptyID(t *testing.T) {RegisterT(t)- svc := web.NewOAuthService("http://login.test.fider.io:3000")- profile, err := svc.ParseProfileResponse(+ storage := inmemory.NewTenantStorage()+ storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{+ Provider: "_test1",+ JSONUserIDPath: "id",+ JSONUserNamePath: "name",+ JSONUserEmailPath: "email",+ })+ svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)+ profile, err := svc.ParseRawProfile(+ "_test1",`{}`,- &models.OAuthConfig{- JSONUserIDPath: "id",- JSONNamePath: "name",- JSONEmailPath: "email",- },)Expect(errors.Cause(err)).Equals(oauth.ErrUserIDRequired)@@ -198,14 +237,17 @@ func TestParseProfileResponse_EmptyID(t *testing.T) {func TestParseProfileResponse_EmptyName(t *testing.T) {RegisterT(t)- svc := web.NewOAuthService("http://login.test.fider.io:3000")- profile, err := svc.ParseProfileResponse(+ storage := inmemory.NewTenantStorage()+ storage.SaveOAuthConfig(&models.CreateEditOAuthConfig{+ Provider: "_test1",+ JSONUserIDPath: "id",+ JSONUserNamePath: "name",+ JSONUserEmailPath: "email",+ })+ svc := web.NewOAuthService("http://login.test.fider.io:3000", storage)+ profile, err := svc.ParseRawProfile(+ "_test1",`{ "id": "A0" }`,- &models.OAuthConfig{- JSONUserIDPath: "id",- JSONNamePath: "name",- JSONEmailPath: "email",- },)Expect(err).IsNil()diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.goindex bd3a37f88..f0fc21ecb 100644--- a/app/pkg/web/renderer.go+++ b/app/pkg/web/renderer.go@@ -133,7 +133,7 @@ func (r *Renderer) Render(w io.Writer, name string, props Props, ctx *Context) {oauthProviders := make([]*oauth.ProviderOption, 0)if !ctx.IsAuthenticated() && ctx.Services() != nil {- oauthProviders, err = ctx.Services().OAuth.ListProviders()+ oauthProviders, err = ctx.Services().OAuth.ListActiveProviders()if err != nil {panic(errors.Wrap(err, "failed to get list of providers"))}diff --git a/app/storage/inmemory/tenant.go b/app/storage/inmemory/tenant.goindex cecd52b7a..20e048cb5 100644--- a/app/storage/inmemory/tenant.go+++ b/app/storage/inmemory/tenant.go@@ -18,6 +18,17 @@ type TenantStorage struct {user *models.Userverifications []*models.EmailVerificationtenantLogos map[int]*models.Upload+ oauthConfigs []*models.OAuthConfig+}++//NewTenantStorage creates a new TenantStorage+func NewTenantStorage() *TenantStorage {+ return &TenantStorage{+ tenants: make([]*models.Tenant, 0),+ verifications: make([]*models.EmailVerification, 0),+ tenantLogos: make(map[int]*models.Upload, 0),+ oauthConfigs: make([]*models.OAuthConfig, 0),+ }}// SetCurrentTenant tenant@@ -190,3 +201,53 @@ func (s *TenantStorage) GetUpload(id int) (*models.Upload, error) {}return nil, app.ErrNotFound}++// SaveOAuthConfig saves given config into database+func (s *TenantStorage) SaveOAuthConfig(config *models.CreateEditOAuthConfig) error {+ for _, c := range s.oauthConfigs {+ if c.ID == config.ID {+ c.Provider = config.Provider+ c.DisplayName = config.DisplayName+ c.ClientID = config.ClientID+ c.ClientSecret = config.ClientSecret+ c.AuthorizeURL = config.AuthorizeURL+ c.TokenURL = config.TokenURL+ c.Scope = config.Scope+ c.ProfileURL = config.ProfileURL+ c.JSONUserIDPath = config.JSONUserIDPath+ c.JSONUserNamePath = config.JSONUserNamePath+ c.JSONUserEmailPath = config.JSONUserEmailPath+ return nil+ }+ }+ s.oauthConfigs = append(s.oauthConfigs, &models.OAuthConfig{+ ID: config.ID,+ Provider: config.Provider,+ DisplayName: config.DisplayName,+ ClientID: config.ClientID,+ ClientSecret: config.ClientSecret,+ AuthorizeURL: config.AuthorizeURL,+ TokenURL: config.TokenURL,+ Scope: config.Scope,+ ProfileURL: config.ProfileURL,+ JSONUserIDPath: config.JSONUserIDPath,+ JSONUserNamePath: config.JSONUserNamePath,+ JSONUserEmailPath: config.JSONUserEmailPath,+ })+ return nil+}++// GetOAuthConfigByProvider returns a custom OAuth configuration by provider name+func (s *TenantStorage) GetOAuthConfigByProvider(provider string) (*models.OAuthConfig, error) {+ for _, c := range s.oauthConfigs {+ if c.Provider == provider {+ return c, nil+ }+ }+ return nil, app.ErrNotFound+}++// ListOAuthConfig returns a list of all custom OAuth provider for current tenant+func (s *TenantStorage) ListOAuthConfig() ([]*models.OAuthConfig, error) {+ return s.oauthConfigs, nil+}diff --git a/app/storage/postgres/tenant.go b/app/storage/postgres/tenant.goindex d8bc8c153..34422d73b 100644--- a/app/storage/postgres/tenant.go+++ b/app/storage/postgres/tenant.go@@ -83,6 +83,42 @@ func (t *dbEmailVerification) toModel() *models.EmailVerification {return model}+type dbOAuthConfig struct {+ ID int `db:"id"`+ Provider string `db:"provider"`+ DisplayName string `db:"display_name"`+ LogoID dbx.NullInt `db:"logo_id"`+ Status int `db:"status"`+ ClientID string `db:"client_id"`+ ClientSecret string `db:"client_secret"`+ AuthorizeURL string `db:"authorize_url"`+ TokenURL string `db:"token_url"`+ Scope string `db:"scope"`+ ProfileURL string `db:"profile_url"`+ JSONUserIDPath string `db:"json_user_id_path"`+ JSONUserNamePath string `db:"json_user_name_path"`+ JSONUserEmailPath string `db:"json_user_email_path"`+}++func (m *dbOAuthConfig) toModel() *models.OAuthConfig {+ return &models.OAuthConfig{+ ID: m.ID,+ Provider: m.Provider,+ DisplayName: m.DisplayName,+ Status: m.Status,+ LogoID: int(m.LogoID.Int64),+ ClientID: m.ClientID,+ ClientSecret: m.ClientSecret,+ AuthorizeURL: m.AuthorizeURL,+ TokenURL: m.TokenURL,+ ProfileURL: m.ProfileURL,+ Scope: m.Scope,+ JSONUserIDPath: m.JSONUserIDPath,+ JSONUserNamePath: m.JSONUserNamePath,+ JSONUserEmailPath: m.JSONUserEmailPath,+ }+}+// TenantStorage contains read and write operations for tenantstype TenantStorage struct {trx *dbx.Trx@@ -176,12 +212,6 @@ func (s *TenantStorage) UpdateSettings(settings *models.UpdateTenantSettings) erreturn errors.Wrap(err, "failed update tenant logo")}- // Remove upload based on old tenant logo ID- err := s.RemoveUpload(s.current.LogoID)- if err != nil {- return errors.Wrap(err, "failed delete old tenant logo")- }-// Update reference to new logo IDs.current.LogoID = int(newLogoID.Int64)}@@ -203,18 +233,6 @@ func (s *TenantStorage) SaveNewUpload(content []byte) (int, error) {return newID, nil}-// RemoveUpload by given id-func (s *TenantStorage) RemoveUpload(uploadID int) error {- if uploadID > 0 {- query := "DELETE FROM uploads WHERE id = $1 AND tenant_id = $2"- _, err := s.trx.Execute(query, uploadID, s.current.ID)- if err != nil {- return errors.Wrap(err, "failed delete upload")- }- }- return nil-}-// UpdateAdvancedSettings of current tenantfunc (s *TenantStorage) UpdateAdvancedSettings(settings *models.UpdateTenantAdvancedSettings) error {query := "UPDATE tenants SET custom_css = $1 WHERE id = $2"@@ -318,3 +336,110 @@ func (s *TenantStorage) GetUpload(id int) (*models.Upload, error) {}return upload, nil}++// SaveOAuthConfig saves given config into database+func (s *TenantStorage) SaveOAuthConfig(config *models.CreateEditOAuthConfig) error {+ var err error++ if config.ID == 0 {+ query := `INSERT INTO oauth_providers (+ tenant_id, provider, display_name, status,+ client_id, client_secret, authorize_url,+ profile_url, token_url, scope, json_user_id_path,+ json_user_name_path, json_user_email_path+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)+ RETURNING id`++ err = s.trx.Get(&config.ID, query, s.current.ID, config.Provider,+ config.DisplayName, config.Status, config.ClientID, config.ClientSecret,+ config.AuthorizeURL, config.ProfileURL, config.TokenURL,+ config.Scope, config.JSONUserIDPath, config.JSONUserNamePath,+ config.JSONUserEmailPath)+ } else {+ query := `+ UPDATE oauth_providers+ SET display_name = $3, status = $4, client_id = $5, client_secret = $6,+ authorize_url = $7, profile_url = $8, token_url = $9, scope = $10,+ json_user_id_path = $11, json_user_name_path = $12, json_user_email_path = $13+ WHERE tenant_id = $1 AND id = $2`++ _, err = s.trx.Execute(query, s.current.ID, config.ID,+ config.DisplayName, config.Status, config.ClientID, config.ClientSecret,+ config.AuthorizeURL, config.ProfileURL, config.TokenURL,+ config.Scope, config.JSONUserIDPath, config.JSONUserNamePath,+ config.JSONUserEmailPath)+ }++ if err != nil {+ return errors.Wrap(err, "failed to save OAuth Provider")+ }++ // Only update OAuth logo if there's a change+ if config.Logo != nil {+ var newLogoID sql.NullInt64++ // If there's an upload, save it+ if !config.Logo.Remove && len(config.Logo.Upload.Content) > 0 {+ uploadID, err := s.SaveNewUpload(config.Logo.Upload.Content)+ if err != nil {+ return errors.Wrap(err, "failed to upload new OAuth logo")+ }+ newLogoID.Scan(uploadID)+ }++ // Update current OAuth logo to either new ID or null+ query := "UPDATE oauth_providers SET logo_id = $1 WHERE tenant_id = $2 and id = $3"+ _, err = s.trx.Execute(query, newLogoID, s.current.ID, config.ID)+ if err != nil {+ return errors.Wrap(err, "failed update OAuth logo")+ }+ }++ return nil+}++// GetOAuthConfigByProvider returns a custom OAuth configuration by provider name+func (s *TenantStorage) GetOAuthConfigByProvider(provider string) (*models.OAuthConfig, error) {+ if s.current == nil {+ return nil, app.ErrNotFound+ }++ config := &dbOAuthConfig{}+ err := s.trx.Get(config, `+ SELECT id, provider, display_name, status, logo_id,+ client_id, client_secret, authorize_url,+ profile_url, token_url, scope, json_user_id_path,+ json_user_name_path, json_user_email_path+ FROM oauth_providers+ WHERE tenant_id = $1 AND provider = $2+ `, s.current.ID, provider)+ if err != nil {+ return nil, err+ }+ return config.toModel(), nil+}++// ListOAuthConfig returns a list of all custom OAuth provider for current tenant+func (s *TenantStorage) ListOAuthConfig() ([]*models.OAuthConfig, error) {+ configs := []*dbOAuthConfig{}+ if s.current != nil {+ err := s.trx.Select(&configs, `+ SELECT id, provider, display_name, status, logo_id,+ client_id, client_secret, authorize_url,+ profile_url, token_url, scope, json_user_id_path,+ json_user_name_path, json_user_email_path+ FROM oauth_providers+ WHERE tenant_id = $1+ ORDER BY id+ `, s.current.ID)+ if err != nil {+ return nil, err+ }+ }++ var result = make([]*models.OAuthConfig, len(configs))+ for i, config := range configs {+ result[i] = config.toModel()+ }+ return result, nil+}diff --git a/app/storage/postgres/tenant_test.go b/app/storage/postgres/tenant_test.goindex 51b0f883a..90d850607 100644--- a/app/storage/postgres/tenant_test.go+++ b/app/storage/postgres/tenant_test.go@@ -186,8 +186,8 @@ func TestTenantStorage_UpdateSettings_WithLogo(t *testing.T) {logo, _ := ioutil.ReadFile(env.Path("./favicon.ico"))settings := &models.UpdateTenantSettings{- Logo: &models.UpdateTenantSettingsLogo{- Upload: &models.UpdateTenantSettingsLogoUpload{+ Logo: &models.ImageUpload{+ Upload: &models.ImageUploadData{Content: logo,},},@@ -226,8 +226,8 @@ func TestTenantStorage_UpdateSettings_ReplaceLogo(t *testing.T) {logo, _ := ioutil.ReadFile(env.Path("./favicon.ico"))settings := &models.UpdateTenantSettings{- Logo: &models.UpdateTenantSettingsLogo{- Upload: &models.UpdateTenantSettingsLogoUpload{+ Logo: &models.ImageUpload{+ Upload: &models.ImageUploadData{Content: logo,},},@@ -259,10 +259,6 @@ func TestTenantStorage_UpdateSettings_ReplaceLogo(t *testing.T) {Expect(upload.Content).Equals(newLogo)Expect(upload.Size).Equals(len(newLogo))Expect(upload.ContentType).Equals("text/html; charset=utf-8")-- upload, err = tenants.GetUpload(firstLogoID)- Expect(err).Equals(app.ErrNotFound)- Expect(upload).IsNil()}func TestTenantStorage_AdvancedSettings(t *testing.T) {@@ -371,3 +367,97 @@ func TestTenantStorage_FindUnknownVerificationKey(t *testing.T) {Expect(errors.Cause(err)).Equals(app.ErrNotFound)Expect(result).IsNil()}++func TestTenantStorage_Save_Get_ListOAuthConfig(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ tenant, _ := tenants.GetByDomain("demo")+ tenants.SetCurrentTenant(tenant)++ config, err := tenants.GetOAuthConfigByProvider("_TEST")+ Expect(config).IsNil()+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)++ logo, _ := ioutil.ReadFile(env.Path("./favicon.ico"))++ err = tenants.SaveOAuthConfig(&models.CreateEditOAuthConfig{+ ID: 0,+ Logo: &models.ImageUpload{+ Upload: &models.ImageUploadData{+ Content: logo,+ ContentType: "image/vnd.microsoft.icon",+ },+ },+ Provider: "_TEST",+ DisplayName: "My Provider",+ ClientID: "823187ahjjfdha8fds7yfdashfjkdsa",+ ClientSecret: "jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij",+ AuthorizeURL: "http://provider/oauth/authorize",+ TokenURL: "http://provider/oauth/token",+ Scope: "profile email",+ ProfileURL: "http://provider/profile/me",+ JSONUserIDPath: "user.id",+ JSONUserNamePath: "user.name",+ JSONUserEmailPath: "user.email",+ })+ Expect(err).IsNil()++ config, err = tenants.GetOAuthConfigByProvider("_TEST")+ Expect(err).IsNil()+ Expect(config.ID).Equals(1)+ Expect(config.Provider).Equals("_TEST")+ Expect(config.DisplayName).Equals("My Provider")+ Expect(config.ClientID).Equals("823187ahjjfdha8fds7yfdashfjkdsa")+ Expect(config.ClientSecret).Equals("jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij")+ Expect(config.AuthorizeURL).Equals("http://provider/oauth/authorize")+ Expect(config.TokenURL).Equals("http://provider/oauth/token")+ Expect(config.Scope).Equals("profile email")+ Expect(config.Status).Equals(0)+ Expect(config.ProfileURL).Equals("http://provider/profile/me")+ Expect(config.JSONUserIDPath).Equals("user.id")+ Expect(config.JSONUserNamePath).Equals("user.name")+ Expect(config.JSONUserEmailPath).Equals("user.email")++ upload, err := tenants.GetUpload(config.LogoID)+ Expect(err).IsNil()+ Expect(upload.Content).Equals(logo)+ Expect(upload.ContentType).Equals("image/vnd.microsoft.icon")++ err = tenants.SaveOAuthConfig(&models.CreateEditOAuthConfig{+ ID: config.ID,+ Logo: &models.ImageUpload{+ Remove: true,+ },+ Provider: "_TEST2222", //this has to be ignored+ DisplayName: "New My Provider",+ ClientID: "New 823187ahjjfdha8fds7yfdashfjkdsa",+ ClientSecret: "New jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij",+ AuthorizeURL: "New http://provider/oauth/authorize",+ TokenURL: "New http://provider/oauth/token",+ Scope: "New profile email",+ ProfileURL: "New http://provider/profile/me",+ JSONUserIDPath: "New user.id",+ JSONUserNamePath: "New user.name",+ JSONUserEmailPath: "New user.email",+ })+ Expect(err).IsNil()++ configs, err := tenants.ListOAuthConfig()+ Expect(err).IsNil()+ Expect(configs).HasLen(1)+ Expect(configs[0].ID).Equals(1)+ Expect(configs[0].LogoID).Equals(0)+ Expect(configs[0].Provider).Equals("_TEST")+ Expect(configs[0].DisplayName).Equals("New My Provider")+ Expect(configs[0].ClientID).Equals("New 823187ahjjfdha8fds7yfdashfjkdsa")+ Expect(configs[0].ClientSecret).Equals("New jijads78d76cn347768x3t4668q275@ˆ&Tnycasdgsacuyhij")+ Expect(configs[0].AuthorizeURL).Equals("New http://provider/oauth/authorize")+ Expect(configs[0].TokenURL).Equals("New http://provider/oauth/token")+ Expect(configs[0].Scope).Equals("New profile email")+ Expect(configs[0].Status).Equals(0)+ Expect(configs[0].ProfileURL).Equals("New http://provider/profile/me")+ Expect(configs[0].JSONUserIDPath).Equals("New user.id")+ Expect(configs[0].JSONUserNamePath).Equals("New user.name")+ Expect(configs[0].JSONUserEmailPath).Equals("New user.email")+}diff --git a/app/storage/storage.go b/app/storage/storage.goindex c53584c4e..803c4dc88 100644--- a/app/storage/storage.go+++ b/app/storage/storage.go@@ -72,6 +72,9 @@ type Tenant interface {FindVerificationByKey(kind models.EmailVerificationKind, key string) (*models.EmailVerification, error)SetKeyAsVerified(key string) errorGetUpload(id int) (*models.Upload, error)+ SaveOAuthConfig(config *models.CreateEditOAuthConfig) error+ GetOAuthConfigByProvider(provider string) (*models.OAuthConfig, error)+ ListOAuthConfig() ([]*models.OAuthConfig, error)}// Tag contains read and write operations for tagsdiff --git a/migrations/201807122132_create_oauth_providers.sql b/migrations/201807122132_create_oauth_providers.sqlnew file mode 100644index 000000000..ed1570a9f--- /dev/null+++ b/migrations/201807122132_create_oauth_providers.sql@@ -0,0 +1,23 @@+create table if not exists oauth_providers (+ id serial not null,+ tenant_id int not null,+ logo_id int null,+ provider varchar(30) not null,+ display_name varchar(50) not null,+ status int not null,+ client_id varchar(100) not null,+ client_secret varchar(500) not null,+ authorize_url varchar(300) not null,+ token_url varchar(300) not null,+ profile_url varchar(300) not null,+ scope varchar(100) not null,+ json_user_id_path varchar(100) not null,+ json_user_name_path varchar(100) not null,+ json_user_email_path varchar(100) not null,+ created_on timestamptz not null default now(),+ primary key (id),+ foreign key (tenant_id) references tenants(id),+ foreign key (logo_id, tenant_id) references uploads(id, tenant_id)+);++CREATE UNIQUE INDEX tenant_id_provider_key ON oauth_providers (tenant_id, provider);\ No newline at end of filediff --git a/public/assets/styles/main.scss b/public/assets/styles/main.scssindex 6bd5ff56a..ffdb4c099 100644--- a/public/assets/styles/main.scss+++ b/public/assets/styles/main.scss@@ -34,13 +34,14 @@ button, input, optgroup, select, textarea {*******************************/h1, h2, h3, h4, h5 {- line-height: 18px;+ line-height: 120%;margin: 25px 0em 14px;font-weight: 600;padding: 0;+ font-weight: 600;}+h1 {- line-height: 28px;font-size: 28px;}h2 {@@ -193,12 +194,9 @@ body, h1, h2, h3, h4, h5, .ui, input {-webkit-font-smoothing: antialiased;}-h1, h2, h3, h4, h5 {- font-weight: 600;-}-.info {font-size: 80%;+ font-weight: 400;color: rgba($text-color, .8);}diff --git a/public/assets/styles/variables.scss b/public/assets/styles/variables.scssindex c53d3c7d4..867e50d8a 100644--- a/public/assets/styles/variables.scss+++ b/public/assets/styles/variables.scss@@ -30,6 +30,7 @@ $gray-darkest: rgba(0, 0, 0, 0.5);$green: #15CD72;$green-darker: #0CB863;$red: #db2828;+$orange: #ff9320;$error: #ef7878;// Queriesdiff --git a/public/components/common/Button.scss b/public/components/common/Button.scssindex 1a51365a6..7c23a5c4e 100644--- a/public/components/common/Button.scss+++ b/public/components/common/Button.scss@@ -124,33 +124,22 @@background-color: $white;color: $text-color;text-align: center;+ height: 40px;+ line-height: 22px;box-shadow: 0 0 0 1px rgba(20,11,47,0.1), 0 2px 4px -2px rgba(0,0,0,0.2);- .svg {+ &.m-loading img {+ display: none;+ }++ img {display: inline-block;vertical-align: middle;width: 24px;- background-size: 100%;height: 24px;margin-right: 5px;}- &.m-loading .svg {- display: none;- }-- &.m-google .svg {- background: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHg9IjBweCIgeT0iMHB4IgogICAgIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIKICAgICB2aWV3Qm94PSIwIDAgNDggNDgiCiAgICAgc3R5bGU9ImZpbGw6IzAwMDAwMDsiPjxnIGlkPSJzdXJmYWNlMSI+PHBhdGggc3R5bGU9IiBmaWxsOiNGRkMxMDc7IiBkPSJNIDQzLjYwOTM3NSAyMC4wODIwMzEgTCA0MiAyMC4wODIwMzEgTCA0MiAyMCBMIDI0IDIwIEwgMjQgMjggTCAzNS4zMDQ2ODggMjggQyAzMy42NTIzNDQgMzIuNjU2MjUgMjkuMjIyNjU2IDM2IDI0IDM2IEMgMTcuMzcxMDk0IDM2IDEyIDMwLjYyODkwNiAxMiAyNCBDIDEyIDE3LjM3MTA5NCAxNy4zNzEwOTQgMTIgMjQgMTIgQyAyNy4wNTg1OTQgMTIgMjkuODQzNzUgMTMuMTUyMzQ0IDMxLjk2MDkzOCAxNS4wMzkwNjMgTCAzNy42MTcxODggOS4zODI4MTMgQyAzNC4wNDY4NzUgNi4wNTQ2ODggMjkuMjY5NTMxIDQgMjQgNCBDIDEyLjk1MzEyNSA0IDQgMTIuOTUzMTI1IDQgMjQgQyA0IDM1LjA0Njg3NSAxMi45NTMxMjUgNDQgMjQgNDQgQyAzNS4wNDY4NzUgNDQgNDQgMzUuMDQ2ODc1IDQ0IDI0IEMgNDQgMjIuNjYwMTU2IDQzLjg2MzI4MSAyMS4zNTE1NjMgNDMuNjA5Mzc1IDIwLjA4MjAzMSBaICI+PC9wYXRoPjxwYXRoIHN0eWxlPSIgZmlsbDojRkYzRDAwOyIgZD0iT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AxNyAzMSAxNy42MDE1NjMgMzEgMTguNzIyNjU2IEwgMzEgMjEgTCAzNSAyMSBaICI+PC9wYXRoPjwvZz48L3N2Zz4=') 50% 50% no-repeat;- }-&:hover {background-color: #fafafb;color: $text-color;diff --git a/public/components/common/Button.tsx b/public/components/common/Button.tsxindex b7ee9cb31..04de1b9af 100644--- a/public/components/common/Button.tsx+++ b/public/components/common/Button.tsx@@ -84,12 +84,18 @@ export class Button extends React.Component<ButtonProps, ButtonState> {{this.props.children}</a>);- } else {+ } else if (this.props.onClick) {return (<button type="button" className={className} onClick={this.click}>{this.props.children}</button>);+ } else {+ return (+ <button type="button" className={className}>+ {this.props.children}+ </button>+ );}}}diff --git a/public/components/common/Header.tsx b/public/components/common/Header.tsxindex b685c5511..17538194f 100644--- a/public/components/common/Header.tsx+++ b/public/components/common/Header.tsx@@ -1,7 +1,7 @@import "./Header.scss";import * as React from "react";-import { SignInModal, EnvironmentInfo, Gravatar, Logo } from "@fider/components";+import { SignInModal, EnvironmentInfo, Gravatar, TenantLogo } from "@fider/components";import { actions, Fider } from "@fider/services";interface HeaderState {@@ -73,7 +73,7 @@ export class Header extends React.Component<{}, HeaderState> {<div className="c-menu"><div className="container"><a href="/" className="c-menu-item-title">- <Logo size={100} />+ <TenantLogo size={100} /><span>{Fider.session.tenant.name}</span></a>{showRightMenu && (diff --git a/public/components/common/Heading.scss b/public/components/common/Heading.scssindex fb79b5f85..3c0395c49 100644--- a/public/components/common/Heading.scss+++ b/public/components/common/Heading.scss@@ -1,11 +1,7 @@@import '~@fider/assets/styles/variables.scss';.c-heading {- display: inline-block;- margin-bottom: 10px;- @include media("sm") {- font-size: $font-size-xlarge;- }+ margin: 0px 0px 10px 0px;.c-heading-content {display: table-cell;@@ -14,12 +10,8 @@.c-heading-subtitle {font-weight: 400;margin-top: 5px;- color: $gray-darker;+ color: $gray-darkest;font-size: $font-size;-- @include media("sm") {- display: none;- }}}diff --git a/public/components/common/Heading.tsx b/public/components/common/Heading.tsxindex 0162edb4f..c35b4d58f 100644--- a/public/components/common/Heading.tsx+++ b/public/components/common/Heading.tsx@@ -9,6 +9,7 @@ interface HeadingLogo {size?: "normal" | "small";icon?: string;subtitle?: string;+ className?: string;}export const Heading = (props: HeadingLogo) => {@@ -18,7 +19,8 @@ export const Heading = (props: HeadingLogo) => {const className = classSet({"c-heading": true,"m-dividing": props.dividing || false,- [`m-${size}`]: true+ [`m-${size}`]: true,+ [`${props.className}`]: props.className});const iconClassName = classSet({diff --git a/public/components/common/Logo.tsx b/public/components/common/Logo.tsxindex 9fee26856..4a16a7d7c 100644--- a/public/components/common/Logo.tsx+++ b/public/components/common/Logo.tsx@@ -1,22 +1,58 @@import * as React from "react";-import { Fider } from "@fider/services";+import { Fider, uploadedImageUrl } from "@fider/services";-interface LogoProps {- size: 50 | 100 | 200;+type Size = 24 | 50 | 100 | 200;++interface TenantLogoProps {+ size: Size;}-export const LogoUrl = (size: 50 | 100 | 200): string | undefined => {+export const TenantLogoUrl = (size: Size): string | undefined => {const tenant = Fider.session.tenant;if (tenant && tenant.logoId > 0) {- return `${Fider.settings.assetsURL}/images/${size}/${Fider.session.tenant.logoId}`;+ return uploadedImageUrl(tenant.logoId, size);}return undefined;};-export const Logo = (props: LogoProps) => {+export const TenantLogo = (props: TenantLogoProps) => {const tenant = Fider.session.tenant;if (tenant && tenant.logoId > 0) {- return <img src={LogoUrl(props.size)} alt={tenant.name} />;+ return <img src={TenantLogoUrl(props.size)} alt={tenant.name} />;+ }+ return null;+};++interface OAuthProviderLogoProps {+ option: {+ provider?: string;+ displayName: string;+ logoId?: number;+ };+}++const systemProvidersLogo: { [key: string]: string } = {+ google: `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHg9IjBweCIgeT0iMHB4IgogICAgIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIKICAgICB2aWV3Qm94PSIwIDAgNDggNDgiCiAgICAgc3R5bGU9ImZpbGw6I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MTYgOS44MDQ2ODggQyAxNy4wMTk1MzEgOS44MDg1OTQgMTguMDQ2ODc1IDkuOTQxNDA2IDE5LjAwMzkwNiAxMC4yMDcwMzEgQyAyMS4yOTY4NzUgOC42NTYyNSAyMi4zMDA3ODEgOC45NzY1NjMgMjIuMzAwNzgxIDguOTc2NTYzIEMgMjIuOTU3MDMxIDEwLjYyODkwNiAyMi41NDY4NzUgMTEuODUxNTYzIDIyLjQyMTg3NSAxMi4xNTIzNDQgQyAyMy4xOTE0MDYgMTIuOTkyMTg4IDIzLjY1MjM0NCAxNC4wNjI1IDIzLjY1MjM0NCAxNS4zNzUgQyAyMy42NTIzNDQgMTkuOTg0Mzc1IDIwLjg0NzY1NiAyMC45OTYwOTQgMTguMTc1NzgxIDIxLjI5Njg3NSBDIDE4LjYwNTQ2OSAyMS42NjQwNjMgMTguOTg4MjgxIDIyLjM5ODQzOCAxOC45ODgyODEgMjMuNTE1NjI1IEMgMTguOTg4MjgxIDI1LjEyMTA5NCAxOC45NzY1NjMgMjYuNDE0MDYzIDE4Ljk3NjU2MyAyNi44MDg1OTQgQyAxOC45NzY1NjMgMjcuMTI4OTA2IDE5LjE5MTQwNiAyNy41MDM5MDYgMTkuODAwNzgxIDI3LjM4NjcxOSBDIDI0LjU2NjQwNiAyNS43OTY4NzUgMjggMjEuMzAwNzgxIDI4IDE2IEMgMjggOS4zNzEwOTQgMjIuNjI4OTA2IDQgMTYgNCBaICI+PC9wYXRoPjwvZz48L3N2Zz4="+};++export const OAuthProviderLogoUrl = (id?: number): string | undefined => {+ if (id && id > 0) {+ return uploadedImageUrl(id, 100);+ }+ return undefined;+};++export const OAuthProviderLogo = (props: OAuthProviderLogoProps) => {+ if (props.option.logoId && props.option.logoId > 0) {+ return <img src={OAuthProviderLogoUrl(props.option.logoId)} alt={props.option.displayName} />;+ }++ if (props.option.provider && props.option.provider in systemProvidersLogo) {+ return <img src={systemProvidersLogo[props.option.provider]} alt={props.option.displayName} />;}+return null;};diff --git a/public/components/common/SignInControl.scss b/public/components/common/SignInControl.scssindex a1570e379..590fd017a 100644--- a/public/components/common/SignInControl.scss+++ b/public/components/common/SignInControl.scss@@ -1,6 +1,15 @@+@import '~@fider/assets/styles/variables.scss';+.c-signin-control {text-align: center;+ .col-lf {+ width: 100%;+ }.l-social-col {padding: 10px 5px;+ max-width: 50%;+ }+ .l-social-col-100 {+ width: 100%;}}\ No newline at end of filediff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsxindex e02b2ab72..5c96ef96a 100644--- a/public/components/common/SignInControl.tsx+++ b/public/components/common/SignInControl.tsx@@ -48,11 +48,7 @@ export class SignInControl extends React.Component<SignInControlProps, SignInCon};public render() {- const oauthProviders = Fider.settings.oauth.map(o => (- <div key={o.provider} className="col-sm l-social-col">- <SocialSignInButton option={o} redirectTo={this.props.redirectTo} />- </div>- ));+ const providersLen = Fider.settings.oauth.length;if (!isCookieEnabled()) {return (@@ -65,9 +61,18 @@ export class SignInControl extends React.Component<SignInControlProps, SignInConreturn (<div className="c-signin-control">- {oauthProviders.length > 0 && (+ {providersLen > 0 && (<div>- <div className="row">{oauthProviders}</div>+ <div className="row">+ {Fider.settings.oauth.map((o, i) => (+ <React.Fragment key={o.provider}>+ {i % 4 === 0 && <div className="col-lf" />}+ <div className={`col-sm l-social-col ${providersLen === 1 ? "l-social-col-100" : ""}`}>+ <SocialSignInButton option={o} redirectTo={this.props.redirectTo} />+ </div>+ </React.Fragment>+ ))}+ </div><p className="info">We will never post to these accounts on your behalf.</p><div className="c-divider">OR</div></div>diff --git a/public/components/common/SocialSignInButton.tsx b/public/components/common/SocialSignInButton.tsxindex d98d939cf..234d4e0c6 100644--- a/public/components/common/SocialSignInButton.tsx+++ b/public/components/common/SocialSignInButton.tsx@@ -1,25 +1,33 @@import * as React from "react";-import { Button } from "@fider/components/common";-import { OAuthProviderOption } from "@fider/models";+import { Button, OAuthProviderLogo } from "@fider/components/common";import { classSet } from "@fider/services";interface SocialSignInButtonProps {- option: OAuthProviderOption;+ option: {+ displayName: string;+ provider?: string;+ url?: string;+ logoId?: number;+ logoUrl?: string;+ };redirectTo?: string;}export class SocialSignInButton extends React.Component<SocialSignInButtonProps, {}> {public render() {const redirectTo = this.props.redirectTo || location.href;- const href = `${this.props.option.url}?redirect=${redirectTo}`;+ const href = this.props.option.url ? `${this.props.option.url}?redirect=${redirectTo}` : undefined;const className = classSet({"m-social": true,- [`m-${this.props.option.provider}`]: true+ [`m-${this.props.option.provider}`]: this.props.option.provider});-return (<Button href={href} fluid={true} className={className}>- <i className="svg" />+ {this.props.option.logoUrl ? (+ <img src={this.props.option.logoUrl} />+ ) : (+ <OAuthProviderLogo option={this.props.option} />+ )}<span>{this.props.option.displayName}</span></Button>);diff --git a/public/components/common/Toggle.scss b/public/components/common/Toggle.scssindex c971172b3..c19cf9c18 100644--- a/public/components/common/Toggle.scss+++ b/public/components/common/Toggle.scss@@ -22,9 +22,9 @@label {display: inline-block;vertical-align: middle;- width: 2em;- height: 1em;- border-radius: 0.5em;+ width: 40px;+ height: 20px;+ border-radius: 10px;position: relative;cursor: pointer;background: $gray;@@ -32,10 +32,10 @@.switch {position: absolute;- width: 0.9em;- height: 0.9em;- margin-top: 0.05em;- margin-left: 0.05em;+ width: 19px;+ height: 18px;+ margin-top: 1px;+ margin-left: 1px;border-radius: 1em;background: $white;box-shadow: 5px 0px 28px -9px rgba(0, 0, 0, 0.75);@@ -48,7 +48,7 @@input:checked ~ label .switch {background: $white;- transform: translatex(1em);+ transform: translatex(19px);transition: transform .2s ease-in;}}diff --git a/public/components/common/form/Form.scss b/public/components/common/form/Form.scssindex 3b0ba8a34..98702cabf 100644--- a/public/components/common/form/Form.scss+++ b/public/components/common/form/Form.scss@@ -18,10 +18,6 @@clear: both;margin: 0 0 10px;- &:last-child {- margin-bottom: 0;- }-&.m-checkbox {label {font-weight: initial;diff --git a/public/components/common/form/ImageUploader.tsx b/public/components/common/form/ImageUploader.tsxindex 39a20531c..e30dd407a 100644--- a/public/components/common/form/ImageUploader.tsx+++ b/public/components/common/form/ImageUploader.tsx@@ -63,7 +63,8 @@ export class ImageUploader extends React.Component<ImageUploaderProps, ImageUplothis.setState({remove: true,- upload: undefined+ upload: undefined,+ previewUrl: undefined},() => {this.props.onChange(this.state, this.state.previewUrl);diff --git a/public/components/common/form/Input.tsx b/public/components/common/form/Input.tsxindex 6f2956dfa..58eb5d671 100644--- a/public/components/common/form/Input.tsx+++ b/public/components/common/form/Input.tsx@@ -7,6 +7,7 @@ import { Button } from "@fider/components";interface InputProps {field: string;label?: string;+ className?: string;autoFocus?: boolean;afterLabel?: JSX.Element;icon?: string;@@ -56,7 +57,8 @@ export class Input extends React.Component<InputProps, {}> {"c-form-field": true,"m-suffix": this.props.suffix,"m-error": hasError(this.props.field, ctx.error),- "m-icon": this.props.icon+ "m-icon": this.props.icon,+ [`${this.props.className}`]: this.props.className})}>{!!this.props.label && (diff --git a/public/models/settings.ts b/public/models/settings.tsindex 7b1d3e6d6..082f93a36 100644--- a/public/models/settings.ts+++ b/public/models/settings.ts@@ -1,7 +1,12 @@export interface OAuthProviderOption {provider: string;displayName: string;+ clientId: string;url: string;+ callbackUrl: string;+ logoId: number;+ isCustomProvider: boolean;+ isEnabled: boolean;}export interface SystemSettings {@@ -20,3 +25,24 @@ export interface SystemSettings {export interface UserSettings {[key: string]: string;}++export const OAuthConfigStatus = {+ Disabled: 1,+ Enabled: 2+};++export interface OAuthConfig {+ provider: string;+ displayName: string;+ status: number;+ clientId: string;+ clientSecret: string;+ authorizeUrl: string;+ tokenUrl: string;+ profileUrl: string;+ logoId: number;+ scope: string;+ jsonUserIdPath: string;+ jsonUserNamePath: string;+ jsonUserEmailPath: string;+}diff --git a/public/pages/Administration/components/AdminBasePage.scss b/public/pages/Administration/components/AdminBasePage.scssnew file mode 100644index 000000000..e5b2f6264--- /dev/null+++ b/public/pages/Administration/components/AdminBasePage.scss@@ -0,0 +1,7 @@+@import '~@fider/assets/styles/variables.scss';++@include media("sm") {+ .l-admin-heading .c-heading-subtitle {+ display: none;+ }+}\ No newline at end of filediff --git a/public/pages/Administration/components/AdminBasePage.tsx b/public/pages/Administration/components/AdminBasePage.tsxindex 4d8beb818..d1bdeac29 100644--- a/public/pages/Administration/components/AdminBasePage.tsx+++ b/public/pages/Administration/components/AdminBasePage.tsx@@ -1,3 +1,5 @@+import "./AdminBasePage.scss";+import * as React from "react";import { Heading } from "@fider/components";import { SideMenu, SideMenuToggler } from "./";@@ -20,7 +22,7 @@ export abstract class AdminBasePage<P, S> extends React.Component<P, S> {public render() {return (<div id={this.id} className="page container">- <Heading title={this.title} icon={this.icon} subtitle={this.subtitle} />+ <Heading title={this.title} icon={this.icon} subtitle={this.subtitle} className="l-admin-heading" /><SideMenuToggler onToggle={this.toggleSideMenu} /><div className="row">diff --git a/public/pages/Administration/components/OAuthForm.tsx b/public/pages/Administration/components/OAuthForm.tsxnew file mode 100644index 000000000..bb4282369--- /dev/null+++ b/public/pages/Administration/components/OAuthForm.tsx@@ -0,0 +1,351 @@+import "./TagForm.scss";++import * as React from "react";+import { OAuthConfig, OAuthConfigStatus } from "@fider/models";+import { Failure, Fider, actions, navigator } from "@fider/services";+import {+ Form,+ Button,+ Input,+ Heading,+ SocialSignInButton,+ Field,+ ImageUploadState,+ ImageUploader,+ Toggle,+ OAuthProviderLogoUrl+} from "@fider/components";++interface OAuthFormProps {+ config?: OAuthConfig;+ onCancel: () => void;+}++export interface OAuthFormState {+ provider: string;+ displayName: string;+ enabled: boolean;+ clientId: string;+ clientSecret: string;+ clientSecretEnabled: boolean;+ authorizeUrl: string;+ tokenUrl: string;+ profileUrl: string;+ scope: string;+ jsonUserIdPath: string;+ jsonUserNamePath: string;+ jsonUserEmailPath: string;+ logoUrl?: string;+ logo?: ImageUploadState;+ error?: Failure;+}++export class OAuthForm extends React.Component<OAuthFormProps, OAuthFormState> {+ constructor(props: OAuthFormProps) {+ super(props);+ this.state = {+ provider: this.props.config ? this.props.config.provider : "",+ enabled: this.props.config ? this.props.config.status === OAuthConfigStatus.Enabled : false,+ displayName: this.props.config ? this.props.config.displayName : "",+ clientId: this.props.config ? this.props.config.clientId : "",+ clientSecret: this.props.config ? this.props.config.clientSecret : "",+ clientSecretEnabled: !this.props.config,+ authorizeUrl: this.props.config ? this.props.config.authorizeUrl : "",+ tokenUrl: this.props.config ? this.props.config.tokenUrl : "",+ profileUrl: this.props.config ? this.props.config.profileUrl : "",+ scope: this.props.config ? this.props.config.scope : "",+ jsonUserIdPath: this.props.config ? this.props.config.jsonUserIdPath : "",+ jsonUserNamePath: this.props.config ? this.props.config.jsonUserNamePath : "",+ jsonUserEmailPath: this.props.config ? this.props.config.jsonUserEmailPath : "",+ logoUrl: this.props.config ? OAuthProviderLogoUrl(this.props.config.logoId) : ""+ };+ }++ private handleSave = async () => {+ const result = await actions.saveOAuthConfig({+ provider: this.state.provider,+ status: this.state.enabled ? OAuthConfigStatus.Enabled : OAuthConfigStatus.Disabled,+ displayName: this.state.displayName,+ clientId: this.state.clientId,+ clientSecret: this.state.clientSecretEnabled ? this.state.clientSecret : "",+ authorizeUrl: this.state.authorizeUrl,+ tokenUrl: this.state.tokenUrl,+ profileUrl: this.state.profileUrl,+ scope: this.state.scope,+ jsonUserIdPath: this.state.jsonUserIdPath,+ jsonUserNamePath: this.state.jsonUserNamePath,+ jsonUserEmailPath: this.state.jsonUserEmailPath,+ logo: this.state.logo+ });+ if (result.ok) {+ navigator.goTo("/admin/authentication");+ } else {+ this.setState({ error: result.error });+ }+ };++ private handleCancel = async () => {+ this.props.onCancel();+ };++ private setDisplayName = (displayName: string) => {+ this.setState({ displayName });+ };++ private setLogo = (logo: ImageUploadState, previewUrl: string) => {+ this.setState({ logo, logoUrl: previewUrl });+ };++ private setStatus = async (enabled: boolean) => {+ this.setState({ enabled });+ };++ private setClientId = (clientId: string) => {+ this.setState({ clientId });+ };++ private setClientSecret = (clientSecret: string) => {+ this.setState({ clientSecret });+ };++ private setAuthorizeUrl = (authorizeUrl: string) => {+ this.setState({ authorizeUrl });+ };++ private setTokenUrl = (tokenUrl: string) => {+ this.setState({ tokenUrl });+ };++ private setProfileUrl = (profileUrl: string) => {+ this.setState({ profileUrl });+ };++ private setScope = (scope: string) => {+ this.setState({ scope });+ };++ private setJSONUserIdPath = (jsonUserIdPath: string) => {+ this.setState({ jsonUserIdPath });+ };++ private setJSONUserNamePath = (jsonUserNamePath: string) => {+ this.setState({ jsonUserNamePath });+ };++ private setJSONUserEmailPath = (jsonUserEmailPath: string) => {+ this.setState({ jsonUserEmailPath });+ };++ private enableClientSecret = () => {+ this.setState({ clientSecretEnabled: true, clientSecret: "" });+ };++ public render() {+ const title = this.props.config ? `OAuth Provider: ${this.props.config.displayName}` : "New OAuth Provider";+ return (+ <>+ <Heading title={title} size="small" />+ <Form error={this.state.error}>+ <div className="row">+ <div className="col-sm-9">+ <Input+ field="displayName"+ label="Display Name"+ maxLength={50}+ value={this.state.displayName}+ disabled={!Fider.session.user.isAdministrator}+ onChange={this.setDisplayName}+ />++ <ImageUploader+ label="Logo"+ field="logo"+ defaultImageUrl={this.state.logoUrl}+ previewMaxWidth={80}+ disabled={!Fider.session.user.isAdministrator}+ onChange={this.setLogo}+ >+ <p className="info">+ We accept JPG, GIF and PNG images, smaller than 50KB and with an aspect ratio of 1:1 with minimum+ dimensions of 24x24 pixels.+ </p>+ </ImageUploader>+ </div>+ <div className="col-sm-3">+ <Field label="Preview">+ <SocialSignInButton option={this.state} />+ </Field>+ </div>+ </div>++ <Input+ field="clientId"+ label="Client ID"+ maxLength={100}+ value={this.state.clientId}+ disabled={!Fider.session.user.isAdministrator}+ onChange={this.setClientId}+ />++ <Input+ field="clientSecret"+ label="Client Secret"+ maxLength={500}+ value={this.state.clientSecret}+ disabled={!this.state.clientSecretEnabled}+ onChange={this.setClientSecret}+ afterLabel={+ !this.state.clientSecretEnabled ? (+ <>+ <span className="info">omitted for security reasons.</span>+ <span className="info clickable" onClick={this.enableClientSecret}>+ change+ </span>+ </>+ ) : (+ undefined+ )+ }+ />+ <Input+ field="authorizeUrl"+ label="Authorize URL"+ maxLength={300}+ value={this.state.authorizeUrl}+ disabled={!Fider.session.user.isAdministrator}+ onChange={this.setAuthorizeUrl}+ />+ <Input+ field="tokenUrl"+ label="Token URL"+ maxLength={300}+ value={this.state.tokenUrl}+ disabled={!Fider.session.user.isAdministrator}+ onChange={this.setTokenUrl}+ />++ <h3>User Profile</h3>+ <p className="info">+ This section is used to configure how Fider will fetch user information like Id, Name and Email after the+ authentication OAuth process.+ </p>++ <Input+ field="profileUrl"+ label="Profile API URL"+ maxLength={300}+ value={this.state.profileUrl}+ disabled={!Fider.session.user.isAdministrator}+ onChange={this.setProfileUrl}+ >+ <p className="info">+ This URL is used to fetch the authenticated user details. It must return a JSON and not require any+ QueryString parameter. E.g: Google Profile URL is https://www.googleapis.com/plus/v1/people/me+ </p>+ </Input>++ <Input+ field="scope"+ label="Scope"+ maxLength={100}+ value={this.state.scope}+ disabled={!Fider.session.user.isAdministrator}+ onChange={this.setScope}+ >+ <p className="info">+ It is recommended to only request the minimum scopes we need to fecth the user <strong>id</strong>,{" "}+ <strong>name</strong> and <strong>email</strong>. Multiple scopes must be separated by space.+ </p>+ </Input>++ <h4>JSON Path</h4>++ <div className="row">+ <Input+ field="jsonUserIdPath"+ label="ID"+ className="col-sm-4"+ maxLength={100}+ value={this.state.jsonUserIdPath}+ disabled={!Fider.session.user.isAdministrator}+ onChange={this.setJSONUserIdPath}+ >+ <p className="info">+ Path to extract User ID from JSON. This ID <strong>must</strong> be unique within the provider or+ unexpected side effects might happen. For example below, the path would be <strong>id</strong>.+ </p>+ </Input>+ <Input+ field="jsonUserNamePath"+ label="Name"+ className="col-sm-4"+ maxLength={100}+ value={this.state.jsonUserNamePath}+ disabled={!Fider.session.user.isAdministrator}+ onChange={this.setJSONUserNamePath}+ >+ <p className="info">+ Path to extract user Display Name from JSON. This is optional, but <strong>highly</strong> recommended.+ For the example below, the path would be <strong>profile.name</strong>.+ </p>+ </Input>+ <Input+ field="jsonUserEmailPath"+ label="Email"+ className="col-sm-4"+ maxLength={100}+ value={this.state.jsonUserEmailPath}+ disabled={!Fider.session.user.isAdministrator}+ onChange={this.setJSONUserEmailPath}+ >+ <p className="info">+ Path to extract user Email from JSON. This is optional, but <strong>highly</strong> recommended. For the+ example below, the path would be <strong>profile.emails[0]</strong>.+ </p>+ </Input>+ </div>+ <pre>+ <h5>Example Response</h5>+ {`+{+ id: "35235"+ title: "Sr. Account Manager",+ profile: {+ dob: "01/05/2018",+ name: "John Doe"+ emails: [+ ]+ }+}+ `}+ </pre>++ <div className="row">+ <div className="col-sm-4">+ <Field label="Status">+ <Toggle active={this.state.enabled} onToggle={this.setStatus} />+ <span>{this.state.enabled ? "Enabled" : "Disabled"}</span>+ {this.state.enabled && (+ <p className="info">+ 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>+ )}+ {!this.state.enabled && <p className="info">Users won't be able to sign in with this Provider.</p>}+ </Field>+ </div>+ </div>++ <div className="c-form-field">+ <Button color="positive" onClick={this.handleSave}>+ Save+ </Button>+ <Button onClick={this.handleCancel}>Cancel</Button>+ </div>+ </Form>+ </>+ );+ }+}diff --git a/public/pages/Administration/components/SideMenu.tsx b/public/pages/Administration/components/SideMenu.tsxindex 5d107fb82..be988a4ec 100644--- a/public/pages/Administration/components/SideMenu.tsx+++ b/public/pages/Administration/components/SideMenu.tsx@@ -55,6 +55,12 @@ export const SideMenu = (props: SiteMenuProps) => {href="/admin/invitations"isActive={activeItem === "invitations"}/>+ <SideMenuItem+ name="authentication"+ title="Authentication"+ href="/admin/authentication"+ isActive={activeItem === "authentication"}+ /><SideMenuItem name="advanced" title="Advanced" href="/admin/advanced" isActive={activeItem === "advanced"} />{Fider.session.user.isAdministrator && (<SideMenuItem name="export" title="Export" href="/admin/export" isActive={activeItem === "export"} />diff --git a/public/pages/Administration/index.ts b/public/pages/Administration/index.tsindex 5e6ea40e4..070ea3aae 100644--- a/public/pages/Administration/index.ts+++ b/public/pages/Administration/index.ts@@ -5,3 +5,4 @@ export * from "./pages/ManageTags.page";export * from "./pages/Export.page";export * from "./pages/Invitations.page";export * from "./pages/ManageMembers.page";+export * from "./pages/ManageAuthentication.page";diff --git a/public/pages/Administration/pages/Export.page.tsx b/public/pages/Administration/pages/Export.page.tsxindex dd93cb3d7..112506b79 100644--- a/public/pages/Administration/pages/Export.page.tsx+++ b/public/pages/Administration/pages/Export.page.tsx@@ -1,5 +1,3 @@-import "./PrivacySettings.page.scss";-import * as React from "react";import { CurrentUser } from "@fider/models";diff --git a/public/pages/Administration/pages/GeneralSettings.page.tsx b/public/pages/Administration/pages/GeneralSettings.page.tsxindex 70cde88f8..c88f025b2 100644--- a/public/pages/Administration/pages/GeneralSettings.page.tsx+++ b/public/pages/Administration/pages/GeneralSettings.page.tsx@@ -10,7 +10,7 @@ import {Input,ImageUploader,ImageUploadState,- LogoUrl+ TenantLogoUrl} from "@fider/components/common";import { actions, Failure, fileToBase64, Fider } from "@fider/services";import { AdminBasePage } from "../components";@@ -153,7 +153,7 @@ export class GeneralSettingsPage extends AdminBasePage<GeneralSettingsPageProps,<ImageUploaderlabel="Logo"field="logo"- defaultImageUrl={LogoUrl(200)}+ defaultImageUrl={TenantLogoUrl(200)}previewMaxWidth={200}disabled={!Fider.session.user.isAdministrator}onChange={this.setLogo}diff --git a/public/pages/Administration/pages/ManageAuthentication.page.scss b/public/pages/Administration/pages/ManageAuthentication.page.scssnew file mode 100644index 000000000..7800e74d4--- /dev/null+++ b/public/pages/Administration/pages/ManageAuthentication.page.scss@@ -0,0 +1,24 @@+@import '~@fider/assets/styles/variables.scss';++#p-admin-authentication {+ .l-provider {+ img, strong {+ vertical-align: middle;+ margin-right: 2px;+ }+ img {+ width: 24px;+ height: 24px;+ }+ .m-enabled {+ color: $green-darker;+ font-weight: 500;+ font-size: $font-size-mini;+ }+ .m-disabled {+ color: $red;+ font-weight: 500;+ font-size: $font-size-mini;+ }+ }+}\ No newline at end of filediff --git a/public/pages/Administration/pages/ManageAuthentication.page.tsx b/public/pages/Administration/pages/ManageAuthentication.page.tsxnew file mode 100644index 000000000..ecc4fec38--- /dev/null+++ b/public/pages/Administration/pages/ManageAuthentication.page.tsx@@ -0,0 +1,119 @@+import "./ManageAuthentication.page.scss";++import * as React from "react";++import { AdminBasePage } from "../components";+import { Segment, List, ListItem, Button, Heading, OAuthProviderLogo } from "@fider/components";+import { OAuthConfig, OAuthProviderOption } from "@fider/models";+import { OAuthForm } from "../components/OAuthForm";+import { actions, notify, navigator, Fider, uploadedImageUrl } from "@fider/services";++interface ManageAuthenticationPageProps {+ providers: OAuthProviderOption[];+}++interface ManageAuthenticationPageState {+ isAdding: boolean;+ editing?: OAuthConfig;+}++export class ManageAuthenticationPage extends AdminBasePage<+ ManageAuthenticationPageProps,+ ManageAuthenticationPageState+> {+ public id = "p-admin-authentication";+ public name = "authentication";+ public icon = "sign in alternate";+ public title = "Authentication";+ public subtitle = "Manage your site authentication";++ constructor(props: ManageAuthenticationPageProps) {+ super(props);+ this.state = {+ isAdding: false+ };+ }++ private addNew = async () => {+ this.setState({ isAdding: true, editing: undefined });+ };++ private edit = async (provider: string) => {+ const result = await actions.getOAuthConfig(provider);+ if (result.ok) {+ this.setState({ editing: result.data, isAdding: false });+ } else {+ notify.error("Failed to retrieve OAuth configuration. Try again later");+ }+ };++ private startTest = async (provider: string) => {+ const redirect = `${Fider.settings.baseURL}/oauth/${provider}/echo`;+ window.open(`/oauth/${provider}?redirect=${redirect}`, "oauth-test", "width=1100,height=600,status=no,menubar=no");+ };++ private cancel = async () => {+ this.setState({ isAdding: false, editing: undefined });+ };++ public content() {+ if (this.state.isAdding) {+ return <OAuthForm onCancel={this.cancel} />;+ }++ if (this.state.editing) {+ return <OAuthForm config={this.state.editing} onCancel={this.cancel} />;+ }++ const enabled = <span className="m-enabled">Enabled</span>;+ const disabled = <span className="m-disabled">Disabled</span>;++ return (+ <>+ <Heading+ title="OAuth Providers"+ subtitle="You can use these section to add any authentication provider thats supports the OAuth2 protocol."+ size="small"+ />+ <p className="info">+ Additional information is available in our{" "}+ <a target="_blank" href="https://getfider.com/docs/configuring-oauth/">+ OAuth Documentation+ </a>.+ </p>+ <Segment>+ <List divided={true}>+ {this.props.providers.map(o => (+ <ListItem key={o.provider}>+ {o.isCustomProvider && (+ <>+ <Button onClick={this.edit.bind(this, o.provider)} className="right">+ <i className="edit icon" />Edit+ </Button>+ <Button onClick={this.startTest.bind(this, o.provider)} className="right">+ <i className="play icon" />Test+ </Button>+ </>+ )}+ <div className="l-provider">+ <OAuthProviderLogo option={o} />+ <strong>{o.displayName}</strong>+ <br /> {o.isEnabled ? enabled : disabled}+ </div>+ {o.isCustomProvider && (+ <span className="info">+ <strong>Client ID:</strong> {o.clientId} <br />+ <strong>Callback URL:</strong> {o.callbackUrl}+ </span>+ )}+ </ListItem>+ ))}+ </List>+ </Segment>+ <Button color="positive" onClick={this.addNew}>+ Add new+ </Button>+ </>+ );+ }+}diff --git a/public/pages/OAuthEcho/OAuthEcho.page.scss b/public/pages/OAuthEcho/OAuthEcho.page.scssnew file mode 100644index 000000000..aca43df01--- /dev/null+++ b/public/pages/OAuthEcho/OAuthEcho.page.scss@@ -0,0 +1,13 @@+@import '~@fider/assets/styles/variables.scss';++#p-oauth-echo {+ i.times.icon {+ color: $red;+ }+ i.check.icon {+ color: $green;+ }+ i.exclamation.icon {+ color: $orange;+ }+}\ No newline at end of filediff --git a/public/pages/OAuthEcho/OAuthEcho.page.tsx b/public/pages/OAuthEcho/OAuthEcho.page.tsxnew file mode 100644index 000000000..daae5c58d--- /dev/null+++ b/public/pages/OAuthEcho/OAuthEcho.page.tsx@@ -0,0 +1,82 @@+import "./OAuthEcho.page.scss";++import * as React from "react";+import { navigator } from "@fider/services";+import { Segments, Segment } from "@fider/components";++interface OAuthEchoPageProps {+ statusCode: number;+ body: string;+ profile: {+ id: string;+ name: string;+ email: string;+ };+}++const ok = <i className="check circle icon" />;+const error = <i className="times circle icon" />;+const warn = <i className="exclamation triangle icon" />;++export class OAuthEchoPage extends React.Component<OAuthEchoPageProps, {}> {+ public componentDidMount() {+ navigator.replaceState("/");+ }++ public render() {+ const idOk = this.props.profile && this.props.profile.id !== "";+ const nameOk = this.props.profile && this.props.profile.name !== "Anonymous";+ const emailOk = this.props.profile && this.props.profile.email !== "";++ let responseBody = "";+ try {+ responseBody = JSON.stringify(JSON.parse(this.props.body), null, " ");+ } catch {+ responseBody = this.props.body;+ }++ return (+ <div id="p-oauth-echo" className="page container">+ <h3>Profile API Response</h3>+ <h5>Status Code: {this.props.statusCode}</h5>+ <h5>Raw Body</h5>+ <pre>{responseBody}</pre>+ <h5>Parsed Profile</h5>+ <Segments>+ <Segment>+ <p>+ {idOk ? ok : error}+ <strong>ID:</strong> {this.props.profile && this.props.profile.id}+ {!idOk && (+ <p className="info">ID is required. If not found, users will see an error during sign in process.</p>+ )}+ </p>+ </Segment>+ <Segment>+ <p>+ {nameOk ? ok : warn}+ <strong>Name:</strong> {this.props.profile && this.props.profile.name}+ </p>+ {!nameOk && (+ <p className="info">+ Name is required, if not found we'll use <strong>Anonymous</strong> as the name of every new user.+ </p>+ )}+ </Segment>+ <Segment>+ <p>+ {emailOk ? ok : warn}+ <strong>Email:</strong> {this.props.profile && this.props.profile.email}+ </p>+ {!emailOk && (+ <p className="info">+ Email is not required, but highly recommended. If invalid or not found, new users won't be able to+ receive notifications.+ </p>+ )}+ </Segment>+ </Segments>+ </div>+ );+ }+}diff --git a/public/pages/OAuthEcho/index.ts b/public/pages/OAuthEcho/index.tsnew file mode 100644index 000000000..0bd990b2d--- /dev/null+++ b/public/pages/OAuthEcho/index.ts@@ -0,0 +1 @@+export * from "./OAuthEcho.page";diff --git a/public/pages/SignIn/SignIn.page.tsx b/public/pages/SignIn/SignIn.page.tsxindex f142c4450..1bfc14ed9 100644--- a/public/pages/SignIn/SignIn.page.tsx+++ b/public/pages/SignIn/SignIn.page.tsx@@ -1,9 +1,8 @@import "./SignIn.page.scss";import * as React from "react";-import { SignInControl, Logo, LegalNotice } from "@fider/components";+import { SignInControl, TenantLogo, LegalNotice } from "@fider/components";import { notify, Fider } from "@fider/services";-import { Tenant } from "@fider/models";export class SignInPage extends React.Component<{}, {}> {private onEmailSent = (email: string) => {@@ -18,7 +17,7 @@ export class SignInPage extends React.Component<{}, {}> {return (<div id="p-signin" className="page container"><div className="message">- <Logo size={100} />+ <TenantLogo size={100} /><p className="welcome"><strong>{Fider.session.tenant.name}</strong> is a private space and requires an invitation to join it.</p>diff --git a/public/pages/UI/UIToolkit.page.tsx b/public/pages/UI/UIToolkit.page.tsxindex d28399ae1..8f5bccd95 100644--- a/public/pages/UI/UIToolkit.page.tsx+++ b/public/pages/UI/UIToolkit.page.tsx@@ -202,19 +202,6 @@ export class UIToolkitPage extends React.Component<{}, UIToolkitPageState> {</ListItem></List>- <h1>Social Buttons</h1>- <div className="row">- <div className="col-md-3">- <SocialSignInButton option={{ provider: "google", displayName: "Google", url: "#" }} />- </div>- <div className="col-md-3">- <SocialSignInButton option={{ provider: "facebook", displayName: "Facebook", url: "#" }} />- </div>- <div className="col-md-3">- <SocialSignInButton option={{ provider: "github", displayName: "GitHub", url: "#" }} />- </div>- </div>-<h1>Toggle</h1><List><ListItem>diff --git a/public/pages/index.ts b/public/pages/index.tsindex 7a5d859e0..fdd2562d9 100644--- a/public/pages/index.ts+++ b/public/pages/index.ts@@ -3,6 +3,7 @@ export * from "./Administration";export * from "./SignIn";export * from "./SignUp";export * from "./CompleteSignInProfile";+export * from "./OAuthEcho";export * from "./MySettings";export * from "./MyNotifications";export * from "./ShowIdea";diff --git a/public/router.spec.tsx b/public/router.spec.tsxindex 68b5cdb1b..7cd3c8dfa 100644--- a/public/router.spec.tsx+++ b/public/router.spec.tsx@@ -1,5 +1,5 @@import { resolveRootComponent } from "./router";-import { HomePage, ShowIdeaPage, InvitationsPage, GeneralSettingsPage } from "@fider/pages";+import { HomePage, ShowIdeaPage, InvitationsPage, GeneralSettingsPage, OAuthEchoPage } from "@fider/pages";[{ path: "", expected: HomePage },@@ -7,7 +7,8 @@ import { HomePage, ShowIdeaPage, InvitationsPage, GeneralSettingsPage } from "@f{ path: "/ideas/123/the-slug", expected: ShowIdeaPage },{ path: "/ideas" },{ path: "/admin", expected: GeneralSettingsPage },- { path: "/admin/invitations", expected: InvitationsPage }+ { path: "/admin/invitations", expected: InvitationsPage },+ { path: "/oauth/_name/echo", expected: OAuthEchoPage }].forEach(x => {test(`Router should resolve correct component for path '${x.path}'`, () => {if (x.expected) {diff --git a/public/router.tsx b/public/router.tsxindex 46eaa16e7..371db96a7 100644--- a/public/router.tsx+++ b/public/router.tsx@@ -11,7 +11,9 @@ import {ExportPage,GeneralSettingsPage,AdvancedSettingsPage,+ ManageAuthenticationPage,ManageTagsPage,+ OAuthEchoPage,ShowIdeaPage,MySettingsPage,MyNotificationsPage,@@ -28,6 +30,7 @@ const route = (path: string, component: any, showHeader: boolean = true): PageCopath = path.replace("/", "/").replace(":number", "\\d+")+ .replace(":string", ".+").replace("*", "/?.*");const regex = new RegExp(`^${path}$`);@@ -42,6 +45,7 @@ const pathRegex = [route("/admin/privacy", PrivacySettingsPage),route("/admin/export", ExportPage),route("/admin/invitations", InvitationsPage),+ route("/admin/authentication", ManageAuthenticationPage),route("/admin/advanced", AdvancedSettingsPage),route("/admin", GeneralSettingsPage),route("/signin", SignInPage, false),@@ -50,6 +54,7 @@ const pathRegex = [route("/invite/verify", CompleteSignInProfilePage),route("/notifications", MyNotificationsPage),route("/settings", MySettingsPage),+ route("/oauth/:string/echo", OAuthEchoPage, false),route("/-/ui", UIToolkitPage)];diff --git a/public/services/actions/tenant.ts b/public/services/actions/tenant.tsindex 13d598d2b..f8ea4cfff 100644--- a/public/services/actions/tenant.ts+++ b/public/services/actions/tenant.ts@@ -1,5 +1,6 @@import { http, Result } from "@fider/services/http";-import { Tenant, UserRole } from "@fider/models";+import { Tenant, UserRole, OAuthConfig } from "@fider/models";+import { ImageUploadState } from "@fider/components";export interface CheckAvailabilityResponse {message: string;@@ -72,3 +73,27 @@ export const changeUserRole = async (userId: number, role: UserRole): Promise<Rerole});};++export const getOAuthConfig = async (provider: string): Promise<Result<OAuthConfig>> => {+ return await http.get<OAuthConfig>(`/api/admin/oauth/${provider}`);+};++export interface CreateEditOAuthConfigRequest {+ provider: string;+ status: number;+ displayName: string;+ clientId: string;+ clientSecret: string;+ authorizeUrl: string;+ tokenUrl: string;+ scope: string;+ profileUrl: string;+ jsonUserIdPath: string;+ jsonUserNamePath: string;+ jsonUserEmailPath: string;+ logo?: ImageUploadState;+}++export const saveOAuthConfig = async (request: CreateEditOAuthConfigRequest): Promise<Result> => {+ return await http.post("/api/admin/oauth", request);+};diff --git a/public/services/navigator.ts b/public/services/navigator.tsindex f3c61a195..f4ed75135 100644--- a/public/services/navigator.ts+++ b/public/services/navigator.ts@@ -7,6 +7,9 @@ const navigator = {goHome: () => {window.location.href = "/";},+ goTo: (url: string) => {+ window.location.href = url;+ },replaceState: (path: string): void => {if (history.replaceState) {const newUrl = Fider.settings.baseURL + path;diff --git a/public/services/utils.ts b/public/services/utils.tsindex ab9443d3f..67ff40e14 100644--- a/public/services/utils.ts+++ b/public/services/utils.ts@@ -1,3 +1,5 @@+import { Fider } from ".";+export const delay = (ms: number) => {return new Promise(resolve => setTimeout(resolve, ms));};@@ -120,3 +122,10 @@ export const isCookieEnabled = (): boolean => {return false;}};++export const uploadedImageUrl = (id: number, size: number): string | undefined => {+ if (id > 0) {+ return `${Fider.settings.assetsURL}/images/${size}/${id}`;+ }+ return undefined;+};