Skip to content

Admin/dev #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from .rooms import examples as rooms_examples
from .click import examples as click_examples
from .monitor import examples as monitor_examples
from .admin import examples as admin_examples
from .views import core

session_path = "/tmp/python_recipe_sessions"
Expand All @@ -20,6 +21,8 @@
app = Flask(__name__, template_folder="click/templates")
elif EXAMPLES_API_TYPE["Monitor"]:
app = Flask(__name__, template_folder="monitor/templates")
elif EXAMPLES_API_TYPE["Admin"]:
app = Flask(__name__, template_folder="admin/templates")
else:
app = Flask(__name__)
app.config.from_pyfile("config.py")
Expand Down Expand Up @@ -59,6 +62,12 @@
app.register_blueprint(click_examples.eg003)
app.register_blueprint(click_examples.eg004)
app.register_blueprint(click_examples.eg005)

elif EXAMPLES_API_TYPE["Admin"]:
app.register_blueprint(admin_examples.eg001)
app.register_blueprint(admin_examples.eg002)
app.register_blueprint(admin_examples.eg003)

else:
app.register_blueprint(examples.eg001)
app.register_blueprint(examples.eg002)
Expand Down
1 change: 1 addition & 0 deletions app/admin/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .utils import create_admin_api_client
3 changes: 3 additions & 0 deletions app/admin/examples/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .eg001_create_a_new_user import eg001
from .eg002_bulk_export_user_data import eg002
from .eg003_add_users_via_bulk_import import eg003
1 change: 1 addition & 0 deletions app/admin/examples/eg001_create_a_new_user/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .views import eg001
70 changes: 70 additions & 0 deletions app/admin/examples/eg001_create_a_new_user/controller.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
from docusign_admin.apis import UsersApi
from flask import session

from app.admin.utils import create_admin_api_client
from app.consts import pattern
from app.ds_config import DS_CONFIG


class Eg001Controller:

@staticmethod
def get_args(request):
"""
Get request and session arguments
"""

return {
'first_name': pattern.sub("", request.form.get("first_name")),
'last_name': pattern.sub("", request.form.get("last_name")),
'user_email': pattern.sub("", request.form.get("user_email")),
'profile_id': pattern.sub("", request.form.get("profile_id")),
'group_id': pattern.sub("", request.form.get("group_id")),
'activate_membership': bool(request.form.get("activate_membership"))
}

@staticmethod
def worker(args):
"""
1. Create the API client object
2. Create the user API request object
3. Create a request body for the create_user method
4. Creates a user using a method from the user API
"""

# 1. Create the API client object
api_client = create_admin_api_client(
access_token=session["ds_access_token"]
)

# 2. Create the user API request object
user_api = UsersApi(api_client=api_client)

# 3. Create a request body for the create_user method
request_body = {
"user_name": f"{args['first_name']} {args['last_name']}",
"first_name": args['first_name'],
"last_name": args['last_name'],
"email": args['user_email'],
"auto_activate_memberships": args['activate_membership'],
"accounts": [
{
"id": session["ds_account_id"],
"permission_profile": {
"id": args['profile_id'],
},
"groups": [
{
"id": args['group_id'],
}
]
}
]
}

