Last active
November 7, 2021 21:39
-
-
Save hypernova7/c0c5e04e53fce38b9d54dfb16f921c47 to your computer and use it in GitHub Desktop.
Checking telegram authorization with ExpressJS
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 app = require('express')(); | |
const consola = require('consola'); | |
const logger = consola.withTag('tg-check-auth') | |
app.listen(process.env.PORT) | |
app.get('/auth', auth) | |
function auth (req, res) { | |
let status = 200 // OK code | |
const { auth_date, hash, id } = req.body | |
if (auth_date && hash && id) { | |
const authTime = parseInt(auth_date, 10) | |
const time = parseInt((Date.now() / 1000), 10) | |
const key = crypto.createHash('sha256').update(process.env.BOT_TOKEN).digest() | |
const data = Object.keys(req.body) | |
.sort() | |
.filter(key => key !== 'hash') | |
.map(key => `${key}=${req.body[key]}`) | |
.join('\n') | |
const secret = crypto.createHmac('sha256', key).update(data).digest('hex') | |
if (hash.localeCompare(secret) === 0 && (time - authTime) <= 86400) { | |
logger.success('Successful authorization') | |
} else { | |
status = 401 // unauthorized code | |
} | |
} else { | |
status = 401 // unauthorized code | |
} | |
res.sendStatus(status) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment