// Auth service for LNbits integration import { ref } from 'vue' import { BaseService } from '@/core/base/BaseService' import { eventBus } from '@/core/event-bus' import { lnbitsAPI, type LoginCredentials, type RegisterData } from '@/lib/api/lnbits' export class AuthService extends BaseService { // Service metadata protected readonly metadata = { name: 'AuthService', version: '1.0.0', dependencies: [] // Auth service has no dependencies on other services } // Public state public isAuthenticated = ref(false) public user = ref(null) public isLoading = ref(false) /** * Service-specific initialization (called by BaseService) */ protected async onInitialize(): Promise { this.debug('Initializing auth service...') // Check for existing auth state and fetch user data await this.checkAuth() if (this.isAuthenticated.value) { eventBus.emit('auth:login', { user: this.user.value }, 'auth-service') } } async checkAuth(): Promise { if (!lnbitsAPI.isAuthenticated()) { this.debug('No auth token found - user needs to login') this.isAuthenticated.value = false this.user.value = null return false } try { this.isLoading.value = true const userData = await lnbitsAPI.getCurrentUser() this.user.value = userData this.isAuthenticated.value = true this.debug(`User authenticated: ${userData.username || userData.id} (${userData.pubkey?.slice(0, 8)})`) return true } catch (error) { this.handleError(error, 'checkAuth') this.isAuthenticated.value = false this.user.value = null // Clear invalid token lnbitsAPI.logout() return false } finally { this.isLoading.value = false } } async login(credentials: LoginCredentials): Promise { this.isLoading.value = true try { await lnbitsAPI.login(credentials) const userData = await lnbitsAPI.getCurrentUser() this.user.value = userData this.isAuthenticated.value = true eventBus.emit('auth:login', { user: userData }, 'auth-service') } catch (error) { const err = this.handleError(error, 'login') eventBus.emit('auth:login-failed', { error: err }, 'auth-service') throw err } finally { this.isLoading.value = false } } async register(data: RegisterData): Promise { this.isLoading.value = true try { await lnbitsAPI.register(data) const userData = await lnbitsAPI.getCurrentUser() this.user.value = userData this.isAuthenticated.value = true eventBus.emit('auth:login', { user: userData }, 'auth-service') } catch (error) { const err = this.handleError(error, 'register') eventBus.emit('auth:login-failed', { error: err }, 'auth-service') throw err } finally { this.isLoading.value = false } } logout(): void { lnbitsAPI.logout() this.user.value = null this.isAuthenticated.value = false eventBus.emit('auth:logout', {}, 'auth-service') } async refresh(): Promise { // Re-fetch user data from API await this.checkAuth() } /** * Cleanup when service is disposed */ protected async onDispose(): Promise { this.logout() this.debug('Auth service disposed') } } // Export singleton instance export const auth = new AuthService()