Skip to content

Commit

Permalink
try these
Browse files Browse the repository at this point in the history
  • Loading branch information
sujay1599 authored Aug 11, 2024
1 parent d978e07 commit 9da4c9a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 96 deletions.
30 changes: 10 additions & 20 deletions 2FA_DEV/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
from cryptography.fernet import Fernet
from rich.console import Console
from instagrapi.exceptions import LoginRequired, TwoFactorRequired
from dotenv import load_dotenv


console = Console()
logger = logging.getLogger()
Expand Down Expand Up @@ -52,7 +50,7 @@ def load_session(client, session_file):
return True
return False

def perform_login(client, username, password, session_file):
def perform_login(client, username, password, session_file, verification_code=None):
"""Handles logging in with or without 2FA enabled."""
if load_session(client, session_file):
try:
Expand All @@ -65,14 +63,18 @@ def perform_login(client, username, password, session_file):
except LoginRequired:
console.print("[bold red]Session is invalid, logging in with username and password[/bold red]")
logger.warning("Session is invalid, logging in with username and password")
return login_with_credentials(client, username, password, session_file)
return login_with_credentials(client, username, password, session_file, verification_code)
else:
return login_with_credentials(client, username, password, session_file)
return login_with_credentials(client, username, password, session_file, verification_code)

def login_with_credentials(client, username, password, session_file):
def login_with_credentials(client, username, password, session_file, verification_code=None):
"""Attempt to log in with username and password, handling 2FA if required."""
try:
client.login(username, password)
if verification_code:
client.login(username, password, verification_code=verification_code)
else:
client.login(username, password)

client.set_timezone_offset(-21600) # Set CST (Chicago) timezone offset
client.inject_sessionid_to_public() # Inject sessionid to public session
save_session(client, session_file)
Expand All @@ -85,19 +87,7 @@ def login_with_credentials(client, username, password, session_file):
console.print("[bold yellow]Two-Factor Authentication required.[/bold yellow]")
logger.warning("Two-Factor Authentication required.")
two_factor_code = input("Enter the 2FA code sent to your device: ")
try:
client.login(username, password, verification_code=two_factor_code)
client.set_timezone_offset(-21600) # Set CST (Chicago) timezone offset
client.inject_sessionid_to_public() # Inject sessionid to public session
save_session(client, session_file)
console.print(f"[bold blue]Logged in with 2FA, session file created - {username}[/bold blue]")
logger.info(f"Logged in with 2FA, session file created - {username}")
client.login_flow() # Simulate real user behavior after login
return True
except Exception as e:
console.print(f"[bold red]Failed to login using 2FA: {e}[/bold red]")
logger.error(f"Failed to login using 2FA: {e}")
return False
return login_with_credentials(client, username, password, session_file, two_factor_code)
except Exception as e:
console.print(f"[bold red]Failed to login using username and password: {e}[/bold red]")
logger.error(f"Failed to login using username and password: {e}")
Expand Down
70 changes: 18 additions & 52 deletions 2FA_DEV/config_setup.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import os
import getpass
import yaml
from cryptography.fernet import Fernet
import getpass
import os
from instagrapi import Client
from auth import perform_login, encrypt_credentials, generate_key, save_session, load_session
from input_helpers import get_input, get_boolean_input
from instagrapi import Client # Correct import of Client class
from auth import perform_login, decrypt_credentials # Import functions from auth.py
from default_comments import DEFAULT_COMMENTS
from default_descriptions import DEFAULT_DESCRIPTIONS
from rich.console import Console

console = Console()

# Constants
SESSION_DIR = 'user_sessions'
CONFIG_FILE = 'config.yaml'
console = Console()

# Ensure the session directory exists
if not os.path.exists(SESSION_DIR):
os.makedirs(SESSION_DIR)
console.print(f"[bold green]Created directory for user sessions: {SESSION_DIR}[/bold green]")

