Add error code to unauthorized responses

This commit is contained in:
aftermath2
2023-04-01 12:00:00 +00:00
parent cb6a044256
commit adb59e192b
2 changed files with 10 additions and 3 deletions

View File

@ -93,6 +93,7 @@ ERRORS = {
7000: "Robot token SHA256 was provided in the header. However it is not a valid 39 or 40 characters Base91 string.",
7001: "On the first request to a RoboSats coordinator, you must provide as well a valid public and encrypted private PGP keys and a nostr pubkey",
7002: "Invalid keys: {bad_keys_context}",
7003: "Authentication credentials were not provided.",
}
def new_error(code: int, parameters: dict = None) -> dict:

View File

@ -7,6 +7,7 @@ from django.contrib.auth.models import AnonymousUser, User, update_last_login
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse
from rest_framework import status
from rest_framework.authtoken.models import Token
from api.errors import new_error
@ -76,7 +77,7 @@ class RobotTokenSHA256AuthenticationMiddleWare:
return response
if not is_valid_token(token_sha256_b91):
return JsonResponse(new_error(7000), status=400)
return JsonResponse(new_error(7001), status=status.HTTP_400_BAD_REQUEST)
# Check if it is an existing robot.
try:
@ -123,7 +124,7 @@ class RobotTokenSHA256AuthenticationMiddleWare:
encrypted_private_key = request.COOKIES.get("encrypted_private_key", "")
if not public_key or not encrypted_private_key or not nostr_pubkey:
return JsonResponse(new_error(7001), status=400)
return JsonResponse(new_error(7002), status=status.HTTP_400_BAD_REQUEST)
(
valid,
@ -132,7 +133,7 @@ class RobotTokenSHA256AuthenticationMiddleWare:
encrypted_private_key,
) = validate_pgp_keys(public_key, encrypted_private_key)
if not valid:
return JsonResponse(new_error(7002, {"bad_keys_context": bad_keys_context}), status=400)
return JsonResponse(new_error(7003, {"bad_keys_context": bad_keys_context}), status=status.HTTP_400_BAD_REQUEST)
# Hash the token_sha256, only 1 iteration.
# This is the second SHA256 of the user token, aka RoboSats ID
@ -166,6 +167,11 @@ class RobotTokenSHA256AuthenticationMiddleWare:
response = self.get_response(request)
return response
def process_template_response(self, request, response):
if response.status_code == status.HTTP_401_UNAUTHORIZED:
response.data = new_error(7003)
return response
# Authenticate WebSockets connections using DRF tokens