| | import { ref } from 'vue'
|
| |
|
| | const getStoredToken = () => {
|
| | try {
|
| | return localStorage.getItem('k9t_token')
|
| | } catch (e) {
|
| | return null
|
| | }
|
| | }
|
| |
|
| | const token = ref(getStoredToken())
|
| | const user = ref(null)
|
| |
|
| |
|
| | const API_URL = import.meta.env.PROD ? '/api' : 'http://localhost:8000/api'
|
| |
|
| | export const useAuth = () => {
|
| | const login = () => {
|
| | window.location.href = `${API_URL}/auth/google/login`
|
| | }
|
| |
|
| | const logout = async () => {
|
| | try {
|
| | if (token.value) {
|
| | await fetch(`${API_URL}/auth/logout`, {
|
| | method: 'POST',
|
| | headers: {
|
| | 'Authorization': `Bearer ${token.value}`
|
| | }
|
| | })
|
| | }
|
| | } catch (e) {
|
| | console.error("Logout backend call failed", e)
|
| | } finally {
|
| | token.value = null
|
| | user.value = null
|
| | localStorage.removeItem('k9t_token')
|
| | window.location.reload()
|
| | }
|
| | }
|
| |
|
| | const setToken = (newToken) => {
|
| | token.value = newToken
|
| | localStorage.setItem('k9t_token', newToken)
|
| | }
|
| |
|
| | const fetchProfile = async () => {
|
| | if (!token.value) return null
|
| | try {
|
| | const response = await fetch(`${API_URL}/user/profile`, {
|
| | headers: {
|
| | 'Authorization': `Bearer ${token.value}`
|
| | }
|
| | })
|
| | if (response.ok) {
|
| | const data = await response.json()
|
| | user.value = data
|
| | return data
|
| | } else {
|
| | if (response.status === 401) {
|
| | logout()
|
| | }
|
| | }
|
| | } catch (error) {
|
| | console.error('Failed to fetch profile:', error)
|
| | }
|
| | return null
|
| | }
|
| |
|
| | return {
|
| | token,
|
| | user,
|
| | login,
|
| | logout,
|
| | setToken,
|
| | fetchProfile,
|
| | isAuthenticated: () => !!token.value
|
| | }
|
| | }
|
| |
|
| |
|
| | export const auth = useAuth()
|
| |
|