Skip to content

Commit

Permalink
🐛 Fix api issues
Browse files Browse the repository at this point in the history
  • Loading branch information
naelob committed Apr 8, 2024
1 parent 5abca6b commit 3504c98
Show file tree
Hide file tree
Showing 27 changed files with 214 additions and 443 deletions.
180 changes: 96 additions & 84 deletions packages/api/scripts/oauthConnector.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,36 +14,27 @@ import { hideBin } from 'yargs/helpers';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const paths = [
path.join(
__dirname,
`../../../docker-compose.dev.yml`,
),
path.join(
__dirname,
`../../../docker-compose.source.yml`,
),
path.join(
__dirname,
`../../../docker-compose.yml`,
),
]
path.join(__dirname, `../../../docker-compose.dev.yml`),
path.join(__dirname, `../../../docker-compose.source.yml`),
path.join(__dirname, `../../../docker-compose.yml`),
];
const envServiceFilePath = path.join(
__dirname,
`../src/@core/environment/environment.service.ts`,
__dirname,
`../src/@core/environment/environment.service.ts`,
);

function createServiceFile(vertical, provider) {
// Create the directory path
const dirPath = path.join(
__dirname,
`../src/@core/connections/${vertical}/services/${provider}`,
);
fs.mkdirSync(dirPath, { recursive: true });
const providerUpper = provider.slice(0,1).toUpperCase() + provider.slice(1);
const verticalUpper = vertical.slice(0,1).toUpperCase() + vertical.slice(1);
// Create the directory path
const dirPath = path.join(
__dirname,
`../src/@core/connections/${vertical}/services/${provider}`,
);
fs.mkdirSync(dirPath, { recursive: true });
const providerUpper = provider.slice(0, 1).toUpperCase() + provider.slice(1);
const verticalUpper = vertical.slice(0, 1).toUpperCase() + vertical.slice(1);

// Define the content of the service file
const serviceFileContent = `
// Define the content of the service file
const serviceFileContent = `
import { Injectable } from '@nestjs/common';
import axios from 'axios';
import { PrismaService } from '@@core/prisma/prisma.service';
Expand All @@ -59,7 +50,8 @@ import {
} from '../../types';
import { ServiceRegistry } from '../registry.service';
import { AuthStrategy } from '@panora/shared';
import { getCredentials, OAuth2AuthData, providerToType } from '@panora/shared/src/envConfig';
import { OAuth2AuthData, providerToType } from '@panora/shared/src/envConfig';
import { ConnectionsStrategiesService } from '@@core/connections-strategies/connections-strategies.service';
export type ${providerUpper}OAuthResponse = {
access_token: string;
Expand All @@ -77,6 +69,7 @@ export class ${providerUpper}ConnectionService implements I${verticalUpper}Conne
private env: EnvironmentService,
private cryptoService: EncryptionService,
private registry: ServiceRegistry,
private cService: ConnectionsStrategiesService,
) {
this.logger.setContext(${providerUpper}ConnectionService.name);
this.registry.registerService('${provider.toLowerCase()}', this);
Expand All @@ -96,7 +89,7 @@ export class ${providerUpper}ConnectionService implements I${verticalUpper}Conne
//reconstruct the redirect URI that was passed in the githubend it must be the same
const REDIRECT_URI = \`\${this.env.getOAuthRredirectBaseUrl()}/connections/oauth/callback\`;
const CREDENTIALS = (await getCredentials(projectId, this.type)) as OAuth2AuthData;
const CREDENTIALS = (await this.cService.getCredentials(projectId, this.type)) as OAuth2AuthData;
const formData = new URLSearchParams({
client_id: CREDENTIALS.CLIENT_ID,
Expand Down Expand Up @@ -177,15 +170,19 @@ export class ${providerUpper}ConnectionService implements I${verticalUpper}Conne
grant_type: 'refresh_token',
refresh_token: this.cryptoService.decrypt(refreshToken),
});
const subdomain = 'panora';
const CREDENTIALS = (await this.cService.getCredentials(
projectId,
this.type,
)) as OAuth2AuthData;
const res = await axios.post(
"",
formData.toString(),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Authorization: \`Basic ${Buffer.from(
`CREDENTIALS.CLIENT_ID}:\${
`CREDENTIALS.CLIENT_ID}:\${
CREDENTIALS.CLIENT_SECRET
}`,
).toString('base64')}\`,
Expand Down Expand Up @@ -213,82 +210,97 @@ export class ${providerUpper}ConnectionService implements I${verticalUpper}Conne
}
`;

// Write the content to the service file
const serviceFilePath = path.join(dirPath, `${provider.toLowerCase()}.service.ts`);
fs.writeFileSync(serviceFilePath, serviceFileContent);
console.log(`Service file created at: ${serviceFilePath}`);
// Write the content to the service file
const serviceFilePath = path.join(
dirPath,
`${provider.toLowerCase()}.service.ts`,
);
fs.writeFileSync(serviceFilePath, serviceFileContent);
console.log(`Service file created at: ${serviceFilePath}`);
}

// Function to add provider to EnvironmentService.ts
function addProviderToEnvironmentService(provider, envServicePath) {
const providerMethodName_ = provider.split('_').map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('_');
const providerMethodName = `get${providerMethodName_}Secret`;
const providerEnvPrefix = provider.toUpperCase();

const methodToAdd = `
const providerMethodName_ = provider
.split('_')
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join('_');
const providerMethodName = `get${providerMethodName_}Secret`;
const providerEnvPrefix = provider.toUpperCase();

const methodToAdd = `
${providerMethodName}(): OAuth {
return {
CLIENT_ID: this.configService.get<string>('${providerEnvPrefix}_CLIENT_ID'),
CLIENT_SECRET: this.configService.get<string>('${providerEnvPrefix}_CLIENT_SECRET'),
};
}
`;

let content = fs.readFileSync(envServicePath, { encoding: 'utf8' });

if (content.includes(providerMethodName)) {
console.log(`${providerMethodName}() already exists in EnvironmentService.`);
return;
}

content = content.replace(/\}\n*$/, methodToAdd + '}\n');
fs.writeFileSync(envServicePath, content);

console.log(`Added ${providerMethodName}() to EnvironmentService.`);

let content = fs.readFileSync(envServicePath, { encoding: 'utf8' });

if (content.includes(providerMethodName)) {
console.log(
`${providerMethodName}() already exists in EnvironmentService.`,
);
return;
}

content = content.replace(/\}\n*$/, methodToAdd + '}\n');
fs.writeFileSync(envServicePath, content);

console.log(`Added ${providerMethodName}() to EnvironmentService.`);
}

// Function to add provider to docker-compose.dev.yml
function addProviderToDockerCompose(provider, vertical, dockerComposePath) {
const providerEnvPrefix = provider.toUpperCase();
const newEnvVariables = `
const providerEnvPrefix = provider.toUpperCase();
const newEnvVariables = `
${providerEnvPrefix}_${vertical.toUpperCase()}_CLIENT_ID: $\{${providerEnvPrefix}_${vertical.toUpperCase()}_CLIENT_ID}
${providerEnvPrefix}_${vertical.toUpperCase()}_CLIENT_SECRET: $\{${providerEnvPrefix}_${vertical.toUpperCase()}_CLIENT_SECRET}
`;

let content = fs.readFileSync(dockerComposePath, { encoding: 'utf8' });

if (content.includes(`${providerEnvPrefix}_${vertical.toUpperCase()}_CLIENT_ID`)) {
console.log(`${providerEnvPrefix}_${vertical.toUpperCase()}_CLIENT_ID already exists in docker-compose.dev.yml.`);
return;
}

content = content.replace(/(api:\n.*?environment:.*?\n)(.*?)(\n\s+restart:)/s, `$1$2${newEnvVariables}$3`);
fs.writeFileSync(dockerComposePath, content);

console.log(`Added ${provider}'s CLIENT_ID and CLIENT_SECRET to docker-compose.dev.yml.`);
`;

let content = fs.readFileSync(dockerComposePath, { encoding: 'utf8' });

if (
content.includes(`${providerEnvPrefix}_${vertical.toUpperCase()}_CLIENT_ID`)
) {
console.log(
`${providerEnvPrefix}_${vertical.toUpperCase()}_CLIENT_ID already exists in docker-compose.dev.yml.`,
);
return;
}

content = content.replace(
/(api:\n.*?environment:.*?\n)(.*?)(\n\s+restart:)/s,
`$1$2${newEnvVariables}$3`,
);
fs.writeFileSync(dockerComposePath, content);

console.log(
`Added ${provider}'s CLIENT_ID and CLIENT_SECRET to docker-compose.dev.yml.`,
);
}

function handleUpdate(vertical, provider){
createServiceFile(vertical, provider);
addProviderToEnvironmentService(provider, envServiceFilePath)
for (const path of paths) {
addProviderToDockerCompose(provider, vertical, path)
}
function handleUpdate(vertical, provider) {
createServiceFile(vertical, provider);
addProviderToEnvironmentService(provider, envServiceFilePath);
for (const path of paths) {
addProviderToDockerCompose(provider, vertical, path);
}
}


if (import.meta.url === process.argv[1]) {
// Get command-line arguments
const args = process.argv.slice(1);
const vertical = args[0];
const provider = args[1];
createServiceFile(vertical, provider);
addProviderToEnvironmentService(provider, envServiceFilePath)
for (const path of paths) {
addProviderToDockerCompose(argv.provider, path)
}
// Get command-line arguments
const args = process.argv.slice(1);
const vertical = args[0];
const provider = args[1];
createServiceFile(vertical, provider);
addProviderToEnvironmentService(provider, envServiceFilePath);
for (const path of paths) {
addProviderToDockerCompose(argv.provider, path);
}
}

const argv = yargs(hideBin(process.argv)).argv;
handleUpdate(argv.vertical, argv.provider)

handleUpdate(argv.vertical, argv.provider);
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,9 @@ import { EnvironmentService } from '@@core/environment/environment.service';
import { EncryptionService } from '@@core/encryption/encryption.service';
import { ServiceRegistry } from '../registry.service';
import { LoggerService } from '@@core/logger/logger.service';
import {
getCredentials,
OAuth2AuthData,
providerToType,
} from '@panora/shared/src/envConfig';
import { OAuth2AuthData, providerToType } from '@panora/shared/src/envConfig';
import { AuthStrategy } from '@panora/shared';
import { ConnectionsStrategiesService } from '@@core/connections-strategies/connections-strategies.service';

type AcceloOAuthResponse = {
access_token: string;
Expand All @@ -38,6 +35,7 @@ export class AcceloConnectionService implements ICrmConnectionService {
private env: EnvironmentService,
private cryptoService: EncryptionService,
private registry: ServiceRegistry,
private cService: ConnectionsStrategiesService,
) {
this.logger.setContext(AcceloConnectionService.name);
this.registry.registerService('accelo', this);
Expand All @@ -60,7 +58,7 @@ export class AcceloConnectionService implements ICrmConnectionService {
if (isNotUnique) return;
//reconstruct the redirect URI that was passed in the frontend it must be the same
const REDIRECT_URI = `${this.env.getOAuthRredirectBaseUrl()}/connections/oauth/callback`;
const CREDENTIALS = (await getCredentials(
const CREDENTIALS = (await this.cService.getCredentials(
projectId,
this.type,
)) as OAuth2AuthData;
Expand Down Expand Up @@ -147,7 +145,7 @@ export class AcceloConnectionService implements ICrmConnectionService {
refresh_token: this.cryptoService.decrypt(refreshToken),
});
//const subdomain = 'panora'; //TODO: if custom oauth then get the actual domain from customer
const CREDENTIALS = (await getCredentials(
const CREDENTIALS = (await this.cService.getCredentials(
projectId,
this.type,
)) as OAuth2AuthData;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,9 @@ import {
ICrmConnectionService,
} from '../../types';
import { ServiceRegistry } from '../registry.service';
import {
getCredentials,
OAuth2AuthData,
providerToType,
} from '@panora/shared/src/envConfig';
import { OAuth2AuthData, providerToType } from '@panora/shared/src/envConfig';
import { AuthStrategy } from '@panora/shared';
import { ConnectionsStrategiesService } from '@@core/connections-strategies/connections-strategies.service';

export type AffinityOAuthResponse = {
access_token: string;
Expand All @@ -35,6 +32,7 @@ export class AffinityConnectionService implements ICrmConnectionService {
private env: EnvironmentService,
private cryptoService: EncryptionService,
private registry: ServiceRegistry,
private cService: ConnectionsStrategiesService,
) {
this.logger.setContext(AffinityConnectionService.name);
this.registry.registerService('affinity', this);
Expand All @@ -54,7 +52,7 @@ export class AffinityConnectionService implements ICrmConnectionService {

//reconstruct the redirect URI that was passed in the githubend it must be the same
const REDIRECT_URI = `${this.env.getOAuthRredirectBaseUrl()}/connections/oauth/callback`;
const CREDENTIALS = (await getCredentials(
const CREDENTIALS = (await this.cService.getCredentials(
projectId,
this.type,
)) as OAuth2AuthData;
Expand Down Expand Up @@ -134,7 +132,7 @@ export class AffinityConnectionService implements ICrmConnectionService {
grant_type: 'refresh_token',
refresh_token: this.cryptoService.decrypt(refreshToken),
});
const CREDENTIALS = (await getCredentials(
const CREDENTIALS = (await this.cService.getCredentials(
projectId,
this.type,
)) as OAuth2AuthData;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,9 @@ import { EnvironmentService } from '@@core/environment/environment.service';
import { EncryptionService } from '@@core/encryption/encryption.service';
import { ServiceRegistry } from '../registry.service';
import { LoggerService } from '@@core/logger/logger.service';
import {
getCredentials,
OAuth2AuthData,
providerToType,
} from '@panora/shared/src/envConfig';
import { OAuth2AuthData, providerToType } from '@panora/shared/src/envConfig';
import { AuthStrategy } from '@panora/shared';
import { ConnectionsStrategiesService } from '@@core/connections-strategies/connections-strategies.service';

export interface AttioOAuthResponse {
access_token: string;
Expand All @@ -34,6 +31,7 @@ export class AttioConnectionService implements ICrmConnectionService {
private env: EnvironmentService,
private cryptoService: EncryptionService,
private registry: ServiceRegistry,
private cService: ConnectionsStrategiesService,
) {
this.logger.setContext(AttioConnectionService.name);
this.registry.registerService('attio', this);
Expand All @@ -56,7 +54,7 @@ export class AttioConnectionService implements ICrmConnectionService {
if (isNotUnique) return;
//reconstruct the redirect URI that was passed in the frontend it must be the same
const REDIRECT_URI = `${this.env.getOAuthRredirectBaseUrl()}/connections/oauth/callback`;
const CREDENTIALS = (await getCredentials(
const CREDENTIALS = (await this.cService.getCredentials(
projectId,
this.type,
)) as OAuth2AuthData;
Expand Down
Loading

1 comment on commit 3504c98

@vercel
Copy link

@vercel vercel bot commented on 3504c98 Apr 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.