def main():
    """
    main function
    """

    credentials = get_cred(email, "admin.directory.user")
    http = httplib2.Http()

    service = build(
        "admin", "directory_v1", http=credentials.authorize(http)
    )

    user_list = []
    page_token = None
    while True:
        results = service.users().list(
            domain=email.split('@')[1],
            maxResults=500,
            pageToken=page_token,
            orderBy='familyName', viewType='domain_public'
        ).execute()

        for r in results["users"]:
            user_list.append(r)

        page_token = results.get('nextPageToken')
        if not page_token:
            break

    for user in user_list:
        pmail = user.get('primaryEmail')
        if pmail:
            credentials = get_cred(pmail, "gmail.settings.basic")
            http = httplib2.Http()
            service = build(
                "gmail", "v1", http=credentials.authorize(http)
            )
            try:
                # sometimes this barfs with 400 server error:
                # "Mail service not enabled"
                # not certain why at this moment.
                aliases = service.users().settings().sendAs().list(
                    userId=pmail
                ).execute(num_retries=10)
                for alias in aliases.get('sendAs'):
                    #if alias.get('treatAsAlias') and alias.get('verificationStatus')=='accepted':
                    if alias.get('treatAsAlias'):
                        print '{}|{}|{}|{}|{}'.format(
                            user.get('name').get('familyName'),
                            user.get('name').get('givenName'),
                            user.get('primaryEmail'), alias.get('sendAsEmail'),
                            alias.get('verificationStatus')
                        )
            except:
                pass
Example #2
0
def main():
    """
    main function
    """

    credentials = get_cred(email, "admin.directory.user")
    http = httplib2.Http()

    service = build(
        "admin", "directory_v1", http=credentials.authorize(http)
    )

    user_list = []
    page_token = None
    while True:
        results = service.users().list(
            domain=email.split('@')[1],
            maxResults=500,
            pageToken=page_token,
            orderBy='familyName', viewType='domain_public'
        ).execute()

        for r in results["users"]:
            user_list.append(r)

        page_token = results.get('nextPageToken')
        if not page_token:
            break

    for user in user_list:
        pmail = user.get('primaryEmail')
        if pmail:
            credentials = get_cred(pmail, "gmail.settings.basic")
            http = httplib2.Http()
            service = build(
                "gmail", "v1", http=credentials.authorize(http)
            )
            try:
                # sometimes this barfs with 400 server error:
                # "Mail service not enabled"
                # not certain why at this moment.
                aliases = service.users().settings().sendAs().list(
                    userId=pmail
                ).execute(num_retries=10)
                for alias in aliases.get('sendAs'):
                    #if alias.get('treatAsAlias') and alias.get('verificationStatus')=='accepted':
                    if alias.get('treatAsAlias'):
                        print '{}|{}|{}|{}|{}'.format(
                            user.get('name').get('familyName'),
                            user.get('name').get('givenName'),
                            user.get('primaryEmail'), alias.get('sendAsEmail'),
                            alias.get('verificationStatus')
                        )
            except:
                pass
def main():
    """
    main function
    """

    global email

    # space separated list of authorized API scopes for this service account
    scope = 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/'
    # create our email settings client
    client = EmailSettingsClient(domain=email.split('@')[1])
    # obtain our street cred
    credentials = get_cred(email, scope)
    # fetch our access token
    auth2token = OAuth2TokenFromCredentials(credentials)
    # authorize our client
    auth2token.authorize(client)

    with open(phile, 'rb') as f:
        reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
        for r in reader:
            try:
                if '@' in r[0]:
                    forwarding = client.RetrieveForwarding(
                        username=r[0].split('@')[0]
                    ).property[1].value
                    if forwarding:
                        print("{}|{}".format(r[0], forwarding))
            except:
                print("{}|Error".format(r[0]))
def main():
    """
    main function
    """

    credentials = get_cred(email, "admin.directory.user")
    http = httplib2.Http()

    service = build(
        "admin", "directory_v1", http=credentials.authorize(http)
    )

    user_list = []
    page_token = None
    while True:
        results = service.users().list(
            domain=email.split('@')[1],
            maxResults=500,
            pageToken=page_token,
            orderBy='email', viewType='domain_public'
        ).execute()

        for r in results["users"]:
            user_list.append(r)

        page_token = results.get('nextPageToken')
        if not page_token:
            break

    print "length of user_list: {}".format(len(user_list))
    for users in user_list:
        #print u["primaryEmail"]
        print users
