Commit 71407536 authored by Volkov Gherman's avatar Volkov Gherman

Merge branch 'develop' into 'master'

Develop

See merge request !5
parents 630b2226 d82b403c
venv
\ No newline at end of file
POSTGRES_USER='databse user'
POSTGRES_PASSWORD='database password'
POSTGRES_DB='database name'
\ No newline at end of file
SECRET_KEY='django secret key'
DATABASE_NAME='your database name'
DATABASE_USER='your database owner'
DATABASE_PASSWORD='your database password'
DATABASE_HOST='your database host'
DATABASE_PORT='your database port'
DOCUSIGN_INTEGRATION_KEY='your integation key'
EMAIL_HOST_USER='host user mail'
EMAIL_HOST_PASSWORD='host user password'
\ No newline at end of file
[flake8]
max-line-length = 100
application-import-names = core
exclude = venv
\ No newline at end of file
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.env.db
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
.DS_Store
private.key
.bash_history
FROM python:3.10
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
COPY requirements /app/requirements
RUN pip install --upgrade pip
RUN pip install -r requirements/dev.txt
COPY ./entrypoint.sh /
ENTRYPOINT ["sh", "/entrypoint.sh"]
COPY . .
# DocuSign_test_project
DocuSign signature test integration with python DRF service
\ No newline at end of file
DocuSign signature test integration with python DRF service
Проект подразумевает то, что Вы уже дали согласие на отправку письма на почту.
## Технологии
- [Django](https://docs.djangoproject.com/en/4.2/)
- [Django Rest Framework](https://www.django-rest-framework.org/)
- [Python](https://www.python.org/)
## Использование
Для начала работы приложения нужно:
Вы можете запустить проект двумя разными способами, локально и с помощью контейнера докер
Начнем с запуска приложения локально
Создайте виртуальное окружение с помощью команды:
```sh
$ python3 -m venv venv
```
Активируйте его:
```sh
$ source venv/bin/activate
```
Установите в него все зависимости:
```sh
$ pip install -r requirements/base.txt
```
После этого проведите миграции:
```sh
python3 manage.py migrate
```
Следом запустите сам проект:
```sh
python3 manage.py runserver
```
## Разработка
### Требования
Для установки и запуска проекта, необходим [Python](https://www.python.org/) v3.10+.
- Также добавьте и заполните **.env** файл со своими данными
### Установка зависимостей
Для установки зависимостей, выполните команду:
```sh
$ pip install -r requirements/base.txt
```
### Проведение миграций
После этого проведите миграции:
```sh
python3 manage.py migrate
```
### Запуск Development сервера
Чтобы запустить сервер для разработки, выполните команду:
```sh
python3 manage.py runserver
```
### Запуск Development сервера через Docker
Чтобы запустить сервер для разработки,через Docker выполните команду:
```sh
docker-compose up
```
## Как пользоваться
Переидите по ссылке:
- если запустили локально - http://127.0.0.1:8000
- если запустили через Docker - http://0.0.0.0
Переидя по ссылке заполните форму, после чего проверьте почту по емейлу который Вы указали в форме, Вам должно прийти письмо с ссылкой на
подпись документа, Вам остается только выполнить эти шаги
### Зачем вы разработали этот проект?
Чтобы выполнить пользователи могли подписывать документы онлайн
## To do
- [x] Создание наброска проекта, с шаблонами и подключением к БД
- [x] Интегрировать приложение DocuSign в проект
- [x] Развернуть сервис в Docker
- [x] Добавить крутое README
- [ ] Добавить страницу с отображением статуса пользователю
- [ ] Покрыть приложение тестами
- [ ] Отполировать все до блеска
## Источники
- [DocuSign](https://www.docusign.com/)
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class ApiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'api'
from os import path
import re
demo_docs_path = path.abspath(path.join(path.dirname(path.realpath(__file__)), "static/demo_documents"))
# Pattern for validating signer name and email
pattern = re.compile("([^\w \-\@\.\,])+")
signer_client_id = 1000 # Used to indicate that the signer will use embedded
# signing. Represents the signer"s userId within
# your application.
authentication_method = "None" # How is this application authenticating
minimum_buffer_min = 3
# Template name for create template example
template_name = "Example Signer and CC template v2"
# Name of static doc file
doc_file = "World_Wide_Corp_fields.pdf"
# Name of static pdf file
pdf_file = "World_Wide_Corp_lorem.pdf"
# Base uri for callback function
base_uri_suffix = "/restapi"
# Default languages for brand
languages = {
"Arabic": "ar",
"Armenian": "hy",
"Bahasa Indonesia": "id",
"Bahasa Malay": "ms",
"Bulgarian": "bg",
"Chinese Simplified": "zh_CN",
"Chinese Traditional": "zh_TW",
"Croatian": "hr",
"Czech": "cs",
"Danish": "da",
"Dutch": "nl",
"English UK": "en_GB",
"English US": "en",
"Estonian": "et",
"Farsi": "fa",
"Finnish": "fi",
"French": "fr",
"French Canada": "fr_CA",
"German": "de",
"Greek": "el",
"Hebrew": "he",
"Hindi": "hi",
"Hungarian": "hu",
"Italian": "it",
"Japanese": "ja",
"Korean": "ko",
"Latvian": "lv",
"Lithuanian": "lt",
"Norwegian": "no",
"Polish": "pl",
"Portuguese": "pt",
"Portuguese Brasil": "pt_BR",
"Romanian": "ro",
"Russian": "ru",
"Serbian": "sr",
"Slovak": "sk",
"Slovenian": "sl",
"Spanish": "es",
"Spanish Latin America": "es_MX",
"Swedish": "sv",
"Thai": "th",
"Turkish": "tr",
"Ukrainian": "uk",
"Vietnamese": "vi"
}
# Default settings for updating and creating permissions
settings = {
"useNewDocuSignExperienceInterface": "optional",
"allowBulkSending": "true",
"allowEnvelopeSending": "true",
"allowSignerAttachments": "true",
"allowTaggingInSendAndCorrect": "true",
"allowWetSigningOverride": "true",
"allowedAddressBookAccess": "personalAndShared",
"allowedTemplateAccess": "share",
"enableRecipientViewingNotifications": "true",
"enableSequentialSigningInterface": "true",
"receiveCompletedSelfSignedDocumentsAsEmailLinks": "false",
"signingUiVersion": "v2",
"useNewSendingInterface": "true",
"allowApiAccess": "true",
"allowApiAccessToAccount": "true",
"allowApiSendingOnBehalfOfOthers": "true",
"allowApiSequentialSigning": "true",
"enableApiRequestLogging": "true",
"allowDocuSignDesktopClient": "false",
"allowSendersToSetRecipientEmailLanguage": "true",
"allowVaulting": "false",
"allowedToBeEnvelopeTransferRecipient": "true",
"enableTransactionPointIntegration": "false",
"powerFormRole": "admin",
"vaultingMode": "none"
}
API_TYPE = {
"ESIGNATURE": "eSignature",
"MONITOR": "Monitor",
"CLICK": "Click",
"ROOMS": "Rooms",
"ADMIN": "Admin"
}
import base64
from os import path
from docusign_esign import EnvelopesApi, EnvelopeDefinition, Document, Signer, CarbonCopy, SignHere, \
Tabs, Recipients
from ...consts import demo_docs_path, pattern
from ...jwt_helpers import create_api_client
class Eg002SigningViaEmailController:
@classmethod
def worker(cls, args, doc_docx_path, doc_pdf_path):
"""
1. Create the envelope request object
2. Send the envelope
"""
envelope_args = args["envelope_args"]
# 1. Create the envelope request object
envelope_definition = cls.make_envelope(envelope_args, doc_docx_path, doc_pdf_path)
api_client = create_api_client(base_path=args["base_path"], access_token=args["access_token"])
# 2. call Envelopes::create API method
# Exceptions will be caught by the calling function
envelopes_api = EnvelopesApi(api_client)
results = envelopes_api.create_envelope(account_id=args["account_id"], envelope_definition=envelope_definition)
envelope_id = results.envelope_id
return {"envelope_id": envelope_id}
@classmethod
def make_envelope(cls, args, doc_docx_path, doc_pdf_path):
"""
Creates envelope
Document 1: An HTML document.
Document 2: A Word .docx document.
Document 3: A PDF document.
DocuSign will convert all of the documents to the PDF format.
The recipients" field tags are placed using <b>anchor</b> strings.
"""
# document 1 (html) has sign here anchor tag **signature_1**
# document 2 (docx) has sign here anchor tag /sn1/
# document 3 (pdf) has sign here anchor tag /sn1/
#
# The envelope has two recipients.
# recipient 1 - signer
# recipient 2 - cc
# The envelope will be sent first to the signer.
# After it is signed, a copy is sent to the cc person.
# create the envelope definition
env = EnvelopeDefinition(
email_subject="Please sign this document set"
)
doc1_b64 = base64.b64encode(bytes(cls.create_document1(args), "utf-8")).decode("ascii")
# read files 2 and 3 from a local directory
# The reads could raise an exception if the file is not available!
with open(path.join(demo_docs_path, doc_docx_path), "rb") as file:
doc2_docx_bytes = file.read()
doc2_b64 = base64.b64encode(doc2_docx_bytes).decode("ascii")
with open(path.join(demo_docs_path, doc_pdf_path), "rb") as file:
doc3_pdf_bytes = file.read()
doc3_b64 = base64.b64encode(doc3_pdf_bytes).decode("ascii")
# Create the document models
document1 = Document( # create the DocuSign document object
document_base64=doc1_b64,
name="Order acknowledgement", # can be different from actual file name
file_extension="html", # many different document types are accepted
document_id="1" # a label used to reference the doc
)
document2 = Document( # create the DocuSign document object
document_base64=doc2_b64,
name="Battle Plan", # can be different from actual file name
file_extension="docx", # many different document types are accepted
document_id="2" # a label used to reference the doc
)
document3 = Document( # create the DocuSign document object
document_base64=doc3_b64,
name="Lorem Ipsum", # can be different from actual file name
file_extension="pdf", # many different document types are accepted
document_id="3" # a label used to reference the doc
)
# The order in the docs array determines the order in the envelope
env.documents = [document1, document2, document3]
# Create the signer recipient model
signer1 = Signer(
email=args["signer_email"],
name=args["signer_name"],
recipient_id="1",
routing_order="1"
)
# routingOrder (lower means earlier) determines the order of deliveries
# to the recipients. Parallel routing order is supported by using the
# same integer as the order for two or more recipients.
# create a cc recipient to receive a copy of the documents
cc1 = CarbonCopy(
email=args["cc_email"],
name=args["cc_name"],
recipient_id="2",
routing_order="2"
)
# Create signHere fields (also known as tabs) on the documents,
# We"re using anchor (autoPlace) positioning
#
# The DocuSign platform searches throughout your envelope"s
# documents for matching anchor strings. So the
# signHere2 tab will be used in both document 2 and 3 since they
# use the same anchor string for their "signer 1" tabs.
sign_here1 = SignHere(
anchor_string="**signature_1**",
anchor_units="pixels",
anchor_y_offset="10",
anchor_x_offset="20"
)
sign_here2 = SignHere(
anchor_string="/sn1/",
anchor_units="pixels",
anchor_y_offset="10",
anchor_x_offset="20"
)
# Add the tabs model (including the sign_here tabs) to the signer
# The Tabs object wants arrays of the different field/tab types
signer1.tabs = Tabs(sign_here_tabs=[sign_here1, sign_here2])
# Add the recipients to the envelope object
recipients = Recipients(signers=[signer1], carbon_copies=[cc1])
env.recipients = recipients
# Request that the envelope be sent by setting |status| to "sent".
# To request that the envelope be created as a draft, set to "created"
env.status = args["status"]
return env
@classmethod
def create_document1(cls, args):
""" Creates document 1 -- an html document"""
return f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="font-family:sans-serif;margin-left:2em;">
<h1 style="font-family: "Trebuchet MS", Helvetica, sans-serif;
color: darkblue;margin-bottom: 0;">World Wide Corp</h1>
<h2 style="font-family: "Trebuchet MS", Helvetica, sans-serif;
margin-top: 0px;margin-bottom: 3.5em;font-size: 1em;
color: darkblue;">Order Processing Division</h2>
<h4>Ordered by {args["signer_name"]}</h4>
<p style="margin-top:0em; margin-bottom:0em;">Email: {args["signer_email"]}</p>
<p style="margin-top:0em; margin-bottom:0em;">Copy to: {args["cc_name"]}, {args["cc_email"]}</p>
<p style="margin-top:3em;">
Candy bonbon pastry jujubes lollipop wafer biscuit biscuit. Topping brownie sesame snaps sweet roll pie.
Croissant danish biscuit soufflé caramels jujubes jelly. Dragée danish caramels lemon drops dragée.
Gummi bears cupcake biscuit tiramisu sugar plum pastry. Dragée gummies applicake pudding liquorice.
Donut jujubes oat cake jelly-o.
Dessert bear claw chocolate cake gummies lollipop sugar plum ice cream gummies cheesecake.
</p>
<!-- Note the anchor tag for the signature field is in white. -->
<h3 style="margin-top:3em;">Agreed: <span style="color:white;">**signature_1**/</span></h3>
</body>
</html>
"""
from core.settings import DOCUSIGN_PRIVATE_KEY_PATH, DOCUSIGN_DOCUMENT_PATH_DOCX, DOCUSIGN_DOCUMENT_PATH_PDF
DS_JWT = {
"ds_client_id": "a2ecda0a-ebda-48f6-b784-a75a51608e07",
"ds_impersonated_user_id": "6c83e6cd-4cac-4aeb-a20e-22ab78b1f020", # The id of the user.
"private_key_file": DOCUSIGN_PRIVATE_KEY_PATH, # Create a new file in your repo source folder named private.key then copy and paste your RSA private key there and save it.
"authorization_server": "account-d.docusign.com",
"doc_docx": DOCUSIGN_DOCUMENT_PATH_DOCX,
"doc_pdf": DOCUSIGN_DOCUMENT_PATH_PDF,
}
\ No newline at end of file
from .jwt_helper import create_api_client, get_jwt_token, get_private_key
from docusign_esign import ApiClient
from os import path
def get_jwt_token(private_key, scopes, auth_server, client_id, impersonated_user_id):
"""Get the jwt token"""
api_client = ApiClient()
api_client.set_base_path(auth_server)
response = api_client.request_jwt_user_token(
client_id=client_id,
user_id=impersonated_user_id,
oauth_host_name=auth_server,
private_key_bytes=private_key,
expires_in=4000,
scopes=scopes
)
return response
def get_private_key(private_key_path):
"""
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(private_key_path)
if path.isfile(private_key_file):
with open(private_key_file) as private_key_file:
private_key = private_key_file.read()
else:
private_key = private_key_path
return private_key
def create_api_client(base_path, access_token):
"""Create api client and construct API headers"""
api_client = ApiClient()
api_client.host = base_path
api_client.set_default_header(header_name="Authorization", header_value=f"Bearer {access_token}")
return api_client
import sys
import subprocess
from docusign_esign import ApiClient
from docusign_esign.client.api_exception import ApiException
from .docusign_app.jwt_helpers import get_jwt_token, get_private_key
from .docusign_app.eSignature.examples.eg002_signing_via_email import Eg002SigningViaEmailController
from .docusign_app.jwt_config import DS_JWT
# pip install DocuSign SDK
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'docusign_esign'])
SCOPES = [
"signature", "impersonation"
]
def get_consent_url():
url_scopes = "+".join(SCOPES)
# Construct consent URL
redirect_uri = "https://developers.docusign.com/platform/auth/consent"
consent_url = f"https://{DS_JWT['authorization_server']}/oauth/auth?response_type=code&" \
f"scope={url_scopes}&client_id={DS_JWT['ds_client_id']}&redirect_uri={redirect_uri}"
return consent_url
def get_token(private_key, api_client):
# Call request_jwt_user_token method
token_response = get_jwt_token(private_key, SCOPES, DS_JWT["authorization_server"], DS_JWT["ds_client_id"],
DS_JWT["ds_impersonated_user_id"])
access_token = token_response.access_token
# Save API account ID
user_info = api_client.get_user_info(access_token)
accounts = user_info.get_accounts()
api_account_id = accounts[0].account_id
base_path = accounts[0].base_uri + "/restapi"
return {"access_token": access_token, "api_account_id": api_account_id, "base_path": base_path}
def get_args(api_account_id, access_token, base_path):
signer_email = input("Please enter the signer's email address: ")
signer_name = input("Please enter the signer's name: ")
cc_email = input("Please enter the cc email address: ")
cc_name = input("Please enter the cc name: ")
envelope_args = {
"signer_email": signer_email,
"signer_name": signer_name,
"cc_email": cc_email,
"cc_name": cc_name,
"status": "sent",
}
args = {
"account_id": api_account_id,
"base_path": base_path,
"access_token": access_token,
"envelope_args": envelope_args
}
return args
def run_example(private_key, api_client):
jwt_values = get_token(private_key, api_client)
args = get_args(jwt_values["api_account_id"], jwt_values["access_token"], jwt_values["base_path"])
envelope_id = Eg002SigningViaEmailController.worker(args, DS_JWT["doc_docx"], DS_JWT["doc_pdf"])
print("Your envelope has been sent.")
print(envelope_id)
def main():
api_client = ApiClient()
api_client.set_base_path(DS_JWT["authorization_server"])
api_client.set_oauth_host_name(DS_JWT["authorization_server"])
private_key = get_private_key(DS_JWT["private_key_file"]).encode("ascii").decode("utf-8")
try:
run_example(private_key, api_client)
except ApiException as err:
body = err.body.decode('utf8')
if "consent_required" in body:
consent_url = get_consent_url()
print("Open the following URL in your browser to grant consent to the application:")
print(consent_url)
consent_granted = input("Consent granted? Select one of the following: \n 1)Yes \n 2)No \n")
if consent_granted == "1":
run_example(private_key, api_client)
else:
sys.exit("Please grant consent")
# Generated by Django 4.2.1 on 2023-05-28 17:20
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='SignerInfo',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('signer_name', models.CharField(max_length=20, verbose_name='Имя')),
('signer_surname', models.CharField(max_length=20, verbose_name='Фамилия')),
('signer_email', models.EmailField(max_length=254, verbose_name='Почта')),
('status', models.CharField(choices=[('Документ успешно подписан', 'Resolve'), ('Не удалось подписать документ', 'Reject'), ('Документ ожидает подтверждения отправки на подпись', 'Default')], default='Документ ожидает подтверждения отправки на подпись', max_length=50, verbose_name='Статус заявки')),
],
),
]
# Generated by Django 4.2.1 on 2023-05-28 17:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='signerinfo',
name='status',
field=models.CharField(choices=[('Документ отправлен на подпись, проверьте Вашу почту', 'Resolve'), ('Не удалось отправить документ на подпись', 'Reject'), ('Документ ожидает подтверждения отправки на подпись', 'Default')], default='Документ ожидает подтверждения отправки на подпись', max_length=100, verbose_name='Статус заявки'),
),
]
from django.core.files.storage import FileSystemStorage
from django.db import models
from core import settings
class StatusChoices(models.TextChoices):
RESOLVE = 'Документ отправлен на подпись, проверьте Вашу почту'
REJECT = 'Не удалось отправить документ на подпись'
DEFAULT = 'Документ ожидает подтверждения отправки на подпись'
class SignerInfo(models.Model):
signer_name = models.CharField(
max_length=20,
null=False,
blank=False,
verbose_name='Имя',
)
signer_surname = models.CharField(
max_length=20,
null=False,
blank=False,
verbose_name='Фамилия',
)
signer_email = models.EmailField(
max_length=254,
verbose_name='Почта',
)
status = models.CharField(
max_length=100,
null=False,
blank=False,
choices=StatusChoices.choices,
default=StatusChoices.DEFAULT,
verbose_name='Статус заявки',
)
def __str__(self):
return f'{self.signer_name} {self.signer_email}'
from rest_framework import serializers
from api.models import SignerInfo
class DocumentNDASerializer(serializers.ModelSerializer):
class Meta:
model = SignerInfo
fields = ('id', 'signer_name', 'signer_surname', 'signer_email', 'status')
import sys
from docusign_esign import ApiClient, ApiException
from api.jwt_console import get_consent_url, get_token
from api.docusign_app.jwt_helpers import get_private_key
from api.models import SignerInfo
from api.docusign_app.jwt_config import DS_JWT
from api.docusign_app.eSignature.examples.eg002_signing_via_email import Eg002SigningViaEmailController
def get_args(api_account_id, access_token, base_path):
document = SignerInfo.objects.last()
signer_email = document.signer_email
signer_name = document.signer_name
cc_email = 'example@mail.com'
cc_name = 'name'
envelope_args = {
"signer_email": signer_email,
"signer_name": signer_name,
"cc_email": cc_email,
"cc_name": cc_name,
"status": "sent",
}
args = {
"account_id": api_account_id,
"base_path": base_path,
"access_token": access_token,
"envelope_args": envelope_args
}
return args
def run_docusign(private_key, api_client):
jwt_values = get_token(private_key, api_client)
args = get_args(jwt_values["api_account_id"], jwt_values["access_token"], jwt_values["base_path"])
envelope_id = Eg002SigningViaEmailController.worker(args, DS_JWT["doc_docx"], DS_JWT["doc_pdf"])
print("Your envelope has been sent.")
print(envelope_id)
def send_docusign_email():
api_client = ApiClient()
api_client.set_base_path(DS_JWT["authorization_server"])
api_client.set_oauth_host_name(DS_JWT["authorization_server"])
private_key = get_private_key(DS_JWT["private_key_file"]).encode("ascii").decode("utf-8")
try:
run_docusign(private_key, api_client)
except ApiException as err:
body = err.body.decode('utf8')
if "consent_required" in body:
consent_url = get_consent_url()
print("Open the following URL in your browser to grant consent to the application:")
print(consent_url)
consent_granted = input("Consent granted? Select one of the following: \n 1)Yes \n 2)No \n")
if consent_granted == "1":
run_docusign(private_key, api_client)
else:
sys.exit("Please grant consent")
return {'status': 'success'}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DocuSign test page</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</head>
<body>
<h1 style="text-align: center; margin-top: 10vh" class="display-6">DocuSign Esign <br>
<small class="text-muted">Подпишите документ с помощью docusign</small>
</h1>
<main style="background: lightgray; width: 70vh; margin-inline: auto">
<form style="width: 70vh; margin: 10vh auto; padding: 20px 30px;" id='form' method="POST">
<div class="form-group">
<label for="formGroupExampleInput">Введите свое имя</label>
<input name="signer_name" type="text" class="form-control" id="formGroupExampleInput" placeholder="Вася"
required>
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Введите свою фамилию</label>
<input name="signer_surname" type="text" class="form-control" id="formGroupExampleInput2"
placeholder="Пупкин" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Введите свой Email</label>
<input name="signer_email" type="email" class="form-control" id="exampleInputEmail1"
aria-describedby="emailHelp"
placeholder="vasyaPupkin@.mail.com" required>
</div>
<button type="submit" class="btn btn-primary">Подтвердить и подписать документ
</button>
</form>
</main>
</body>
<script>
const sendForm = (e) => {
e.preventDefault();
fetch(`${window.location.protocol + '//' + window.location.host}/api/v1/`, {
method: 'POST',
body: new FormData(form)
}).then(form.reset())
}
const form = document.querySelector('#form');
try {
form.addEventListener('submit', sendForm);
} catch (e) {
throw e
}
</script>
</html>
\ No newline at end of file
from django.test import TestCase
# Create your tests here.
from http.client import HTTPException
from django.shortcuts import redirect
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from api.models import StatusChoices
from api.serializers import DocumentNDASerializer
from api.services import send_docusign_email
def index_view(request):
return redirect('send_email')
class SendDocumentView(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'index.html'
def get(self, request):
data = {'error': 'error'}
return Response(data, template_name=self.template_name, status=200)
def post(self, request):
serializer = DocumentNDASerializer(data=request.data)
if serializer.is_valid():
signer = serializer.save()
try:
send_docusign_email()
signer.status = StatusChoices.RESOLVE
signer.save()
return Response(status=200, data=serializer.data)
except HTTPException as e:
signer.status = StatusChoices.REJECT
signer.save()
return Response({'error': e, 'signer': signer}, status=503)
return Response({'error': 'Bad Request', 'description': 'Введенные Вами данные не валидны'}, status=400)
"""
ASGI config for core project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
application = get_asgi_application()
"""
Django settings for core project.
Generated by 'django-admin startproject' using Django 4.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
import os
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'api',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.common.CommonMiddleware',
]
ROOT_URLCONF = 'core.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
APP_DIRS = True
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
]
}
WSGI_APPLICATION = 'core.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.getenv('DATABASE_NAME'),
'USER': os.getenv('DATABASE_USER'),
'PASSWORD': os.getenv('DATABASE_PASSWORD'),
'HOST': os.getenv('DATABASE_HOST'),
'PORT': os.getenv('DATABASE_PORT'),
},
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
CORS_ALLOWED_ORIGINS = [
'http://localhost:8000',
'http://0.0.0.0:8000',
]
CSRF_TRUSTED_ORIGINS = [
'http://localhost:8000',
'http://0.0.0.0:8000',
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "api/docusign_app/static"]
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'api/docusign_app/static')
MEDIA_URL = '/api/docusign_app/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DOCUSIGN_INTEGRATION_KEY = os.getenv('DOCUSIGN_INTEGRATION_KEY')
DOCUSIGN_PRIVATE_KEY_PATH = os.path.join(BASE_DIR, 'api/docusign_app/private.key')
DOCUSIGN_DOCUMENT_PATH_DOCX = os.path.join(BASE_DIR, 'api/docusign_app/static/demo_documents'
'/World_Wide_Corp_Battle_Plan_Trafalgar.docx')
DOCUSIGN_DOCUMENT_PATH_PDF = os.path.join(BASE_DIR, 'api/docusign_app/static/demo_documents/World_Wide_Corp_lorem.pdf')
DOCUSIGN_AUTH_SERVER = 'https://account-d.docusign.com'
DOCUSIGN_API_SERVER = 'https://api-d.docusign.com'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD')
EMAIL_PORT = 587
APPEND_SLASH = False
"""
URL configuration for core project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from api.views import index_view, SendDocumentView
urlpatterns = [
path('admin/', admin.site.urls),
path('', index_view, name='index'),
path('api/v1/', SendDocumentView.as_view(), name='send_email'),
]
"""
WSGI config for core project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
application = get_wsgi_application()
version: '3'
services:
docusign:
build:
context: .
dockerfile: ./Dockerfile
container_name: docusign
image: docusign_image
command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 --workers 3
restart: always
volumes:
- static_volume:/app/static
expose:
- 8000
env_file:
- ./.env
depends_on:
- postgres
postgres:
container_name: postgres
image: postgres:14
restart: always
volumes:
- postgres_data:/var/lib/postgresql/data/
env_file:
- ./.env.db
environment:
POSTGRES_USER: ${DATABASE_USER}
POSTGRES_PASSWORD: ${DATABASE_PASSWORD}
nginx:
build: ./nginx
container_name: nginx
restart: always
volumes:
- static_volume:/app/static
command: "/bin/sh -c 'while :; do sleep 6h & wait $${!}; nginx -s reload; done & nginx -g \"daemon off;\"'"
ports:
- "80:80"
depends_on:
- docusign
volumes:
static_volume:
postgres_data:
#!/bin/sh
if [ "$DATABASE" = "postgres" ]
then
echo "Waiting for postgres..."
while ! nc -z $DATABASE_HOST $DATABASE_PORT; do
sleep 0.1
done
echo "PostgreSQL started"
fi
python manage.py migrate --noinput
python manage.py collectstatic --no-input --clear
exec "$@"
\ No newline at end of file
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?",
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
FROM nginx:latest
RUN rm /etc/nginx/conf.d/default.conf
COPY default.conf /etc/nginx/conf.d/
\ No newline at end of file
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream wsgiserver {
server docusign:8000;
}
server {
listen 80;
server_name localhost;
location / {
try_files $uri @proxy_api;
}
location @proxy_api {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
proxy_pass http://wsgiserver;
}
location /static/ {
root /app/;
expires 1M;
access_log off;
add_header Cache-Control "public";
}
}
\ No newline at end of file
django==4.2.*
djangorestframework==3.14.*
psycopg2-binary==2.9.*
python-dotenv==1.0.*
docusign-esign==3.22.*
django-cors-headers==4.0.*
gunicorn==20.1.*
-r base.txt
flake8
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment