Skip to content
This repository was archived by the owner on Nov 3, 2019. It is now read-only.

Commit c10987e

Browse files
committed
Release 0.5
1 parent b46a48c commit c10987e

File tree

10 files changed

+236
-152
lines changed

10 files changed

+236
-152
lines changed

CHANGES.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,5 @@ Revision History
1212
|---------|-----------------------|-------------------------------------------------------------------------|
1313
| 0.4 | 13 July 2017 | Further http fixes |
1414
|---------|-----------------------|-------------------------------------------------------------------------|
15+
| 0.5 | 24 July 2017 | Encryption of Cookies file |
16+
|---------|-----------------------|-------------------------------------------------------------------------|

GoogleToken/Configuration.py

Lines changed: 61 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,87 +1,82 @@
11
# Author: Scott Philip (sp@scottphilip.com)
2-
# Version: 0.4 (13 July 2017)
2+
# Version: 0.5 (24 July 2017)
33
# Source: https://github.com/scottphilip/google-token/
44
# Licence: GNU GENERAL PUBLIC LICENSE (Version 3, 29 June 2007)
5+
56
import json
67
from os.path import expanduser, join, isdir
78
from os import makedirs
89
from tempfile import gettempdir
910
from datetime import datetime
1011

1112

12-
class GoogleTokenConfiguration:
13-
"""
14-
Configuration
15-
"""
13+
class GoogleTokenConfiguration(object):
14+
account_email = None
15+
account_password = None
16+
account_otp_secret = None
17+
cookie_storage_path = None
18+
oauth_client_id = None
19+
oauth_redirect_uri = None
20+
oauth_scope = None
21+
logger = None
22+
image_path = None
23+
execute_script = None
24+
phantomjs_path = "phantomjs"
25+
phantomjs_config_useragent = "phantomjs.page.settings.userAgent"
26+
phantomjs_log_path = None
27+
cookies_ignore_discard = False
28+
cookies_store_plain = False
29+
url_accounts = "https://accounts.google.com"
30+
url_my_account = "https://myaccount.google.com"
31+
url_service_login = "https://accounts.google.com/ServiceLogin"
32+
url_accounts_no_form = "https://accounts.google.com/x"
33+
timeout_seconds = 30
34+
oauth2_protocol = "https"
35+
oauth2_domain = "accounts.google.com"
36+
oauth2_path = "/o/oauth2/v2/auth"
37+
user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0"
38+
default_headers = None
39+
oauth2_data = None
1640

17-
def __init__(self,
18-
account_email=None,
19-
account_password=None,
20-
account_otp_secret=None,
21-
cookie_storage_path=None,
22-
oauth_client_id=None,
23-
oauth_redirect_uri=None,
24-
oauth_scope=None,
25-
logger=None,
26-
image_path=None,
27-
execute_script=None,
28-
phantomjs_path="phantomjs",
29-
phantomjs_config_useragent="phantomjs.page.settings.userAgent",
30-
phantomjs_log_path=None,
31-
cookies_ignore_discard=False,
32-
url_accounts="https://accounts.google.com",
33-
url_my_account="https://myaccount.google.com",
34-
url_service_login="https://accounts.google.com/ServiceLogin",
35-
url_accounts_no_form="https://accounts.google.com/x",
36-
timeout_seconds=30,
37-
oauth2_protocol="https",
38-
oauth2_domain="accounts.google.com",
39-
oauth2_path="/o/oauth2/v2/auth",
40-
user_agent="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0",
41-
default_headers=None,
42-
oauth2_data=None):
41+
def __init__(self, **kwargs):
42+
for key, value in kwargs.items():
43+
if hasattr(self, key):
44+
setattr(self, key, value)
45+
continue
46+
raise Exception("Unknown Argument: {0}".format(key))
4347

44-
self.account_email = account_email
48+
argument_missing = []
49+
if self.account_email is None:
50+
argument_missing.append("account_email")
51+
if self.oauth_client_id is None:
52+
argument_missing.append("oauth_client_id")
53+
if self.oauth_redirect_uri is None:
54+
argument_missing.append("oauth_redirect_uri")
55+
if self.oauth_scope is None:
56+
argument_missing.append("oauth_scope")
57+
if len(argument_missing) > 0:
58+
raise Exception("REQUIRED_ARGUMENT", str(argument_missing))
4559

