Giter VIP home page Giter VIP logo

fusionauth-python-client's Introduction

FusionAuth Python Client semver 2.0.0 compliant

Intro

If you're integrating FusionAuth with a Python 3 application, this library will speed up your development time. Please also make sure to check our SDK Usage Suggestions page.

For additional information and documentation on FusionAuth refer to https://fusionauth.io.

Install

To install the FusionAuth Python Client package run:

pip install fusionauth-client

This library can be found on PyPI at https://pypi.org/project/fusionauth-client/.

Examples

Set Up

First, you have to make sure you have a running FusionAuth instance. If you don't have one already, the easiest way to install FusionAuth is via Docker, but there are other ways. By default, it'll be running on localhost:9011.

Then, you have to create an API Key in the admin UI to allow calling API endpoints.

You are now ready to use this library.

Create the Client

Include the package in your code by using the following statement.

from fusionauth.fusionauth_client import FusionAuthClient

Now you're ready to begin making requests to FusionAuth. You will need to supply an API key you created in FusionAuth, the following example assumes an API key of 6b87a398-39f2-4692-927b-13188a81a9a3.

client = FusionAuthClient('6b87a398-39f2-4692-927b-13188a81a9a3', 'http://localhost:9011')

Error Handling

After every request is made, you need to check for any errors and handle them. To avoid cluttering things up, we'll omit the error handling in the next examples, but you should do something like the following.

Create an Application

To create an Application, use the create_application() method.

data = {
    'application': {
        'name': 'ChangeBank'
    }
}

result = client.create_application(data)

# Handle errors as shown in the beginning of the Examples section

# Otherwise parse the successful response
print(result.success_response)

Check the API docs for this endpoint

Adding Roles to an Existing Application

To add roles to an Application, use create_application_role().

data = {
    'role': {
        'name': 'customer',
        'description': 'Default role for regular customers',
        'isDefault': 1
    }
}

result = client.create_application_role(
    application_id='5a89377e-a250-4b15-b766-377ecc9b9fc9',
    request=data
)

# Handle errors as shown in the beginning of the Examples section

# Otherwise parse the successful response
print(result.success_response)

Check the API docs for this endpoint

Retrieve Application Details

To fetch details about an Application, use retrieve_application().

result = client.retrieve_application(
    application_id='5a89377e-a250-4b15-b766-377ecc9b9fc9'
)
print(result.success_response)

Check the API docs for this endpoint

Delete an Application

To delete an Application, use delete_application().

client.delete_application(
    application_id='5a89377e-a250-4b15-b766-377ecc9b9fc9'
)

Check the API docs for this endpoint

Lock a User

To prevent a User from logging in, use deactivate_user().

client.deactivate_user(
    user_id='231b982c-9304-4642-9bac-492d6917f5aa'
)

Check the API docs for this endpoint

Registering a User

To register a User in an Application, use register().

The code below also adds a customer role and a custom appBackgroundColor property to the User Registration.

result = client.register(
    user_id='231b982c-9304-4642-9bac-492d6917f5aa',
    request={
        'registration': {
            'applicationId': '5a89377e-a250-4b15-b766-377ecc9b9fc9',
            'roles': [
                'customer'
            ],
            'data': {
                'appBackgroundColor': '#096324'
            }
        }
    }
)
print(result.success_response)

Check the API docs for this endpoint

Questions and support

If you find any bugs in this library, please open an issue. Note that changes to the FusionAuthClient class have to be done on the FusionAuth Client Builder repository, which is responsible for generating that file.

But if you have a question or support issue, we'd love to hear from you.

If you have a paid plan with support included, please open a ticket in your account portal. Learn more about paid plan here.

Otherwise, please post your question in the community forum.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/FusionAuth/fusionauth-python-client.

Note: if you want to change the FusionAuthClient class, you have to do it on the FusionAuth Client Builder repository, which is responsible for generating all client libraries we support.

License

This code is available as open source under the terms of the Apache v2.0 License.

Upgrade Policy

This library is built automatically to keep track of the FusionAuth API, and may also receive updates with bug fixes, security patches, tests, code samples, or documentation changes.

These releases may also update dependencies, language engines, and operating systems, as we'll follow the deprecation and sunsetting policies of the underlying technologies that it uses.

This means that after a dependency (e.g. language, framework, or operating system) is deprecated by its maintainer, this library will also be deprecated by us, and will eventually be updated to use a newer version.

fusionauth-python-client's People

Contributors

johnjeffers avatar matthew-altman avatar mooreds avatar robfusion avatar robotdan avatar sycured avatar trex avatar tyduptyler13 avatar vcampitelli avatar voidmain 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

Watchers

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

fusionauth-python-client's Issues

Package broken?

Hi,

This isn't a very useful issue sorry as I don't understand your build system, but, the package seems to be broken, both on PyPI and if I manually clone the repo and run setup.py

I managed to get it installing by moving the code around in src/ adjusting the setup.py and including requests as an install_requires but I didn't submit a pull request due to not understanding your larger build environment and guessing that would break it.

Cheers

Logout API does not revoke the access_token

Hi, I am using the python client to logout a user using this function logout(). After calling this function, the access_token remains invalid. I have tried this anonymous_client.logout_with_request() function but the results were same.

I have read these articles:
https://fusionauth.io/learn/expert-advice/tokens/revoking-jwts
https://fusionauth.io/learn/expert-advice/tokens/pros-and-cons-of-jwts
If I understood correctly, this is the intended behaviour but I can still achieve the desired behaviour using JWTManager. But I could not find JWTManager for the python client.

So, in summary, is there any way to invalidate access_token when a user logs out.

Versions
Fusionauth-client 1.31
FusionAuth 1.31

Function client_response.was_successful() return False instead of True

