Files
no-copy-frontend/src/app/actions/auth.ts
T

686 lines
15 KiB
TypeScript
Raw Normal View History

2025-11-27 21:33:53 +07:00
'use server'
2026-01-12 14:16:34 +07:00
import { loginFormSchema, API_BASE_URL, getSignupFormSchema } from '@/app/actions/definitions';
2026-01-14 18:15:52 +07:00
import { createSession, deleteSession, getSessionData, updateSession } from '@/app/actions/session';
2025-12-02 17:46:12 +07:00
import { redirect } from 'next/navigation';
2026-02-13 19:17:10 +07:00
import { fetchINN } from '@/app/actions/action';
2026-03-23 12:45:05 +07:00
import { headers } from 'next/headers';
2025-12-02 17:46:12 +07:00
2025-11-27 21:33:53 +07:00
export async function logout() {
2025-12-02 17:11:53 +07:00
const token = await getSessionData('token');
2025-11-28 15:28:15 +07:00
try {
2025-12-05 16:25:23 +07:00
await fetch(`${API_BASE_URL}/v1/api/auth/logout`, {
2025-11-28 15:28:15 +07:00
method: 'POST',
headers: {
2026-01-28 18:53:08 +07:00
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${token}`,
2025-11-28 15:28:15 +07:00
}
});
} catch (error) {
throw error;
2026-01-12 13:39:35 +07:00
} finally {
await deleteSession();
2025-11-28 15:28:15 +07:00
}
2025-11-27 21:33:53 +07:00
}
export async function authorization(
2025-12-07 12:53:56 +07:00
state: {
previousState: {
email: string;
}
error: Record<string, string>
} | undefined,
2025-11-27 21:33:53 +07:00
formData: FormData,
) {
2025-12-07 12:53:56 +07:00
const email = formData.get('email') as string || '';
const password = formData.get('password');
2025-12-11 18:28:35 +07:00
/* для теста */
2026-01-28 18:53:08 +07:00
if (email === 'test' && password === 'test') {
await createSession('1111', 'test');
2025-12-11 18:28:35 +07:00
redirect('/pages/dashboard');
}
/* для теста */
2025-11-28 15:28:15 +07:00
const validatedFields = loginFormSchema.safeParse({
2025-12-07 12:53:56 +07:00
email,
password
2025-11-28 15:28:15 +07:00
})
if (!validatedFields.success) {
2025-12-07 12:53:56 +07:00
const errors: Record<string, string> = {}
JSON.parse(validatedFields.error.message).forEach((obj: {
message: string,
path: string
}) => {
if (errors[obj.path[0]]) {
errors[obj.path[0]] = `${errors[obj.path[0]]} ${obj.message}`;
} else {
errors[obj.path[0]] = obj.message;
}
});
return {
previousState: {
email
},
error: errors
};
2025-11-28 15:28:15 +07:00
}
2025-11-27 21:33:53 +07:00
try {
2025-11-28 15:28:15 +07:00
const { email, password } = validatedFields.data;
2025-12-12 14:29:00 +07:00
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
2025-11-28 15:28:15 +07:00
method: 'POST',
body: JSON.stringify({
2025-12-12 14:29:00 +07:00
version: 1,
msg_id: 20001,
message_body: {
email: email,
password: password
}
2025-11-28 15:28:15 +07:00
}),
headers: {
2026-01-28 18:53:08 +07:00
'Content-Type': 'application/json',
'Accept': 'application/json'
2025-11-28 15:28:15 +07:00
}
});
if (response.ok) {
let parsed = await response.json();
2026-02-05 12:52:34 +07:00
if (parsed.message_code === 0) {
2025-12-17 14:30:54 +07:00
await createSession(parsed.message_body.token, email);
} else {
throw (`${parsed.message_code}`);
}
2025-11-28 15:28:15 +07:00
} else {
2025-12-10 16:39:13 +07:00
throw ('request-ended-with-an-error');
2025-11-28 15:28:15 +07:00
}
2025-11-27 21:33:53 +07:00
} catch (error) {
2025-12-07 12:53:56 +07:00
const errors: Record<string, string> = {}
2025-12-17 14:30:54 +07:00
switch (error) {
case '2':
errors['server'] = 'password-does-not-match'
break;
case '4':
errors['server'] = 'email-not-found'
break;
default:
errors['server'] = 'request-ended-with-an-error'
break;
}
2025-12-07 12:53:56 +07:00
2025-11-27 21:33:53 +07:00
if (error) {
2025-12-07 12:53:56 +07:00
return {
previousState: {
email,
password
},
error: errors
};
2025-11-27 21:33:53 +07:00
}
throw error;
}
2025-11-28 15:28:15 +07:00
redirect('/pages/dashboard');
2025-11-27 21:33:53 +07:00
}
2025-12-22 13:02:39 +07:00
export type FormState = {
2025-12-07 12:53:56 +07:00
previousState: {
2026-02-13 19:17:10 +07:00
fullName?: string | undefined;
email?: string | undefined;
password?: string | undefined;
confirm_password?: string | undefined;
phone?: string | undefined;
companyName?: string | undefined;
agree?: string | undefined;
referralCode?: string | undefined;
inn?: string | undefined;
} | undefined,
2026-01-14 18:15:52 +07:00
mailConfirm?: boolean,
2026-01-23 17:33:48 +07:00
userId?: number,
2026-01-14 18:15:52 +07:00
error: Record<string, string> | null
2025-12-07 12:53:56 +07:00
};
2025-11-27 21:33:53 +07:00
export async function registration(
2025-12-07 12:53:56 +07:00
state: FormState | undefined,
2025-11-27 21:33:53 +07:00
formData: FormData,
2025-12-07 12:53:56 +07:00
): Promise<FormState> {
2026-03-23 12:45:05 +07:00
const headersList = await headers();
2026-01-29 21:34:02 +07:00
const accountType = formData.get('accountType') as 'b2b' | 'b2c';
2026-01-29 14:34:04 +07:00
2026-03-04 15:22:26 +07:00
/* вернуть в true когда проект выйдет из дева */
2026-03-25 12:17:33 +07:00
const mail_verified = false;
2025-12-19 16:11:58 +07:00
const fullName = formData.get('fullName') as string || '';
2025-12-07 12:53:56 +07:00
const email = formData.get('email') as string || '';
const password = formData.get('password') as string || '';
const confirm_password = formData.get('confirm_password') as string || '';
const phone = formData.get('phone') as string || '';
2025-12-19 16:11:58 +07:00
const companyName = formData.get('companyName') as string || '';
const agree = formData.get('agree') as string || '';
const referralCode = formData.get('referralCode') as string || '';
2026-02-13 19:17:10 +07:00
const inn = formData.get('inn') as string || '';
2025-12-07 12:53:56 +07:00
2026-03-23 12:45:05 +07:00
const forwardedFor = headersList.get('x-forwarded-for');
const realIp = headersList.get('x-real-ip');
const ip = forwardedFor?.split(',')[0] || realIp || 'unknown';
const userAgent = headersList.get('user-agent') || 'unknown';
2026-01-29 21:34:02 +07:00
const SignupFormSchema = await getSignupFormSchema(accountType);
2026-01-10 15:12:51 +07:00
const dataToValidate = {
2025-12-19 16:11:58 +07:00
fullName,
2025-12-07 12:53:56 +07:00
email,
phone: phone.replace(/[-\(\)\s]/g, ''),
2025-12-07 12:53:56 +07:00
password,
confirm_password,
agree,
2026-02-13 19:17:10 +07:00
...(accountType === 'b2b' && { companyName, inn })
2026-01-10 15:12:51 +07:00
};
2026-02-05 18:10:16 +07:00
const validatedFields = await SignupFormSchema.safeParse(dataToValidate);
2025-11-27 21:33:53 +07:00
2026-02-05 11:55:02 +07:00
console.log(`try to register ${accountType}`);
2026-02-13 19:17:10 +07:00
let confirmedCompanyName: boolean = true;
if (accountType === 'b2b') {
try {
const response = await fetchINN(inn);
confirmedCompanyName = response?.companyName ? true : false;
} catch (error) {
confirmedCompanyName = false;
}
}
if (!validatedFields.success || !confirmedCompanyName) {
2025-11-28 12:38:14 +07:00
const errors: Record<string, string> = {}
2026-02-13 19:17:10 +07:00
if (validatedFields?.error?.message) {
JSON?.parse(validatedFields?.error?.message).forEach((obj: {
message: string,
path: string
}) => {
if (errors[obj.path[0]]) {
errors[obj.path[0]] = `${errors[obj.path[0]]}&${obj.message}`;
} else {
errors[obj.path[0]] = obj.message;
}
});
}
if (!confirmedCompanyName) {
errors.inn = 'inn-invalid'
}
2025-11-28 12:38:14 +07:00
2025-12-07 12:53:56 +07:00
return {
previousState: {
2025-12-19 16:11:58 +07:00
fullName,
2025-12-07 12:53:56 +07:00
email,
password,
confirm_password,
phone,
2026-01-29 14:34:04 +07:00
agree,
...(referralCode !== '' && { referralCode }),
2026-02-13 19:17:10 +07:00
...(accountType === 'b2b' && { companyName, inn })
2025-12-07 12:53:56 +07:00
},
error: errors
};
2025-11-27 21:33:53 +07:00
}
try {
2025-12-19 16:11:58 +07:00
const { fullName, email, password, phone } = validatedFields.data;
2025-12-12 14:29:00 +07:00
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
2025-11-27 21:33:53 +07:00
method: 'POST',
2025-12-11 18:28:35 +07:00
body: JSON.stringify({
2025-12-12 14:29:00 +07:00
version: 1,
msg_id: 20002,
message_body: {
2025-12-19 16:11:58 +07:00
fullName: fullName,
2025-12-12 14:29:00 +07:00
email,
phone: phone,
password,
2026-01-29 17:01:00 +07:00
accountType,
mail_verified: mail_verified,
2026-03-25 12:17:33 +07:00
ip: ip,
user_agent: userAgent,
2026-02-13 19:17:10 +07:00
...(accountType === 'b2b' && { companyName: companyName, inn: inn }),
...(referralCode !== '' && { referralLink: referralCode })
2025-12-12 14:29:00 +07:00
}
2025-12-11 18:28:35 +07:00
}),
2025-11-27 21:33:53 +07:00
headers: {
2026-01-28 18:53:08 +07:00
'Content-Type': 'application/json',
'Accept': 'application/json'
2025-11-27 21:33:53 +07:00
}
});
2025-11-28 15:28:15 +07:00
2026-02-07 12:28:07 +07:00
console.log({
fullName: fullName,
email,
phone: phone,
password,
accountType,
2026-03-25 12:17:33 +07:00
ip: ip,
user_agent: userAgent,
2026-02-13 19:17:10 +07:00
...(accountType === 'b2b' && { companyName: companyName, inn: inn }),
...(referralCode !== '' && { referralLink: referralCode })
2026-02-07 12:28:07 +07:00
})
2025-11-28 15:28:15 +07:00
if (response.ok) {
2025-12-19 16:11:58 +07:00
let parsed = await response.json() as {
message_desc: string,
2026-03-25 12:17:33 +07:00
message_body: { token: string, userId: number, fieldErrors: string },
2026-02-05 12:52:34 +07:00
message_code: number
2025-12-19 16:11:58 +07:00
};
2026-01-23 17:33:48 +07:00
2026-02-05 12:52:34 +07:00
if (parsed.message_code === 0) {
2026-02-05 11:55:02 +07:00
console.log(`registration - ${accountType}`);
2026-02-05 12:17:52 +07:00
console.log({
fullName: fullName,
email,
phone: phone,
password,
accountType,
2026-02-13 19:23:34 +07:00
...(referralCode !== '' && { referralLink: referralCode }),
2026-02-13 19:17:10 +07:00
...(accountType === 'b2b' && { companyName: companyName, inn: inn })
2026-02-05 12:17:52 +07:00
});
2026-02-17 18:20:50 +07:00
if (mail_verified) {
return {
previousState: {
fullName,
email,
password,
confirm_password,
phone,
agree,
...(referralCode !== '' && { referralLink: referralCode }),
...(accountType === 'b2b' && { companyName: companyName, inn: inn })
},
mailConfirm: true,
userId: parsed.message_body.userId,
error: null
};
} else {
await createSession(parsed.message_body.token, email as string);
}
2026-02-17 18:20:50 +07:00
2025-12-17 14:30:54 +07:00
} else {
2025-12-19 16:11:58 +07:00
throw parsed;
2025-12-17 14:30:54 +07:00
}
2025-11-28 15:28:15 +07:00
} else {
throw (`${response.status}`);
2025-11-28 15:28:15 +07:00
}
2026-01-14 18:17:02 +07:00
2025-12-19 16:11:58 +07:00
} catch (error: unknown) {
2026-02-03 11:44:02 +07:00
const errors: Record<string, string> = {};
2025-11-27 21:33:53 +07:00
if (error) {
2025-12-19 16:11:58 +07:00
const typedError = error as any;
switch (typedError.message_code) {
case 1:
if (typedError.message_desc === 'Refferal link is not exist') {
errors['server'] = 'referral-link-is-not-exist'
break;
} else {
errors['server'] = 'email-or-already-registered'
break;
}
2025-12-19 16:11:58 +07:00
case 2:
2026-01-30 23:02:18 +07:00
if (typedError.message_body?.fieldErrors) {
typedError.message_body?.fieldErrors?.forEach((obj: {
code: string,
field: string
}) => {
if (errors[obj.field]) {
errors[obj.field] = `${errors[obj.field]}&${obj.code.replaceAll('.', '-')}`;
} else {
errors[obj.field] = obj.code.replaceAll('.', '-');
}
});
} else if (typedError.message_desc === 'Company already exists') {
errors['inn'] = 'company-already-registered'
2026-01-30 23:02:18 +07:00
} else {
errors['server'] = 'unknown-error'
}
2025-12-19 16:11:58 +07:00
break;
2025-12-17 14:30:54 +07:00
default:
errors['server'] = 'request-ended-with-an-error'
break;
}
2025-12-07 12:53:56 +07:00
return {
previousState: {
2025-12-19 16:11:58 +07:00
fullName,
2025-12-07 12:53:56 +07:00
email,
password,
confirm_password,
phone,
2025-12-19 16:11:58 +07:00
companyName,
2026-02-13 19:17:10 +07:00
agree,
inn
2025-12-07 12:53:56 +07:00
},
2026-01-23 17:33:48 +07:00
mailConfirm: false,
2025-12-07 12:53:56 +07:00
error: errors
};
2025-11-27 21:33:53 +07:00
}
2025-12-26 14:03:57 +07:00
2026-02-03 11:44:02 +07:00
return {
previousState: {
fullName,
email,
password,
confirm_password,
phone,
companyName,
2026-02-13 19:17:10 +07:00
agree,
inn
2026-02-03 11:44:02 +07:00
},
error: errors
};
2025-11-27 21:33:53 +07:00
}
2026-01-14 18:17:02 +07:00
redirect('/pages/dashboard');
2026-01-14 18:15:52 +07:00
/* console.log('/v2');
redirect('/v2'); */
2026-01-12 13:39:35 +07:00
}
export async function tokenLifeExtension() {
const token = await getSessionData('token');
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
headers: {
2026-01-28 18:53:08 +07:00
'Content-Type': 'application/json',
'Accept': 'application/json',
2026-01-12 13:39:35 +07:00
},
body: JSON.stringify({
version: 1,
msg_id: 20008,
message_body: {
token: token
}
}),
});
if (response.ok) {
const parsed = await response.json();
2026-01-20 16:53:11 +07:00
if (parsed.message_code === 0) {
await updateSession(parsed.message_body.token);
}
2026-01-12 13:39:35 +07:00
}
} catch (error) {
await deleteSession();
throw error;
}
2026-01-14 18:15:52 +07:00
}
2026-02-27 14:18:14 +07:00
export async function confirmEmail(userId: number, verifyToken: string) {
2026-01-14 18:15:52 +07:00
console.log('confirmEmail');
2026-01-23 17:33:48 +07:00
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
body: JSON.stringify({
version: 1,
msg_id: 20009,
message_body: {
resend: 0,
user_id: userId,
2026-02-27 14:18:14 +07:00
verify_token: verifyToken
2026-01-23 17:33:48 +07:00
}
}),
});
if (response.ok) {
const parsed = await response.json();
console.log(parsed);
if (parsed.message_code === 0) {
await createSession(parsed.message_body.token, parsed.message_body.email as string);
2026-02-27 14:18:14 +07:00
} else {
return {
success: false,
error: 'entered-code-is-incorrect'
};
2026-01-23 17:33:48 +07:00
}
2026-02-27 14:18:14 +07:00
} else {
return {
success: false,
error: 'server-error'
};
2026-01-23 17:33:48 +07:00
}
} catch (error) {
return {
2026-02-27 14:18:14 +07:00
success: false,
error: 'network-error'
};
2026-01-23 17:33:48 +07:00
}
redirect('/pages/dashboard');
}
export async function resendConfirmEmail(userId: number) {
console.log('resendConfirmEmail');
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
body: JSON.stringify({
version: 1,
msg_id: 20009,
message_body: {
resend: 1,
user_id: userId,
}
}),
});
if (response.ok) {
const parsed = await response.json();
console.log(parsed);
if (parsed.message_code === 0) {
return {
fine: true
}
}
}
} catch (error) {
return {
fine: false
}
}
2026-02-17 19:20:04 +07:00
}
export type FormStateConfirmPassword = {
previousState: {
email: string;
password: string;
confirm_password: string;
verifyToken: string;
},
error: Record<string, string> | null
};
export async function resetPassword(
state: any | undefined,
formData: FormData,
) {
const email = formData.get('email');
console.log('resetPassword');
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
version: 1,
msg_id: 20010,
message_body: {
email: email,
action: "resetPassword"
}
}),
});
if (response.ok) {
const parsed = await response.json();
console.log(parsed);
if (parsed.message_code === 0) {
} else {
throw 'error';
}
}
} catch (error) {
return {
error: error
};
}
console.log('redirect')
redirect(`/reset-password?email=${email}`);
}
export async function confirmPassword(
state: FormStateConfirmPassword | undefined,
formData: any,
): Promise<FormStateConfirmPassword | undefined> {
const email = formData.get('email');
const password = formData.get('password');
const confirm_password = formData.get('confirm_password');
const verifyToken = formData.get('verify-token');
console.log('confirmPassword');
const SignupFormSchema = await getSignupFormSchema('resetPassword');
const dataToValidate = {
password,
confirm_password
};
const validatedFields = SignupFormSchema.safeParse(dataToValidate);
if (!validatedFields.success) {
const errors: Record<string, string> = {}
JSON.parse(validatedFields.error.message).forEach((obj: {
message: string,
path: string
}) => {
if (errors[obj.path[0]]) {
errors[obj.path[0]] = `${errors[obj.path[0]]}&${obj.message}`;
} else {
errors[obj.path[0]] = obj.message;
}
});
return {
previousState: {
email,
password,
confirm_password,
verifyToken
},
error: errors
};
}
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
version: 1,
msg_id: 20010,
message_body: {
email: email,
password: password,
verifyToken: verifyToken,
action: "confirmVerification"
}
}),
});
if (response.ok) {
const parsed = await response.json();
console.log(parsed);
if (parsed.message_code === 0) {
await createSession(parsed.message_body.authToken, email as string);
} else {
throw parsed;
2026-02-17 19:20:04 +07:00
}
} else {
throw (`${response.status}`);
}
} catch (error: unknown) {
const errors: Record<string, string> = {};
if (error) {
const typedError = error as any;
switch (typedError.message_code) {
case 1:
errors['server'] = 'unknown-error'
break
case 2:
if (typedError.message_desc === 'Token not found or time expired') {
errors['server'] = 'token-not-found-or-time-expired'
} else {
errors['server'] = 'unknown-error'
}
break;
default:
errors['server'] = 'request-ended-with-an-error'
break;
}
2026-02-17 19:20:04 +07:00
return {
previousState: {
email,
password,
confirm_password,
verifyToken
},
error: errors
};
}
return {
previousState: {
email,
password,
confirm_password,
verifyToken
},
error: errors
};
2026-02-17 19:20:04 +07:00
}
redirect('/pages/dashboard');
2025-11-27 21:33:53 +07:00
}