518 lines
10 KiB
TypeScript
518 lines
10 KiB
TypeScript
'use server'
|
|
|
|
import { loginFormSchema, API_BASE_URL, getSignupFormSchema } from '@/app/actions/definitions';
|
|
import { createSession, deleteSession, getSessionData, updateSession } from '@/app/actions/session';
|
|
import { redirect } from 'next/navigation';
|
|
|
|
export async function logout() {
|
|
const token = await getSessionData('token');
|
|
|
|
try {
|
|
await fetch(`${API_BASE_URL}/v1/api/auth/logout`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json',
|
|
'Authorization': `Bearer ${token}`,
|
|
}
|
|
});
|
|
} catch (error) {
|
|
throw error;
|
|
} finally {
|
|
await deleteSession();
|
|
}
|
|
}
|
|
|
|
export async function authorization(
|
|
state: {
|
|
previousState: {
|
|
email: string;
|
|
}
|
|
error: Record<string, string>
|
|
} | undefined,
|
|
formData: FormData,
|
|
) {
|
|
const email = formData.get('email') as string || '';
|
|
const password = formData.get('password');
|
|
|
|
/* для теста */
|
|
if (email === 'test' && password === 'test') {
|
|
await createSession('1111', 'test');
|
|
redirect('/pages/dashboard');
|
|
}
|
|
/* для теста */
|
|
|
|
const validatedFields = loginFormSchema.safeParse({
|
|
email,
|
|
password
|
|
})
|
|
|
|
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
|
|
},
|
|
error: errors
|
|
};
|
|
}
|
|
|
|
try {
|
|
const { email, password } = validatedFields.data;
|
|
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
version: 1,
|
|
msg_id: 20001,
|
|
message_body: {
|
|
email: email,
|
|
password: password
|
|
}
|
|
}),
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json'
|
|
}
|
|
});
|
|
if (response.ok) {
|
|
let parsed = await response.json();
|
|
if (parsed.message_desc === 'Operation successful') {
|
|
await createSession(parsed.message_body.token, email);
|
|
} else {
|
|
throw (`${parsed.message_code}`);
|
|
}
|
|
} else {
|
|
throw ('request-ended-with-an-error');
|
|
}
|
|
|
|
} catch (error) {
|
|
const errors: Record<string, string> = {}
|
|
|
|
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;
|
|
}
|
|
|
|
if (error) {
|
|
return {
|
|
previousState: {
|
|
email,
|
|
password
|
|
},
|
|
error: errors
|
|
};
|
|
}
|
|
throw error;
|
|
}
|
|
|
|
redirect('/pages/dashboard');
|
|
}
|
|
|
|
export type FormState = {
|
|
previousState: {
|
|
fullName: string;
|
|
email: string;
|
|
password: string;
|
|
confirm_password: string;
|
|
phone: string;
|
|
companyName?: string;
|
|
agree: string;
|
|
},
|
|
mailConfirm?: boolean,
|
|
error: Record<string, string> | null
|
|
};
|
|
|
|
export async function registration(
|
|
state: FormState | undefined,
|
|
formData: FormData,
|
|
): Promise<FormState> {
|
|
const accountType = formData.get('accountType') as 'b2b' | 'b2c';
|
|
|
|
const fullName = formData.get('fullName') as string || '';
|
|
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 || '';
|
|
const companyName = formData.get('companyName') as string || '';
|
|
const agree = formData.get('agree') as string || '';
|
|
|
|
const SignupFormSchema = await getSignupFormSchema(accountType);
|
|
|
|
const dataToValidate = {
|
|
fullName,
|
|
email,
|
|
phone: phone.replace(/[-\(\)\s]/g, ''),
|
|
password,
|
|
confirm_password,
|
|
agree,
|
|
...(accountType === 'b2b' && { companyName })
|
|
};
|
|
|
|
const validatedFields = SignupFormSchema.safeParse(dataToValidate);
|
|
|
|
console.log(`account-type ${accountType}`)
|
|
|
|
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: {
|
|
fullName,
|
|
email,
|
|
password,
|
|
confirm_password,
|
|
phone,
|
|
agree,
|
|
...(accountType === 'b2b' && { companyName })
|
|
},
|
|
error: errors
|
|
};
|
|
}
|
|
|
|
/*
|
|
return {
|
|
previousState: {
|
|
fullName,
|
|
email,
|
|
password,
|
|
confirm_password,
|
|
phone,
|
|
agree,
|
|
...(accountType === 'b2b' && { companyName })
|
|
}
|
|
}; */
|
|
|
|
try {
|
|
const { fullName, email, password, phone } = validatedFields.data;
|
|
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
version: 1,
|
|
msg_id: 20002,
|
|
message_body: {
|
|
fullName: fullName,
|
|
email,
|
|
phone: phone,
|
|
password,
|
|
accountType,
|
|
...(accountType === 'b2b' && { companyName: companyName })
|
|
}
|
|
}),
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json'
|
|
}
|
|
});
|
|
|
|
if (response.ok) {
|
|
let parsed = await response.json() as {
|
|
message_desc: string,
|
|
message_body: { token: string },
|
|
message_code: string
|
|
};
|
|
|
|
if (parsed.message_desc === 'Operation successful') {
|
|
await createSession(parsed.message_body.token, email as string);
|
|
console.log('succes registration');
|
|
} else {
|
|
throw parsed;
|
|
}
|
|
} else {
|
|
throw (`${response.status}`);
|
|
}
|
|
|
|
/* return {
|
|
previousState: {
|
|
fullName,
|
|
email,
|
|
password,
|
|
confirm_password,
|
|
phone,
|
|
companyName,
|
|
agree
|
|
},
|
|
mailConfirm: true,
|
|
error: null
|
|
}; */
|
|
} catch (error: unknown) {
|
|
const errors: Record<string, string> = {};
|
|
if (error) {
|
|
const typedError = error as any;
|
|
|
|
switch (typedError.message_code) {
|
|
case 1:
|
|
errors['server'] = 'email-or-already-registered'
|
|
break;
|
|
|
|
case 2:
|
|
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 {
|
|
errors['server'] = 'unknown-error'
|
|
}
|
|
break;
|
|
|
|
default:
|
|
errors['server'] = 'request-ended-with-an-error'
|
|
break;
|
|
}
|
|
|
|
return {
|
|
previousState: {
|
|
fullName,
|
|
email,
|
|
password,
|
|
confirm_password,
|
|
phone,
|
|
companyName,
|
|
agree
|
|
},
|
|
error: errors
|
|
};
|
|
}
|
|
|
|
return {
|
|
previousState: {
|
|
fullName,
|
|
email,
|
|
password,
|
|
confirm_password,
|
|
phone,
|
|
companyName,
|
|
agree
|
|
},
|
|
error: errors
|
|
};
|
|
}
|
|
|
|
redirect('/pages/dashboard');
|
|
/* console.log('/v2');
|
|
redirect('/v2'); */
|
|
}
|
|
|
|
export async function tokenLifeExtension() {
|
|
const token = await getSessionData('token');
|
|
|
|
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: 20008,
|
|
message_body: {
|
|
token: token
|
|
}
|
|
}),
|
|
});
|
|
|
|
if (response.ok) {
|
|
const parsed = await response.json();
|
|
if (parsed.message_code === 0) {
|
|
await updateSession(parsed.message_body.token);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
await deleteSession();
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function confirmEmail(
|
|
state: any | undefined,
|
|
formData: any,
|
|
) {
|
|
console.log('confirmEmail');
|
|
const emailConfirm = formData.get('emailConfirm') as string || '';
|
|
console.log(emailConfirm);
|
|
}
|
|
|
|
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 type FormStateConfirmPassword = {
|
|
previousState: {
|
|
email: string;
|
|
password: string;
|
|
confirm_password: string;
|
|
verifyToken: string;
|
|
},
|
|
error: Record<string, string> | null
|
|
};
|
|
|
|
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.message_body;
|
|
}
|
|
} else {
|
|
throw (`${response.status}`);
|
|
}
|
|
} catch (error: unknown) {
|
|
const typedError = error as any;
|
|
const errors: Record<string, string> = {};
|
|
|
|
if (error) {
|
|
return {
|
|
previousState: {
|
|
email,
|
|
password,
|
|
confirm_password,
|
|
verifyToken
|
|
},
|
|
error: errors
|
|
};
|
|
}
|
|
throw error;
|
|
}
|
|
|
|
redirect('/pages/dashboard');
|
|
} |