Reset password using Firestore authentication using python API - firebase-authentication

Aim is to send a password reset link using Firestore authentication. Initially I used the default action URL and the script was working fine. But when I changed the action URL, I am getting OK in the web page. It is not resetting the password.
Code:
import firebase_admin
from firebase_admin import credentials,firestore,auth
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Email
from python_http_client.exceptions import HTTPError
sg = SendGridAPIClient(os.environ["SENDGRID_API_KEY"])
action_code_settings = auth.ActionCodeSettings(
url='https://us-central1-xxxx.cloudfunctions.net/xxxx',
handle_code_in_app=False
)
link = auth.generate_password_reset_link(Email)
html_content = f"""
<p>Hello,</p>
<p>Click on the link to reset the password.</p>
<p>{link}</p>
<p>If you didn't ask to reset password, you can ignore this email.</p>
"""
message = Mail(
to_emails=Email,
from_email=Email('abc#gmail.com', "ABC System"),
subject="Reset password for ABC System",
html_content=html_content
)
try:
response = sg.send(message)
return f"The password for {Email} has been reset."
except HTTPError as e:
print(e.message)
return e.message
Can someone point out what is wrong.

Related

Is there a way to authenticate OAUTH2.0 of google API through terminal?

I am fetching google photos from my account using Google Photo API. Now there is a need for me to execute that php file via terminal, but the problem is that I can't authenticate with Google API in doing so. Is there a way to do this, and if yes, then how shall it be done?
Yes, it is possible, you need an interactive login for the first authentication but then you can save the token and refresh it automatically as required.
I have implemented this class in Python to do just that.
from requests.adapters import HTTPAdapter
from requests_oauthlib import OAuth2Session
from pathlib import Path
from urllib3.util.retry import Retry
from typing import List, Optional
from json import load, dump, JSONDecodeError
import logging
log = logging.getLogger(__name__)
# OAuth endpoints given in the Google API documentation
authorization_base_url = "https://accounts.google.com/o/oauth2/v2/auth"
token_uri = "https://www.googleapis.com/oauth2/v4/token"
class Authorize:
def __init__(
self, scope: List[str], token_file: Path,
secrets_file: Path, max_retries: int = 5
):
""" A very simple class to handle Google API authorization flow
for the requests library. Includes saving the token and automatic
token refresh.
Args:
scope: list of the scopes for which permission will be granted
token_file: full path of a file in which the user token will be
placed. After first use the previous token will also be read in from
this file
secrets_file: full path of the client secrets file obtained from
Google Api Console
"""
self.max_retries = max_retries
self.scope: List[str] = scope
self.token_file: Path = token_file
self.session = None
self.token = None
try:
with secrets_file.open('r') as stream:
all_json = load(stream)
secrets = all_json['installed']
self.client_id = secrets['client_id']
self.client_secret = secrets['client_secret']
self.redirect_uri = secrets['redirect_uris'][0]
self.token_uri = secrets['token_uri']
self.extra = {
'client_id': self.client_id,
'client_secret': self.client_secret}
except (JSONDecodeError, IOError):
print('missing or bad secrets file: {}'.format(secrets_file))
exit(1)
def load_token(self) -> Optional[str]:
try:
with self.token_file.open('r') as stream:
token = load(stream)
except (JSONDecodeError, IOError):
return None
return token
def save_token(self, token: str):
with self.token_file.open('w') as stream:
dump(token, stream)
self.token_file.chmod(0o600)
def authorize(self):
""" Initiates OAuth2 authentication and authorization flow
"""
token = self.load_token()
if token:
self.session = OAuth2Session(self.client_id, token=token,
auto_refresh_url=self.token_uri,
auto_refresh_kwargs=self.extra,
token_updater=self.save_token)
else:
self.session = OAuth2Session(self.client_id, scope=self.scope,
redirect_uri=self.redirect_uri,
auto_refresh_url=self.token_uri,
auto_refresh_kwargs=self.extra,
token_updater=self.save_token)
# Redirect user to Google for authorization
authorization_url, _ = self.session.authorization_url(
authorization_base_url,
access_type="offline",
prompt="select_account")
print('Please go here and authorize,', authorization_url)
# Get the authorization verifier code from the callback url
response_code = input('Paste the response token here:')
# Fetch the access token
self.token = self.session.fetch_token(
self.token_uri, client_secret=self.client_secret,
code=response_code)
self.save_token(self.token)
# note we want retries on POST as well, need to review this once we
# start to do methods that write to Google Photos
retries = Retry(total=self.max_retries,
backoff_factor=0.1,
status_forcelist=[500, 502, 503, 504],
method_whitelist=frozenset(['GET', 'POST']),
raise_on_status=False)
self.session.mount('https://', HTTPAdapter(max_retries=retries))

Singing in TelegramClient telethon

