|
| 1 | +import fs from 'node:fs/promises'; |
| 2 | +import os from 'node:os'; |
| 3 | +import path from 'node:path'; |
| 4 | + |
| 5 | +interface Credentials { |
| 6 | + accessToken: string; |
| 7 | + email: string; |
| 8 | + userId: string; |
| 9 | + expiry: string; |
| 10 | +} |
| 11 | + |
| 12 | +export class LoginHelper { |
| 13 | + private static instance: LoginHelper; |
| 14 | + |
| 15 | + private constructor( |
| 16 | + public isLoggedIn: boolean, |
| 17 | + public credentials?: Credentials |
| 18 | + ) {}; |
| 19 | + |
| 20 | + static async load(): Promise<LoginHelper> { |
| 21 | + if (LoginHelper.instance) { |
| 22 | + return LoginHelper.instance; |
| 23 | + } |
| 24 | + |
| 25 | + const credentials = await LoginHelper.read(); |
| 26 | + if (!credentials) { |
| 27 | + LoginHelper.instance = new LoginHelper(false); |
| 28 | + return LoginHelper.instance; |
| 29 | + } |
| 30 | + |
| 31 | + if (new Date(credentials.expiry).getTime() < Date.now()) { |
| 32 | + LoginHelper.instance = new LoginHelper(false); |
| 33 | + return LoginHelper.instance; |
| 34 | + } |
| 35 | + |
| 36 | + LoginHelper.instance = new LoginHelper(true, credentials); |
| 37 | + return LoginHelper.instance; |
| 38 | + } |
| 39 | + |
| 40 | + static get(): LoginHelper | undefined { |
| 41 | + return LoginHelper.instance; |
| 42 | + } |
| 43 | + |
| 44 | + static async save(credentials: Credentials) { |
| 45 | + const credentialsPath = path.join(os.homedir(), '.codify', 'credentials.json'); |
| 46 | + console.log(`Saving credentials to ${credentialsPath}`); |
| 47 | + await fs.writeFile(credentialsPath, JSON.stringify(credentials)); |
| 48 | + } |
| 49 | + |
| 50 | + private static async read(): Promise<Credentials | undefined> { |
| 51 | + const credentialsPath = path.join(os.homedir(), '.codify', 'credentials.json'); |
| 52 | + const credentialsStr = await fs.readFile(credentialsPath, 'utf8'); |
| 53 | + |
| 54 | + try { |
| 55 | + return JSON.parse(credentialsStr); |
| 56 | + } catch { |
| 57 | + return undefined; |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments