How to check if user is already logged-in in pyrogram? - telegram

while trying to run a pyrogram script, how to check user is already logged-in in pyrogram or that session is valid ?
So we no need to login again and we can go on next step without login ?

You can use this method to check if your connection to Telegram has not expired or if it was done successfully.
from pyrogram import errors
from pyrogram import Client
app = Client(
...
)
app.connect()
try:
app.get_me()
except (
errors.ActiveUserRequired,
errors.AuthKeyInvalid,
errors.AuthKeyPermEmpty,
errors.AuthKeyUnregistered,
errors.AuthKeyDuplicated,
errors.SessionExpired,
errors.SessionPasswordNeeded,
errors.SessionRevoked,
errors.UserDeactivated,
errors.UserDeactivatedBan,
):
print("Session invalid / Login failed")
else:
print('Login successfully')
app.disconnect()
Chers

Related

Telegram Bot Python Inlinekeyboardmarkup does not work for all users in a group

I want to respond when someone sends the /start comand and display a text with a like/dislike button in a group.
Here is my sample code:
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
Updater,
CommandHandler,
CallbackQueryHandler,
ConversationHandler)
import logging
FIRST, SECOND = range(2)
keyboard = [[InlineKeyboardButton('👍', callback_data='0'),
InlineKeyboardButton('👎', callback_data='2')]]
def start(update, context):
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(
'Test Message\n',
reply_markup=reply_markup
)
return FIRST
def main():
updater = Updater(
'TOKEN', use_context=True)
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
FIRST: [CallbackQueryHandler(a, pattern='^'+str(0)+'$'),
CallbackQueryHandler(b, pattern='^'+str(2)+'$')]
},
fallbacks=[CommandHandler('start', start)]
)
dp.add_handler(conv_handler)
updater.start_polling()
updater.idle()
if __name__ == "__main__":
main()
The callbacks only work for the user who sent the /start command. Other users cannot click the button or there is no callback. if another user sends a /start command, both like/dislike buttons of both posts of the bot work for the two users.
Where is the mistake?
I want every user to be able to press the buttons and it triggers a callback. regardless of whether the user has ever sent the /start command
I am thankful for every help.
The issue here is that by default conversations are per user - please also see this faq entry for details.
For your use case, I doubt that a ConversationHandler gives you any benefit. I would just register the CommandHandler and the CallbackQueryHandler independently.
Disclaimer: I'm currently the maintainer of python-telegram-bot.

Setup programmatically the language code to send translated email verification - ns+angular app

I'm using this plugin: https://docs.nativescript.org/plugins/firebase-auth.html
to integrate my nativescript+angular mobile app with firebase authentication system.
Is there any way to setup the language code to send a translated email verification (template provided already by firebase) ?
I tried to setup by doing that
import { firebase } from '#nativescript/firebase-core'
import '#nativescript/firebase-auth'
...
let authFirebase = firebase().auth()
authFirebase.languageCode = 'fr'
authFirebase
.createUserWithEmailAndPassword(useremail, userpassword)
.then((cred) => {
if (cred && !cred.user.emailVerified) {
// send the account activation email
cred.user.sendEmailVerification()
}
})
but I got immediately a compilation error:
Cannot assign to 'languageCode' because it is a read-only property.ts(2540)
Any suggestion?
Many thanks in advance

couldn't authenticate spotify in vercel production

