diff --git a/routers/auth.py b/routers/auth.py index 3629f2d..0176843 100644 --- a/routers/auth.py +++ b/routers/auth.py @@ -2,6 +2,10 @@ from typing import Optional, Dict from fastapi import APIRouter, Depends, Form from dependencies import ClientStorage, get_clients +from instagrapi.exceptions import ( + ChallengeRequired +) + router = APIRouter( prefix="/auth", @@ -9,13 +13,24 @@ responses={404: {"description": "Not found"}} ) - -def challenge_code_handler(username, choice, challenge_url, session=None): - # Aqui salva o challenge_url e os headers e os cookies que tão nessa session - print(f"username:{username} \n CHOICE:{choice}") - print(f"URL:{challenge_url} \n session {session}") - - return False +def handle_exception(client, e): + if isinstance(e, ChallengeRequired): + print("------ Challenge required \n\n") + api_path = client.last_json['challenge']['api_path'] + user_id = client.last_json['challenge']['user_id'] + settings = client.get_settings(); + settings.challenge_url = api_path + # Vamos salvar as configurações do usuário que iniciou o challenge + clients: ClientStorage = Depends(get_clients) + cl = clients.client() + cl.set_settings(json.loads(settings)) + # Mock an session ID + sessionid = user_id + ":challenge_required" + cl.sessionid = sessionid + # aqui ele vai salvar no tinydb + clients.set(cl) + + return True @router.post("/login") async def auth_login(username: str = Form(...), @@ -27,8 +42,11 @@ async def auth_login(username: str = Form(...), clients: ClientStorage = Depends(get_clients)) -> str: """Login by username and password with 2FA """ + + cl = clients.client() - cl.challenge_code_handler = challenge_code_handler + + cl.handle_exception = handle_exception if proxy != "": cl.set_proxy(proxy) @@ -44,6 +62,8 @@ async def auth_login(username: str = Form(...), password, verification_code=verification_code ) + + if result: clients.set(cl) return cl.sessionid @@ -68,13 +88,9 @@ async def challenge_code(sessionid: str = Form(...), cl = clients.get(sessionid) ## Aqui você puxa os headers, os cookies e o challenge_url que você salvou na linha 14 e chama o checkpoint_resume - old_session = "" - challenge_url = "" - - if(old_session): - result = cl.resume_checkpoint(code, challenge_url, old_session) - else: - result = cl.send_checkpoint_code(code, challenge_url) + settings = cl.get_settings() + challenge_url = settings.challenge_url + result = cl.send_checkpoint_code(code, challenge_url) return result