Skip to content
9 changes: 7 additions & 2 deletions piccolo/apps/user/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from piccolo.columns import Boolean, Secret, Timestamp, Varchar
from piccolo.columns.column_types import Serial
from piccolo.columns.readable import Readable
from piccolo.table import Table
from piccolo.table import ExcludedSecretValue, Table
from piccolo.utils.sync import run_sync

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -171,7 +171,12 @@ def __setattr__(self, name: str, value: Any):
"""
Make sure that if the password is set, it's stored in a hashed form.
"""
if name == "password" and not value.startswith("pbkdf2_sha256"):
if (
name == "password"
and value
and not isinstance(value, ExcludedSecretValue)
and not value.startswith("pbkdf2_sha256")
):
value = self.__class__.hash_password(value)

super().__setattr__(name, value)
Expand Down
6 changes: 5 additions & 1 deletion piccolo/query/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,11 @@ async def _process_results(self, results) -> QueryResponseType:
return cast(
QueryResponseType,
[
self.table(**columns, _exists_in_db=True)
self.table(
**columns,
_exists_in_db=True,
_ignore_missing_secrets=True,
)
for columns in raw
],
)
Expand Down
6 changes: 5 additions & 1 deletion piccolo/query/methods/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ class Objects(

__slots__ = (
"nested",
"exclude_secrets",
"as_of_delegate",
"limit_delegate",
"offset_delegate",
Expand All @@ -323,9 +324,12 @@ def __init__(
self,
table: type[TableInstance],
prefetch: Sequence[Union[ForeignKey, list[ForeignKey]]] = (),
exclude_secrets: bool = False,
**kwargs,
):
super().__init__(table, **kwargs)
self.exclude_secrets = exclude_secrets

self.as_of_delegate = AsOfDelegate()
self.limit_delegate = LimitDelegate()
self.offset_delegate = OffsetDelegate()
Expand Down Expand Up @@ -457,7 +461,7 @@ async def response_handler(self, response):

@property
def default_querystrings(self) -> Sequence[QueryString]:
select = Select(table=self.table)
select = Select(table=self.table, exclude_secrets=self.exclude_secrets)

for attr in (
"as_of_delegate",
Expand Down
42 changes: 38 additions & 4 deletions piccolo/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@
TABLE_REGISTRY: list[type[Table]] = []


class ExcludedSecretValue:
pass


@dataclass
class TableMeta:
"""
Expand Down Expand Up @@ -438,15 +442,17 @@ def __init__(
_data: Optional[dict[Column, Any]] = None,
_ignore_missing: bool = False,
_exists_in_db: bool = False,
_ignore_missing_secrets: bool = False,
**kwargs,
):
"""
The constructor can be used to assign column values.

.. note::
The ``_data``, ``_ignore_missing``, and ``_exists_in_db``
arguments are prefixed with an underscore to help prevent a clash
with a column name which might be passed in via kwargs.
The ``_data``, ``_ignore_missing``, ``_exists_in_db`` and
``_ignore_missing_secrets`` arguments are prefixed with an
underscore to help prevent a clash with a column name which might
be passed in via kwargs.

:param _data:
There's two ways of passing in the data for each column. Firstly,
Expand All @@ -467,6 +473,9 @@ def __init__(
haven't been provided.
:param _exists_in_db:
Used internally to track whether this row exists in the database.
:param _ignore_missing_secrets:
If ``False`` any missing columns with ``secret=True`` will be set
to an instance of ``ExcludedSecretValue``.

"""
_data = _data or {}
Expand All @@ -489,6 +498,13 @@ def __init__(
cast(str, column._meta.db_column_name), ...
)

if (
value is ...
and column._meta.secret
and _ignore_missing_secrets
):
value = ExcludedSecretValue()

if value is ...:
value = column.get_default_value()

Expand Down Expand Up @@ -579,6 +595,12 @@ def save(
i: getattr(self, i._meta.name, None) for i in column_instances
}

values = {
i: v
for i, v in values.items()
if not isinstance(v, ExcludedSecretValue)
}

# Assign any `auto_update` values
if cls._meta.auto_update_columns:
auto_update_values = cls._meta.get_auto_update_values()
Expand Down Expand Up @@ -1246,6 +1268,7 @@ def alter(cls) -> Alter:
def objects(
cls: type[TableInstance],
*prefetch: Union[ForeignKey, list[ForeignKey]],
exclude_secrets=False,
) -> Objects[TableInstance]:
"""
Returns a list of table instances (each representing a row), which you
Expand Down Expand Up @@ -1280,8 +1303,19 @@ def objects(
>>> band.manager
<Band 1>

:param exclude_secrets:
If ``True``, any columns with ``secret=True`` are being set to an
ExcludedSecretValue default value in the response. For example, we
use this for the password column of
:class:`BaseUser <piccolo.apps.user.tables.BaseUser>`. Even though
the passwords are hashed, you still don't want them being passed
over the network if avoidable.

"""
return Objects[TableInstance](table=cls, prefetch=prefetch)

return Objects[TableInstance](
table=cls, prefetch=prefetch, exclude_secrets=exclude_secrets
)

@classmethod
def count(
Expand Down
2 changes: 1 addition & 1 deletion piccolo/utils/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,6 @@ def make_nested_object(
else:
table_params[key] = value

table_instance = table_class(**table_params)
table_instance = table_class(**table_params, _ignore_missing_secrets=True)
table_instance._exists_in_db = True
return table_instance
28 changes: 28 additions & 0 deletions tests/table/test_objects.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from piccolo.apps.user.tables import BaseUser
from piccolo.columns.column_types import ForeignKey
from piccolo.table import ExcludedSecretValue
from piccolo.testing.test_case import AsyncTableTest
from tests.base import DBTestCase, engines_only, sqlite_only
from tests.example_apps.music.tables import Band, Manager
Expand Down Expand Up @@ -64,6 +66,15 @@ def test_offset_sqlite(self):


class TestGet(DBTestCase):

def setUp(self):
super().setUp()
BaseUser.create_table().run_sync()

def tearDown(self):
super().tearDown()
BaseUser.alter().drop_table().run_sync()

def test_get(self):
self.insert_row()

Expand Down Expand Up @@ -94,6 +105,23 @@ def test_get_prefetch(self):
assert band is not None
self.assertIsInstance(band.manager, Manager)

def test_get_exclude_secrets(self):
"""
Make sure that secret fields are omitted from the response when
requested.
"""
user = BaseUser(username="piccolo", password="piccolo123")
user.save().run_sync()

user = BaseUser.objects(exclude_secrets=True).first().run_sync()
assert user is not None
assert isinstance(user.password, ExcludedSecretValue)

user.save().run_sync()

authenticated = BaseUser.login_sync("piccolo", "piccolo123")
self.assertTrue(authenticated is not None)


class TestGetOrCreate(DBTestCase):
def test_simple_where_clause(self):
Expand Down
Loading