|
| 1 | +import { Injectable, Logger } from '@nestjs/common'; |
| 2 | +import * as moment from 'moment'; |
| 3 | +import { v4 as uuidv4 } from 'uuid'; |
| 4 | +import { ID } from '@gauzy/contracts'; |
| 5 | + |
| 6 | +@Injectable() |
| 7 | +export class ZapierAuthCodeService { |
| 8 | + private readonly logger = new Logger(ZapierAuthCodeService.name); |
| 9 | + |
| 10 | + // Using a Map to store temporary auth codes - this is temporary storage |
| 11 | + // and doesn't need to be persisted to the database |
| 12 | + private authCodes: Map<string, { |
| 13 | + userId: string, |
| 14 | + expiresAt: Date, |
| 15 | + tenantId: string, |
| 16 | + organizationId?: string |
| 17 | + }> = new Map(); |
| 18 | + |
| 19 | + /** |
| 20 | + * Generates and stores an authentication code for a user |
| 21 | + * |
| 22 | + * @param userId The user's ID |
| 23 | + * @param tenantId The tenant ID |
| 24 | + * @param organizationId The organization ID |
| 25 | + * @returns The generated authorization code |
| 26 | + */ |
| 27 | + |
| 28 | + generateAuthCode(userId: ID, tenantId: ID, organizationId?: ID): String { |
| 29 | + // Generation of a unique code |
| 30 | + const code = uuidv4(); |
| 31 | + // Auth codes expire in 60 minutes |
| 32 | + const expiresAt = moment().add(60, 'minutes').toDate(); |
| 33 | + |
| 34 | + // Stores the code with user infos |
| 35 | + this.authCodes.set(code, { |
| 36 | + userId: userId.toString(), |
| 37 | + tenantId: tenantId.toString(), |
| 38 | + organizationId: organizationId?.toString(), |
| 39 | + expiresAt |
| 40 | + }); |
| 41 | + this.logger.debug(`Generated auth code for user ${userId}, expires at ${expiresAt}`); |
| 42 | + return code; |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Gets the user information associated with an auth code |
| 47 | + * |
| 48 | + * @param code The authorization code |
| 49 | + * @returns The user info or null if code is invalid or expired |
| 50 | + */ |
| 51 | + getUserInfoFromAuthCode(code: string): { |
| 52 | + userId: string, |
| 53 | + tenantId: string, |
| 54 | + organizationId?: string |
| 55 | + } | null { |
| 56 | + const authCodeData = this.authCodes.get(code); |
| 57 | + |
| 58 | + // Check if code exists and is not expired |
| 59 | + if (authCodeData && moment().isBefore(authCodeData.expiresAt)) { |
| 60 | + this.authCodes.delete(code); |
| 61 | + |
| 62 | + return { |
| 63 | + userId: authCodeData.userId, |
| 64 | + tenantId: authCodeData.tenantId, |
| 65 | + organizationId: authCodeData.organizationId |
| 66 | + }; |
| 67 | + } |
| 68 | + return null; |
| 69 | + } |
| 70 | +} |
0 commit comments