Skip to content
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 55 additions & 55 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 2 additions & 3 deletions mesh/accountSettings/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from . import views as accountsettings_views

urlpatterns = [
path("displayTheme/<int:account_id>", accountsettings_views.display_theme, name="display_theme"),
path("", accountsettings_views.SettingsView.as_view(), name = "settings"),
path("<int:account_id>/", accountsettings_views.SettingsDetailView.as_view(), name = "specific_settings"),
path('', accountsettings_views.SettingsView.as_view(), name = 'settings'),
path('<int:account_id>/', accountsettings_views.SettingsDetailView.as_view(), name = 'specific_settings'),
]
50 changes: 36 additions & 14 deletions mesh/accountSettings/views.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
# Django
from django.http import JsonResponse, HttpResponse
from django.views import View
from django.core.serializers import serialize
from django.core.exceptions import ValidationError, ObjectDoesNotExist

# Libraries
import json

# Models
from .models import Settings, Account

# Utils
from ..utils.validate_data import validate_json_and_required_fields

def display_theme(request, account_id):
Expand Down Expand Up @@ -87,34 +93,50 @@ def post(self, request):
)

class SettingsDetailView(View):
valid_fields = ['isVerified', 'verificationToken', 'hasContentFilterEnabled', 'displayTheme', 'is2FAEnabled']

def get(self, request, account_id, *args, **kwargs):
"""
Handles GET requests when the client fetches for a specific account settings
"""
try:
fields = request.GET.get('fields')
if fields:
fields = [field for field in fields.split(',') if field in self.valid_fields]
else:
fields = self.valid_fields
if len(fields) == 0:
return JsonResponse({'error': 'Invalid fields'}, status=400)

Comment on lines +103 to +110

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just curious... wasn't the validate_json_and_required_fields made for this or is this one a special case that requires us to not use the util function?

@blu3eee blu3eee Aug 27, 2024

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tdlr: validate_json_and_required_fields was not made for this. the two use cases are different.

  • validate_json_and_required_fields is to validate the request body. It takes in a json object, check if the request body has the required fields for the action (i.e. creating account will need enough information) and returns an indicator saying if the request body is valid for the action.

  • The fields checking in this particular case is getting the fields param from the request, then parse it into an array and double-check it with valid fields to see if the requested fields are matched with return object available fields. (Kindof mimicking graphQL behavior in a sense)

    • For example, the account settings have these fields: twoFactorEnabled, theme, and notificationSetting. The fields in the request body will indicate how much information the backend is returning, in some cases, we only need partial information. So, instead of returning the whole accountSetting object from the database, we only return the requested fields. If in the request body, fields="theme,twoFactorEnabled", only those information is returned in the response.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay that makes sense, is there no need to split this into its own function as well or does this seem like it'd be a one-off operation?

settings = Settings.objects.get(accountID= account_id)
settings_detail = serialize('json', [settings])
settings_detail = { field: getattr(settings, field, None) for field in fields }
# Add accountID to the response data
settings_detail['accountID'] = account_id

return JsonResponse(settings_detail, safe = False, status=200)

except Settings.DoesNotExist:
return JsonResponse({'error': 'Settings for this account do not exist'}, status=404)
return JsonResponse({'error': 'Setting for account not found'}, status=404)

def patch(self, request, account_id):
"""
Handle PATCH requests to update a specific setting.
"""
try:
setting = Settings.objects.get(accountID=account_id)
data = json.loads(request.body)

for field, value in data.items():
if field in self.valid_fields:
setattr(setting, field, value)

# After updating, save the setting
setting.save()
return HttpResponse(status=204)
except Settings.DoesNotExist:
return JsonResponse({'error': 'Settings do not exist'}, status=404)

