Skip to content

Commit

Permalink
30 prod generated content can be viewed and edited by anyone with the…
Browse files Browse the repository at this point in the history
… redis note (#35)

* fix(view-tc): no longer allows users to view other users temporary content

* fix(docker-compose): uncommented ngrok
  • Loading branch information
neilscallywag authored Apr 27, 2024
1 parent b197f4e commit 3c135cc
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,12 @@ def ViewAllNotes(self, request, context):
def ViewNotesByUserId(self, request, context):
response = view_notes_pb2.ViewAllNotesResponse()
try:
limit, offset, page, user_id, notesTitle = request.limit, request.offset, request.page, request.user_id, request.notesTitle
user_id = request.user_id # user_id is mandatory
notes_stub = notes_client.NotesClient().get_notes_stub()

notes_request = notes_pb2.RetrieveMultipleNotesByUserIdRequest()
notes_request.limit = limit
notes_request.offset = offset
notes_request.page = page
notes_request.userId = user_id
notes_request.notesTitle = notesTitle
notes_request.limit = request.limit if request.limit else 999

notes_response = notes_stub.RetrieveMultipleNotesByUserId(notes_request)

Expand All @@ -101,7 +98,7 @@ def ViewNotesByUserId(self, request, context):
grpc.StatusCode.INVALID_ARGUMENT,
e
)

def ViewSavedNotesByUserId(self, request, context):
response = view_notes_pb2.ViewAllNotesResponse()
try:
Expand Down
5 changes: 4 additions & 1 deletion backend/simple/notes/src/services/note_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,10 @@ def RetrieveMultipleNotesByUserId(self, request, context):
db = Database()
limit, offset, page, user_id, notesTitle = request.limit, request.offset, request.page, request.userId, request.notesTitle
if offset == 0 and page == 0:
raise ValueError('Offset and page cannot be 0 at the same time')
logger.error('Offset and Page are 0 at the same time. Reverting to default offset = 0 and page = 1')
offset = 0
page = 1
# raise ValueError('Offset and page cannot be 0 at the same time')
if offset == 0:
offset = (page - 1) * limit

Expand Down
59 changes: 57 additions & 2 deletions client/src/pages/notes/GeneratedContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
import { isFlashcardType } from "~shared/util";

import {
api,
commitTemporaryContents,
createTemporaryContent,
deleteTemporaryContent,
Expand All @@ -49,7 +50,7 @@ const GeneratedContent: React.FC = () => {
const toast = useToast();
const { noteId } = useParams<{ noteId: string }>();
const [topics, setTopics] = useState<Topic[]>([]);
const { authorization } = useAuth();
const { authorization, user } = useAuth();

const [GPTContent, setFlashcards] = useState<FlashcardType[]>([]);
const [MCQs, setMCQs] = useState<MultipleChoiceQuestion[]>([]); // Initialize state for MCQs
Expand All @@ -62,14 +63,55 @@ const GeneratedContent: React.FC = () => {
const intervalIdRef = useRef<ReturnType<typeof setInterval> | null>(null);
const filename = localStorage.getItem("filename") || "No file uploaded";
const [isLoading, setIsLoading] = useState(true);

const [userNotes, setUserNotes] = useState([]);
const [isAuthorized, setIsAuthorized] = useState(false);
const pulseAnimation = keyframes`
0% { opacity: 0.5; }
50% { opacity: 1; }
100% { opacity: 0.5; }
`;

useEffect(() => {
const checkAuthorization = async () => {
try {
const notes = await fetchUserNotes(user?.user_id);
setUserNotes(notes.notes);
userNotes;
isAuthorized;
const noteExists = notes.notes.some(
(note: any) => note.fileId === noteId,
);
if (!noteExists) {
toast({
title: "Unauthorized",
description: "You do not have access to this note.",
status: "error",
duration: 3000,
isClosable: true,
});
navigate("/generator"); // Redirect to an unauthorized page or any other route
} else {
setIsAuthorized(true);
}
} catch (error) {
toast({
title: "Error",
description: "Failed to fetch user notes.",
status: "error",
duration: 3000,
isClosable: true,
});
navigate("/generator"); // Redirect or handle errors
}
};

checkAuthorization();
}, [user?.user_id, noteId, navigate, toast]);

useEffect(() => {
// Call once to fetch immediately

const fetchTopics = async () => {
const fetchedTopics = await getTopics();
if (!fetchedTopics || fetchedTopics.length === 0) {
Expand Down Expand Up @@ -99,7 +141,20 @@ const GeneratedContent: React.FC = () => {

return () =>
clearInterval(intervalIdRef.current as ReturnType<typeof setInterval>); // Clean up on component unmount
}, [noteId, authorization]);
}, [noteId, authorization, isAuthorized]);

const fetchUserNotes = async (userId: any) => {
const response = await api.get(`/api/v1/notes/user/${userId}`, {
headers: {
Authorization: `Bearer ${authorization}`,
},
});
if (!response.data) {
throw new Error("Failed to fetch notes");
}
console.log(response);
return await response.data;
};

const handleGetTemporaryContents = async (
noteId: string | undefined,
Expand Down
7 changes: 3 additions & 4 deletions client/src/pages/notes/components/PreMCQ.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ interface PreMCQProps {
onDelete: (id: string) => void;
onUpdate?: (
id: string,
updatedMCQ: { question: string; options: MultipleChoiceQuestionOption[] }
updatedMCQ: { question: string; options: MultipleChoiceQuestionOption[] },
) => void;
}

Expand Down Expand Up @@ -67,14 +67,14 @@ const PreMCQ: React.FC<PreMCQProps> = ({

const handleOptionTextChange = (optionIndex: number, newText: string) => {
const updatedOptions = editOptions.map((option, index) =>
index === optionIndex ? { ...option, option: newText } : option
index === optionIndex ? { ...option, option: newText } : option,
);
setEditOptions(updatedOptions);
};

const handleCorrectnessToggle = (optionIndex: number, isCorrect: boolean) => {
const updatedOptions = editOptions.map((option, index) =>
index === optionIndex ? { ...option, is_correct: isCorrect } : option
index === optionIndex ? { ...option, is_correct: isCorrect } : option,
);
setEditOptions(updatedOptions);
};
Expand Down Expand Up @@ -278,7 +278,6 @@ const PreMCQ: React.FC<PreMCQProps> = ({
</Box>
</DragDropContext>
);

};

export default PreMCQ;
2 changes: 1 addition & 1 deletion client/src/pages/subscribe/Subscribe.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ const SubscribePage = () => {
variant={user?.is_paid ? "outline" : "solid"}
disabled={user?.is_paid}
isDisabled={user?.is_paid}
onClick={user?.is_paid ? () => { } : handleSubscribe}
onClick={user?.is_paid ? () => {} : handleSubscribe}
>
{user?.is_paid ? "You are on Pro Plan" : "Go Pro"}
</Button>
Expand Down
6 changes: 1 addition & 5 deletions client/src/pages/viewnotes/components/MCQ.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,7 @@ export default function MCQ({ question, options, multiple_answers }: MCQProps) {
onClick={() => toggleOption(option.option)}
variant="solid"
colorScheme="white"
bg={
selectedOptions.includes(option.option)
? "white"
: "blue.800"
}
bg={selectedOptions.includes(option.option) ? "white" : "blue.800"}
color={
selectedOptions.includes(option.option) ? "blue.800" : "white"
}
Expand Down

0 comments on commit 3c135cc

Please sign in to comment.