I have a flask web application (app.py) running on amazon ec2 server to which my users authenticate using their box login and password. The application also has a background cron process (cron.py) that needs to process the user's box files every few minutes.
The flask app is structured in such a way that as soon as the user authenticates and box.com redirects them back to the app home page, the access_token and refresh_token are stored in the database so that the cron can access it:
def store_the_tokens(access_token, refresh_token):
print("store_the_tokens() called.")
conn, cursor = db.opendb()
cursor.execute("update box_tokens set auth_code=?, access_token=?, refresh_token=?", (session.get('auth_code'),access_token, refresh_token))
conn.commit()
#session["message_info"] = "Authentication successful!"
redirect(url_for("index"))
oauth = OAuth2(
client_id=config.client_id,
client_secret=config.client_secret,
store_tokens=store_the_tokens,
)
Now, the trouble is that the cron is able to access the user files and folders, but only for one hour! After that, the following error message keeps coming:
Message: b'{"error":"invalid_grant","error_description":"The authorization code
Here is the cron.py code that tries to access the files through api. I also tried to handle the exception and get a new refresh_token by using the auth_code used during authentication, but in that case, I get the error: :"The authorization code has expired".
try:
oauth = OAuth2(
client_id=config.client_id,
client_secret=config.client_secret,
access_token = access_token,
refresh_token = refresh_token,
store_tokens = store_the_tokens,
)
test_folder = client.folder(folder_id=0)
except Exception as eouth:
#print(str(eoauth))
#invalid grant, token expired
log("Authentication error. Trying to refresh token.")
access_token, refresh_token = oauth.authenticate(auth_code)
oauth = OAuth2(
client_id=config.client_id,
client_secret=config.client_secret,
access_token = access_token,
store_tokens = store_the_tokens,
)
What can I do so that the cron.py is able to function without the need for user re-authentication every hour?
