forked from docusign/code-examples-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathds_client.py
More file actions
145 lines (121 loc) · 4.87 KB
/
Copy pathds_client.py
File metadata and controls
145 lines (121 loc) · 4.87 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import uuid
from os import path
import requests
from flask import current_app as app, url_for, redirect, render_template, request
from flask_oauthlib.client import OAuth
from docusign_esign import ApiClient
from docusign_esign.client.api_exception import ApiException
from ..ds_config import DS_CONFIG, DS_JWT
from ..error_handlers import process_error
class DSClient:
ds_app = None
@classmethod
def _init(cls, auth_type):
if auth_type == "code_grant":
cls._auth_code_grant()
elif auth_type == "jwt":
cls._jwt_auth()
@classmethod
def _auth_code_grant(cls):
"""Authorize with the Authorization Code Grant - OAuth 2.0 flow"""
oauth = OAuth(app)
request_token_params = {
"scope": "signature",
"state": lambda: uuid.uuid4().hex.upper()
}
if not DS_CONFIG["allow_silent_authentication"]:
request_token_params["prompt"] = "login"
cls.ds_app = oauth.remote_app(
"docusign",
consumer_key=DS_CONFIG["ds_client_id"],
consumer_secret=DS_CONFIG["ds_client_secret"],
access_token_url=DS_CONFIG["authorization_server"] + "/oauth/token",
authorize_url=DS_CONFIG["authorization_server"] + "/oauth/auth",
request_token_params=request_token_params,
base_url=None,
request_token_url=None,
access_token_method="POST"
)
@classmethod
def _jwt_auth(cls):
"""JSON Web Token authorization"""
api_client = ApiClient()
api_client.set_base_path(DS_JWT["authorization_server"])
# Catch IO error
try:
private_key = cls._get_private_key().encode("ascii").decode("utf-8")
except (OSError, IOError) as err:
return render_template(
"error.html",
err=err
)
try:
cls.ds_app = api_client.request_jwt_user_token(
client_id=DS_JWT["ds_client_id"],
user_id=DS_JWT["ds_impersonated_user_id"],
oauth_host_name=DS_JWT["authorization_server"],
private_key_bytes=private_key,
expires_in=3600
)
return redirect(url_for("ds.ds_callback"))
except ApiException as err:
body = err.body.decode('utf8')
# Grand explicit consent for the application
if "consent_required" in body:
consent_scopes = "signature%20impersonation"
redirect_uri = DS_CONFIG["app_url"] + url_for("ds.ds_callback")
consent_url = f"{DS_CONFIG['authorization_server']}/oauth/auth?response_type=code&" \
f"scope={consent_scopes}&client_id={DS_JWT['ds_client_id']}&redirect_uri={redirect_uri}"
return redirect(consent_url)
else:
process_error(err)
@classmethod
def destroy(cls):
cls.ds_app = None
@staticmethod
def _get_private_key():
"""
Check that the private key present in the file and if it is, get it from the file.
In the opposite way get it from config variable.
"""
private_key_file = path.abspath(DS_JWT["private_key_file"])
if path.isfile(private_key_file):
with open(private_key_file) as private_key_file:
private_key = private_key_file.read()
else:
private_key = DS_JWT["private_key_file"]
return private_key
@classmethod
def login(cls, auth_type):
if auth_type == "code_grant":
return cls.get(auth_type).authorize(callback=url_for("ds.ds_callback", _external=True))
elif auth_type == "jwt":
return cls._jwt_auth()
@classmethod
def get_token(cls, auth_type):
resp = None
if auth_type == "code_grant":
resp = cls.get(auth_type).authorized_response()
elif auth_type == "jwt":
resp = cls.get(auth_type).to_dict()
if resp is None or resp.get("access_token") is None:
return "Access denied: reason=%s error=%s resp=%s" % (
request.args["error"],
request.args["error_description"],
resp
)
return resp
@classmethod
def get_user(cls, access_token):
"""Make request to the API to get the user information"""
# Determine user, account_id, base_url by calling OAuth::getUserInfo
# See https://developers.docusign.com/esign-rest-api/guides/authentication/user-info-endpoints
url = DS_CONFIG["authorization_server"] + "/oauth/userinfo"
auth = {"Authorization": "Bearer " + access_token}
response = requests.get(url, headers=auth).json()
return response
@classmethod
def get(cls, auth_type):
if not cls.ds_app:
cls._init(auth_type)
return cls.ds_app