def main():
    """
    main function
    """

    credentials = get_cred(email, "admin.directory.user")
    http = httplib2.Http()

    service = build("admin", "directory_v1", http=credentials.authorize(http))

    user_list = []
    page_token = None
    while True:
        results = service.users().list(domain=email.split('@')[1],
                                       maxResults=500,
                                       pageToken=page_token,
                                       orderBy='email',
                                       viewType='domain_public').execute()

        for r in results["users"]:
            user_list.append(r)

        page_token = results.get('nextPageToken')
        if not page_token:
            break

    print "length of user_list: {}".format(len(user_list))
    for user in user_list:
        print user["primaryEmail"]
Example #6
0
def search(request):

    forwarding = None
    if request.method == "POST":
        form = SearchForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            # space separated list of authorized API scopes for
            # the service account
            scope = 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/'
            # create our email settings client
            client = EmailSettingsClient(
                domain=settings.DOMAIN_SUPER_USER_EMAIL.split('@')[1]
            )
            # obtain our street cred
            credentials = get_cred(settings.DOMAIN_SUPER_USER_EMAIL, scope)
            # fetch our access token
            auth2token = OAuth2TokenFromCredentials(credentials)
            # authorize our client
            auth2token.authorize(client)
            try:
                forwarding = client.RetrieveForwarding(
                    username=cd["username"]
                ).property[1].value
            except:
                forwarding = None
    else:
        form = SearchForm()

    return render_to_response(
        'emailsettings/search.html', {
            'form': form, 'forwarding': forwarding,
        },
        context_instance=RequestContext(request)
    )
Example #7
0
def search(request):

    forwarding = None
    emails = None
    if request.method == "POST":
        form = SearchForm(request.POST)
        if form.is_valid():

            cd = form.cleaned_data
            # space separated list of authorized API scopes for
            # the service account
            scope = 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/'
            # create our email settings client
            client = EmailSettingsClient(
                domain=settings.DOMAIN_SUPER_USER_EMAIL.split('@')[1])
            # obtain our street cred
            credentials = get_cred(settings.DOMAIN_SUPER_USER_EMAIL, scope)
            # fetch our access token
            auth2token = OAuth2TokenFromCredentials(credentials)
            # authorize our client
            auth2token.authorize(client)
            if cd['username']:
                try:
                    forwarding = client.RetrieveForwarding(
                        username=cd["username"]).property[1].value
                except:
                    forwarding = None
            elif request.FILES.get('phile'):
                save_path = os.path.join(settings.MEDIA_ROOT,
                                         'files/emailsettings.csv')
                path = default_storage.save(save_path, request.FILES['phile'])
                emails = []
                with open(path, 'rb') as f:
                    reader = csv.reader(f,
                                        delimiter=',',
                                        quoting=csv.QUOTE_NONE)
                    for r in reader:
                        try:
                            if '@' in r[0]:
                                forwarding = client.RetrieveForwarding(
                                    username=r[0].split(
                                        '@')[0]).property[1].value
                                if forwarding:
                                    emails.append(forwarding)
                        except:
                            forwarding = None
            else:
                forwarding = 'Error'
    else:
        form = SearchForm()

    return render(request, 'emailsettings/search.html', {
        'form': form,
        'forwarding': forwarding,
        'emails': emails
    })
def main():
    """main function."""

    sql = """
        SELECT
            lastname, firstname, username
        FROM
            provisioning_vw
        WHERE
            {} is not null
        ORDER BY
            lastname, firstname
    """.format(who)

    if test:
        print("sql = {}".format(sql))
    else:
        user_list = do_sql(sql, key=settings.INFORMIX_DEBUG, earl=EARL)
        for user in user_list:
            email = '{0}@carthage.edu'.format(user.username)
            try:
                credentials = get_cred(email, 'calendar')
                http = httplib2.Http()
                http = credentials.authorize(http)
                service = build('calendar', 'v3', http=http)
            except Exception as error:
                print('{0}|{1}|{2}|Invalid email'.format(user.lastname, user.firstname, email))
                continue
            page_token = None
            domain = None
            while True:
                try:
                    acl = service.acl().list(calendarId=email).execute()
                except Exception:
                    print('{0}|{1}|{2}|No calendar'.format(user.lastname, user.firstname, email))
                    break
                for rule in acl['items']:
                    #print(rule)
                    #print('%s: %s' % (rule['id'], rule['role']))
                    # type == 'domain' value == 'carthage.edu'
                    #print(rule['scope']['type'])
                    #print(rule['scope']['value'])
                    if rule['scope']['type'] == 'domain':
                        domain = rule['role']
                        break
                page_token = acl.get('nextPageToken')
                if not page_token:
                    break
                # sometimes the google returns a shit tonne of pages that are just repeats
                if domain:
                    break
            if domain:
                print('{0}|{1}|{2}|{3}'.format(user.lastname, user.firstname, email, domain))
            else:
                print('{0}|{1}|{2}|No access'.format(user.lastname, user.firstname, email))
