Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

refactor: get list of OAuth providers from server (#447)

Guilherme Oenning7a6ec47bd181
diff --git a/app/pkg/mock/oauth.go b/app/pkg/mock/oauth.go
index a3955e04f..fa77b178c 100644
--- a/app/pkg/mock/oauth.go
+++ b/app/pkg/mock/oauth.go
@@ -6,12 +6,12 @@ import "github.com/getfider/fider/app/pkg/oauth"
type OAuthService struct{}
//GetAuthURL returns authentication url for given provider
-func (p *OAuthService) GetAuthURL(provider string, redirect string) (string, error) {
+func (s *OAuthService) GetAuthURL(provider string, redirect string) (string, error) {
return "http://avengers.test.fider.io/oauth/token?provider=" + provider + "&redirect=" + redirect, nil
}
//GetProfile returns user profile based on provider and code
-func (p *OAuthService) GetProfile(provider string, code string) (*oauth.UserProfile, error) {
+func (s *OAuthService) GetProfile(provider string, code string) (*oauth.UserProfile, error) {
if provider == "facebook" && code == "123" {
return &oauth.UserProfile{
ID: "FB123",
@@ -46,3 +46,8 @@ func (p *OAuthService) GetProfile(provider string, code string) (*oauth.UserProf
return nil, nil
}
+
+//ListProviders returns a list of all providers for current tenant
+func (s *OAuthService) ListProviders() ([]*oauth.ProviderOption, error) {
+ return []*oauth.ProviderOption{}, nil
+}
diff --git a/app/pkg/oauth/oauth.go b/app/pkg/oauth/oauth.go
index c9d7a4a6e..677dfa956 100644
--- a/app/pkg/oauth/oauth.go
+++ b/app/pkg/oauth/oauth.go
@@ -2,7 +2,6 @@ package oauth
import (
"errors"
- "os"
)
const (
@@ -24,20 +23,16 @@ type UserProfile struct {
Email string
}
-//IsProviderEnabled returns true if provider is enabled
-func IsProviderEnabled(name string) bool {
- if name == GoogleProvider {
- return os.Getenv("OAUTH_GOOGLE_CLIENTID") != ""
- } else if name == FacebookProvider {
- return os.Getenv("OAUTH_FACEBOOK_APPID") != ""
- } else if name == GitHubProvider {
- return os.Getenv("OAUTH_GITHUB_CLIENTID") != ""
- }
- return false
+//ProviderOption represents an OAuth provider that can be used to authenticate
+type ProviderOption struct {
+ Provider string `json:"provider"`
+ DisplayName string `json:"displayName"`
+ URL string `json:"url"`
}
//Service provides OAuth operations
type Service interface {
GetAuthURL(provider string, redirect string) (string, error)
GetProfile(provider string, code string) (*UserProfile, error)
+ ListProviders() ([]*ProviderOption, error)
}
diff --git a/app/pkg/web/oauth.go b/app/pkg/web/oauth.go
index bb7c594ec..878faf8f7 100644
--- a/app/pkg/web/oauth.go
+++ b/app/pkg/web/oauth.go
@@ -8,6 +8,7 @@ import (
"os"
"strings"
+ "github.com/getfider/fider/app"
"github.com/getfider/fider/app/pkg/validate"
"github.com/getfider/fider/app/pkg/jsonq"
@@ -28,8 +29,10 @@ type providerSettings struct {
}
var (
- systemProviders = map[string]*models.OAuthConfig{
- oauth.FacebookProvider: &models.OAuthConfig{
+ 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"),
@@ -40,7 +43,9 @@ var (
JSONNamePath: "name",
JSONEmailPath: "email",
},
- oauth.GoogleProvider: &models.OAuthConfig{
+ &models.OAuthConfig{
+ Provider: oauth.GoogleProvider,
+ DisplayName: "Google",
ProfileURL: "https://www.googleapis.com/oauth2/v2/userinfo",
ClientID: os.Getenv("OAUTH_GOOGLE_CLIENTID"),
ClientSecret: os.Getenv("OAUTH_GOOGLE_SECRET"),
@@ -51,7 +56,9 @@ var (
JSONNamePath: "name",
JSONEmailPath: "email",
},
- oauth.GitHubProvider: &models.OAuthConfig{
+ &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"),
@@ -154,6 +161,23 @@ func (s *OAuthService) ParseProfileResponse(body string, config *models.OAuthCon
return profile, nil
}
+//ListProviders returns a list of all providers for current tenant
+func (s *OAuthService) ListProviders() ([]*oauth.ProviderOption, error) {
+ list := make([]*oauth.ProviderOption, 0)
+
+ for _, p := range systemProviders {
+ if p.ClientID != "" {
+ list = append(list, &oauth.ProviderOption{
+ Provider: p.Provider,
+ DisplayName: p.DisplayName,
+ URL: fmt.Sprintf("%s/oauth/%s", s.authEndpoint, p.Provider),
+ })
+ }
+ }
+
+ return list, nil
+}
+
func (s *OAuthService) doGet(url, accessToken string) ([]byte, error) {
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "Bearer "+accessToken)
@@ -164,18 +188,24 @@ func (s *OAuthService) doGet(url, accessToken string) ([]byte, error) {
}
defer r.Body.Close()
- if r.StatusCode != 200 {
- return nil, errors.New("failed to request GET %s with status code %d", url, r.StatusCode)
- }
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
}
func (s *OAuthService) getConfig(provider string) (*models.OAuthConfig, error) {
- return systemProviders[provider], nil
+ for _, p := range systemProviders {
+ if p.Provider == provider {
+ return p, nil
+ }
+ }
+ return nil, app.ErrNotFound
}
diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.go
index d30e137a9..08400f0ea 100644
--- a/app/pkg/web/renderer.go
+++ b/app/pkg/web/renderer.go
@@ -78,6 +78,8 @@ func (r *Renderer) getBundle(folder, prefix, suffix string) string {
//Render a template based on parameters
func (r *Renderer) Render(w io.Writer, name string, props Props, ctx *Context) {
+ var err error
+
if len(r.assets) == 0 || env.IsDevelopment() {
r.assets["main.js"] = r.getBundle("/dist/js", "main", "js")
r.assets["vendor.js"] = r.getBundle("/dist/js", "vendor", "js")
@@ -128,6 +130,15 @@ func (r *Renderer) Render(w io.Writer, name string, props Props, ctx *Context) {
m["__contextID"] = ctx.ContextID()
m["__currentURL"] = ctx.Request.URL.String()
m["__tenant"] = ctx.Tenant()
+
+ oauthProviders := make([]*oauth.ProviderOption, 0)
+ if !ctx.IsAuthenticated() && ctx.Services() != nil {
+ oauthProviders, err = ctx.Services().OAuth.ListProviders()
+ if err != nil {
+ panic(errors.Wrap(err, "failed to get list of providers"))
+ }
+ }
+
m["__settings"] = &Map{
"mode": r.settings.Mode,
"buildTime": r.settings.BuildTime,
@@ -139,14 +150,7 @@ func (r *Renderer) Render(w io.Writer, name string, props Props, ctx *Context) {
"hasLegal": r.settings.HasLegal,
"baseURL": ctx.BaseURL(),
"assetsURL": ctx.TenantAssetsURL(""),
- "auth": Map{
- "endpoint": ctx.AuthEndpoint(),
- "providers": Map{
- oauth.GoogleProvider: oauth.IsProviderEnabled(oauth.GoogleProvider),
- oauth.FacebookProvider: oauth.IsProviderEnabled(oauth.FacebookProvider),
- oauth.GitHubProvider: oauth.IsProviderEnabled(oauth.GitHubProvider),
- },
- },
+ "oauth": oauthProviders,
}
if ctx.IsAuthenticated() {
@@ -162,7 +166,7 @@ func (r *Renderer) Render(w io.Writer, name string, props Props, ctx *Context) {
}
}
- err := tmpl.Execute(w, m)
+ err = tmpl.Execute(w, m)
if err != nil {
panic(errors.Wrap(err, "failed to execute template %s", name))
}
diff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsx
index c98e6982d..7de48b3cc 100644
--- a/public/components/common/SignInControl.tsx
+++ b/public/components/common/SignInControl.tsx
@@ -48,44 +48,17 @@ export class SignInControl extends React.Component<SignInControlProps, SignInCon
};
public render() {
- const google = Fider.settings.auth.providers.google && (
- <div className="col-sm l-social-col">
- <SocialSignInButton
- oauthEndpoint={Fider.settings.auth.endpoint}
- provider="google"
- redirectTo={this.props.redirectTo}
- />
+ 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 facebook = Fider.settings.auth.providers.facebook && (
- <div className="col-sm l-social-col">
- <SocialSignInButton
- oauthEndpoint={Fider.settings.auth.endpoint}
- provider="facebook"
- redirectTo={this.props.redirectTo}
- />
- </div>
- );
- const github = Fider.settings.auth.providers.github && (
- <div className="col-sm l-social-col">
- <SocialSignInButton
- oauthEndpoint={Fider.settings.auth.endpoint}
- provider="github"
- redirectTo={this.props.redirectTo}
- />
- </div>
- );
- const hasOAuth = !!(google || facebook || github);
+ ));
return (
<div className="c-signin-control">
- {hasOAuth && (
+ {oauthProviders.length > 0 && (
<div>
- <div className="row">
- {facebook}
- {google}
- {github}
- </div>
+ <div className="row">{oauthProviders}</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.tsx
index 54f7d4238..d98d939cf 100644
--- a/public/components/common/SocialSignInButton.tsx
+++ b/public/components/common/SocialSignInButton.tsx
@@ -1,38 +1,26 @@
import * as React from "react";
import { Button } from "@fider/components/common";
+import { OAuthProviderOption } from "@fider/models";
+import { classSet } from "@fider/services";
interface SocialSignInButtonProps {
- provider: "google" | "facebook" | "github";
- oauthEndpoint?: string;
+ option: OAuthProviderOption;
redirectTo?: string;
}
-const providers = {
- google: {
- name: "Google",
- class: "m-social m-google"
- },
- facebook: {
- name: "Facebook",
- class: "m-social m-facebook"
- },
- github: {
- name: "GitHub",
- class: "m-social m-github"
- }
-};
-
export class SocialSignInButton extends React.Component<SocialSignInButtonProps, {}> {
public render() {
const redirectTo = this.props.redirectTo || location.href;
- const href = this.props.oauthEndpoint
- ? `${this.props.oauthEndpoint}/oauth/${this.props.provider}?redirect=${redirectTo}`
- : undefined;
+ const href = `${this.props.option.url}?redirect=${redirectTo}`;
+ const className = classSet({
+ "m-social": true,
+ [`m-${this.props.option.provider}`]: true
+ });
return (
- <Button href={href} fluid={true} className={providers[this.props.provider].class}>
+ <Button href={href} fluid={true} className={className}>
<i className="svg" />
- <span>{providers[this.props.provider].name}</span>
+ <span>{this.props.option.displayName}</span>
</Button>
);
}
diff --git a/public/models/settings.ts b/public/models/settings.ts
index 9e39d3e47..7b1d3e6d6 100644
--- a/public/models/settings.ts
+++ b/public/models/settings.ts
@@ -1,3 +1,9 @@
+export interface OAuthProviderOption {
+ provider: string;
+ displayName: string;
+ url: string;
+}
+
export interface SystemSettings {
mode: string;
buildTime: string;
@@ -8,14 +14,7 @@ export interface SystemSettings {
hasLegal: boolean;
baseURL: string;
assetsURL: string;
- auth: {
- endpoint: string;
- providers: {
- google: boolean;
- facebook: boolean;
- github: boolean;
- };
- };
+ oauth: OAuthProviderOption[];
}
export interface UserSettings {
diff --git a/public/pages/UI/UIToolkit.page.tsx b/public/pages/UI/UIToolkit.page.tsx
index 66d1b0ea2..d28399ae1 100644
--- a/public/pages/UI/UIToolkit.page.tsx
+++ b/public/pages/UI/UIToolkit.page.tsx
@@ -205,13 +205,13 @@ export class UIToolkitPage extends React.Component<{}, UIToolkitPageState> {
<h1>Social Buttons</h1>
<div className="row">
<div className="col-md-3">
- <SocialSignInButton provider="google" />
+ <SocialSignInButton option={{ provider: "google", displayName: "Google", url: "#" }} />
</div>
<div className="col-md-3">
- <SocialSignInButton provider="facebook" />
+ <SocialSignInButton option={{ provider: "facebook", displayName: "Facebook", url: "#" }} />
</div>
<div className="col-md-3">
- <SocialSignInButton provider="github" />
+ <SocialSignInButton option={{ provider: "github", displayName: "GitHub", url: "#" }} />
</div>
</div>