"Fossies" - the Fresh Open Source Software Archive

Member "getmail-5.16/getmail-gmail-xoauth-tokens" (31 Oct 2021, 3571 Bytes) of package /linux/misc/getmail-5.16.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "getmail-gmail-xoauth-tokens": 5.15_vs_5.16.

    1 #!/usr/bin/env python2
    2 
    3 #
    4 # Copyright 2012 Google Inc.
    5 #
    6 # Licensed under the Apache License, Version 2.0 (the "License");
    7 # you may not use this file except in compliance with the License.
    8 # You may obtain a copy of the License at
    9 #
   10      # http://www.apache.org/licenses/LICENSE-2.0
   11 #
   12 # Unless required by applicable law or agreed to in writing, software
   13 # distributed under the License is distributed on an "AS IS" BASIS,
   14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   15 # See the License for the specific language governing permissions and
   16 # limitations under the License.
   17 #
   18 
   19 #
   20 # Derived from oauth2.py (https://github.com/google/gmail-oauth2-tools).
   21 # Heavily modified and rewritten by Stefan Krah.
   22 #
   23 
   24 
   25 import os
   26 import sys
   27 import urllib
   28 import json
   29 import argparse
   30 import time
   31 
   32 
   33 class OAuth2(object):
   34 
   35     def __init__(self, token_data_path):
   36         self.token_data_path = token_data_path
   37 
   38         with open(self.token_data_path) as f:
   39             self.data = json.load(f)
   40 
   41     def copy(self, *keys):
   42         data = {}
   43         for k in keys:
   44             data[k] = self.data[k]
   45         return data
   46 
   47     def query(self, params):
   48         lst = []
   49         for param in sorted(params.iteritems(), key=lambda x: x[0]):
   50             escaped = urllib.quote(param[1], safe='~-._')
   51             lst.append('%s=%s' % (param[0], escaped))
   52         return '&'.join(lst)
   53 
   54     def code_url(self):
   55         params = self.copy('scope', 'client_id', 'redirect_uri')
   56         params['response_type'] = 'code'
   57         return '%s?%s' % (self.data['auth_uri'], self.query(params))
   58 
   59     def get_response(self, url, params):
   60         encoded = urllib.urlencode(params)
   61         response = urllib.urlopen(url, encoded).read()
   62         return json.loads(response)
   63 
   64     def update_config(self, d):
   65         self.data['access_token'] = d['access_token']
   66         self.data['expires_at'] = time.time() + d['expires_in'] - 100
   67 
   68         refresh_token = d.get('refresh_token')
   69         if refresh_token is not None:
   70             self.data['refresh_token'] = refresh_token
   71 
   72         with open(self.token_data_path, "w") as f:
   73             json.dump(self.data, f)
   74 
   75     def init_tokens(self, code):
   76         params = self.copy('user', 'client_id', 'client_secret',
   77                            'redirect_uri')
   78         params['code'] = code
   79         params['grant_type'] = 'authorization_code'
   80 
   81         d = self.get_response(self.data['token_uri'], params)
   82         self.update_config(d)
   83 
   84     def refresh_tokens(self):
   85         params = self.copy('client_id', 'client_secret', 'refresh_token')
   86         params['grant_type'] = 'refresh_token'
   87 
   88         d = self.get_response(self.data['token_uri'], params)
   89         self.update_config(d)
   90 
   91     def token(self):
   92         if time.time() >= self.data.get('expires_at'):
   93             self.refresh_tokens()
   94 
   95         return self.data['access_token']
   96 
   97 
   98 if __name__ == '__main__':
   99     parser = argparse.ArgumentParser()
  100     parser.add_argument("-i", "--init", action="store_true", default=False,
  101                         help="initialize access and refresh tokens")
  102     parser.add_argument('tokenfile', metavar='<token data file path>',
  103                         help="location of the token data file")
  104 
  105     args = parser.parse_args()
  106     auth = OAuth2(args.tokenfile)
  107 
  108     if args.init:
  109         print "Visit this url to obtain a verification code:"
  110         print "    %s\n" % auth.code_url()
  111 
  112         code = raw_input("Enter verification code: ")
  113         response = auth.init_tokens(code)
  114     else:
  115         sys.stdout.write("%s" % auth.token())
  116 
  117     sys.exit(0)