Giter Club home page Giter Club logo

go-auth0's Introduction

Go SDK for Auth0

GoDoc Go Report Card Release License Build Status Codecov FOSSA Status

๐Ÿ“š Documentation โ€ข ๐Ÿš€ Getting Started โ€ข ๐Ÿ’ฌ Feedback


Documentation

  • Godoc - explore the Go SDK documentation.
  • Docs site โ€” explore our docs site and learn more about Auth0.
  • Examples - Further examples around usage of the SDK.

Getting started

Requirements

This library follows the same support policy as Go. The last two major Go releases are actively supported and compatibility issues will be fixed. While you may find that older versions of Go may work, we will not actively test and fix compatibility issues with these versions.

  • Go 1.21+

Installation

go get github.com/auth0/go-auth0

Usage

Authentication API Client

The Authentication API client is based on the Authentication API docs.

Create an Authentication API client by providing the details of your Auth0 Application.

package main

import (
	"context"
	"log"

	"github.com/auth0/go-auth0/authentication"
	"github.com/auth0/go-auth0/authentication/database"
	"github.com/auth0/go-auth0/authentication/oauth"
)

func main() {
	// Get these from your Auth0 Application Dashboard.
	domain := "example.us.auth0.com"
	clientID := "EXAMPLE_16L9d34h0qe4NVE6SaHxZEid"
	clientSecret := "EXAMPLE_XSQGmnt8JdXs23407hrK6XXXXXXX"

	// Initialize a new client using a domain, client ID and client secret.
	authAPI, err := authentication.New(
		context.TODO(), // Replace with a Context that better suits your usage
		domain,
		authentication.WithClientID(clientID),
		authentication.WithClientSecret(clientSecret), // Optional depending on the grants used
	)
	if err != nil {
		log.Fatalf("failed to initialize the auth0 authentication API client: %+v", err)
	}

	// Now we can interact with the Auth0 Authentication API.
	// Sign up a user
	userData := database.SignupRequest{
		Connection: "Username-Password-Authentication",
		Username:   "mytestaccount",
		Password:   "mypassword",
		Email:      "[email protected]",
	}

	createdUser, err := authAPI.Database.Signup(context.Background(), userData)
	if err != nil {
		log.Fatalf("failed to sign user up: %+v", err)
	}

	// Login using OAuth grants
	tokenSet, err := authAPI.OAuth.LoginWithAuthCodeWithPKCE(context.Background(), oauth.LoginWithAuthCodeWithPKCERequest{
		Code:         "test-code",
		CodeVerifier: "test-code-verifier",
	}, oauth.IDTokenValidationOptions{})
	if err != nil {
		log.Fatalf("failed to retrieve tokens: %+v", err)
	}
}

Note The context package can be used to pass cancellation signals and deadlines to the Client for handling a request. If there is no context available then context.Background() can be used.

Management API Client

The Management API client is based on the Management API docs.

package main

import (
	"context"
	"log"

	"github.com/auth0/go-auth0"
	"github.com/auth0/go-auth0/management"
)

func main() {
	// Get these from your Auth0 Application Dashboard.
	// The application needs to be a Machine To Machine authorized
	// to request access tokens for the Auth0 Management API,
	// with the desired permissions (scopes).
	domain := "example.auth0.com"
	clientID := "EXAMPLE_16L9d34h0qe4NVE6SaHxZEid"
	clientSecret := "EXAMPLE_XSQGmnt8JdXs23407hrK6XXXXXXX"

	// Initialize a new client using a domain, client ID and client secret.
	// Alternatively you can specify an access token:
	// `management.WithStaticToken("token")`
	auth0API, err := management.New(
		domain,
		management.WithClientCredentials(context.TODO(), clientID, clientSecret),  // Replace with a Context that better suits your usage
	)
	if err != nil {
		log.Fatalf("failed to initialize the auth0 management API client: %+v", err)
	}

	// Now we can interact with the Auth0 Management API.
	// Example: Creating a new client.
	client := &management.Client{
		Name:        auth0.String("My Client"),
		Description: auth0.String("Client created through the Go SDK"),
	}

	// The passed in client will get hydrated with the response.
	// This means that after this request, we will have access
	// to the client ID on the same client object.
	err = auth0API.Client.Create(context.TODO(), client)  // Replace with a Context that better suits your usage
	if err != nil {
		log.Fatalf("failed to create a new client: %+v", err)
	}

	// Make use of the getter functions to safely access
	// fields without causing a panic due nil pointers.
	log.Printf(
		"Created an auth0 client successfully. The ID is: %q",
		client.GetClientID(),
	)
}

Note The context package can be used to pass cancellation signals and deadlines to the Client for handling a request. If there is no context available then context.Background() can be used.

Rate Limiting

The Auth0 Management API imposes a rate limit on all API clients. When the limit is reached, the SDK will handle it in the background by retrying the API request when the limit is lifted.

Note The SDK does not prevent http.StatusTooManyRequests errors, instead it waits for the rate limit to be reset based on the value of the X-Rate-Limit-Reset header as the amount of seconds to wait.

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public Github issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.


Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform.
To learn more checkout Why Auth0?

This project is licensed under the MIT license. See the LICENSE file for more info.

go-auth0's People

Contributors

alexkappa avatar apamildner avatar apricote avatar bishtawi avatar cyx avatar dependabot[bot] avatar developerkunal avatar epintos avatar evansims avatar ewanharris avatar fschoell avatar gagalago avatar jmaeso avatar kgunbin avatar kpurdon avatar lambdalisue avatar mattoddie avatar mcalster avatar mkusaka avatar mlafeldt avatar nialdaly avatar nishanths avatar sergiught avatar sethyates avatar shushen avatar simonbarendse avatar widcket avatar willvedd avatar yinzara avatar yvovandoorn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-auth0's Issues

Support for Authentication APIs

Checklist

Describe the problem you'd like to have solved

Hello. I'm a long time user of the Python SDK

I started tinkering with the Go implementation, and realized it doesn't have support for the Authentication APIs.

Are there any plans to add Authentication APIs? And if so... what's the timeline for their availability?

Describe the ideal solution

Equivalent support for what's offered in Python's auth0.authentication package

Alternatives and current workarounds

Rolling our own implementation for these in Go (less than ideal), or sticking with our Python implementation

Additional context

No response

Ticket missing field ClientId for ChangePassword and VerifyEmail

From auth0 created by scampbell-zus: go-auth0/auth0#253

Description

According to the Auth0 documentation, the endpoint to request a password change and verify email should be able to take an additional argument of ClientID

client_id: ID of the client. If provided for tenants using New Universal Login experience, the user will be prompted to redirect to the default login route of the corresponding application once the ticket is used. See Configuring Default Login Routes for more details.

Currently, this library does not support passing in this argument, and as such removes the option for being navigated to the correct login page.

Affected Resources

  • management.Ticket

References

Documentation of Ticket endpoints:
https://auth0.com/docs/api/management/v2/#!/Tickets/post_email_verification
https://auth0.com/docs/api/management/v2/#!/Tickets/post_password_change