data = json.loads(request.body)
# Here, update the setting's attributes based on the data received
setting.isVerified = data.get('isVerified', setting.isVerified)
setting.verificationToken = data.get('verificationToken', setting.verificationToken)
setting.hasContentFilterEnabled = data.get('hasContentFilterEnabled', setting.hasContentFilterEnabled)
setting.displayTheme = data.get('displayTheme', setting.displayTheme)
setting.is2FAEnabled = data.get('is2FAEnabled', setting.is2FAEnabled)
# After updating, save the setting
setting.save()
return HttpResponse(status=204)
return JsonResponse({'error': 'Setting for account not found'}, status=404)
except json.JSONDecodeError:
return JsonResponse({"error": "Invalid JSON format."}, status=400)
except KeyError:
return JsonResponse({"error": "Invalid fields in the request."}, status=400)

18 changes: 11 additions & 7 deletions mesh/accounts/views.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
# Django
from django.http import JsonResponse, HttpResponse
from django.core.exceptions import ValidationError
from django.core.serializers import serialize
from .models import *
from django.views import View

# Libraries
import bcrypt
import os
import json

from django.views import View
# Models
from .models import *
from ..accountSettings.models import Settings

from .models import Account
# Utils
from ..utils.validate_data import validate_json_and_required_fields
from ..accountSettings.models import Settings
import json

from mesh.accounts.services import (
get_OTP_validity_service,
Expand Down Expand Up @@ -210,7 +214,7 @@ def delete(self, request, account_id):
account.delete()
return JsonResponse({'message': f'successfully deleted Account with account_id: {account_id}'}, status=204)

def check_password(request):
def check_password(request, *args, **kwargs):
"""
Handles a POST request to authenticate a user's credentials.

Expand Down Expand Up @@ -251,7 +255,7 @@ def check_password(request):
else:
return JsonResponse({"error": "Method not allowed"}, status=405)

def change_password(request):
def change_password(request, *args, **kwargs):
"""
Handles a PATCH request to change a user's password.

Expand Down
7 changes: 6 additions & 1 deletion mesh/auth/views.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
# in auth folder: views.py (auth.views)

import json
# Django
from django.http import JsonResponse, HttpResponseRedirect
from django.contrib.auth import login, logout
from django.views.decorators.http import require_POST,require_GET
from django.views.decorators.csrf import ensure_csrf_cookie

# Libraries
import json

# Models
from mesh.accounts.models import Account
from .backend import AccountAuthenticationBackend

Expand Down
5 changes: 5 additions & 0 deletions mesh/confirmation/views.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
# Django
from django.http import HttpResponse
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags

# Models
from ..accounts.models import Account
from ..accountSettings.models import Settings
from ..profiles.models import Profile

# Libraries
import secrets
import os
import time
Expand Down
15 changes: 9 additions & 6 deletions mesh/conversation/views.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
# mesh/conversation/views.py
from django.shortcuts import get_object_or_404

import json
from django.http import JsonResponse, HttpResponseBadRequest
# Django
from django.http import JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.views.decorators.http import require_GET
from django.views import View
from django.core.exceptions import ValidationError

# Libraries
import json

# Models
from .models import Conversation, Message, ConversationParticipant
from ..accounts.models import Account
from ..profiles.models import Profile

# Utils
from ..utils.validate_data import validate_json_and_required_fields
from django.core.exceptions import ValidationError

class ConversationsView(View):
def post(self, request):
Expand Down
3 changes: 1 addition & 2 deletions mesh/education/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,5 @@
path('', education_views.EducationView.as_view(), name="education"),

# GET /educations/:account_id/
path("<int:account_id>/", education_views.EducationsDetailView.as_view(),
name="user_educations")
path("<int:account_id>/", education_views.EducationsDetailView.as_view(), name="user_educations")
]
1 change: 0 additions & 1 deletion mesh/education/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
from mesh.exceptions.MissingRequiredFields import MissingRequiredFields
from mesh.exceptions.InvalidJsonFormat import InvalidJsonFormat


class EducationView(View):
def get(self, request, *args, **kwargs):
"""
Expand Down
2 changes: 1 addition & 1 deletion mesh/exampleapi/urls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.urls import path, include
from django.urls import path
from . import views as exampleapi_views

urlpatterns = [
Comment thread
blu3eee marked this conversation as resolved.
Expand Down
Loading