Danyc0 / Society-voting-bot

A Discord bot for doing society elections
Apache License 2.0
2 stars 4 forks source link

Fix Google OAuth so that it can generate tokens on the server and the bot can refresh the token as needed #39

Open Danyc0 opened 3 years ago

Danyc0 commented 3 years ago

Fix Google OAuth so that it can: A. Generate tokens on the server, and B. Refresh the token as needed

Danyc0 commented 2 years ago

The current workaround is to pretend that it's a desktop app. This requires token generation on a desktop PC using this code which is a stripped-down version of the google sheets API python quickstart code:

import os.path
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

def main():
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
        print('Got token from token.json file')
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

if __name__ == '__main__':
    main()

To run it you must have first created a credentials.json file through the google sheets API console. It will result in a token.json file which then can just be transferred to the server and dropped into the folder for this repo. It'll need manually refreshing every so often

Danyc0 commented 2 years ago

As far as I can tell this needs us to set up a bunch of stuff including a domain and an https cert for a callback so unfortunately this isn't going to happen in time for the 2021 CSS EGM. We can just continue to use the workaround for now