Skip to content

Commit

Permalink
allow setting token in user settings (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuadavidthomas authored May 13, 2024
1 parent d7a2047 commit ebb730e
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 10 deletions.
11 changes: 10 additions & 1 deletion src/django_opfield/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import Any

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

OPFIELD_SETTINGS_NAME = "DJANGO_OPFIELD"

Expand Down Expand Up @@ -38,7 +39,15 @@ def OP_CLI_PATH(self) -> Path:

@property
def OP_SERVICE_ACCOUNT_TOKEN(self) -> str:
return os.environ.get("OP_SERVICE_ACCOUNT_TOKEN", "")
if user_token := self._get_user_settings("OP_SERVICE_ACCOUNT_TOKEN"):
token = user_token
else:
token = os.environ.get("OP_SERVICE_ACCOUNT_TOKEN", None)

if not token:
raise ImproperlyConfigured("OP_SERVICE_ACCOUNT_TOKEN is not set")

return token


app_settings = AppSettings()
14 changes: 7 additions & 7 deletions src/django_opfield/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,14 @@ def contribute_to_class(
super().contribute_to_class(cls, name, private_only)

def get_secret(self: models.Model) -> str | None:
if not app_settings.OP_SERVICE_ACCOUNT_TOKEN:
raise ValueError("OP_SERVICE_ACCOUNT_TOKEN is not set")
try:
op = app_settings.OP_CLI_PATH
except ImportError as err:
raise err
op = app_settings.OP_CLI_PATH
op_uri = getattr(self, name)
result = subprocess.run([op, "read", op_uri], capture_output=True)
op_token = app_settings.OP_SERVICE_ACCOUNT_TOKEN
result = subprocess.run(
[op, "read", op_uri],
capture_output=True,
env={"OP_SERVICE_ACCOUNT_TOKEN": op_token},
)
if result.returncode != 0:
raise ValueError(
f"Could not read secret from 1Password: {result.stderr.decode('utf-8')}"
Expand Down
5 changes: 3 additions & 2 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from unittest.mock import patch

import pytest
from django.core.exceptions import ImproperlyConfigured
from django.core.exceptions import ValidationError
from django.db import models

Expand Down Expand Up @@ -88,7 +89,7 @@ def test_get_secret(mock_run):
secret = model.op_uri_secret

mock_run.assert_called_once_with(
[ANY, "read", "op://vault/item/field"], capture_output=True
[ANY, "read", "op://vault/item/field"], capture_output=True, env=ANY
)
assert secret == "secret value"

Expand All @@ -100,7 +101,7 @@ def test_get_secret_no_token(mock_run):

model = TestModel(op_uri="op://vault/item/field")

with pytest.raises(ValueError) as exc_info:
with pytest.raises(ImproperlyConfigured) as exc_info:
_ = model.op_uri_secret

assert "OP_SERVICE_ACCOUNT_TOKEN is not set" in str(exc_info.value)
Expand Down

0 comments on commit ebb730e

Please sign in to comment.