Skip to content

Commit

Permalink
Logic to add secret field if needed, refs #46
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw committed Apr 27, 2024
1 parent 9a42643 commit 7643fd2
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
34 changes: 34 additions & 0 deletions datasette_enrichments/__init__.py
Expand Up @@ -9,6 +9,8 @@
import urllib
from datasette.plugins import pm
from .views import enrichment_picker, enrichment_view
from wtforms import PasswordField
from wtforms.validators import DataRequired
from .utils import get_with_auth, mark_job_complete, pks_for_rows
from . import hookspecs

Expand Down Expand Up @@ -130,6 +132,38 @@ async def log_error(
async def get_config_form(self, datasette: "Datasette", db: "Database", table: str):
return None

async def _get_config_form(
self, datasette: "Datasette", db: "Database", table: str
):
# Helper method that adds a `_secret` form field if the enrichment has a secret
FormClass = await self.get_config_form(datasette, db, table)
if self.secret is None:
return FormClass
# If secret is already set, return form unmodified
if await get_secret(datasette, self.secret.name):
return FormClass

# Otherwise, return form with secret field
def stash_api_key(form, field):
if not hasattr(datasette, "_enrichments_gpt_stashed_keys"):
datasette._enrichments_gpt_stashed_keys = {}
key = secrets.token_urlsafe(16)
datasette._enrichments_gpt_stashed_keys[key] = field.data
field.data = key

class FormWithSecret(FormClass):
enrichment_secret = PasswordField(
self.secret.name,
description=self.secret.description,
validators=[
DataRequired(message="Secret is required."),
stash_api_key,
],
render_kw={"autocomplete": "off"},
)

return FormWithSecret

async def initialize(
self, datasette: "Datasette", db: "Database", table: str, config: dict
):
Expand Down
4 changes: 2 additions & 2 deletions datasette_enrichments/views.py
Expand Up @@ -65,7 +65,7 @@ async def enrichment_view(datasette, request):

form = (
await async_call_with_supported_arguments(
enrichment.get_config_form,
enrichment._get_config_form,
datasette=datasette,
db=datasette.get_database(database),
table=table,
Expand Down Expand Up @@ -170,7 +170,7 @@ async def enrich_data_post(datasette, request, enrichment, filtered_data):
post_vars = MultiParams(urllib.parse.parse_qs(body.decode("utf-8")))

Form = await async_call_with_supported_arguments(
enrichment.get_config_form, datasette=datasette, db=db, table=table
enrichment._get_config_form, datasette=datasette, db=db, table=table
)

form = Form(post_vars)
Expand Down

0 comments on commit 7643fd2

Please sign in to comment.