Similar GitHub issues within other language SDKs:
auth0/auth0-java#351
auth0/auth0.net#463

  • #0000

Community Note

  • Please vote on this issue by adding a ๐Ÿ‘ reaction to the original issue to help the community and maintainers prioritize this request
  • Please do not leave "+1" or "me too" comments, they generate extra noise for issue followers and do not help prioritize the request
  • If you are interested in working on this issue or have submitted a pull request, please leave a comment

Request function return http response

Describe the problem you'd like to have solved

To return the http request response back to the user which could be used for various features in therre software

Describe the ideal solution

Modifying the request function in the management.go file
image

Management client fails to fetch access token

Checklist

  • I have looked into the README and have not found a suitable solution or answer.
  • I have looked into the documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have upgraded to the latest version of this SDK and the issue still persists.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Description

Iโ€™m using Auth0 GO SDK to perform some user management calls like create or update user. I can instantiate management client without any issues.

options := management.WithClientCredentialsAndAudience("client_id", "client_sec", "aud")
m, err := management.New("domain_url", options)
if err != nil {
	log.Error().Msgf("failed to initialize Auth0 client: %s", err.Error())
	return nil, err
}

But when I try to use to make some API calls (like create user for instance), it returns the following error:

user := &management.User{
		Email:        &req.Email,
....
	}
err := m.User.Create(user)

Error message: failed to send the request: Post \"https://domain-url/api/v2/users\": oauth2: cannot fetch token: 404 Not Found\nResponse: Not found., Http status code: 500

I can create access token and create user using cli so there is no issue with Auth0 configuration.

Expectation

Backend server should be able to create Auth0 user using management API client.

Reproduction

See desc

Auth0 Go SDK version

v0.14.0

User struct missing the `groups` key

Checklist

  • I have looked into the README and have not found a suitable solution or answer.
  • I have looked into the documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have upgraded to the latest version of this SDK and the issue still persists.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Description

The User struct is not returning the groups value when called via the management API, however this gets returned when calling the API directly.

Would you be ok with me sending a PR adding this?

Expectation

The User struct includes a groups property

Reproduction

  1. Given I use the users search management API via this SDK
  2. I can't read the value of the groups because the User struct is not including it even thought the response is

Auth0 Go SDK version

v0.14.0

Bug when decoding Social Google Connection

From auth0 created by juniocezar: go-auth0/auth0#117

The allowed audiences field for the Google OAuth2 Social connection has the []interface{} type.

https://github.com/go-auth0/auth0/blob/1c72b20f2cab2ec7b754b93169a19d773af8d444/management/connection.go#L195

The Social Google account usually comes enabled by default in Auth0, but if you disable it:

image

and run a ConnectionManager.List() to get the list of all connections, this Social Google connection is still being listed.

{
    "total":1,
    "start":0,
    "limit":50,
    "connections":[
       {
          "id":"con_jBya21zJU4o*****",
          "options":{
             "email":true,
             "gmail":false,
             "orkut":false,
             "scope":[
                "email",
                "profile"
             ],
             "sites":false,
             "tasks":false,
             "blogger":false,
             "profile":true,
             "youtube":false,
             "calendar":false,
             "contacts":false,
             "analytics":false,
             "client_id":"",
             "moderator":false,
             "coordinate":false,
             "picasa_web":false,
             "google_plus":false,
             "google_books":false,
             "google_drive":false,
             "spreadsheets":false,
             "client_secret":"",
             "document_list":false,
             "latitude_best":false,
             "latitude_city":false,
             "url_shortener":false,
             "webmaster_tools":false,
             "chrome_web_store":false,
             "allowed_audiences":"",
             "adsense_management":false,
             "google_drive_files":false,
             "coordinate_readonly":false,
             "google_cloud_storage":false,
             "content_api_for_shopping":false,
             "google_affiliate_network":false
          },
          "strategy":"google-oauth2",
          "name":"google-oauth2",
          "is_domain_connection":false,
          "realms":[
             "google-oauth2"
          ],
          "enabled_clients":[
 
          ]
       }
    ]
 }

The problem here is that the allowed_audiences option comes as an empty string, leading to an Unmarshall error.

json: cannot unmarshal string into Go struct field ConnectionOptionsGoogleOAuth2.allowed_audiences of type []interface {}

I may try to work on a fix for it when I get some spare time

make authenticationError an exported type

Checklist

Describe the problem you'd like to have solved

The authenticationError is not an exported type even though it has JSON annotations.

I would like to be able to handle specific authentication errors in my code and I can't because this type is not exported from the package.

For example, how can I condition on an mfa_required error from the LoginWithPassword function?

Describe the ideal solution

Export the AuthenticationError type.

Alternatives and current workarounds

No response

Additional context

https://go.dev/blog/error-handling-and-go

Cannot remove the User Picture

Checklist

  • I have looked into the README and have not found a suitable solution or answer.
  • I have looked into the documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have upgraded to the latest version of this SDK and the issue still persists.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Description

It seems to not be possible to remove the profile picture of a user even though the auth0 management API allows it

Here is the auth0 request that I'd like to make using the SDK

curl -L -X PATCH 'https://AUTH0_DOMAIN/api/v2/users/USER_ID' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer ๐Ÿ”’' \
-d '{"picture":null}'

But a request like that is impossible to make becuase in the SDK, the type of the Picture field is *string, so if I make it nil it just gets omitted from the request body

Expectation

I expect to be able to remove the User picture with the SDK, by either setting it to an empty string

func TestRemoveUserProfilePicture(t *testing.T) {
	userId := "USER_ID"

	emptyString := ""
	userUpdate := &management.User{
		Picture: &emptyString,
	}
	err := client.User.Update(context.Background(), userId, userUpdate)

	assert.NoError(t, err)
	assert.Equal(t, userUpdate.GetPicture(), "")
}

Or that the type of Picture is sql.NullString (or similar) and I can explicitly set it to null:

func TestRemoveUserProfilePicture(t *testing.T) {
	userId := "USER_ID"

	nullString := sql.NullString{}
	userUpdate := &management.User{
		Picture: &nullString,
	}
	err := client.User.Update(context.Background(), userId, userUpdate)

	assert.NoError(t, err)
	assert.Equal(t, userUpdate.GetPicture(), "")
}

Reproduction

  1. Create a user with a profile picture
  2. Try to remove the profile picture using the SDK
  3. It doesn't work

Auth0 Go SDK version

1.0.1

Prompt.SetCustomText not passing body

Describe the problem

I Think i may have discovered a bug - the SetCustomText method does not appear to be passing a body.

However, I have never written a line of Go before today, so it very possible i have done something wrong.

Originally discovered by using the terraform provider for setting prompt language texts - and noticing that the body of the request is empty, in auth0 logs.

Tracked the code backwards the the go sdk, and have produced the following test script.

package main

import (
	"encoding/json"
	"fmt"
	"github.com/auth0/go-auth0/management"
)

