Skip to content

Commit

Permalink
Merge pull request #96 from friggframework/ironclad-and-slack-updates
Browse files Browse the repository at this point in the history
Ironclad and slack updates
  • Loading branch information
seanspeaks authored Jan 18, 2023
2 parents 9c65dbb + d11fd1a commit 117cd02
Show file tree
Hide file tree
Showing 7 changed files with 47 additions and 79 deletions.
4 changes: 2 additions & 2 deletions api-module-library/ironclad/manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ class Manager extends ModuleManager {
const subdomain = get(params, 'subdomain', null);
const subType = get(params, 'subType', null);

const search = await Entity.find({
const search = await Credential.find({
user: this.userId,
apiKey,
subType,
Expand Down Expand Up @@ -123,7 +123,7 @@ class Manager extends ModuleManager {
const apiKey = get(params, 'apiKey', null);
const name = get(params, 'name', null);
const subType = get(params, 'subType', null);
const externalId = createHash('sha256', apiKey);
const externalId = createHash('sha256').update(apiKey).digest('hex');

const search = await Entity.find({
user: this.userId,
Expand Down
12 changes: 12 additions & 0 deletions api-module-library/ironclad/test/manager.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,18 @@ describe(`Should fully test the ${config.label} Manager`, () => {
expect(e.message).to.contain('Auth Error');
}
});
it('should CastError', async () => {
try {
const authRes = await manager.processAuthorizationCallback({
data: {
subdomain: process.env.IRONCLAD_SUBDOMAIN,
},
});
expect(authRes).to.not.exist;
} catch (e) {
expect(e.message).to.contain('Auth Error');
}
});
});

describe('subType tests', () => {
Expand Down
18 changes: 9 additions & 9 deletions api-module-library/slack/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,39 +67,39 @@ class Api extends OAuth2Requester {
options.headers = await this.addAuthHeaders(options.headers);

const response = await this.fetch(encodedUrl, options);
const parsedResponse = await this.parsedBody(response);
const { status } = response;
const { ok } = response.body;
const { ok, error } = parsedResponse;

// If the status is retriable and there are back off requests left, retry the request
if ((status === 429 || status >= 500) && i < this.backOff.length) {
const delay = this.backOff[i] * 1000;
await new Promise((resolve) => setTimeout(resolve, delay));
return this._request(url, options, i + 1);
} else if (status === 401) {
} else if (
parsedResponse.error === 'invalid_auth' ||
parsedResponse.error === 'auth_expired'
) {
if (!this.isRefreshable || this.refreshCount > 0) {
await this.notify(this.DLGT_INVALID_AUTH);
} else {
this.refreshCount++;
// this.isRefreshable = false; // Set so that if we 401 during refresh request, we hit the above block
await this.refreshAuth();
// this.isRefreshable = true;// Set so that we can retry later? in case it's a fast expiring auth
this.refreshCount = 0;
return this._request(url, options, i + 1); // Retries
}
}

// If the error wasn't retried, throw.
if (status >= 400) {
if (!ok) {
throw await FetchError.create({
resource: encodedUrl,
init: options,
response,
body: parsedResponse,
});
}

return options.returnFullRes
? response
: await this.parsedBody(response);
return parsedResponse;
}

async addAuthHeaders(headers) {
Expand Down
54 changes: 3 additions & 51 deletions api-module-library/slack/authFields.js
Original file line number Diff line number Diff line change
@@ -1,54 +1,6 @@
const AuthFields = {
jsonSchema: {
type: 'object',
required: ['clientId', 'clientSecret'],
properties: {
clientId: {
type: 'string',
title: 'Client ID',
},
clientSecret: {
type: 'string',
title: 'Client Secret',
},
},
},
uiSchema: {
clientId: {
'ui:help':
'Your Client ID can be found under App Credentials on the Basic Information page for your App.',
'ui:placeholder': 'Client ID...',
},
clientSecret: {
'ui:widget': 'password',
'ui:help':
'Your Client Secret can be found in under App Credentials on the Basic Information page for your App.',
'ui:placeholder': 'Client Secret...',
},
},
jsonSchema: {},
uiSchema: {},
};

const ConfigFields = {
jsonSchema: {
type: 'object',
required: ['channel'],
properties: {
channel: {
type: 'string',
title: 'Post to Channel:',
enum: [
'#legal', // Call slack api for channels and add here
'#random',
],
},
},
},
uiSchema: {
channel: {
'ui:widget': 'select',
'ui:placeholder': 'Choose a #channel',
},
},
};

module.exports = { AuthFields, ConfigFields };
module.exports = { AuthFields };
17 changes: 9 additions & 8 deletions api-module-library/slack/manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,14 @@ class Manager extends ModuleManager {
return {
url: await this.api.getAuthUri(),
type: ModuleConstants.authType.oauth2,
data: {
jsonSchema: ConfigFields.jsonSchema,
uiSchema: ConfigFields.uiSchema,
},
data: {},
};
}

async testAuth() {
let validAuth = false;
try {
const authRes = await this.api.authTest();
if (authRes.ok) validAuth = true;
if (await this.api.authTest()) validAuth = true;
} catch (e) {
flushDebugLog(e);
}
Expand All @@ -66,7 +62,12 @@ class Manager extends ModuleManager {
const code = get(params.data, 'code', null);

// For OAuth2, generate the token and store in this.credential and the DB
await this.api.getTokenFromCode(code);

try {
await this.api.getTokenFromCode(code);
} catch (e) {
throw new Error('Auth Error');
}
const authRes = await this.testAuth();
if (!authRes) throw new Error('Auth Error');

Expand Down Expand Up @@ -94,7 +95,7 @@ class Manager extends ModuleManager {
const access_token = get(params, 'access_token', null);
const refresh_token = get(params, 'access_token', null);

const search = await Entity.find({
const search = await Credential.find({
user: this.userId,
});

Expand Down
18 changes: 10 additions & 8 deletions api-module-library/slack/test/manager.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const Authenticator = require('@friggframework/test-environment/Authenticator');
require('dotenv').config();

describe(`Should fully test the ${config.label} Manager`, () => {
let manager, userManager;
let manager, authUrl;

beforeAll(async () => {
await mongoose.connect(process.env.MONGO_URI);
Expand All @@ -25,28 +25,30 @@ describe(`Should fully test the ${config.label} Manager`, () => {
const requirements = await manager.getAuthorizationRequirements();
expect(requirements).exists;
expect(requirements.type).to.equal('oauth2');
authUrl = requirements.url;
});
describe('processAuthorizationCallback()', () => {
it.skip('should return client', async () => {
const requirements = await manager.getAuthorizationRequirements();
const { url } = requirements;
const response = await Authenticator.oauth2(url);
it('should return auth details', async () => {
const response = await Authenticator.oauth2(authUrl);
const baseArr = response.base.split('/');
response.entityType = baseArr[baseArr.length - 1];
delete response.base;
expect(requirements).exists;
expect(requirements.type).to.equal('oauth2');

const authRes = await manager.processAuthorizationCallback({
data: {
code: response.data.code,
},
});
expect(authRes).exists;
expect(authRes).to.exist;
expect(authRes).to.have.property('entity_id');
expect(authRes).to.have.property('credential_id');
expect(authRes).to.have.property('type');
});
it('should refresh token', async () => {
manager.api.access_token = 'nope';
await manager.testAuth();
expect(manager.api.access_token).to.not.equal('nope');
});
it('should error if incorrect auth data', async () => {
try {
const authRes = await manager.processAuthorizationCallback({
Expand Down
3 changes: 2 additions & 1 deletion packages/errors/fetch-error.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ class FetchError extends BaseError {

static async create(options = {}) {
const { response } = options;
const responseBody = response?.bodyUsed ? null : await response?.text();
let responseBody = response?.bodyUsed ? null : await response?.text();
if (!responseBody && options.body) responseBody = options.body;
return new FetchError({ ...options, responseBody });
}
}
Expand Down

0 comments on commit 117cd02

Please sign in to comment.