]> git.ekhem.eu.org Git - gdrive_knife.git/commitdiff
Add a subprogram for obtaining an authentication token.
authorJakub Czajka <jakub@ekhem.eu.org>
Tue, 12 Sep 2023 18:04:33 +0000 (20:04 +0200)
committerJakub Czajka <jakub@ekhem.eu.org>
Sun, 19 Nov 2023 12:28:34 +0000 (13:28 +0100)
gdrive_knife.py
requirements.txt [new file with mode: 0644]

index 1c975d065429a4b20217eed43a5a8b193f2d9aee..1172c8a6512d12f8f1f48cc9d95a0bcff18db3d2 100644 (file)
@@ -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 (file)
index 0000000..8b3b6a3
--- /dev/null
@@ -0,0 +1,2 @@
+google-auth-httplib2==0.1.0
+google-auth-oauthlib==1.0.0