Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop #26

Merged
merged 7 commits into from
Jan 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions packages/backend/.env
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ AP_CACHE_PATH="./dev/cache"
AP_CHATBOT_ENABLED=true
AP_CONFIG_PATH="./dev/config"
AP_DB_TYPE=SQLITE3
AP_DEV_PIECES="github,ethereum,tookey-wallet,polygon-id,telegram-bot,discord,cryptomus"
AP_DEV_PIECES="tookey-wallet,instant-form"
AP_ENVIRONMENT="dev"
AP_FRONTEND_URL="http://localhost:4200"
# AP_FRONTEND_URL="http://localhost:4200"
AP_FRONTEND_URL="https://0329-64-226-96-123.ngrok-free.app"
AP_ENRICH_ERROR_CONTEXT=true
AP_LOG_LEVEL=debug
AP_LOG_PRETTY=true
Expand All @@ -27,4 +28,5 @@ AP_TELEMETRY_ID=<ID_HERE>

AP_CLOUD_AUTH_URL="http://localhost:3001/api/secrets"
AP_WEBHOOK_TIMEOUT_SECONDS=30
AP_WEBHOOK_URL="https://60fb-2-152-161-169.ngrok-free.app"
# AP_WEBHOOK_URL="http://localhost:3000"
AP_WEBHOOK_URL="https://e842-64-226-96-123.ngrok-free.app"
36 changes: 36 additions & 0 deletions packages/backend/src/app/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,42 @@ export const setupApp = async (): Promise<FastifyInstance> => {

await setupBullMQBoard(app)

app.get(
'/code_catch',
async(
request: FastifyRequest<{ Querystring: { url: string } }>, reply
) => {

return reply.type('text/html').send(`
<html>
<body>
<iframe src="${request.query.url}" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0"/>
<script>
async function catchCode() {
while(true) {
const code = window.localStorage.getItem('__code')
if (code) {
window.localStorage.removeItem('__code');
window.opener.postMessage({ 'code': encodeURIComponent(code) },'*')
await new Promise((resolve) => setTimeout(resolve, 500))
break;
}
console.log('wait for code')
await new Promise((resolve) => setTimeout(resolve, 500))
}

window.close()
}

catchCode()
</script>
</body>
</html>

`)
}
)

app.get(
'/redirect',
async (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const authenticationService = {
return { token }
},
async signUp(params: SignUpParams): Promise<AuthenticationResponse> {
if (!params.skipAssertiong)
if (!params.skipAsserting)
await assertSignUpIsEnabled()

await hooks.get().preSignUp({
Expand Down Expand Up @@ -68,7 +68,7 @@ export const authenticationService = {

async federatedAuthn(params: FederatedAuthnParams): Promise<AuthenticationResponse> {
const existingUser = await userService.getByPlatformAndEmail({
platformId: params.platformId === 'EXTERNAL' ? null : params.platformId,
platformId: params.platformId,
email: params.email,
})

Expand All @@ -87,7 +87,7 @@ export const authenticationService = {
newsLetter: true,
password: await generateRandomPassword(),
platformId: params.platformId,
skipAssertiong: params.platformId === 'EXTERNAL' ? true : undefined,
skipAsserting: params.skipAsseting,
})
},

Expand Down Expand Up @@ -262,7 +262,7 @@ type SignUpParams = {
status: UserStatus
platformId: string | null
referringUserId?: string
skipAssertiong?: true
skipAsserting?: boolean
}

type SignInParams = {
Expand All @@ -282,6 +282,7 @@ type FederatedAuthnParams = {
firstName: string
lastName: string
platformId: string | null
skipAsseting?: boolean
}

type SignUpResponseParams = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export const authenticationController: FastifyPluginAsyncTypebox = async (app) =
...request.body,
status: edition === ApEdition.COMMUNITY ? UserStatus.VERIFIED : UserStatus.CREATED,
platformId,
skipAsserting: undefined
})
})

Expand Down Expand Up @@ -46,7 +47,8 @@ export const authenticationController: FastifyPluginAsyncTypebox = async (app) =
userStatus: UserStatus.VERIFIED,
firstName: request.body.firstName,
lastName: request.body.lastName,
platformId: 'EXTERNAL'
platformId: null,
skipAsseting: true
})
},
)
Expand All @@ -59,18 +61,19 @@ export const authenticationController: FastifyPluginAsyncTypebox = async (app) =
},
},
async (request, reply) => {
console.log(request, request.principal)
if (request.principal.type !== PrincipalType.EXTERNAL) {
reply.status(StatusCodes.FORBIDDEN)
return
}
console.log('auth EXTERNAL')

return authenticationService.federatedAuthn({
email: request.body.id,
userStatus: UserStatus.VERIFIED,
firstName: '', // SHOULD BE AVAILABLE IN PREVIOUSLY INJECTED USER
lastName: '', // SHOULD BE AVAILABLE IN PREVIOUSLY INJECTED USER
platformId: 'EXTERNAL'
platformId: null,
skipAsseting: true
})
},
)
Expand Down
2 changes: 1 addition & 1 deletion packages/pieces/cryptomus/package.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"name": "@tookey-io/piece-cryptomus",
"version": "0.0.1"
"version": "0.0.4"
}
2 changes: 1 addition & 1 deletion packages/pieces/cryptomus/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const cryptomus = createPiece({
displayName: 'Cryptomus',
auth: CryptomusAuth,
minimumSupportedRelease: '0.9.0',
logoUrl: 'https://raw.githubusercontent.com/tookey-io/icons/main/piece-uniswap.png',
logoUrl: 'https://raw.githubusercontent.com/tookey-io/icons/main/piece-cryptomus.png',
authors: ["Aler Denisov"],
actions: [cryptomusCreatePaymentAction, cryptomusGetPaymentsHistory, cryptomusGetPaymentCurrencies],
triggers: [cryptomusPaymentTrigger],
Expand Down
33 changes: 33 additions & 0 deletions packages/pieces/instant-form/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"extends": [
"../../../.eslintrc.json"
],
"ignorePatterns": [
"!**/*"
],
"overrides": [
{
"files": [
"*.ts",
"*.tsx",
"*.js",
"*.jsx"
],
"rules": {}
},
{
"files": [
"*.ts",
"*.tsx"
],
"rules": {}
},
{
"files": [
"*.js",
"*.jsx"
],
"rules": {}
}
]
}
7 changes: 7 additions & 0 deletions packages/pieces/instant-form/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# pieces-instant-form

This library was generated with [Nx](https://nx.dev).

## Building

Run `nx build pieces-instant-form` to build the library.
4 changes: 4 additions & 0 deletions packages/pieces/instant-form/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"name": "@tookey-io/piece-instant-form",
"version": "0.0.2"
}
45 changes: 45 additions & 0 deletions packages/pieces/instant-form/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"name": "pieces-instant-form",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "packages/pieces/instant-form/src",
"projectType": "library",
"targets": {
"build": {
"executor": "@nx/js:tsc",
"outputs": [
"{options.outputPath}"
],
"options": {
"outputPath": "dist/packages/pieces/instant-form",
"tsConfig": "packages/pieces/instant-form/tsconfig.lib.json",
"packageJson": "packages/pieces/instant-form/package.json",
"main": "packages/pieces/instant-form/src/index.ts",
"assets": [
"packages/pieces/instant-form/*.md"
],
"buildableProjectDepsInPackageJsonType": "dependencies",
"updateBuildableProjectDepsInPackageJson": true
}
},
"publish": {
"command": "node tools/scripts/publish.mjs pieces-instant-form {args.ver} {args.tag}",
"dependsOn": [
"build"
]
},
"lint": {
"executor": "@nx/eslint:lint",
"outputs": [
"{options.outputFile}"
],
"options": {
"lintFilePatterns": [
"packages/pieces/instant-form/**/*.ts"
]
}
}
},
"tags": [
"@tookey-io"
]
}
126 changes: 126 additions & 0 deletions packages/pieces/instant-form/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import FormData from "form-data";
import { AuthenticationType, httpClient, HttpMethod } from "@activepieces/pieces-common";
import { ActionContext, createAction, createPiece, createTrigger, OAuth2Property, OAuth2PropertyValue, OAuth2Props, PieceAuth, PieceAuthProperty, Property, StaticPropsValue, Store, TestOrRunHookContext, TriggerStrategy } from "@activepieces/pieces-framework";
import { TriggerPayload } from "@activepieces/shared";