Example #9
0
 def __init__(self, email, cache=True):
     # obtain our street cred
     scope = 'https://www.google.com/m8/feeds/'
     credentials = get_cred(email, scope)
     # initialise the client with an ad-hoc name
     self.client = client_contacts.ContactsClient(
         source=settings.CONTACTS_SOURCE
     )
     # fetch our access token
     auth2token = OAuth2TokenFromCredentials(credentials)
     # authorize our client
     auth2token.authorize(self.client)
def main():
    """
    main function
    """

    credentials = get_cred(email, "admin.directory.user")
    http = httplib2.Http()

    service = build("admin", "directory_v1", http=credentials.authorize(http))

    results = service.users().aliases().list(userKey=email).execute()
    print results
Example #11
0
def main():
    """
    main function
    """

    credentials = get_cred(email, "admin.directory.user")
    http = httplib2.Http()

    service = build("admin", "directory_v1", http=credentials.authorize(http))

    results = service.users().aliases().list(userKey=email).execute()
    print results
def main():
    """
    main function
    """

    # API scope
    scope = 'https://www.google.com/m8/feeds/'

    client = client_contacts.ContactsClient(
        source='Carthage_College_DJUsagi_ContactsClient')

    # obtain our street cred
    credentials = get_cred(email, scope)
    # fetch our access token
    auth2token = OAuth2TokenFromCredentials(credentials)
    # authorize our client
    auth2token.authorize(client)

    # Note: The special userEmail value default can be used
    # to refer to the authenticated user.
    #earl = 'https://www.google.com/m8/feeds/contacts/default/full/'

    query = ContactsQuery()
    query.max_results = 10000

    contacts = client.GetContacts(q=query)

    for i, entry in enumerate(contacts.entry):
        try:
            print '\n%s %s' % (i + 1, entry.name.full_name.text)
        except:
            print '\n%s %s' % (i + 1, 'no full_name')
        if entry.content:
            print '    %s' % (entry.content.text)
        # Display the primary email address for the contact.
        for e in entry.email:
            if e.primary and e.primary == 'true':
                print '    %s' % (e.address)
        # Show the contact groups that this contact is a member of.
        for group in entry.group_membership_info:
            print '    Member of group: %s' % (group.href)
        # Display extended properties.
        for extended_property in entry.extended_property:
            if extended_property.value:
                value = extended_property.value
            else:
                value = extended_property.GetXmlBlob()
            print '    Extended Property - %s: %s' % (extended_property.name,
                                                      value)
def main():
    """
    main function
    """

    credentials = get_cred(email, "gmail.settings.basic")
    http = httplib2.Http()
    service = build(
        "gmail", "v1", http=credentials.authorize(http)
    )
    aliases = service.users().settings().sendAs().list(
        userId=email
    ).execute()
    for alias in aliases.get('sendAs'):
        if alias.get('treatAsAlias') and alias.get('verificationStatus')=='accepted':
            print alias
Example #14
0
def main():
    """
    main function
    """

    credentials = get_cred(email, "gmail.settings.basic")
    http = httplib2.Http()
    service = build(
        "gmail", "v1", http=credentials.authorize(http)
    )
    aliases = service.users().settings().sendAs().list(
        userId=email
    ).execute()
    for alias in aliases.get('sendAs'):
        if alias.get('treatAsAlias') and alias.get('verificationStatus')=='accepted':
            print alias