func main() {
	m, err := management.New("CLIENT_DOMAIN", management.WithClientCredentials("CLIENT_ID", "CLIENT_SECRET"))
	if err != nil {
		// handle err
	}

	var body map[string]interface{}
	err1 := json.Unmarshal([]byte(`{ "login": { "title": "Welcome" } }`), &body)
	if err1 != nil {
		fmt.Println(err)
	}

	err = m.Client.Prompt.SetCustomText("login", "en", body)
	if err != nil {
		fmt.Printf("Something broken")
		fmt.Println(err)

	}

}

When i run the code above, I get no output (indicating success) however, the logs in auth0 show no body was passed. (same issue as i encountered with the terraform provider)

Could someone help to identify if this is an issue, or if i am using this incorrectly?

What was the expected behavior?

I expect

	var body map[string]interface{}
	err1 := json.Unmarshal([]byte(`{ "login": { "title": "Welcome" } }`), &body)
	if err1 != nil {
		fmt.Println(err)
	}

	err = m.Client.Prompt.SetCustomText("login", "en", body)

To make a PUT request to Auth0 Management API, and the language strings are included in the body of the request when viewing the auth0 logs.

Reproduction

Reproduction steps included above :-)

Environment

Im not sure how to validate what version of things i am using - i have never written GO before today.