After running the code, I try to enter a password (but I don’t have it) and can’t enter anything. I use VS Code
Please enter your phone (or bot token): 79622222693
Please enter the code you received: 40589
Please enter your password: (CANT ENTER ANYTHING, AND I DON'T HAVE ANY PASS ON MY ACCOUNT)
Tried different accounts.
from telethon import TelegramClient, sync
api_id = 973111111111145
api_hash = '05c6f86e67922222222222225ad7615a8'
client = TelegramClient('sessi1onname', api_id, api_hash)
client.start()
from telethon.sync import TelegramClient
api_id = 0
api_hash = ''
with TelegramClient('sessi1onname', api_id, api_hash) as client:
client.get_messages('me', "telethon sign in success")
use this code and then check your Saved Messages in telegram. will work for you. way you are trying is not sync!

How to transfert From Kraken to Poloniex by API

i would like to know can you transfert some currencies from Kraken to Poloniex using API functions ?
Didn't see anything talking about that.
Thank a lot
*
create new API key with "Withdraw funds" right on kraken
Go to account settings then click on "api" to go to settings api page, then click on "generate new key"
Fill all field and tick the box "Withdraw Funds", then validate.
add the poloniex deposit address in kraken (assuming deposit address already created)
Go to funding deposit page
then click on "withdraw" to go to funding withdraw page
Select the currency on the left side
(here we assume that you want withdraw BTC)
so you have to click on "Bitcoin (XBT)" on the left panel
Then click on "add address" then
fill both "Description" & "Bitcoin address" field.
Write down "Description" field because it will be required later when you will send API request to withdraw from Kraken to Poloniex.
Create the API request which will be sent to Kraken
Use the following code (re-use this example python library):
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import time
import requests
import urllib
import urllib2
import json
import hashlib
import httplib
import hmac
import random
import string
import base64
def _query( urlpath, req = {}, conn = None, headers = {}):
"""Low-level query handling.
Arguments:
urlpath -- API URL path sans host (string, no default)
req -- additional API request parameters (default: {})
conn -- kraken.Connection object (default: None)
headers -- HTTPS headers (default: {})
"""
uri = 'https://api.kraken.com'
url = uri + urlpath
if conn is None:
conn = Connection()
ret = conn._request(url, req, headers)
return json.loads(ret)
def query_private( method, req={}, conn = None):
#secret data
key = "123456789_my_api_key"
secret = "123456798_my_api_secret"
apiversion='0'
uri='https://api.kraken.com'
urlpath = '/' + apiversion + '/private/' + method
req['nonce'] = int(1000*time.time())
postdata = urllib.urlencode(req)
message = urlpath + hashlib.sha256(str(req['nonce']) +
postdata).digest()
signature = hmac.new(base64.b64decode(secret),
message, hashlib.sha512)
headers = {
'API-Key': key,
'API-Sign': base64.b64encode(signature.digest())
}
return _query(urlpath, req, conn, headers)
withdraw_params={
'asset': 'xbt',
'key': "Withdrawal address Description",
'amount': 0.25,
}
res=query_private('Withdraw', withdraw_params)
You'll need the withdrawFunds method from the Kraken API (https://www.kraken.com/help/api#withdraw-funds).
Using the Poloniex API, you'll need to get your deposit address using returnDepositAddresses. If you don't have a deposit address for the given cryptocurrency, use generateNewAddress.
Kraken API Documentation: https://www.kraken.com/help/api
Poloniex API Documentation: https://poloniex.com/support/api/

How can i trigger basic http auth and send user info in realtime?

I have just tried
===============================
# Give user the file requested
url = "http://superhost.gr/data/files/%s" % realfile
username = getpass.getuser()
password = getpass.getpass()
r = requests.get( url, auth = (username, password) ) # ask user for authentication data
r.raise_for_status()
===============================
as well as input() for both user & pass combo but iam not getting in chrome the basic pop-up HTTP auth window.
Any idea why?
How can i ASK the user for http auth data and store them isntead of giving them to the script?
You can try to use below code to ask user for credentials and send them via HTTP request
from requests.auth import HTTPBasicAuth
import requests
import sys
username = sys.argv[1]
password = sys.argv[2]
realfile = sys.argv[3]
url = "http://superhost.gr/data/files/%s" % realfile
r = requests.get( url, auth=HTTPBasicAuth(username, password))
print(r.status_code)
This script user can run as python script.py username password filename
# Give user the file requested
print('''<meta http-equiv="refresh"
content="5;url=http://superhost.gr/data/files/%s">''' % realfile)
authuser = os.environ.get( 'REMOTE_USER', 'Άγνωστος' )
print( authuser )
================================
Trying this, feels liek i'm almost there except that when printing the value of authuser variable it default to "Άγνωστος" meaning not there.
is there any other way i can grab what the user gave a auth login info?

python3 - can't pass through autorization

I need to build webcrawler for internal usage and I need to login into administration area. I'm trying to use requests lib, tried this ways:
import urllib.parse
import requests
base_url = "https://target.url"
data = ({'login': 'login', 'pass': 'password'})
params = urllib.parse.urlencode(data)
r = requests.post(base_url, data=params)
print(r.text)
and
import requests
base_url = "https://target.url"
r = requests.post(base_url, auth=('login', 'password')
print(r.text)
but in both cases r.text returns me login page content same as if I try to get any other page after auth code:
req = requests.get("https://target.url/smth")
What I lose sight of? I have ideas:
chain of hidden redirections from https://target.url to real login page, so I send auth info to wrong url
I don't send additional required info (like cookies e.g.)
Could you please comment? How can I gather required for login information?
In my case problem was in 'Referer' parameter in headers, which is required but wasn't specified