Skip to content

Commit

Permalink
Add auth with telegram sdk and validate data
Browse files Browse the repository at this point in the history
  • Loading branch information
chiliec committed Jun 21, 2024
1 parent 2d8ae34 commit ac210be
Show file tree
Hide file tree
Showing 12 changed files with 1,183 additions and 954 deletions.
8 changes: 5 additions & 3 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
{
"ignorePatterns": [
"build/src/*",
"src/frontend/dist/*",
"src/frontend/*.d.ts"
"src/frontend/*"
// "src/frontend/dist/*",
// "src/frontend/*.d.ts"
],
"env": {
"es2021": true,
Expand Down Expand Up @@ -53,7 +54,8 @@
"error",
{
"replacements": {
"ctx": false
"ctx": false,
"err": false
}
}
]
Expand Down
1,922 changes: 983 additions & 939 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"@grammyjs/parse-mode": "1.10.0",
"@grammyjs/types": "3.9.0",
"@pinata/sdk": "^2.1.0",
"@tma.js/init-data-node": "^1.2.8",
"@ton/core": "^0.56.3",
"@ton/crypto": "^3.2.0",
"@ton/ton": "^13.11.2",
Expand Down
35 changes: 35 additions & 0 deletions src/backend/auth-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { findUserById } from "#root/bot/models/user";
import { config } from "#root/config";
import { validate } from "@tma.js/init-data-node";
import { FastifyInstance } from "fastify";

const authHandler = (
fastify: FastifyInstance,
_options: unknown,
done: () => void,
) => {
fastify.post("/:userId", async (request, _reply) => {
const { userId } = request.params as any;
if (!userId) {
return { error: "No userId provided" };
}
const { initData } = request.body as any;
if (!initData) {
return { error: `No initData or hash provided` };
}
try {
validate(initData, config.BOT_TOKEN, { expiresIn: 86_400 });
const user = await findUserById(userId);
if (!user) {
return { error: "User not found" };
}
return { id: user.id, language: user.language, wallet: user.wallet };
} catch (error_) {
return { error: error_ };
}
});

done();
};
export default authHandler;
100 changes: 100 additions & 0 deletions src/frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"@ton/core": "^0.56.3",
"@tonconnect/ui": "^2.0.5",
"@vitejs/plugin-vue": "^5.0.5",
"axios": "^1.7.2",
"element-plus": "^2.7.5",
"pinia": "^2.1.7",
"rollup-plugin-polyfill-node": "^0.13.0",
Expand Down
21 changes: 11 additions & 10 deletions src/frontend/src/components/Main.vue
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
<script setup lang="ts">
import { ref } from "vue";
import { useWebAppHapticFeedback } from "vue-tg";
import { useWebApp } from "vue-tg";
import { useAuth } from "../composables/use-auth";
import { onMounted } from "vue";
defineProps<{ msg?: string }>();
const count = ref(0);
const { notificationOccurred } = useWebAppHapticFeedback();
function increment() {
notificationOccurred("success");
count.value++;
}
onMounted(async () => {
const webAppUser = useWebApp().initDataUnsafe.user;
if (webAppUser) {
const { user, error, login } = useAuth(useWebApp().initData, webAppUser.id);
await login();
console.log(user.value, error.value);
}
});
</script>

<template>
Expand Down
30 changes: 30 additions & 0 deletions src/frontend/src/composables/use-auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { ref } from "vue";
import { authenticateUser } from "../services/auth-service";
import { unknown } from "zod";

export const useAuth = (initData: string, userId: number) => {
const user = ref();
const error = ref();

const login = async () => {
try {
const userString = sessionStorage.getItem("user");
if (userString) {
const userModel = JSON.parse(userString);
user.value = userModel;
return;
}
const userModel = await authenticateUser(initData, userId);
user.value = userModel;
sessionStorage.setItem("user", JSON.stringify(userModel));
} catch (error_) {
error.value = error_
}
};

return {
user,
error,
login,
};
};
11 changes: 11 additions & 0 deletions src/frontend/src/services/auth-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import axios from "axios";

export const authenticateUser = async (initData: string, userId: number) => {
try {
const response = await axios.post(`/api/auth/${userId}`, { initData });
return response.data;
} catch (error) {
console.error('Error authenticating user:', error);
throw error;
}
};
3 changes: 2 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ try {
});

const subscription = new Subscription(bot);
await subscription.startProcessTransactions();
// eslint-disable-next-line no-void
void subscription.startProcessTransactions();

if (config.BOT_MODE === "webhook") {
// to prevent receiving updates before the bot is ready
Expand Down
3 changes: 3 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { logger } from "#root/logger.js";
import path from "node:path";
import fastifyStatic from "@fastify/static";
import { fileURLToPath } from "node:url";
import userHandler from "./backend/auth-handler";
import nftHandler from "./backend/nft-handler";
import checkCaptcha from "./backend/captcha";

Expand All @@ -19,6 +20,8 @@ export const createServer = async (bot: Bot) => {
await response.status(500).send({ error: "Oops! Something went wrong." });
});

await server.register(userHandler, { prefix: "/api/auth" });

await server.register(nftHandler, { prefix: "/api/nft" });

await server.register(checkCaptcha, { bot });
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"noEmit": true,
"module": "ES2022",
"target": "ES2021",
"moduleResolution": "Node",
"moduleResolution": "Node10",
"sourceMap": true,
"outDir": "build",
"rootDir": ".",
Expand Down

0 comments on commit ac210be

Please sign in to comment.