def token_new(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username and password: user = authenticate(username=username, password=password) if user: if not getattr(user, 'is_active', True): return JsonResponseForbidden("User account is disabled.") data = { 'token': token_generator.make_token(user), 'user': user.pk, } return JsonResponse(data) else: return JsonResponseUnauthorized( "Unable to log you in, please try again.") else: return JsonResponseBadRequest( "Must include 'username' and 'password' as POST parameters.") else: return JsonResponseNotAllowed("Must access via a POST request.")
def token_new(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username and password: user = authenticate(username=username, password=password) if user: TOKEN_CHECK_ACTIVE_USER = getattr(settings, "TOKEN_CHECK_ACTIVE_USER", False) if TOKEN_CHECK_ACTIVE_USER and not user.is_active: return JsonResponseForbidden("User account is disabled.") data = { 'token': token_generator.make_token(user), 'user': user.pk, } return JsonResponse(data) else: return JsonResponseUnauthorized( "Unable to log you in, please try again.") else: return JsonError( "Must include 'username' and 'password' as POST parameters.") else: return JsonError("Must access via a POST request.")
def _wrapped_view(request, *args, **kwargs): basic_auth = request.META.get('HTTP_AUTHORIZATION') user = request.POST.get('user', request.GET.get('user')) token = request.POST.get('token', request.GET.get('token')) if not (user and token) and basic_auth: auth_method, auth_string = basic_auth.split(' ', 1) if auth_method.lower() == 'basic': auth_string = b64decode(auth_string.strip()) user, token = auth_string.decode().split(':', 1) if not (user and token): return JsonResponseUnauthorized("Must include 'user' and 'token' parameters with request.") user = authenticate(pk=user, token=token) if user: request.user = user return view_func(request, *args, **kwargs) return JsonResponseForbidden("Incorrect user and token pair.")
def token(request, token, user): if authenticate(pk=user, token=token) is not None: return JsonResponse({}) else: return JsonResponseUnauthorized("Token did not match user.")