2

I am looking to generate a django authtoken for a non user object. previously I had easily generated auth tokens for user objects like this

email = request.data.get('email')
user = User.objects.get(email=email)
Token.objects.create(user=user)

but if I am trying this for non user object it is not getting generated.

device_id = request.data.get('device_id')
tablet = Table.objects.get(device_id=device_id)
Token.objects.create(user=tablet)

Here Table is simple model holding various device_ids.

I just want to generate an auth token for each tablet like we do for each user.

ChrisM
  • 1,576
  • 6
  • 18
  • 29
Rishabh Pandey
  • 209
  • 1
  • 4
  • 16

1 Answers1

3

If you are linking devices to users, and need a "per device" token where a user has >1 device (e.g. desktop, tablet, phone, etc) that are logged in separately and where the tokens can be revoked, then look at the Knox App:

Django Knox (https://github.com/James1345/django-rest-knox)


Otherwise, authentication tokens are normally used to log in a user. If you don't have a user then they aren't much use as far as the standard infrastructure is concerned.

If you want something custom, then you'll have to write your own solution, which might include:

  • A custom middleware if:
    • you want/need to set request.device=, like request.user
    • you want a custom user object (below)
  • Decide if you want a "fake" user like DeviceUser
    • Implement the User interface (see AnonymousUser's example)
    • Has is_authenticated=True
    • Has permissions (?)
    • Has is_device_user=True so you can distinguish
  • Be really careful not to rely on request.user to have a user_id
  • Possibly a new Permission class (e.g. a new IsAuthenticated)

The main problem I see is with things that expect a non-anonymous User object (in request) to be a real user with a pk. If you are careful then this might not be too big an issue, but you'll need to start implementing to be sure how it affects you.

Andrew
  • 8,322
  • 2
  • 47
  • 70