Example #15
0
def main():
    """main function."""

    credentials = get_cred(email, 'calendar')
    http = httplib2.Http()
    http = credentials.authorize(http)

    service = build('calendar', 'v3', http=http)

    page_token = None
    while True:
        acl = service.acl().list(calendarId=email).execute()
        for rule in acl['items']:
            print(rule)
            #print('%s: %s' % (rule['id'], rule['role']))
        page_token = acl.get('nextPageToken')
        if not page_token:
            break
def main():
    """
    main function
    """

    global username
    global email
    global client

    if not username:
        username = '******'
    else:
        username = '******'.format(username)

    # storage for credentials
    storage = Storage(settings.STORAGE_FILE)
    # create an http client
    http = httplib2.Http()

    # obtain the admin directory user cred
    users_cred = storage.get()
    if users_cred is None or users_cred.invalid:
        users_cred = get_cred(email, SCOPE)
        storage.put(users_cred)
    else:
        users_cred.refresh(http)

    # build the service connection
    service = build("admin", "reports_v1", http=users_cred.authorize(http))

    results = service.activities().list(userKey=username,
                                        applicationName='login',
                                        maxResults=10).execute()

    activities = results.get('items', [])

    if not activities:
        print('No logins found.')
    else:
        print('Logins:')
        for activity in activities:
            print('{0}: {1} ({2})'.format(activity['id']['time'],
                                          activity['actor']['email'],
                                          activity['events'][0]['name']))
def main():
    """
    main function
    """

    credentials = get_cred(email, "admin.directory.user")
    http = httplib2.Http()

    service = build(
        "admin", "directory_v1", http=credentials.authorize(http)
    )

    user_list = []
    page_token = None
    while True:
        results = service.users().list(
            domain=email.split('@')[1],
            maxResults=100,
            pageToken=page_token,
            orderBy='familyName', viewType='domain_public'
        ).execute(num_retries=10)

        for r in results["users"]:
            user_list.append(r)

        page_token = results.get('nextPageToken')
        if not page_token:
            break

    for user in user_list:
        pmail = user.get('primaryEmail')
        if pmail:
            aliases = service.users().aliases().list(userKey=pmail).execute(num_retries=10)
            if aliases and aliases.get('aliases'):
                for alias in aliases.get('aliases'):
                    if alias.get('alias'):
                        print '{}|{}|{}|{}'.format(
                            user.get('name').get('familyName'),
                            user.get('name').get('givenName'),
                            user.get('primaryEmail'), alias.get('alias')
                        )
def main():
    """
    main function
    """

    credentials = get_cred(email, "calendar")
    http = httplib2.Http()
    http = credentials.authorize(http)

    service = build("calendar", "v3", http=http)

    page_token = None
    while True:
        calendar_list = service.calendarList().list(pageToken=page_token).execute()
        for calendar_list_entry in calendar_list['items']:
            print calendar_list_entry['summary']
            print calendar_list_entry['accessRole']
            print calendar_list_entry['id']
        page_token = calendar_list.get('nextPageToken')
        if not page_token:
            break
def main():
    """
    main function
    """

    global email

    # space separated list of authorized API scopes for this service account
    scope = 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/'
    # create our email settings client
    client = gdata.apps.emailsettings.client.EmailSettingsClient(
        domain=email.split('@')[1]
    )
    # obtain our street cred
    credentials = get_cred(email, scope)
    # fetch our access token
    auth2token = OAuth2TokenFromCredentials(credentials)
    # authorize our client
    auth2token.authorize(client)

    forwarding = client.RetrieveForwarding(username=username)
    print forwarding
def main():
    """
    main function
    """

    credentials = get_cred(email, "calendar")
    http = httplib2.Http()
    http = credentials.authorize(http)

    service = build("calendar", "v3", http=http)

    page_token = None
    while True:
        calendar_list = service.calendarList().list(
            pageToken=page_token).execute()
        for calendar_list_entry in calendar_list['items']:
            print('summary{0}'.format(calendar_list_entry['summary']))
            print('accessRole{0}'.format(calendar_list_entry['accessRole']))
            print('id{0}'.format(calendar_list_entry['id']))
        page_token = calendar_list.get('nextPageToken')
        if not page_token:
            break
