jpulgarin/django-tokenapi

Validate user before accessing attributes

Closed this issue · 1 comments

ERROR Internal Server Error: /api/check
Traceback (most recent call last):
  File "/home/chillaranand/.virtualenvs/bar/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/home/chillaranand/.virtualenvs/bar/lib/python3.5/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "/home/chillaranand/.virtualenvs/bar/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/chillaranand/.virtualenvs/bar/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/chillaranand/.virtualenvs/bar/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/chillaranand/projects/foo/views.py", line 150, in check
    if token_generator.check_token(user, token) and user.is_active:
  File "/home/chillaranand/.virtualenvs/bar/lib/python3.5/site-packages/tokenapi/tokens.py", line 38, in check_token
    if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
  File "/home/chillaranand/.virtualenvs/bar/lib/python3.5/site-packages/tokenapi/tokens.py", line 54, in _make_token_with_timestamp
    value = (six.text_type(user.pk) + user.password + six.text_type(timestamp))
AttributeError: 'NoneType' object has no attribute 'pk'

Hey @ChillarAnand, this is working as expected. The check_token method expects a user with a primary key. You can see similar logic in Django's own check_token.

Is there a reason you're calling check_token on your own? The token_required decorator takes care of checking a user's token for you. If you want to check a token on your own you can add tokenapi.backend.TokenBackend to your AUTHENTICATION_BACKENDS and then check a user/token pair like so:

from django.contrib.auth import authenticate

if authenticate(pk=user.pk, token=token):
   # Correct user/token pair