Skip to content

Commit

Permalink
Merge branch 'main' into community
Browse files Browse the repository at this point in the history
  • Loading branch information
Taseen18 committed Apr 1, 2024
2 parents 3096327 + 2904923 commit 981ca44
Show file tree
Hide file tree
Showing 51 changed files with 591 additions and 48 deletions.
Binary file modified .DS_Store
Binary file not shown.
Empty file.
Binary file not shown.
Binary file not shown.
3 changes: 3 additions & 0 deletions backend/authentication/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions backend/authentication/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class AuthenticationConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'authentication'
47 changes: 47 additions & 0 deletions backend/authentication/authentication.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework import authentication, exceptions
import jwt

class JWTAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
auth_header = authentication.get_authorization_header(request).decode('utf-8')
if not auth_header or not auth_header.startswith('Bearer '):
print("No JWT token found in request headers")
return None

token = auth_header.split(' ')[1]
try:
payload = jwt.decode(token, settings.SUPABASE_SECRET_KEY, algorithms=['HS256'], audience='authenticated')
user_id = payload['sub']
email = payload.get('email', '')
first_name = payload.get('user_metadata', {}).get('first_name', '')
last_name = payload.get('user_metadata', {}).get('last_name', '')

# Check if the user exists and update/create accordingly
user, created = User.objects.get_or_create(username=user_id, defaults={
'first_name': first_name,
'last_name': last_name,
'email': email
})

# If the user was not created (i.e., it already exists), update its details
if not created:
user.first_name = first_name
user.last_name = last_name
user.email = email
user.save()

if created:
print("\nNew user authenticated and created")
else:
print("User authenticated")

return (user, token)

except jwt.ExpiredSignatureError:
raise exceptions.AuthenticationFailed('Token expired, login again')
except jwt.InvalidTokenError:
raise exceptions.AuthenticationFailed('Invalid token')
except Exception as e:
raise exceptions.AuthenticationFailed(f'Unexpected error during authentication: {e}')
Empty file.
3 changes: 3 additions & 0 deletions backend/authentication/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
3 changes: 3 additions & 0 deletions backend/authentication/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
3 changes: 3 additions & 0 deletions backend/authentication/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.shortcuts import render

# Create your views here.
Binary file removed backend/backend/__pycache__/settings.cpython-311.pyc
Binary file not shown.
Binary file removed backend/backend/__pycache__/urls.cpython-311.pyc
Binary file not shown.
2 changes: 1 addition & 1 deletion backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'to_do_list.authentication.JWTAuthentication',
'authentication.authentication.JWTAuthentication',
),
}

Expand Down
1 change: 1 addition & 0 deletions backend/backend/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@
urlpatterns = [
path('admin/', admin.site.urls),
path('to_do_list/', include('to_do_list.urls')),
path('chat/', include('chat.urls')),
path('community/', include('community.urls'))
]
Empty file added backend/chat/__init__.py
Empty file.
Binary file added backend/chat/__pycache__/__init__.cpython-311.pyc
Binary file not shown.
Binary file not shown.
Binary file added backend/chat/__pycache__/urls.cpython-311.pyc
Binary file not shown.
Binary file added backend/chat/__pycache__/views.cpython-311.pyc
Binary file not shown.
3 changes: 3 additions & 0 deletions backend/chat/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions backend/chat/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class ChatConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'chat'
48 changes: 48 additions & 0 deletions backend/chat/authentication.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#this file is a copy from the file in authentication app. this file is not needed but im too scared to remove it.
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework import authentication, exceptions
import jwt

class JWTAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
auth_header = authentication.get_authorization_header(request).decode('utf-8')
if not auth_header or not auth_header.startswith('Bearer '):
print("No JWT token found in request headers")
return None

token = auth_header.split(' ')[1]
try:
payload = jwt.decode(token, settings.SUPABASE_SECRET_KEY, algorithms=['HS256'], audience='authenticated')
user_id = payload['sub']
email = payload.get('email', '')
first_name = payload.get('user_metadata', {}).get('first_name', '')
last_name = payload.get('user_metadata', {}).get('last_name', '')

# Check if the user exists and update/create accordingly
user, created = User.objects.get_or_create(username=user_id, defaults={
'first_name': first_name,
'last_name': last_name,
'email': email
})

# If the user was not created (i.e., it already exists), update its details
if not created:
user.first_name = first_name
user.last_name = last_name
user.email = email
user.save()

if created:
print("\nNew user authenticated and created")
else:
print("User authenticated")

return (user, token)

except jwt.ExpiredSignatureError:
raise exceptions.AuthenticationFailed('Token expired, login again')
except jwt.InvalidTokenError:
raise exceptions.AuthenticationFailed('Invalid token')
except Exception as e:
raise exceptions.AuthenticationFailed(f'Unexpected error during authentication: {e}')
42 changes: 42 additions & 0 deletions backend/chat/db_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from supabase import create_client, Client
from django.conf import settings

def get_supabase_client() -> Client:
url: str = settings.SUPABASE_URL
key: str = settings.SUPABASE_KEY
return create_client(url, key)

def check_user_type(user_id):
client = get_supabase_client()
# Attempt to fetch the user from the 'mhp' table
response = client.table('mhp').select('*').eq('mhp_id', user_id).execute()
print(response)

if response.data:
print("User found as a MHP.")
return "mhp"
else:
print("User not found as MHP, marked as employee.")
return "employee"

def fetch_chats(user_id):
client = get_supabase_client()
user_type = check_user_type(user_id)

