Skip to content

Instantly share code, notes, and snippets.

@marcantoine
Created June 26, 2018 16:17
Show Gist options
  • Save marcantoine/08880ea5e4c1138dc429452ce415445b to your computer and use it in GitHub Desktop.
Save marcantoine/08880ea5e4c1138dc429452ce415445b to your computer and use it in GitHub Desktop.
sign in with telegram
// this is the file where i configure the telegram strategy for passport
const TelegramStrategy = require('passport-telegram-official') // i use this package
module.exports = function(passport){
passport.use( // i say to passport
new TelegramStrategy({ // hey please use the TelegramStrategy
botToken: process.env.BOT_TOKEN // with this bot (ps the token of the bot that i keep in an environment variable
},
async function(profile, done) { // then also do this stuff below to check if the user exist or to create it
user = await User.findOrCreate({ // this syntax is for my ORM sequelize, it will probably be different for you
where:{
telegramId: profile.id // here i check if user exist with this telegramID
},
defaults: { // if not, i create him
username: profile.username,
firstname: profile.first_name,
lastname: profile.last_name,
photoUrl: profile.photo_url,
telegramId: profile.id
}
}
).catch(err => callback(err, false)) //maybe if error
if(user) { // so if i dont have any errors, i have a user that i can send back
return done(null, user[0]) // in my case, the user is actually in an array after a findorcreate, probably different for you
}else{
return done(null, false) // if no user or error or anything, i send back flase and the user will not be logged in
}
}
))
}
//i have a router in my back-end/api express app
const express = require('express')
const router = express.Router()
const passport = require('passport') //with passport
require('./passport')(passport) // i need the main passport package config
require('./passport-telegram')(passport) // i need the telegram passport package config
//and here is my api endpoint where the ajax arrive with user
router.post('api/users/auth/telegram', passport.authenticate('telegram'), manageTelegramUser )
//so i send the user info to passport.authenticate('telegram') and it tells me everything is ok
// then he send the user to the manageTelegramUser function which basically just send the token of this user to the front
const telegram = async function(req, res){
res.setHeader('Content-Type', 'application/json')
let user = req.user
return ReS(res, {token:user.getJWT(), user:user.toWeb()})
}
// user.getJWT() and user.toWeb() are 2 custom function i have
// getJWT create the token for this user
// user.toWeb just clean the data and remove the critical one before sending to frontend
// so in my js, i have the onTelegramAuth function on window
window.onTelegramAuth = function(user) {
let url = '/api/users/auth/telegram' // i have an endpoint for login my user with telegram
$.ajax({ // i use jquery so ajax, but yeah, xhr / fetch works too
type: 'POST', // i post
url: url, // to the url
data: user, // the user send by telegram
success: function(data, textStatus, xhr){
// on success, my backend send a JWT token so i can keep it in user session, in localstorage here
localStorage.setItem('jwt', data.token)
localStorage.setItem('id', data.user.id)
redirectTo('/account')// just a function that redirect the user to his account
//after redirection, on the new page, i check that the jwt token is still ok, but thats another topic
},
error: function(xhr, textStatus){
console.log('error')
console.log(xhr)
//OMG PROBLEM
}
})
}
<!DOCTYPE html>
<html>
<head>
<title>Nice gist wow</title>
</head>
<body>
<div id="app">
<div id="base" class="js-mainLayout">
<h1>HELLO</h1>
<p>This is a basic html page where I put the sign in with telegram button.</p>
<p>Just below</p>
<p>in data-telegram-login="", you need ot put your bot username</p>
<p> in data-onauth="", i put a callback function > this function is called after the user validate the login in telegram, so i can start to get the info in my app
<br/> called the function onTelegramAuth(user) and pass user as parameters since i need his info</p>
<p>good to know, you can use data-auth-url to redirect the user after his ogin, its easier to implement, i didn't did that cause i want to manage everything on the frontend</p>
<br/>
<script async src="https://telegram.org/js/telegram-widget.js?4" data-telegram-login="thisisusernamebot" data-size="large" data-onauth="onTelegramAuth(user)" data-request-access="write"></script>
</div>
</div>
<script src="/js/script.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment