From 08f827267d18e56ba590166f157de57c2297c7e0 Mon Sep 17 00:00:00 2001 From: Tatiana Nikolaeva Date: Mon, 2 Jun 2025 18:23:14 +0500 Subject: [PATCH] fix registration --- SurveyFrontend/src/api/AnswerApi.ts | 5 ++- SurveyFrontend/src/api/AnswerVariantsApi.ts | 5 ++- SurveyFrontend/src/api/AuthApi.ts | 41 ++++++++++--------- SurveyFrontend/src/api/BaseApi.ts | 18 +++++--- SurveyFrontend/src/api/CompletionApi.ts | 5 ++- SurveyFrontend/src/api/QuestionApi.ts | 16 ++++---- SurveyFrontend/src/api/SurveyApi.ts | 15 ++++--- .../CompletingSurvey.module.css | 15 +++++++ .../CompletingSurvey/CompletingSurvey.tsx | 26 +++--------- .../QuestionsList/QuestionsList.module.css | 16 -------- .../QuestionsList/QuestionsList.tsx | 5 +-- .../components/RegisterForm/RegisterForm.tsx | 5 +-- 12 files changed, 84 insertions(+), 88 deletions(-) diff --git a/SurveyFrontend/src/api/AnswerApi.ts b/SurveyFrontend/src/api/AnswerApi.ts index adeef06..26bbec5 100644 --- a/SurveyFrontend/src/api/AnswerApi.ts +++ b/SurveyFrontend/src/api/AnswerApi.ts @@ -1,4 +1,4 @@ -import {BASE_URL, createRequestConfig, handleResponse} from "./BaseApi.ts"; +import {BASE_URL, createRequestConfig, handleResponse, handleUnauthorizedError} from "./BaseApi.ts"; export const getAnswer = async (id: number) => { const token = localStorage.getItem("token"); @@ -13,6 +13,7 @@ export const getAnswer = async (id: number) => { return await handleResponse(response) } catch (error) { + handleUnauthorizedError(error); console.error(`error when receiving the response: ${error}`); throw error; } @@ -28,9 +29,11 @@ export const getCompletionsAnswer = async (id: number) => { const response = await fetch(`${BASE_URL}/questions/${id}/answers`, { ...createRequestConfig('GET'), }) + return await handleResponse(response) } catch (error) { + handleUnauthorizedError(error); console.error(`error when receiving the selected response: ${error}`); throw error; } diff --git a/SurveyFrontend/src/api/AnswerVariantsApi.ts b/SurveyFrontend/src/api/AnswerVariantsApi.ts index e09e84c..5ba5a72 100644 --- a/SurveyFrontend/src/api/AnswerVariantsApi.ts +++ b/SurveyFrontend/src/api/AnswerVariantsApi.ts @@ -1,4 +1,4 @@ -import {BASE_URL, createRequestConfig, handleResponse} from "./BaseApi.ts"; +import {BASE_URL, createRequestConfig, handleResponse, handleUnauthorizedError} from "./BaseApi.ts"; export interface INewAnswer{ text: string; @@ -42,6 +42,7 @@ export const addNewAnswerVariant = async (surveyId: number, questionId: number, return await handleResponse(response) } catch(err){ + handleUnauthorizedError(err); console.error(`Error adding a new response option: ${err}`); throw err; } @@ -67,6 +68,7 @@ export const updateAnswerVariant = async (id: number, answer: INewAnswer): Promi return await handleResponse(response) } catch(err){ + handleUnauthorizedError(err); console.error(`Error updating the response option: ${err}`); throw err; } @@ -88,6 +90,7 @@ export const deleteAnswerVariant = async (id: number) => { return responseData; } catch(err){ + handleUnauthorizedError(err); console.error(`Error deleting a answer: ${err}`); throw err; } diff --git a/SurveyFrontend/src/api/AuthApi.ts b/SurveyFrontend/src/api/AuthApi.ts index 6347d46..c8f7b4e 100644 --- a/SurveyFrontend/src/api/AuthApi.ts +++ b/SurveyFrontend/src/api/AuthApi.ts @@ -1,4 +1,4 @@ -import {BASE_URL, createRequestConfig, handleResponse} from "./BaseApi.ts"; +import {BASE_URL, createRequestConfig, handleResponse, handleUnauthorizedError} from "./BaseApi.ts"; interface IAuthData{ email: string; @@ -26,12 +26,6 @@ export const getCurrentUser = async () => { } }); - if (response.status === 401) { - localStorage.removeItem("token"); - localStorage.removeItem("user"); - throw new Error("Сессия истекла. Пожалуйста, войдите снова."); - } - if (!response.ok) { throw new Error(`Ошибка сервера: ${response.status}`); } @@ -40,33 +34,38 @@ export const getCurrentUser = async () => { localStorage.setItem("user", JSON.stringify(userData)); return userData; } catch (error) { + handleUnauthorizedError(error); console.error("Ошибка при получении данных пользователя:", error); throw error; } }; export const registerUser = async (data: IRegistrationData) => { - try{ + try { const response = await fetch(`${BASE_URL}/auth/register`, { - ...createRequestConfig('POST'), body: JSON.stringify(data), - }) - const responseData = await handleResponse(response); + ...createRequestConfig('POST'), + body: JSON.stringify(data), + }); - if (responseData.accessToken) { - localStorage.setItem("token", responseData.accessToken); - localStorage.setItem("user", JSON.stringify({ - firstName: data.firstName, - lastName: data.lastName, - email: data.email - })); + if (!response.ok) { + const errorData = await response.json(); + throw new Error(errorData.message || `Ошибка: ${response.status}`); + } + + const responseData = await handleResponse(response); + if (responseData.accessToken || responseData.token) { + localStorage.setItem("token", responseData.accessToken || responseData.token); + if (responseData.user) { + localStorage.setItem("user", JSON.stringify(responseData.user)); + } } return responseData; - } catch (error){ + } catch (error) { console.error("Registration error:", error); throw error; } -} +}; export const authUser = async (data: IAuthData) => { try { @@ -74,6 +73,7 @@ export const authUser = async (data: IAuthData) => { ...createRequestConfig('POST'), body: JSON.stringify(data), }); + const responseData = await handleResponse(response); const token = responseData.accessToken || responseData.token; @@ -89,6 +89,7 @@ export const authUser = async (data: IAuthData) => { return responseData; } catch (error) { + handleUnauthorizedError(error); console.error("Login error:", error); throw error; } diff --git a/SurveyFrontend/src/api/BaseApi.ts b/SurveyFrontend/src/api/BaseApi.ts index 6a85675..f1a537a 100644 --- a/SurveyFrontend/src/api/BaseApi.ts +++ b/SurveyFrontend/src/api/BaseApi.ts @@ -6,6 +6,13 @@ interface RequestConfig { body?: BodyInit | null; } +export const handleUnauthorizedError = (error: unknown) => { + if (error instanceof Error && error.message.includes('401')) { + window.location.href = '/login'; + console.log('Сессия истекла. Перенаправление на страницу входа.'); + } +}; + /** * Создаёт конфигурацию для fetch-запроса * @param method HTTP-метод (GET, POST, PUT, DELETE) @@ -37,14 +44,15 @@ const createRequestConfig = (method: string, isFormData: boolean = false): Reque * @returns Распарсенные данные или ошибку */ const handleResponse = async (response: Response) => { + if (response.status === 401) { + localStorage.removeItem("token"); + localStorage.removeItem("user"); + throw new Error("401: Unauthorized"); + } + const responseText = await response.text(); if (!responseText) { - if (response.status === 401) { - window.location.href = '/auth/login'; - throw new Error('Требуется авторизация'); - } - if (response.ok) { return null; } diff --git a/SurveyFrontend/src/api/CompletionApi.ts b/SurveyFrontend/src/api/CompletionApi.ts index c2e4ad9..8a51757 100644 --- a/SurveyFrontend/src/api/CompletionApi.ts +++ b/SurveyFrontend/src/api/CompletionApi.ts @@ -1,4 +1,4 @@ -import {BASE_URL, createRequestConfig, handleResponse} from "./BaseApi.ts"; +import {BASE_URL, createRequestConfig, handleResponse, handleUnauthorizedError} from "./BaseApi.ts"; export interface IAnswer{ questionId: number; answerText: string; @@ -16,6 +16,7 @@ export const getAllCompletions = async (surveyId: number) => { return await handleResponse(response); } catch (error) { + handleUnauthorizedError(error); console.error(`Error when receiving all selected responses: ${error}`); throw error; } @@ -36,6 +37,7 @@ export const addNewCompletion = async (surveyId: number, answer: IAnswer) => { return await handleResponse(response) } catch (error) { + handleUnauthorizedError(error); console.error(`Error when adding a new survey passage: ${error}`); throw error; } @@ -54,6 +56,7 @@ export const getCompletionById = async (id: number) => { return await handleResponse(response); } catch (error) { + handleUnauthorizedError(error); console.error(`Error when receiving a completed survey by id: ${error}`); throw error; } diff --git a/SurveyFrontend/src/api/QuestionApi.ts b/SurveyFrontend/src/api/QuestionApi.ts index 92defc5..d16668c 100644 --- a/SurveyFrontend/src/api/QuestionApi.ts +++ b/SurveyFrontend/src/api/QuestionApi.ts @@ -1,4 +1,4 @@ -import {BASE_URL, createRequestConfig, handleResponse} from "./BaseApi.ts"; +import {BASE_URL, createRequestConfig, handleResponse, handleUnauthorizedError} from "./BaseApi.ts"; import {IAnswerVariant} from "./AnswerVariantsApi.ts"; export interface INewQuestion{ @@ -25,6 +25,7 @@ export const addNewQuestion = async (surveyId: number, question: INewQuestion) = }) return await handleResponse(response) } catch (error){ + handleUnauthorizedError(error); throw new Error(`Error when adding a new question: ${error}`); } } @@ -34,12 +35,10 @@ export const getListQuestions = async (surveyId: number): Promise = const response = await fetch(`${BASE_URL}/surveys/${surveyId}/questions`, { ...createRequestConfig('GET'), }) - if (response.status === 200) { - return await handleResponse(response); - } - throw new Error(`Ожидался код 200, получен ${response.status}`); + return await handleResponse(response); } catch(error){ + handleUnauthorizedError(error); console.error(`Error when receiving the list of questions: ${error}`); throw error; } @@ -59,12 +58,10 @@ export const updateQuestion = async (id: number, question: Partial questionType: question.questionType, }), }) - if (response.status === 200) { - return await handleResponse(response) - } - throw new Error(`Ожидался код 200, получен ${response.status}`) + return await handleResponse(response) } catch(error){ + handleUnauthorizedError(error); console.error(`Error when updating question: ${error}`); throw error; } @@ -86,6 +83,7 @@ export const deleteQuestion = async (id: number) => { } return responseData; } catch (error){ + handleUnauthorizedError(error); console.error(`Error deleting a question: ${error}`); throw error; } diff --git a/SurveyFrontend/src/api/SurveyApi.ts b/SurveyFrontend/src/api/SurveyApi.ts index 4c20c73..ad3baab 100644 --- a/SurveyFrontend/src/api/SurveyApi.ts +++ b/SurveyFrontend/src/api/SurveyApi.ts @@ -1,4 +1,4 @@ -import {BASE_URL, createRequestConfig, handleResponse} from "./BaseApi.ts"; +import {BASE_URL, createRequestConfig, handleResponse, handleUnauthorizedError} from "./BaseApi.ts"; export interface ISurvey { id: number; @@ -28,6 +28,7 @@ export const getMySurveys = async (): Promise => { }); return await handleResponse(response); } catch (error) { + handleUnauthorizedError(error); console.error("Error receiving surveys:", error); throw error; } @@ -43,6 +44,7 @@ export const getAllSurveys = async (): Promise => { }) return await handleResponse(response); } catch (error) { + handleUnauthorizedError(error); console.error("Error receiving surveys:", error); throw error; } @@ -68,12 +70,13 @@ export const postNewSurvey = async (survey: INewSurvey): Promise => { throw new Error(`Ошибка: ${response.status}`); } - const data = await response.json(); + const data = await handleResponse(response); if (!data.id) { throw new Error("Сервер не вернул ID опроса"); } return data; } catch (error) { + handleUnauthorizedError(error); console.error(`Error when adding a new survey: ${error}`); throw error; } @@ -90,6 +93,7 @@ export const getSurveyById = async (surveyId: number): Promise => { }) return await handleResponse(response); } catch (error){ + handleUnauthorizedError(error); console.error(`Error finding the survey by id: ${error}`); throw error; } @@ -115,6 +119,7 @@ export const deleteSurvey = async (surveyId: number) => { } return responseData; } catch (error){ + handleUnauthorizedError(error); console.error(`Error deleting a survey: ${error}`); throw error; } @@ -138,12 +143,10 @@ export const updateSurvey = async (surveyId: number, survey: Partial description: survey.description, }) }) - if (response.status === 200) { - return await handleResponse(response); - } - throw new Error(`Ожидался код 200, получен ${response.status}`); + return await handleResponse(response); } catch (error){ + handleUnauthorizedError(error); console.error(`Error updating survey: ${error}`); throw error; } diff --git a/SurveyFrontend/src/components/CompletingSurvey/CompletingSurvey.module.css b/SurveyFrontend/src/components/CompletingSurvey/CompletingSurvey.module.css index aa10c8d..e6922fe 100644 --- a/SurveyFrontend/src/components/CompletingSurvey/CompletingSurvey.module.css +++ b/SurveyFrontend/src/components/CompletingSurvey/CompletingSurvey.module.css @@ -4,4 +4,19 @@ max-width: 100vw; min-height: 100vh; padding: 34px 16%; +} + +.departur_button{ + display: block; + margin: 10px auto; + padding: 25px 50.5px; + border: none; + border-radius: 20px; + background-color: #3788D6; + color: white; + font-weight: 700; + font-size: 24px; + text-align: center; + box-shadow: 0 0 7.4px 0 rgba(154, 202, 247, 1); + box-sizing: border-box; } \ No newline at end of file diff --git a/SurveyFrontend/src/components/CompletingSurvey/CompletingSurvey.tsx b/SurveyFrontend/src/components/CompletingSurvey/CompletingSurvey.tsx index 0bf3150..67e61cf 100644 --- a/SurveyFrontend/src/components/CompletingSurvey/CompletingSurvey.tsx +++ b/SurveyFrontend/src/components/CompletingSurvey/CompletingSurvey.tsx @@ -7,34 +7,16 @@ import {getSurveyById, ISurvey} from "../../api/SurveyApi.ts"; import {getListQuestions} from "../../api/QuestionApi.ts"; import {getAnswerVariants, IAnswerVariant} from "../../api/AnswerVariantsApi.ts"; + + export const CompletingSurvey = () => { - // const [titleSurvey, setTitleSurvey] = useState("Название опроса"); - // const [descriptionSurvey, setDescriptionSurvey] = useState(""); - // const [questions, setQuestions] = useState([ - // { id: 1, text: 'Вопрос 1', questionType: 'SingleAnswerQuestion', answerVariants: [{ id: 1, text: 'Ответ 1' }, - // { id: 2, text: 'Ответ 1' }, { id: 3, text: 'Ответ 1' }]}, - // { id: 2, text: 'Вопрос 2', questionType: 'MultipleAnswerQuestion', answerVariants: [{ id: 1, text: 'Ответ 1' }, - // { id: 2, text: 'Ответ 1' }, { id: 3, text: 'Ответ 1' }]} - // ]); - - // const [questions, setQuestions] = useState([]); - // const [loading, setLoading] = useState(true); - // const [error, setError] = useState(null); - // - // const [description, setDescription] = useState(''); - // const [title, setTitle] = useState(''); - // - // const { survey, setSurvey } = useOutletContext<{ - // survey: ISurvey; - // setSurvey: (survey: ISurvey) => void; - // }>(); - const {surveyId} = useParams<{surveyId: string}>(); const [survey, setSurvey] = useState(null); const [questions, setQuestions] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); + useEffect(() => { const fetchSurveyData = async () => { try { @@ -73,6 +55,7 @@ export const CompletingSurvey = () => { if (error) return
{error}
; if (!survey) return
Опрос не найден
; + return (
{ questions={questions} setQuestions={setQuestions} /> +
) } diff --git a/SurveyFrontend/src/components/QuestionsList/QuestionsList.module.css b/SurveyFrontend/src/components/QuestionsList/QuestionsList.module.css index c75e0d5..e69de29 100644 --- a/SurveyFrontend/src/components/QuestionsList/QuestionsList.module.css +++ b/SurveyFrontend/src/components/QuestionsList/QuestionsList.module.css @@ -1,16 +0,0 @@ -/*QuestionsList.module.css*/ - -.departur_button{ - display: block; - margin: 10px auto; - padding: 25px 50.5px; - border: none; - border-radius: 20px; - background-color: #3788D6; - color: white; - font-weight: 700; - font-size: 24px; - text-align: center; - box-shadow: 0 0 7.4px 0 rgba(154, 202, 247, 1); - box-sizing: border-box; -} \ No newline at end of file diff --git a/SurveyFrontend/src/components/QuestionsList/QuestionsList.tsx b/SurveyFrontend/src/components/QuestionsList/QuestionsList.tsx index 24c6dc4..85e0e1c 100644 --- a/SurveyFrontend/src/components/QuestionsList/QuestionsList.tsx +++ b/SurveyFrontend/src/components/QuestionsList/QuestionsList.tsx @@ -3,7 +3,6 @@ import QuestionItem from "../QuestionItem/QuestionItem.tsx"; import AddQuestionButton from "../AddQuestionButton/AddQuestionButton.tsx"; import {addNewQuestion, deleteQuestion, getListQuestions} from "../../api/QuestionApi.ts"; import {addNewAnswerVariant} from "../../api/AnswerVariantsApi.ts"; -import styles from './QuestionsList.module.css' import {useRouteReadOnly} from "../../hooks/useRouteReadOnly.ts"; interface QuestionsListProps { @@ -127,9 +126,7 @@ const QuestionsList: React.FC = ({questions, setQuestions, s surveyId={surveyId} /> ))} - {!isReadOnly ? : ( - - )} + {!isReadOnly ? : ''} ); diff --git a/SurveyFrontend/src/components/RegisterForm/RegisterForm.tsx b/SurveyFrontend/src/components/RegisterForm/RegisterForm.tsx index f7163fc..ab73c54 100644 --- a/SurveyFrontend/src/components/RegisterForm/RegisterForm.tsx +++ b/SurveyFrontend/src/components/RegisterForm/RegisterForm.tsx @@ -38,10 +38,7 @@ const RegisterForm = () => { const responseData = await registerUser({username, firstName, lastName, email, password}); if (responseData && !responseData.error) { console.log('Регистрация успешна'); - localStorage.setItem("user", JSON.stringify({ - firstName, - lastName - })); + localStorage.setItem("user", JSON.stringify(responseData.user)); navigate('/my-surveys'); } else if (responseData.status === 409){