DEFAULT_TAGS = [
'instagram', 'instadaily', 'LikeForLike', 'FollowForFollow', 'viral',
'trending', 'explorepage', 'love', 'photooftheday', 'instagood',
Expand All @@ -27,41 +29,19 @@
'wanderlust', 'model', 'india', 'usa', 'goals'
]

# Ensure the session directory exists
if not os.path.exists(SESSION_DIR):
os.makedirs(SESSION_DIR)
console.print(f"[bold green]Created directory for user sessions: {SESSION_DIR}[/bold green]")

def generate_key():
return Fernet.generate_key()

def encrypt_credentials(username, password, key):
cipher_suite = Fernet(key)
encrypted_username = cipher_suite.encrypt(username).decode()
encrypted_password = cipher_suite.encrypt(password).decode()
return encrypted_username, encrypted_password

def get_user_credentials():
"""Prompt the user for Instagram credentials and validate by attempting login."""
"""Prompt the user for Instagram credentials and return them."""
while True:
username = input('Enter Instagram username: ').encode()
password = getpass.getpass('Enter Instagram password: ').encode()

# Check if the user has 2FA enabled
two_fa_enabled = get_boolean_input('Is 2FA enabled on this account? (true/false): ')
verification_code = None
if two_fa_enabled:
verification_code = input('Enter the 2FA verification code: ')

# Initialize the Client object
client = Client()
client.delay_range = [1, 3] # Mimic human behavior with delays between requests
session_file = os.path.join(SESSION_DIR, f"{username.decode()}_session.json")
client.delay_range = [1, 3] # Mimic human behavior with delays between requests

# Use perform_login function from auth.py to attempt login and manage session
if perform_login(client, username.decode(), password.decode(), session_file, verification_code):
# Attempt to login
if perform_login(client, username.decode(), password.decode(), session_file):
console.print("[bold green]Login successful![/bold green]")
return username, password, two_fa_enabled
return username, password, client.two_factor_auth_required
else:
console.print("[bold red]Login failed. Please try again.[/bold red]")

Expand Down Expand Up @@ -144,29 +124,15 @@ def save_config(config, filename=CONFIG_FILE):
yaml.dump(config, file)
console.print(f"[bold green]Configuration saved to {filename}[/bold green]")

def delete_files(files):
"""Delete specified files if they exist."""
for file in files:
if os.path.exists(file):
os.remove(file)
console.print(f"[bold yellow]Deleted {file}[/bold yellow]")

def load_config(config_file=CONFIG_FILE):
"""Load configuration from a YAML file."""
with open(config_file, 'r') as file:
return yaml.safe_load(file)

def main():
"""Main function to generate configuration and manage session files."""
key = generate_key()
username, password, two_fa_enabled = get_user_credentials()
encrypted_username, encrypted_password = encrypt_credentials(username, password, key)

encrypted_username, encrypted_password = encrypt_credentials(username.decode(), password.decode(), key)

config = create_config(encrypted_username, encrypted_password, key)
config['instagram']['original_username'] = username.decode() # Add original username to config
save_config(config)

delete_files(['status.json', 'last_scraped_timestamp.txt', 'random-upload-times.json', 'random-waits.json'])

if __name__ == "__main__":
main()
24 changes: 0 additions & 24 deletions 2FA_DEV/main.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,3 @@
import json

def display_version_info():
try:
with open('version.txt', 'r') as f:
version_info = json.load(f)

print("="*80)
print(f"Created by: {version_info['created_by']}")
print(f"Program: {version_info['program_name']}")
print(f"Version: {version_info['version']}")
print(f"Working as of: {version_info['working_as_of']}")
print("="*80)
except (FileNotFoundError, KeyError):
print("="*80)
print("Created by: Sujay1599")
print("Program: InstgramTheftyScraperPosterHuman")
print("Version: Unknown version")
print("Working as of: Unknown date")
print("="*80)

if __name__ == "__main__":
display_version_info()

import logging
import os
import random
Expand Down

0 comments on commit 9da4c9a

Please sign in to comment.