This commit is contained in:
Vladimir Voronin
2024-10-25 13:28:44 +03:00
parent 37d974b8fc
commit b007fdcb81
9 changed files with 144 additions and 16 deletions

View File

@@ -0,0 +1,82 @@
<template>
<div class="flex items-center justify-center h-screen bg-gray-100">
<div class="w-full max-w-sm p-6 bg-white rounded-lg shadow-md">
<h2 class="text-2xl font-bold text-center mb-6">Вход</h2>
<form @submit.prevent="login">
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="username">Логин</label>
<input
v-model="username"
type="text"
id="username"
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
/>
</div>
<div class="mb-6">
<label class="block text-gray-700 text-sm font-bold mb-2" for="password">Пароль</label>
<input
v-model="password"
type="password"
id="password"
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
/>
</div>
<div class="flex items-center justify-between">
<button
type="submit"
class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
>
Войти
</button>
</div>
</form>
</div>
</div>
</template>
<script setup lang="ts">
import qs from 'qs';
import {computed, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import apiClient from '@/services/axiosSetup';
const username = ref('');
const password = ref('');
const router = useRouter();
const route = useRoute()
console.log(route.query['back'])
const tg_id = computed(() => {
if (window.Telegram.WebApp) {
const tg = window.Telegram.WebApp;
tg.expand(); // Разворачиваем веб-приложение на весь экран
// Получаем информацию о пользователе и выводим её
return tg.initDataUnsafe.user.id
}
})
const login = async () => {
try {
let response: string
if (tg_id){
response = await apiClient.post('/auth/token/tg', qs.stringify({ tg_id: tg_id.value }));
} else {
response = await apiClient.post('/auth/token', qs.stringify({ username: username.value, password: password.value }));
}
const token = response.data.access_token;
localStorage.setItem('token', token);
apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`;
await router.push(route.query['back']? route.query['back'] : '/');
} catch (error) {
console.log(error)
alert('Ошибка входа. Проверьте логин и пароль.');
}
};
</script>
<style scoped>
body {
background-color: #f0f2f5;
}
</style>

View File

@@ -8,7 +8,7 @@ import RecurrentSettingView from "@/components/settings/RecurrentSettingView.vue
<div class="flex flex-col h-full px-4 ">
<h2 class="text-4xl font-bold ">Настройки</h2>
test
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4 items-start ">
<CategorySettingView />
<RecurrentSettingView />

View File

@@ -3,7 +3,8 @@ import axios from 'axios';
// Создание экземпляра axios с базовым URL
const apiClient = axios.create({
baseURL: 'https://luminic.space/api/v1',
// baseURL: 'https://luminic.space/api/v1',
baseURL: 'http://localhost:8000/api/v1',
headers: {
'Content-Type': 'application/json',

View File

@@ -1,4 +1,4 @@
import {createRouter, createWebHistory} from 'vue-router';
import {createRouter, createWebHistory, useRoute} from 'vue-router';
import CategoriesList from '@/components/settings/categories/CategoriesList.vue';
import CreateCategoryModal from "@/components/settings/categories/CreateCategoryModal.vue";
import CategoryListItem from "@/components/settings/categories/CategoryListItem.vue"; // Импортируем новый компонент
@@ -7,19 +7,21 @@ import BudgetView from "@/components/budgets/BudgetView.vue";
import SettingsView from "@/components/settings/SettingsView.vue";
import RecurrentList from "@/components/settings/recurrent/RecurrentList.vue";
import TransactionList from "@/components/transactions/TransactionList.vue";
import LoginView from "@/components/auth/LoginView.vue";
const routes = [
{path: '/', name: 'Budgets main', component: BudgetList},
{path: '/budgets', name: 'Budgets', component: BudgetList},
{path: '/budgets/:id', name: 'BudgetView', component: BudgetView},
{path: '/transactions/:mode*', name: 'Transaction List', component: TransactionList},
{path: '/', name: 'Budgets main', component: BudgetList, meta: { requiresAuth: true }},
{ path: '/login', component: LoginView },
{path: '/budgets', name: 'Budgets', component: BudgetList, meta: { requiresAuth: true }},
{path: '/budgets/:id', name: 'BudgetView', component: BudgetView, meta: { requiresAuth: true }},
{path: '/transactions/:mode*', name: 'Transaction List', component: TransactionList, meta: { requiresAuth: true }},
// {path: '/transactions/create', name: 'Transaction List', component: TransactionList},
{path: '/settings/', name: 'Settings', component: SettingsView},
{path: '/settings/categories', name: 'Categories', component: CategoriesList},
{path: '/settings/recurrents', name: 'Recurrent operations list', component: RecurrentList},
{path: '/settings/categories/create', name: "Categories Creation", component: CreateCategoryModal},// Добавляем новый маршрут
{path: '/settings/categories/one', name: "Categories Creation", component: CategoryListItem}// Добавляем новый маршрут
{path: '/settings/', name: 'Settings', component: SettingsView, meta: { requiresAuth: true }},
{path: '/settings/categories', name: 'Categories', component: CategoriesList, meta: { requiresAuth: true }},
{path: '/settings/recurrents', name: 'Recurrent operations list', component: RecurrentList, meta: { requiresAuth: true }},
{path: '/settings/categories/create', name: "Categories Creation", component: CreateCategoryModal, meta: { requiresAuth: true }},// Добавляем новый маршрут
{path: '/settings/categories/one', name: "Categories Creation", component: CategoryListItem, meta: { requiresAuth: true }}// Добавляем новый маршрут
];
const router = createRouter({
@@ -27,4 +29,16 @@ const router = createRouter({
routes,
});
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('token');
if (to.meta.requiresAuth && !token) {
const router= useRoute()
console.log(to)
console.log(router.path)
console.log(router.params)
next('/login?back='+to.fullPath);
} else {
next();
}
});
export default router;

View File

@@ -0,0 +1,31 @@
// src/services/axiosSetup.ts
import axios from 'axios';
import { useRouter } from 'vue-router';
// Создаем экземпляр axios
const api = axios.create({
baseURL: 'http://localhost:8000/api/v1',
});
// Устанавливаем токен из localStorage при каждом запуске
const token = localStorage.getItem('token');
if (token) {
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
}
// Перехватчик ответа для проверки 401 статуса
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response && error.response.status === 401) {
localStorage.removeItem('token');
const router = useRouter();
console.log(router.params)
router.push('/login');
}
return Promise.reject(error);
}
);
export default api;

View File

@@ -1,4 +1,4 @@
import apiClient from '@/plugins/axios';
import apiClient from '@/services/axiosSetup';
import {BudgetCategory} from "@/models/Budget";
// Импортируете настроенный экземпляр axios

View File

@@ -1,5 +1,5 @@
// src/services/categoryService.ts
import apiClient from '@/plugins/axios';
import apiClient from '@/services/axiosSetup';
import {Category} from "@/models/Category"; // Импортируете настроенный экземпляр axios
export const getCategories = async (type = null) => {

View File

@@ -1,5 +1,5 @@
// src/services/recurrentyService.ts
import apiClient from '@/plugins/axios';
import apiClient from '@/services/axiosSetup';
import { RecurrentPayment} from "@/models/Recurrent"; // Импортируете настроенный экземпляр axios
export const getRecurrentPayments = async () => {

View File

@@ -1,4 +1,4 @@
import apiClient from '@/plugins/axios';
import apiClient from '@/services/axiosSetup';
import {Transaction} from "@/models/Transaction";
import {format} from "date-fns";
// Импортируете настроенный экземпляр axios