Last active
May 10, 2022 11:42
-
-
Save an-ivannikov/f972852f259ab9304103ff226d34d7b4 to your computer and use it in GitHub Desktop.
Checking Telegram Auth Data in Express.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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