import * as jsforce from 'jsforce';
import * as fs from 'fs';
import * as jwt from 'jsonwebtoken';
import axios from 'axios';
import config from '../config';
export class SalesforceConnection {
private connection: jsforce.Connection | null = null;
async connectWithOAuth(username: string, password: string, securityToken: string): Promise<jsforce.Connection> {
this.connection = new jsforce.Connection({
loginUrl: config.salesforce.loginUrl
});
await this.connection.login(username, password + securityToken);
return this.connection;
}
async connectWithJWT(clientId: string, username: string, privateKeyPath: string): Promise<jsforce.Connection> {
const privateKey = fs.readFileSync(privateKeyPath, 'utf8');
const jwtToken = this.createJWT(clientId, username, privateKey);
const accessToken = await this.requestToken(jwtToken, clientId);
this.connection = new jsforce.Connection({
instanceUrl: config.salesforce.loginUrl,
accessToken: accessToken
});
return this.connection;
}
private createJWT(clientId: string, username: string, privateKey: string): string {
const claims = {
iss: clientId,
sub: username,
aud: config.salesforce.loginUrl || 'https://login.salesforce.com',
exp: Math.floor(Date.now() / 1000) + 300
};
return jwt.sign(claims, privateKey, { algorithm: 'RS256' });
}
private async requestToken(jwtToken: string, clientId: string): Promise<string> {
const tokenUrl = `${config.salesforce.loginUrl}/services/oauth2/token`;
const response = await axios.post(tokenUrl, {
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: jwtToken
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
return response.data.access_token;
}
getConnection(): jsforce.Connection {
if (!this.connection) {
throw new Error('Not connected to Salesforce. Call connect method first.');
}
return this.connection;
}
async disconnect(): Promise<void> {
if (this.connection) {
await this.connection.logout();
this.connection = null;
}
}
}