fix: verify session belongs to expected account before using
- Add _verify_session() to check profile exists after loading session - Skip session files from wrong accounts - Clear cookies before trying next auth method
This commit is contained in:
@@ -52,8 +52,13 @@ class InstagramMonitor:
|
||||
if session_path.exists():
|
||||
try:
|
||||
self.loader.load_session_from_file(config.instagram_username, str(session_path))
|
||||
logger.info(f"Session loaded from {session_path}")
|
||||
return True
|
||||
# Verify session belongs to the right account
|
||||
if self._verify_session():
|
||||
logger.info(f"Session loaded from {session_path}")
|
||||
return True
|
||||
else:
|
||||
logger.warning(f"Session from {session_path} belongs to wrong account, skipping")
|
||||
self._reset_session()
|
||||
except Exception as e:
|
||||
logger.warning(f"Session file {session_path} invalid: {e}")
|
||||
|
||||
@@ -134,6 +139,20 @@ class InstagramMonitor:
|
||||
# Verify session works
|
||||
instaloader.Profile.from_username(self.loader.context, config.instagram_username)
|
||||
|
||||
def _verify_session(self) -> bool:
|
||||
"""Check if loaded session belongs to the expected account."""
|
||||
try:
|
||||
profile = instaloader.Profile.from_username(self.loader.context, config.instagram_username)
|
||||
return True
|
||||
except instaloader.exceptions.ProfileNotExistsException:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _reset_session(self) -> None:
|
||||
"""Clear session cookies to start fresh."""
|
||||
self.loader.context._session.cookies.clear()
|
||||
|
||||
def _load_cookies_from_json(self, path: Path) -> None:
|
||||
with open(path) as f:
|
||||
cookies = json.load(f)
|
||||
|
||||
Reference in New Issue
Block a user