# 4. Creates a user using a method from the user API
response = user_api.create_user(
DS_CONFIG["organization_id"],
request_body
)
return response
61 changes: 61 additions & 0 deletions app/admin/examples/eg001_create_a_new_user/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Example 001: Create a new user"""

import json
from os import path

from flask import Blueprint, render_template, request, current_app
from docusign_admin.client.api_exception import ApiException

from app.error_handlers import process_error
from app.docusign import authenticate
from app.ds_config import DS_CONFIG

from .controller import Eg001Controller

eg = "eg001" # Reference (and URL) for this example
eg001 = Blueprint(eg, __name__)

@eg001.route("/eg001", methods=["POST"])
@authenticate(eg=eg)
def get_user_data():
"""
1. Get required arguments
2. Call the worker method
3. Render the response
"""

# 1. Get required arguments
args = Eg001Controller.get_args(request)

# 2. Call the worker method
try:
results = Eg001Controller.worker(args)
current_app.logger.info(f"ID of the created user: {results.id}")
except ApiException as err:
return process_error(err)

# 3. Render the response
return render_template(
"example_done.html",
title="Create a new user",
h1="Result of creating a new user",
message="Results from Users:createUser method:",
json=json.dumps(json.dumps(results.to_dict(), default=str))
)

@eg001.route("/eg001", methods=["GET"])
@authenticate(eg=eg)
def get_view():
"""
Responds with the form for the example
"""

# Render the response
return render_template(
"eg001_create_a_new_user.html",
title="Create a new user",
source_file=path.basename(path.dirname(__file__)) + "/controller.py",
source_url=DS_CONFIG["admin_github_url"] + path.basename(
path.dirname(__file__)) + "/controller.py",
documentation=DS_CONFIG["documentation"] + eg,
)
1 change: 1 addition & 0 deletions app/admin/examples/eg002_bulk_export_user_data/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .views import eg002
94 changes: 94 additions & 0 deletions app/admin/examples/eg002_bulk_export_user_data/controller.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
from docusign_admin import ApiClient
from docusign_admin.apis import BulkExportsApi
from flask import session

from app.admin.utils import create_admin_api_client
from app.ds_config import DS_CONFIG


class Eg002Controller:

@staticmethod
def _get_export_api():
"""
1. Create the API client object
2. Return the bulk exports API Object
"""

# 1. Create the API client object
api_client = create_admin_api_client(
access_token=session["ds_access_token"]
)

# 2. Return the bulk exports API Object
return BulkExportsApi(api_client=api_client)

@classmethod
def worker(cls):
"""
1. Create the export API object
2. Create a user list export request
3. Save user_list_export_id in a client session
4. Returns a list of pending and completed export requests
"""

# 1. Create the export API object
export_api = cls._get_export_api()

# 2. Create a user list export request
response = export_api.create_user_list_export(
DS_CONFIG["organization_id"],
{
"type": "organization_memberships_export"
}
)

# 3. Save user_list_export_id in a client session
session['user_list_export_id'] = response.id

# 4. Returns a list of pending and completed export requests
return response

@classmethod
def get_csv_user_list(cls):
"""
Getting the csv file of the current list of users:
1. Create the export API object
2. Getting the user list export response
3. Trying to get the user list export id
4. Create the API client object
5. Add headers to the API client object and the desired URL
6. Getting a response containing a csv file
7. Returns the csv file
"""

# 1. Create the export API object
export_api = cls._get_export_api()

# 2. Getting the user list export response
response = export_api.get_user_list_export(
DS_CONFIG["organization_id"],
session['user_list_export_id']
)

# 3. Trying to get the user list export id
try:
obj_id = response.results[0].id
except TypeError:
return None

# 4. Create the API client object
api_client = ApiClient()

# 5. Add headers to the API client object and the desired URL
headers = {"Authorization": "Bearer " + session["ds_access_token"]}
url = (
"https://demo.docusign.net/restapi/v2/organization_exports/"
f"{DS_CONFIG['organization_id']}/user_list/{obj_id}"
)

# 6. Getting a response containing a csv file
response = api_client.request("GET", url, headers=headers)

# 7. Returns the csv file
return response.data.decode("UTF8")
104 changes: 104 additions & 0 deletions app/admin/examples/eg002_bulk_export_user_data/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""Example 002: Bulk export user data"""

import json
from os import path

from flask import Blueprint, render_template, Response, current_app
from docusign_admin.client.api_exception import ApiException

from app.error_handlers import process_error
from app.docusign import authenticate
from app.ds_config import DS_CONFIG
from .controller import Eg002Controller


eg = "eg002" # Reference (and URL) for this example
eg002 = Blueprint(eg, __name__)

@eg002.route("/eg002", methods=["POST"])
@authenticate(eg=eg)
def get_user_list_data():
"""
1. Call the worker method
2. Render the response
"""

# 1. Call the worker method
try:
results = Eg002Controller.worker()
current_app.logger.info(f"User list export ID: {results.id}")
except ApiException as err:
return process_error(err)

# 2. Render the response
return render_template(
"example_done.html",
get_csv=True,
title="Bulk export user data",
h1="Result of creating a bulk export user data",
message="Results from UserExport:createUserListExport:",
json=json.dumps(json.dumps(results.to_dict(), default=str))
)

@eg002.route("/eg002", methods=["GET"])
@authenticate(eg=eg)
def get_view():
"""
Responds with the form for the example
"""

# Render the response
return render_template(
"eg002_bulk_export_user_data.html",
title="Bulk export user data",
source_file=path.basename(path.dirname(__file__)) + "/controller.py",
source_url=(
DS_CONFIG["admin_github_url"] +
path.basename(path.dirname(__file__)) + "/controller.py"
),
documentation=DS_CONFIG["documentation"] + eg,
)

@eg002.route("/eg002check", methods=["GET"])
@authenticate(eg=eg)
def check_if_csv_ready():
"""
1. Checking if a CSV file exists
2. Render the response
"""

# 1. Checking if a CSV file exists
try:
csv_file = Eg002Controller.get_csv_user_list()
except ApiException as err:
return process_error(err)

# 2. Render the response
return render_template(
"eg002_file_state.html",
get_csv=bool(csv_file)
)

@eg002.route("/eg002csv", methods=["GET"])
@authenticate(eg=eg)
def get_csv():
"""
1. Getting an existing CSV file
2. Returns the finished csv file to the user
"""

# 1. Getting an existing CSV file
try:
csv_file = Eg002Controller.get_csv_user_list()
except ApiException as err:
return process_error(err)

# 2. Returns the finished csv file to the user
return Response(
csv_file,
mimetype="text/csv",
headers={
"Content-disposition":"attachment; filename=user_list.csv"
}
)

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .views import eg003
Loading