remove cookies before login
ShoGinn opened this issue · comments
I have experienced an issue that cookies can be set (incorrectly programmatically) and that when you then try and recover by using .login(),
you must use your internal HTTP.client.cookies.clear()
instead of login just doing it.
Recommend just clearing cookies when the login command is ran.
Just use client.set_cookies({}, True)
The first arg is te cookies (se {} to avoid) and the second arg is a flag to clear cookies.
I understand there is a way to clear cookies.
Lets use this scenario:
First Program Run:
login, save cookies.
Second Program Run:
note that cookies are saved and use saved cookies (using set_cookies)
get_tweets
etc. works fine
Third Program Run:
note that cookies are saved. Use saved cookies (using set_cookies)
get_tweets
throws an error for Unauthorized
This is where you are saying to run, then
.set_cookies(clear_cookies=true)
Real case.
.login()
and cookies are used anyway... so you have to.
This is my current code:
def login_with_credentials(twikit_client: Client, mongodb_client: MongoDBClient, app_settings: Settings) -> bool:
"""Login to X using the provided credentials."""
# Check to make sure the authentication information is provided
if not app_settings.x_username or not app_settings.x_email or not app_settings.x_password.get_secret_value():
raise ValueError("X credentials are missing or incomplete.")
logger.info("Logging in to X...")
twikit_client.http.client.cookies.clear() # TODO: Remove this once the twikit library is updated
try:
twikit_client.login(
auth_info_1=app_settings.x_username,
auth_info_2=app_settings.x_email,
password=app_settings.x_password.get_secret_value(),
)
logger.info("Successfully logged in to X.")
store_cookies(mongodb_client, twikit_client)
return True
except Exception as e:
logger.error(f"Error logging in to X: {e}")
logger.error("Please check your X credentials and run the program again.")
return False
Because the .login()
uses the HTTP engine, and if you have set cookies, it will always attempt to use cookies.
I hope I have explained why clearing cookies in .login()
is essential because of the HTTP engine's nature.
I understand now! In fact, the suggested correction has already been uploaded.
That's hilarious ;) I'll have to pick on @d60 for not closing this, then!
I'll close it with this comment!!!
Good find @itsManeka
I forgot to close this issue. Sorry for the confusion!
@ShoGinn @itsManeka
I think that any dialog/examination of code is beneficial and shows that your efforts are being acknowledged so apologies are unnecessary!