4660
if not isdir(join(gettempdir(), "GoogleToken", self.account_email)):
4761
makedirs(join(gettempdir(), "GoogleToken", self.account_email))
48-
if self.account_email is None:
49-
raise Exception("account_email configuration must be set.")
50-
self.account_password = account_password
51-
self.account_otp_secret = account_otp_secret
52-
self.cookie_storage_path = cookie_storage_path if cookie_storage_path is not None \
53-
else join(expanduser("~"), "{0}.cookies".format(self.account_email))
54-
self.oauth_client_id = oauth_client_id
55-
self.oauth_redirect_uri = oauth_redirect_uri
56-
self.oauth_scope = oauth_scope
57-
self.logger = logger
58-
self.image_path = image_path if image_path is not None else join(
59-
gettempdir(),
60-
"GoogleToken",
61-
self.account_email,
62-
datetime.now().strftime("%Y-%m-%d_%H-%M-%S"))
63-
self.execute_script = execute_script
64-
self.phantomjs_path = phantomjs_path
65-
self.phantomjs_config_useragent = phantomjs_config_useragent
66-
self.phantomjs_log_path = phantomjs_log_path if phantomjs_log_path is not None \
67-
else join(gettempdir(),
68-
"GoogleToken",
69-
self.account_email, "phantomjs.log")
70-
self.cookies_ignore_discard = cookies_ignore_discard
71-
self.url_accounts = url_accounts
72-
self.url_my_account = url_my_account
73-
self.url_service_login = url_service_login
74-
self.url_accounts_no_form = url_accounts_no_form
75-
self.timeout_seconds = timeout_seconds
76-
self.oauth2_protocol = oauth2_protocol
77-
self.oauth2_domain = oauth2_domain
78-
self.oauth2_path = oauth2_path
79-
self.user_agent = user_agent
80-
self.default_headers = {"User-Agent": user_agent} if default_headers is None else default_headers
62+
63+
self.cookie_storage_path = join(expanduser("~"), "{0}.cookies".format(self.account_email)) \
64+
if self.cookie_storage_path is None else self.cookie_storage_path
65+
66+
self.image_path = join(gettempdir(), "GoogleToken", self.account_email, datetime.now()
67+
.strftime("%Y-%m-%d_%H-%M-%S")) if \
68+
self.image_path is None else self.image_path
69+
70+
self.phantomjs_log_path = join(gettempdir(), "GoogleToken", self.account_email, "phantomjs.log") if \
71+
self.phantomjs_log_path is None else self.phantomjs_log_path
72+
73+
self.default_headers = {"User-Agent": self.user_agent} if self.default_headers is \
74+
None else self.default_headers
75+
8176
self.oauth2_data = {"response_type": "token",
8277
"client_id": "oauth_client_id",
8378
"redirect_uri": "oauth_redirect_uri",
84-
"scope": "oauth_scope"} if oauth2_data is None else oauth2_data
79+
"scope": "oauth_scope"}
8580

8681
def json(self):
8782
result = {}

GoogleToken/Generator.py

Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
# Author: Scott Philip (sp@scottphilip.com)
2-
# Version: 0.4 (13 July 2017)
2+
# Version: 0.5 (24 July 2017)
33
# Source: https://github.com/scottphilip/google-token/
44
# Licence: GNU GENERAL PUBLIC LICENSE (Version 3, 29 June 2007)
55

6+
from GoogleToken.Configuration import GoogleTokenConfiguration
67
from GoogleToken.Utils import *
7-
from http.cookiejar import MozillaCookieJar
88
from os.path import isfile
9-
from json import dumps
9+
1010
try:
1111
from urllib.parse import urlparse, parse_qs
1212
from urllib.request import build_opener, Request, HTTPCookieProcessor
@@ -15,19 +15,18 @@
1515
from urllib2 import HTTPCookieProcessor, build_opener, Request
1616

1717

18-
class GoogleTokenGenerator(GoogleTokenBase):
18+
class GoogleTokenGenerator(object):
1919
"""
2020
Google Token Generator
2121
"""
2222

23-
def __init__(self, config=None):
24-
super(GoogleTokenGenerator, self).__init__(config)
25-
debug(self.config, "SYSTEM_CONFIGURATION", config.json())
23+
def __init__(self, **kwargs):
24+
self.config = GoogleTokenConfiguration(**kwargs)
25+
debug(self.config, "SYSTEM_CONFIGURATION", self.config.json())
2626

2727
def generate(self):
28-
cookie_storage_path = super(GoogleTokenGenerator, self).get_cookie_file_path()
29-
if not isfile(cookie_storage_path):
30-
debug(self.config, "COOKIE_FILE_NOT_FOUND", cookie_storage_path)
28+
if not isfile(self.config.cookie_storage_path):
29+
debug(self.config, "COOKIE_FILE_NOT_FOUND", self.config.cookie_storage_path)
3130
self.__phantom_login()
3231
return self.__cookies_login()
3332

@@ -44,31 +43,40 @@ def __cookies_login(self):
4443
return http_handler.get_access_token()
4544

4645

47-
class GoogleTokenHttpHandler(GoogleTokenBase):
46+
class GoogleTokenHttpHandler(object):
4847
"""
4948
Http Handler
5049
"""
5150

