Open platform to collect and prioritize feedback
feature: parse OAuth profile from Access Token (#491)
Guilherme Oenning9e7754cb6b98
diff --git a/app/actions/oauth.go b/app/actions/oauth.goindex 826684fcd..567468eb0 100644--- a/app/actions/oauth.go+++ b/app/actions/oauth.go@@ -90,10 +90,10 @@ func (input *CreateEditOAuthConfig) Validate(user *models.User, services *app.Seresult.AddFieldFailure("tokenUrl", messages...)}- if input.Model.ProfileURL == "" {- result.AddFieldFailure("profileUrl", "Profile URL is required.")- } else if messages := validate.URL(input.Model.ProfileURL); len(messages) > 0 {- result.AddFieldFailure("profileUrl", messages...)+ if input.Model.ProfileURL != "" {+ if messages := validate.URL(input.Model.ProfileURL); len(messages) > 0 {+ result.AddFieldFailure("profileUrl", messages...)+ }}if input.Model.JSONUserIDPath == "" {diff --git a/app/actions/oauth_test.go b/app/actions/oauth_test.goindex 10a4ddd4b..09490c167 100644--- a/app/actions/oauth_test.go+++ b/app/actions/oauth_test.go@@ -18,7 +18,7 @@ func TestCreateEditOAuthConfig_InvalidInput(t *testing.T) {input *models.CreateEditOAuthConfig}{{- expected: []string{"displayName", "status", "tokenUrl", "clientId", "clientSecret", "scope", "authorizeUrl", "tokenUrl", "profileUrl", "jsonUserIdPath"},+ expected: []string{"displayName", "status", "tokenUrl", "clientId", "clientSecret", "scope", "authorizeUrl", "tokenUrl", "jsonUserIdPath"},input: &models.CreateEditOAuthConfig{},},{diff --git a/app/handlers/oauth.go b/app/handlers/oauth.goindex 12d49bb36..4b22a9173 100644--- a/app/handlers/oauth.go+++ b/app/handlers/oauth.go@@ -36,9 +36,14 @@ func OAuthEcho() web.HandlerFunc {return c.Redirect("/")}- statusCode, body, err := c.Services().OAuth.GetRawProfile(provider, code)+ body, err := c.Services().OAuth.GetRawProfile(provider, code)if err != nil {- return c.Failure(err)+ return c.Page(web.Props{+ Title: "OAuth Test Page",+ Data: web.Map{+ "err": errors.Cause(err).Error(),+ },+ })}profile, _ := c.Services().OAuth.ParseRawProfile(provider, body)@@ -46,9 +51,8 @@ func OAuthEcho() web.HandlerFunc {return c.Page(web.Props{Title: "OAuth Test Page",Data: web.Map{- "statusCode": statusCode,- "body": body,- "profile": profile,+ "body": body,+ "profile": profile,},})}diff --git a/app/pkg/dbx/dbx_test.go b/app/pkg/dbx/dbx_test.goindex f0742cd20..027348823 100644--- a/app/pkg/dbx/dbx_test.go+++ b/app/pkg/dbx/dbx_test.go@@ -103,7 +103,7 @@ func TestBind_SimpleStruct_Multiple(t *testing.T) {defer trx.Rollback()u := []*user{}- err := trx.Select(&u, "SELECT name FROM users WHERE tenant_id = 1")+ err := trx.Select(&u, "SELECT name FROM users WHERE tenant_id = 1 ORDER BY id")Expect(err).IsNil()Expect(u).HasLen(3)@@ -154,6 +154,7 @@ func TestBind_NestedStruct_Multiple(t *testing.T) {INNER JOIN tenants tON t.id = u.tenant_idWHERE u.tenant_id = 1+ ORDER BY u.id`)Expect(err).IsNil()Expect(u).HasLen(3)diff --git a/app/pkg/mock/oauth.go b/app/pkg/mock/oauth.goindex 79f0f31f7..601fb83f5 100644--- a/app/pkg/mock/oauth.go+++ b/app/pkg/mock/oauth.go@@ -11,8 +11,8 @@ func (s *OAuthService) GetAuthURL(provider, redirect, identifier string) (string}//GetRawProfile returns raw JSON response from Profile API-func (s *OAuthService) GetRawProfile(provider string, code string) (int, string, error) {- return 500, "", nil+func (s *OAuthService) GetRawProfile(provider string, code string) (string, error) {+ return "", nil}//ParseRawProfile parses raw profile response into UserProfile modeldiff --git a/app/pkg/oauth/oauth.go b/app/pkg/oauth/oauth.goindex a3b1297c2..64e228026 100644--- a/app/pkg/oauth/oauth.go+++ b/app/pkg/oauth/oauth.go@@ -39,7 +39,7 @@ type ProviderOption struct {type Service interface {GetAuthURL(provider, redirect, identifier string) (string, error)GetProfile(provider string, code string) (*UserProfile, error)- GetRawProfile(provider string, code string) (int, string, error)+ GetRawProfile(provider string, code string) (string, error)ParseRawProfile(provider, body string) (*UserProfile, error)ListActiveProviders() ([]*ProviderOption, error)ListAllProviders() ([]*ProviderOption, error)diff --git a/app/pkg/web/oauth.go b/app/pkg/web/oauth.goindex 94ff68a94..939e45b8b 100644--- a/app/pkg/web/oauth.go+++ b/app/pkg/web/oauth.go@@ -8,6 +8,7 @@ import ("os""strings"+ jwt "github.com/dgrijalva/jwt-go""github.com/getfider/fider/app/pkg/validate""github.com/getfider/fider/app/storage"@@ -124,23 +125,19 @@ func (s *OAuthService) GetProfile(provider string, code string) (*oauth.UserProfreturn nil, errors.New("Provider %s is disabled", provider)}- statusCode, body, err := s.GetRawProfile(provider, code)+ 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) {+func (s *OAuthService) GetRawProfile(provider string, code string) (string, error) {config, err := s.getConfig(provider)if err != nil {- return 0, "", err+ return "", err}exchange := (&oauth2.Config{@@ -155,11 +152,29 @@ func (s *OAuthService) GetRawProfile(provider string, code string) (int, string,oauthToken, err := exchange(oauth2.NoContext, code)if err != nil {- rErr := err.(*oauth2.RetrieveError)- return rErr.Response.StatusCode, string(rErr.Body), nil+ return "", err+ }++ if config.ProfileURL == "" {+ parts := strings.Split(oauthToken.AccessToken, ".")+ if len(parts) != 3 {+ return "", errors.New("AccessToken is not JWT")+ }++ body, _ := jwt.DecodeSegment(parts[1])+ return string(body), nil+ }++ statusCode, body, err := s.doGet(config.ProfileURL, oauthToken.AccessToken)+ if err != nil {+ return "", err+ }++ if statusCode != 200 {+ return "", errors.New("Failed to request profile. Status Code: %d. Body: %s", statusCode, body)}- return s.doGet(config.ProfileURL, oauthToken.AccessToken)+ return body, nil}//ParseRawProfile parses raw profile response into UserProfile modeldiff --git a/public/pages/Administration/components/OAuthForm.tsx b/public/pages/Administration/components/OAuthForm.tsxindex 9cefefbf0..b473dceb9 100644--- a/public/pages/Administration/components/OAuthForm.tsx+++ b/public/pages/Administration/components/OAuthForm.tsx@@ -224,10 +224,23 @@ export class OAuthForm extends React.Component<OAuthFormProps, OAuthFormState> {onChange={this.setTokenUrl}/>+ <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>+<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.+ This section is used to configure how Fider will fetch user after the authentication process.</p><Input@@ -239,22 +252,8 @@ export class OAuthForm extends React.Component<OAuthFormProps, OAuthFormState> {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.+ The URL to fetch the authenticated user info. If empty, Fider will try to parse the user info from the+ Access Token.</p></Input>@@ -271,7 +270,7 @@ export class OAuthForm extends React.Component<OAuthFormProps, OAuthFormState> {onChange={this.setJSONUserIdPath}><p className="info">- Path to extract User ID from JSON. This ID <strong>must</strong> be unique within the provider or+ Path to extract User ID from the JSON. This ID <strong>must</strong> be unique within the provider orunexpected side effects might happen. For example below, the path would be <strong>id</strong>.</p></Input>@@ -285,8 +284,8 @@ export class OAuthForm extends React.Component<OAuthFormProps, OAuthFormState> {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>.+ Path to extract user Display Name from the JSON. This is optional, but <strong>highly</strong>+ recommended. For the example below, the path would be <strong>profile.name</strong>.</p></Input><Input@@ -299,8 +298,8 @@ export class OAuthForm extends React.Component<OAuthFormProps, OAuthFormState> {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>.+ Path to extract user Email from the 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>diff --git a/public/pages/OAuthEcho/OAuthEcho.page.tsx b/public/pages/OAuthEcho/OAuthEcho.page.tsxindex daae5c58d..0c90c01ae 100644--- a/public/pages/OAuthEcho/OAuthEcho.page.tsx+++ b/public/pages/OAuthEcho/OAuthEcho.page.tsx@@ -5,7 +5,7 @@ import { navigator } from "@fider/services";import { Segments, Segment } from "@fider/components";interface OAuthEchoPageProps {- statusCode: number;+ err: string | undefined;body: string;profile: {id: string;@@ -23,7 +23,16 @@ export class OAuthEchoPage extends React.Component<OAuthEchoPageProps, {}> {navigator.replaceState("/");}- public render() {+ private renderError() {+ return (+ <>+ <h5>Error</h5>+ <pre>{this.props.err}</pre>+ </>+ );+ }++ private renderParseResult() {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 !== "";@@ -36,9 +45,7 @@ export class OAuthEchoPage extends React.Component<OAuthEchoPageProps, {}> {}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>@@ -76,6 +83,14 @@ export class OAuthEchoPage extends React.Component<OAuthEchoPageProps, {}> {)}</Segment></Segments>+ </>+ );+ }++ public render() {+ return (+ <div id="p-oauth-echo" className="page container">+ {this.props.err ? this.renderError() : this.renderParseResult()}</div>);}