if user_type == "employee":
response = client.table('chats').select('*').eq('user_id', user_id).execute()
return response
elif user_type == "mhp":
response = client.table('chats').select('*').eq('mhp_id', user_id).execute()
return response
else:
response = client.table('chats').select('*').eq('user_id', user_id).execute()
print("user type unknown")
return response
return None

def fetch_messages(chat_id):
client = get_supabase_client()

response = client.table('messages').select('*').eq('chat_id', chat_id).execute()
return response
Empty file.
3 changes: 3 additions & 0 deletions backend/chat/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
3 changes: 3 additions & 0 deletions backend/chat/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
7 changes: 7 additions & 0 deletions backend/chat/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.urls import path
from .views import GetChats, GetMessages

urlpatterns = [
path('getChats/', GetChats.as_view(), name='get-chats'),
path('getMessages/', GetMessages.as_view(), name='get-messages'),
]
66 changes: 66 additions & 0 deletions backend/chat/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from django.http import JsonResponse
import json
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import get_object_or_404
from .db_service import fetch_chats, fetch_messages
from django.contrib.auth.models import User

class GetChats(APIView):
permission_classes = [IsAuthenticated]

def get(self, request):
user_id = request.user.username

try:
response = fetch_chats(user_id)
chats = []

if response.data:
for chat in response.data:
chats.append({
'chat_id': chat['chat_id'],
'created_at': chat['created_at'],
'user_id': chat['user_id'],
'mhp_id': chat['mhp_id'],
})

print(len(chats), "chats found")
return JsonResponse({'chats': chats}, safe=False)

except Exception as e:
print("Error fetching chats")
print(e)
return JsonResponse({'error': 'Failed to fetch chats'}, status=500)

class GetMessages(APIView):
permission_classes = [IsAuthenticated]

def get(self, request, *args, **kwargs):
user_id = request.user.username
chat_id = request.GET.get('chat_id', None)

try:
if chat_id is not None:
messages = []
response = fetch_messages(chat_id)
for message in response.data:
messages.append({
'message_id': message['message_id'],
'sent_at': message['sent_at'],
'sender_id': message['sender_id'],
'receiver_id': message['receiver_id'],
'content': message['content'],
'chat_id': message['chat_id'],
})

print(len(messages), "messages found")
return JsonResponse({'messages': messages}, safe=False)

except Exception as e:
print("Error fethcing messages")
print(e)
return JsonResponse({'error': 'Failed to fetch messages'}, status=500)

Binary file not shown.
Binary file not shown.
Binary file removed backend/to_do_list/__pycache__/urls.cpython-311.pyc
Binary file not shown.
Binary file not shown.
26 changes: 21 additions & 5 deletions backend/to_do_list/authentication.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# authentication.py in your Django app
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework import authentication, exceptions
Expand All @@ -15,11 +14,28 @@ def authenticate(self, request):
try:
payload = jwt.decode(token, settings.SUPABASE_SECRET_KEY, algorithms=['HS256'], audience='authenticated')
user_id = payload['sub']
user, created = User.objects.get_or_create(username=user_id, defaults={'first_name': 'SupabaseUser'})
email = payload.get('email', '')
first_name = payload.get('user_metadata', {}).get('first_name', '')
last_name = payload.get('user_metadata', {}).get('last_name', '')

# Check if the user exists and update/create accordingly
user, created = User.objects.get_or_create(username=user_id, defaults={
'first_name': first_name,
'last_name': last_name,
'email': email
})

# If the user was not created (i.e., it already exists), update its details
if not created:
user.first_name = first_name
user.last_name = last_name
user.email = email
user.save()

if created:
print("\nuser created")
print("\nNew user authenticated and created")
else:
print("\nuser authenticated")
print("User authenticated")

return (user, token)

Expand All @@ -28,4 +44,4 @@ def authenticate(self, request):
except jwt.InvalidTokenError:
raise exceptions.AuthenticationFailed('Invalid token')
except Exception as e:
raise exceptions.AuthenticationFailed('Unexpected error during authentication', e)
raise exceptions.AuthenticationFailed(f'Unexpected error during authentication: {e}')
20 changes: 18 additions & 2 deletions backend/to_do_list/db_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ def get_supabase_client() -> Client:
key: str = settings.SUPABASE_KEY
return create_client(url, key)

def fetch_user_tasks(user_uuid):
def fetch_user_tasks(user_id):
client = get_supabase_client()
data = client.table('to_do_list_tasks').select('*').eq('user_id', user_uuid).eq('completed', False).execute()
data = client.table('to_do_list_tasks').select('*').eq('user_id', user_id).eq('completed', False).execute()
return data

def mark_as_complete(task_id):
Expand All @@ -26,3 +26,19 @@ def mark_as_complete(task_id):
return error_message

return None # No errors, return None

def add_task(title, description, user_id):
client = get_supabase_client()
error_message = None
response = client.table('to_do_list_tasks').insert({
'title': title,
'description': description,
'user_id': user_id,
'completed': False
}).execute()

if not response.data:
error_message = "Failed to create task in supabase."
if hasattr(response, 'error') and response.error:
error_message = response.error.message
return error_message
4 changes: 2 additions & 2 deletions backend/to_do_list/urls.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@

from django.urls import path
from .views import TaskListCreate, TaskUpdate
from .views import TaskListCreate, TaskUpdate, TaskCreate

urlpatterns = [
path('tasks/', TaskListCreate.as_view(), name='task-list-create'),
path('tasks/update/<str:task_id>/', TaskUpdate.as_view(), name='task-update'),
path('tasks/create/', TaskCreate.as_view(), name='task-create'),
]
Loading

0 comments on commit 981ca44

Please sign in to comment.