From 9cb4b85af80904a1fd873173435dc86c1d646983 Mon Sep 17 00:00:00 2001 From: Taseen18 Date: Fri, 29 Mar 2024 23:10:47 +0000 Subject: [PATCH] bugs fixes successfully pulls user chats now. --- .../backend/__pycache__/urls.cpython-311.pyc | Bin 1251 -> 1334 bytes .../chat/__pycache__/__init__.cpython-311.pyc | Bin 0 -> 245 bytes .../__pycache__/db_service.cpython-311.pyc | Bin 0 -> 2599 bytes backend/chat/__pycache__/urls.cpython-311.pyc | Bin 0 -> 501 bytes .../chat/__pycache__/views.cpython-311.pyc | Bin 0 -> 2253 bytes backend/chat/authentication.py | 47 ++++++++++++ backend/chat/db_service.py | 16 ++-- .../__pycache__/db_service.cpython-311.pyc | Bin 2609 -> 2603 bytes web/src/App.js | 70 +++++++++--------- web/src/lib/helper/AuthContext.js | 26 +++++++ web/src/pages/Homepage.js | 4 +- web/src/pages/Login.js | 4 +- web/src/pages/Messenger.js | 52 +++++++++---- 13 files changed, 160 insertions(+), 59 deletions(-) create mode 100644 backend/chat/__pycache__/__init__.cpython-311.pyc create mode 100644 backend/chat/__pycache__/db_service.cpython-311.pyc create mode 100644 backend/chat/__pycache__/urls.cpython-311.pyc create mode 100644 backend/chat/__pycache__/views.cpython-311.pyc create mode 100644 backend/chat/authentication.py create mode 100644 web/src/lib/helper/AuthContext.js diff --git a/backend/backend/__pycache__/urls.cpython-311.pyc b/backend/backend/__pycache__/urls.cpython-311.pyc index d200b53482f18392472fae84e09559e1a86d8ddf..735dc33350bd102e7430f66a00bba872b30847bd 100644 GIT binary patch delta 149 zcmaFNxs6MGIWI340}y1Ju%{(5GcY^`abSQ0%J{rwqI$Uy6GJLX3OkTwP2pI^$iT3g zabkiPS2}YPM+#>!gC^I;6(^W@s#udV5=-=}IDypUEau;geUsBzay4(Ta5T7dh)+Q`9QKd`g#Gc|C7U=c6SIsh(rBcK2P delta 89 zcmdnS^_WwAIWI340}y<9&y;4t%)sy%#DM{JDC2X@MD=p6bfzed6!u^SO^%HhPB2Yg b#r&1Abn*h0T!9a)%=}CZ+#p!Q3)BJtU}qFW diff --git a/backend/chat/__pycache__/__init__.cpython-311.pyc b/backend/chat/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7dcc5fa2b76e12f74f517e5d05f172387a25b3ca GIT binary patch literal 245 zcmXv|I|{-;5ZyH>B8XQ=YvX{m*r;6;MJ%ksW;0?m$%ffYk;d8^cm(lWUO=!Atel9x z;(eQU?RGnY5xiQvTJJUeA%EuCVsjC(Sc|?~+ypf^KkM;*hK)tC;FLwoAxI)pRKeUt zNs9i|=rY6HSLA2E+X@0EivOt=igK~cTiqs+u*ieqZ>vHH60F+Dsf@*98x*Z?eS}&B2pb4u}C8U9-b->o~JyIr>m&n)`2qboP?Q8>u zDwUXo`m$;-@W>Ne)t5f<*gqkTEG4ppgf#78Z;^QG)6O+XAb_T6m8Kopzx#2HuaD3D zo#Xp!EOrfnbWaG&hde^R(?LVndgtVG=HhZ1w#N74Kaxlkw58j3D%G41ZxgX>6tV(9X~u8vhy_*fOm+4`(z$q7def2XxEs=V5@b$@dap$afF5qLIqS{4nX&^sZXL8%uIqO zAu#gaNiNJi_~JowJhd=Cb#62{{+Lh?;2XF+$@ttl-mvKsit^@}x?p2stBz)4Y^qb~ zC8CiHb=q1=XRtD6>G>>ttgY%+_KB9uW$=^HjFmS)VXNOvFHEVAu|||n)FjSg+rdG1 zT$v-*8rB^ZTE}uWav1akn`vi5UDEV*Y#OS*syV8$l!CW^pVskUZo`*Xu#>X$Ic*7? zsfU@gfuA&lb{wFHj-*acx>Fo&w$ZLVc~5tvaW5J#@$nO|LV7c<`{%Tcc?A49fcckA-F`FvXEtEPUa+Duza$1%K&^YYPd&UO7kp!#=$T33 z!kZXWVAsM8J?S`aYw)dJ0p~+W)M637WFY|W#TlQ=uI7AZzz;*4N*kLuC|8taD{mT# zW-FR9{cvv3=Kwbc0+newXKI-KSjlQ+9S7Dpo6A@m7!Uelqni+d?e#;Bwv@qs*v1)P zjnCrmd;$N6^}K`qP>!S_+jv8Bv;^l1d2j)I@x%2r6bZI-mT6;~hFeh-5`)&4^i`~{ zrvhtAKyn*qBXHY40RWF;iW`f2v3T*zW9jD4g=dAmaaW3aQoJH1%2MLDURN6Qq```G zuPohr)qnVvD~);5SVfvDOH-~i<4H5chev#5r~m2f_H1$XSdg~2YA6)yITB-~wmYua z=ZSqKv9BuK*vbDv=RS4CVNV<`iNjT?duNkK;K|igod<&bJyo4^}w^?w{ohw{EIhS0ieP#_@E zkkaHPSok4Yd~I?a`s95I9Ta4M%?_F|3e6ZLZ?2ox4`w|{g9IY)Qo~LPT@<=0^Z>vw zC|KwN==+hgth)tco7Oi-%z9==77O1S$WicdtY$d`@Q!5;@8JQ z`}2viaI1zQp{}ajy*u*D2x#SgPwubCYFSoaajtydlkZpLp|U)57iEm*sg^e&orI>Wdx!duM_= z@u4fmJuzMq|146gRj~Z*5xnd3Kmbo09D1z#Iy76?Qf)y{k z^^G`^wTyfQe@5uLsJHf0fEvdzOcf23uDYs7DYafTo@09VzO5l>F2c1a(^ErD=xJlx RYp4l#875Lgmm&DlzW^qq4(k8_ literal 0 HcmV?d00001 diff --git a/backend/chat/__pycache__/urls.cpython-311.pyc b/backend/chat/__pycache__/urls.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fd9752102f191e6e8cd86b26e925fcd335c141b GIT binary patch literal 501 zcmY*VJ4-_`6i)7=t=8&x7afX&*g*q=Q^iHa#fnlY*hSKtV;|lZNv?7g#KEDXoBzNE z`eSaPgWT20t>ETlV%x!!lbr86UvhGi=Td1FDO=vmpZ8V#)MRS*1bm+;@Q4^<*h4;U zVvLxGaMO1da z@R$_#LGE;@6xTED2_k=R&DB}GJ)k}uR&rU9^=Qxz*JJJpuIp#^Wf!gl*WG7%D$X>` zib_{ENZ^5ZMc+z8Klh{|fD0n200_uIx5X(>NG)u2Jt*&nZtO!K1#v_FmPU~Ww>w@K zGbIReTx%SVQ=q)OLF(XxP?a^@DDXYO|Ui>b5n&>1=_17~&UtiIf& WR&`)ihgNlD8Vkl`oGgU9XuL z6B0Ry1C>$ zBr9yosvPiPD`H30Xu!)>%#N$^fR9)STTvC@qh`!X+9@?WE*tI{v(lV+Gvu)+ z>(UBb`P;1?Hih2yFi4>eN$ilMP00-3l{)8qxiXy()P5NA(S@C-^sJ`s~H=(j}~u{KusU4AsYQz>elG5Qo=n z33}$R`6>oI!Id(bFHP#kWjIcWJ5#y}?*T1V=Y0_heL>kMydp>`aFX^wh;AS+)BE#a zBXe*m(v-5X3&Qi<-jz>Ra|4asz|xr4-Lo|MXF7Llv56wdoVUC0?%5`iyK({CIq7xx zE|32-?(IAHAa?Id??C^9V~qo!ZHRjhtX#WSY{tTSdzuK~B?|A%z2X4kI{ceL$;>bN z?%*H$fA0U)UR4Gg%Al(ZKF@x*l6$b<%^&`~=4OXiv%`(-u&WHe{wMuj6N%vHR(!5> zxtT+&N}-_?T%`cwojpH{-5OgO3+%Z4$KCviXGh%Z`PJ+7toL=Nxjm7^Df2V5Prnn`+Z-+B!&X z+k|!v$b5OKQ%m@(?(bN4gU&dF88t>pj1R}nNeyb_YT0PjBT)he)+ZZIg^}`PQHKv% z5h9B%O86_<3Q|Akf}`@ly@?)c#r_L&6h!_xpnm~0ML`fe)aQ1RhY~k}pN9^)o#dfU w+)nb)pxa3v+T(VThl*||dFY7yF7nWT+euBSSK!zAZd{ss8E9Vpk3NXOe}fB0rvLx| literal 0 HcmV?d00001 diff --git a/backend/chat/authentication.py b/backend/chat/authentication.py new file mode 100644 index 00000000..a3f4f0bb --- /dev/null +++ b/backend/chat/authentication.py @@ -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}') diff --git a/backend/chat/db_service.py b/backend/chat/db_service.py index e0827918..78005ad1 100644 --- a/backend/chat/db_service.py +++ b/backend/chat/db_service.py @@ -8,18 +8,16 @@ def get_supabase_client() -> Client: 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.get('error') is not None: - print("An error occurred checking the user type.", response['error']) - return None - - if not response.data: - print("User was not found in mhp table.") - #should check users table in the future - return "employee" + if response.data: + print("User found as a MHP.") + return "MHP" else: - return "mhp" + print("User not found as MHP, marked as employee.") + return "employee" def fetch_chats(user_id): client = get_supabase_client() diff --git a/backend/to_do_list/__pycache__/db_service.cpython-311.pyc b/backend/to_do_list/__pycache__/db_service.cpython-311.pyc index 4372510909a10eb8274692ad0f62471d2340b6b6..db8c8973e9d2bf8b9b0d4ba6c1dbaedfffb81f96 100644 GIT binary patch delta 250 zcmdlevRZ_9IWI340}#yk&6dWnkvEf>wMYoao!rQ*$0#*<1G9r(`bBQPE8Kq9xdSh8 z2VMw@y%3*rkvsJYcj|TS+)LcK7rFDVaOXF;+~DSK@Gjz;tjHv}*_@@FQAHAH%q{ke z#Nxz~lAtH4p)ET#*EbPy`W5lWRES7&Ru(=D4RO1rksO5gI^ZB|{M(h|L2eesS33 R=BJeAq}mnfOrFm<2>^s3K1=`r delta 222 zcmZ22vQdP0IWI340}u$WV@+e($eYQ`eT%cSIJGFgv@|niay7Faqx9re%nquV7r6tj za0guH4!*=4d?6(MLSouQ?({3%>DRgQFLCEz=}v0i6tdP zMRH(XZfbFHVtT43OOY&)UnDvC4y!Gr%4R7xJ|;%F$(kIp1|VHU3LpZcqeu}*XtEWl uf!OLGLI^}if(RuLp**>aLyl2%@>Gs{+|nQc6%e60xsFqcQFro8&Pf37{5aYG diff --git a/web/src/App.js b/web/src/App.js index dc29d18a..8d932aa2 100644 --- a/web/src/App.js +++ b/web/src/App.js @@ -1,6 +1,7 @@ -import React, { useState,useEffect } from 'react' +import React, { useState, useEffect } from 'react'; +import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; +import { AuthProvider } from './lib/helper/AuthContext'; import { SignUp, Login, Homepage} from './pages' -import {Routes, Route} from 'react-router-dom' import Resources from './pages/Resources' import Community from './pages/Community' import Chat from './pages/Chat' @@ -9,43 +10,46 @@ import About from './pages/About' import Exercise from './pages/Exercise' import Diet from './pages/Diet' import MentalHealth from './pages/MentalHealth' -import ChatPage from './pages/Messenger' +import Messenger from './pages/Messenger'; const App = () => { - - const [token, setToken] = useState(false) - - if(token){ - sessionStorage.setItem('token',JSON.stringify(token)) - } + const [token, setToken] = useState(null); useEffect(() => { - if(sessionStorage.getItem('token')){ - let data = JSON.parse(sessionStorage.getItem('token')) - setToken(data) + const storedToken = sessionStorage.getItem('token'); + if (storedToken) { + setToken(JSON.parse(storedToken)); + console.log("token found") } - }, []) - + }, []); - return ( -
- - }/> - } /> - {token?}/>:""} - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - + useEffect(() => { + if (token) { + sessionStorage.setItem('token', JSON.stringify(token)); + console.log("token set") + } + }, [token]); -
- ) + return ( +
+ + + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + +
+ ); } -export default App \ No newline at end of file +export default App; diff --git a/web/src/lib/helper/AuthContext.js b/web/src/lib/helper/AuthContext.js new file mode 100644 index 00000000..75187cef --- /dev/null +++ b/web/src/lib/helper/AuthContext.js @@ -0,0 +1,26 @@ +import React, { createContext, useContext, useState, useEffect } from "react"; + +const AuthContext = createContext(); + +export function AuthProvider({ children }) { + const [token, setToken] = useState(() => { + const storedToken = sessionStorage.getItem('token'); + return storedToken ? JSON.parse(storedToken) : null; + }); + + useEffect(() => { + if (token) { + sessionStorage.setItem('token', JSON.stringify(token)); + } + }, [token]); + + return ( + + {children} + + ); +} + +export function useAuth() { + return useContext(AuthContext); +} diff --git a/web/src/pages/Homepage.js b/web/src/pages/Homepage.js index f9e334e9..6ed93592 100644 --- a/web/src/pages/Homepage.js +++ b/web/src/pages/Homepage.js @@ -1,11 +1,13 @@ import React, {useState, useEffect, useCallback} from "react"; +import { useAuth } from "../lib/helper/AuthContext"; import { Link } from 'react-router-dom'; //import { supabase } from '../lib/helper/supabaseClient'; import '../css/Homepage.css' import Line from "../assets/images/Line.png" import Navbar from "../components/Navbar"; -function Homepage({ token }) { +function Homepage() { + const { token } = useAuth(); const [tasks, setTasks] = useState([]); const [isModalOpen, setIsModalOpen] = useState(false); // For modal visibility const [newTask, setNewTask] = useState({ title: '', description: '' }); diff --git a/web/src/pages/Login.js b/web/src/pages/Login.js index 77c987bc..6212704e 100644 --- a/web/src/pages/Login.js +++ b/web/src/pages/Login.js @@ -1,12 +1,14 @@ import React, {useState, useEffect, useRef} from "react"; +import { useAuth } from "../lib/helper/AuthContext"; import { supabase } from "../lib/helper/supabaseClient"; import { useNavigate } from "react-router-dom"; import HALO from "vanta/dist/vanta.halo.min.js"; import '../css/Login.css' -const Login = ({setToken}) => { +const Login = () => { let navigate = useNavigate() + const { setToken } = useAuth(); const [formData,setFormData] = useState({email:'',password:''}) const vantaRef = useRef(null); diff --git a/web/src/pages/Messenger.js b/web/src/pages/Messenger.js index 4bc84eb2..1c93ae32 100644 --- a/web/src/pages/Messenger.js +++ b/web/src/pages/Messenger.js @@ -1,31 +1,53 @@ import React, { useState, useEffect } from 'react'; +import { useAuth } from '../lib/helper/AuthContext'; import { Link } from 'react-router-dom'; -function ChatPage() { - const [messages, setMessages] = useState([]); // State to store messages +function Messenger() { + const { token } = useAuth(); + const [chats, setChats] = useState([]); + useEffect(() => { - // Fetch existing chats from Supabase and setMessages - }, []); + const fetchChats = async () => { + if (!token || !token.session.access_token) { + console.error('Token not available'); + return; + } + const response = await fetch('/chat/getChats/', { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${token.session.access_token}`, + }, + }); + const data = await response.json(); + if (data && data.chats) { + setChats(data.chats); + } else { + // Handle any errors or empty responses + console.error('Failed to fetch chats or no chats available'); + } + }; - const sendMessage = (content) => { - // Function to send a message. Implement sending message to Supabase here. - }; + fetchChats(); + }, [token]); return (
-

Chat with a Mental Health Professional

+

Chats with Mental Health Professionals

- {/* Display messages here */} - {messages.map((message) => ( -
{message.content}
+ {chats.map((chat, index) => ( +
+

Chat with: {chat.mhp_id}

+

Chat ID: {chat.chat_id}

+

Created At: {chat.created_at}

+ {/* You can add more details or interaction options like opening the chat */} +
))}
- - - Homepage + Back to Homepage
); } -export default ChatPage; \ No newline at end of file +export default Messenger;