Hi.
With this code:
client_response = client.exchange_o_auth_code_for_access_token(authCode,redirectURL,applicationID,clientSecret)
the value of client_response.was_successful() is True with version 1.18.0, but with 1.19.0 the returned value is False.
In the last case the error_response was: <Response [401]>

Uri not working for urls ending with a backslash ?

Hi ! Trying to use the uri method, it seems to have some odd behavior when the url ends with a backslash. The method (link to code):

    def uri(self, uri):
        if self._url is None:
            return self
        if self._url.endswith('/') and uri.startswith('/'):
            self._url += uri[:1]
        elif self._url.endswith('/') and not uri.startswith('/'):
            self._url += "/" + uri
        else:
            self._url += uri
        return self
  • For self._url = "http://example.com/" & uri = "/example/path", the method returns "http://example.com//"
  • For self._url = "http://example.com/" & uri = "example/path", the method returns "http://example.com//example/path"

Is this intended for a particular reason / case ?

Documentation and/or test cases?

The documentation and/or test case coverage for this package is woefully lacking.

For example: I just took several hours of debugging, including stepping into this package code, to discover the correct format for the "request" parameter in the update_user(id,request) function (hint: you don't include the 'user' key).

Could you please add an example for each call or document the usage more carefully?

Logout API not working

Hi, I am using the python client to logout a user. Unfortunately, I am getting the following response from the server.

{
   "fieldErrors":{
      "global":[
         {
            "code":"[couldNotConvert]global",
            "message":"Invalid"
         }
      ]
   }
}

Here is my code:

token = serializer.get_cleaned_data()["refreshToken"]
print(token)
client_response = anonymous_client.logout(True, token)

if not client_response.was_successful():
    code = client_response.response.status_code
    raise UnKnownError(http_code_number=code)

return Response({"detail": "Successfully logged out."}, status=status.HTTP_200_OK)

Versions
Fusionauth-client 1.19.8
FusionAuth 1.19.8

search_users_by_ids does not work / does not follow your API spec

It looks like search_users_by_ids does not work / never worked?

Reading to your API specs, it requires a parameter for each id. https://fusionauth.io/docs/apis/users#search-for-users
What it does however is somehow expecting a list of user ids and then converting that list value to a boolean value instead of looping trough all the ids and appending paramteres.

It could be changed in that way; however as this is auto-generated, I don't really know how to do it properly:

    uri = fa_client(tenant_id).start().uri("/api/user/search")
    for id in ids:
        uri.url_parameter("ids", id)
    search_res = await uri.get().go()

Python types

Can types be added? There are a lot of data structures coming back from the fusionauth API. It would be really helpful if they were defined here.

Async Support

A lot of the examples and clients are based on rather old Python stylings.
Would be nice to have a python client that can work asynchronously.
Addtionally, documentation would be better moved into FastAPI for the following reasons:

  • Depends, Requests, Response, cookies, etc. look much more clean and less ambiguous than in Flask.
  • Doesn't require the boilerplate of django
  • Newer features such as async support which is pretty important in a language like python where synchronous code can block threads in a high-level (aka SLOW) language.

Use Python optional parameters

Thanks for all your work on this library!

Small suggestion, but I believe making use of Python's optional parameters would greatly improve the usability of this library.

For example, the exchange_user_credentials_for_access_token method has 4 optional parameters, but they still need to be specified.

If I just wanted to specify the scope it would look like:

client.exchange_user_credentials_for_access_token(
  username='username', 
  password='password', 
  client_id=None, 
  client_secret=None, 
  scope='scope', 
  user_code=None)

However, I would prefer to do:

client.exchange_user_credentials_for_access_token(
  username='username',  
  password='password', 
  scope='scope')

This can be accomplished by changing the method signature to specify None for the optional parameters:

def exchange_user_credentials_for_access_token(self, 
  username, 
  password, 
  client_id=None, 
  client_secret=None, 
  scope=None, 
  user_code=None):

Let me know what you think. I can definitely put a PR up for this change!

Bug, missing requirements

Not sure if this is a needed part. Commenting this part out makes it run okay, but hey, not sure what I'm missing. The documentation of the Python code is lacking on your website.

[2022-08-11 09:16:40,469] ERROR in app: Exception on /oauth-callback [GET]
Traceback (most recent call last):
File "/home/michael/git/fusionauth-example-python-flask/venv/lib/python3.8/site-packages/flask/app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "/home/michael/git/fusionauth-example-python-flask/venv/lib/python3.8/site-packages/flask/app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/michael/git/fusionauth-example-python-flask/venv/lib/python3.8/site-packages/flask/app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "/home/michael/git/fusionauth-example-python-flask/venv/lib/python3.8/site-packages/flask/app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "/home/michael/git/fusionauth-example-python-flask/app/views.py", line 75, in oauth_callback
if registrations is None or len(registrations) == 0 or not any(r["applicationId"] == client_id for r in requirements):
NameError: name 'requirements' is not defined

validate_jwt method using incorrect header

The validate_jwt method is passing an authorization header with _jwt as the token type, which is invalid as FusionAuth expects this to be JWT and thus always returns a 401 response. Replacing these here makes validation work (returns a 200 with the expected data).

This might be affecting other endpoints as well, as I see several other places where this pattern is used.

Some endpoints missing

Hi,
I might have understood the protocols wrong but I was looking for the introspect endpoint in the client with no luck. Why is it and some other endpoints missing? Are they not needed in backends perhaps?

Search identity providers API doesn't work as expected

Trying to search identity provider by its name:

 client.search_identity_providers({"search.name": "test"})

it returns all the identity providers instead of the one named "test".

Tried calling the API directly, same issue.

No version in Python package

>>> import fusionauth
>>> fusionauth.__version__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'fusionauth' has no attribute '__version__'

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.