w-funnel/src/hooks/auth/useAuth.ts
2025-10-07 00:44:57 +02:00

154 lines
4.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useCallback, useMemo, useState } from "react";
import { useSession } from "../session/useSession";
import { getClientTimezone } from "@/shared/utils/locales";
import { ICreateAuthorizeRequest } from "@/entities/user/types";
import { filterNullKeysOfObject } from "@/shared/utils/filter-object";
import { createAuthorization } from "@/entities/user/actions";
import { setAuthTokenToCookie } from "@/entities/user/serverActions";
// TODO
const locale = "en";
interface IUseAuthProps {
funnelId: string;
}
export const useAuth = ({ funnelId }: IUseAuthProps) => {
const { updateSession } = useSession({ funnelId });
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const getAllCookies = useCallback(() => {
const cookies: Record<string, string> = {};
document.cookie.split(";").forEach((cookie) => {
const [name, value] = cookie.trim().split("=");
if (name && value) {
cookies[name] = decodeURIComponent(value);
}
});
return cookies;
}, []);
const getAuthorizationPayload = useCallback(
(email: string): ICreateAuthorizeRequest => {
const timezone = getClientTimezone();
return filterNullKeysOfObject<ICreateAuthorizeRequest>({
timezone,
locale,
email,
// source: funnelId,
source: "aura.compatibility.v2",
// profile: {
// name: username || "",
// gender: EGender[gender as keyof typeof EGender] || null,
// birthdate: formatDate(`${birthdate} ${birthtime}`),
// birthplace: {
// address: birthPlace,
// },
// },
// partner: {
// name: partnerName,
// gender: EGender[partnerGender as keyof typeof EGender] || null,
// birthdate: formatDate(partnerBirthdate),
// birthplace: {
// address: partnerBirthPlace,
// },
// },
sign: true,
signDate: new Date().toISOString(),
// feature: feature.includes("black") ? "ios" : feature,
});
},
[
// birthPlace,
// birthdate,
// gender,
// locale,
// partnerBirthPlace,
// partnerBirthdate,
// partnerGender,
// partnerName,
// username,
// birthtime,
// checked,
// dateOfCheck,
]
);
const authorization = useCallback(
async (email: string) => {
try {
setIsLoading(true);
setError(null);
// Обновляем сессию с куки перед авторизацией
try {
const cookies = getAllCookies();
await updateSession({ cookies });
console.log(
"Session updated with cookies before authorization:",
cookies
);
} catch (sessionError) {
console.warn("Failed to update session with cookies:", sessionError);
// Продолжаем авторизацию даже если обновление сессии не удалось
}
const payload = getAuthorizationPayload(email);
const {
token,
// userId: userIdFromApi,
// generatingVideo,
// videoId,
// authCode,
} = await createAuthorization(payload);
await setAuthTokenToCookie(token);
// const { user: userMe } = await api.getMe({ token });
// const userId = userIdFromApi || userMe?._id;
// if (userId?.length) {
// dispatch(actions.userId.update({ userId }));
// metricService.userParams({
// hasPersonalVideo: generatingVideo || false,
// email: user?.email,
// UserID: userId,
// });
// metricService.setUserID(userId);
// }
// signUp(token, userMe, isAnonymous);
// setToken(token);
// dispatch(actions.userConfig.setAuthCode(authCode || ""));
// dispatch(
// actions.personalVideo.updateStatus({
// generatingVideo: generatingVideo || false,
// videoId: videoId || "",
// })
// );
// if (generatingVideo) {
// metricService.reachGoal(EGoals.ROSE_VIDEO_CREATION_START, [
// EMetrics.YANDEX,
// EMetrics.KLAVIYO,
// ]);
// }
// dispatch(actions.status.update("registred"));
} catch (error) {
setError((error as Error).message);
} finally {
setIsLoading(false);
}
},
[getAllCookies, getAuthorizationPayload, updateSession]
);
return useMemo(
() => ({
authorization,
isLoading,
error,
}),
[authorization, isLoading, error]
);
};