5251
def __init__(self, config):
53-
super(GoogleTokenHttpHandler, self).__init__(config)
54-
self.cookie_jar = MozillaCookieJar()
55-
if not isfile(super(GoogleTokenHttpHandler, self).get_cookie_file_path()):
56-
raise Exception("COOKIE_FILE_NOT_FOUND", super(GoogleTokenHttpHandler, self).get_cookie_file_path())
57-
self.cookie_jar.load(super(GoogleTokenHttpHandler, self).get_cookie_file_path())
52+
self.config = config
53+
if not isfile(self.config.cookie_storage_path):
54+
raise Exception("COOKIE_FILE_NOT_FOUND", self.config.cookie_storage_path)
55+
self.cookie_jar = open_cookie_jar(self.config)
5856
self.opener = build_opener(GoogleTokenHttpNoRedirect,
59-
HTTPCookieProcessor(self.cookie_jar))
57+
HTTPCookieProcessor(self.cookie_jar))
6058
debug(self.config, "COOKIES_LOADED")
6159

6260
def __enter__(self):
6361
return self
6462

6563
def __exit__(self, exc_type, exc_val, exc_tb):
66-
self.cookie_jar.save(super(GoogleTokenHttpHandler, self).get_cookie_file_path(),
67-
ignore_discard=self.config.cookies_ignore_discard)
64+
save_cookie_jar(self.config, self.cookie_jar)
6865
debug(self.config, "COOKIES_SAVED")
6966

67+
def get_oauth_url(self):
68+
data = {}
69+
data.update(self.config.oauth2_data)
70+
for key in data:
71+
if hasattr(self.config, data[key]):
72+
data[key] = getattr(self.config, data[key])
73+
return "{0}://{1}{2}?{3}" \
74+
.format(self.config.oauth2_protocol,
75+
self.config.oauth2_domain,
76+
self.config.oauth2_path, urlencode(data))
77+
7078
def get_access_token(self):
71-
request = Request(super(GoogleTokenHttpHandler, self).get_oauth_url(),
79+
request = Request(self.get_oauth_url(),
7280
headers=self.config.default_headers)
7381
debug(self.config, "SENDING_REQUEST")
7482
response = self.opener.open(request)
@@ -99,7 +107,6 @@ def get_first_value(obj, attr_name):
99107
return item
100108
return obj[attr_name]
101109

102-
103110
@staticmethod
104111
def get_fragment(url):
105112
parsed = urlparse(url)

GoogleToken/Main.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from GoogleToken.Generator import GoogleTokenGenerator
2+
3+
4+
def get_google_token(account_email,
5+
oauth_client_id,
6+
oauth_redirect_uri,
7+
oauth_scope,
8+
account_password=None,
9+
account_otp_secret=None,
10+
**kwargs):
11+
"""
12+
:param account_email: (REQUIRED)
13+
:param oauth_client_id: (REQUIRED)
14+
:param oauth_redirect_uri: (REQUIRED)
15+
:param oauth_scope: (REQUIRED)
16+
:param account_password: Necessary for first use.
17+
:param account_otp_secret: Necessary for first use if enabled on account
18+
:return: generated token
19+
"""
20+
21+
items = {"account_email": account_email,
22+
"oauth_client_id": oauth_client_id,
23+
"oauth_redirect_uri": oauth_redirect_uri,
24+
"oauth_scope": oauth_scope,
25+
"account_password": account_password,
26+
"account_otp_secret": account_otp_secret}
27+
for key, value in kwargs.items():
28+
if key not in items:
29+
items[key] = value
30+
31+
generator = GoogleTokenGenerator(**items)
32+
return generator.generate()

GoogleToken/Phantom.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# Author: Scott Philip (sp@scottphilip.com)
2-
# Version: 0.4 (13 July 2017)
2+
# Version: 0.5 (24 July 2017)
33
# Source: https://github.com/scottphilip/google-token/
44
# Licence: GNU GENERAL PUBLIC LICENSE (Version 3, 29 June 2007)
55

@@ -54,8 +54,7 @@ def save_cookies(self):
5454
for driver_cookie in driver_cookies:
5555
http_cookie = self.get_cookie(driver_cookie)
5656
cookie_jar.set_cookie(http_cookie)
57-
cookie_jar.save(super(GoogleTokenPhantomLogin, self).get_cookie_file_path(),
58-
ignore_discard=self.config.cookies_ignore_discard)
57+
save_cookie_jar(self.config, cookie_jar)
5958

6059
@staticmethod
6160
def get_cookie(item):

GoogleToken/Sample.py

Lines changed: 0 additions & 20 deletions
This file was deleted.

0 commit comments

Comments
 (0)