Skip to content

Commit

Permalink
Merge pull request #11 from jotacemarin/develop
Browse files Browse the repository at this point in the history
History with ttl
  • Loading branch information
jotacemarin authored Sep 8, 2024
2 parents 3b6e5bc + b4a135b commit bae19e5
Show file tree
Hide file tree
Showing 18 changed files with 155 additions and 42 deletions.
1 change: 1 addition & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ export { telegramCleanReplyMarkup } from "./src/functions/telegram_clean_reply_m
export { telegramMembersMute } from "./src/functions/telegram_members_mute";
export { telegramMembersUnmute } from "./src/functions/telegram_members_unmute";
export { telegramPublicWebhook } from "./src/functions/telegram_public_webhook";
export { telegramGetMessages } from "./src/functions/telegram_get_messages";
2 changes: 1 addition & 1 deletion mock_events/event_telegram_authorizer.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"authorizationToken": "Basic S0dSYWZ2eVNxSTBoSm5vQVZuOHFqZzFRRkp3WEg4cFI6OjEyTUd6alhmeENEMmVTbGR3azdabXNiUWlRTHN6OTY1ZFhyZFJSSS0yR1U5V2kzdVpvLVY4bmN5Y3JFVEZLbEk="
"authorizationToken": "Basic MTM0NjU1NzA4NToyMmYzOTFkNS0xODcyLTRhZmItYTIxMS1hYjNiYmEyNGRlNjk="
}
3 changes: 3 additions & 0 deletions serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ provider:
MONGO_PASSWORD: ${self:custom.secrets.provider.environment.MONGO_PASSWORD}
MONGO_HOST: ${self:custom.secrets.provider.environment.MONGO_HOST}
MONGO_DATABASE: ${self:custom.secrets.provider.environment.MONGO_DATABASE}
USERNAME: ${self:custom.secrets.provider.environment.USERNAME}
PASSWORD: ${self:custom.secrets.provider.environment.PASSWORD}

functions:
telegramAuthorizer: ${file(./src/functions/telegram_authorizer/function.yml)}
Expand All @@ -39,3 +41,4 @@ functions:
telegramMembersMute: ${file(./src/functions/telegram_members_mute/function.yml)}
telegramMembersUnmute: ${file(./src/functions/telegram_members_unmute/function.yml)}
telegramPublicWebhook: ${file(./src/functions/telegram_public_webhook/function.yml)}
telegramGetAllMessages: ${file(./src/functions/telegram_get_messages/function.yml)}
22 changes: 10 additions & 12 deletions src/functions/telegram_authorizer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
APIGatewayAuthorizerResult,
APIGatewayTokenAuthorizerEvent,
} from "aws-lambda";
import { AuthService } from "../../lib/services";
import { UserDao } from "../../lib/dao/userDao";

