Commented the code in ga_auth
[ckanext-ga-report.git] / ckanext / ga_report / ga_auth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import httplib2
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run
 
from pylons import config
 
 
def _prepare_credentials( token_filename, credentials_filename ):
    """
    Either returns the user's oauth credentials or uses the credentials
    file to generate a token (by forcing the user to login in the browser)
    """
    storage = Storage( token_filename )
    credentials = storage.get()
 
    if credentials is None or credentials.invalid:
        flow = flow_from_clientsecrets(credentials_filename,
                scope='https://www.googleapis.com/auth/analytics.readonly',
                message="Can't find the credentials file")
        credentials = run(flow, storage)
 
    return credentials
 
def init_service( token_file, credentials_file ):
    """
    Given a file containing the user's oauth token (and another with
    credentials in case we need to generate the token) will return a
    service object representing the analytics API.
    """
    http = httplib2.Http()
 
    credentials = _prepare_credentials(token_file, credentials_file)
    http = credentials.authorize(http)  # authorize the http object
 
    return build('analytics', 'v3', http=http)
 
 
def get_profile_id(service):
    """
    Get the profile ID for this user and the service specified by the
    'googleanalytics.id' configuration option.
    """
    accounts = service.management().accounts().list().execute()
 
    if not accounts.get('items'):
        return None
 
    accountId = accounts.get('items')[0].get('id')
    webPropertyId = config.get('googleanalytics.id')
    profiles = service.management().profiles().list(
        accountId=accountId, webPropertyId=webPropertyId).execute()
 
    if profiles.get('items'):
        return profiles.get('items')[0].get('id')
 
    return None