Skip to content

Commit

Permalink
Re-organize examples into subfolders based on Duo APIs (#248)
Browse files Browse the repository at this point in the history
* doc: add report_user_by_email.py to examples

* feat: add get_user_by_email() method to admin.py
doc: add report_user_by_email.py to examples

* Revert "feat: add get_user_by_email() method to admin.py"

This reverts commit 48580c1.

* feat: add get_user_by_email() method to admin.py
doc: add report_user_by_email.py to examples

* doc: update report_user_by_email.py example to use get_user_by_email() method instead of generic json_api_call() method.

* chore: reorganize examples into client specific folders and add Auth API examples for user authentication

* chore: reorganize examples into client specific folders. add Auth API examples for user authentication and Accounts API examples for managing child accounts

* chore: remove obsolete reort_user_by_email.py example

* refactor: organize examples into client specific folders. add new examples for Accounts and Auth APIs

* Revert "chore: remove obsolete reort_user_by_email.py example"

This reverts commit 6294f16.

* Revert "refactor: organize examples into client specific folders. add new examples for Accounts and Auth APIs"

This reverts commit abde747.

* doc: add README.md files for each example folder

* doc: add Accounts API get/set edition examples

* chore: move get_billing_and_telephony_credits.py from examples/Admin to examples/Accounts

* chore: clean up path locations in examples README files

* chore: clean up path locations in examples

* chore: remove duplicate files in examples

* chore: add README.md for examples

* docs: add get_users_in_group_with_aliases.py to examples/Admin
  • Loading branch information
MarkTripod-Duo authored Feb 14, 2024
1 parent d4c011a commit 653a103
Show file tree
Hide file tree
Showing 29 changed files with 1,619 additions and 146 deletions.
30 changes: 30 additions & 0 deletions examples/Accounts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Duo Accounts API Examples Overview


## Examples

This folder contains various examples to illustrate the usage of the `Accounts` module within the
`duo_client_python` library. The Duo Accounts API is primarily intended for use by Managed Service
Partners (MSP) to assist in the automation of managing their child (customer) Duo accounts.

Use of the Duo Accounts API requires special access to be enabled. Please see the
[online documentation](https://www.duosecurity.com/docs/accountsapi) for more information.

# Using

To run an example query, execute a command like the following from the repo root:
```python
$ python3 examples/Accounts/get_billing_and_telephony_credits.py
```

Or, from within this folder:
```python
$ python3 get_billing_and_telephony_credits.py
```

# Tested Against Python Versions
* 3.7
* 3.8
* 3.9
* 3.10
* 3.11
63 changes: 63 additions & 0 deletions examples/Accounts/create_child_account.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""
Example of Duo Accounts API child account creation
"""

import duo_client
import os
import sys
import getpass

from pprint import pprint


argv_iter = iter(sys.argv[1:])


def _get_next_arg(prompt, secure=False):
"""Read information from STDIN, using getpass when sensitive information should not be echoed to tty"""
try:
return next(argv_iter)
except StopIteration:
if secure is True:
return getpass.getpass(prompt)
else:
return input(prompt)


def prompt_for_credentials() -> dict:
"""Collect required API credentials from command line prompts
:return: dictionary containing Duo Accounts API ikey, skey and hostname strings
"""

ikey = _get_next_arg('Duo Accounts API integration key ("DI..."): ')
skey = _get_next_arg('Duo Accounts API integration secret key: ', secure=True)
host = _get_next_arg('Duo Accounts API hostname ("api-....duosecurity.com"): ')
account_name = _get_next_arg('Name for new child account: ')

return {"IKEY": ikey, "SKEY": skey, "APIHOST": host, "ACCOUNT_NAME": account_name}


def main():
"""Main program entry point"""

inputs = prompt_for_credentials()

account_client = duo_client.Accounts(
ikey=inputs['IKEY'],
skey=inputs['SKEY'],
host=inputs['APIHOST']
)

print(f"Creating child account with name [{inputs['ACCOUNT_NAME']}]")
child_account = account_client.create_account(inputs['ACCOUNT_NAME'])

if 'account_id' in child_account:
print(f"Child account for [{inputs['ACCOUNT_NAME']}] created successfully.")
else:
print(f"An unexpected error occurred while creating child account for {inputs['ACCOUNT_NAME']}")
print(child_account)


if __name__ == '__main__':
main()
70 changes: 70 additions & 0 deletions examples/Accounts/delete_child_account.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""
Example of Duo Accounts API child account deletiom
"""

import duo_client
import os
import sys
import getpass

from pprint import pprint


argv_iter = iter(sys.argv[1:])


def _get_next_arg(prompt, secure=False):
"""Read information from STDIN, using getpass when sensitive information should not be echoed to tty"""
try:
return next(argv_iter)
except StopIteration:
if secure is True:
return getpass.getpass(prompt)
else:
return input(prompt)


def prompt_for_credentials() -> dict:
"""Collect required API credentials from command line prompts
:return: dictionary containing Duo Accounts API ikey, skey and hostname strings
"""

ikey = _get_next_arg('Duo Accounts API integration key ("DI..."): ')
skey = _get_next_arg('Duo Accounts API integration secret key: ', secure=True)
host = _get_next_arg('Duo Accounts API hostname ("api-....duosecurity.com"): ')
account_id = _get_next_arg('ID of child account to delete: ')

return {"IKEY": ikey, "SKEY": skey, "APIHOST": host, "ACCOUNT_ID": account_id}


def main():
"""Main program entry point"""

inputs = prompt_for_credentials()

account_client = duo_client.Accounts(
ikey=inputs['IKEY'],
skey=inputs['SKEY'],
host=inputs['APIHOST']
)

account_name = None
child_account_list = account_client.get_child_accounts()
for account in child_account_list:
if account['account_id'] == inputs['ACCOUNT_ID']:
account_name = account['name']
if account_name is None:
print(f"Unable to find account with ID [{inputs['ACCOUNT_ID']}]")
sys.exit()

print(f"Deleting child account with name [{account_name}]")
deleted_account = account_client.delete_account(inputs['ACCOUNT_ID'])
if deleted_account == '':
print(f"Account {inputs['ACCOUNT_ID']} was deleted successfully.")
else:
print(f"An unexpected error occurred while deleting account [{account_name}: {deleted_account}]")


if __name__ == '__main__':
main()
57 changes: 57 additions & 0 deletions examples/Accounts/get_account_edition.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""
Example of Duo Accounts API get child account edition
"""

import duo_client
import getpass

DUO_EDITIONS = {
"ENTERPRISE": "Duo Essentials",
"PLATFORM": "Duo Advantage",
"BEYOND": "Duo Premier",
"PERSONAL": "Duo Free"
}

def _get_user_input(prompt, secure=False):
"""Read information from STDIN, using getpass when sensitive information should not be echoed to tty"""
if secure is True:
return getpass.getpass(prompt)
else:
return input(prompt)


def prompt_for_credentials() -> dict:
"""Collect required API credentials from command line prompts"""

ikey = _get_user_input('Duo Accounts API integration key ("DI..."): ')
skey = _get_user_input('Duo Accounts API integration secret key: ', secure=True)
host = _get_user_input('Duo Accounts API hostname ("api-....duosecurity.com"): ')
account_id = _get_user_input('Child account ID: ')

return {
"ikey": ikey,
"skey": skey,
"host": host,
"account_id": account_id,
}


def main():
"""Main program entry point"""

inputs = prompt_for_credentials()

account_admin_api = duo_client.admin.AccountAdmin(**inputs)

print(f"Getting edition for account ID {inputs['account_id']}...")
result = account_admin_api.get_edition()
if 'edition' not in result:
print(f"An error occurred while getting edition for account {inputs['account_id']}")
print(f"Error message: {result}")
else:
print(f"The current Duo Edition for account {inputs['account_id']} is '{result['edition']}' " +
f"[{DUO_EDITIONS[result['edition']]}]")


if __name__ == '__main__':
main()
79 changes: 79 additions & 0 deletions examples/Accounts/get_billing_and_telephony_credits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
import sys

import duo_client
from six.moves import input

EDITIONS = {
"ENTERPRISE": "Duo Essentials",
"PLATFORM": "Duo Advantage",
"BEYOND": "Duo Premier",
"PERSONAL": "Duo Free"
}

def get_next_input(prompt):
try:
return next(iter(sys.argv[1:]))
except StopIteration:
return input(prompt)


def main():
"""Program entry point"""
ikey=get_next_input('Accounts API integration key ("DI..."): ')
skey=get_next_input('Accounts API integration secret key: ')
host=get_next_input('Accounts API hostname ("api-....duosecurity.com"): ')

# Configuration and information about objects to create.
accounts_api = duo_client.Accounts(
ikey=ikey,
skey=skey,
host=host,
)

kwargs = {
'ikey': ikey,
'skey': skey,
'host': host,
}

# Get all child accounts
child_accounts = accounts_api.get_child_accounts()

for child_account in child_accounts:
# Create AccountAdmin with child account_id, child api_hostname and kwargs consisting of ikey, skey, and host
account_admin_api = duo_client.admin.AccountAdmin(
child_account['account_id'],
child_api_host = child_account['api_hostname'],
**kwargs,
)
try:
# Get edition of child account
child_account_edition = account_admin_api.get_edition()
print(f"Edition for child account {child_account['name']}: {child_account_edition['edition']}")
except RuntimeError as err:
# The account might not have access to get billing information
if "Received 403 Access forbidden" == str(err):
print("{error}: No access for billing feature".format(error=err))
else:
print(err)

try:
# Get telephony credits of child account
child_telephony_credits = account_admin_api.get_telephony_credits()
print("Telephony credits for child account {name}: {edition}".format(
name=child_account['name'],
edition=child_telephony_credits['credits'])
)
except RuntimeError as err:
# The account might not have access to get telephony credits
if "Received 403 Access forbidden" == str(err):
print("{error}: No access for telephony feature".format(error=err))
else:
print(err)


if __name__ == "__main__":
main()
64 changes: 64 additions & 0 deletions examples/Accounts/retrieve_account_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""
Example of Duo account API uaer accountentication with synchronous request/response
"""

import duo_client
import os
import sys
import getpass

from pprint import pprint


argv_iter = iter(sys.argv[1:])


def _get_next_arg(prompt, secure=False):
"""Read information from STDIN, using getpass when sensitive information should not be echoed to tty"""
try:
return next(argv_iter)
except StopIteration:
if secure is True:
return getpass.getpass(prompt)
else:
return input(prompt)


def prompt_for_credentials() -> dict:
"""Collect required API credentials from command line prompts
:return: dictionary containing Duo Accounts API ikey, skey and hostname strings
"""

ikey = _get_next_arg('Duo Accounts API integration key ("DI..."): ')
skey = _get_next_arg('Duo Accounts API integration secret key: ', secure=True)
host = _get_next_arg('Duo Accounts API hostname ("api-....duosecurity.com"): ')

return {"IKEY": ikey, "SKEY": skey, "APIHOST": host}


def main():
"""Main program entry point"""

inputs = prompt_for_credentials()

account_client = duo_client.Accounts(
ikey=inputs['IKEY'],
skey=inputs['SKEY'],
host=inputs['APIHOST']
)

child_accounts = account_client.get_child_accounts()

if isinstance(child_accounts, list):
# Expected list of child accounts returned
for child_account in child_accounts:
print(child_account)

if isinstance(child_accounts, dict):
# Non-successful response returned
print(child_accounts)


if __name__ == '__main__':
main()
Loading

0 comments on commit 653a103

Please sign in to comment.