Skip to content

Commit 11e80d1

Browse files
authored
refactore: get the agreement statues from db instead of session (#552)
* style: fix the loading * chore: update the signatureIcon * chore: fix type * chore: release @petercatai/assistant@1.0.18 * refactore: get the agreement statues from db instead of session * chore: remove log * chore: fix ci * chore: fix test
1 parent 5f33065 commit 11e80d1

File tree

7 files changed

+108
-33
lines changed

7 files changed

+108
-33
lines changed

client/app/factory/edit/page.tsx

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import {
2626
useBotCreate,
2727
useBotEdit,
2828
} from '@/app/hooks/useBot';
29-
import { useAgreement } from '@/app/hooks/useAgreement';
29+
import { useAgreement, useAgreementStatus } from '@/app/hooks/useAgreement';
3030
import FullPageSkeleton from '@/components/FullPageSkeleton';
3131
import { isEmpty } from 'lodash';
3232
import { Chat } from '@petercatai/assistant';
@@ -64,6 +64,11 @@ export default function Edit() {
6464
const { language } = useGlobal();
6565
const { botProfile, setBotProfile } = useBot();
6666
const { user, status } = useUser();
67+
const {
68+
data: agreementStatus,
69+
isLoading: getAgreementStatusLoading,
70+
error: getAgreementStatusError,
71+
} = useAgreementStatus();
6772
const router = useRouter();
6873
const searchParams = useSearchParams();
6974
const id = searchParams.get('id');
@@ -103,15 +108,21 @@ export default function Edit() {
103108
}
104109
if (!user || user.id.startsWith('client|')) {
105110
router.push(`${apiDomain}/api/auth/login`);
106-
} else {
107-
if (!user?.agreement_accepted) {
108-
setAgreementModalIsOpen(true);
109-
} else {
110-
setAgreementModalIsOpen(false);
111-
}
112111
}
113112
}, [user, status]);
114113

