|
| 1 | +import { Injectable } from '@angular/core'; |
| 2 | +import { ElectronService } from '../electron/electron.service'; |
| 3 | +import { events } from '@minsky/shared'; |
| 4 | + |
| 5 | +@Injectable({ |
| 6 | + providedIn: 'root', |
| 7 | +}) |
| 8 | +export class ClerkService { |
| 9 | + private clerk: any = null; |
| 10 | + private initialized = false; |
| 11 | + |
| 12 | + constructor(private electronService: ElectronService) {} |
| 13 | + |
| 14 | + async initialize(): Promise<void> { |
| 15 | + if (this.initialized) return; |
| 16 | + |
| 17 | + const publishableKey = (window as any).__clerkPublishableKey |
| 18 | + ?? (typeof process !== 'undefined' && process.env?.['CLERK_PUBLISHABLE_KEY']) |
| 19 | + ?? ''; |
| 20 | + |
| 21 | + if (!publishableKey) { |
| 22 | + console.warn( |
| 23 | + 'ClerkService: No publishable key found in window.__clerkPublishableKey or ' + |
| 24 | + 'CLERK_PUBLISHABLE_KEY environment variable. Authentication will not be available.' |
| 25 | + ); |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + const { default: Clerk } = await import('@clerk/clerk-js'); |
| 30 | + this.clerk = new Clerk(publishableKey); |
| 31 | + await this.clerk.load(); |
| 32 | + this.initialized = true; |
| 33 | + } |
| 34 | + |
| 35 | + async isSignedIn(): Promise<boolean> { |
| 36 | + if (!this.clerk) return false; |
| 37 | + return !!this.clerk.user; |
| 38 | + } |
| 39 | + |
| 40 | + async getToken(): Promise<string | null> { |
| 41 | + if (!this.clerk?.session) return null; |
| 42 | + return await this.clerk.session.getToken(); |
| 43 | + } |
| 44 | + |
| 45 | + async signInWithEmailPassword(email: string | null | undefined, password: string | null | undefined): Promise<void> { |
| 46 | + if (!this.clerk) throw new Error('Clerk is not initialized.'); |
| 47 | + if (!email || !password) throw new Error('Email and password are required.'); |
| 48 | + const result = await this.clerk.client.signIn.create({ |
| 49 | + identifier: email, |
| 50 | + password, |
| 51 | + }); |
| 52 | + if (result.status === 'complete') { |
| 53 | + await this.clerk.setActive({ session: result.createdSessionId }); |
| 54 | + } else { |
| 55 | + throw new Error('Sign-in was not completed. Additional steps may be required.'); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + async signOut(): Promise<void> { |
| 60 | + if (!this.clerk) throw new Error('Clerk is not initialized.'); |
| 61 | + await this.clerk.signOut(); |
| 62 | + if (this.electronService.isElectron) { |
| 63 | + await this.electronService.invoke(events.SET_AUTH_TOKEN, null); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + async sendTokenToElectron(): Promise<void> { |
| 68 | + if (!this.electronService.isElectron) return; |
| 69 | + const token = await this.getToken(); |
| 70 | + await this.electronService.invoke(events.SET_AUTH_TOKEN, token); |
| 71 | + } |
| 72 | +} |
0 commit comments