web-app/src/lib/api/lnbits.ts
padreug 0cc0bf3555 feat: Enhance authentication and user management with detailed logging
- Add console logging for authentication initialization, login attempts, and user retrieval to improve debugging and traceability.
- Introduce a new getCurrentUser function in useAuth for better user data management.
- Update useTicketPurchase to include detailed logging for user wallets and balance checks, enhancing visibility into wallet states.
- Refactor LNBits API request and response logging for clearer error handling and debugging.
2025-08-03 11:20:58 +02:00

187 lines
No EOL
4.2 KiB
TypeScript

interface LoginCredentials {
username: string
password: string
}
interface RegisterData {
username: string
email?: string
password: string
password_repeat: string
}
interface AuthResponse {
access_token: string
user_id: string
username?: string
email?: string
}
interface Wallet {
id: string
user: string
name: string
adminkey: string
inkey: string
deleted: boolean
created_at: string
updated_at: string
currency?: string
balance_msat: number
extra?: {
icon: string
color: string
pinned: boolean
}
}
interface User {
id: string
username?: string
email?: string
pubkey?: string
external_id?: string
extensions: string[]
wallets: Wallet[]
admin: boolean
super_user: boolean
fiat_providers: string[]
has_password: boolean
created_at: string
updated_at: string
extra?: {
email_verified?: boolean
first_name?: string
last_name?: string
display_name?: string
picture?: string
provider?: string
visible_wallet_count?: number
}
}
import { getApiUrl, getAuthToken, setAuthToken, removeAuthToken } from '@/lib/config/lnbits'
class LnbitsAPI {
private accessToken: string | null = null
constructor() {
// Try to load token from localStorage
this.accessToken = getAuthToken()
}
private async request<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
const url = getApiUrl(endpoint)
const headers: HeadersInit = {
'Content-Type': 'application/json',
...options.headers,
}
if (this.accessToken) {
(headers as Record<string, string>)['Authorization'] = `Bearer ${this.accessToken}`
}
// Debug logging
console.log('LNBits API Request:', {
url,
method: options.method || 'GET',
headers: headers,
hasAccessToken: !!this.accessToken,
endpoint
})
const response = await fetch(url, {
...options,
headers,
})
console.log('LNBits API Response:', {
status: response.status,
statusText: response.statusText,
ok: response.ok,
url: response.url
})
if (!response.ok) {
const errorText = await response.text()
console.error('LNBits API Error:', {
status: response.status,
statusText: response.statusText,
errorText
})
throw new Error(`API request failed: ${response.status} ${response.statusText}`)
}
const data = await response.json()
console.log('LNBits API Response Data:', data)
return data
}
async login(credentials: LoginCredentials): Promise<AuthResponse> {
const response = await this.request<AuthResponse>('/auth', {
method: 'POST',
body: JSON.stringify(credentials),
})
this.accessToken = response.access_token
setAuthToken(response.access_token)
return response
}
async register(data: RegisterData): Promise<AuthResponse> {
const response = await this.request<AuthResponse>('/auth/register', {
method: 'POST',
body: JSON.stringify(data),
})
this.accessToken = response.access_token
setAuthToken(response.access_token)
return response
}
async logout(): Promise<void> {
// Just clear local state - no API call needed for logout
this.accessToken = null
removeAuthToken()
}
async getCurrentUser(): Promise<User> {
console.log('getCurrentUser called, accessToken:', this.accessToken ? 'present' : 'missing')
const user = await this.request<User>('/user')
console.log('getCurrentUser response:', user)
return user
}
async updatePassword(currentPassword: string, newPassword: string): Promise<User> {
return this.request<User>('/auth/password', {
method: 'PUT',
body: JSON.stringify({
current_password: currentPassword,
new_password: newPassword,
}),
})
}
async updateProfile(data: Partial<User>): Promise<User> {
return this.request<User>('/auth/update', {
method: 'PUT',
body: JSON.stringify(data),
})
}
isAuthenticated(): boolean {
return !!this.accessToken
}
getAccessToken(): string | null {
return this.accessToken
}
}
export const lnbitsAPI = new LnbitsAPI()
export type { LoginCredentials, RegisterData, AuthResponse, User }