auth, login + register

This commit is contained in:
JSC
2025-06-28 19:20:15 +02:00
parent e23e4bca2e
commit 984334d948
13 changed files with 929 additions and 7 deletions

127
src/services/auth.ts Normal file
View File

@@ -0,0 +1,127 @@
interface User {
id: string
email: string
name: string
picture?: string
role: string
is_active: boolean
provider: string
providers: string[]
}
interface AuthResponse {
message: string
user: User
}
interface ErrorResponse {
error: string
}
const API_BASE = 'http://localhost:5000/api'
class AuthService {
async register(email: string, password: string, name: string): Promise<User> {
const response = await fetch(`${API_BASE}/auth/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({ email, password, name }),
})
const data = await response.json()
if (!response.ok) {
throw new Error((data as ErrorResponse).error || 'Registration failed')
}
return (data as AuthResponse).user
}
async login(email: string, password: string): Promise<User> {
const response = await fetch(`${API_BASE}/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({ email, password }),
})
const data = await response.json()
if (!response.ok) {
throw new Error((data as ErrorResponse).error || 'Login failed')
}
return (data as AuthResponse).user
}
async logout(): Promise<void> {
const response = await fetch(`${API_BASE}/auth/logout`, {
credentials: 'include',
})
if (!response.ok) {
throw new Error('Logout failed')
}
}
async getCurrentUser(): Promise<User | null> {
try {
const response = await fetch(`${API_BASE}/auth/me`, {
credentials: 'include',
})
if (!response.ok) {
return null
}
const data = await response.json()
return data.user
} catch (error) {
console.error('getCurrentUser error:', error)
return null
}
}
async getOAuthProviders(): Promise<Record<string, { name: string; display_name: string }>> {
try {
const response = await fetch(`${API_BASE}/auth/providers`)
if (!response.ok) {
throw new Error('Failed to get OAuth providers')
}
const data = await response.json()
return data.providers
} catch (error) {
console.warn('Backend not available, using fallback OAuth providers')
// Fallback OAuth providers when backend is not running
return {
google: { name: 'google', display_name: 'Google' },
github: { name: 'github', display_name: 'GitHub' }
}
}
}
getOAuthLoginUrl(provider: string): string {
return `${API_BASE}/auth/login/${provider}`
}
async refreshToken(): Promise<void> {
const response = await fetch(`${API_BASE}/auth/refresh`, {
method: 'POST',
credentials: 'include',
})
if (!response.ok) {
throw new Error('Token refresh failed')
}
}
}
export const authService = new AuthService()
export type { User }