Compare commits
74 Commits
deployment
...
dependabot
Author | SHA1 | Date | |
---|---|---|---|
![]() |
06b99ac58a | ||
![]() |
f0e194e584 | ||
![]() |
d4b9331cf2 | ||
![]() |
4c49367910 | ||
![]() |
a506c4411d | ||
![]() |
1859c9854e | ||
![]() |
6ff29b9ae6 | ||
![]() |
3578f6b849 | ||
![]() |
0347864fde | ||
![]() |
5f9786a2c7 | ||
![]() |
75aeff1898 | ||
![]() |
0afcdce6d3 | ||
![]() |
a591d0ea87 | ||
![]() |
0e111a3532 | ||
![]() |
b599466ffa | ||
![]() |
69727e78df | ||
![]() |
02ae67b147 | ||
![]() |
a769f78801 | ||
![]() |
d583e42428 | ||
![]() |
da732becb6 | ||
![]() |
b89a4d58d9 | ||
![]() |
09854147d1 | ||
![]() |
3648c2bfe3 | ||
![]() |
3f3ee032f6 | ||
![]() |
68e5d54331 | ||
![]() |
824c434b0b | ||
![]() |
9f0e0ca656 | ||
![]() |
95f89ba03e | ||
![]() |
697f72ecf4 | ||
![]() |
4f03f2ab51 | ||
![]() |
c81531cb7a | ||
![]() |
7b6e4aa153 | ||
![]() |
f21039d19d | ||
![]() |
8c936a91be | ||
![]() |
24451892ff | ||
![]() |
6bba2c82fe | ||
![]() |
3320dc6bc4 | ||
![]() |
9d42fd9293 | ||
![]() |
e6b806616f | ||
![]() |
6ec5872391 | ||
![]() |
a26cf932a1 | ||
![]() |
38a3e3ab9f | ||
![]() |
32b17c1418 | ||
![]() |
44aa6a1579 | ||
![]() |
2369aacd2a | ||
![]() |
7dafc6364b | ||
![]() |
3d25fa0aeb | ||
![]() |
0297b0f296 | ||
![]() |
4c7d09c3d8 | ||
![]() |
48a74826e8 | ||
![]() |
ef34068ac4 | ||
![]() |
3987a8db77 | ||
![]() |
953c5a5b5b | ||
![]() |
4313265c00 | ||
![]() |
9405f267ba | ||
![]() |
1d29238199 | ||
![]() |
c5bf66f462 | ||
![]() |
e6180bdfaa | ||
![]() |
55c391afc8 | ||
![]() |
782fa67320 | ||
![]() |
1e3ab75bb7 | ||
![]() |
5f6dd12a73 | ||
![]() |
d18c06d2c4 | ||
![]() |
baf99a9cfe | ||
![]() |
159931a6ea | ||
![]() |
7831f2925b | ||
![]() |
8fcb7840de | ||
![]() |
9ece9461dc | ||
![]() |
b304acaaba | ||
![]() |
5a1960609a | ||
![]() |
476aa6e3aa | ||
![]() |
aa76007fd0 | ||
![]() |
17a8813c4b | ||
![]() |
fe79fc9003 |
@@ -8,7 +8,7 @@
|
||||
"version": "latest"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
"version": 16
|
||||
"version": 20
|
||||
},
|
||||
"ghcr.io/devcontainers/features/common-utils:1": {
|
||||
"username": "vscode",
|
||||
|
17
.github/workflows/ci.yml
vendored
17
.github/workflows/ci.yml
vendored
@@ -83,20 +83,3 @@ jobs:
|
||||
env:
|
||||
CI: false
|
||||
- run: echo "🍏 This job's status is ${{ job.status }}."
|
||||
build-cli:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: echo "🎉 The job was automatically triggered by a ${{ github.event_name }} event."
|
||||
- run: echo "🐧 This job is now running on a ${{ runner.os }} server hosted by GitHub!"
|
||||
- run: echo "🔎 The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}."
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: '18'
|
||||
cache: 'yarn'
|
||||
cache-dependency-path: yarn.lock
|
||||
- run: echo "💡 The ${{ github.repository }} repository has been cloned to the runner."
|
||||
- run: echo "🖥️ The workflow is now ready to test your code on the runner."
|
||||
- run: yarn --frozen-lockfile && yarn lerna bootstrap
|
||||
- run: cd packages/cli && yarn build
|
||||
- run: echo "🍏 This job's status is ${{ job.status }}."
|
||||
|
@@ -6,8 +6,7 @@
|
||||
"start": "lerna run --stream --parallel --scope=@*/{web,backend} dev",
|
||||
"start:web": "lerna run --stream --scope=@*/web dev",
|
||||
"start:backend": "lerna run --stream --scope=@*/backend dev",
|
||||
"lint": "lerna run --no-bail --stream --parallel --scope=@*/{web,backend,cli} lint",
|
||||
"build:watch": "lerna run --no-bail --stream --parallel --scope=@*/{web,backend,cli} build:watch",
|
||||
"lint": "lerna run --no-bail --stream --parallel --scope=@*/{web,backend} lint",
|
||||
"build:docs": "cd ./packages/docs && yarn install && yarn build"
|
||||
},
|
||||
"workspaces": {
|
||||
@@ -18,7 +17,6 @@
|
||||
"**/babel-loader",
|
||||
"**/webpack",
|
||||
"**/@automatisch/web",
|
||||
"**/@automatisch/types",
|
||||
"**/ajv"
|
||||
]
|
||||
},
|
||||
|
@@ -33,7 +33,6 @@
|
||||
"axios": "1.6.0",
|
||||
"bcrypt": "^5.0.1",
|
||||
"bullmq": "^3.0.0",
|
||||
"copyfiles": "^2.4.1",
|
||||
"cors": "^2.8.5",
|
||||
"crypto-js": "^4.1.1",
|
||||
"debug": "~2.6.9",
|
||||
@@ -45,7 +44,6 @@
|
||||
"graphql-middleware": "^6.1.15",
|
||||
"graphql-shield": "^7.5.0",
|
||||
"graphql-tools": "^8.2.0",
|
||||
"graphql-type-json": "^0.3.2",
|
||||
"handlebars": "^4.7.7",
|
||||
"http-errors": "~1.6.3",
|
||||
"http-proxy-agent": "^7.0.0",
|
||||
@@ -59,7 +57,7 @@
|
||||
"morgan": "^1.10.0",
|
||||
"multer": "1.4.5-lts.1",
|
||||
"node-html-markdown": "^1.3.0",
|
||||
"nodemailer": "6.7.0",
|
||||
"nodemailer": "6.9.9",
|
||||
"oauth-1.0a": "^2.2.6",
|
||||
"objection": "^3.0.0",
|
||||
"passport": "^0.6.0",
|
||||
@@ -68,7 +66,6 @@
|
||||
"pluralize": "^8.0.0",
|
||||
"raw-body": "^2.5.2",
|
||||
"showdown": "^2.1.0",
|
||||
"stripe": "^11.13.0",
|
||||
"winston": "^3.7.1",
|
||||
"xmlrpc": "^1.3.2"
|
||||
},
|
||||
|
@@ -1,5 +1,6 @@
|
||||
import defineAction from '../../../../helpers/define-action.js';
|
||||
|
||||
import base64ToString from './transformers/base64-to-string.js';
|
||||
import capitalize from './transformers/capitalize.js';
|
||||
import extractEmailAddress from './transformers/extract-email-address.js';
|
||||
import extractNumber from './transformers/extract-number.js';
|
||||
@@ -8,10 +9,12 @@ import lowercase from './transformers/lowercase.js';
|
||||
import markdownToHtml from './transformers/markdown-to-html.js';
|
||||
import pluralize from './transformers/pluralize.js';
|
||||
import replace from './transformers/replace.js';
|
||||
import stringToBase64 from './transformers/string-to-base64.js';
|
||||
import trimWhitespace from './transformers/trim-whitespace.js';
|
||||
import useDefaultValue from './transformers/use-default-value.js';
|
||||
|
||||
const transformers = {
|
||||
base64ToString,
|
||||
capitalize,
|
||||
extractEmailAddress,
|
||||
extractNumber,
|
||||
@@ -20,6 +23,7 @@ const transformers = {
|
||||
markdownToHtml,
|
||||
pluralize,
|
||||
replace,
|
||||
stringToBase64,
|
||||
trimWhitespace,
|
||||
useDefaultValue,
|
||||
};
|
||||
@@ -37,6 +41,7 @@ export default defineAction({
|
||||
required: true,
|
||||
variables: true,
|
||||
options: [
|
||||
{ label: 'Base64 to String', value: 'base64ToString' },
|
||||
{ label: 'Capitalize', value: 'capitalize' },
|
||||
{ label: 'Convert HTML to Markdown', value: 'htmlToMarkdown' },
|
||||
{ label: 'Convert Markdown to HTML', value: 'markdownToHtml' },
|
||||
@@ -45,6 +50,7 @@ export default defineAction({
|
||||
{ label: 'Lowercase', value: 'lowercase' },
|
||||
{ label: 'Pluralize', value: 'pluralize' },
|
||||
{ label: 'Replace', value: 'replace' },
|
||||
{ label: 'String to Base64', value: 'stringToBase64' },
|
||||
{ label: 'Trim Whitespace', value: 'trimWhitespace' },
|
||||
{ label: 'Use Default Value', value: 'useDefaultValue' },
|
||||
],
|
||||
|
@@ -0,0 +1,8 @@
|
||||
const base64ToString = ($) => {
|
||||
const input = $.step.parameters.input;
|
||||
const decodedString = Buffer.from(input, 'base64').toString('utf8');
|
||||
|
||||
return decodedString;
|
||||
};
|
||||
|
||||
export default base64ToString;
|
@@ -0,0 +1,8 @@
|
||||
const stringtoBase64 = ($) => {
|
||||
const input = $.step.parameters.input;
|
||||
const base64String = Buffer.from(input).toString('base64');
|
||||
|
||||
return base64String;
|
||||
};
|
||||
|
||||
export default stringtoBase64;
|
@@ -1,3 +1,4 @@
|
||||
import base64ToString from './text/base64-to-string.js';
|
||||
import capitalize from './text/capitalize.js';
|
||||
import extractEmailAddress from './text/extract-email-address.js';
|
||||
import extractNumber from './text/extract-number.js';
|
||||
@@ -6,6 +7,7 @@ import lowercase from './text/lowercase.js';
|
||||
import markdownToHtml from './text/markdown-to-html.js';
|
||||
import pluralize from './text/pluralize.js';
|
||||
import replace from './text/replace.js';
|
||||
import stringToBase64 from './text/string-to-base64.js';
|
||||
import trimWhitespace from './text/trim-whitespace.js';
|
||||
import useDefaultValue from './text/use-default-value.js';
|
||||
import performMathOperation from './numbers/perform-math-operation.js';
|
||||
@@ -15,6 +17,7 @@ import formatPhoneNumber from './numbers/format-phone-number.js';
|
||||
import formatDateTime from './date-time/format-date-time.js';
|
||||
|
||||
const options = {
|
||||
base64ToString,
|
||||
capitalize,
|
||||
extractEmailAddress,
|
||||
extractNumber,
|
||||
@@ -23,6 +26,7 @@ const options = {
|
||||
markdownToHtml,
|
||||
pluralize,
|
||||
replace,
|
||||
stringToBase64,
|
||||
trimWhitespace,
|
||||
useDefaultValue,
|
||||
performMathOperation,
|
||||
|
@@ -0,0 +1,12 @@
|
||||
const base64ToString = [
|
||||
{
|
||||
label: 'Input',
|
||||
key: 'input',
|
||||
type: 'string',
|
||||
required: true,
|
||||
description: 'Text that will be converted from Base64 to string.',
|
||||
variables: true,
|
||||
},
|
||||
];
|
||||
|
||||
export default base64ToString;
|
@@ -0,0 +1,12 @@
|
||||
const stringToBase64 = [
|
||||
{
|
||||
label: 'Input',
|
||||
key: 'input',
|
||||
type: 'string',
|
||||
required: true,
|
||||
description: 'Text that will be converted to Base64.',
|
||||
variables: true,
|
||||
},
|
||||
];
|
||||
|
||||
export default stringToBase64;
|
@@ -18,7 +18,9 @@ const port = process.env.PORT || '3000';
|
||||
const serveWebAppSeparately =
|
||||
process.env.SERVE_WEB_APP_SEPARATELY === 'true' ? true : false;
|
||||
|
||||
let apiUrl = new URL(`${protocol}://${host}:${port}`).toString();
|
||||
let apiUrl = new URL(
|
||||
process.env.API_URL || `${protocol}://${host}:${port}`
|
||||
).toString();
|
||||
apiUrl = apiUrl.substring(0, apiUrl.length - 1);
|
||||
|
||||
// use apiUrl by default, which has less priority over the following cases
|
||||
@@ -88,6 +90,10 @@ const appConfig = {
|
||||
licenseKey: process.env.LICENSE_KEY,
|
||||
sentryDsn: process.env.SENTRY_DSN,
|
||||
CI: process.env.CI === 'true',
|
||||
disableNotificationsPage: process.env.DISABLE_NOTIFICATIONS_PAGE === 'true',
|
||||
disableFavicon: process.env.DISABLE_FAVICON === 'true',
|
||||
additionalDrawerLink: process.env.ADDITIONAL_DRAWER_LINK,
|
||||
additionalDrawerLinkText: process.env.ADDITIONAL_DRAWER_LINK_TEXT,
|
||||
};
|
||||
|
||||
if (!appConfig.encryptionKey) {
|
||||
|
@@ -0,0 +1,6 @@
|
||||
import appConfig from '../../../../config/app.js';
|
||||
import { renderObject } from '../../../../helpers/renderer.js';
|
||||
|
||||
export default async (request, response) => {
|
||||
renderObject(response, { version: appConfig.version });
|
||||
};
|
@@ -0,0 +1,26 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import app from '../../../../app.js';
|
||||
|
||||
describe('GET /api/v1/automatisch/version', () => {
|
||||
it('should return Automatisch version', async () => {
|
||||
const response = await request(app)
|
||||
.get('/api/v1/automatisch/version')
|
||||
.expect(200);
|
||||
|
||||
const expectedPayload = {
|
||||
data: {
|
||||
version: '0.10.0',
|
||||
},
|
||||
meta: {
|
||||
count: 1,
|
||||
currentPage: null,
|
||||
isArray: false,
|
||||
totalPages: null,
|
||||
type: 'Object',
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedPayload);
|
||||
});
|
||||
});
|
@@ -0,0 +1,5 @@
|
||||
import { renderObject } from '../../../../helpers/renderer.js';
|
||||
|
||||
export default async (request, response) => {
|
||||
renderObject(response, request.currentUser);
|
||||
};
|
@@ -0,0 +1,26 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import app from '../../../../app.js';
|
||||
import createAuthTokenByUserId from '../../../../helpers/create-auth-token-by-user-id';
|
||||
import { createUser } from '../../../../../test/factories/user';
|
||||
import getCurrentUserMock from '../../../../../test/mocks/rest/api/v1/users/get-current-user';
|
||||
|
||||
describe('GET /api/v1/users/me', () => {
|
||||
let role, currentUser, token;
|
||||
|
||||
beforeEach(async () => {
|
||||
currentUser = await createUser();
|
||||
role = await currentUser.$relatedQuery('role');
|
||||
token = createAuthTokenByUserId(currentUser.id);
|
||||
});
|
||||
|
||||
it('should return current user info', async () => {
|
||||
const response = await request(app)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', token)
|
||||
.expect(200);
|
||||
|
||||
const expectedPayload = getCurrentUserMock(currentUser, role);
|
||||
expect(response.body).toEqual(expectedPayload);
|
||||
});
|
||||
});
|
@@ -0,0 +1,12 @@
|
||||
import { renderObject } from '../../../../helpers/renderer.js';
|
||||
|
||||
export default async (request, response) => {
|
||||
const inTrial = await request.currentUser.inTrial();
|
||||
|
||||
const trialInfo = {
|
||||
inTrial,
|
||||
expireAt: request.currentUser.trialExpiryDate,
|
||||
};
|
||||
|
||||
renderObject(response, trialInfo);
|
||||
};
|
@@ -0,0 +1,38 @@
|
||||
import { vi, describe, it, expect, beforeEach } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import app from '../../../../app.js';
|
||||
import createAuthTokenByUserId from '../../../../helpers/create-auth-token-by-user-id.js';
|
||||
import { createUser } from '../../../../../test/factories/user.js';
|
||||
import getUserTrialMock from '../../../../../test/mocks/rest/api/v1/users/get-user-trial.js';
|
||||
import appConfig from '../../../../config/app.js';
|
||||
import { DateTime } from 'luxon';
|
||||
import User from '../../../../models/user.js';
|
||||
|
||||
describe('GET /api/v1/users/:userId/trial', () => {
|
||||
let user, token;
|
||||
|
||||
beforeEach(async () => {
|
||||
const trialExpiryDate = DateTime.now().plus({ days: 30 }).toISODate();
|
||||
user = await createUser({ trialExpiryDate });
|
||||
token = createAuthTokenByUserId(user.id);
|
||||
|
||||
vi.spyOn(appConfig, 'isCloud', 'get').mockReturnValue(true);
|
||||
});
|
||||
|
||||
describe('should return in trial, active subscription and expire at info', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(User.prototype, 'inTrial').mockResolvedValue(false);
|
||||
vi.spyOn(User.prototype, 'hasActiveSubscription').mockResolvedValue(true);
|
||||
});
|
||||
|
||||
it('should return null', async () => {
|
||||
const response = await request(app)
|
||||
.get(`/api/v1/users/${user.id}/trial`)
|
||||
.set('Authorization', token)
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = await getUserTrialMock(user);
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
});
|
||||
});
|
16
packages/backend/src/controllers/api/v1/users/get-user.js
Normal file
16
packages/backend/src/controllers/api/v1/users/get-user.js
Normal file
@@ -0,0 +1,16 @@
|
||||
import { renderObject } from '../../../../helpers/renderer.js';
|
||||
import User from '../../../../models/user.js';
|
||||
|
||||
export default async (request, response) => {
|
||||
const user = await User.query()
|
||||
.leftJoinRelated({
|
||||
role: true,
|
||||
})
|
||||
.withGraphFetched({
|
||||
role: true,
|
||||
})
|
||||
.findById(request.params.userId)
|
||||
.throwIfNotFound();
|
||||
|
||||
renderObject(response, user);
|
||||
};
|
@@ -0,0 +1,36 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import app from '../../../../app.js';
|
||||
import createAuthTokenByUserId from '../../../../helpers/create-auth-token-by-user-id';
|
||||
import { createUser } from '../../../../../test/factories/user';
|
||||
import { createPermission } from '../../../../../test/factories/permission';
|
||||
import getUserMock from '../../../../../test/mocks/rest/api/v1/users/get-user';
|
||||
|
||||
describe('GET /api/v1/users/:userId', () => {
|
||||
let currentUser, currentUserRole, anotherUser, anotherUserRole, token;
|
||||
|
||||
beforeEach(async () => {
|
||||
currentUser = await createUser();
|
||||
anotherUser = await createUser();
|
||||
currentUserRole = await currentUser.$relatedQuery('role');
|
||||
anotherUserRole = await anotherUser.$relatedQuery('role');
|
||||
|
||||
await createPermission({
|
||||
roleId: currentUserRole.id,
|
||||
action: 'read',
|
||||
subject: 'User',
|
||||
});
|
||||
|
||||
token = createAuthTokenByUserId(currentUser.id);
|
||||
});
|
||||
|
||||
it('should return specified user info', async () => {
|
||||
const response = await request(app)
|
||||
.get(`/api/v1/users/${anotherUser.id}`)
|
||||
.set('Authorization', token)
|
||||
.expect(200);
|
||||
|
||||
const expectedPayload = getUserMock(anotherUser, anotherUserRole);
|
||||
expect(response.body).toEqual(expectedPayload);
|
||||
});
|
||||
});
|
18
packages/backend/src/controllers/api/v1/users/get-users.js
Normal file
18
packages/backend/src/controllers/api/v1/users/get-users.js
Normal file
@@ -0,0 +1,18 @@
|
||||
import { renderObject } from '../../../../helpers/renderer.js';
|
||||
import User from '../../../../models/user.js';
|
||||
import paginateRest from '../../../../helpers/pagination-rest.js';
|
||||
|
||||
export default async (request, response) => {
|
||||
const usersQuery = User.query()
|
||||
.leftJoinRelated({
|
||||
role: true,
|
||||
})
|
||||
.withGraphFetched({
|
||||
role: true,
|
||||
})
|
||||
.orderBy('full_name', 'asc');
|
||||
|
||||
const users = await paginateRest(usersQuery, request.query.page);
|
||||
|
||||
renderObject(response, users);
|
||||
};
|
@@ -0,0 +1,56 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import app from '../../../../app';
|
||||
import createAuthTokenByUserId from '../../../../helpers/create-auth-token-by-user-id';
|
||||
import { createRole } from '../../../../../test/factories/role';
|
||||
import { createPermission } from '../../../../../test/factories/permission';
|
||||
import { createUser } from '../../../../../test/factories/user';
|
||||
import getUsersMock from '../../../../../test/mocks/rest/api/v1/users/get-users';
|
||||
|
||||
describe('GET /api/v1/users', () => {
|
||||
let currentUser, currentUserRole, anotherUser, anotherUserRole, token;
|
||||
|
||||
beforeEach(async () => {
|
||||
currentUserRole = await createRole({
|
||||
key: 'currentUser',
|
||||
name: 'Current user role',
|
||||
});
|
||||
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'User',
|
||||
roleId: currentUserRole.id,
|
||||
});
|
||||
|
||||
currentUser = await createUser({
|
||||
roleId: currentUserRole.id,
|
||||
fullName: 'Current User',
|
||||
});
|
||||
|
||||
anotherUserRole = await createRole({
|
||||
key: 'anotherUser',
|
||||
name: 'Another user role',
|
||||
});
|
||||
|
||||
anotherUser = await createUser({
|
||||
roleId: anotherUserRole.id,
|
||||
fullName: 'Another User',
|
||||
});
|
||||
|
||||
token = createAuthTokenByUserId(currentUser.id);
|
||||
});
|
||||
|
||||
it('should return users data', async () => {
|
||||
const response = await request(app)
|
||||
.get('/api/v1/users')
|
||||
.set('Authorization', token)
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = await getUsersMock(
|
||||
[anotherUser, currentUser],
|
||||
[anotherUserRole, currentUserRole]
|
||||
);
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
});
|
3
packages/backend/src/controllers/healthcheck/index.js
Normal file
3
packages/backend/src/controllers/healthcheck/index.js
Normal file
@@ -0,0 +1,3 @@
|
||||
export default async (request, response) => {
|
||||
response.status(200).end();
|
||||
};
|
@@ -0,0 +1,9 @@
|
||||
import { describe, it } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import app from '../../app.js';
|
||||
|
||||
describe('GET /healthcheck', () => {
|
||||
it('should return 200 response with version data', async () => {
|
||||
await request(app).get('/healthcheck').expect(200);
|
||||
});
|
||||
});
|
@@ -1,7 +1,10 @@
|
||||
import appConfig from '../../config/app.js';
|
||||
import User from '../../models/user.js';
|
||||
import Role from '../../models/role.js';
|
||||
|
||||
const registerUser = async (_parent, params) => {
|
||||
if (!appConfig.isCloud) return;
|
||||
|
||||
const { fullName, email, password } = params.input;
|
||||
|
||||
const existingUser = await User.query().findOne({
|
||||
|
@@ -1,9 +1,17 @@
|
||||
import appConfig from '../../config/app.js';
|
||||
import { hasValidLicense } from '../../helpers/license.ee.js';
|
||||
import Config from '../../models/config.js';
|
||||
|
||||
const getConfig = async (_parent, params) => {
|
||||
if (!(await hasValidLicense())) return {};
|
||||
|
||||
const defaultConfig = {
|
||||
disableNotificationsPage: appConfig.disableNotificationsPage,
|
||||
disableFavicon: appConfig.disableFavicon,
|
||||
additionalDrawerLink: appConfig.additionalDrawerLink,
|
||||
additionalDrawerLinkText: appConfig.additionalDrawerLinkText,
|
||||
};
|
||||
|
||||
const configQuery = Config.query();
|
||||
|
||||
if (Array.isArray(params.keys)) {
|
||||
@@ -18,7 +26,7 @@ const getConfig = async (_parent, params) => {
|
||||
computedConfig[key] = value?.data;
|
||||
|
||||
return computedConfig;
|
||||
}, {});
|
||||
}, defaultConfig);
|
||||
};
|
||||
|
||||
export default getConfig;
|
||||
|
@@ -2,6 +2,7 @@ import { vi, describe, it, expect, beforeEach } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import app from '../../app';
|
||||
import { createConfig } from '../../../test/factories/config';
|
||||
import appConfig from '../../config/app';
|
||||
import * as license from '../../helpers/license.ee';
|
||||
|
||||
describe('graphQL getConfig query', () => {
|
||||
@@ -56,6 +57,10 @@ describe('graphQL getConfig query', () => {
|
||||
[configOne.key]: configOne.value.data,
|
||||
[configTwo.key]: configTwo.value.data,
|
||||
[configThree.key]: configThree.value.data,
|
||||
disableNotificationsPage: false,
|
||||
disableFavicon: false,
|
||||
additionalDrawerLink: undefined,
|
||||
additionalDrawerLinkText: undefined,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -82,6 +87,48 @@ describe('graphQL getConfig query', () => {
|
||||
getConfig: {
|
||||
[configOne.key]: configOne.value.data,
|
||||
[configTwo.key]: configTwo.value.data,
|
||||
disableNotificationsPage: false,
|
||||
disableFavicon: false,
|
||||
additionalDrawerLink: undefined,
|
||||
additionalDrawerLinkText: undefined,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
});
|
||||
|
||||
describe('and with different defaults', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(appConfig, 'disableNotificationsPage', 'get').mockReturnValue(
|
||||
true
|
||||
);
|
||||
vi.spyOn(appConfig, 'disableFavicon', 'get').mockReturnValue(true);
|
||||
vi.spyOn(appConfig, 'additionalDrawerLink', 'get').mockReturnValue(
|
||||
'https://automatisch.io'
|
||||
);
|
||||
vi.spyOn(appConfig, 'additionalDrawerLinkText', 'get').mockReturnValue(
|
||||
'Automatisch'
|
||||
);
|
||||
});
|
||||
|
||||
it('should return custom config', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getConfig: {
|
||||
[configOne.key]: configOne.value.data,
|
||||
[configTwo.key]: configTwo.value.data,
|
||||
[configThree.key]: configThree.value.data,
|
||||
disableNotificationsPage: true,
|
||||
disableFavicon: true,
|
||||
additionalDrawerLink: 'https://automatisch.io',
|
||||
additionalDrawerLinkText: 'Automatisch',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
@@ -6,100 +6,74 @@ import { createRole } from '../../../test/factories/role';
|
||||
import { createUser } from '../../../test/factories/user';
|
||||
|
||||
describe('graphQL getCurrentUser query', () => {
|
||||
describe('with unauthenticated user', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const invalidUserToken = 'invalid-token';
|
||||
let role, currentUser, token, requestObject;
|
||||
|
||||
const query = `
|
||||
query {
|
||||
getCurrentUser {
|
||||
id
|
||||
email
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', invalidUserToken)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not Authorised!');
|
||||
beforeEach(async () => {
|
||||
role = await createRole({
|
||||
key: 'sample',
|
||||
name: 'sample',
|
||||
});
|
||||
|
||||
currentUser = await createUser({
|
||||
roleId: role.id,
|
||||
});
|
||||
|
||||
token = createAuthTokenByUserId(currentUser.id);
|
||||
requestObject = request(app).post('/graphql').set('Authorization', token);
|
||||
});
|
||||
|
||||
describe('with authenticated user', () => {
|
||||
let role, currentUser, token, requestObject;
|
||||
|
||||
beforeEach(async () => {
|
||||
role = await createRole({
|
||||
key: 'sample',
|
||||
name: 'sample',
|
||||
});
|
||||
|
||||
currentUser = await createUser({
|
||||
roleId: role.id,
|
||||
});
|
||||
|
||||
token = createAuthTokenByUserId(currentUser.id);
|
||||
requestObject = request(app).post('/graphql').set('Authorization', token);
|
||||
});
|
||||
|
||||
it('should return user data', async () => {
|
||||
const query = `
|
||||
query {
|
||||
getCurrentUser {
|
||||
it('should return user data', async () => {
|
||||
const query = `
|
||||
query {
|
||||
getCurrentUser {
|
||||
id
|
||||
email
|
||||
fullName
|
||||
email
|
||||
createdAt
|
||||
updatedAt
|
||||
role {
|
||||
id
|
||||
email
|
||||
fullName
|
||||
email
|
||||
createdAt
|
||||
updatedAt
|
||||
role {
|
||||
id
|
||||
name
|
||||
}
|
||||
name
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await requestObject.send({ query }).expect(200);
|
||||
const response = await requestObject.send({ query }).expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getCurrentUser: {
|
||||
createdAt: currentUser.createdAt.getTime().toString(),
|
||||
email: currentUser.email,
|
||||
fullName: currentUser.fullName,
|
||||
id: currentUser.id,
|
||||
role: { id: role.id, name: role.name },
|
||||
updatedAt: currentUser.updatedAt.getTime().toString(),
|
||||
},
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getCurrentUser: {
|
||||
createdAt: currentUser.createdAt.getTime().toString(),
|
||||
email: currentUser.email,
|
||||
fullName: currentUser.fullName,
|
||||
id: currentUser.id,
|
||||
role: { id: role.id, name: role.name },
|
||||
updatedAt: currentUser.updatedAt.getTime().toString(),
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
|
||||
it('should not return user password', async () => {
|
||||
const query = `
|
||||
query {
|
||||
getCurrentUser {
|
||||
id
|
||||
email
|
||||
password
|
||||
}
|
||||
it('should not return user password', async () => {
|
||||
const query = `
|
||||
query {
|
||||
getCurrentUser {
|
||||
id
|
||||
email
|
||||
password
|
||||
}
|
||||
`;
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await requestObject.send({ query }).expect(400);
|
||||
const response = await requestObject.send({ query }).expect(400);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual(
|
||||
'Cannot query field "password" on type "User".'
|
||||
);
|
||||
});
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual(
|
||||
'Cannot query field "password" on type "User".'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
@@ -40,307 +40,291 @@ describe('graphQL getExecutions query', () => {
|
||||
}
|
||||
`;
|
||||
|
||||
const invalidToken = 'invalid-token';
|
||||
|
||||
describe('with unauthenticated user', () => {
|
||||
describe('and without correct permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const userWithoutPermissions = await createUser();
|
||||
const token = createAuthTokenByUserId(userWithoutPermissions.id);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', invalidToken)
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not Authorised!');
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
});
|
||||
});
|
||||
|
||||
describe('with authenticated user', () => {
|
||||
describe('and without permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const userWithoutPermissions = await createUser();
|
||||
const token = createAuthTokenByUserId(userWithoutPermissions.id);
|
||||
describe('and with correct permission', () => {
|
||||
let role,
|
||||
currentUser,
|
||||
anotherUser,
|
||||
token,
|
||||
flowOne,
|
||||
stepOneForFlowOne,
|
||||
stepTwoForFlowOne,
|
||||
executionOne,
|
||||
flowTwo,
|
||||
stepOneForFlowTwo,
|
||||
stepTwoForFlowTwo,
|
||||
executionTwo,
|
||||
flowThree,
|
||||
stepOneForFlowThree,
|
||||
stepTwoForFlowThree,
|
||||
executionThree,
|
||||
expectedResponseForExecutionOne,
|
||||
expectedResponseForExecutionTwo,
|
||||
expectedResponseForExecutionThree;
|
||||
|
||||
beforeEach(async () => {
|
||||
role = await createRole({
|
||||
key: 'sample',
|
||||
name: 'sample',
|
||||
});
|
||||
|
||||
currentUser = await createUser({
|
||||
roleId: role.id,
|
||||
fullName: 'Current User',
|
||||
});
|
||||
|
||||
anotherUser = await createUser();
|
||||
|
||||
token = createAuthTokenByUserId(currentUser.id);
|
||||
|
||||
flowOne = await createFlow({
|
||||
userId: currentUser.id,
|
||||
});
|
||||
|
||||
stepOneForFlowOne = await createStep({
|
||||
flowId: flowOne.id,
|
||||
});
|
||||
|
||||
stepTwoForFlowOne = await createStep({
|
||||
flowId: flowOne.id,
|
||||
});
|
||||
|
||||
executionOne = await createExecution({
|
||||
flowId: flowOne.id,
|
||||
});
|
||||
|
||||
await createExecutionStep({
|
||||
executionId: executionOne.id,
|
||||
stepId: stepOneForFlowOne.id,
|
||||
status: 'success',
|
||||
});
|
||||
|
||||
await createExecutionStep({
|
||||
executionId: executionOne.id,
|
||||
stepId: stepTwoForFlowOne.id,
|
||||
status: 'success',
|
||||
});
|
||||
|
||||
flowTwo = await createFlow({
|
||||
userId: currentUser.id,
|
||||
});
|
||||
|
||||
stepOneForFlowTwo = await createStep({
|
||||
flowId: flowTwo.id,
|
||||
});
|
||||
|
||||
stepTwoForFlowTwo = await createStep({
|
||||
flowId: flowTwo.id,
|
||||
});
|
||||
|
||||
executionTwo = await createExecution({
|
||||
flowId: flowTwo.id,
|
||||
});
|
||||
|
||||
await createExecutionStep({
|
||||
executionId: executionTwo.id,
|
||||
stepId: stepOneForFlowTwo.id,
|
||||
status: 'success',
|
||||
});
|
||||
|
||||
await createExecutionStep({
|
||||
executionId: executionTwo.id,
|
||||
stepId: stepTwoForFlowTwo.id,
|
||||
status: 'failure',
|
||||
});
|
||||
|
||||
flowThree = await createFlow({
|
||||
userId: anotherUser.id,
|
||||
});
|
||||
|
||||
stepOneForFlowThree = await createStep({
|
||||
flowId: flowThree.id,
|
||||
});
|
||||
|
||||
stepTwoForFlowThree = await createStep({
|
||||
flowId: flowThree.id,
|
||||
});
|
||||
|
||||
executionThree = await createExecution({
|
||||
flowId: flowThree.id,
|
||||
});
|
||||
|
||||
await createExecutionStep({
|
||||
executionId: executionThree.id,
|
||||
stepId: stepOneForFlowThree.id,
|
||||
status: 'success',
|
||||
});
|
||||
|
||||
await createExecutionStep({
|
||||
executionId: executionThree.id,
|
||||
stepId: stepTwoForFlowThree.id,
|
||||
status: 'failure',
|
||||
});
|
||||
|
||||
expectedResponseForExecutionOne = {
|
||||
node: {
|
||||
createdAt: executionOne.createdAt.getTime().toString(),
|
||||
flow: {
|
||||
active: flowOne.active,
|
||||
id: flowOne.id,
|
||||
name: flowOne.name,
|
||||
steps: [
|
||||
{
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${stepOneForFlowOne.appKey}/assets/favicon.svg`,
|
||||
},
|
||||
{
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${stepTwoForFlowOne.appKey}/assets/favicon.svg`,
|
||||
},
|
||||
],
|
||||
},
|
||||
id: executionOne.id,
|
||||
status: 'success',
|
||||
testRun: executionOne.testRun,
|
||||
updatedAt: executionOne.updatedAt.getTime().toString(),
|
||||
},
|
||||
};
|
||||
|
||||
expectedResponseForExecutionTwo = {
|
||||
node: {
|
||||
createdAt: executionTwo.createdAt.getTime().toString(),
|
||||
flow: {
|
||||
active: flowTwo.active,
|
||||
id: flowTwo.id,
|
||||
name: flowTwo.name,
|
||||
steps: [
|
||||
{
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${stepTwoForFlowTwo.appKey}/assets/favicon.svg`,
|
||||
},
|
||||
{
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${stepTwoForFlowTwo.appKey}/assets/favicon.svg`,
|
||||
},
|
||||
],
|
||||
},
|
||||
id: executionTwo.id,
|
||||
status: 'failure',
|
||||
testRun: executionTwo.testRun,
|
||||
updatedAt: executionTwo.updatedAt.getTime().toString(),
|
||||
},
|
||||
};
|
||||
|
||||
expectedResponseForExecutionThree = {
|
||||
node: {
|
||||
createdAt: executionThree.createdAt.getTime().toString(),
|
||||
flow: {
|
||||
active: flowThree.active,
|
||||
id: flowThree.id,
|
||||
name: flowThree.name,
|
||||
steps: [
|
||||
{
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${stepOneForFlowThree.appKey}/assets/favicon.svg`,
|
||||
},
|
||||
{
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${stepTwoForFlowThree.appKey}/assets/favicon.svg`,
|
||||
},
|
||||
],
|
||||
},
|
||||
id: executionThree.id,
|
||||
status: 'failure',
|
||||
testRun: executionThree.testRun,
|
||||
updatedAt: executionThree.updatedAt.getTime().toString(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
describe('and with isCreator condition', () => {
|
||||
beforeEach(async () => {
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'Execution',
|
||||
roleId: role.id,
|
||||
conditions: ['isCreator'],
|
||||
});
|
||||
});
|
||||
|
||||
it('should return executions data of the current user', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getExecutions: {
|
||||
edges: [
|
||||
expectedResponseForExecutionTwo,
|
||||
expectedResponseForExecutionOne,
|
||||
],
|
||||
pageInfo: { currentPage: 1, totalPages: 1 },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
});
|
||||
|
||||
describe('and with correct permission', () => {
|
||||
let role,
|
||||
currentUser,
|
||||
anotherUser,
|
||||
token,
|
||||
flowOne,
|
||||
stepOneForFlowOne,
|
||||
stepTwoForFlowOne,
|
||||
executionOne,
|
||||
flowTwo,
|
||||
stepOneForFlowTwo,
|
||||
stepTwoForFlowTwo,
|
||||
executionTwo,
|
||||
flowThree,
|
||||
stepOneForFlowThree,
|
||||
stepTwoForFlowThree,
|
||||
executionThree,
|
||||
expectedResponseForExecutionOne,
|
||||
expectedResponseForExecutionTwo,
|
||||
expectedResponseForExecutionThree;
|
||||
|
||||
describe('and without isCreator condition', () => {
|
||||
beforeEach(async () => {
|
||||
role = await createRole({
|
||||
key: 'sample',
|
||||
name: 'sample',
|
||||
});
|
||||
|
||||
currentUser = await createUser({
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'Execution',
|
||||
roleId: role.id,
|
||||
fullName: 'Current User',
|
||||
});
|
||||
|
||||
anotherUser = await createUser();
|
||||
|
||||
token = createAuthTokenByUserId(currentUser.id);
|
||||
|
||||
flowOne = await createFlow({
|
||||
userId: currentUser.id,
|
||||
});
|
||||
|
||||
stepOneForFlowOne = await createStep({
|
||||
flowId: flowOne.id,
|
||||
});
|
||||
|
||||
stepTwoForFlowOne = await createStep({
|
||||
flowId: flowOne.id,
|
||||
});
|
||||
|
||||
executionOne = await createExecution({
|
||||
flowId: flowOne.id,
|
||||
});
|
||||
|
||||
await createExecutionStep({
|
||||
executionId: executionOne.id,
|
||||
stepId: stepOneForFlowOne.id,
|
||||
status: 'success',
|
||||
});
|
||||
|
||||
await createExecutionStep({
|
||||
executionId: executionOne.id,
|
||||
stepId: stepTwoForFlowOne.id,
|
||||
status: 'success',
|
||||
});
|
||||
|
||||
flowTwo = await createFlow({
|
||||
userId: currentUser.id,
|
||||
});
|
||||
|
||||
stepOneForFlowTwo = await createStep({
|
||||
flowId: flowTwo.id,
|
||||
});
|
||||
|
||||
stepTwoForFlowTwo = await createStep({
|
||||
flowId: flowTwo.id,
|
||||
});
|
||||
|
||||
executionTwo = await createExecution({
|
||||
flowId: flowTwo.id,
|
||||
});
|
||||
|
||||
await createExecutionStep({
|
||||
executionId: executionTwo.id,
|
||||
stepId: stepOneForFlowTwo.id,
|
||||
status: 'success',
|
||||
});
|
||||
|
||||
await createExecutionStep({
|
||||
executionId: executionTwo.id,
|
||||
stepId: stepTwoForFlowTwo.id,
|
||||
status: 'failure',
|
||||
});
|
||||
|
||||
flowThree = await createFlow({
|
||||
userId: anotherUser.id,
|
||||
});
|
||||
|
||||
stepOneForFlowThree = await createStep({
|
||||
flowId: flowThree.id,
|
||||
});
|
||||
|
||||
stepTwoForFlowThree = await createStep({
|
||||
flowId: flowThree.id,
|
||||
});
|
||||
|
||||
executionThree = await createExecution({
|
||||
flowId: flowThree.id,
|
||||
});
|
||||
|
||||
await createExecutionStep({
|
||||
executionId: executionThree.id,
|
||||
stepId: stepOneForFlowThree.id,
|
||||
status: 'success',
|
||||
});
|
||||
|
||||
await createExecutionStep({
|
||||
executionId: executionThree.id,
|
||||
stepId: stepTwoForFlowThree.id,
|
||||
status: 'failure',
|
||||
});
|
||||
|
||||
expectedResponseForExecutionOne = {
|
||||
node: {
|
||||
createdAt: executionOne.createdAt.getTime().toString(),
|
||||
flow: {
|
||||
active: flowOne.active,
|
||||
id: flowOne.id,
|
||||
name: flowOne.name,
|
||||
steps: [
|
||||
{
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${stepOneForFlowOne.appKey}/assets/favicon.svg`,
|
||||
},
|
||||
{
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${stepTwoForFlowOne.appKey}/assets/favicon.svg`,
|
||||
},
|
||||
],
|
||||
},
|
||||
id: executionOne.id,
|
||||
status: 'success',
|
||||
testRun: executionOne.testRun,
|
||||
updatedAt: executionOne.updatedAt.getTime().toString(),
|
||||
},
|
||||
};
|
||||
|
||||
expectedResponseForExecutionTwo = {
|
||||
node: {
|
||||
createdAt: executionTwo.createdAt.getTime().toString(),
|
||||
flow: {
|
||||
active: flowTwo.active,
|
||||
id: flowTwo.id,
|
||||
name: flowTwo.name,
|
||||
steps: [
|
||||
{
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${stepTwoForFlowTwo.appKey}/assets/favicon.svg`,
|
||||
},
|
||||
{
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${stepTwoForFlowTwo.appKey}/assets/favicon.svg`,
|
||||
},
|
||||
],
|
||||
},
|
||||
id: executionTwo.id,
|
||||
status: 'failure',
|
||||
testRun: executionTwo.testRun,
|
||||
updatedAt: executionTwo.updatedAt.getTime().toString(),
|
||||
},
|
||||
};
|
||||
|
||||
expectedResponseForExecutionThree = {
|
||||
node: {
|
||||
createdAt: executionThree.createdAt.getTime().toString(),
|
||||
flow: {
|
||||
active: flowThree.active,
|
||||
id: flowThree.id,
|
||||
name: flowThree.name,
|
||||
steps: [
|
||||
{
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${stepOneForFlowThree.appKey}/assets/favicon.svg`,
|
||||
},
|
||||
{
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${stepTwoForFlowThree.appKey}/assets/favicon.svg`,
|
||||
},
|
||||
],
|
||||
},
|
||||
id: executionThree.id,
|
||||
status: 'failure',
|
||||
testRun: executionThree.testRun,
|
||||
updatedAt: executionThree.updatedAt.getTime().toString(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
describe('and with isCreator condition', () => {
|
||||
beforeEach(async () => {
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'Execution',
|
||||
roleId: role.id,
|
||||
conditions: ['isCreator'],
|
||||
});
|
||||
});
|
||||
|
||||
it('should return executions data of the current user', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getExecutions: {
|
||||
edges: [
|
||||
expectedResponseForExecutionTwo,
|
||||
expectedResponseForExecutionOne,
|
||||
],
|
||||
pageInfo: { currentPage: 1, totalPages: 1 },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
conditions: [],
|
||||
});
|
||||
});
|
||||
|
||||
describe('and without isCreator condition', () => {
|
||||
beforeEach(async () => {
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'Execution',
|
||||
roleId: role.id,
|
||||
conditions: [],
|
||||
});
|
||||
});
|
||||
it('should return executions data of all users', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
it('should return executions data of all users', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getExecutions: {
|
||||
edges: [
|
||||
expectedResponseForExecutionThree,
|
||||
expectedResponseForExecutionTwo,
|
||||
expectedResponseForExecutionOne,
|
||||
],
|
||||
pageInfo: { currentPage: 1, totalPages: 1 },
|
||||
},
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getExecutions: {
|
||||
edges: [
|
||||
expectedResponseForExecutionThree,
|
||||
expectedResponseForExecutionTwo,
|
||||
expectedResponseForExecutionOne,
|
||||
],
|
||||
pageInfo: { currentPage: 1, totalPages: 1 },
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
});
|
||||
|
||||
describe('and with filters', () => {
|
||||
beforeEach(async () => {
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'Execution',
|
||||
roleId: role.id,
|
||||
conditions: [],
|
||||
});
|
||||
});
|
||||
|
||||
describe('and with filters', () => {
|
||||
beforeEach(async () => {
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'Execution',
|
||||
roleId: role.id,
|
||||
conditions: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('should return executions data for the specified flow', async () => {
|
||||
const query = `
|
||||
it('should return executions data for the specified flow', async () => {
|
||||
const query = `
|
||||
query {
|
||||
getExecutions(limit: 10, offset: 0, filters: { flowId: "${flowOne.id}" }) {
|
||||
pageInfo {
|
||||
@@ -368,26 +352,26 @@ describe('graphQL getExecutions query', () => {
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getExecutions: {
|
||||
edges: [expectedResponseForExecutionOne],
|
||||
pageInfo: { currentPage: 1, totalPages: 1 },
|
||||
},
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getExecutions: {
|
||||
edges: [expectedResponseForExecutionOne],
|
||||
pageInfo: { currentPage: 1, totalPages: 1 },
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
|
||||
it('should return only executions data with success status', async () => {
|
||||
const query = `
|
||||
it('should return only executions data with success status', async () => {
|
||||
const query = `
|
||||
query {
|
||||
getExecutions(limit: 10, offset: 0, filters: { status: "success" }) {
|
||||
pageInfo {
|
||||
@@ -415,30 +399,30 @@ describe('graphQL getExecutions query', () => {
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getExecutions: {
|
||||
edges: [expectedResponseForExecutionOne],
|
||||
pageInfo: { currentPage: 1, totalPages: 1 },
|
||||
},
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getExecutions: {
|
||||
edges: [expectedResponseForExecutionOne],
|
||||
pageInfo: { currentPage: 1, totalPages: 1 },
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
|
||||
it('should return only executions data within date range', async () => {
|
||||
const createdAtFrom = executionOne.createdAt.getTime().toString();
|
||||
it('should return only executions data within date range', async () => {
|
||||
const createdAtFrom = executionOne.createdAt.getTime().toString();
|
||||
|
||||
const createdAtTo = executionOne.createdAt.getTime().toString();
|
||||
const createdAtTo = executionOne.createdAt.getTime().toString();
|
||||
|
||||
const query = `
|
||||
const query = `
|
||||
query {
|
||||
getExecutions(limit: 10, offset: 0, filters: { createdAt: { from: "${createdAtFrom}", to: "${createdAtTo}" }}) {
|
||||
pageInfo {
|
||||
@@ -466,23 +450,22 @@ describe('graphQL getExecutions query', () => {
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getExecutions: {
|
||||
edges: [expectedResponseForExecutionOne],
|
||||
pageInfo: { currentPage: 1, totalPages: 1 },
|
||||
},
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getExecutions: {
|
||||
edges: [expectedResponseForExecutionOne],
|
||||
pageInfo: { currentPage: 1, totalPages: 1 },
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -40,222 +40,200 @@ describe('graphQL getFlow query', () => {
|
||||
`;
|
||||
};
|
||||
|
||||
describe('with unauthenticated user', () => {
|
||||
describe('and without permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const invalidToken = 'invalid-token';
|
||||
const userWithoutPermissions = await createUser();
|
||||
const token = createAuthTokenByUserId(userWithoutPermissions.id);
|
||||
const flow = await createFlow();
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', invalidToken)
|
||||
.set('Authorization', token)
|
||||
.send({ query: query(flow.id) })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not Authorised!');
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
});
|
||||
});
|
||||
|
||||
describe('with authenticated user', () => {
|
||||
describe('and without permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const userWithoutPermissions = await createUser();
|
||||
const token = createAuthTokenByUserId(userWithoutPermissions.id);
|
||||
const flow = await createFlow();
|
||||
describe('and with correct permission', () => {
|
||||
let currentUser, currentUserRole, currentUserFlow;
|
||||
|
||||
beforeEach(async () => {
|
||||
currentUserRole = await createRole();
|
||||
currentUser = await createUser({ roleId: currentUserRole.id });
|
||||
currentUserFlow = await createFlow({ userId: currentUser.id });
|
||||
});
|
||||
|
||||
describe('and with isCreator condition', () => {
|
||||
it('should return executions data of the current user', async () => {
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'Flow',
|
||||
roleId: currentUserRole.id,
|
||||
conditions: ['isCreator'],
|
||||
});
|
||||
|
||||
const triggerStep = await createStep({
|
||||
flowId: currentUserFlow.id,
|
||||
type: 'trigger',
|
||||
key: 'catchRawWebhook',
|
||||
webhookPath: `/webhooks/flows/${currentUserFlow.id}`,
|
||||
});
|
||||
|
||||
const actionConnection = await createConnection({
|
||||
userId: currentUser.id,
|
||||
formattedData: {
|
||||
screenName: 'Test',
|
||||
authenticationKey: 'test key',
|
||||
},
|
||||
});
|
||||
|
||||
const actionStep = await createStep({
|
||||
flowId: currentUserFlow.id,
|
||||
type: 'action',
|
||||
connectionId: actionConnection.id,
|
||||
key: 'translateText',
|
||||
});
|
||||
|
||||
const token = createAuthTokenByUserId(currentUser.id);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query: query(flow.id) })
|
||||
.send({ query: query(currentUserFlow.id) })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getFlow: {
|
||||
active: currentUserFlow.active,
|
||||
id: currentUserFlow.id,
|
||||
name: currentUserFlow.name,
|
||||
status: 'draft',
|
||||
steps: [
|
||||
{
|
||||
appKey: triggerStep.appKey,
|
||||
connection: null,
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${triggerStep.appKey}/assets/favicon.svg`,
|
||||
id: triggerStep.id,
|
||||
key: 'catchRawWebhook',
|
||||
parameters: {},
|
||||
position: 1,
|
||||
status: triggerStep.status,
|
||||
type: 'trigger',
|
||||
webhookUrl: `${appConfig.baseUrl}/webhooks/flows/${currentUserFlow.id}`,
|
||||
},
|
||||
{
|
||||
appKey: actionStep.appKey,
|
||||
connection: {
|
||||
createdAt: actionConnection.createdAt.getTime().toString(),
|
||||
id: actionConnection.id,
|
||||
verified: actionConnection.verified,
|
||||
},
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${actionStep.appKey}/assets/favicon.svg`,
|
||||
id: actionStep.id,
|
||||
key: 'translateText',
|
||||
parameters: {},
|
||||
position: 1,
|
||||
status: actionStep.status,
|
||||
type: 'action',
|
||||
webhookUrl: 'http://localhost:3000/null',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
});
|
||||
|
||||
describe('and with correct permission', () => {
|
||||
let currentUser, currentUserRole, currentUserFlow;
|
||||
|
||||
beforeEach(async () => {
|
||||
currentUserRole = await createRole();
|
||||
currentUser = await createUser({ roleId: currentUserRole.id });
|
||||
currentUserFlow = await createFlow({ userId: currentUser.id });
|
||||
});
|
||||
|
||||
describe('and with isCreator condition', () => {
|
||||
it('should return executions data of the current user', async () => {
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'Flow',
|
||||
roleId: currentUserRole.id,
|
||||
conditions: ['isCreator'],
|
||||
});
|
||||
|
||||
const triggerStep = await createStep({
|
||||
flowId: currentUserFlow.id,
|
||||
type: 'trigger',
|
||||
key: 'catchRawWebhook',
|
||||
webhookPath: `/webhooks/flows/${currentUserFlow.id}`,
|
||||
});
|
||||
|
||||
const actionConnection = await createConnection({
|
||||
userId: currentUser.id,
|
||||
formattedData: {
|
||||
screenName: 'Test',
|
||||
authenticationKey: 'test key',
|
||||
},
|
||||
});
|
||||
|
||||
const actionStep = await createStep({
|
||||
flowId: currentUserFlow.id,
|
||||
type: 'action',
|
||||
connectionId: actionConnection.id,
|
||||
key: 'translateText',
|
||||
});
|
||||
|
||||
const token = createAuthTokenByUserId(currentUser.id);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query: query(currentUserFlow.id) })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getFlow: {
|
||||
active: currentUserFlow.active,
|
||||
id: currentUserFlow.id,
|
||||
name: currentUserFlow.name,
|
||||
status: 'draft',
|
||||
steps: [
|
||||
{
|
||||
appKey: triggerStep.appKey,
|
||||
connection: null,
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${triggerStep.appKey}/assets/favicon.svg`,
|
||||
id: triggerStep.id,
|
||||
key: 'catchRawWebhook',
|
||||
parameters: {},
|
||||
position: 1,
|
||||
status: triggerStep.status,
|
||||
type: 'trigger',
|
||||
webhookUrl: `${appConfig.baseUrl}/webhooks/flows/${currentUserFlow.id}`,
|
||||
},
|
||||
{
|
||||
appKey: actionStep.appKey,
|
||||
connection: {
|
||||
createdAt: actionConnection.createdAt
|
||||
.getTime()
|
||||
.toString(),
|
||||
id: actionConnection.id,
|
||||
verified: actionConnection.verified,
|
||||
},
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${actionStep.appKey}/assets/favicon.svg`,
|
||||
id: actionStep.id,
|
||||
key: 'translateText',
|
||||
parameters: {},
|
||||
position: 1,
|
||||
status: actionStep.status,
|
||||
type: 'action',
|
||||
webhookUrl: 'http://localhost:3000/null',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
describe('and without isCreator condition', () => {
|
||||
it('should return executions data of all users', async () => {
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'Flow',
|
||||
roleId: currentUserRole.id,
|
||||
conditions: [],
|
||||
});
|
||||
});
|
||||
|
||||
describe('and without isCreator condition', () => {
|
||||
it('should return executions data of all users', async () => {
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'Flow',
|
||||
roleId: currentUserRole.id,
|
||||
conditions: [],
|
||||
});
|
||||
const anotherUser = await createUser();
|
||||
const anotherUserFlow = await createFlow({ userId: anotherUser.id });
|
||||
|
||||
const anotherUser = await createUser();
|
||||
const anotherUserFlow = await createFlow({ userId: anotherUser.id });
|
||||
|
||||
const triggerStep = await createStep({
|
||||
flowId: anotherUserFlow.id,
|
||||
type: 'trigger',
|
||||
key: 'catchRawWebhook',
|
||||
webhookPath: `/webhooks/flows/${anotherUserFlow.id}`,
|
||||
});
|
||||
|
||||
const actionConnection = await createConnection({
|
||||
userId: anotherUser.id,
|
||||
formattedData: {
|
||||
screenName: 'Test',
|
||||
authenticationKey: 'test key',
|
||||
},
|
||||
});
|
||||
|
||||
const actionStep = await createStep({
|
||||
flowId: anotherUserFlow.id,
|
||||
type: 'action',
|
||||
connectionId: actionConnection.id,
|
||||
key: 'translateText',
|
||||
});
|
||||
|
||||
const token = createAuthTokenByUserId(currentUser.id);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query: query(anotherUserFlow.id) })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getFlow: {
|
||||
active: anotherUserFlow.active,
|
||||
id: anotherUserFlow.id,
|
||||
name: anotherUserFlow.name,
|
||||
status: 'draft',
|
||||
steps: [
|
||||
{
|
||||
appKey: triggerStep.appKey,
|
||||
connection: null,
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${triggerStep.appKey}/assets/favicon.svg`,
|
||||
id: triggerStep.id,
|
||||
key: 'catchRawWebhook',
|
||||
parameters: {},
|
||||
position: 1,
|
||||
status: triggerStep.status,
|
||||
type: 'trigger',
|
||||
webhookUrl: `${appConfig.baseUrl}/webhooks/flows/${anotherUserFlow.id}`,
|
||||
},
|
||||
{
|
||||
appKey: actionStep.appKey,
|
||||
connection: {
|
||||
createdAt: actionConnection.createdAt
|
||||
.getTime()
|
||||
.toString(),
|
||||
id: actionConnection.id,
|
||||
verified: actionConnection.verified,
|
||||
},
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${actionStep.appKey}/assets/favicon.svg`,
|
||||
id: actionStep.id,
|
||||
key: 'translateText',
|
||||
parameters: {},
|
||||
position: 1,
|
||||
status: actionStep.status,
|
||||
type: 'action',
|
||||
webhookUrl: 'http://localhost:3000/null',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
const triggerStep = await createStep({
|
||||
flowId: anotherUserFlow.id,
|
||||
type: 'trigger',
|
||||
key: 'catchRawWebhook',
|
||||
webhookPath: `/webhooks/flows/${anotherUserFlow.id}`,
|
||||
});
|
||||
|
||||
const actionConnection = await createConnection({
|
||||
userId: anotherUser.id,
|
||||
formattedData: {
|
||||
screenName: 'Test',
|
||||
authenticationKey: 'test key',
|
||||
},
|
||||
});
|
||||
|
||||
const actionStep = await createStep({
|
||||
flowId: anotherUserFlow.id,
|
||||
type: 'action',
|
||||
connectionId: actionConnection.id,
|
||||
key: 'translateText',
|
||||
});
|
||||
|
||||
const token = createAuthTokenByUserId(currentUser.id);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query: query(anotherUserFlow.id) })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getFlow: {
|
||||
active: anotherUserFlow.active,
|
||||
id: anotherUserFlow.id,
|
||||
name: anotherUserFlow.name,
|
||||
status: 'draft',
|
||||
steps: [
|
||||
{
|
||||
appKey: triggerStep.appKey,
|
||||
connection: null,
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${triggerStep.appKey}/assets/favicon.svg`,
|
||||
id: triggerStep.id,
|
||||
key: 'catchRawWebhook',
|
||||
parameters: {},
|
||||
position: 1,
|
||||
status: triggerStep.status,
|
||||
type: 'trigger',
|
||||
webhookUrl: `${appConfig.baseUrl}/webhooks/flows/${anotherUserFlow.id}`,
|
||||
},
|
||||
{
|
||||
appKey: actionStep.appKey,
|
||||
connection: {
|
||||
createdAt: actionConnection.createdAt.getTime().toString(),
|
||||
id: actionConnection.id,
|
||||
verified: actionConnection.verified,
|
||||
},
|
||||
iconUrl: `${appConfig.baseUrl}/apps/${actionStep.appKey}/assets/favicon.svg`,
|
||||
id: actionStep.id,
|
||||
key: 'translateText',
|
||||
parameters: {},
|
||||
position: 1,
|
||||
status: actionStep.status,
|
||||
type: 'action',
|
||||
webhookUrl: 'http://localhost:3000/null',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -17,7 +17,6 @@ describe('graphQL getRole query', () => {
|
||||
userWithoutPermissions,
|
||||
tokenWithPermissions,
|
||||
tokenWithoutPermissions,
|
||||
invalidToken,
|
||||
permissionOne,
|
||||
permissionTwo;
|
||||
|
||||
@@ -74,108 +73,91 @@ describe('graphQL getRole query', () => {
|
||||
tokenWithoutPermissions = createAuthTokenByUserId(
|
||||
userWithoutPermissions.id
|
||||
);
|
||||
|
||||
invalidToken = 'invalid-token';
|
||||
});
|
||||
|
||||
describe('with unauthenticated user', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', invalidToken)
|
||||
.send({ query: queryWithValidRole })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not Authorised!');
|
||||
describe('and with valid license', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(license, 'hasValidLicense').mockResolvedValue(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('with authenticated user', () => {
|
||||
describe('and with valid license', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(license, 'hasValidLicense').mockResolvedValue(true);
|
||||
describe('and without permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithoutPermissions)
|
||||
.send({ query: queryWithValidRole })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
});
|
||||
});
|
||||
|
||||
describe('and without permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithoutPermissions)
|
||||
.send({ query: queryWithValidRole })
|
||||
.expect(200);
|
||||
describe('and correct permissions', () => {
|
||||
it('should return role data for a valid role id', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithPermissions)
|
||||
.send({ query: queryWithValidRole })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
});
|
||||
});
|
||||
|
||||
describe('and correct permissions', () => {
|
||||
it('should return role data for a valid role id', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithPermissions)
|
||||
.send({ query: queryWithValidRole })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getRole: {
|
||||
description: validRole.description,
|
||||
id: validRole.id,
|
||||
isAdmin: validRole.key === 'admin',
|
||||
key: validRole.key,
|
||||
name: validRole.name,
|
||||
permissions: [
|
||||
{
|
||||
action: permissionOne.action,
|
||||
conditions: permissionOne.conditions,
|
||||
id: permissionOne.id,
|
||||
subject: permissionOne.subject,
|
||||
},
|
||||
{
|
||||
action: permissionTwo.action,
|
||||
conditions: permissionTwo.conditions,
|
||||
id: permissionTwo.id,
|
||||
subject: permissionTwo.subject,
|
||||
},
|
||||
],
|
||||
},
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getRole: {
|
||||
description: validRole.description,
|
||||
id: validRole.id,
|
||||
isAdmin: validRole.key === 'admin',
|
||||
key: validRole.key,
|
||||
name: validRole.name,
|
||||
permissions: [
|
||||
{
|
||||
action: permissionOne.action,
|
||||
conditions: permissionOne.conditions,
|
||||
id: permissionOne.id,
|
||||
subject: permissionOne.subject,
|
||||
},
|
||||
{
|
||||
action: permissionTwo.action,
|
||||
conditions: permissionTwo.conditions,
|
||||
id: permissionTwo.id,
|
||||
subject: permissionTwo.subject,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
|
||||
it('should return not found for invalid role id', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithPermissions)
|
||||
.send({ query: queryWithInvalidRole })
|
||||
.expect(200);
|
||||
it('should return not found for invalid role id', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithPermissions)
|
||||
.send({ query: queryWithInvalidRole })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('NotFoundError');
|
||||
});
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('NotFoundError');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('and without valid license', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(license, 'hasValidLicense').mockResolvedValue(false);
|
||||
});
|
||||
describe('and without valid license', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(license, 'hasValidLicense').mockResolvedValue(false);
|
||||
});
|
||||
|
||||
describe('and correct permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithPermissions)
|
||||
.send({ query: queryWithInvalidRole })
|
||||
.expect(200);
|
||||
describe('and correct permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithPermissions)
|
||||
.send({ query: queryWithInvalidRole })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
});
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -15,8 +15,7 @@ describe('graphQL getRoles query', () => {
|
||||
userWithPermissions,
|
||||
userWithoutPermissions,
|
||||
tokenWithPermissions,
|
||||
tokenWithoutPermissions,
|
||||
invalidToken;
|
||||
tokenWithoutPermissions;
|
||||
|
||||
beforeEach(async () => {
|
||||
currentUserRole = await createRole({ name: 'Current user role' });
|
||||
@@ -53,99 +52,82 @@ describe('graphQL getRoles query', () => {
|
||||
tokenWithoutPermissions = createAuthTokenByUserId(
|
||||
userWithoutPermissions.id
|
||||
);
|
||||
|
||||
invalidToken = 'invalid-token';
|
||||
});
|
||||
|
||||
describe('with unauthenticated user', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', invalidToken)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not Authorised!');
|
||||
describe('and with valid license', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(license, 'hasValidLicense').mockResolvedValue(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('with authenticated user', () => {
|
||||
describe('and with valid license', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(license, 'hasValidLicense').mockResolvedValue(true);
|
||||
});
|
||||
describe('and without permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithoutPermissions)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
describe('and without permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithoutPermissions)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
});
|
||||
});
|
||||
|
||||
describe('and correct permissions', () => {
|
||||
it('should return roles data', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithPermissions)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getRoles: [
|
||||
{
|
||||
description: currentUserRole.description,
|
||||
id: currentUserRole.id,
|
||||
isAdmin: currentUserRole.key === 'admin',
|
||||
key: currentUserRole.key,
|
||||
name: currentUserRole.name,
|
||||
},
|
||||
{
|
||||
description: roleOne.description,
|
||||
id: roleOne.id,
|
||||
isAdmin: roleOne.key === 'admin',
|
||||
key: roleOne.key,
|
||||
name: roleOne.name,
|
||||
},
|
||||
{
|
||||
description: roleSecond.description,
|
||||
id: roleSecond.id,
|
||||
isAdmin: roleSecond.key === 'admin',
|
||||
key: roleSecond.key,
|
||||
name: roleSecond.name,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
});
|
||||
});
|
||||
|
||||
describe('and without valid license', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(license, 'hasValidLicense').mockResolvedValue(false);
|
||||
describe('and correct permissions', () => {
|
||||
it('should return roles data', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithPermissions)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getRoles: [
|
||||
{
|
||||
description: currentUserRole.description,
|
||||
id: currentUserRole.id,
|
||||
isAdmin: currentUserRole.key === 'admin',
|
||||
key: currentUserRole.key,
|
||||
name: currentUserRole.name,
|
||||
},
|
||||
{
|
||||
description: roleOne.description,
|
||||
id: roleOne.id,
|
||||
isAdmin: roleOne.key === 'admin',
|
||||
key: roleOne.key,
|
||||
name: roleOne.name,
|
||||
},
|
||||
{
|
||||
description: roleSecond.description,
|
||||
id: roleSecond.id,
|
||||
isAdmin: roleSecond.key === 'admin',
|
||||
key: roleSecond.key,
|
||||
name: roleSecond.name,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('and correct permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithPermissions)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
describe('and without valid license', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(license, 'hasValidLicense').mockResolvedValue(false);
|
||||
});
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
});
|
||||
describe('and correct permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', tokenWithPermissions)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -16,34 +16,46 @@ describe('graphQL getTrialStatus query', () => {
|
||||
}
|
||||
`;
|
||||
|
||||
const invalidToken = 'invalid-token';
|
||||
let user, userToken;
|
||||
|
||||
describe('with unauthenticated user', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
beforeEach(async () => {
|
||||
const trialExpiryDate = DateTime.now().plus({ days: 30 }).toISODate();
|
||||
|
||||
user = await createUser({ trialExpiryDate });
|
||||
userToken = createAuthTokenByUserId(user.id);
|
||||
});
|
||||
|
||||
describe('and with cloud flag disabled', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(appConfig, 'isCloud', 'get').mockReturnValue(false);
|
||||
});
|
||||
|
||||
it('should return null', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', invalidToken)
|
||||
.set('Authorization', userToken)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not Authorised!');
|
||||
const expectedResponsePayload = {
|
||||
data: { getTrialStatus: null },
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
});
|
||||
|
||||
describe('with authenticated user', () => {
|
||||
let user, userToken;
|
||||
|
||||
describe('and with cloud flag enabled', () => {
|
||||
beforeEach(async () => {
|
||||
const trialExpiryDate = DateTime.now().plus({ days: 30 }).toISODate();
|
||||
|
||||
user = await createUser({ trialExpiryDate });
|
||||
userToken = createAuthTokenByUserId(user.id);
|
||||
vi.spyOn(appConfig, 'isCloud', 'get').mockReturnValue(true);
|
||||
});
|
||||
|
||||
describe('and with cloud flag disabled', () => {
|
||||
describe('and not in trial and has active subscription', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(appConfig, 'isCloud', 'get').mockReturnValue(false);
|
||||
vi.spyOn(User.prototype, 'inTrial').mockResolvedValue(false);
|
||||
vi.spyOn(User.prototype, 'hasActiveSubscription').mockResolvedValue(
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
it('should return null', async () => {
|
||||
@@ -61,56 +73,27 @@ describe('graphQL getTrialStatus query', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('and with cloud flag enabled', () => {
|
||||
describe('and in trial period', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(appConfig, 'isCloud', 'get').mockReturnValue(true);
|
||||
vi.spyOn(User.prototype, 'inTrial').mockResolvedValue(true);
|
||||
});
|
||||
|
||||
describe('and not in trial and has active subscription', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(User.prototype, 'inTrial').mockResolvedValue(false);
|
||||
vi.spyOn(User.prototype, 'hasActiveSubscription').mockResolvedValue(
|
||||
true
|
||||
);
|
||||
});
|
||||
it('should return null', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', userToken)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
it('should return null', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', userToken)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: { getTrialStatus: null },
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
});
|
||||
|
||||
describe('and in trial period', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(User.prototype, 'inTrial').mockResolvedValue(true);
|
||||
});
|
||||
|
||||
it('should return null', async () => {
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', userToken)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getTrialStatus: {
|
||||
expireAt: new Date(user.trialExpiryDate).getTime().toString(),
|
||||
},
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getTrialStatus: {
|
||||
expireAt: new Date(user.trialExpiryDate).getTime().toString(),
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -8,37 +8,12 @@ import { createPermission } from '../../../test/factories/permission';
|
||||
import { createUser } from '../../../test/factories/user';
|
||||
|
||||
describe('graphQL getUser query', () => {
|
||||
describe('with unauthenticated user', () => {
|
||||
describe('and without permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const invalidUserId = '123123123';
|
||||
const userWithoutPermissions = await createUser();
|
||||
const anotherUser = await createUser();
|
||||
|
||||
const query = `
|
||||
query {
|
||||
getUser(id: "${invalidUserId}") {
|
||||
id
|
||||
email
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', 'invalid-token')
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not Authorised!');
|
||||
});
|
||||
});
|
||||
|
||||
describe('with authenticated user', () => {
|
||||
describe('and without permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const userWithoutPermissions = await createUser();
|
||||
const anotherUser = await createUser();
|
||||
|
||||
const query = `
|
||||
query {
|
||||
getUser(id: "${anotherUser.id}") {
|
||||
id
|
||||
@@ -47,50 +22,48 @@ describe('graphQL getUser query', () => {
|
||||
}
|
||||
`;
|
||||
|
||||
const token = createAuthTokenByUserId(userWithoutPermissions.id);
|
||||
const token = createAuthTokenByUserId(userWithoutPermissions.id);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
});
|
||||
});
|
||||
|
||||
describe('and correct permissions', () => {
|
||||
let role, currentUser, anotherUser, token, requestObject;
|
||||
|
||||
beforeEach(async () => {
|
||||
role = await createRole({
|
||||
key: 'sample',
|
||||
name: 'sample',
|
||||
});
|
||||
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'User',
|
||||
roleId: role.id,
|
||||
});
|
||||
|
||||
currentUser = await createUser({
|
||||
roleId: role.id,
|
||||
});
|
||||
|
||||
anotherUser = await createUser({
|
||||
roleId: role.id,
|
||||
});
|
||||
|
||||
token = createAuthTokenByUserId(currentUser.id);
|
||||
requestObject = request(app).post('/graphql').set('Authorization', token);
|
||||
});
|
||||
|
||||
describe('and correct permissions', () => {
|
||||
let role, currentUser, anotherUser, token, requestObject;
|
||||
|
||||
beforeEach(async () => {
|
||||
role = await createRole({
|
||||
key: 'sample',
|
||||
name: 'sample',
|
||||
});
|
||||
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'User',
|
||||
roleId: role.id,
|
||||
});
|
||||
|
||||
currentUser = await createUser({
|
||||
roleId: role.id,
|
||||
});
|
||||
|
||||
anotherUser = await createUser({
|
||||
roleId: role.id,
|
||||
});
|
||||
|
||||
token = createAuthTokenByUserId(currentUser.id);
|
||||
requestObject = request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token);
|
||||
});
|
||||
|
||||
it('should return user data for a valid user id', async () => {
|
||||
const query = `
|
||||
it('should return user data for a valid user id', async () => {
|
||||
const query = `
|
||||
query {
|
||||
getUser(id: "${anotherUser.id}") {
|
||||
id
|
||||
@@ -107,26 +80,26 @@ describe('graphQL getUser query', () => {
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await requestObject.send({ query }).expect(200);
|
||||
const response = await requestObject.send({ query }).expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getUser: {
|
||||
createdAt: anotherUser.createdAt.getTime().toString(),
|
||||
email: anotherUser.email,
|
||||
fullName: anotherUser.fullName,
|
||||
id: anotherUser.id,
|
||||
role: { id: role.id, name: role.name },
|
||||
updatedAt: anotherUser.updatedAt.getTime().toString(),
|
||||
},
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getUser: {
|
||||
createdAt: anotherUser.createdAt.getTime().toString(),
|
||||
email: anotherUser.email,
|
||||
fullName: anotherUser.fullName,
|
||||
id: anotherUser.id,
|
||||
role: { id: role.id, name: role.name },
|
||||
updatedAt: anotherUser.updatedAt.getTime().toString(),
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
|
||||
it('should not return user password for a valid user id', async () => {
|
||||
const query = `
|
||||
it('should not return user password for a valid user id', async () => {
|
||||
const query = `
|
||||
query {
|
||||
getUser(id: "${anotherUser.id}") {
|
||||
id
|
||||
@@ -136,18 +109,18 @@ describe('graphQL getUser query', () => {
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await requestObject.send({ query }).expect(400);
|
||||
const response = await requestObject.send({ query }).expect(400);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual(
|
||||
'Cannot query field "password" on type "User".'
|
||||
);
|
||||
});
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual(
|
||||
'Cannot query field "password" on type "User".'
|
||||
);
|
||||
});
|
||||
|
||||
it('should return not found for invalid user id', async () => {
|
||||
const invalidUserId = Crypto.randomUUID();
|
||||
it('should return not found for invalid user id', async () => {
|
||||
const invalidUserId = Crypto.randomUUID();
|
||||
|
||||
const query = `
|
||||
const query = `
|
||||
query {
|
||||
getUser(id: "${invalidUserId}") {
|
||||
id
|
||||
@@ -164,11 +137,10 @@ describe('graphQL getUser query', () => {
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await requestObject.send({ query }).expect(200);
|
||||
const response = await requestObject.send({ query }).expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('NotFoundError');
|
||||
});
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('NotFoundError');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -30,111 +30,95 @@ describe('graphQL getUsers query', () => {
|
||||
}
|
||||
`;
|
||||
|
||||
describe('with unauthenticated user', () => {
|
||||
describe('and without permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const userWithoutPermissions = await createUser();
|
||||
const token = createAuthTokenByUserId(userWithoutPermissions.id);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', 'invalid-token')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not Authorised!');
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
});
|
||||
});
|
||||
|
||||
describe('with authenticated user', () => {
|
||||
describe('and without permissions', () => {
|
||||
it('should throw not authorized error', async () => {
|
||||
const userWithoutPermissions = await createUser();
|
||||
const token = createAuthTokenByUserId(userWithoutPermissions.id);
|
||||
describe('and with correct permissions', () => {
|
||||
let role, currentUser, anotherUser, token, requestObject;
|
||||
|
||||
const response = await request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token)
|
||||
.send({ query })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual('Not authorized!');
|
||||
beforeEach(async () => {
|
||||
role = await createRole({
|
||||
key: 'sample',
|
||||
name: 'sample',
|
||||
});
|
||||
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'User',
|
||||
roleId: role.id,
|
||||
});
|
||||
|
||||
currentUser = await createUser({
|
||||
roleId: role.id,
|
||||
fullName: 'Current User',
|
||||
});
|
||||
|
||||
anotherUser = await createUser({
|
||||
roleId: role.id,
|
||||
fullName: 'Another User',
|
||||
});
|
||||
|
||||
token = createAuthTokenByUserId(currentUser.id);
|
||||
requestObject = request(app).post('/graphql').set('Authorization', token);
|
||||
});
|
||||
|
||||
describe('and with correct permissions', () => {
|
||||
let role, currentUser, anotherUser, token, requestObject;
|
||||
it('should return users data', async () => {
|
||||
const response = await requestObject.send({ query }).expect(200);
|
||||
|
||||
beforeEach(async () => {
|
||||
role = await createRole({
|
||||
key: 'sample',
|
||||
name: 'sample',
|
||||
});
|
||||
|
||||
await createPermission({
|
||||
action: 'read',
|
||||
subject: 'User',
|
||||
roleId: role.id,
|
||||
});
|
||||
|
||||
currentUser = await createUser({
|
||||
roleId: role.id,
|
||||
fullName: 'Current User',
|
||||
});
|
||||
|
||||
anotherUser = await createUser({
|
||||
roleId: role.id,
|
||||
fullName: 'Another User',
|
||||
});
|
||||
|
||||
token = createAuthTokenByUserId(currentUser.id);
|
||||
requestObject = request(app)
|
||||
.post('/graphql')
|
||||
.set('Authorization', token);
|
||||
});
|
||||
|
||||
it('should return users data', async () => {
|
||||
const response = await requestObject.send({ query }).expect(200);
|
||||
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getUsers: {
|
||||
edges: [
|
||||
{
|
||||
node: {
|
||||
email: anotherUser.email,
|
||||
fullName: anotherUser.fullName,
|
||||
id: anotherUser.id,
|
||||
role: {
|
||||
id: role.id,
|
||||
name: role.name,
|
||||
},
|
||||
const expectedResponsePayload = {
|
||||
data: {
|
||||
getUsers: {
|
||||
edges: [
|
||||
{
|
||||
node: {
|
||||
email: anotherUser.email,
|
||||
fullName: anotherUser.fullName,
|
||||
id: anotherUser.id,
|
||||
role: {
|
||||
id: role.id,
|
||||
name: role.name,
|
||||
},
|
||||
},
|
||||
{
|
||||
node: {
|
||||
email: currentUser.email,
|
||||
fullName: currentUser.fullName,
|
||||
id: currentUser.id,
|
||||
role: {
|
||||
id: role.id,
|
||||
name: role.name,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
pageInfo: {
|
||||
currentPage: 1,
|
||||
totalPages: 1,
|
||||
},
|
||||
totalCount: 2,
|
||||
{
|
||||
node: {
|
||||
email: currentUser.email,
|
||||
fullName: currentUser.fullName,
|
||||
id: currentUser.id,
|
||||
role: {
|
||||
id: role.id,
|
||||
name: role.name,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
pageInfo: {
|
||||
currentPage: 1,
|
||||
totalPages: 1,
|
||||
},
|
||||
totalCount: 2,
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
expect(response.body).toEqual(expectedResponsePayload);
|
||||
});
|
||||
|
||||
it('should not return users data with password', async () => {
|
||||
const query = `
|
||||
it('should not return users data with password', async () => {
|
||||
const query = `
|
||||
query {
|
||||
getUsers(limit: 10, offset: 0) {
|
||||
pageInfo {
|
||||
@@ -153,13 +137,12 @@ describe('graphQL getUsers query', () => {
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await requestObject.send({ query }).expect(400);
|
||||
const response = await requestObject.send({ query }).expect(400);
|
||||
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual(
|
||||
'Cannot query field "password" on type "User".'
|
||||
);
|
||||
});
|
||||
expect(response.body.errors).toBeDefined();
|
||||
expect(response.body.errors[0].message).toEqual(
|
||||
'Cannot query field "password" on type "User".'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -3,7 +3,7 @@ import jwt from 'jsonwebtoken';
|
||||
import appConfig from '../config/app.js';
|
||||
import User from '../models/user.js';
|
||||
|
||||
const isAuthenticated = rule()(async (_parent, _args, req) => {
|
||||
export const isAuthenticated = async (_parent, _args, req) => {
|
||||
const token = req.headers['authorization'];
|
||||
|
||||
if (token == null) return false;
|
||||
@@ -20,35 +20,47 @@ const isAuthenticated = rule()(async (_parent, _args, req) => {
|
||||
.withGraphFetched({
|
||||
role: true,
|
||||
permissions: true,
|
||||
});
|
||||
})
|
||||
.throwIfNotFound();
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const authentication = shield(
|
||||
{
|
||||
Query: {
|
||||
'*': isAuthenticated,
|
||||
getAutomatischInfo: allow,
|
||||
getConfig: allow,
|
||||
getNotifications: allow,
|
||||
healthcheck: allow,
|
||||
listSamlAuthProviders: allow,
|
||||
},
|
||||
Mutation: {
|
||||
'*': isAuthenticated,
|
||||
forgotPassword: allow,
|
||||
login: allow,
|
||||
registerUser: allow,
|
||||
resetPassword: allow,
|
||||
},
|
||||
},
|
||||
{
|
||||
allowExternalErrors: true,
|
||||
export const authenticateUser = async (request, response, next) => {
|
||||
if (await isAuthenticated(null, null, request)) {
|
||||
next();
|
||||
} else {
|
||||
return response.status(401).end();
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
const isAuthenticatedRule = rule()(isAuthenticated);
|
||||
|
||||
export const authenticationRules = {
|
||||
Query: {
|
||||
'*': isAuthenticatedRule,
|
||||
getAutomatischInfo: allow,
|
||||
getConfig: allow,
|
||||
getNotifications: allow,
|
||||
healthcheck: allow,
|
||||
listSamlAuthProviders: allow,
|
||||
},
|
||||
Mutation: {
|
||||
'*': isAuthenticatedRule,
|
||||
forgotPassword: allow,
|
||||
login: allow,
|
||||
registerUser: allow,
|
||||
resetPassword: allow,
|
||||
},
|
||||
};
|
||||
|
||||
const authenticationOptions = {
|
||||
allowExternalErrors: true,
|
||||
};
|
||||
|
||||
const authentication = shield(authenticationRules, authenticationOptions);
|
||||
|
||||
export default authentication;
|
||||
|
72
packages/backend/src/helpers/authentication.test.js
Normal file
72
packages/backend/src/helpers/authentication.test.js
Normal file
@@ -0,0 +1,72 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { allow } from 'graphql-shield';
|
||||
import { isAuthenticated, authenticationRules } from './authentication.js';
|
||||
import { createUser } from '../../test/factories/user.js';
|
||||
import createAuthTokenByUserId from '../helpers/create-auth-token-by-user-id.js';
|
||||
|
||||
describe('isAuthenticated', () => {
|
||||
it('should return false if no token is provided', async () => {
|
||||
const req = { headers: {} };
|
||||
expect(await isAuthenticated(null, null, req)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if token is invalid', async () => {
|
||||
const req = { headers: { authorization: 'invalidToken' } };
|
||||
expect(await isAuthenticated(null, null, req)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true if token is valid and there is a user', async () => {
|
||||
const user = await createUser();
|
||||
const token = createAuthTokenByUserId(user.id);
|
||||
|
||||
const req = { headers: { authorization: token } };
|
||||
expect(await isAuthenticated(null, null, req)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false if token is valid and but there is no user', async () => {
|
||||
const user = await createUser();
|
||||
const token = createAuthTokenByUserId(user.id);
|
||||
await user.$query().delete();
|
||||
|
||||
const req = { headers: { authorization: token } };
|
||||
expect(await isAuthenticated(null, null, req)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('authentication rules', () => {
|
||||
const getQueryAndMutationNames = (rules) => {
|
||||
const queries = Object.keys(rules.Query || {});
|
||||
const mutations = Object.keys(rules.Mutation || {});
|
||||
return { queries, mutations };
|
||||
};
|
||||
|
||||
const { queries, mutations } = getQueryAndMutationNames(authenticationRules);
|
||||
|
||||
describe('for queries', () => {
|
||||
queries.forEach((query) => {
|
||||
it(`should apply correct rule for query: ${query}`, () => {
|
||||
const ruleApplied = authenticationRules.Query[query];
|
||||
|
||||
if (query === '*') {
|
||||
expect(ruleApplied.func).toBe(isAuthenticated);
|
||||
} else {
|
||||
expect(ruleApplied).toEqual(allow);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('for mutations', () => {
|
||||
mutations.forEach((mutation) => {
|
||||
it(`should apply correct rule for mutation: ${mutation}`, () => {
|
||||
const ruleApplied = authenticationRules.Mutation[mutation];
|
||||
|
||||
if (mutation === '*') {
|
||||
expect(ruleApplied.func).toBe(isAuthenticated);
|
||||
} else {
|
||||
expect(ruleApplied).toBe(allow);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
22
packages/backend/src/helpers/authorization.js
Normal file
22
packages/backend/src/helpers/authorization.js
Normal file
@@ -0,0 +1,22 @@
|
||||
const authorizationList = {
|
||||
'/api/v1/users/:userId': {
|
||||
action: 'read',
|
||||
subject: 'User',
|
||||
},
|
||||
'/api/v1/users/': {
|
||||
action: 'read',
|
||||
subject: 'User',
|
||||
},
|
||||
};
|
||||
|
||||
export const authorizeUser = async (request, response, next) => {
|
||||
const currentRoute = request.baseUrl + request.route.path;
|
||||
const currentRouteRule = authorizationList[currentRoute];
|
||||
|
||||
try {
|
||||
request.currentUser.can(currentRouteRule.action, currentRouteRule.subject);
|
||||
next();
|
||||
} catch (error) {
|
||||
return response.status(403).end();
|
||||
}
|
||||
};
|
11
packages/backend/src/helpers/check-is-cloud.js
Normal file
11
packages/backend/src/helpers/check-is-cloud.js
Normal file
@@ -0,0 +1,11 @@
|
||||
import appConfig from '../config/app.js';
|
||||
|
||||
export const checkIsCloud = async (request, response, next) => {
|
||||
if (appConfig.isCloud) {
|
||||
next();
|
||||
} else {
|
||||
return response.status(404).end();
|
||||
}
|
||||
};
|
||||
|
||||
export default checkIsCloud;
|
@@ -1,6 +1,9 @@
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
import * as handlebars from 'handlebars';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import handlebars from 'handlebars';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const compileEmail = (emailPath, replacements = {}) => {
|
||||
const filePath = path.join(__dirname, `../views/emails/${emailPath}.ee.hbs`);
|
||||
|
25
packages/backend/src/helpers/pagination-rest.js
Normal file
25
packages/backend/src/helpers/pagination-rest.js
Normal file
@@ -0,0 +1,25 @@
|
||||
const paginateRest = async (query, page) => {
|
||||
const pageSize = 10;
|
||||
|
||||
page = parseInt(page, 10);
|
||||
|
||||
if (isNaN(page) || page < 1) {
|
||||
page = 1;
|
||||
}
|
||||
|
||||
const [records, count] = await Promise.all([
|
||||
query.limit(pageSize).offset((page - 1) * pageSize),
|
||||
query.resultSize(),
|
||||
]);
|
||||
|
||||
return {
|
||||
pageInfo: {
|
||||
currentPage: page,
|
||||
totalPages: Math.ceil(count / pageSize),
|
||||
},
|
||||
totalCount: count,
|
||||
records,
|
||||
};
|
||||
};
|
||||
|
||||
export default paginateRest;
|
42
packages/backend/src/helpers/renderer.js
Normal file
42
packages/backend/src/helpers/renderer.js
Normal file
@@ -0,0 +1,42 @@
|
||||
import serializers from '../serializers/index.js';
|
||||
|
||||
const isPaginated = (object) =>
|
||||
object?.pageInfo &&
|
||||
object?.totalCount !== undefined &&
|
||||
Array.isArray(object?.records);
|
||||
|
||||
const isArray = (object) =>
|
||||
Array.isArray(object) || Array.isArray(object?.records);
|
||||
|
||||
const totalCount = (object) =>
|
||||
isPaginated(object) ? object.totalCount : isArray(object) ? object.length : 1;
|
||||
|
||||
const renderObject = (response, object) => {
|
||||
let data = isPaginated(object) ? object.records : object;
|
||||
const type = isPaginated(object)
|
||||
? object.records[0].constructor.name
|
||||
: object.constructor.name;
|
||||
|
||||
const serializer = serializers[type];
|
||||
|
||||
if (serializer) {
|
||||
data = Array.isArray(data)
|
||||
? data.map((item) => serializer(item))
|
||||
: serializer(data);
|
||||
}
|
||||
|
||||
const computedPayload = {
|
||||
data,
|
||||
meta: {
|
||||
type,
|
||||
count: totalCount(object),
|
||||
isArray: isArray(object),
|
||||
currentPage: isPaginated(object) ? object.pageInfo.currentPage : null,
|
||||
totalPages: isPaginated(object) ? object.pageInfo.totalPages : null,
|
||||
},
|
||||
};
|
||||
|
||||
return response.json(computedPayload);
|
||||
};
|
||||
|
||||
export { renderObject };
|
@@ -15,7 +15,7 @@ const webUIHandler = async (app) => {
|
||||
app.use(express.static(webBuildPath));
|
||||
|
||||
app.get('*', (_req, res) => {
|
||||
res.set('Content-Security-Policy', 'frame-ancestors: none;');
|
||||
res.set('Content-Security-Policy', 'frame-ancestors \'none\';');
|
||||
res.set('X-Frame-Options', 'DENY');
|
||||
|
||||
res.sendFile(indexHtml);
|
||||
|
8
packages/backend/src/routes/api/v1/automatisch.js
Normal file
8
packages/backend/src/routes/api/v1/automatisch.js
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Router } from 'express';
|
||||
import versionAction from '../../../controllers/api/v1/automatisch/version.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.get('/version', versionAction);
|
||||
|
||||
export default router;
|
22
packages/backend/src/routes/api/v1/users.js
Normal file
22
packages/backend/src/routes/api/v1/users.js
Normal file
@@ -0,0 +1,22 @@
|
||||
import { Router } from 'express';
|
||||
import { authenticateUser } from '../../../helpers/authentication.js';
|
||||
import { authorizeUser } from '../../../helpers/authorization.js';
|
||||
import checkIsCloud from '../../../helpers/check-is-cloud.js';
|
||||
import getCurrentUserAction from '../../../controllers/api/v1/users/get-current-user.js';
|
||||
import getUserAction from '../../../controllers/api/v1/users/get-user.js';
|
||||
import getUsersAction from '../../../controllers/api/v1/users/get-users.js';
|
||||
import getUserTrialAction from '../../../controllers/api/v1/users/get-user-trial.ee.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.get('/', authenticateUser, authorizeUser, getUsersAction);
|
||||
router.get('/me', authenticateUser, getCurrentUserAction);
|
||||
router.get('/:userId', authenticateUser, authorizeUser, getUserAction);
|
||||
router.get(
|
||||
'/:userId/trial',
|
||||
authenticateUser,
|
||||
checkIsCloud,
|
||||
getUserTrialAction
|
||||
);
|
||||
|
||||
export default router;
|
8
packages/backend/src/routes/healthcheck.js
Normal file
8
packages/backend/src/routes/healthcheck.js
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Router } from 'express';
|
||||
import indexAction from '../controllers/healthcheck/index.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.get('/', indexAction);
|
||||
|
||||
export default router;
|
@@ -2,11 +2,17 @@ import { Router } from 'express';
|
||||
import graphQLInstance from '../helpers/graphql-instance.js';
|
||||
import webhooksRouter from './webhooks.js';
|
||||
import paddleRouter from './paddle.ee.js';
|
||||
import healthcheckRouter from './healthcheck.js';
|
||||
import automatischRouter from './api/v1/automatisch.js';
|
||||
import usersRouter from './api/v1/users.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.use('/graphql', graphQLInstance);
|
||||
router.use('/webhooks', webhooksRouter);
|
||||
router.use('/paddle', paddleRouter);
|
||||
router.use('/healthcheck', healthcheckRouter);
|
||||
router.use('/api/v1/automatisch', automatischRouter);
|
||||
router.use('/api/v1/users', usersRouter);
|
||||
|
||||
export default router;
|
||||
|
11
packages/backend/src/serializers/index.js
Normal file
11
packages/backend/src/serializers/index.js
Normal file
@@ -0,0 +1,11 @@
|
||||
import userSerializer from './user.js';
|
||||
import roleSerializer from './role.js';
|
||||
import permissionSerializer from './permission.js';
|
||||
|
||||
const serializers = {
|
||||
User: userSerializer,
|
||||
Role: roleSerializer,
|
||||
Permission: permissionSerializer,
|
||||
};
|
||||
|
||||
export default serializers;
|
13
packages/backend/src/serializers/permission.js
Normal file
13
packages/backend/src/serializers/permission.js
Normal file
@@ -0,0 +1,13 @@
|
||||
const permissionSerializer = (permission) => {
|
||||
return {
|
||||
id: permission.id,
|
||||
roleId: permission.roleId,
|
||||
action: permission.action,
|
||||
subject: permission.subject,
|
||||
conditions: permission.conditions,
|
||||
createdAt: permission.createdAt,
|
||||
updatedAt: permission.updatedAt,
|
||||
};
|
||||
};
|
||||
|
||||
export default permissionSerializer;
|
13
packages/backend/src/serializers/role.js
Normal file
13
packages/backend/src/serializers/role.js
Normal file
@@ -0,0 +1,13 @@
|
||||
const roleSerializer = (role) => {
|
||||
return {
|
||||
id: role.id,
|
||||
name: role.name,
|
||||
key: role.key,
|
||||
description: role.description,
|
||||
createdAt: role.createdAt,
|
||||
updatedAt: role.updatedAt,
|
||||
isAdmin: role.isAdmin,
|
||||
};
|
||||
};
|
||||
|
||||
export default roleSerializer;
|
32
packages/backend/src/serializers/user.js
Normal file
32
packages/backend/src/serializers/user.js
Normal file
@@ -0,0 +1,32 @@
|
||||
import roleSerializer from './role.js';
|
||||
import permissionSerializer from './permission.js';
|
||||
import appConfig from '../config/app.js';
|
||||
|
||||
const userSerializer = (user) => {
|
||||
let userData = {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
createdAt: user.createdAt,
|
||||
updatedAt: user.updatedAt,
|
||||
fullName: user.fullName,
|
||||
roleId: user.roleId,
|
||||
};
|
||||
|
||||
if (user.role) {
|
||||
userData.role = roleSerializer(user.role);
|
||||
}
|
||||
|
||||
if (user.permissions) {
|
||||
userData.permissions = user.permissions.map((permission) =>
|
||||
permissionSerializer(permission)
|
||||
);
|
||||
}
|
||||
|
||||
if (appConfig.isCloud && user.trialExpiryDate) {
|
||||
userData.trialExpiryDate = user.trialExpiryDate;
|
||||
}
|
||||
|
||||
return userData;
|
||||
};
|
||||
|
||||
export default userSerializer;
|
@@ -1,4 +1,5 @@
|
||||
import { faker } from '@faker-js/faker';
|
||||
import Config from '../../src/models/config';
|
||||
|
||||
export const createConfig = async (params = {}) => {
|
||||
const configData = {
|
||||
@@ -6,10 +7,7 @@ export const createConfig = async (params = {}) => {
|
||||
value: params?.value || { data: 'sampleConfig' },
|
||||
};
|
||||
|
||||
const [config] = await global.knex
|
||||
.table('config')
|
||||
.insert(configData)
|
||||
.returning('*');
|
||||
const config = await Config.query().insert(configData).returning('*');
|
||||
|
||||
return config;
|
||||
};
|
||||
|
@@ -1,5 +1,6 @@
|
||||
import appConfig from '../../src/config/app';
|
||||
import { AES } from 'crypto-js';
|
||||
import Connection from '../../src/models/connection';
|
||||
|
||||
export const createConnection = async (params = {}) => {
|
||||
params.key = params?.key || 'deepl';
|
||||
@@ -16,10 +17,7 @@ export const createConnection = async (params = {}) => {
|
||||
appConfig.encryptionKey
|
||||
).toString();
|
||||
|
||||
const [connection] = await global.knex
|
||||
.table('connections')
|
||||
.insert(params)
|
||||
.returning('*');
|
||||
const connection = await Connection.query().insert(params).returning('*');
|
||||
|
||||
return connection;
|
||||
};
|
||||
|
@@ -1,3 +1,4 @@
|
||||
import ExecutionStep from '../../src/models/execution-step';
|
||||
import { createExecution } from './execution';
|
||||
import { createStep } from './step';
|
||||
|
||||
@@ -8,8 +9,7 @@ export const createExecutionStep = async (params = {}) => {
|
||||
params.dataIn = params?.dataIn || { dataIn: 'dataIn' };
|
||||
params.dataOut = params?.dataOut || { dataOut: 'dataOut' };
|
||||
|
||||
const [executionStep] = await global.knex
|
||||
.table('executionSteps')
|
||||
const executionStep = await ExecutionStep.query()
|
||||
.insert(params)
|
||||
.returning('*');
|
||||
|
||||
|
@@ -1,3 +1,4 @@
|
||||
import Execution from '../../src/models/execution';
|
||||
import { createFlow } from './flow';
|
||||
|
||||
export const createExecution = async (params = {}) => {
|
||||
@@ -6,10 +7,7 @@ export const createExecution = async (params = {}) => {
|
||||
params.createdAt = params?.createdAt || new Date().toISOString();
|
||||
params.updatedAt = params?.updatedAt || new Date().toISOString();
|
||||
|
||||
const [execution] = await global.knex
|
||||
.table('executions')
|
||||
.insert(params)
|
||||
.returning('*');
|
||||
const execution = await Execution.query().insert(params).returning('*');
|
||||
|
||||
return execution;
|
||||
};
|
||||
|
@@ -1,3 +1,4 @@
|
||||
import Flow from '../../src/models/flow';
|
||||
import { createUser } from './user';
|
||||
|
||||
export const createFlow = async (params = {}) => {
|
||||
@@ -6,7 +7,7 @@ export const createFlow = async (params = {}) => {
|
||||
params.createdAt = params?.createdAt || new Date().toISOString();
|
||||
params.updatedAt = params?.updatedAt || new Date().toISOString();
|
||||
|
||||
const [flow] = await global.knex.table('flows').insert(params).returning('*');
|
||||
const flow = await Flow.query().insert(params).returning('*');
|
||||
|
||||
return flow;
|
||||
};
|
||||
|
@@ -1,3 +1,4 @@
|
||||
import Permission from '../../src/models/permission';
|
||||
import { createRole } from './role';
|
||||
|
||||
export const createPermission = async (params = {}) => {
|
||||
@@ -6,10 +7,7 @@ export const createPermission = async (params = {}) => {
|
||||
params.subject = params?.subject || 'User';
|
||||
params.conditions = params?.conditions || ['isCreator'];
|
||||
|
||||
const [permission] = await global.knex
|
||||
.table('permissions')
|
||||
.insert(params)
|
||||
.returning('*');
|
||||
const permission = await Permission.query().insert(params).returning('*');
|
||||
|
||||
return permission;
|
||||
};
|
||||
|
@@ -1,8 +1,10 @@
|
||||
import Role from '../../src/models/role';
|
||||
|
||||
export const createRole = async (params = {}) => {
|
||||
params.name = params?.name || 'Viewer';
|
||||
params.key = params?.key || 'viewer';
|
||||
|
||||
const [role] = await global.knex.table('roles').insert(params).returning('*');
|
||||
const role = await Role.query().insert(params).returning('*');
|
||||
|
||||
return role;
|
||||
};
|
||||
|
@@ -1,3 +1,4 @@
|
||||
import Step from '../../src/models/step';
|
||||
import { createFlow } from './flow';
|
||||
|
||||
export const createStep = async (params = {}) => {
|
||||
@@ -16,7 +17,7 @@ export const createStep = async (params = {}) => {
|
||||
params.appKey =
|
||||
params?.appKey || (params.type === 'action' ? 'deepl' : 'webhook');
|
||||
|
||||
const [step] = await global.knex.table('steps').insert(params).returning('*');
|
||||
const step = await Step.query().insert(params).returning('*');
|
||||
|
||||
return step;
|
||||
};
|
||||
|
@@ -1,5 +1,6 @@
|
||||
import { createRole } from './role';
|
||||
import { faker } from '@faker-js/faker';
|
||||
import User from '../../src/models/user';
|
||||
|
||||
export const createUser = async (params = {}) => {
|
||||
params.roleId = params?.roleId || (await createRole()).id;
|
||||
@@ -7,7 +8,7 @@ export const createUser = async (params = {}) => {
|
||||
params.email = params?.email || faker.internet.email();
|
||||
params.password = params?.password || faker.internet.password();
|
||||
|
||||
const [user] = await global.knex.table('users').insert(params).returning('*');
|
||||
const user = await User.query().insert(params).returning('*');
|
||||
|
||||
return user;
|
||||
};
|
||||
|
@@ -0,0 +1,32 @@
|
||||
const getCurrentUserMock = (currentUser, role) => {
|
||||
return {
|
||||
data: {
|
||||
createdAt: currentUser.createdAt.toISOString(),
|
||||
email: currentUser.email,
|
||||
fullName: currentUser.fullName,
|
||||
id: currentUser.id,
|
||||
permissions: [],
|
||||
role: {
|
||||
createdAt: role.createdAt.toISOString(),
|
||||
description: null,
|
||||
id: role.id,
|
||||
isAdmin: role.isAdmin,
|
||||
key: role.key,
|
||||
name: role.name,
|
||||
updatedAt: role.updatedAt.toISOString(),
|
||||
},
|
||||
roleId: role.id,
|
||||
trialExpiryDate: currentUser.trialExpiryDate.toISOString(),
|
||||
updatedAt: currentUser.updatedAt.toISOString(),
|
||||
},
|
||||
meta: {
|
||||
count: 1,
|
||||
currentPage: null,
|
||||
isArray: false,
|
||||
totalPages: null,
|
||||
type: 'User',
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default getCurrentUserMock;
|
@@ -0,0 +1,17 @@
|
||||
const getUserTrialMock = async (currentUser) => {
|
||||
return {
|
||||
data: {
|
||||
inTrial: await currentUser.inTrial(),
|
||||
expireAt: currentUser.trialExpiryDate.toISOString(),
|
||||
},
|
||||
meta: {
|
||||
count: 1,
|
||||
currentPage: null,
|
||||
isArray: false,
|
||||
totalPages: null,
|
||||
type: 'Object',
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default getUserTrialMock;
|
31
packages/backend/test/mocks/rest/api/v1/users/get-user.js
Normal file
31
packages/backend/test/mocks/rest/api/v1/users/get-user.js
Normal file
@@ -0,0 +1,31 @@
|
||||
const getUserMock = (currentUser, role) => {
|
||||
return {
|
||||
data: {
|
||||
createdAt: currentUser.createdAt.toISOString(),
|
||||
email: currentUser.email,
|
||||
fullName: currentUser.fullName,
|
||||
id: currentUser.id,
|
||||
role: {
|
||||
createdAt: role.createdAt.toISOString(),
|
||||
description: null,
|
||||
id: role.id,
|
||||
isAdmin: role.isAdmin,
|
||||
key: role.key,
|
||||
name: role.name,
|
||||
updatedAt: role.updatedAt.toISOString(),
|
||||
},
|
||||
roleId: role.id,
|
||||
trialExpiryDate: currentUser.trialExpiryDate.toISOString(),
|
||||
updatedAt: currentUser.updatedAt.toISOString(),
|
||||
},
|
||||
meta: {
|
||||
count: 1,
|
||||
currentPage: null,
|
||||
isArray: false,
|
||||
totalPages: null,
|
||||
type: 'User',
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default getUserMock;
|
38
packages/backend/test/mocks/rest/api/v1/users/get-users.js
Normal file
38
packages/backend/test/mocks/rest/api/v1/users/get-users.js
Normal file
@@ -0,0 +1,38 @@
|
||||
const getUsersMock = async (users, roles) => {
|
||||
const data = users.map((user) => {
|
||||
const role = roles.find((r) => r.id === user.roleId);
|
||||
return {
|
||||
createdAt: user.createdAt.toISOString(),
|
||||
email: user.email,
|
||||
fullName: user.fullName,
|
||||
id: user.id,
|
||||
role: role
|
||||
? {
|
||||
createdAt: role.createdAt.toISOString(),
|
||||
description: role.description,
|
||||
id: role.id,
|
||||
isAdmin: role.isAdmin,
|
||||
key: role.key,
|
||||
name: role.name,
|
||||
updatedAt: role.updatedAt.toISOString(),
|
||||
}
|
||||
: null, // Fallback to null if role not found
|
||||
roleId: user.roleId,
|
||||
trialExpiryDate: user.trialExpiryDate.toISOString(),
|
||||
updatedAt: user.updatedAt.toISOString(),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
data: data,
|
||||
meta: {
|
||||
count: data.length,
|
||||
currentPage: 1,
|
||||
isArray: true,
|
||||
totalPages: 1,
|
||||
type: 'User',
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default getUsersMock;
|
@@ -1,11 +0,0 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
@@ -1 +0,0 @@
|
||||
/dist
|
16
packages/cli/.github/dependabot.yml
vendored
16
packages/cli/.github/dependabot.yml
vendored
@@ -1,16 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: 'npm'
|
||||
versioning-strategy: increase
|
||||
directory: '/'
|
||||
schedule:
|
||||
interval: 'monthly'
|
||||
labels:
|
||||
- 'dependencies'
|
||||
open-pull-requests-limit: 100
|
||||
pull-request-branch-name:
|
||||
separator: '-'
|
||||
ignore:
|
||||
- dependency-name: 'fs-extra'
|
||||
- dependency-name: '*'
|
||||
update-types: ['version-update:semver-major']
|
9
packages/cli/.gitignore
vendored
9
packages/cli/.gitignore
vendored
@@ -1,9 +0,0 @@
|
||||
*-debug.log
|
||||
*-error.log
|
||||
/.nyc_output
|
||||
/dist
|
||||
/lib
|
||||
/package-lock.json
|
||||
/tmp
|
||||
node_modules
|
||||
oclif.manifest.json
|
@@ -1,4 +0,0 @@
|
||||
# `@automatisch/cli`
|
||||
|
||||
The open source Zapier alternative. Build workflow automation without spending
|
||||
time and money.
|
@@ -1,5 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
const oclif = require('@oclif/core')
|
||||
|
||||
oclif.run().then(require('@oclif/core/flush')).catch(require('@oclif/core/handle'))
|
@@ -1,3 +0,0 @@
|
||||
@echo off
|
||||
|
||||
node "%~dp0\automatisch" %*
|
@@ -1,73 +0,0 @@
|
||||
{
|
||||
"name": "@automatisch/cli",
|
||||
"version": "0.10.0",
|
||||
"license": "See LICENSE file",
|
||||
"description": "The open source Zapier alternative. Build workflow automation without spending time and money.",
|
||||
"contributors": [
|
||||
{
|
||||
"name": "automatisch contributors",
|
||||
"url": "https://github.com/automatisch/automatisch/graphs/contributors"
|
||||
}
|
||||
],
|
||||
"homepage": "https://github.com/automatisch/automatisch#readme",
|
||||
"main": "dist/index.js",
|
||||
"bin": {
|
||||
"automatisch": "./bin/automatisch"
|
||||
},
|
||||
"files": [
|
||||
"/bin",
|
||||
"/dist",
|
||||
"oclif.manifest.json"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/automatisch/automatisch.git"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "shx rm -rf dist && tsc -b",
|
||||
"build:watch": "nodemon --watch 'src/**/*.ts' --exec 'shx rm -rf dist && tsc -b' --ext 'ts'",
|
||||
"lint": "eslint . --ext .js --ignore-path ../../.eslintignore",
|
||||
"postpack": "shx rm -f oclif.manifest.json",
|
||||
"posttest": "yarn lint",
|
||||
"prepack": "yarn build && oclif manifest && oclif readme",
|
||||
"version": "oclif readme && git add README.md"
|
||||
},
|
||||
"dependencies": {
|
||||
"@automatisch/backend": "^0.10.0",
|
||||
"@oclif/core": "^1",
|
||||
"@oclif/plugin-help": "^5",
|
||||
"@oclif/plugin-plugins": "^2.0.1",
|
||||
"dotenv": "^10.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@oclif/test": "^2",
|
||||
"@types/node": "^16.9.4",
|
||||
"eslint-config-oclif": "^4",
|
||||
"eslint-config-oclif-typescript": "^1.0.2",
|
||||
"globby": "^11",
|
||||
"oclif": "^2",
|
||||
"shx": "^0.3.3",
|
||||
"ts-node": "^10.2.1",
|
||||
"tslib": "^2.3.1",
|
||||
"typescript": "^4.6.3"
|
||||
},
|
||||
"oclif": {
|
||||
"bin": "automatisch",
|
||||
"dirname": "automatisch",
|
||||
"commands": "./dist/commands",
|
||||
"plugins": [
|
||||
"@oclif/plugin-help",
|
||||
"@oclif/plugin-plugins"
|
||||
]
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/automatisch/automatisch/issues"
|
||||
},
|
||||
"types": "dist/index.d.ts",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
@@ -1,50 +0,0 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { Command, Flags } from '@oclif/core';
|
||||
import * as dotenv from 'dotenv';
|
||||
import process from 'process';
|
||||
|
||||
export default class StartWorker extends Command {
|
||||
static description = 'Run automatisch worker';
|
||||
|
||||
static flags = {
|
||||
env: Flags.string({
|
||||
multiple: true,
|
||||
char: 'e',
|
||||
}),
|
||||
'env-file': Flags.string(),
|
||||
};
|
||||
|
||||
async prepareEnvVars() {
|
||||
const { flags } = await this.parse(StartWorker);
|
||||
|
||||
if (flags['env-file']) {
|
||||
const envFile = readFileSync(flags['env-file'], 'utf8');
|
||||
const envConfig = dotenv.parse(envFile);
|
||||
|
||||
for (const key in envConfig) {
|
||||
const value = envConfig[key];
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
if (flags.env) {
|
||||
for (const env of flags.env) {
|
||||
const [key, value] = env.split('=');
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
// must serve until more customization is introduced
|
||||
delete process.env.SERVE_WEB_APP_SEPARATELY;
|
||||
}
|
||||
|
||||
async runWorker() {
|
||||
await import('@automatisch/backend/worker');
|
||||
}
|
||||
|
||||
async run() {
|
||||
await this.prepareEnvVars();
|
||||
|
||||
await this.runWorker();
|
||||
}
|
||||
}
|
@@ -1,96 +0,0 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { Command, Flags } from '@oclif/core';
|
||||
import * as dotenv from 'dotenv';
|
||||
import process from 'process';
|
||||
|
||||
export default class Start extends Command {
|
||||
static description = 'Run automatisch';
|
||||
|
||||
static flags = {
|
||||
env: Flags.string({
|
||||
multiple: true,
|
||||
char: 'e',
|
||||
}),
|
||||
'env-file': Flags.string(),
|
||||
};
|
||||
|
||||
get isProduction() {
|
||||
return process.env.APP_ENV === 'production';
|
||||
}
|
||||
|
||||
async prepareEnvVars() {
|
||||
const { flags } = await this.parse(Start);
|
||||
|
||||
if (flags['env-file']) {
|
||||
const envFile = readFileSync(flags['env-file'], 'utf8');
|
||||
const envConfig = dotenv.parse(envFile);
|
||||
|
||||
for (const key in envConfig) {
|
||||
const value = envConfig[key];
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
if (flags.env) {
|
||||
for (const env of flags.env) {
|
||||
const [key, value] = env.split('=');
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
// must serve until more customization is introduced
|
||||
delete process.env.SERVE_WEB_APP_SEPARATELY;
|
||||
}
|
||||
|
||||
async createDatabaseAndUser() {
|
||||
const utils = await import('@automatisch/backend/database-utils');
|
||||
|
||||
await utils.createDatabaseAndUser(
|
||||
process.env.POSTGRES_DATABASE,
|
||||
process.env.POSTGRES_USERNAME
|
||||
);
|
||||
}
|
||||
|
||||
async runMigrationsIfNeeded() {
|
||||
const { logger } = await import('@automatisch/backend/logger');
|
||||
const database = await import('@automatisch/backend/database');
|
||||
const migrator = database.client.migrate;
|
||||
|
||||
const [, pendingMigrations] = await migrator.list();
|
||||
const pendingMigrationsCount = pendingMigrations.length;
|
||||
const needsToMigrate = pendingMigrationsCount > 0;
|
||||
|
||||
if (needsToMigrate) {
|
||||
logger.info(`Processing ${pendingMigrationsCount} migrations.`);
|
||||
|
||||
await migrator.latest();
|
||||
logger.info(`Completed ${pendingMigrationsCount} migrations.`);
|
||||
} else {
|
||||
logger.info('No migrations needed.');
|
||||
}
|
||||
}
|
||||
|
||||
async seedUser() {
|
||||
const utils = await import('@automatisch/backend/database-utils');
|
||||
|
||||
await utils.createUser();
|
||||
}
|
||||
|
||||
async runApp() {
|
||||
await import('@automatisch/backend/server');
|
||||
}
|
||||
|
||||
async run() {
|
||||
await this.prepareEnvVars();
|
||||
|
||||
if (!this.isProduction) {
|
||||
await this.createDatabaseAndUser();
|
||||
}
|
||||
|
||||
await this.runMigrationsIfNeeded();
|
||||
|
||||
await this.seedUser();
|
||||
|
||||
await this.runApp();
|
||||
}
|
||||
}
|
@@ -1 +0,0 @@
|
||||
export { run } from '@oclif/core';
|
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"declaration": true,
|
||||
"allowJs": true,
|
||||
"esModuleInterop": true,
|
||||
"importHelpers": true,
|
||||
"lib": ["es2021"],
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"noImplicitAny": false,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"target": "es2021",
|
||||
"typeRoots": ["node_modules/@types", "./src/types"]
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
15993
packages/cli/yarn.lock
15993
packages/cli/yarn.lock
File diff suppressed because it is too large
Load Diff
@@ -14,31 +14,33 @@ The default values for some environment variables might be different in our deve
|
||||
Please be careful with the `ENCRYPTION_KEY` and `WEBHOOK_SECRET_KEY` environment variables. They are used to encrypt your credentials from third-party services and verify webhook requests. If you change them, your existing connections and flows will not continue to work.
|
||||
:::
|
||||
|
||||
| Variable Name | Type | Default Value | Description |
|
||||
| --------------------------- | ------- | ------------------ | ---------------------------------------------------------------------------------------------------- |
|
||||
| `HOST` | string | `localhost` | HTTP Host |
|
||||
| `PROTOCOL` | string | `http` | HTTP Protocol |
|
||||
| `PORT` | string | `3000` | HTTP Port |
|
||||
| `APP_ENV` | string | `production` | Automatisch Environment |
|
||||
| `WEB_APP_URL` | string | | Can be used to override connection URLs and CORS URL |
|
||||
| `WEBHOOK_URL` | string | | Can be used to override webhook URL |
|
||||
| `LOG_LEVEL` | string | `info` | Can be used to configure log level such as `error`, `warn`, `info`, `http`, `debug` |
|
||||
| `POSTGRES_DATABASE` | string | `automatisch` | Database Name |
|
||||
| `POSTGRES_SCHEMA` | string | `public` | Database Schema |
|
||||
| `POSTGRES_PORT` | number | `5432` | Database Port |
|
||||
| `POSTGRES_ENABLE_SSL` | boolean | `false` | Enable/Disable SSL for the database |
|
||||
| `POSTGRES_HOST` | string | `postgres` | Database Host |
|
||||
| `POSTGRES_USERNAME` | string | `automatisch_user` | Database User |
|
||||
| `POSTGRES_PASSWORD` | string | | Password of Database User |
|
||||
| `ENCRYPTION_KEY` | string | | Encryption Key to store credentials |
|
||||
| `WEBHOOK_SECRET_KEY` | string | | Webhook Secret Key to verify webhook requests |
|
||||
| `APP_SECRET_KEY` | string | | Secret Key to authenticate the user |
|
||||
| `REDIS_HOST` | string | `redis` | Redis Host |
|
||||
| `REDIS_PORT` | number | `6379` | Redis Port |
|
||||
| `REDIS_USERNAME` | string | | Redis Username |
|
||||
| `REDIS_PASSWORD` | string | | Redis Password |
|
||||
| `REDIS_TLS` | boolean | `false` | Redis TLS |
|
||||
| `TELEMETRY_ENABLED` | boolean | `true` | Enable/Disable Telemetry |
|
||||
| `ENABLE_BULLMQ_DASHBOARD` | boolean | `false` | Enable BullMQ Dashboard |
|
||||
| `BULLMQ_DASHBOARD_USERNAME` | string | | Username to login BullMQ Dashboard |
|
||||
| `BULLMQ_DASHBOARD_PASSWORD` | string | | Password to login BullMQ Dashboard |
|
||||
| Variable Name | Type | Default Value | Description |
|
||||
| ---------------------------- | ------- | ------------------ | ----------------------------------------------------------------------------------- |
|
||||
| `HOST` | string | `localhost` | HTTP Host |
|
||||
| `PROTOCOL` | string | `http` | HTTP Protocol |
|
||||
| `PORT` | string | `3000` | HTTP Port |
|
||||
| `APP_ENV` | string | `production` | Automatisch Environment |
|
||||
| `WEB_APP_URL` | string | | Can be used to override connection URLs and CORS URL |
|
||||
| `WEBHOOK_URL` | string | | Can be used to override webhook URL |
|
||||
| `LOG_LEVEL` | string | `info` | Can be used to configure log level such as `error`, `warn`, `info`, `http`, `debug` |
|
||||
| `POSTGRES_DATABASE` | string | `automatisch` | Database Name |
|
||||
| `POSTGRES_SCHEMA` | string | `public` | Database Schema |
|
||||
| `POSTGRES_PORT` | number | `5432` | Database Port |
|
||||
| `POSTGRES_ENABLE_SSL` | boolean | `false` | Enable/Disable SSL for the database |
|
||||
| `POSTGRES_HOST` | string | `postgres` | Database Host |
|
||||
| `POSTGRES_USERNAME` | string | `automatisch_user` | Database User |
|
||||
| `POSTGRES_PASSWORD` | string | | Password of Database User |
|
||||
| `ENCRYPTION_KEY` | string | | Encryption Key to store credentials |
|
||||
| `WEBHOOK_SECRET_KEY` | string | | Webhook Secret Key to verify webhook requests |
|
||||
| `APP_SECRET_KEY` | string | | Secret Key to authenticate the user |
|
||||
| `REDIS_HOST` | string | `redis` | Redis Host |
|
||||
| `REDIS_PORT` | number | `6379` | Redis Port |
|
||||
| `REDIS_USERNAME` | string | | Redis Username |
|
||||
| `REDIS_PASSWORD` | string | | Redis Password |
|
||||
| `REDIS_TLS` | boolean | `false` | Redis TLS |
|
||||
| `TELEMETRY_ENABLED` | boolean | `true` | Enable/Disable Telemetry |
|
||||
| `ENABLE_BULLMQ_DASHBOARD` | boolean | `false` | Enable BullMQ Dashboard |
|
||||
| `BULLMQ_DASHBOARD_USERNAME` | string | | Username to login BullMQ Dashboard |
|
||||
| `BULLMQ_DASHBOARD_PASSWORD` | string | | Password to login BullMQ Dashboard |
|
||||
| `DISABLE_NOTIFICATIONS_PAGE` | boolean | `false` | Enable/Disable notifications page |
|
||||
| `DISABLE_FAVICON` | boolean | `false` | Enable/Disable favicon |
|
||||
|
@@ -1,7 +1,7 @@
|
||||
# Telemetry
|
||||
|
||||
:::info
|
||||
We want to be very transparent about the data we collect and how we use it. Therefore, we have abstracted all of the code we use with our telemetry system into a single, easily accessible place. You can check the code [here](https://github.com/automatisch/automatisch/blob/main/packages/backend/src/helpers/telemetry/index.ts) and let us know if you have any suggestions for changes.
|
||||
We want to be very transparent about the data we collect and how we use it. Therefore, we have abstracted all of the code we use with our telemetry system into a single, easily accessible place. You can check the code [here](https://github.com/automatisch/automatisch/blob/main/packages/backend/src/helpers/telemetry/index.js) and let us know if you have any suggestions for changes.
|
||||
:::
|
||||
|
||||
Automatisch comes with a built-in telemetry system that collects anonymous usage data. This data is used to help us improve the product and to make sure we are focusing on the right features. While we're doing it, we don't collect any personal information. You can also disable the telemetry system by setting the `TELEMETRY_ENABLED` environment variable. See the [environment variables](/advanced/configuration#environment-variables) section for more information.
|
||||
|
@@ -16,13 +16,13 @@ The build integrations section is best understood when read from beginning to en
|
||||
|
||||
## Add actions to the app.
|
||||
|
||||
Open the `thecatapi/index.ts` file and add the highlighted lines for actions.
|
||||
Open the `thecatapi/index.js` file and add the highlighted lines for actions.
|
||||
|
||||
```typescript{4,17}
|
||||
import defineApp from '../../helpers/define-app';
|
||||
import auth from './auth';
|
||||
import triggers from './triggers';
|
||||
import actions from './actions';
|
||||
```javascript{4,17}
|
||||
import defineApp from '../../helpers/define-app.js';
|
||||
import auth from './auth/index.js';
|
||||
import triggers from './triggers/index.js';
|
||||
import actions from './actions/index.js';
|
||||
|
||||
export default defineApp({
|
||||
name: 'The cat API',
|
||||
@@ -41,24 +41,24 @@ export default defineApp({
|
||||
|
||||
## Define actions
|
||||
|
||||
Create the `actions/index.ts` file inside of the `thecatapi` folder.
|
||||
Create the `actions/index.js` file inside of the `thecatapi` folder.
|
||||
|
||||
```typescript
|
||||
import markCatImageAsFavorite from './mark-cat-image-as-favorite';
|
||||
```javascript
|
||||
import markCatImageAsFavorite from './mark-cat-image-as-favorite/index.js';
|
||||
|
||||
export default [markCatImageAsFavorite];
|
||||
```
|
||||
|
||||
:::tip
|
||||
If you add new actions, you need to add them to the actions/index.ts file and export all actions as an array.
|
||||
If you add new actions, you need to add them to the actions/index.js file and export all actions as an array.
|
||||
:::
|
||||
|
||||
## Add metadata
|
||||
|
||||
Create the `actions/mark-cat-image-as-favorite/index.ts` file inside the `thecatapi` folder.
|
||||
Create the `actions/mark-cat-image-as-favorite/index.js` file inside the `thecatapi` folder.
|
||||
|
||||
```typescript
|
||||
import defineAction from '../../../../helpers/define-action';
|
||||
```javascript
|
||||
import defineAction from '../../../../helpers/define-action.js';
|
||||
|
||||
export default defineAction({
|
||||
name: 'Mark the cat image as favorite',
|
||||
@@ -68,7 +68,7 @@ export default defineAction({
|
||||
{
|
||||
label: 'Image ID',
|
||||
key: 'imageId',
|
||||
type: 'string' as const,
|
||||
type: 'string',
|
||||
required: true,
|
||||
description: 'The ID of the cat image you want to mark as favorite.',
|
||||
variables: true,
|
||||
@@ -91,10 +91,10 @@ Let's briefly explain what we defined here.
|
||||
|
||||
## Implement the action
|
||||
|
||||
Open the `actions/mark-cat-image-as-favorite.ts` file and add the highlighted lines.
|
||||
Open the `actions/mark-cat-image-as-favorite.js` file and add the highlighted lines.
|
||||
|
||||
```typescript{7-20}
|
||||
import defineAction from '../../../../helpers/define-action';
|
||||
```javascript{7-20}
|
||||
import defineAction from '../../../../helpers/define-action.js';
|
||||
|
||||
export default defineAction({
|
||||
// ...
|
||||
@@ -104,7 +104,7 @@ export default defineAction({
|
||||
const imageId = $.step.parameters.imageId;
|
||||
|
||||
const headers = {
|
||||
'x-api-key': $.auth.data.apiKey as string,
|
||||
'x-api-key': $.auth.data.apiKey,
|
||||
};
|
||||
|
||||
const response = await $.http.post(
|
||||
|
@@ -27,17 +27,17 @@ cd packages/backend/src/apps
|
||||
mkdir thecatapi
|
||||
```
|
||||
|
||||
We need to create an `index.ts` file inside of the `thecatapi` folder.
|
||||
We need to create an `index.js` file inside of the `thecatapi` folder.
|
||||
|
||||
```bash
|
||||
cd thecatapi
|
||||
touch index.ts
|
||||
touch index.js
|
||||
```
|
||||
|
||||
Then let's define the app inside of the `index.ts` file as follows:
|
||||
Then let's define the app inside of the `index.js` file as follows:
|
||||
|
||||
```typescript
|
||||
import defineApp from '../../helpers/define-app';
|
||||
```javascript
|
||||
import defineApp from '../../helpers/define-app.js';
|
||||
|
||||
export default defineApp({
|
||||
name: 'The cat API',
|
||||
|
@@ -24,11 +24,11 @@ You can find detailed documentation of the cat API [here](https://docs.thecatapi
|
||||
|
||||
## Add auth to the app
|
||||
|
||||
Open the `thecatapi/index.ts` file and add the highlighted lines for authentication.
|
||||
Open the `thecatapi/index.js` file and add the highlighted lines for authentication.
|
||||
|
||||
```typescript{2,13}
|
||||
import defineApp from '../../helpers/define-app';
|
||||
import auth from './auth';
|
||||
```javascript{2,13}
|
||||
import defineApp from '../../helpers/define-app.js';
|
||||
import auth from './auth/index.js';
|
||||
|
||||
export default defineApp({
|
||||
name: 'The cat API',
|
||||
@@ -45,22 +45,22 @@ export default defineApp({
|
||||
|
||||
## Define auth fields
|
||||
|
||||
Let's create the `auth/index.ts` file inside of the `thecatapi` folder.
|
||||
Let's create the `auth/index.js` file inside of the `thecatapi` folder.
|
||||
|
||||
```bash
|
||||
mkdir auth
|
||||
touch auth/index.ts
|
||||
touch auth/index.js
|
||||
```
|
||||
|
||||
Then let's start with defining fields the auth inside of the `auth/index.ts` file as follows:
|
||||
Then let's start with defining fields the auth inside of the `auth/index.js` file as follows:
|
||||
|
||||
```typescript
|
||||
```javascript
|
||||
export default {
|
||||
fields: [
|
||||
{
|
||||
key: 'screenName',
|
||||
label: 'Screen Name',
|
||||
type: 'string' as const,
|
||||
type: 'string',
|
||||
required: true,
|
||||
readOnly: false,
|
||||
value: null,
|
||||
@@ -72,7 +72,7 @@ export default {
|
||||
{
|
||||
key: 'apiKey',
|
||||
label: 'API Key',
|
||||
type: 'string' as const,
|
||||
type: 'string',
|
||||
required: true,
|
||||
readOnly: false,
|
||||
value: null,
|
||||
@@ -101,10 +101,10 @@ If the third-party service you use provides both an API key and OAuth for the au
|
||||
|
||||
So until now, we integrated auth folder with the app definition and defined the auth fields. Now we need to verify the credentials that the user entered. We will do that by defining the `verifyCredentials` method.
|
||||
|
||||
Start with adding the `verifyCredentials` method to the `auth/index.ts` file.
|
||||
Start with adding the `verifyCredentials` method to the `auth/index.js` file.
|
||||
|
||||
```typescript{1,8}
|
||||
import verifyCredentials from './verify-credentials';
|
||||
```javascript{1,8}
|
||||
import verifyCredentials from './verify-credentials.js';
|
||||
|
||||
export default {
|
||||
fields: [
|
||||
@@ -115,12 +115,10 @@ export default {
|
||||
};
|
||||
```
|
||||
|
||||
Let's create the `verify-credentials.ts` file inside the `auth` folder.
|
||||
Let's create the `verify-credentials.js` file inside the `auth` folder.
|
||||
|
||||
```typescript
|
||||
import { IGlobalVariable } from '@automatisch/types';
|
||||
|
||||
const verifyCredentials = async ($: IGlobalVariable) => {
|
||||
```javascript
|
||||
const verifyCredentials = async ($) => {
|
||||
// TODO: Implement verification of the credentials
|
||||
};
|
||||
|
||||
@@ -129,12 +127,10 @@ export default verifyCredentials;
|
||||
|
||||
We generally use the `users/me` endpoint or any other endpoint that we can validate the API key or any other credentials that the user provides. For our example, we don't have a specific API endpoint to check whether the credentials are correct or not. So we will randomly pick one of the API endpoints, which will be the `GET /v1/images/search` endpoint. We will send a request to this endpoint with the API key. If the API key is correct, we will get a response from the API. If the API key is incorrect, we will get an error response from the API.
|
||||
|
||||
Let's implement the authentication logic that we mentioned above in the `verify-credentials.ts` file.
|
||||
Let's implement the authentication logic that we mentioned above in the `verify-credentials.js` file.
|
||||
|
||||
```typescript
|
||||
import { IGlobalVariable } from '@automatisch/types';
|
||||
|
||||
const verifyCredentials = async ($: IGlobalVariable) => {
|
||||
```javascript
|
||||
const verifyCredentials = async ($) => {
|
||||
await $.http.get('/v1/images/search');
|
||||
|
||||
await $.auth.set({
|
||||
@@ -155,11 +151,11 @@ You must always provide a `screenName` field to auth data in the `verifyCredenti
|
||||
|
||||
We have implemented the `verifyCredentials` method. Now we need to check whether the credentials are still valid or not for the test connection functionality in Automatisch. We will do that by defining the `isStillVerified` method.
|
||||
|
||||
Start with adding the `isStillVerified` method to the `auth/index.ts` file.
|
||||
Start with adding the `isStillVerified` method to the `auth/index.js` file.
|
||||
|
||||
```typescript{2,10}
|
||||
import verifyCredentials from './verify-credentials';
|
||||
import isStillVerified from './is-still-verified';
|
||||
```javascript{2,10}
|
||||
import verifyCredentials from './verify-credentials.js';
|
||||
import isStillVerified from './is-still-verified.js';
|
||||
|
||||
export default {
|
||||
fields: [
|
||||
@@ -171,13 +167,12 @@ export default {
|
||||
};
|
||||
```
|
||||
|
||||
Let's create the `is-still-verified.ts` file inside the `auth` folder.
|
||||
Let's create the `is-still-verified.js` file inside the `auth` folder.
|
||||
|
||||
```typescript
|
||||
import { IGlobalVariable } from '@automatisch/types';
|
||||
import verifyCredentials from './verify-credentials';
|
||||
```javascript
|
||||
import verifyCredentials from './verify-credentials.js';
|
||||
|
||||
const isStillVerified = async ($: IGlobalVariable) => {
|
||||
const isStillVerified = async ($) => {
|
||||
await verifyCredentials($);
|
||||
return true;
|
||||
};
|
||||
|
@@ -18,35 +18,35 @@ The build integrations section is best understood when read from beginning to en
|
||||
|
||||
### 3-legged OAuth
|
||||
|
||||
- [Discord](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/discord/auth/index.ts)
|
||||
- [Flickr](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/flickr/auth/index.ts)
|
||||
- [Github](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/github/auth/index.ts)
|
||||
- [Salesforce](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/salesforce/auth/index.ts)
|
||||
- [Slack](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/slack/auth/index.ts)
|
||||
- [Twitter](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twitter/auth/index.ts)
|
||||
- [Discord](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/discord/auth/index.js)
|
||||
- [Flickr](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/flickr/auth/index.js)
|
||||
- [Github](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/github/auth/index.js)
|
||||
- [Salesforce](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/salesforce/auth/index.js)
|
||||
- [Slack](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/slack/auth/index.js)
|
||||
- [Twitter](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twitter/auth/index.js)
|
||||
|
||||
### OAuth with the refresh token
|
||||
|
||||
- [Salesforce](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/salesforce/auth/index.ts)
|
||||
- [Salesforce](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/salesforce/auth/index.js)
|
||||
|
||||
### API key
|
||||
|
||||
- [DeepL](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/deepl/auth/index.ts)
|
||||
- [Twilio](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twilio/auth/index.ts)
|
||||
- [SignalWire](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/signalwire/auth/index.ts)
|
||||
- [SMTP](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/smtp/auth/index.ts)
|
||||
- [DeepL](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/deepl/auth/index.js)
|
||||
- [Twilio](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twilio/auth/index.js)
|
||||
- [SignalWire](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/signalwire/auth/index.js)
|
||||
- [SMTP](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/smtp/auth/index.js)
|
||||
|
||||
### Without authentication
|
||||
|
||||
- [RSS](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/rss/index.ts)
|
||||
- [Scheduler](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/scheduler/index.ts)
|
||||
- [RSS](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/rss/index.js)
|
||||
- [Scheduler](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/scheduler/index.js)
|
||||
|
||||
## Triggers
|
||||
|
||||
### Polling-based triggers
|
||||
|
||||
- [Search tweets - Twitter](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twitter/triggers/search-tweets/index.ts)
|
||||
- [New issues - Github](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/github/triggers/new-issues/index.ts)
|
||||
- [Search tweets - Twitter](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twitter/triggers/search-tweets/index.js)
|
||||
- [New issues - Github](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/github/triggers/new-issues/index.js)
|
||||
|
||||
### Webhook-based triggers
|
||||
|
||||
@@ -54,27 +54,27 @@ The build integrations section is best understood when read from beginning to en
|
||||
If you are developing a webhook-based trigger, you need to ensure that the webhook is publicly accessible. You can use [ngrok](https://ngrok.com) for this purpose and override the webhook URL by setting the **WEBHOOK_URL** environment variable.
|
||||
:::
|
||||
|
||||
- [New entry - Typeform](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/typeform/triggers/new-entry/index.ts)
|
||||
- [New entry - Typeform](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/typeform/triggers/new-entry/index.js)
|
||||
|
||||
### Pagination with descending order
|
||||
|
||||
- [Search tweets - Twitter](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twitter/triggers/search-tweets/index.ts)
|
||||
- [New issues - Github](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/github/triggers/new-issues/index.ts)
|
||||
- [Receive SMS - Twilio](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twilio/triggers/receive-sms/index.ts)
|
||||
- [Receive SMS - SignalWire](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/signalwire/triggers/receive-sms/index.ts)
|
||||
- [New photos - Flickr](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/flickr/triggers/new-photos/index.ts)
|
||||
- [Search tweets - Twitter](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twitter/triggers/search-tweets/index.js)
|
||||
- [New issues - Github](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/github/triggers/new-issues/index.js)
|
||||
- [Receive SMS - Twilio](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twilio/triggers/receive-sms/index.js)
|
||||
- [Receive SMS - SignalWire](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/signalwire/triggers/receive-sms/index.js)
|
||||
- [New photos - Flickr](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/flickr/triggers/new-photos/index.js)
|
||||
|
||||
### Pagination with ascending order
|
||||
|
||||
- [New stargazers - Github](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/github/triggers/new-stargazers/index.ts)
|
||||
- [New watchers - Github](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/github/triggers/new-watchers/index.ts)
|
||||
- [New stargazers - Github](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/github/triggers/new-stargazers/index.js)
|
||||
- [New watchers - Github](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/github/triggers/new-watchers/index.js)
|
||||
|
||||
## Actions
|
||||
|
||||
- [Send a message to channel - Slack](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/slack/actions/send-a-message-to-channel/index.ts)
|
||||
- [Send SMS - Twilio](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twilio/actions/send-sms/index.ts)
|
||||
- [Send a message to channel - Discord](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/discord/actions/send-message-to-channel/index.ts)
|
||||
- [Create issue - Github](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/github/actions/create-issue/index.ts)
|
||||
- [Send an email - SMTP](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/smtp/actions/send-email/index.ts)
|
||||
- [Create tweet - Twitter](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twitter/actions/create-tweet/index.ts)
|
||||
- [Translate text - DeepL](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/deepl/actions/translate-text/index.ts)
|
||||
- [Send a message to channel - Slack](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/slack/actions/send-a-message-to-channel/index.js)
|
||||
- [Send SMS - Twilio](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twilio/actions/send-sms/index.js)
|
||||
- [Send a message to channel - Discord](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/discord/actions/send-message-to-channel/index.js)
|
||||
- [Create issue - Github](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/github/actions/create-issue/index.js)
|
||||
- [Send an email - SMTP](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/smtp/actions/send-email/index.js)
|
||||
- [Create tweet - Twitter](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/twitter/actions/create-tweet/index.js)
|
||||
- [Translate text - DeepL](https://github.com/automatisch/automatisch/tree/main/packages/backend/src/apps/deepl/actions/translate-text/index.js)
|
||||
|
@@ -35,13 +35,13 @@ Here, you can see the folder structure of an example app. We will briefly walk t
|
||||
├── auth
|
||||
├── common
|
||||
├── dynamic-data
|
||||
├── index.ts
|
||||
├── index.js
|
||||
└── triggers
|
||||
```
|
||||
|
||||
## App
|
||||
|
||||
The `index.ts` file is the entry point of the app. It contains the definition of the app and the app's metadata. It also includes the list of triggers, actions, and data sources that the app provides. So, whatever you build inside the app, you need to associate it within the `index.ts` file.
|
||||
The `index.js` file is the entry point of the app. It contains the definition of the app and the app's metadata. It also includes the list of triggers, actions, and data sources that the app provides. So, whatever you build inside the app, you need to associate it within the `index.js` file.
|
||||
|
||||
## Auth
|
||||
|
||||
|
@@ -16,11 +16,11 @@ The build integrations section is best understood when read from beginning to en
|
||||
|
||||
Before handling authentication and building a trigger and an action, it's better to explain the `global variable` concept in Automatisch. Automatisch provides you the global variable that you need to use with authentication, triggers, actions, and basically all the stuff you will build for the integration.
|
||||
|
||||
The global variable is represented as `$` variable in the codebase, and it's a JSON object that contains the following properties:
|
||||
The global variable is represented as `$` variable in the codebase, and it's a JS object that contains the following properties:
|
||||
|
||||
## $.auth.set
|
||||
|
||||
```typescript
|
||||
```javascript
|
||||
await $.auth.set({
|
||||
key: 'value',
|
||||
});
|
||||
@@ -30,7 +30,7 @@ It's used to set the authentication data, and you can use this method with multi
|
||||
|
||||
## $.auth.data
|
||||
|
||||
```typescript
|
||||
```javascript
|
||||
$.auth.data; // { key: 'value' }
|
||||
```
|
||||
|
||||
@@ -38,7 +38,7 @@ It's used to retrieve the authentication data that we set with `$.auth.set()`. T
|
||||
|
||||
## $.app.baseUrl
|
||||
|
||||
```typescript
|
||||
```javascript
|
||||
$.app.baseUrl; // https://thecatapi.com
|
||||
```
|
||||
|
||||
@@ -46,7 +46,7 @@ It's used to retrieve the base URL of the app that we defined previously. In our
|
||||
|
||||
## $.app.apiBaseUrl
|
||||
|
||||
```typescript
|
||||
```javascript
|
||||
$.app.apiBaseUrl; // https://api.thecatapi.com
|
||||
```
|
||||
|
||||
@@ -54,7 +54,7 @@ It's used to retrieve the API base URL of the app that we defined previously. In
|
||||
|
||||
## $.app.auth.fields
|
||||
|
||||
```typescript
|
||||
```javascript
|
||||
$.app.auth.fields;
|
||||
```
|
||||
|
||||
@@ -64,7 +64,7 @@ It's used to retrieve the fields that we defined in the `auth` section of the ap
|
||||
|
||||
It's an HTTP client to be used for making HTTP requests. It's a wrapper around the [axios](https://axios-http.com) library. We use this property when we need to make HTTP requests to the third-party service. The `apiBaseUrl` field we set up in the app will be used as the base URL for the HTTP requests. For example, to search the cat images, we can use the following code:
|
||||
|
||||
```typescript
|
||||
```javascript
|
||||
await $.http.get('/v1/images/search?order=DESC', {
|
||||
headers: {
|
||||
'x-api-key': $.auth.data.apiKey,
|
||||
@@ -76,15 +76,15 @@ Keep in mind that the HTTP client handles the error with the status code that fa
|
||||
|
||||
## $.step.parameters
|
||||
|
||||
```typescript
|
||||
```javascript
|
||||
$.step.parameters; // { key: 'value' }
|
||||
```
|
||||
|
||||
It refers to the parameters that are set by users in the UI. We use this property when we need to get the parameters for corresponding triggers and actions. For example [Send a message to channel](https://github.com/automatisch/automatisch/blob/main/packages/backend/src/apps/slack/actions/send-a-message-to-channel/post-message.ts) action from Slack integration, we have a step parameter called `message` that we need to use in the action. We can use `$.step.parameters.message` to get the value of the message to send a message to the Slack channel.
|
||||
It refers to the parameters that are set by users in the UI. We use this property when we need to get the parameters for corresponding triggers and actions. For example [Send a message to channel](https://github.com/automatisch/automatisch/blob/main/packages/backend/src/apps/slack/actions/send-a-message-to-channel/post-message.js) action from Slack integration, we have a step parameter called `message` that we need to use in the action. We can use `$.step.parameters.message` to get the value of the message to send a message to the Slack channel.
|
||||
|
||||
## $.pushTriggerItem
|
||||
|
||||
```typescript
|
||||
```javascript
|
||||
$.pushTriggerItem({
|
||||
raw: resourceData,
|
||||
meta: {
|
||||
@@ -97,7 +97,7 @@ It's used to push trigger data to be processed by Automatisch. It must reflect t
|
||||
|
||||
## $.setActionItem
|
||||
|
||||
```typescript
|
||||
```javascript
|
||||
$.setActionItem({
|
||||
raw: resourceData,
|
||||
});
|
||||
|
@@ -20,12 +20,12 @@ We used a polling-based HTTP trigger in our example but if you need to use a web
|
||||
|
||||
## Add triggers to the app
|
||||
|
||||
Open the `thecatapi/index.ts` file and add the highlighted lines for triggers.
|
||||
Open the `thecatapi/index.js` file and add the highlighted lines for triggers.
|
||||
|
||||
```typescript{3,15}
|
||||
import defineApp from '../../helpers/define-app';
|
||||
import auth from './auth';
|
||||
import triggers from './triggers';
|
||||
```javascript{3,15}
|
||||
import defineApp from '../../helpers/define-app.js';
|
||||
import auth from './auth/index.js';
|
||||
import triggers from './triggers/index.js';
|
||||
|
||||
export default defineApp({
|
||||
name: 'The cat API',
|
||||
@@ -43,24 +43,24 @@ export default defineApp({
|
||||
|
||||
## Define triggers
|
||||
|
||||
Create the `triggers/index.ts` file inside of the `thecatapi` folder.
|
||||
Create the `triggers/index.js` file inside of the `thecatapi` folder.
|
||||
|
||||
```typescript
|
||||
import searchCatImages from './search-cat-images';
|
||||
```javascript
|
||||
import searchCatImages from './search-cat-images/index.js';
|
||||
|
||||
export default [searchCatImages];
|
||||
```
|
||||
|
||||
:::tip
|
||||
If you add new triggers, you need to add them to the `triggers/index.ts` file and export all triggers as an array. The order of triggers in this array will be reflected in the Automatisch user interface.
|
||||
If you add new triggers, you need to add them to the `triggers/index.js` file and export all triggers as an array. The order of triggers in this array will be reflected in the Automatisch user interface.
|
||||
:::
|
||||
|
||||
## Add metadata
|
||||
|
||||
Create the `triggers/search-cat-images/index.ts` file inside of the `thecatapi` folder.
|
||||
Create the `triggers/search-cat-images/index.js` file inside of the `thecatapi` folder.
|
||||
|
||||
```typescript
|
||||
import defineTrigger from '../../../../helpers/define-trigger';
|
||||
```javascript
|
||||
import defineTrigger from '../../../../helpers/define-trigger.js';
|
||||
|
||||
export default defineTrigger({
|
||||
name: 'Search cat images',
|
||||
@@ -93,9 +93,8 @@ Let's briefly explain what we defined here.
|
||||
|
||||
Implement the `run` function by adding highlighted lines.
|
||||
|
||||
```typescript{1,7-30}
|
||||
import { IJSONObject } from '@automatisch/types';
|
||||
import defineTrigger from '../../../../helpers/define-trigger';
|
||||
```javascript{1,7-30}
|
||||
import defineTrigger from '../../../../helpers/define-trigger.js';
|
||||
|
||||
export default defineTrigger({
|
||||
// ...
|
||||
@@ -104,18 +103,18 @@ export default defineTrigger({
|
||||
let response;
|
||||
|
||||
const headers = {
|
||||
'x-api-key': $.auth.data.apiKey as string,
|
||||
'x-api-key': $.auth.data.apiKey,
|
||||
};
|
||||
|
||||
do {
|
||||
let requestPath = `/v1/images/search?page=${page}&limit=10&order=DESC`;
|
||||
response = await $.http.get(requestPath, { headers });
|
||||
|
||||
response.data.forEach((image: IJSONObject) => {
|
||||
response.data.forEach((image) => {
|
||||
const dataItem = {
|
||||
raw: image,
|
||||
meta: {
|
||||
internalId: image.id as string
|
||||
internalId: image.id
|
||||
},
|
||||
};
|
||||
|
||||
|
@@ -35,7 +35,7 @@ yarn db:create
|
||||
```
|
||||
|
||||
:::warning
|
||||
`yarn db:create` commands expect that you have the `postgres` superuser. If not, you can create a superuser called `postgres` manually or you can create the database manually by checking PostgreSQL-related default values from the [app config](https://github.com/automatisch/automatisch/blob/main/packages/backend/src/config/app.ts).
|
||||
`yarn db:create` commands expect that you have the `postgres` superuser. If not, you can create a superuser called `postgres` manually or you can create the database manually by checking PostgreSQL-related default values from the [app config](https://github.com/automatisch/automatisch/blob/main/packages/backend/src/config/app.js).
|
||||
:::
|
||||
|
||||
Run the database migrations in the backend folder.
|
||||
|
@@ -1,4 +0,0 @@
|
||||
# `@automatisch/types`
|
||||
|
||||
The open source Zapier alternative. Build workflow automation without spending
|
||||
time and money.
|
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"name": "@automatisch/types",
|
||||
"version": "0.10.0",
|
||||
"license": "See LICENSE file",
|
||||
"description": "Type definitions for automatisch",
|
||||
"homepage": "https://github.com/automatisch/automatisch",
|
||||
"types": "./index.d.ts",
|
||||
"scripts": {},
|
||||
"typeScriptVersion": "4.1",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/automatisch/automatisch.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/automatisch/automatisch/issues"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
@@ -5,7 +5,6 @@
|
||||
"description": "The open source Zapier alternative. Build workflow automation without spending time and money.",
|
||||
"dependencies": {
|
||||
"@apollo/client": "^3.6.9",
|
||||
"@automatisch/types": "^0.10.0",
|
||||
"@casl/ability": "^6.5.0",
|
||||
"@casl/react": "^3.1.0",
|
||||
"@emotion/react": "^11.4.1",
|
||||
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
@@ -2,7 +2,6 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#0059F7" />
|
||||
<meta
|
||||
|
@@ -2,13 +2,6 @@
|
||||
"short_name": "automatisch",
|
||||
"name": "automatisch",
|
||||
"description": "Build workflow automation without spending time and money. No code is required.",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
|
@@ -1,4 +1,4 @@
|
||||
import type { IApp, IField, IJSONObject } from '@automatisch/types';
|
||||
import type { IApp, IField, IJSONObject } from 'types';
|
||||
import LoadingButton from '@mui/lab/LoadingButton';
|
||||
import Alert from '@mui/material/Alert';
|
||||
import Dialog from '@mui/material/Dialog';
|
||||
|
@@ -19,7 +19,7 @@ import InputLabel from '@mui/material/InputLabel';
|
||||
import OutlinedInput from '@mui/material/OutlinedInput';
|
||||
import FormControl from '@mui/material/FormControl';
|
||||
import Box from '@mui/material/Box';
|
||||
import type { IApp } from '@automatisch/types';
|
||||
import type { IApp } from 'types';
|
||||
|
||||
import * as URLS from 'config/urls';
|
||||
import AppIcon from 'components/AppIcon';
|
||||
|
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import type { IField } from '@automatisch/types';
|
||||
import type { IField } from 'types';
|
||||
import LoadingButton from '@mui/lab/LoadingButton';
|
||||
import Alert from '@mui/material/Alert';
|
||||
import Dialog from '@mui/material/Dialog';
|
||||
|
@@ -1,5 +1,5 @@
|
||||
import React, { useCallback, useMemo } from 'react';
|
||||
import type { IApp } from '@automatisch/types';
|
||||
import type { IApp } from 'types';
|
||||
import { FieldValues, SubmitHandler } from 'react-hook-form';
|
||||
import { useMutation } from '@apollo/client';
|
||||
import { CREATE_APP_CONFIG } from 'graphql/mutations/create-app-config';
|
||||
|
@@ -1,6 +1,6 @@
|
||||
import React, { useCallback, useMemo } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import type { IApp } from '@automatisch/types';
|
||||
import type { IApp } from 'types';
|
||||
import { FieldValues, SubmitHandler } from 'react-hook-form';
|
||||
import { useMutation } from '@apollo/client';
|
||||
import { UPDATE_APP_AUTH_CLIENT } from 'graphql/mutations/update-app-auth-client';
|
||||
|
@@ -15,6 +15,7 @@ import { SvgIconComponent } from '@mui/icons-material';
|
||||
import AppBar from 'components/AppBar';
|
||||
import Drawer from 'components/Drawer';
|
||||
import * as URLS from 'config/urls';
|
||||
import useFormatMessage from 'hooks/useFormatMessage';
|
||||
import useCurrentUserAbility from 'hooks/useCurrentUserAbility';
|
||||
|
||||
type SettingsLayoutProps = {
|
||||
@@ -86,19 +87,11 @@ function createDrawerLinks({
|
||||
return items;
|
||||
}
|
||||
|
||||
const drawerBottomLinks = [
|
||||
{
|
||||
Icon: ArrowBackIosNewIcon,
|
||||
primary: 'adminSettingsDrawer.goBack',
|
||||
to: '/',
|
||||
dataTest: 'go-back-drawer-link',
|
||||
},
|
||||
];
|
||||
|
||||
export default function SettingsLayout({
|
||||
children,
|
||||
}: SettingsLayoutProps): React.ReactElement {
|
||||
const theme = useTheme();
|
||||
const formatMessage = useFormatMessage();
|
||||
const currentUserAbility = useCurrentUserAbility();
|
||||
const matchSmallScreens = useMediaQuery(theme.breakpoints.down('lg'));
|
||||
const [isDrawerOpen, setDrawerOpen] = React.useState(!matchSmallScreens);
|
||||
@@ -116,6 +109,15 @@ export default function SettingsLayout({
|
||||
canUpdateApp: currentUserAbility.can('update', 'App'),
|
||||
});
|
||||
|
||||
const drawerBottomLinks = [
|
||||
{
|
||||
Icon: ArrowBackIosNewIcon,
|
||||
primary: formatMessage('adminSettingsDrawer.goBack'),
|
||||
to: '/',
|
||||
dataTest: 'go-back-drawer-link',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<AppBar
|
||||
|
@@ -3,7 +3,7 @@ import { Link } from 'react-router-dom';
|
||||
import Menu from '@mui/material/Menu';
|
||||
import type { PopoverProps } from '@mui/material/Popover';
|
||||
import MenuItem from '@mui/material/MenuItem';
|
||||
import type { IConnection } from '@automatisch/types';
|
||||
import type { IConnection } from 'types';
|
||||
|
||||
import * as URLS from 'config/urls';
|
||||
import useFormatMessage from 'hooks/useFormatMessage';
|
||||
|
@@ -11,7 +11,7 @@ import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
|
||||
import { DateTime } from 'luxon';
|
||||
import * as React from 'react';
|
||||
|
||||
import type { IConnection } from '@automatisch/types';
|
||||
import type { IConnection } from 'types';
|
||||
import ConnectionContextMenu from 'components/AppConnectionContextMenu';
|
||||
import { DELETE_CONNECTION } from 'graphql/mutations/delete-connection';
|
||||
import { TEST_CONNECTION } from 'graphql/queries/test-connection';
|
||||
@@ -83,8 +83,8 @@ function AppConnectionRow(props: AppConnectionRowProps): React.ReactElement {
|
||||
enqueueSnackbar(formatMessage('connection.deletedMessage'), {
|
||||
variant: 'success',
|
||||
SnackbarProps: {
|
||||
'data-test': 'snackbar-delete-connection-success'
|
||||
}
|
||||
'data-test': 'snackbar-delete-connection-success',
|
||||
},
|
||||
});
|
||||
} else if (action.type === 'test') {
|
||||
setVerificationVisible(true);
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user