day-cohort-70 / Bangazon-API-BandyChamps

0 stars 0 forks source link

Updated Error Handling in `register.py` #51

Closed soyuz43 closed 1 month ago

soyuz43 commented 1 month ago

Pull Request Title: Enhance Registration Endpoint with Robust Error Handling and Optimized Structure

Repository: Bangazon-API-BandyChamps

Branch Name: fix-register-error-handling

Description:

This pull request significantly enhances the registration endpoint by integrating robust error handling mechanisms and optimizing the function's structural organization. This ensures that user registration is reliable, comprehensible, and efficient.

Related Issue

Changes

Requests / Responses

If this PR contains code that defines a new request/response or modifies an existing one, please find the JSON representations detailed below.

Request

POST /register Creates a new user with the provided credentials and additional information.

{
    "username": "johndoe",
    "password": "password123",
    "first_name": "John",
    "last_name": "Doe",
    "email": "johndoe@example.com",
    "address": "123 Main St",
    "phone_number": "555-555-5555"
}

Response

HTTP/1.1 201 Created

{
    "token": "7ec4de87c7f9902d1d9ebe5ab9b67ba8f639625a",
    "id": 30
}

Testing

Instructions for validating the code changes:

Code Changes:

bangazonapi/views/register.py:

import json
from django.http import HttpResponse, HttpResponseNotAllowed
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
from rest_framework.authtoken.models import Token
from bangazonapi.models import Customer

@csrf_exempt
def login_user(request):
    """Handles the authentication of a user

    Method arguments:
    request -- The full HTTP request object
    """
    body = request.body.decode("utf-8")
    req_body = json.loads(body)

    if request.method == "POST":
        name = req_body["username"]
        pass_word = req_body["password"]
        authenticated_user = authenticate(username=name, password=pass_word)

        if authenticated_user is not None:
            token = Token.objects.get(user=authenticated_user)
            data = json.dumps({"valid": True, "token": token.key, "id": authenticated_user.id})
            return HttpResponse(data, content_type="application/json")

        else:
            data = json.dumps({"valid": False})
            return HttpResponse(data, content_type="application/json")

    return HttpResponseNotAllowed(permitted_methods=["POST"])

@csrf_exempt
def register_user(request):
    """Handles the creation of a new user for authentication

    Method arguments:
    request -- The full HTTP request object
    """
    try:
        req_body = json.loads(request.body.decode())
    except json.JSONDecodeError as e:
        return HttpResponse(
            json.dumps({"error": "Invalid JSON format"}),
            content_type="application/json",
            status=status.HTTP_400_BAD_REQUEST,
        )

    try:
        new_user = User.objects.create_user(
            username=req_body["username"],
            password=req_body["password"],
            first_name=req_body["first_name"],
            last_name=req_body["last_name"],
            email=req_body["email"],
        )

        customer = Customer.objects.create(
            phone_number=req_body["phone_number"],
            address=req_body["address"],
            user=new_user,
        )
        customer.save()

        token = Token.objects.create(user=new_user)

        data = json.dumps({"token": token.key, "id": new_user.id})
        return HttpResponse(
            data, content_type="application/json", status=status.HTTP_201_CREATED
        )
    except Exception as e:
        return HttpResponse(
            json.dumps({"error": str(e)}),
            content_type="application/json",
            status=status.HTTP_500_INTERNAL_SERVER_ERROR,
        )
soyuz43 commented 1 month ago

This update is not needed right now and this PR has been closed without being merged