114+
useEffect(() => {
115+
if (getAgreementStatusLoading) {
116+
return;
117+
}
118+
if (getAgreementStatusError) {
119+
setAgreementModalIsOpen(true);
120+
} else {
121+
const agreementAccepted = agreementStatus?.data?.agreement_accepted;
122+
setAgreementModalIsOpen(!agreementAccepted);
123+
}
124+
}, [agreementStatus, getAgreementStatusError, getAgreementStatusLoading]);
125+
115126
const {
116127
updateBot: onUpdateBot,
117128
isLoading: updateBotLoading,

client/app/hooks/useAgreement.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1-
import { useMutation } from '@tanstack/react-query';
2-
import { acceptAgreement } from '@/app/services/UserController';
1+
import { useMutation, useQuery } from '@tanstack/react-query';
2+
import {
3+
acceptAgreement,
4+
getAgreementStatus,
5+
} from '@/app/services/UserController';
36
export function useAgreement() {
47
const mutation = useMutation({
58
mutationFn: acceptAgreement,
@@ -13,3 +16,11 @@ export function useAgreement() {
1316
isSuccess: mutation.isSuccess,
1417
};
1518
}
19+
20+
export const useAgreementStatus = () => {
21+
return useQuery({
22+
queryKey: [`agreement`],
23+
queryFn: async () => getAgreementStatus(),
24+
retry: false,
25+
});
26+
};

client/app/services/UserController.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,13 @@ export async function acceptAgreement() {
2020
return response.data;
2121
}
2222

23+
export async function getAgreementStatus() {
24+
const response = await axios.get(`${apiDomain}/api/auth/agreement/status`, {
25+
withCredentials: true,
26+
});
27+
return response.data;
28+
}
29+
2330
export async function getAvailableLLMs() {
2431
const response = await axios.get(`${apiDomain}/api/user/llms`, {
2532
withCredentials: true,

server/auth/router.py

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1+
from core.dao.profilesDAO import ProfilesDAO
12
from fastapi import APIRouter, Request, HTTPException, status, Depends
23
from fastapi.responses import RedirectResponse, JSONResponse
34
import secrets
45
from petercat_utils import get_client, get_env_variable
56
from starlette.config import Config
67
from authlib.integrations.starlette_client import OAuth
7-
from typing import Annotated
8+
from typing import Annotated, Optional
89

910
from auth.get_user_info import generateAnonymousUser, getUserInfoByToken, get_user_id
1011

@@ -98,33 +99,33 @@ async def userinfo(request: Request):
9899
return { "data": data, "status": 200}
99100
return { "data": user, "status": 200}
100101

102+
@router.get("/agreement/status")
103+
async def get_agreement_status(user_id: Optional[str] = Depends(get_user_id)):
104+
if not user_id:
105+
raise HTTPException(status_code=401, detail="User not found")
106+
try:
107+
profiles_dao = ProfilesDAO()
108+
response = profiles_dao.get_agreement_status(user_id=user_id)
109+
if not response:
110+
raise HTTPException(status_code=404, detail="User does not exist, accept failed.")
111+
return {"success": True, "data": response}
112+
except Exception as e:
113+
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
114+
101115
@router.post("/accept/agreement", status_code=200)
102116
async def bot_generator(
103117
request: Request,
104118
user_id: Annotated[str | None, Depends(get_user_id)] = None,
105119
):
106120
if not user_id:
107-
return JSONResponse(
108-
content={
109-
"success": False,
110-
"errorMessage": "User not found",
111-
},
112-
status_code=401,
113-
)
121+
raise HTTPException(status_code=401, detail="User not found")
114122
try:
115-
supabase = get_client()
116-
response = supabase.table("profiles").update({"agreement_accepted": True}).match({"id": user_id}).execute()
117-
118-
if not response.data:
119-
return JSONResponse(
120-
content={
121-
"success": False,
122-
"errorMessage": "User does not exist, accept failed.",
123-
}
124-
)
125-
request.session['user'] = response.data[0]
126-
return JSONResponse(content={"success": True})
123+
profiles_dao = ProfilesDAO()
124+
response = profiles_dao.accept_agreement(user_id=user_id)
125+
if response:
126+
request.session['user'] = response
127+
return JSONResponse(content={"success": True})
128+
else:
129+
raise HTTPException(status_code=400, detail="User update failed")
127130
except Exception as e:
128-
return JSONResponse(
129-
content={"success": False, "errorMessage": str(e)}, status_code=500
130-
)
131+
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")

server/core/dao/profilesDAO.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from core.dao.BaseDAO import BaseDAO
2+
from supabase.client import Client
3+
4+
from core.models.profiles import Profiles
5+
from petercat_utils.db.client.supabase import get_client
6+
7+
class ProfilesDAO(BaseDAO):
8+
client: Client
9+
10+
def __init__(self):
11+
super().__init__()
12+
self.client = get_client()
13+
14+
def get_agreement_status(self, user_id: str):
15+
16+
resp = self.client.table("profiles")\
17+
.select("agreement_accepted") \
18+
.eq("id", user_id) \
19+
.execute()
20+
agreement_accepted = resp.data[0]
21+
return agreement_accepted
22+
23+
def accept_agreement(self, user_id: str):
24+
try:
25+
response = self.client.table("profiles").update({"agreement_accepted": True}).match({"id": user_id}).execute()
26+
27+
if not response.data:
28+
return False, {"message": "User does not exist, accept failed."}
29+
return response.data[0]
30+
except Exception as e:
31+
print("Error: ", e)
32+
return False, {"message": "Profile Update failed"}
33+

server/core/models/profiles.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from pydantic import BaseModel
2+
from datetime import datetime
3+
from typing import Optional
4+
5+
class Profiles(BaseModel):
6+
id: str
7+
created_at: datetime = datetime.now()
8+
nickname: Optional[str] = ""
9+
name: Optional[str] = ""
10+
picture: Optional[str] = ""
11+
sid: Optional[str] = ""
12+
sub: Optional[str] = ""
13+
agreement_accepted: Optional[bool] = False

server/github_app/router.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
get_installation_repositories,
2929
get_jwt,
3030
get_private_key,
31-
get_user_orgs,
3231
)
3332

3433
from petercat_utils import get_env_variable

0 commit comments

Comments
 (0)