feat: implement frontend auth store and API
This commit is contained in:
@@ -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<AuthResponse>('/auth/login', data)
|
||||||
|
},
|
||||||
|
register(data: RegisterRequest) {
|
||||||
|
return api.post<any>('/auth/register', data)
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -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<string | null>(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 }
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user