Example #21
0
def main():
    """
    main function
    """

    credentials = get_cred(EMAIL, "admin.directory.user")
    http = httplib2.Http()

    service = build("admin", "directory_v1", http=credentials.authorize(http))

    user_list = []
    page_token = None
    while True:
        results = service.users().list(
            domain=EMAIL.split('@')[1],
            maxResults=100,
            pageToken=page_token,
            orderBy='familyName',
            viewType='domain_public').execute(num_retries=10)

        for r in results["users"]:
            user_list.append(r)

        page_token = results.get('nextPageToken')
        if not page_token:
            break

    for user in user_list:
        pmail = user.get('primaryEmail')
        if pmail:
            aliases = service.users().aliases().list(userKey=pmail).execute(
                num_retries=10)
            if aliases and aliases.get('aliases'):
                for alias in aliases.get('aliases'):
                    if alias.get('alias'):
                        print('{}|{}|{}|{}'.format(
                            user.get('name').get('familyName'),
                            user.get('name').get('givenName'),
                            user.get('primaryEmail'), alias.get('alias')))
Example #22
0
def main():
    """
    Cycle through the users, obtain the user's calendar list, check
    for the calendar
    """

    sql = '{} ORDER BY id_rec.lastname, id_rec.firstname'.format(FACULTY_ALPHA)
    user_list = do_sql(sql, key=settings.INFORMIX_DEBUG, earl=EARL)
    cal_dict = {'id': cid, "hidden": "False"}
    fails = []
    exists = []
    inserts = 1
    credentials = get_cred(email, "calendar")
    http = httplib2.Http()
    credentials.authorize(http)

    for user in user_list:
        email = user["email"]
        print email
        try:
            service = build("calendar", "v3", http=http)
            try:
                c = service.calendarList().get(calendarId=cid).execute()
                print "calendar already exists."
                #service.calendarList().delete(calendarId=cid).execute()
                exists.append(email)
            except:
                print "insert calendar"
                if not test:
                    service.calendarList().insert(body=cal_dict).execute()
                inserts += 1
        except:
            print "{} is not a valid email".format(email)
            fails.append(email)

    print "Total number of users: {}".format(len(user_list))
    print "Inserts = {}".format(inserts)
    print "Already exists ({}) = {}".format(len(exists), exists)
    print "Failures = {}".format(fails)
Example #23
0
def main():
    """Main function."""
    credentials = get_cred(EMAIL, 'admin.directory.user')
    http = httplib2.Http()

    service = build('admin', 'directory_v1', http=credentials.authorize(http))

    user_list = []
    page_token = None
    while True:
        users = service.users().list(
            domain=EMAIL.split('@')[1],
            maxResults=100,
            pageToken=page_token,
            orderBy='familyName',
            #viewType='domain_public',
            viewType='admin_view',  # default
        ).execute(num_retries=10)

        for user in users['users']:
            user_list.append(user)

        page_token = users.get('nextPageToken')
        if not page_token:
            break

    print('email|suspended|name|directory')
    for user in user_list:
        if user.get('suspended') and user.get('includeInGlobalAddressList'):
        #if not user.get('includeInGlobalAddressList'):
            #print('{0}|{1}|{2}|{3}'.format(
            print('{0}|{1}|{2}'.format(
                user.get('primaryEmail'),
                #user.get('suspended'),
                user.get('name')['familyName'],
                user.get('name')['givenName'],
                #user.get('includeInGlobalAddressList'),
            ))
Example #24
0
def main():
    """
    Cycle through the users, obtain the user's calendar list, check
    for the calendar
    """

    user_list = do_sql(FACULTY_ALPHA,key=settings.INFORMIX_DEBUG,earl=EARL)
    cal_dict = { 'id': cid, "hidden": "False" }
    fails = []
    exists = []
    inserts = 1
    credentials = get_cred(email, "calendar")
    http = httplib2.Http()
    credentials.authorize(http)

    for user in user_list:
        email = user["email"]
        print email
        try:
            service = build("calendar", "v3", http=http)
            try:
                c = service.calendarList().get(calendarId=cid).execute()
                print "calendar already exists."
                #service.calendarList().delete(calendarId=cid).execute()
                exists.append(email)
            except:
                print "insert calendar"
                if not test:
                    service.calendarList().insert(body=cal_dict).execute()
                inserts += 1
        except:
            print "{} is not a valid email".format(email)
            fails.append(email)

    print "Total number of users: {}".format(len(user_list))
    print "Inserts = {}".format(inserts)
    print "Already exists ({}) = {}".format(len(exists), exists)
    print "Failures = {}".format(fails)
