Skip to content

Commit

Permalink
Move and update Python examples from didkit (spruceid#6)
Browse files Browse the repository at this point in the history
Also:
- Fix CD
- Add CI

Related to didkit#308
  • Loading branch information
sbihel authored Aug 26, 2022
1 parent 503a337 commit 0a3dbb4
Show file tree
Hide file tree
Showing 39 changed files with 1,124 additions and 210 deletions.
24 changes: 24 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: CI

on: push

jobs:
CI:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: "3.10"
- name: Build Wheel
uses: messense/maturin-action@v1
with:
manylinux: off
args: --find-interpreter
- uses: abatilo/[email protected]
- name: Run Tests
working-directory: pydidkit_tests
run: |
curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python -
poetry install
poetry run pytest
23 changes: 4 additions & 19 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: CI/CD
name: CD

on:
push:
Expand All @@ -21,12 +21,7 @@ jobs:
uses: messense/maturin-action@v1
with:
target: ${{ matrix.target }}
args: --release --out dist --no-sdist
- name: Install built wheel
if: matrix.target == 'x64'
run: |
pip install didkit --no-index --find-links dist --force-reinstall
python -c "import didkit"
args: --release -o dist --find-interpreter
- name: Upload wheels
uses: actions/upload-artifact@v2
with:
Expand All @@ -44,12 +39,7 @@ jobs:
uses: messense/maturin-action@v1
with:
target: ${{ matrix.target }}
args: --release --out dist --no-sdist
- name: Install built wheel
if: matrix.target == 'x64'
run: |
pip install didkit --no-index --find-links dist --force-reinstall
python -c "import didkit"
args: --release -o dist --find-interpreter
- name: Upload wheels
uses: actions/upload-artifact@v2
with:
Expand All @@ -70,12 +60,7 @@ jobs:
with:
target: ${{ matrix.target }}
manylinux: auto
args: --release --out dist
- name: Install built wheel
if: matrix.target == 'x86_64'
run: |
pip install didkit --no-index --find-links dist --force-reinstall
python -c "import didkit"
args: --release -o dist --find-interpreter
- name: Upload wheels
uses: actions/upload-artifact@v2
with:
Expand Down
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ crate-type = ["cdylib"]
didkit_core = { version = "0.4", default-features = false, features = ["secp256k1", "p256", "no-ring"], package = "didkit" }
serde_json = "1.0"

pyo3 = { version = "0.15", features = ["extension-module"] }
pyo3-asyncio = { version = "0.15", features = ["tokio-runtime"] }
pyo3 = { version = "0.16", features = ["extension-module"] }
pyo3-asyncio = { version = "0.16", features = ["tokio-runtime"] }
tokio = "1.17"

[build-dependencies]
Expand Down
3 changes: 3 additions & 0 deletions examples/python-flask/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
key.jwk
**/__pycache__/
dist
21 changes: 21 additions & 0 deletions examples/python-flask/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Flask Example

This project demonstrates use of verifiable credentials and presentation for an
application.

## Dependencies

- Poetry ([installation instructions](https://python-poetry.org/docs/#installation))
- Python 3.7 or higher

### Python dependencies

```bash
$ poetry install
```

## Running

```bash
$ poetry run main
```
1 change: 1 addition & 0 deletions examples/python-flask/didkit_flask/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = "0.1.0"
45 changes: 45 additions & 0 deletions examples/python-flask/didkit_flask/issue_credential.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import json
import uuid
from datetime import datetime, timedelta

from didkit import issue_credential, key_to_did, key_to_verification_method


async def req_issue_vc(request):
with open("key.jwk", "r") as f:
key = f.readline()
f.close()

did_key = request.form.get("subject_id", key_to_did("key", key))
verification_method = await key_to_verification_method("key", key)
issuance_date = datetime.utcnow().replace(microsecond=0)
expiration_date = issuance_date + timedelta(weeks=24)

credential = {
"id": "urn:uuid:" + uuid.uuid4().__str__(),
"@context": [
"https://www.w3.org/2018/credentials/v1",
"https://www.w3.org/2018/credentials/examples/v1",
],
"type": ["VerifiableCredential"],
"issuer": did_key,
"issuanceDate": issuance_date.isoformat() + "Z",
"expirationDate": expiration_date.isoformat() + "Z",
"credentialSubject": {
"@context": [{"username": "https://schema.org/Text"}],
"id": "urn:uuid:" + uuid.uuid4().__str__(),
"username": "Someone",
},
}

didkit_options = {
"proofPurpose": "assertionMethod",
"verificationMethod": verification_method,
}

credential = await issue_credential(
credential.__str__().replace("'", '"'),
didkit_options.__str__().replace("'", '"'),
key,
)
return json.loads(credential)
66 changes: 66 additions & 0 deletions examples/python-flask/didkit_flask/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import errno
import json
import os
from socket import AF_INET, SOCK_DGRAM, socket

from didkit import generate_ed25519_key
from flask import Flask, jsonify, render_template, request
from flask_qrcode import QRcode

from didkit_flask.issue_credential import req_issue_vc

app = Flask(__name__)
qrcode = QRcode(app)


@app.route("/")
def index():
s = socket(AF_INET, SOCK_DGRAM)
try:
s.connect(("10.255.255.255", 1))
IP = s.getsockname()[0]
except Exception:
IP = "127.0.0.1"
finally:
s.close()

url = (
(request.is_secure and "https://" or "http://")
+ IP
+ ":"
+ request.host.split(":")[-1]
+ "/wallet"
)

return render_template("index.html", url=url)


@app.route("/credential", methods=["GET", "POST"])
async def credential():
credential = json.dumps(await req_issue_vc(request), indent=2, sort_keys=True)

return render_template("credential.html", credential=credential)


@app.route("/wallet", methods=["GET", "POST"])
async def wallet():
credential = await req_issue_vc(request)
if request.method == "GET":
return jsonify({"type": "CredentialOffer", "credentialPreview": credential})
elif request.method == "POST":
return jsonify(credential)


def main():
flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
try:
file_handle = os.open("key.jwk", flags)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise
else:
with os.fdopen(file_handle, "w") as file_obj:
file_obj.write(generate_ed25519_key())
app.run(host="0.0.0.0", port=5001)
11 changes: 11 additions & 0 deletions examples/python-flask/didkit_flask/templates/credential.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
<title>DIDKit Django</title>
</head>
<body class="h-screen w-screen flex">
<pre class="whitespace-pre-wrap m-auto">{{ credential }}</pre>
</body>
</html>
30 changes: 30 additions & 0 deletions examples/python-flask/didkit_flask/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
<title>DIDKit Django</title>
</head>
<body class="flex flex-col items-center justify-center h-screen w-screen">
<form class="flex items-center justify-center mb-4" method="post" action="/credential">
<input type="text" placeholder="Enter your DID:" class="h-12 p-4 border border-blue-900 rounded mr-4" name="subject_id" />
<button
class="h-12 p-2 border border-blue-900 rounded"
type="submit"
>
Get credential
</button>
</form>
<p>or scan the QRCode bellow with your wallet. i.e: Credible</p>
<div class="my-8"><img src={{ qrcode(url) }} class="w-32 h-32"></div>
<p>or</p>
<a href="/credential">
<button
class="h-12 p-2 border mt-6 border-blue-900 rounded"
type="submit"
>
Get server issued credential
</button>
</a>
</body>
</html>
Loading

0 comments on commit 0a3dbb4

Please sign in to comment.