nakama/moderation/frontend/src/utils/api.js

194 lines
6.4 KiB
JavaScript
Raw Normal View History

2025-11-10 21:22:58 +00:00
import axios from 'axios'
2025-11-10 20:13:22 +00:00
2025-12-08 23:42:32 +00:00
// Определить базовый URL API
export const getApiUrl = () => {
// Если указан явно в env
if (import.meta.env.VITE_API_URL) {
return import.meta.env.VITE_API_URL;
}
2025-12-09 00:29:13 +00:00
// В production используем относительный путь (HTTPS через nginx)
2025-12-08 23:42:32 +00:00
if (import.meta.env.PROD) {
return '/api';
}
2025-12-09 00:29:13 +00:00
// В development используем порт модерации (только для dev)
2025-12-08 23:42:32 +00:00
return 'http://localhost:3001/api';
};
const API_URL = getApiUrl();
2025-11-10 20:13:22 +00:00
const api = axios.create({
baseURL: API_URL,
2025-11-10 21:56:36 +00:00
withCredentials: true
2025-11-10 21:22:58 +00:00
})
2025-11-10 20:13:22 +00:00
2025-12-08 23:42:32 +00:00
// Получить токен авторизации
const getAuthToken = () => {
// 1. Сначала пробуем JWT токен из localStorage
const jwtToken = localStorage.getItem('moderation_jwt_token');
if (jwtToken) {
return { token: jwtToken, type: 'jwt' };
}
// 2. Потом пробуем Telegram WebApp
2025-11-10 22:19:37 +00:00
const initData = window.Telegram?.WebApp?.initData;
if (initData) {
2025-12-08 23:42:32 +00:00
return { initData, type: 'telegram' };
}
// 3. Старый способ через localStorage
const storedToken = localStorage.getItem('moderation_token');
if (storedToken) {
return { initData: storedToken, type: 'telegram' };
}
return null;
};
api.interceptors.request.use((config) => {
const auth = getAuthToken();
if (auth) {
2025-11-10 22:19:37 +00:00
config.headers = config.headers || {};
2025-12-08 23:42:32 +00:00
if (auth.type === 'jwt' && auth.token) {
// JWT токен
config.headers.Authorization = `Bearer ${auth.token}`;
} else if (auth.initData) {
// Telegram initData
if (!config.headers.Authorization) {
config.headers.Authorization = `tma ${auth.initData}`;
}
if (!config.headers['x-telegram-init-data']) {
config.headers['x-telegram-init-data'] = auth.initData;
}
2025-11-10 22:48:18 +00:00
}
2025-11-10 22:19:37 +00:00
}
return config;
});
2025-11-10 23:16:43 +00:00
// Response interceptor для обработки устаревших токенов
api.interceptors.response.use(
(response) => response,
(error) => {
const status = error?.response?.status;
const errorMessage = error?.response?.data?.error || '';
2025-12-08 23:42:32 +00:00
// Если токен устарел или невалиден
if (status === 401) {
console.warn('[Moderation API] Auth token expired or invalid');
// Очистить все токены из localStorage
localStorage.removeItem('moderation_token');
localStorage.removeItem('moderation_jwt_token');
2025-11-10 23:16:43 +00:00
// Показать уведомление пользователю
const tg = window.Telegram?.WebApp;
if (tg?.showAlert) {
tg.showAlert('Сессия устарела. Перезагрузка...', () => {
window.location.reload();
});
} else {
2025-12-08 23:42:32 +00:00
// Для обычного браузера - перезагрузка страницы (покажет форму входа)
window.location.reload();
2025-11-10 23:16:43 +00:00
}
}
return Promise.reject(error);
}
);
2025-12-08 23:42:32 +00:00
// Авторизация
export const sendVerificationCode = (email) =>
api.post('/moderation-auth/send-code', { email }).then((res) => res.data)
export const registerWithCode = (email, code, password, username) =>
api.post('/moderation-auth/register', { email, code, password, username }).then((res) => {
if (res.data.accessToken) {
localStorage.setItem('moderation_jwt_token', res.data.accessToken);
}
return res.data;
})
export const login = (email, password) =>
api.post('/moderation-auth/login', { email, password }).then((res) => {
if (res.data.accessToken) {
localStorage.setItem('moderation_jwt_token', res.data.accessToken);
}
return res.data;
})
export const loginTelegram = () =>
api.post('/moderation-auth/telegram').then((res) => {
if (res.data.accessToken) {
localStorage.setItem('moderation_jwt_token', res.data.accessToken);
}
return res.data;
})
export const logout = () => {
localStorage.removeItem('moderation_jwt_token');
localStorage.removeItem('moderation_token');
return api.post('/moderation-auth/logout').then((res) => res.data);
}
export const getCurrentUser = () =>
api.get('/moderation-auth/me').then((res) => res.data.user)
2025-11-10 21:56:36 +00:00
export const verifyAuth = () => api.post('/mod-app/auth/verify').then((res) => res.data.user)
2025-11-10 20:13:22 +00:00
export const fetchUsers = (params = {}) =>
2025-11-10 21:22:58 +00:00
api.get('/mod-app/users', { params }).then((res) => res.data)
2025-11-10 20:13:22 +00:00
export const banUser = (userId, data) =>
2025-11-10 21:22:58 +00:00
api.put(`/mod-app/users/${userId}/ban`, data).then((res) => res.data)
2025-11-10 20:13:22 +00:00
export const fetchPosts = (params = {}) =>
2025-11-10 21:22:58 +00:00
api.get('/mod-app/posts', { params }).then((res) => res.data)
2025-11-10 20:13:22 +00:00
export const updatePost = (postId, data) =>
2025-11-10 21:22:58 +00:00
api.put(`/mod-app/posts/${postId}`, data).then((res) => res.data)
2025-11-10 20:13:22 +00:00
export const deletePost = (postId) =>
2025-11-10 21:22:58 +00:00
api.delete(`/mod-app/posts/${postId}`).then((res) => res.data)
2025-11-10 20:13:22 +00:00
export const removePostImage = (postId, index) =>
2025-11-10 21:22:58 +00:00
api.delete(`/mod-app/posts/${postId}/images/${index}`).then((res) => res.data)
2025-11-10 20:13:22 +00:00
export const banPostAuthor = (postId, data) =>
2025-11-10 21:22:58 +00:00
api.post(`/mod-app/posts/${postId}/ban`, data).then((res) => res.data)
2025-11-10 20:13:22 +00:00
export const fetchReports = (params = {}) =>
2025-11-10 21:22:58 +00:00
api.get('/mod-app/reports', { params }).then((res) => res.data)
2025-11-10 20:13:22 +00:00
export const updateReportStatus = (reportId, data) =>
2025-11-10 21:22:58 +00:00
api.put(`/mod-app/reports/${reportId}`, data).then((res) => res.data)
2025-11-10 20:13:22 +00:00
export const publishToChannel = (formData) =>
api.post('/mod-app/channel/publish', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
2025-11-10 21:22:58 +00:00
})
2025-11-10 20:13:22 +00:00
2025-11-11 00:40:29 +00:00
export const fetchAdmins = () =>
api.get('/mod-app/admins').then((res) => res.data)
export const initiateAddAdmin = (userId, adminNumber) =>
api.post('/mod-app/admins/initiate-add', { userId, adminNumber }).then((res) => res.data)
export const confirmAddAdmin = (userId, code) =>
api.post('/mod-app/admins/confirm-add', { userId, code }).then((res) => res.data)
export const initiateRemoveAdmin = (adminId) =>
api.post('/mod-app/admins/initiate-remove', { adminId }).then((res) => res.data)
export const confirmRemoveAdmin = (adminId, code) =>
api.post('/mod-app/admins/confirm-remove', { adminId, code }).then((res) => res.data)
2025-12-04 21:45:02 +00:00
export const getPostComments = (postId) =>
2025-12-04 21:49:05 +00:00
api.get(`/mod-app/posts/${postId}`).then((res) => res.data.post)
2025-12-04 21:45:02 +00:00
export const deleteComment = (postId, commentId) =>
2025-12-04 21:49:05 +00:00
api.delete(`/mod-app/posts/${postId}/comments/${commentId}`).then((res) => res.data)
2025-12-04 21:45:02 +00:00
2025-11-10 21:22:58 +00:00
export default api
2025-11-10 20:13:22 +00:00