From: Jakub Czajka Date: Tue, 12 Sep 2023 18:04:33 +0000 (+0200) Subject: Add a subprogram for obtaining an authentication token. X-Git-Url: https://git.ekhem.eu.org/?a=commitdiff_plain;h=4f9c9ab34ec0c1923f0caf0fbd6b4bed83278baa;p=gdrive_knife.git Add a subprogram for obtaining an authentication token. --- diff --git a/gdrive_knife.py b/gdrive_knife.py index 1c975d0..1172c8a 100644 --- a/gdrive_knife.py +++ b/gdrive_knife.py @@ -2,7 +2,55 @@ # License: GPL-3.0 or later. import argparse +import os.path + +from google.auth.transport.requests import Request +from google.oauth2.credentials import Credentials +from google_auth_oauthlib.flow import InstalledAppFlow + +SCOPES = ['https://www.googleapis.com/auth/drive.metadata', + 'https://www.googleapis.com/auth/drive', + 'https://www.googleapis.com/auth/drive.file'] + +def file_path(parser, path): + if not os.path.isfile(path): + return parser.error(f'{path} does not exist!') + return path + +def auth(args): + creds = None + if os.path.exists(args.token): + print(f'{args.token} exists. Trying to authenticate with it.') + creds = Credentials.from_authorized_user_file(args.token, SCOPES) + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + print(f'{args.token} has expired. Refreshing.') + creds.refresh(Request()) + else: + print(f'{args.token} does not exist. Obtaining a new token.') + flow = InstalledAppFlow.from_client_secrets_file(args.credentials, + SCOPES) + creds = flow.run_local_server(port=0) + print(f'Writing new token to {args.token}.') + with open(args.token, 'w') as token: + token.write(creds.to_json()) + print('Authentication successful.') if __name__ == '__main__': parser = argparse.ArgumentParser(prog='gdrive_knife', description='Swiss ' 'army knife for working with Google Drive.') + + subparsers = parser.add_subparsers() + + auth_parser = subparsers.add_parser('auth', help='Authenticate and obtain a ' + 'token.') + auth_parser.add_argument('-c', dest='credentials', required=True, + type=lambda x : file_path(parser, x), help='File with credentials.') + auth_parser.add_argument('-t', dest='token', default='token.json', + required=True, help='Path where the authentication token should be ' + 'saved.') + auth_parser.set_defaults(func=auth) + + args = parser.parse_args() + + args.func(args) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..8b3b6a3 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +google-auth-httplib2==0.1.0 +google-auth-oauthlib==1.0.0