const catchQuery = new URLSearchParams({
appName: "InstantForm",
appIcon: "https://raw.githubusercontent.com/tookey-io/icons/main/piece-instant-form.png",
url: "https://t.me/InstantFormsBot/oauth?startapp={{client_id}}"
});

export const InstantFormAuth = PieceAuth.OAuth2({
required: true,
authUrl: `{{window.location.origin}}/catch_code?${catchQuery.toString()}`,
tokenUrl: 'https://instantlyform.com/webBot/oauth/token',
scope: [
'all'
]
})

export const instantFormGetAllForms = createAction({
name: "get_all_forms",
displayName: "Get All Forms",
description: "",
props: {},
auth: InstantFormAuth,
requireAuth: true,
async run(ctx) {
return httpClient.sendRequest({
method: HttpMethod.GET,
url: "https://instantlyform.com/api/form",
headers: {
Authorization: `Bearer ${ctx.auth.access_token}`
}
}).then(r => r.body)
}
})

export const instantFormNewResponse = createTrigger({
name: "new_response",
displayName: "New Response",
description: "",
props: {
formId: Property.Dropdown({
displayName: "Form ID",
required: true,
refreshers: [],
options: async ({ auth }) => {
if (!auth) {
return {
disabled: true,
options: [],
placeholder: 'Please authenticate first'
}
}
const authProp: OAuth2PropertyValue = auth as OAuth2PropertyValue;
const forms = await httpClient.sendRequest<{ data: Array<{ id: string, name: string }> }>({
method: HttpMethod.GET,
url: `https://instantlyform.com/api/form`,
headers: {
Authorization: `Bearer ${authProp.access_token}`
}
}).then(r => r.body.data)

return {
disabled: false,
options: forms.map((form: { id: string, name: string }) => {
return {
label: form.name,
value: form.id
}
})
};
}
})
},
auth: InstantFormAuth,
requireAuth: true,
type: TriggerStrategy.WEBHOOK,
async onEnable(ctx) {
const id = await httpClient.sendRequest<{ data: {id: string } }>({
method: HttpMethod.POST,
url: `https://instantlyform.com/api/form/${ctx.propsValue.formId}/webhook`,
headers: {
Authorization: `Bearer ${ctx.auth.access_token}`,
},
body: {
url: ctx.webhookUrl
}
}).then(r => r.body.data.id)

await ctx.store.put('__webhook_id', id);
},
async onDisable(ctx) {
const id = await ctx.store.get('__webhook_id');
if (id) {
await httpClient.sendRequest({
method: HttpMethod.DELETE,
url: `https://instantlyform.com/api/webhook/${id}`,
headers: {
Authorization: `Bearer ${ctx.auth.access_token}`
}
})
}
},

async run(ctx) {
const payloadBody = ctx.payload.body as Record<string, unknown>;
if ('event_type' in payloadBody && payloadBody["event_type"] === "PING") {
return [];
}
return [payloadBody];
},
sampleData: {}
})

export const instantForm = createPiece({
displayName: "InstantForm",
auth: InstantFormAuth,
minimumSupportedRelease: '0.9.0',
logoUrl:
'https://raw.githubusercontent.com/tookey-io/icons/main/piece-instant-form.png',
authors: [],
actions: [instantFormGetAllForms],
triggers: [instantFormNewResponse],
});
Loading