def main():
    """
    main function
    """

    global email

    # space separated list of authorized API scopes for this service account
    scope = 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/'
    # create our email settings client
    client = EmailSettingsClient(domain=email.split('@')[1])
    # obtain our street cred
    credentials = get_cred(email, scope)
    # fetch our access token
    auth2token = OAuth2TokenFromCredentials(credentials)
    # authorize our client
    auth2token.authorize(client)

    forwarding = client.RetrieveForwarding(username=username)

    #print forwarding
    #print forwarding.__dict__
    print forwarding.property[1].value
Example #26
0
def main():
    """
    main function
    """

    global description

    scope = 'https://www.googleapis.com/auth/drive '
    scope += 'https://spreadsheets.google.com/feeds'

    credentials = get_cred(email, scope, settings.SERVICE_ACCOUNT_JSON)

    http = httplib2.Http()
    credentials.authorize(http)

    service = build("drive", "v2", http=http)

    gc = gspread.authorize(credentials)

    try:
        wks = gc.open(filename).sheet1
        print "opened existing file: {}".format(filename)
    except:
        if not description:
            description = "{}: File created from API".format(filename),
        body = {
            'title': filename,
            'description': description,
            'mimeType': "application/vnd.google-apps.spreadsheet"
        }

        # Create a new blank Google Spreadsheet file in user's Google Drive
        google_spreadsheet = service.files().insert(body=body).execute()

        #wks = gc.open(filename).sheet1
        print "newly created file: {}".format(filename)
def main():
    """
    main function
    """

    global description

    scope = 'https://www.googleapis.com/auth/drive '
    scope += 'https://spreadsheets.google.com/feeds'

    credentials = get_cred(email, scope, settings.SERVICE_ACCOUNT_JSON)

    http = httplib2.Http()
    credentials.authorize(http)

    service = build( "drive", "v2", http=http )

    gc = gspread.authorize(credentials)

    try:
        wks = gc.open(filename).sheet1
        print "opened existing file: {}".format(filename)
    except:
        if not description:
            description = "{}: File created from API".format(filename),
        body = {
            'title': filename,
            'description': description,
            'mimeType': "application/vnd.google-apps.spreadsheet"
        }

        # Create a new blank Google Spreadsheet file in user's Google Drive
        google_spreadsheet = service.files().insert(body=body).execute()

        #wks = gc.open(filename).sheet1
        print "newly created file: {}".format(filename)
Example #28
0
 def __init__(self):
     # scope
     scope =  'https://www.googleapis.com/auth/admin.directory.group '
     scope +=  'https://www.googleapis.com/auth/admin.directory.user '
     # obtain the admin directory service account cred
     self.cred = get_cred(settings.DOMAIN_SUPER_USER_EMAIL, scope)
def main():
    """
    main function
    """

    global username
    global email
    global client

    if username:

        scope = 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/'
        credentials = get_cred(email, scope)

        auth2token = OAuth2TokenFromCredentials(credentials)

        # create our email settings client
        client = EmailSettingsClient( domain=email.split('@')[1])
        auth2token.authorize(client)

        forwarding = client.RetrieveForwarding(username=username)

        #print forwarding
        #print forwarding.__dict__
        print forwarding.property[1].value
    else:
        # storage for credentials
        storage = Storage(settings.STORAGE_FILE)
        # create an http client
        http = httplib2.Http()
        # email settings scope
        scope = 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/'

        # obtain the admin directory user cred
        users_cred = storage.get()
        if users_cred is None or users_cred.invalid:
            users_cred = get_cred(email, "admin.directory.user")
            storage.put(users_cred)
        else:
            users_cred.refresh(http)

        # build the service connection
        service = build(
            "admin", "directory_v1", http = users_cred.authorize(http)
        )

        # fetch all of our users and put the results into a list
        user_list = []
        # intialize page_token
        page_token = None
        while True:
            results = service.users().list(
                domain=email.split('@')[1],
                maxResults=500,
                pageToken=page_token,
                orderBy='familyName', viewType='domain_public'
            ).execute()

            page_token = results.get('nextPageToken')
            user_list.append(results)
            if not page_token:
                break

        print "length of user_list: {}".format(len(user_list))

        # we cycle through all of the users and fetch their
        # email settings, looking for the forwardTo key
        for users in user_list:

            for user in users["users"]:
                pmail = user["primaryEmail"]
                username = pmail.split('@')[0]
                given_name = user['name']['givenName']
                family_name = user['name']['familyName']
                # create our email settings client
                client = EmailSettingsClient(domain=email.split('@')[1])
                # obtain street cred
                credentials = get_cred(email, scope)
                auth2token = OAuth2TokenFromCredentials(credentials)
                auth2token.authorize(client)

                try:
                    forwarding = client.RetrieveForwarding(username=username)
                    if forwarding.property[1].value:
                        print "{}|{}|{}|{}".format(
                            family_name, given_name, pmail,
                            forwarding.property[1].value
                        )
                except Exception, e:
                    logger.debug("{}|{}|{}|{}".format(
                        family_name, given_name, pmail,
                        str(e)
                    ))
