Skip to content

Instantly share code, notes, and snippets.

@an-ivannikov
Last active May 10, 2022 11:42
Show Gist options
  • Save an-ivannikov/f972852f259ab9304103ff226d34d7b4 to your computer and use it in GitHub Desktop.
Save an-ivannikov/f972852f259ab9304103ff226d34d7b4 to your computer and use it in GitHub Desktop.
Checking Telegram Auth Data in Express.js
const { createHash, createHmac } = require('crypto');
function checkTelegramAuthData({ token, hash, ...data }) {
const secret = createHash('sha256')
.update(token)
.digest();
const stringToCheck = Object.keys(data)
.sort()
.map((key) => (`${key}=${data[key]}`))
.join('\n');
const hmac = createHmac('sha256', secret)
.update(stringToCheck)
.digest('hex');
return hmac === hash;
}
module.exports = checkTelegramAuthData;
// See in https://expressjs.com/en/guide/routing.html
const express = require('express');
const router = express.Router();
const checkTelegramAuthData = require('./check-telegram-auth-data');
router.use('/auth/tg', async (req, res, next) => {
// See in https://core.telegram.org/bots/api#authorizing-your-bot
const token = 'bot123456:ABC...';
// See in https://core.telegram.org/widgets/login#receiving-authorization-data
const authData = req.query;
if (checkTelegramAuthData({ token, ...authData }))
return res.json({ ok: true });
else
return res.json({ ok: false });
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment