Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Oauth composite name (#1299)

Matt Roberts9b5c745f3a0c
diff --git a/app/services/oauth/oauth.go b/app/services/oauth/oauth.go
index 70af7906b..a71484c0b 100644
--- a/app/services/oauth/oauth.go
+++ b/app/services/oauth/oauth.go
@@ -116,9 +116,13 @@ func parseOAuthRawProfile(ctx context.Context, c *cmd.ParseOAuthRawProfile) erro
}
query := jsonq.New(c.Body)
+
+ // Extract and combine name parts
+ name := extractCompositeName(query, config.JSONUserNamePath)
+
profile := &dto.OAuthUserProfile{
ID: strings.TrimSpace(query.String(config.JSONUserIDPath)),
- Name: strings.TrimSpace(query.String(config.JSONUserNamePath)),
+ Name: name,
Email: strings.ToLower(strings.TrimSpace(query.String(config.JSONUserEmailPath))),
}
@@ -143,6 +147,52 @@ func parseOAuthRawProfile(ctx context.Context, c *cmd.ParseOAuthRawProfile) erro
return nil
}
+// extractCompositeName handles composite name selectors
+// Format can be:
+// - Simple path: "name"
+// - Fallback paths: "name, login" (tries name, if empty tries login)
+// - Composite paths: "firstname + ' ' + lastname" (combines multiple fields)
+func extractCompositeName(query *jsonq.Query, namePath string) string {
+ // Check if it's a composite path (contains '+')
+ if strings.Contains(namePath, "+") {
+ // Split by '+' and process each part
+ parts := strings.Split(namePath, "+")
+ var result strings.Builder
+
+ for _, part := range parts {
+ part = strings.TrimSpace(part)
+
+ // If it's a string literal (enclosed in quotes or single quotes)
+ if (strings.HasPrefix(part, "'") && strings.HasSuffix(part, "'")) ||
+ (strings.HasPrefix(part, "\"") && strings.HasSuffix(part, "\"")) {
+ // Extract the literal without quotes
+ literal := part[1 : len(part)-1]
+ result.WriteString(literal)
+ } else {
+ // It's a JSON path
+ value := strings.TrimSpace(query.String(part))
+ if value != "" {
+ result.WriteString(value)
+ }
+ }
+ }
+
+ return strings.TrimSpace(result.String())
+ }
+
+ // Handle fallback paths (comma-separated)
+ paths := strings.Split(namePath, ",")
+ for _, path := range paths {
+ path = strings.TrimSpace(path)
+ value := strings.TrimSpace(query.String(path))
+ if value != "" {
+ return value
+ }
+ }
+
+ return ""
+}
+
func getOAuthAuthorizationURL(ctx context.Context, q *query.GetOAuthAuthorizationURL) error {
config, err := getConfig(ctx, q.Provider)
if err != nil {
@@ -161,7 +211,7 @@ func getOAuthAuthorizationURL(ctx context.Context, q *query.GetOAuthAuthorizatio
Redirect: q.Redirect,
Identifier: q.Identifier,
})
-
+
if err != nil {
return err
}
diff --git a/app/services/oauth/oauth_test.go b/app/services/oauth/oauth_test.go
index 83f5efcb1..f61c49b6c 100644
--- a/app/services/oauth/oauth_test.go
+++ b/app/services/oauth/oauth_test.go
@@ -54,7 +54,7 @@ func TestGetAuthURL_Facebook(t *testing.T) {
err := bus.Dispatch(ctx, authURL)
Expect(err).IsNil()
- Expect(authURL.Result).Equals("https://www.facebook.com/v3.2/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="+expectedState)
+ Expect(authURL.Result).Equals("https://www.facebook.com/v3.2/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=" + expectedState)
}
func TestGetAuthURL_Google(t *testing.T) {
@@ -76,7 +76,7 @@ func TestGetAuthURL_Google(t *testing.T) {
err := bus.Dispatch(ctx, authURL)
Expect(err).IsNil()
- Expect(authURL.Result).Equals("https://accounts.google.com/o/oauth2/v2/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="+expectedState)
+ Expect(authURL.Result).Equals("https://accounts.google.com/o/oauth2/v2/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=" + expectedState)
}
func TestGetAuthURL_GitHub(t *testing.T) {
@@ -98,7 +98,7 @@ func TestGetAuthURL_GitHub(t *testing.T) {
err := bus.Dispatch(ctx, authURL)
Expect(err).IsNil()
- Expect(authURL.Result).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="+expectedState)
+ Expect(authURL.Result).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=" + expectedState)
}
func TestGetAuthURL_Custom(t *testing.T) {
@@ -131,7 +131,7 @@ func TestGetAuthURL_Custom(t *testing.T) {
err := bus.Dispatch(ctx, authURL)
Expect(err).IsNil()
- Expect(authURL.Result).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="+expectedState)
+ Expect(authURL.Result).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=" + expectedState)
}
func TestGetAuthURL_Twitch(t *testing.T) {
@@ -164,7 +164,7 @@ func TestGetAuthURL_Twitch(t *testing.T) {
err := bus.Dispatch(ctx, authURL)
Expect(err).IsNil()
- Expect(authURL.Result).Equals("https://id.twitch.tv/oauth/authorize?claims=%7B%22userinfo%22%3A%7B%22preferred_username%22%3Anull%2C%22email%22%3Anull%2C%22email_verified%22%3Anull%7D%7D&client_id=CU_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2F_custom%2Fcallback&response_type=code&scope=openid&state="+expectedState)
+ Expect(authURL.Result).Equals("https://id.twitch.tv/oauth/authorize?claims=%7B%22userinfo%22%3A%7B%22preferred_username%22%3Anull%2C%22email%22%3Anull%2C%22email_verified%22%3Anull%7D%7D&client_id=CU_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2F_custom%2Fcallback&response_type=code&scope=openid&state=" + expectedState)
}
func TestParseProfileResponse_AllFields(t *testing.T) {
@@ -456,3 +456,188 @@ func TestCustomOAuth_Disabled(t *testing.T) {
Expect(err).IsNotNil()
Expect(oauthProfile.Result).IsNil()
}
+
+func TestParseOAuthRawProfile_CompositeName(t *testing.T) {
+ RegisterT(t)
+
+ // Initialize the OAuth service
+ bus.Init(&oauth.Service{})
+
+ testCases := []struct {
+ name string
+ jsonBody string
+ jsonNamePath string
+ expectedName string
+ expectedEmail string
+ expectedID string
+ }{
+ {
+ name: "Simple path",
+ jsonBody: `{"id": "123", "name": "Jon Snow", "email": "[email protected]"}`,
+ jsonNamePath: "name",
+ expectedName: "Jon Snow",
+ expectedEmail: "[email protected]",
+ expectedID: "123",
+ },
+ {
+ name: "Fallback path - first exists",
+ jsonBody: `{"id": "123", "name": "Jon Snow", "login": "jonsnow", "email": "[email protected]"}`,
+ jsonNamePath: "name, login",
+ expectedName: "Jon Snow",
+ expectedEmail: "[email protected]",
+ expectedID: "123",
+ },
+ {
+ name: "Fallback path - first missing",
+ jsonBody: `{"id": "123", "login": "jonsnow", "email": "[email protected]"}`,
+ jsonNamePath: "name, login",
+ expectedName: "jonsnow",
+ expectedEmail: "[email protected]",
+ expectedID: "123",
+ },
+ {
+ name: "Composite path with space",
+ jsonBody: `{"id": "123", "firstname": "Jon", "lastname": "Snow", "email": "[email protected]"}`,
+ jsonNamePath: "firstname + ' ' + lastname",
+ expectedName: "Jon Snow",
+ expectedEmail: "[email protected]",
+ expectedID: "123",
+ },
+ {
+ name: "Composite path with comma",
+ jsonBody: `{"id": "123", "firstname": "Jon", "lastname": "Snow", "email": "[email protected]"}`,
+ jsonNamePath: "lastname + ', ' + firstname",
+ expectedName: "Snow, Jon",
+ expectedEmail: "[email protected]",
+ expectedID: "123",
+ },
+ {
+ name: "Composite path with missing field",
+ jsonBody: `{"id": "123", "firstname": "Jon", "email": "[email protected]"}`,
+ jsonNamePath: "firstname + ' ' + lastname",
+ expectedName: "Jon", // lastname is missing, so only firstname is used
+ expectedEmail: "[email protected]",
+ expectedID: "123",
+ },
+ {
+ name: "Nested JSON path",
+ jsonBody: `{"id": "123", "profile": {"name": {"first": "Jon", "last": "Snow"}}, "email": "[email protected]"}`,
+ jsonNamePath: "profile.name.first + ' ' + profile.name.last",
+ expectedName: "Jon Snow",
+ expectedEmail: "[email protected]",
+ expectedID: "123",
+ },
+ {
+ name: "Empty name with email fallback",
+ jsonBody: `{"id": "123", "email": "[email protected]"}`,
+ jsonNamePath: "name",
+ expectedName: "jon.snow", // Should use part before @ in email
+ expectedEmail: "[email protected]",
+ expectedID: "123",
+ },
+ {
+ name: "Empty name and email",
+ jsonBody: `{"id": "123"}`,
+ jsonNamePath: "name",
+ expectedName: "Anonymous", // Should use "Anonymous"
+ expectedEmail: "",
+ expectedID: "123",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ // Create a mock config for this test case
+ mockConfig := &entity.OAuthConfig{
+ JSONUserIDPath: "id",
+ JSONUserNamePath: tc.jsonNamePath,
+ JSONUserEmailPath: "email",
+ }
+
+ // Register a mock handler for getConfig
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ q.Result = mockConfig
+ return nil
+ })
+
+ // Create the parse command
+ parseCmd := &cmd.ParseOAuthRawProfile{
+ Provider: "test_provider",
+ Body: tc.jsonBody,
+ }
+
+ // Execute the command
+ err := bus.Dispatch(context.Background(), parseCmd)
+ Expect(err).IsNil()
+
+ // Verify the result
+ profile := parseCmd.Result
+ Expect(profile).IsNotNil()
+ Expect(profile.ID).Equals(tc.expectedID)
+ Expect(profile.Name).Equals(tc.expectedName)
+ Expect(profile.Email).Equals(tc.expectedEmail)
+ })
+ }
+}
+
+// Test for invalid inputs
+func TestParseOAuthRawProfile_InvalidInputs(t *testing.T) {
+ RegisterT(t)
+
+ // Initialize the OAuth service
+ bus.Init(&oauth.Service{})
+
+ testCases := []struct {
+ name string
+ jsonBody string
+ jsonNamePath string
+ expectedError bool
+ }{
+ {
+ name: "Missing ID",
+ jsonBody: `{"name": "Jon Snow", "email": "[email protected]"}`,
+ jsonNamePath: "name",
+ expectedError: true,
+ },
+ {
+ name: "Invalid email",
+ jsonBody: `{"id": "123", "name": "Jon Snow", "email": "not-an-email"}`,
+ jsonNamePath: "name",
+ expectedError: false, // Should not error, but email should be empty
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ // Create a mock config for this test case
+ mockConfig := &entity.OAuthConfig{
+ JSONUserIDPath: "id",
+ JSONUserNamePath: tc.jsonNamePath,
+ JSONUserEmailPath: "email",
+ }
+
+ // Register a mock handler for getConfig
+ bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
+ q.Result = mockConfig
+ return nil
+ })
+
+ // Create the parse command
+ parseCmd := &cmd.ParseOAuthRawProfile{
+ Provider: "test_provider",
+ Body: tc.jsonBody,
+ }
+
+ // Execute the command
+ err := bus.Dispatch(context.Background(), parseCmd)
+
+ if tc.expectedError {
+ Expect(err).IsNotNil()
+ } else {
+ Expect(err).IsNil()
+ profile := parseCmd.Result
+ Expect(profile).IsNotNil()
+ }
+ })
+ }
+}
diff --git a/public/pages/Administration/components/OAuthForm.tsx b/public/pages/Administration/components/OAuthForm.tsx
index 793470b97..e08b8bd5f 100644
--- a/public/pages/Administration/components/OAuthForm.tsx
+++ b/public/pages/Administration/components/OAuthForm.tsx
@@ -86,7 +86,7 @@ export const OAuthForm: React.FC<OAuthFormProps> = (props) => {
disabled={!fider.session.user.isAdministrator}
onChange={setDisplayName}
/>
- <Field label="Button Preview">
+ <Field className="flex flex-y" label="Button Preview">
<SocialSignInButton option={{ displayName: displayName || "Button", provider, logoBlobKey, logoURL }} />
</Field>
</div>
@@ -149,6 +149,13 @@ export const OAuthForm: React.FC<OAuthFormProps> = (props) => {
</Input>
<h3 className="text-title mt-8 mb-2">JSON Path</h3>
+ <p>
+ Find out more about{" "}
+ <a rel="noopener" className="text-link" target="_blank" href="https://fider.io/docs/configuring-oauth#configuring-the-json-paths">
+ configuring the JSON Paths
+ </a>
+ .
+ </p>
<div className="grid grid-cols-3 gap-4">
<Input
@@ -159,10 +166,7 @@ export const OAuthForm: React.FC<OAuthFormProps> = (props) => {
disabled={!fider.session.user.isAdministrator}
onChange={setJSONUserIDPath}
>
- <p className="text-muted">
- Path to extract User ID from the 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>
+ <p className="text-muted">Make sure it&apos;s unique. </p>
</Input>
<Input
field="jsonUserNamePath"
@@ -173,8 +177,7 @@ export const OAuthForm: React.FC<OAuthFormProps> = (props) => {
onChange={setJSONUserNamePath}
>
<p className="text-muted">
- 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>.
+ Optional, but <strong>highly</strong> recommended.
</p>
</Input>
<Input
@@ -186,29 +189,11 @@ export const OAuthForm: React.FC<OAuthFormProps> = (props) => {
onChange={setJSONUserEmailPath}
>
<p className="text-muted">
- 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>.
+ Optional, but <strong>highly</strong> recommended.
</p>
</Input>
</div>
- <h3 className="text-title mb-2">Example Response</h3>
-
- <pre>
- {`{
- id: "35235"
- title: "Sr. Account Manager",
- profile: {
- dob: "01/05/2018",
- name: "John Doe"
- emails: [
- ]
- }
-}
- `}
- </pre>
-
<Field label="Trusted Source">
<Toggle field="isTrusted" active={isTrusted} onToggle={setTrusted} label={isTrusted ? "Yes" : "No"} />
<p className="text-muted mt-1">