diff --git a/imagecreator/frontend/src/api/auth.ts b/imagecreator/frontend/src/api/auth.ts new file mode 100644 index 0000000..ebd0698 --- /dev/null +++ b/imagecreator/frontend/src/api/auth.ts @@ -0,0 +1,28 @@ +// src/api/auth.ts +import api from './index' + +export interface LoginRequest { + username: string + password: string +} + +export interface RegisterRequest { + username: string + email: string + password: string +} + +export interface AuthResponse { + access_token: string + refresh_token: string + token_type: string +} + +export const authApi = { + login(data: LoginRequest) { + return api.post('/auth/login', data) + }, + register(data: RegisterRequest) { + return api.post('/auth/register', data) + }, +} diff --git a/imagecreator/frontend/src/stores/auth.ts b/imagecreator/frontend/src/stores/auth.ts new file mode 100644 index 0000000..5b6ef75 --- /dev/null +++ b/imagecreator/frontend/src/stores/auth.ts @@ -0,0 +1,40 @@ +// src/stores/auth.ts +import { defineStore } from 'pinia' +import { ref } from 'vue' +import { authApi } from '../api/auth' +import api from '../api/index' + +export const useAuthStore = defineStore('auth', () => { + const token = ref(localStorage.getItem('access_token')) + const user = ref<{ id: string; username: string; email: string } | null>(null) + + const login = async (username: string, password: string) => { + const response = await authApi.login({ username, password }) + token.value = response.data.access_token + localStorage.setItem('access_token', response.data.access_token) + await fetchCurrentUser() + } + + const fetchCurrentUser = async () => { + if (!token.value) return + try { + const response = await api.get('/users/me') + user.value = response.data + } catch { + // Token might be expired + logout() + } + } + + const register = async (username: string, email: string, password: string) => { + await authApi.register({ username, email, password }) + } + + const logout = () => { + token.value = null + user.value = null + localStorage.removeItem('access_token') + } + + return { token, user, login, register, logout, fetchCurrentUser } +})