enum Effect {
DENY = "Deny",
Expand Down Expand Up @@ -33,33 +33,31 @@ const extractToken = (authorizationToken: string) => {
const [_, token] = authorizationToken?.split(" ");
const cleanToken = atob(token);
const [clientId, clientSecret] = cleanToken?.split(":");
console.log("extractToken", `${clientId}, ${clientSecret}`);
return { clientId, clientSecret };
};

const loginToAuth0 = async (
clientId: string | number,
clientSecret: string | number
const login = async (
clientId: string,
clientSecret: string
): Promise<Effect> => {
try {
AuthService.initInstance();
await AuthService.getToken(clientId, clientSecret);
return Effect.ALLOW;
await UserDao.initInstance();
const user = await UserDao.findByKey(clientId, clientSecret);
return Boolean(user) ? Effect.ALLOW : Effect.DENY;
} catch (error) {
console.log(`${Effect.DENY}: ${error.message}`, error);
return Effect.ALLOW;
return Effect.DENY;
}
};

export const telegramAuthorizer = async (
event: APIGatewayTokenAuthorizerEvent
): Promise<APIGatewayAuthorizerResult> => {
if (!event?.authorizationToken) {
console.log(`Effect: ${Effect.DENY}`);
return buildPolicy(event.methodArn, Effect.DENY);
}

const { clientId, clientSecret } = extractToken(event.authorizationToken);
const effect = await loginToAuth0(clientId, clientSecret);
console.log(`Effect: ${effect}`);
const effect = await login(clientId, clientSecret);
return buildPolicy(event.methodArn, effect);
};
13 changes: 13 additions & 0 deletions src/functions/telegram_get_messages/function.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
name: ${self:custom.secrets.service.name}-${self:custom.secrets.provider.stage}-telegram-get-messages
handler: index.telegramGetMessages
memorySize: 128
timeout: 30
reservedConcurrency: 5
events:
- http:
path: /${self:custom.secrets.service.name}-${self:custom.secrets.provider.stage}/telegram/get-messages
method: GET
cors: true
authorizer:
name: telegramAuthorizer
resultTtlInSeconds: 0
28 changes: 28 additions & 0 deletions src/functions/telegram_get_messages/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { APIGatewayEvent, Callback, Context } from "aws-lambda";
import { BAD_REQUEST, OK } from "http-status";
import { ChatMessageDao } from "../../lib/dao";

const execute = async (event: APIGatewayEvent): Promise<any> => {
if (!event?.queryStringParameters?.chat_id) {
return { statusCode: BAD_REQUEST };
}

const chatId = Number(event.queryStringParameters.chat_id);

await ChatMessageDao.initInstance();
const messages = await ChatMessageDao.getAll(chatId);

return { statusCode: OK, body: JSON.stringify(messages) };
};

export const telegramGetMessages = async (
event: APIGatewayEvent,
context: Context,
callback: Callback
): Promise<void> => {
context.callbackWaitsForEmptyEventLoop = false;

const response = await execute(event);

return callback(null, response);
};
3 changes: 3 additions & 0 deletions src/functions/telegram_public_webhook/function.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ events:
path: /${self:custom.secrets.service.name}-${self:custom.secrets.provider.stage}/telegram/public-webhook
method: POST
cors: true
authorizer:
name: telegramAuthorizer
resultTtlInSeconds: 0
28 changes: 1 addition & 27 deletions src/functions/telegram_public_webhook/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { APIGatewayEvent, Callback, Context } from "aws-lambda";
import { OK, BAD_REQUEST, UNAUTHORIZED } from "http-status";
import { OK, BAD_REQUEST } from "http-status";
import { TelegramService } from "../../lib/services";
import { UserDao } from "../../lib/dao";
import { FormattingOptionsTg } from "../../lib/models";

interface PublicWebhookParams {
Expand All @@ -13,26 +12,6 @@ interface PublicWebhookParams {
media_is_spoiler?: boolean;
}

const checkAuthorization = async (event: APIGatewayEvent) => {
if (
!event?.queryStringParameters?.id ||
!event?.queryStringParameters?.username
) {
return false;
}

const { id, username } = event?.queryStringParameters;

await UserDao.initInstance();

try {
const user = await UserDao.findByIdAndUsername(id, username);
return Boolean(user);
} catch (_error) {
return false;
}
};

const buildText = (body: PublicWebhookParams): string | undefined => {
if (!body?.text) {
return;
Expand Down Expand Up @@ -138,11 +117,6 @@ export const telegramPublicWebhook = async (
): Promise<void> => {
context.callbackWaitsForEmptyEventLoop = false;

const checkAuth = await checkAuthorization(event);
if (!checkAuth) {
return callback(null, { statusCode: UNAUTHORIZED });
}

if (!event?.body) {
return callback(null, { statusCode: BAD_REQUEST });
}
Expand Down
3 changes: 3 additions & 0 deletions src/functions/telegram_send_message/function.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ events:
path: /${self:custom.secrets.service.name}-${self:custom.secrets.provider.stage}/telegram/send-message
method: POST
cors: true
authorizer:
name: telegramAuthorizer
resultTtlInSeconds: 0
3 changes: 3 additions & 0 deletions src/functions/telegram_send_photo/function.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ events:
path: /${self:custom.secrets.service.name}-${self:custom.secrets.provider.stage}/telegram/send-photo
method: POST
cors: true
authorizer:
name: telegramAuthorizer
resultTtlInSeconds: 0
3 changes: 3 additions & 0 deletions src/functions/telegram_send_video/function.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ events:
path: /${self:custom.secrets.service.name}-${self:custom.secrets.provider.stage}/telegram/send-video
method: POST
cors: true
authorizer:
name: telegramAuthorizer
resultTtlInSeconds: 0
3 changes: 3 additions & 0 deletions src/functions/telegram_set_webhook/function.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ events:
path: /${self:custom.secrets.service.name}-${self:custom.secrets.provider.stage}/telegram/set-webhook
method: POST
cors: true
authorizer:
name: telegramAuthorizer
resultTtlInSeconds: 0
10 changes: 9 additions & 1 deletion src/functions/telegram_webhook/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { OK, BAD_REQUEST, NO_CONTENT } from "http-status";
import axios from "axios";
import { getTextCommand } from "../../lib/utils/telegramHelper";
import { Command, UpdateTg, User, FormattingOptionsTg } from "../../lib/models";
import { CommandDao, UserDao } from "../../lib/dao";
import { CommandDao, UserDao, ChatMessageDao } from "../../lib/dao";
import { TelegramService } from "../../lib/services";

const { STAGE } = process.env;
Expand All @@ -21,6 +21,11 @@ const getCommand = async (body: UpdateTg): Promise<Command | null> => {
return CommandDao.findByKey(key);
};

const saveChatMessage = async (body: UpdateTg): Promise<void> => {
await ChatMessageDao.initInstance();
await ChatMessageDao.save({ telegramMessage: body, expireAt: new Date() });
};

const request = async (command: Command, body: UpdateTg) => {
try {
console.log(`${command.key}: ${command.url}`);
Expand Down Expand Up @@ -115,6 +120,9 @@ export const telegramWebhook = async (
if (STAGE === "dev") {
console.log(`webhook message: \n${JSON.stringify(body, null, 2)} `);
}

await saveChatMessage(body);

const response = await execute(body);

const endDate = new Date();
Expand Down
52 changes: 52 additions & 0 deletions src/lib/dao/chatMessageDao.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Model, Schema, model } from "mongoose";
import { ChatMessage } from "../models";
import { MongodbService } from "../services";

export class ChatMessageDao {
private static schemaName: string = "chat_message";
private static chatMessageSchema: Schema<ChatMessage>;
public static chatMessageModel: Model<ChatMessage>;

private constructor() {}

public static async initInstance() {
await MongodbService.initInstance();

if (!ChatMessageDao.chatMessageSchema) {
ChatMessageDao.chatMessageSchema = new Schema(
{
telegramMessage: { type: Schema.Types.Mixed, required: true },
expireAt: { type: Schema.Types.Date, expires: 43200 },
},
{
timestamps: true,
expireAfterSeconds: 43200,
}
);
}

if (!ChatMessageDao.chatMessageModel) {
ChatMessageDao.chatMessageModel = model(
ChatMessageDao.schemaName,
ChatMessageDao.chatMessageSchema
);
}
}

public static async save(
chatMessage: ChatMessage
): Promise<ChatMessage | null> {
return ChatMessageDao.chatMessageModel.create(chatMessage);
}

public static async getAll(chatId: Number): Promise<Array<ChatMessage>> {
const chatMessages = await ChatMessageDao.chatMessageModel
.find({ "telegramMessage.message.chat.id": chatId })
.exec();
if (!chatMessages || !chatMessages?.length) {
return [];
}

return chatMessages;
}
}
1 change: 1 addition & 0 deletions src/lib/dao/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { CommandDao } from "./commandDao";
export { UserDao } from "./userDao";
export { ChatMessageDao } from "./chatMessageDao";
9 changes: 9 additions & 0 deletions src/lib/dao/userDao.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,15 @@ export class UserDao {
return null;
}

public static async findByKey(id: string, key: string): Promise<User | null> {
const document = await UserDao.userModel.findOne({ id, key }).exec();
if (document) {
return { ...document.toObject() } as User;
}

return null;
}

public static async save(user: User): Promise<User | null> {
if (!user?.id) {
throw new Error("id is missing");
Expand Down
11 changes: 11 additions & 0 deletions src/lib/models/botnorrea.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { UpdateTg } from "./telegram";

interface ID {
$oid: string;
}
Expand All @@ -13,6 +15,7 @@ export interface User {
firstname?: string;
lastname?: string;
qrPathId?: string;
key?: string;
createdAt?: AtedAt | string;
updatedAt?: AtedAt | string;
}
Expand All @@ -33,3 +36,11 @@ export interface Command {
createdAt?: AtedAt | string;
updatedAt?: AtedAt | string;
}

export interface ChatMessage {
_id?: ID | string;
telegramMessage: UpdateTg;
expireAt?: Date | AtedAt | string;
createdAt?: AtedAt | string;
updatedAt?: AtedAt | string;
}
2 changes: 1 addition & 1 deletion src/lib/models/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { Command, Crew, User } from "./botnorrea";
export { Command, Crew, User, ChatMessage } from "./botnorrea";
export {
ChatTg,
ChatTypeTg,
Expand Down

0 comments on commit bae19e5

Please sign in to comment.