Example #30
0
def main():
    """
    main function
    """

    global username
    global email
    global client

    if username:

        scope = 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/'
        credentials = get_cred(email, scope)

        auth2token = OAuth2TokenFromCredentials(credentials)

        # create our email settings client
        client = EmailSettingsClient(domain=email.split('@')[1])
        auth2token.authorize(client)

        forwarding = client.RetrieveForwarding(username=username)

        #print forwarding
        #print forwarding.__dict__
        print forwarding.property[1].value
    else:
        # storage for credentials
        storage = Storage(settings.STORAGE_FILE)
        # create an http client
        http = httplib2.Http()
        # email settings scope
        scope = 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/'

        # obtain the admin directory user cred
        users_cred = storage.get()
        if users_cred is None or users_cred.invalid:
            users_cred = get_cred(email, "admin.directory.user")
            storage.put(users_cred)
        else:
            users_cred.refresh(http)

        # build the service connection
        service = build("admin",
                        "directory_v1",
                        http=users_cred.authorize(http))

        # fetch all of our users and put the results into a list
        user_list = []
        # intialize page_token
        page_token = None
        while True:
            results = service.users().list(domain=email.split('@')[1],
                                           maxResults=500,
                                           pageToken=page_token,
                                           orderBy='familyName',
                                           viewType='domain_public').execute()

            page_token = results.get('nextPageToken')
            user_list.append(results)
            if not page_token:
                break

        print "length of user_list: {}".format(len(user_list))

        # we cycle through all of the users and fetch their
        # email settings, looking for the forwardTo key
        for users in user_list:

            for user in users["users"]:
                pmail = user["primaryEmail"]
                username = pmail.split('@')[0]
                given_name = user['name']['givenName']
                family_name = user['name']['familyName']
                # create our email settings client
                client = EmailSettingsClient(domain=email.split('@')[1])
                # obtain street cred
                credentials = get_cred(email, scope)
                auth2token = OAuth2TokenFromCredentials(credentials)
                auth2token.authorize(client)

                try:
                    forwarding = client.RetrieveForwarding(username=username)
                    if forwarding.property[1].value:
                        print "{}|{}|{}|{}".format(
                            family_name, given_name, pmail,
                            forwarding.property[1].value)
                except Exception, e:
                    logger.debug("{}|{}|{}|{}".format(family_name, given_name,
                                                      pmail, str(e)))
Example #31
0
 def __init__(self):
     # scope
     scope = 'https://www.googleapis.com/auth/apps.groups.settings'
     # obtain the admin directory user cred
     self.cred = get_cred(settings.DOMAIN_SUPER_USER_EMAIL, scope)
Example #32
0
 def __init__(self, scope, cache=True):
     # obtain the reports user cred
     self.cred = get_cred(settings.DOMAIN_SUPER_USER_EMAIL, scope)
     self.cache = cache
 def __init__(self):
     # scope
     scope = 'https://www.googleapis.com/auth/apps.groups.settings'
     # obtain the admin directory user cred
     self.cred = get_cred(settings.DOMAIN_SUPER_USER_EMAIL, scope)
Example #34
0
 def __init__(self):
     # scope
     scope = 'https://www.googleapis.com/auth/admin.directory.group '
     scope += 'https://www.googleapis.com/auth/admin.directory.user '
     # obtain the admin directory service account cred
     self.cred = get_cred(settings.DOMAIN_SUPER_USER_EMAIL, scope)