Giter Site home page Giter Site logo

eshaan7 / django-rest-durin Goto Github PK

View Code? Open in Web Editor NEW
40.0 3.0 15.0 191 KB

Token Authentication module for Django Rest Framework with different token configuration for API client.

Home Page: https://django-rest-durin.rtfd.io

License: MIT License

Shell 0.25% Python 99.75%
django drf drf-tokens tokenauthentication api-client django-rest-framework python hacktoberfest

django-rest-durin's Introduction

Django-Rest-Durin

django-rest-durin on pypi Build Status codecov CodeFactor Language grade: Python

Per API client token authentication Module for Django REST Framework.

The idea is to provide one library that does token auth for multiple Web/CLI/Mobile API clients (i.e. devices/user-agents) via one interface but allows different token configuration for each client.

Durin authentication is token based, similar to the TokenAuthentication built in to DRF. However, it adds some extra sauce:

  • Durin allows multiple tokens per user. But only one token each user per API client.
  • Each user token is associated with an API Client.
    • These API Clients are configurable via Django's Admin Interface.
    • Includes permission enforcing to allow only specific clients to make authenticated requests to certain APIViews or vice-a-versa.
    • Configure Rate-Throttling per User <-> Client pair.
  • Durin provides an option for a logged in user to remove all tokens that the server has - forcing them to re-authenticate for all API clients.
  • Durin tokens can be renewed to get a fresh expiry.
  • Durin provides a CachedTokenAuthentication backend as well which uses memoization for faster look ups.
  • Durin provides Session Management features. Refer to Session Management Views i.e.,
    • REST view for an authenticated user to get list of sessions (in context of django-rest-durin, this means AuthToken instances) and revoke a session. Useful for pages like "View active browser sessions".
    • REST view for an authenticated user to get/create/delete token against a pre-defined client. Useful for pages like "Get API key" where a user can get an API key to be able to interact directly with your project's RESTful API using cURL or a custom client.

More information can be found in the Documentation. I'd also recommend going through the example_project/ included in this repository.

Django Compatibility Matrix

PyPi versions - Python

If your project uses an older verison of Django or Django Rest Framework, you can choose an older version of this project.

This Project Python Version Django Version Django Rest Framework
0.1+ 3.5 - 3.10 2.2, 3.0, 3.1, 3.2, 4.0 3.7>=

Make sure to use at least DRF 3.10 when using Django 3.0 or newer.

Changelog / Releases

All releases should be listed in the releases tab on GitHub.

See CHANGELOG for a more detailed listing.

License

This project is published with the MIT License. See https://choosealicense.com/licenses/mit/ for more information about what this means.

Credits

Durin is inpired by the django-rest-knox and django-rest-multitokenauth libraries and adopts some learnings and code from both.

django-rest-durin's People

Contributors

caiofcas avatar deepsource-autofix[bot] avatar deepsourcebot avatar eshaan7 avatar lgtm-com[bot] avatar lovvskillz avatar mlodic 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

Watchers

 avatar  avatar  avatar

django-rest-durin's Issues

AuthTokenAdmin list_filter is causing performance problems (mostly timeouts)

Our app has ~50k User objects and even more Client objects, and currently, because of AuthTokenAdmin's list_filter, our app times out every time we access the AuthToken list page in Django admin (because the filter lists every single one of these User and Client objects as possible filters). Can AuthTokenAdmin's list_filter be removed?

Session management

I am using django-rest-durin in a closed-source project where I've extended it to add a sort-of "sessions management" feature.

  • REST view for an authenticated user to get list of sessions (in context of django-rest-durin, this means AuthToken instances), revoke session by ID. Useful for pages like "View active browser sessions".
  • REST views for an authenticated user to create/delete token against a pre-defined client. Useful for pages like "Get API key".

If and when I find the time, I'd really like to take that code, generalize it and make it part of this package.

Increase code coverage

At the moment, the durin/models.py is omitted from code coverage, I'd like to change this.

  • Include test cases for both models, AuthToken and Client.
  • Include test cases which could potentially invoke some weird behavior

Logout view, doesn't check if user is authenticated or not

Hello, first I want to say thanks for the library and well documentation,

If you POST request on Logout view without an authorization header, it returns 500 Internal server error that says:


File .../venv/lib/python3.8/site-packages/durin/views.py", line 172, in post
    request._auth.delete()
AttributeError: 'NoneType' object has no attribute 'delete'

I know it doesn't make sense that an unauthenticated user wants to log out, But shouldn't we check?

post method in Logout view can be:

def post(self, request, *args, **kwargs):
        if request._auth:
            request._auth.delete()
            user_logged_out.send(
                sender=request.user.__class__, request=request, user=request.user
            )
        return Response(None, status=status.HTTP_204_NO_CONTENT)

OR in my case I overwrite the LogoutView method and add permission_class:

from durin.views import LogoutView as DurinLogoutView

class LogoutView(DurinLogoutView):
    **permission_classes = [permissions.IsAuthenticated]**

The same happens in LogoutAllView except there can't find the user

File ".../venv/lib/python3.8/site-packages/durin/views.py", line 195, in post
    request.user.auth_token_set.all().delete()
AttributeError: 'AnonymousUser' object has no attribute 'auth_token_set'

Optimize user fetching in `TokenAuthentication`

From django-silk profiling,

        if not auth_token.user.is_active:

is causing a query like:

SELECT "api_user"."id",
       "api_user"."password",
       "api_user"."last_login",
       "api_user"."is_superuser",
       "api_user"."username",
       "api_user"."first_name",
       "api_user"."last_name",
       "api_user"."email",
       "api_user"."is_staff",
       "api_user"."is_active",
       "api_user"."date_joined"
FROM "api_user"
WHERE "api_user"."id" = 1
LIMIT 21

this can be potentially be optimized using select_related.

Ability to store metadata/settings as part of Client <-> User relationship

There can be use cases where developers wish to store settings/metadata about a user specific to a client. (For example, theme name, styling, avatar, display name, etc.)

Few initial implementation ideas:

  • Provide an abstract UserClient model with user_id and client_id fields that developers could subclass.
  • Provide an UserClientSettings model with user_id, client_id, metadata = JsonField fields that developers can directly use.

Model should provide a shortcut method:

def get_current(request: "rest_framework.request.Request") -> UserClient

More ideas welcome.

Setup/usage with Social Auth

Hi, was wondering if there are any additional setup required when authenticating a Google OAuth token? The header format is of the form Authorization: Token some_hash, but for some reason the response form calling an API afterwards returns {detail: Invalid token. }. Can this be caused if a default expiry and additional settings are not set? When not using 3rd party Oauth, the client logs in and is able to perform API calls with the token created by durin.

AuthTokenManager.get_or_create calls wrong create

Hi!
Thanks for the library, it really helped me solve my problem. But while implementing authorization via GraphQL I encountered the following problem: AuthToken.objects.get_or_create(user=user, client=auth_client) method does not work correctly.
Expected behavior: classic get_or_create
Real result: error NOT NULL constraint failed: durin_authtoken.expiry

A piece of code in which an error occurs:

login(request, user)
token, created = AuthToken.objects.get_or_create(user=user, client=auth_client)

If I wrap it in try-exept, everything works as it should.

try:
    token = AuthToken.objects.get(user=user, client=auth_client)
except AuthToken.DoesNotExist:
    token = AuthToken.objects.create(user=user, client=auth_client)

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.