The go.mod file in my test directory has the following content (this is automatically generated - the only dependency i added with go get was github.com/auth0/go-auth0 :

module sdk-test

go 1.18

require (
	github.com/PuerkitoBio/rehttp v1.1.0 // indirect
	github.com/auth0/go-auth0 v0.6.3 // indirect
	github.com/golang/protobuf v1.4.2 // indirect
	golang.org/x/net v0.0.0-20210510120150-4163338589ed // indirect
	golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 // indirect
	google.golang.org/appengine v1.6.6 // indirect
	google.golang.org/protobuf v1.25.0 // indirect
)

Any other info i can provide, please let me know.

Organizations.List request has bugs with checkpoint paginations params input

Describe the problem

While making auth0 call to list all organization, we are getting unexpected results.

Request:

                 Auth0Client.Organization.List(
			 management.From(<prev next>),
		)

When we dont send Take, the Limit is set to 50, but in each request, we dont get a Next value. Start is always set to 0, next to empty string and total to the number of documents.

When we do send Take (i did set it as 10, then 50), it send start, limit, length, total as 0 and next as a string and with organizations list. First 50 organizations.

Similar issue: auth0/auth0-python#277

What was the expected behavior?

To get next value for list request and proper params for the same with Take value

Reproduction

The error is reproducible. Making a call to the following function would help.
https://github.com/auth0/go-auth0/blob/main/management/organization.go#L187

Environment

  • Version of go-auth0 - v0.10.0

Add LastPasswordReset field to management.User struct

Describe the problem

The API provides a last_password_reset field if relevant, but the management.User struct has no field to deserialize it to.

What was the expected behavior?

I think it should be possible to read the last_password_reset field when necessary, so this field should be added to the struct.

Reproduction

  1. Create/sign up as a new user
  2. Set a password
  3. Retrieve this user record from the Auth0 management API
  4. Observe that it is not possible to access the last_password_reset data.

Environment

Version v0.10.1

Add feature to make query params a list

Checklist

Describe the problem you'd like to have solved

I am trying to run Connection.List with multiple strategies, however I cannot make it like the curl request similar to strategy=&strategy=&strategy= because Connection.List does use the search_engine query builder and Parameter function replaces the strategy each time I put one

Describe the ideal solution

Ideally a function like

func ParameterArray(key, values []string) RequestOption {
	return newRequestOption(func(r *http.Request) {
		q := r.URL.Query()
                for _, value := range values {
		      q.Add(key, value)
		}
		r.URL.RawQuery = q.Encode()
	})
}

or something similar

Alternatives and current workarounds

call the function 3 times

Additional context

No response

Support Get Organization Invitation by TicketID

Checklist

Describe the problem you'd like to have solved

Hi, I am wondering why user invitation is sent with invitation ticket id and organization id, but the API does not expose search by ticket id for invitations? By the time we have a url link, we cannot look up the invitation unless we fetch all the invitations and search by ticket id. This isn't an ideal solution.

Describe the ideal solution

Please provide an interface that allows to search an invitation by ticket id.

Alternatives and current workarounds

The current work around is to search manually by invitation id but this does not solve the issue when the size invitations is big as paginated.

Additional context

No response

UserIdentity is Missing profileData

Describe the problem

The field profileData is present in social User Identities (see below) and retrievable from the REST API, but is not in the UserIdentity struct. This means that this SDK cannot be used to retrieve social profile data.
Here's an example of the key within an account with two identities:

...
  "identities": [
    {
      "connection": "Initial-Connection",
      "user_id": "123xyz",
      "provider": "auth0",
      "isSocial": false
    },
    {
      "connection": "google-oauth2",
      "user_id": "abc123",
      "provider": "google-oauth2",
      "isSocial": true,
      "profileData": {
         "family_name": "some name",
         "picture": "https://cdn.googleusercontent.com/user/abc123"
      }
    }
  ],
...

What was the expected behavior?

The UserIdentity struct has the profileData field and data.

Environment

gopkg.in/auth0.v5 v5.21.1

failed to unmarshal response payload: invalid character 'W' looking for beginning of value

Checklist

  • I have looked into the README and have not found a suitable solution or answer.
  • I have looked into the documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have upgraded to the latest version of this SDK and the issue still persists.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Description

I'm using the SDK to trigger a password reset:

// Reset password method
func (a *Auth0) ResetPassword(userEmail string) error {

	type ChangePassword struct {
		ClientId   string `json:"client_id"`
		Email      string `json:"email"`
		Connection string `json:"connection"`
	}

	baseURL := "https://" + a.config.Auth0_domain + "/"

	err := a.Request(context.TODO(), http.MethodPost, baseURL+"dbconnections/change_password", &ChangePassword{
		ClientId:   a.config.Auth0_client_id,
		Email:      userEmail,
		Connection: "Username-Password-Authentication",
	},
	)

	if err != nil {
		return err
	}

	return nil
}

It returns an error:

failed to unmarshal response payload: invalid character 'W' looking for begininng of value

Even though the reset password is sent, and users can safely reset the password

Expectation

Ideally, it would be great to have a direct method to trigger a password reset with the SDK, without having to make an HTTP call manually (I guess this is a very common use case)

But in this case, using the Request method, it should be able to unmarshal the response, I guess this is a format issue?

Reproduction

  1. Call the dbconnections/change_password endpoint using the Request method of the Go Auth0 SDK with correct payload and Auth0 domain
  2. You should receive the reset password email, but the response should throw an error because it can't be unmarshal

Auth0 Go SDK version

1.3.1

Add support for segment log stream

Checklist

Describe the problem you'd like to have solved

Segment is supported at the api level but not on go-auth0 (thus not supported on terraform-provider-auth0 either!)

Describe the ideal solution

go-auth0 and terraform-provider-auth0 support segment log streams

Alternatives and current workarounds

No response

Additional context

No response

Terraform-provider-auth0 and go-Auth0

Terraform-provider-auth0 and go-Auth0

๐Ÿ‘‹ Hello, many of you have probably seen the GitHub updates by now. Still, we want to take a minute to formally announce that we (Auth0) are officially supporting the terraform-provider-auth0 plugin and go-auth0 SDK! Weโ€™re incredibly excited about the potential of these tools and we canโ€™t wait to start making more frequent contributions to both libraries soon ๐Ÿ˜Š

Why Now ๐Ÿคท

Given the popularity and massive support for Alex's libraries, we felt it was time to give both libraries the the first-class support they deserve. From a developer experience lens, we see a huge potential in developer productivity by supporting tools like these, making it even easier for developers to build with Auth0.

Logistics ๐Ÿšš

Going forward, both the new terraform-provider-auth0 and go-auth0 will reside under the Auth0 org in GitHub. Before transferring both repos in GitHub, we worked to burn down many of the feature requests, enhancements, and PRs from the previous repos. However, there are still plenty for us to work through. Any open issues should still be retained after the transfer in the Auth0 org as well. If you feel that any feedback or issues may have gotten lost in the shuffle, please let us know so we can rectify that. Over the coming weeks, expect to see a lot of activity from the team as we focus on burning down the issue backlog and planning the longer-term roadmap.

How to Contribute ๐Ÿ‘ฉโ€๐Ÿ’ป

As mentioned, weโ€™re incredibly excited about making headway on both libraries but we need your help! We would love to hear from all of you and learn more about your needs and pain points so we can move these tools into the future. Please do not hesitate to reach out on GitHub for any feedback, issues, feature requests, and PRโ€™s. Also, make sure you take a look at our contributing guidelines to learn more about getting involved.

Thanks again to all of you and especially Alex for the support and contributions to terraform-provider-auth0 and go-auth0 SDK! Without his countless hours of work we wouldn't be where we are today. We canโ€™t wait to start working with all of you building the future of these tools ๐Ÿ™‡

Support MFA APIs

Checklist

Describe the problem you'd like to have solved

The current SDK contains only a portion of the Auth0 Authentication APIs. It's missing MFA APIs.

Describe the ideal solution

Add support for MFA and the rest of APIs as described in the Auth0 Authentication APIs: https://auth0.com/docs/api/authentication

Alternatives and current workarounds

No response

Additional context

No response

Recommended to use interface instead of struct in xxxManager

From auth0 created by starsz: go-auth0/auth0#226

Description

Hello, I found that the xxxManager was defined as a struct.
And it was referenced in management.

https://github.com/go-auth0/auth0/blob/0ed82d242c8bfacb02db3352ef6688591108b371/management/management.go#L85-L106

https://github.com/go-auth0/auth0/blob/0ed82d242c8bfacb02db3352ef6688591108b371/management/user.go#L280-L282

Affected Resources

  • management.Xxx
  • management.XxxManager

Potential Sample Code

I recommend to use interface instead of struct in xxxManager
Like this:

type UserManager interface{
 Create(u *User, opts ...RequestOption) error
 Read(id string, opts ...RequestOption) (u *User, err error)
 Update(id string, u *User, opts ...RequestOption) (err error) 
 List(opts ...RequestOption) (ul *UserList, err error) 
...
}

So that we can mock the Management.User and do some unit tests.

The same as other managers.

Support `upstream_params` option for connections

From auth0 created by choncou: go-auth0/auth0#234

Description

Currently I don't see if it is possible to pass upstream_params in the options for a connection. My goal is for the functionality to be available in the terraform provider.

My use-case would be to be able to pass a through "prompt":{"value":"select_account"} to a google oauth2 connection, which will help avoid an issue of Google always using the current signed-in Google account, and not allowing a user to pick a different account

Affected Resources

  • management.Connection

Potential Sample Code

N/A

References

Community Note

  • Please vote on this issue by adding a ๐Ÿ‘ reaction to the original issue to help the community and maintainers prioritize this request
  • Please do not leave "+1" or "me too" comments, they generate extra noise for issue followers and do not help prioritize the request
  • If you are interested in working on this issue or have submitted a pull request, please leave a comment

List log endpoints returns scope field as an array of strings instead of string for certain log types.

Checklist

  • I have looked into the README and have not found a suitable solution or answer.
  • I have looked into the documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have upgraded to the latest version of this SDK and the issue still persists.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Description

The list logs endpoint causes an JSON unmarshal error for certain log types:

Example of a log type that causes error (this log is extracted directly from the Auth0 management REST API):

{
		"date": "2023-03-30T09:02:33.667Z",
		"type": "fsa",
		"description": "Login required",
		"client_id": "redacted",
		"client_name": "Admin",
		"ip": "79.160.79.156",
		"user_agent": "Firefox 111.0.0 / Mac OS X 10.15.0",
		"details": {
			"body": {},
			"qs": {
				"audience": "https://domain.com",
				"client_id": "redacted",
				"redirect_uri": "http://localhost:3000",
				"scope": "openid profile email",
				"response_type": "code",
				"response_mode": "web_message",
				"state": "redacted==",
				"nonce": "redacted==",
				"code_challenge": "redacted",
				"code_challenge_method": "S256",
				"prompt": "none",
				"auth0Client": "redacted="
			},
			"connection": null,
			"error": {
				"message": "Login required",
				"oauthError": "login_required",
				"type": "oauth-authorization"
			},
			"riskAssessment": null
		},
		"hostname": "tenant.eu.auth0.com",
		"audience": "https://domain.com",
		"scope": [
			"openid",
			"profile",
			"email"
		],
		"auth0_client": {
			"name": "auth0-react",
			"version": "1.11.0"
		},
		"log_id": "90020230330090235500182000000000000001223372036901203194",
		"_id": "90020230330090235500182000000000000001223372036901203194",
		"isMobile": false
	}

The management.Log struct has the scope field as a *string

	// Scope permissions applied to the event.
	Scope *string `json:"scope"`

This causes the following error from the management client:

failed to unmarshal response payload: json: cannot unmarshal array into Go struct field Log.scope of type string

Expectation

I expected the management*Client to be able to parse all log types from Auth0 without error.

Reproduction

See the above log example for a log that causes the error.

Auth0 Go SDK version

0.16

Suggested Way to Check StatusCode of Management API Errors

Describe the problem

This may just be my misunderstanding of how this library is meant to be used, but with managementError being private to the package, I don't see an elegant or idiomatic way to retrieve the status code of an error from the management API.

If my understanding is correct, you should be able to use errors.As() to recursively unwrap and find an error that matches the target type, but because management.managementError is not exposed on the package, and management.Error is an interface, I don't see a clean way to get at and check the status code of the error that is agnostic to the error type being returned.

What was the expected behavior?

I need some way to check if the status code of an error returned from the auth0 management API in an idiomatic manner. Right now this only seems to be possible if I manually unwrap the error and then type assert it as a management.Error but that seems kind of non-standard to me. I am less experienced in Golang than other languages though, so it is possible that there is a pattern/understanding I'm missing here. Please LMK if so.

Reproduction

Not sure what all to provide here, but I can offer snippets of the code if needed. The core issue isn't really something "reproduce-able" per-se but more just a question of implementation/approach.

Environment

  • Version of go-auth0 used: gopkg.in/auth0.v5/management
  • Other modules/plugins/libraries that might be involved: N/a

Ticket.ChangePassword doesn't return the response

From auth0 created by nicolaigj: go-auth0/auth0#252

Description

In the API documentation the endpoint tickets/password-change responds with a ticket URL that we can distribute to the user, but the SDK only returns an error value. The ChangePassword-function has no value when the ticket isn't returned and there is no other way of getting it (I think?).

Affected Resources

  • management.Ticket.ChangePassword

Potential Sample Code

References

https://auth0.com/docs/api/management/v2#!/Tickets/post_password_change

Community Note

  • Please vote on this issue by adding a ๐Ÿ‘ reaction to the original issue to help the community and maintainers prioritize this request
  • Please do not leave "+1" or "me too" comments, they generate extra noise for issue followers and do not help prioritize the request
  • If you are interested in working on this issue or have submitted a pull request, please leave a comment

Get Default BrandingTheme

Describe the problem you'd like to have solved

Add support for getting default branding theme i.e. by using this API:
https://auth0.com/docs/api/management/v2#!/Branding/get_default_branding_theme

This would be useful if current theme ID is not known

Describe the ideal solution

A way to get the default branding theme, something like this:

var m &management.Management
defaultTheme, err := m.BrandingTheme.Default()

Alternatives and current workarounds

Can currently get default theme like this:

var m &management.Management
theme := &management.BrandingTheme{}
err := m.Request(http.MethodGet, m.URI("branding", "themes", "default"), &theme)

Additional context

None

Ticket is missing OrganizationID

Checklist

  • I have looked into the README and have not found a suitable solution or answer.
  • I have looked into the documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have upgraded to the latest version of this SDK and the issue still persists.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Description

I was looking into supporting organization-branded Password Reset auth0 pages using ChangePassword(), but always got the tenant branded pages from ResultURL. Eventually I realized OrganizationID was needed, which worked when used in curl generated by the docs pages.

However when I tried the same in go-auth, I noticed the Ticket struct was missing OrganizationID.

https://github.com/auth0/go-auth0/blob/v0.16.0/management/ticket.go#L69

// Ticket is used for a users' email verification or password change.
type Ticket struct {
	// The user will be redirected to this endpoint once the ticket is used.
	ResultURL *string `json:"result_url,omitempty"`

	// The UserID for which the ticket is to be created.
	UserID *string `json:"user_id,omitempty"`

	// The ticket's lifetime in seconds starting from the moment of creation.
	// After expiration the ticket can not be used to verify the users' email.
	// If not specified or if you send 0 the Auth0 default lifetime will be
	// applied.
	TTLSec *int `json:"ttl_sec,omitempty"`

	// ID of the client. If provided for tenants using New Universal Login experience,
	// the user will be prompted to redirect to the default login route of the
	// corresponding application once the ticket is used.
	//
	// Conflicts with: ResultURL
	ClientID *string `json:"client_id,omitempty"`

	// The connection that provides the identity for which the password is to be
	// changed. If sending this parameter, the email is also required and the
	// UserID is invalid.
	//
	// Requires: Email
	// Conflicts with: UserID
	ConnectionID *string `json:"connection_id,omitempty"`

	// The user's email.
	//
	// Requires: ConnectionID
	// Conflicts with: UserID
	Email *string `json:"email,omitempty"`

	// The URL that represents the ticket.
	Ticket *string `json:"ticket,omitempty"`

	// Whether to set the email_verified attribute to true (true) or whether it
	// should not be updated.
	MarkEmailAsVerified *bool `json:"mark_email_as_verified,omitempty"`

	// Whether to include the email address as part of the returnUrl in
	// the reset_email (true), or not (false - default).
	IncludeEmailInRedirect *bool `json:"includeEmailInRedirect,omitempty"`
}

ChangePassword

// ChangePassword creates a password change ticket for a user.
//
// See: https://auth0.com/docs/api/management/v2#!/Tickets/post_password_change
func (m *TicketManager) ChangePassword(t *Ticket, opts ...RequestOption) error {
	return m.Request("POST", m.URI("tickets", "password-change"), t, opts...)
}

This surprised me as according to the docs everything else is included in the Ticket struct.
https://auth0.com/docs/api/management/v2#!/Tickets/post_password_change

It succeeded when I forked a Ticket struct with OrganizationID and called the request function directly. That returned a link leading to branded pages.

Expectation

I would expect management.Ticket to support OrganizationID, with any validation logic that would entail.

Reproduction

  1. Given you are on the most recent Auth0 Go SDK version
  2. When you attempt to add OrganizationID to a created management.Ticket variable
  3. Then you get a compilation error

Auth0 Go SDK version

v0.16.0

Can not remove all clients from a connection

From auth0 created by mvanderlee: go-auth0/auth0#241

Description

Setting c.EnabledClients to an empty list causes it to be omitted from the actual update request and thus the field is not actually updated.

This is because omitempty omits empty slices as well. As found in EnabledClients []interface{} json:"enabled_clients,omitempty".
This appears to be related to golang/go#22480

I'm not familiar with GoLang, but maybe there is a way to omit nil in the MarshalJSON function in connection.py?

Package Version

v5.19.2

Affected Resources

  • management.Connection

Sample Code

c := &management.Connection{
  EnabledClients = []interface{}
}
err = api.Connection.Update(connId, c, management.Context(ctx))

Expected Behavior

Should set EnabledClients to an empty list. i.e.: disable the connection for all clients

Actual Behavior

EnabledClients update is ignored, or if it's the only property set, the request actually fails.

Output

Error: 400 Bad Request: Payload validation error: 'Too few properties defined (0), minimum 1'

References

golang/go#22480

Community Note

  • Please vote on this issue by adding a ๐Ÿ‘ reaction to the original issue to help the community and maintainers prioritize this request
  • Please do not leave "+1" or "me too" comments, they generate extra noise for issue followers and do not help prioritize the request
  • If you are interested in working on this issue or have submitted a pull request, please leave a comment

Every request returns a 401 http response with `Invalid token`

From auth0 created by Breigner01: go-auth0/auth0#256

Description

Package Version

v5.21.1

Affected Resources

  • management.User

Sample Code

type User struct {
	UserDB    model.User      `json:"user_db"`
	UserAuth0 management.User `json:"user_auth0"`
}

func getUserByID(c *gin.Context, db *gorm.DB) {
	m, err := management.New(os.Getenv("AUTH0_DOMAIN"), management.WithClientCredentials(
		os.Getenv("AUTH0_CLIENT_ID"),
		os.Getenv("AUTH0_CLIENT_SECRET"),
	))
	if err != nil {
		panic(err)
	}

	var usersDB []model.User
	var users []User

	db.Find(&usersDB)

	for i := range usersDB {
		auth0User, err := m.User.Read(usersDB[i].UserId)
		fmt.Println(err)
		if err != nil {
			c.JSON(500, gin.H{
				"message": "Error getting user from Auth0",
				"error":   err,
			})
			return
		}
		users = append(users, User{
			UserDB:    usersDB[i],
			UserAuth0: *auth0User,
		})
	}

	c.JSON(200, gin.H{
		"user_number": len(users),
		"users":       users,
	})
}

Expected Behavior

I'm expecting it to return the user asked for.

Actual Behavior

I get a 401 http response with the message Unauthorized: Invalid token

Output

401 Unauthorized: Invalid token

References

  • #0000

Community Note

  • Please vote on this issue by adding a ๐Ÿ‘ reaction to the original issue to help the community and maintainers prioritize this request
  • Please do not leave "+1" or "me too" comments, they generate extra noise for issue followers and do not help prioritize the request
  • If you are interested in working on this issue or have submitted a pull request, please leave a comment

Getting azure's upn attribute

From auth0 created by Gilwe: go-auth0/auth0#152

Im trying to create an integration with azure but auth0 notifies that sometime azure wont send to auth0 the user's email upon creation so auth0 will get the user's upn (UserPrincipalName) which is an applicable replacement, that most of the times will hold the email.

Look at the bottom of:
https://auth0.com/docs/connections/azuread-adfs-email-verification?_ga=2.142645749.1771189736.1603610793-286699271.1581410788&_gac=1.220607850.1603614771.Cj0KCQjwxNT8BRD9ARIsAJ8S5xa5ttTL_Lyo15V8RN-VrNUkMGgnA1jIJ50_-5N_2-XwjV8LDe3g8DoaAshuEALw_wcB

I can issue a PR that will add it to User in management/user.go but would like to know if there's a more elegant way of getting that upn attribute when querying a user.

Thank you.

Add WithClientCredentialsAndTokenURL option

Checklist

Describe the problem you'd like to have solved

We are trying to use the SDK for Auth0 API operations, but running into issues with the tokens.

We realized that in your code, you're using the uri to generate the token url by concatenating the domain with oauth/token. Unfortunately for us, the token url is different than our auth0 domain; not sure why this is the case.

So, the option WithClientCredentials will not work. We have tried to use WithClient option by generating our own http.Client and pass it to that option.

func generateCilent() *http.Client {
    ctx := context.Background()
   
    conf := clientCredentials.Config{
        ClientId: "client id",
        ClientSecret: "secret",
        TokenURL:  "token url",
        EndpointParams: "params goes here",
        AuthStyle: "oauth style"
    }

    return conf.Client(ctx)
}

We were expecting it to work but unfortunately it did not, we came across with this error.

oauth2: Transport's Source is nil

We took a look under hood and saw that WithClient option only updates the m.http, so the m.tokenSource remains empty; we think.

We used WithStaticToken, which it works but that's assuming the token never expires. We want to refresh the tokens.

Describe the ideal solution

Ideally, we would like another option to the tokenURL, so something like this

WithClientCredentialsAndTokenURL(clientID string, clientSecret string, tokenURL string) management.Option

so this tokenURL field will be used to update the TokenURL under this function, https://github.com/auth0/go-auth0/blob/main/internal/client/client.go#L223

func OAuth2ClientCredentialsAndAudience(
	ctx context.Context,
	uri,
	clientID,
	clientSecret,
	audience string,
) oauth2.TokenSource {
	cfg := &clientcredentials.Config{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		TokenURL:     uri + "/oauth/token",
		EndpointParams: url.Values{
			"audience": []string{audience},
		},
	}

	return cfg.TokenSource(ctx)
}

This is an idea from what we have seen from your code, but the main point is to provide an alternative to pass a token URL that's different the Auth0 domain.

Alternatives and current workarounds

No response

Additional context

No response

Add `decryptionKey` to management.ConnectionOptionsSAML

Checklist

Describe the problem you'd like to have solved

ConnectionOptionsSAML should have decryptionKey. It is used in the documentation here: https://auth0.com/docs/authenticate/protocols/saml/saml-sso-integrations/sign-and-encrypt-saml-requests#use-your-key-pair-to-decrypt-encrypted-responses

Describe the ideal solution

A new field in ConnectionOptionsSAML, where when we do a Read request for a SAML connection, that field will be filled

Alternatives and current workarounds

No response

Additional context

No response

CloudQuery source plugin?

Checklist

Describe the problem you'd like to have solved

Hi Team, hopefully this is right place to ask, if not, I'd appreciate if you can direct me.

I'm the founder of cloudquery.io, a high performance open source ELT framework.

Our users are interested in an Auth0 plugin, but as we cannot maintain all the plugins ourselves, I was curious if this would be an interesting collaboration, where we would help implement an initial source plugin, and you will help maintain it.

This will give your users the ability to sync Auth0 data to any of their datalakes/data-warehouses/databases easily using any of the growing list of CQ destination plugins.

Best,
Yevgeny

Describe the ideal solution

Alternatives and current workarounds

No response

Additional context

No response

LogWrapper fails to unmarshal log user_id field

Checklist

  • I have looked into the README and have not found a suitable solution or answer.
  • I have looked into the documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have upgraded to the latest version of this SDK and the issue still persists.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Description

Hi, I've implemented a Prometheus exporter,https://github.com/tfadeyi/auth0-simple-exporter, that uses the go-auth0 library to export tenant log events to prometheus, recently one of the users as reported the following error

json: cannot unmarshal number into Go struct field logWrapper.user_id of type string"

Following the call stack, the exporter makes a request to go-auth0 log client to fetch logs, but the operation seems to fail and an error seems to occur during the unmarshalling of the log struct by the library https://github.com/auth0/go-auth0/blob/main/management/log.go#L162.

The user is using a custom database connection but I don't know if it's possible for it to have made it possible to have a number instead of a string. Looking at the auth0 docs the log user_id seems to never be a number and always string.
I'm not 100% sure if it's possible that a log entry ended with number instead of a string for the user_id field.

Expectation

No unmarshalling error occurs when listing logs.

Reproduction

I was only able to reproduce it in the unit tests for the log client.
If a log element has user_id as a number instead of string the error will occur.

{
 "log_id": "..."
 "user_id": 1
}

Auth0 Go SDK version

1.1.0

Function to enable WebAuthN Platform factor updates wrong factor

While looking at the new Terraform module, I saw that webauthn support did not appear in the Guardian resource. I dug in to the source code for the Go SDK and looked at the implementation for enabling webauthn. The function appears to pass in webauthn-roaming as the factor type when it should be passing webauthn-platform.

Looking at the unit test, it appears that it only verifies the enabled property and not the factor type that was also provided.

Expose RateLimit headers in 429 responses from the API

Checklist

Describe the problem you'd like to have solved

The SDK does not appear to expose Rate Limit response headers from the API for 429 responses.

Describe the ideal solution

Create a Rate Limited Error type to be used for unmarshaling 429 responses that can expose the values of the X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset headers.

Alternatives and current workarounds

No response

Additional context

No response

Sdk itself handles request for Management Api Rate Limiting

From auth0 created by sambhavjain9138: go-auth0/auth0#261

Question

we are currently using this SDK to make management api calls. But we face some error due to management api rate limiting. Following is an article for the same.
https://auth0.com/docs/troubleshoot/customer-support/operational-policies/rate-limit-policy/management-api-endpoint-rate-limits

During this request, auth0 returns a status code of 409, which helps us identify that the error is due to rate limiting. So can sdk itself make a small delay and then make a retry, during such responses?

Even if it doesnt, How can we get this response status code in the response so as to make such check and introduce delay?

Can't update user email

From auth0 created by munir131: go-auth0/auth0#217

Description

As per REST api doc
If you are updating email or phone_number you can specify, optionally, the client_id property.
But in this sdk user struct doesn't have client_id support.

Package Version

v5

Affected Resources

  • management.User

Expected Behavior

Email should be updated

Actual Behavior

no user with the provided email found

Community Note

  • Please vote on this issue by adding a ๐Ÿ‘ reaction to the original issue to help the community and maintainers prioritize this request
  • Please do not leave "+1" or "me too" comments, they generate extra noise for issue followers and do not help prioritize the request
  • If you are interested in working on this issue or have submitted a pull request, please leave a comment

User Management Create method should return User after creation

Checklist

Describe the problem you'd like to have solved

When creating a user using the User Management Create method, it should return a user like the REST endpoint does instead of only returning an error. Since no user attributes are returned after the user is created, it is not the easiest to then fetch the newly created user. For instance, the new user would need to be fetched by their email using another method (List maybe?).

Describe the ideal solution

Currently, the Create method returns an error if there is one. However, it would be great if it would return the newly created user like the REST endpoint does. This would save an extra API call and some potential hacky solutions.

Alternatives and current workarounds

Once the user is created, assuming there is no error, I suppose I could use the List or ListByEmail methods to search for the newly created user by their email and get that user from the returned array.

Additional context

The docs show the REST endpoint returns the created user: https://auth0.com/docs/api/management/v2#!/Users/post_users

SDK is expecting different JSON schema for ListAuthenticationMethods API endpoint

Checklist

  • I have looked into the README and have not found a suitable solution or answer.
  • I have looked into the documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have upgraded to the latest version of this SDK and the issue still persists.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Description

The Auth0 Go SDK is expecting a different JSON schema than what is returned from the API for the ListAuthenticationMethods API endpoint.

Response sample from Management API V2 endpoint:

[
    {
        "id": "phone|dev_sampleid",
        "type": "phone",
        "confirmed": true,
        "phone_number": "XXXXXXXX1234",
        "created_at": "2023-07-13T20:24:42.388Z",
        "last_auth_at": "2023-07-13T20:28:49.095Z",
        "preferred_authentication_method": "sms",
        "authentication_methods": [
            {
                "id": "sms|dev_sampleid",
                "type": "sms"
            }
        ]
    }
]

Error message from Auth0 Management GO SDK Call:

failed to unmarshal response payload: json: cannot unmarshal array into Go value of type management.AuthenticationMethodList

Expectation

The SDK is expecting a wrapping authenticators parent object wrapping around the array of authentication methods, for example:


{
    "authenticators": [
      {
          "id": "phone|dev_sampleid",
          "type": "phone",
          "confirmed": true,
          "phone_number": "XXXXXXXX1234",
          "created_at": "2023-07-13T20:24:42.388Z",
          "last_auth_at": "2023-07-13T20:28:49.095Z",
          "preferred_authentication_method": "sms",
          "authentication_methods": [
              {
                  "id": "sms|dev_sampleid",
                  "type": "sms"
              }
          ]
      }
   ]
}

I would expect the SDK to be able to handle the latest version of the Auth0 Management API.

Reproduction

  1. Given a user who is enrolled with one or more Authentication factors in an Auth0 Tenant.
  2. When you call the ListAuthenticationMethods function, providing the user ID from step 1, then ....
  3. You receive the error "failed to unmarshal response payload: json: cannot unmarshal array into Go value of type management.AuthenticationMethodList"

Auth0 Go SDK version

0.17.2

docs do not explain how to paginate

Checklist

  • I have looked into the README and have not found a suitable solution or answer.
  • I have looked into the documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have upgraded to the latest version of this SDK and the issue still persists.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Description

The documentation does not explain how to use pagination.

PS: bonus bug: the link in the PR template to the Auth0 Community forums (https://community.auth0.com/c/sdks/5) 404s

Expectation

A concise explanation of pagination using the go-auth0 sdk, including

  • a code snippet showing how to do it
  • a discussion of whether sorting is needed or not
  • explanation of tradeoffs using List.Next vs page indexes
  • links from each method returning a List to the explanation

Reproduction

Infinite loop doing the naive thing:

auth0API, _ := management.New(...)
ul, _ := auth0API.User.List(ctx)
for {
	for _, u := range ul.Users {
		// process user
	}

	if !ul.HasNext() {
		break
	}
	ul, _ = auth0API.User.List(ctx, management.From(ul.Next))
}

Auth0 Go SDK version

v1.2.0

SDK overwrites transport when sending in custom http client with WithClient()

Describe the problem

We want to use our custom HTTP client with the management client. We are using datadog http tracing to trace our http requests, which works by modifying the client's transport to augment it with tracing. However, it seems like our transport/roundtripper is overwritten by the "default" roundtripper in the package and the tracing does not work. When commenting out the WithUserAgent and WithRateLimit in management.New(), we get the desired Transport with tracing.

What was the expected behavior?

The calls to auth0 management API should function as normal and traces should appear in DataDog.

Reproduction

Here is a repo that replicates a simple version of our setup, that can be used to demonstrate the issue.

Here are the values that we see for Transport inside our New function when debugging:
Before calling management.New()

Transport = {net/http.RoundTripper | *gopkg.in/DataDog/dd-trace-go.v1/contrib/net/http.roundTripper}

After calling management.New()

http = {@net/http.Client}
     Transport = {net/http.RoundTripper | *github.com/PuerkitoBio/rehttp.Transport}

Environment

go-auth0 v0.5.0
Go 1.17

Absence of `multifactor` field in `User` struct

Describe the problem you'd like to have solved.

I'm always frustrated when I'm trying to get user and deal with Multifactor []string property, but there is no such property in the library. This field is actually a part of the api. I do not understand why it's missing in the lib(((

Describe the ideal solution.

Add multifactor field to User struct

User struct is missing additional identity provider details

Checklist

  • I have looked into the README and have not found a suitable solution or answer.
  • I have looked into the documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have upgraded to the latest version of this SDK and the issue still persists.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Description

Using the Management API explorer, I see that the GET /users/:id API returns the user profile with extra details from an identity provider that matches the "Raw JSON" in the user management UI.

However using the Go client, the User struct doesn't have a place to unmarshal these extra details.

#34 is possibly related, but in this API the extra details are on the top level response, not under user.identities.

Perhaps the User struct could have one more field with the complete API response in a map[string]interface{} ?

Expectation

When the User Raw JSON is like

{
    "active": true,
    "created_at": "2023-04-26T20:57:04.053Z",
    "email": "[email protected]",
    "email_verified": true,
    "family_name": "Example",
    "given_name": "User",
    "id": "https://login.salesforce.com/id/00D46000001EXAMPLE/0054o000002EXAMPLE",
    "identities": [
        {
            "provider": "salesforce",
            "user_id": "0054o000002EXAMPLE",
            "connection": "salesforce",
            "isSocial": true
        }
    ],
    "is_lightning_login_user": false,
    "language": "en_US",
    "last_modified_date": "2023-04-11T17:17:47Z",
    "locale": "en_US",
    "mobile_phone_verified": false,
    "name": "User Example",
    "nickname": "User",
    "organization_id": "00D46000001EXAMPLE",
    "picture": "https://example.file.force.com/profilephoto/005/F",
    "picture_thumbnail": "https://example.file.force.com/profilephoto/005/T",
    "status": {
        "created_date": null,
        "body": null
    },
    "timezone": "America/Phoenix",
    "updated_at": "2023-04-27T16:15:25.526Z",
    "urls": {
        "enterprise": "https://example.my.salesforce.com/services/Soap/c/{version}/00D46000EXAMPLE",
        "metadata": "https://example.my.salesforce.com/services/Soap/m/{version}/00D46000EXAMPLE",
        "partner": "https://example.my.salesforce.com/services/Soap/u/{version}/00D46000EXAMPLE",
        "rest": "https://example.my.salesforce.com/services/data/v{version}/",
        "sobjects": "https://example.my.salesforce.com/services/data/v{version}/sobjects/",
        "search": "https://example.my.salesforce.com/services/data/v{version}/search/",
        "query": "https://example.my.salesforce.com/services/data/v{version}/query/",
        "recent": "https://example.my.salesforce.com/services/data/v{version}/recent/",
        "tooling_soap": "https://example.my.salesforce.com/services/Soap/T/{version}/00D46000EXAMPLE",
        "tooling_rest": "https://example.my.salesforce.com/services/data/v{version}/tooling/",
        "profile": "https://example.my.salesforce.com/0054o000002EXAMPLE",
        "feeds": "https://example.my.salesforce.com/services/data/v{version}/chatter/feeds",
        "groups": "https://example.my.salesforce.com/services/data/v{version}/chatter/groups",
        "users": "https://example.my.salesforce.com/services/data/v{version}/chatter/users",
        "feed_items": "https://example.my.salesforce.com/services/data/v{version}/chatter/feed-items",
        "feed_elements": "https://example.my.salesforce.com/services/data/v{version}/chatter/feed-elements",
        "custom_domain": "https://example.my.salesforce.com"
    },
    "user_id": "salesforce|0054o000002EXAMPLE",
    "user_type": "STANDARD",
    "username": "[email protected]",
    "utcOffset": -25200000,
    "last_ip": "2600:1700:9da3:c850:d424:b148:1f01:46d8",
    "last_login": "2023-04-27T16:15:25.522Z",
    "logins_count": 33,
    "blocked_for": [],
    "guardian_authenticators": []
}

A call to auth0.User.Read(profile.ID) will allow a client to get additional identity provider details like organization_id 00D46000001EXAMPLE

Reproduction

  1. Register or log in with a Salesforce connection
  2. See Salesforce identity provider data like organization_id 00D46000001EXAMPLE in API response from GET /users/:id call
  3. See no Salesforce identity provider data in the User struct from auth0.User.Read(profile.ID) call

Auth0 Go SDK version

main

Sorting

Checklist

Describe the problem you'd like to have solved

I'd like to sort Users as described here: https://auth0.com/docs/api/management/v2#!/Users/get_users

Describe the ideal solution

Having a func Sort(s string) RequestOption { ... } function similar to Query in management/management_request.go

Alternatives and current workarounds

No response

Additional context

No response

The payload passed from ImportUsers is json encoded by Management.NewRequest and the request fails

Checklist

  • I have looked into the README and have not found a suitable solution or answer.
  • I have looked into the documentation and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have upgraded to the latest version of this SDK and the issue still persists.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Description

The problem is happening with m.NewRequest in management.Request that ImportUsers is using at request time.
ImportUsers throws a request expecting multipart/form-data, but in m.NewRequest it does not work as expected and re-encodes the payload already completed in ImportUsers just like a normal json request. The request is then re-encoded like a normal json request.

This results in an empty body and failure.

Expectation

That a user is created in the connection specified by auth0 using ImportUsers().

Reproduction

func main() {
	m, _ := management.New(DOMAIN, management.WithClientCredentials(CLIENTID, CLIENTSECRET))

	user := map[string]interface{}{
		"email":          auth0.String(EMAIL),
		"password_hash":  auth0.String(HASH),
	}

	job := management.Job{
		ConnectionID:        auth0.String(CONNECTIONID),
		Upsert:              auth0.Bool(false),
		SendCompletionEmail: auth0.Bool(true),
		Users:               []map[string]interface{}{user},
	}
	
	_ = m.Job.ImportUsers(&job)
}

Auth0 Go SDK version

v0.13.0

Support returning member roles in `OrganizationManager.Members()`

Checklist

Describe the problem you'd like to have solved

Auth0 API recently added support for member roles in the organizations/get-members endpoint. This enables us to fetch all the organization members' roles all at once without risking hitting the rate limit.

Currently, go-auth0 unfortunately doesn't return roles in OrganizationMember, and therefore there is no way to take advantage of this new RBAC feature.

// ===== github.com/auth0/[email protected]/management/organization.go =====

// OrganizationMemberList is a list of OrganizationMembers.
type OrganizationMemberList struct {
	List
	Members []OrganizationMember `json:"members"`
}

// OrganizationMember holds member information for an Organization.
type OrganizationMember struct {
	UserID  *string `json:"user_id,omitempty"`
	Picture *string `json:"picture,omitempty"`
	Name    *string `json:"name,omitempty"`
	Email   *string `json:"email,omitempty"`
}

Describe the ideal solution

  • Add a new Roles []OrganizationMemberRole field to OrganizationMember
  • Optional: add a new boolean flag to Organization.Members() function to enable fetching of roles. Or simply ask users to use IncludeFields("roles")

Alternatives and current workarounds

No response

Additional context

No response

Organization's OrganizationInvitationList is not behaving as expected

Describe the problem

The listing operation for OrganizationInvitation is non-functioning. The API does not provide the total field which breaks the HasNext method.

What was the expected behavior?

The OrganizationInvitationList.HasNext should return true when there is actually a next page. The work around is to look at the number of elements returned, if it's equal to the page size, return true. I suspect that this is what auth0's UI is doing.

Reproduction

Force pagination to 1 element, create 2 invitations, expect OrganizationInvitationList.HasNext to return true, but it returns false.

Environment

version 0.6.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.