diff --git a/packages/backend/src/apps/telegram-bot/auth/index.ts b/packages/backend/src/apps/telegram-bot/auth/index.ts new file mode 100644 index 00000000..01e68c2f --- /dev/null +++ b/packages/backend/src/apps/telegram-bot/auth/index.ts @@ -0,0 +1,21 @@ +import verifyCredentials from './verify-credentials'; +import isStillVerified from './is-still-verified'; + +export default { + fields: [ + { + key: 'token', + label: 'Bot token', + type: 'string' as const, + required: true, + readOnly: false, + value: null, + placeholder: null, + description: 'Bot token which should be retrieved from @botfather.', + clickToCopy: false, + }, + ], + + verifyCredentials, + isStillVerified, +}; diff --git a/packages/backend/src/apps/telegram-bot/auth/is-still-verified.ts b/packages/backend/src/apps/telegram-bot/auth/is-still-verified.ts new file mode 100644 index 00000000..66bb963e --- /dev/null +++ b/packages/backend/src/apps/telegram-bot/auth/is-still-verified.ts @@ -0,0 +1,9 @@ +import { IGlobalVariable } from '@automatisch/types'; +import verifyCredentials from './verify-credentials'; + +const isStillVerified = async ($: IGlobalVariable) => { + await verifyCredentials($); + return true; +}; + +export default isStillVerified; diff --git a/packages/backend/src/apps/telegram-bot/auth/verify-credentials.ts b/packages/backend/src/apps/telegram-bot/auth/verify-credentials.ts new file mode 100644 index 00000000..17bbfa94 --- /dev/null +++ b/packages/backend/src/apps/telegram-bot/auth/verify-credentials.ts @@ -0,0 +1,12 @@ +import { IGlobalVariable } from '@automatisch/types'; + +const verifyCredentials = async ($: IGlobalVariable) => { + const { data } = await $.http.get('/getMe'); + const { result: me } = data; + + await $.auth.set({ + screenName: me.first_name, + }); +}; + +export default verifyCredentials; diff --git a/packages/backend/src/apps/telegram-bot/common/add-auth-header.ts b/packages/backend/src/apps/telegram-bot/common/add-auth-header.ts new file mode 100644 index 00000000..aa17b14f --- /dev/null +++ b/packages/backend/src/apps/telegram-bot/common/add-auth-header.ts @@ -0,0 +1,13 @@ +import { TBeforeRequest } from '@automatisch/types'; +import { URL } from 'node:url'; + +const addAuthHeader: TBeforeRequest = ($, requestConfig) => { + if ($.auth.data?.token) { + const token = $.auth.data.token as string; + requestConfig.baseURL = (new URL(`/bot${token}`, requestConfig.baseURL)).toString(); + } + + return requestConfig; +}; + +export default addAuthHeader; diff --git a/packages/backend/src/apps/telegram-bot/index.ts b/packages/backend/src/apps/telegram-bot/index.ts index 9f3c7db3..e57aecb3 100644 --- a/packages/backend/src/apps/telegram-bot/index.ts +++ b/packages/backend/src/apps/telegram-bot/index.ts @@ -12,4 +12,6 @@ export default defineApp({ baseUrl: 'https://telegram.org', apiBaseUrl: 'https://api.telegram.org', primaryColor: '2AABEE', + beforeRequest: [addAuthHeader], + auth, });