1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
// register.ts
export const validate = (
username: string,
email: string,
password: string,
passwordConfirm: string,
) => {
const newErrors: Record<string, string> = {};
if (!username) newErrors.username = 'Введите никнейм';
else if (username.length < 3) newErrors.username = 'Минимум 3 символа.';
else if (username.length > 32) newErrors.username = 'Максимум 32 символа';
if (!email) newErrors.email = 'Введите email.';
else {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) newErrors.email = 'Некорректный email';
if (email.length > 254) newErrors.email = 'Слишком длинный email.';
}
if (!password) newErrors.password = 'Введите пароль.';
else if (password.length < 8)
newErrors.password = 'Необходимо минимум 8 символов.';
else {
const hasLetter = /[A-Za-z]/.test(password);
const hasNumber = /\d/.test(password);
const hasSymbol = /[^\w\s]/.test(password);
if (!(hasLetter && hasNumber && hasSymbol)) {
newErrors.password = 'Попробуйте сочетание букв, цифр и символов.';
}
}
if (password !== passwordConfirm)
newErrors.passwordConfirm = 'Пароли не совпадают.';
return newErrors;
};
export const registerUser = async (
username: string,
email: string,
password: string,
) => {
try {
const res = await fetch('http://localhost:8000/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, email, password }),
});
const data = await res.json();
if (!res.ok) {
const { field, message } = data.detail || {};
return {
data: null,
error: field
? { [field]: message }
: { general: 'Ошибка регистрации' },
};
}
const body = new URLSearchParams();
body.append('username', username);
body.append('password', password);
const loginRes = await fetch('http://localhost:8000/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: body.toString(),
});
const loginData = await loginRes.json();
if (!loginRes.ok) {
return {
data: null,
error: {
general:
loginData.detail || 'Ошибка входа после регистрации',
},
};
}
localStorage.setItem('token', loginData.access_token);
localStorage.setItem('refresh_token', loginData.refresh_token);
const meRes = await fetch('http://localhost:8000/api/me', {
headers: { Authorization: `Bearer ${loginData.access_token}` },
});
const meData = await meRes.json();
return { data: meData, error: null };
} catch (err: any) {
return { data: null, error: { general: err.message } };
}
};
|