I made a spotify clone which have a login,main pages. The user is initially directed to login page (localhost:3000/login) and once the user clicks login button they are taken to spotify authentication callback url (from spotify side, we can login using google, facebook or email etc) and once the user is logged in (successfully authenticated) , spotify provides a token which is used to check if the user is authenticated from client side. If success, the user is taken to the main page (which has all the music in it).
The spotify dashboard takes in redirect url for authentication which in my case its -> http://localhost:3000/api/auth/callback/spotify
This workflow worked perfectly when working and running locally ( localhost:3000 ).
When hosting in vercel,
I created a project in vercel without envs
I took my https://sp-app.vercel.app which is the domain and added to NEXTAUTH_URL into my env, and also added - NEXT_PUBLIC_CLIENT_SECRET, NEXT_PUBLIC_CLIENT_ID and JWT_SECRET
Went to spotify dashboard and editing the redirect url to https://sp-app.vercel.app/api/auth/callback/spotify and saved
redeployed the app from vercel (which gave me a deployent url, but nevermind) and clicked on the domains --> sp-app.vercel.app
The login page came, once I clicked on login button, it loads and stays in login page itself. It isn't moving to my home page nor authenticating but this same code worked locally fine.
Code to understand :
Login button:
{providers !== null && Object.values(providers).map((provider) => (
<div key={provider.name}>
<button onClick={()=>signIn(provider.id, {callbackUrl:"/"})}
>Login with {provider.name}</button>
</div>
}
export async function getServerSideProps(){
const providers = await getProviders(); //getProviders is imported from next-auth
return {
props:{
providers,
}
}
}
middleware:
export async function middleware(req){
const token = await getToken({req,secret:process.env.JWT_SECRET});
const {pathname} = req.nextUrl;
//Allow the request if,
// (1) Its a request for next-auth session & provider fetching
// (2) The token exists
if(pathname.includes('/api/auth') || token){
return NextResponse.next();
}
//Redirect to login if no token or requesting a protected route
if(!token && pathname !== "/login"){
return NextResponse.redirect("/login");
}
}
While I checked with Network tab, I get a session which should log me in and redirect to main page, but it isn't working in vercel deployment.
Hey so first off make sure your NEXTAUTH_URL environment variable is correct. Also check that the redirect URI (from the Spotify developer dashboard) is correct.
After that, add this secureCookie code to the getToken function in the _middleware.js file. So that function should end up looking like this:
const token = await getToken({
req,
secret: process.env.JWT_SECRET,
secureCookie:
process.env.NEXTAUTH_URL?.startsWith("https://") ??
!!process.env.VERCEL_URL,
});
Let me know if this works. I had the same exact issue and this worked for me.

How can I setup passwordless email signin in Firebase?

I'm trying to setup passwordless authentification in Firebase. I already enabled "email without password" auth in my Project settings.
Using this documentation : https://firebase.google.com/docs/auth/admin/email-action-links#generate_email_link_for_sign-in I managed to implement a way to create auth links.
My goal is to open https://dev.test.com/signup/ with the email of the user so he will be instantly signed in.
This is my code so far:
import firebase_admin
from firebase_admin import auth
def main():
default_app = firebase_admin.initialize_app()
email = 'name.chris#gmail.com'
action_code_settings = auth.ActionCodeSettings(
url=f'https://dev.test.com/signup/?email={email}',
handle_code_in_app=True,
ios_bundle_id='com.example.ios',
android_package_name='com.example.android',
android_install_app=True,
android_minimum_version='12',
dynamic_link_domain='magic42.page.link',
)
link = auth.generate_sign_in_with_email_link(email, action_code_settings)
print(f"LINK = {link}")
When I click on the link, I don't get automatically signed in. I guess I should also modify my front end. I'm using Angular. My signup looks like this :
signUp(email: string, password: string): Observable<UserCredential> {
const credential = firebase.auth.EmailAuthProvider.credential(email, password);
return from(firebase.auth().currentUser.linkWithCredential(credential));
}
I'm confused why you have email and password on frontend. To complete sign in using the email link, you should be using firebase.auth().signInWithEmailLink() method and not linkWithCredential on your /signup page.
You can get sample code (which should be executed on your /signup page) of completing sign in with email link in the documentation:
https://firebase.google.com/docs/auth/web/email-link-auth

Flask/NGINX 404s on only some POST requests

I have a Flask app served by Gunicorn using NGINX as a webserver. I only have two endpoints that have POST requests, a login and a submit post. The login works flawlessly however whenever I attempt to POST using the submit post endpoint, I receive a 404. My code works running on localhost without NGINX or Gunicorn and in order to detect that the request is POST vs GET I am using WTForms validate_on_submit method. The NGINX error and access logs don't show anything out of the ordinary.
Edit: Here is the code for the endpoints with post requests
New Post:
#app.route('/newpost', methods=['GET', 'POST'])
#login_required
def new_post():
form = BlogForm()
if form.validate_on_submit():
#Omitted code for getting form data and creating form object
try:
#Omitted code for database actions
return redirect(url_for('index', _external=True))
except IntegrityError:
flash("Error inserting into database")
return('', 203)
else:
#Omitted some code for template rendering
return render_template('new_post.html')
Login:
#app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
userAuth = current_user.is_authenticated
if form.validate_on_submit():
flash("Login attempt logged")
user = User.query.filter_by(username=form.userID.data).first()
if user:
checkPass = form.password.data.encode('utf-8')
if bcrypt.checkpw(checkPass, user.password):
user.authenticated = True
login_user(user, remember=form.remember_me.data)
return redirect(url_for('index', _external=True))
else:
form.errors['password'] = 'false'
else:
form.errors['username'] = 'false'
else:
return render_template('login.html',
title='Log In',
loggedIn=userAuth,
form=form)
The problem ended up being with NGINX after all, I fixed it by changing the ownership of /var/lib/nginx from the nginx user to the user running the Flask application. Prior to doing this AWS wasn't letting me upload files from my form in new_post.

Resources