n8n
Version:
n8n Workflow Automation Tool
196 lines • 10.3 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OAuth2CredentialController = void 0;
const client_oauth2_1 = require("@n8n/client-oauth2");
const pkce_challenge_1 = __importDefault(require("pkce-challenge"));
const qs = __importStar(require("querystring"));
const omit_1 = __importDefault(require("lodash/omit"));
const set_1 = __importDefault(require("lodash/set"));
const split_1 = __importDefault(require("lodash/split"));
const decorators_1 = require("../../decorators");
const n8n_workflow_1 = require("n8n-workflow");
const abstractOAuth_controller_1 = require("./abstractOAuth.controller");
const constants_1 = require("../../constants");
let OAuth2CredentialController = class OAuth2CredentialController extends abstractOAuth_controller_1.AbstractOAuthController {
constructor() {
super(...arguments);
this.oauthVersion = 2;
}
async getAuthUri(req) {
const credential = await this.getCredential(req);
const additionalData = await this.getAdditionalData();
const decryptedDataOriginal = await this.getDecryptedData(credential, additionalData);
if ((decryptedDataOriginal === null || decryptedDataOriginal === void 0 ? void 0 : decryptedDataOriginal.scope) &&
credential.type.includes('OAuth2') &&
!constants_1.GENERIC_OAUTH2_CREDENTIALS_WITH_EDITABLE_SCOPE.includes(credential.type)) {
delete decryptedDataOriginal.scope;
}
const oauthCredentials = this.applyDefaultsAndOverwrites(credential, decryptedDataOriginal, additionalData);
const [csrfSecret, state] = this.createCsrfState(credential.id);
const oAuthOptions = {
...this.convertCredentialToOptions(oauthCredentials),
state,
};
if (oauthCredentials.authQueryParameters) {
oAuthOptions.query = qs.parse(oauthCredentials.authQueryParameters);
}
await this.externalHooks.run('oauth2.authenticate', [oAuthOptions]);
decryptedDataOriginal.csrfSecret = csrfSecret;
if (oauthCredentials.grantType === 'pkce') {
const { code_verifier, code_challenge } = (0, pkce_challenge_1.default)();
oAuthOptions.query = {
...oAuthOptions.query,
code_challenge,
code_challenge_method: 'S256',
};
decryptedDataOriginal.codeVerifier = code_verifier;
}
await this.encryptAndSaveData(credential, decryptedDataOriginal);
const oAuthObj = new client_oauth2_1.ClientOAuth2(oAuthOptions);
const returnUri = oAuthObj.code.getUri();
this.logger.verbose('OAuth2 authorization url created for credential', {
userId: req.user.id,
credentialId: credential.id,
});
return returnUri.toString();
}
async handleCallback(req, res) {
try {
const { code, state: encodedState } = req.query;
if (!code || !encodedState) {
return this.renderCallbackError(res, 'Insufficient parameters for OAuth2 callback.', `Received following query parameters: ${JSON.stringify(req.query)}`);
}
let state;
try {
state = this.decodeCsrfState(encodedState);
}
catch (error) {
return this.renderCallbackError(res, error.message);
}
const credentialId = state.cid;
const credential = await this.getCredentialWithoutUser(credentialId);
if (!credential) {
const errorMessage = 'OAuth2 callback failed because of insufficient permissions';
this.logger.error(errorMessage, { credentialId });
return this.renderCallbackError(res, errorMessage);
}
const additionalData = await this.getAdditionalData();
const decryptedDataOriginal = await this.getDecryptedData(credential, additionalData);
const oauthCredentials = this.applyDefaultsAndOverwrites(credential, decryptedDataOriginal, additionalData);
if (this.verifyCsrfState(decryptedDataOriginal, state)) {
const errorMessage = 'The OAuth2 callback state is invalid!';
this.logger.debug(errorMessage, { credentialId });
return this.renderCallbackError(res, errorMessage);
}
let options = {};
const oAuthOptions = this.convertCredentialToOptions(oauthCredentials);
if (oauthCredentials.grantType === 'pkce') {
options = {
body: { code_verifier: decryptedDataOriginal.codeVerifier },
};
}
else if (oauthCredentials.authentication === 'body') {
options = {
body: {
client_id: oAuthOptions.clientId,
client_secret: oAuthOptions.clientSecret,
},
};
delete oAuthOptions.clientSecret;
}
await this.externalHooks.run('oauth2.callback', [oAuthOptions]);
const oAuthObj = new client_oauth2_1.ClientOAuth2(oAuthOptions);
const queryParameters = req.originalUrl.split('?').splice(1, 1).join('');
const oauthToken = await oAuthObj.code.getToken(`${oAuthOptions.redirectUri}?${queryParameters}`, options);
if (Object.keys(req.query).length > 2) {
(0, set_1.default)(oauthToken.data, 'callbackQueryString', (0, omit_1.default)(req.query, 'state', 'code'));
}
if (oauthToken === undefined) {
const errorMessage = 'Unable to get OAuth2 access tokens!';
this.logger.error(errorMessage, { credentialId });
return this.renderCallbackError(res, errorMessage);
}
if (decryptedDataOriginal.oauthTokenData) {
Object.assign(decryptedDataOriginal.oauthTokenData, oauthToken.data);
}
else {
decryptedDataOriginal.oauthTokenData = oauthToken.data;
}
delete decryptedDataOriginal.csrfSecret;
await this.encryptAndSaveData(credential, decryptedDataOriginal);
this.logger.verbose('OAuth2 callback successful for credential', {
credentialId,
});
return res.render('oauth-callback');
}
catch (error) {
return this.renderCallbackError(res, error.message, 'body' in error ? (0, n8n_workflow_1.jsonStringify)(error.body) : undefined);
}
}
convertCredentialToOptions(credential) {
var _a, _b, _c, _d, _e, _f, _g;
return {
clientId: credential.clientId,
clientSecret: (_a = credential.clientSecret) !== null && _a !== void 0 ? _a : '',
accessTokenUri: (_b = credential.accessTokenUrl) !== null && _b !== void 0 ? _b : '',
authorizationUri: (_c = credential.authUrl) !== null && _c !== void 0 ? _c : '',
authentication: (_d = credential.authentication) !== null && _d !== void 0 ? _d : 'header',
redirectUri: `${this.baseUrl}/callback`,
scopes: (0, split_1.default)((_e = credential.scope) !== null && _e !== void 0 ? _e : 'openid', ','),
scopesSeparator: ((_f = credential.scope) === null || _f === void 0 ? void 0 : _f.includes(',')) ? ',' : ' ',
ignoreSSLIssues: (_g = credential.ignoreSSLIssues) !== null && _g !== void 0 ? _g : false,
};
}
};
exports.OAuth2CredentialController = OAuth2CredentialController;
__decorate([
(0, decorators_1.Get)('/auth'),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", Promise)
], OAuth2CredentialController.prototype, "getAuthUri", null);
__decorate([
(0, decorators_1.Get)('/callback', { usesTemplates: true, skipAuth: true }),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], OAuth2CredentialController.prototype, "handleCallback", null);
exports.OAuth2CredentialController = OAuth2CredentialController = __decorate([
(0, decorators_1.RestController)('/oauth2-credential')
], OAuth2CredentialController);
//# sourceMappingURL=oAuth2Credential.controller.js.map
;