Repository navigation
Expand file tree
/
Copy pathauth.ts
More file actions
54 lines (46 loc) · 1.48 KB
/
Copy pathauth.ts
File metadata and controls
54 lines (46 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import type { Env, TelegramUpdate, RequestContext } from "../lib/types";
import { upsertUser, resolveRole } from "../lib/kv";
/**
* Builds the RequestContext from a raw Telegram update: identifies the user,
* chat, and message/callback content. Also upserts a lightweight user record
* so "lastSeenAt" / "joinedAt" stay accurate for every interaction.
*
* Returns null if the update cannot be attributed to a user (e.g. channel
* posts with no `from` field) — callers should silently ignore these.
*/
export async function authenticate(env: Env, update: TelegramUpdate): Promise<RequestContext | null> {
if (update.callback_query) {
const cq = update.callback_query;
const chatId = cq.message?.chat.id ?? cq.from.id;
await upsertUser(env, cq.from.id, {
username: cq.from.username,
firstName: cq.from.first_name,
});
const role = await resolveRole(env, cq.from.id);
return {
env,
update,
userId: cq.from.id,
chatId,
role,
isCallback: true,
callbackData: cq.data,
};
}
const message = update.message ?? update.edited_message;
if (!message || !message.from) return null;
await upsertUser(env, message.from.id, {
username: message.from.username,
firstName: message.from.first_name,
});
const role = await resolveRole(env, message.from.id);
return {
env,
update,
userId: message.from.id,
chatId: message.chat.id,
role,
isCallback: false,
text: message.text,
};
}