111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207 | class EncryptedString(types.TypeDecorator):
"""
Used to store encrypted values in a database
"""
impl = types.TypeEngine
def __init__(
self,
encrypt_secret: Union[str, Callable],
encrypt_backend: EncryptBackends = EncryptBackends.FERNET,
encrypt_custom_backend: Optional[Type[EncryptBackend]] = None,
**kwargs: Any,
) -> None:
_field_type = kwargs.pop("_field_type")
super().__init__()
if not cryptography: # pragma: nocover
raise ModelDefinitionError(
"In order to encrypt a column 'cryptography' is required!"
)
backend = BACKENDS_MAP.get(encrypt_backend, encrypt_custom_backend)
if (
not backend
or not isinstance(backend, type)
or not issubclass(backend, EncryptBackend)
):
raise ModelDefinitionError("Wrong or no encrypt backend provided!")
self.backend: EncryptBackend = backend()
self._field_type: "BaseField" = _field_type
self._underlying_type: Any = _field_type.column_type
self._key: Union[str, Callable] = encrypt_secret
type_ = self._field_type.__type__
if type_ is None: # pragma: nocover
raise ModelDefinitionError(
f"Improperly configured field " f"{self._field_type.name}"
)
self.type_: Any = type_
def __repr__(self) -> str: # pragma: nocover
return "TEXT()"
def load_dialect_impl(self, dialect: Dialect) -> Any:
return dialect.type_descriptor(types.TEXT())
def _refresh(self) -> None:
key = self._key() if callable(self._key) else self._key
self.backend._refresh(key)
def process_bind_param(self, value: Any, dialect: Dialect) -> Optional[str]:
if value is None:
return value
self._refresh()
try:
value = self._underlying_type.process_bind_param(value, dialect)
except AttributeError:
encoder, additional_parameter = self._get_coder_type_and_params(
coders=ormar.SQL_ENCODERS_MAP
)
if encoder is not None:
params = [value] + (
[additional_parameter] if additional_parameter else []
)
value = encoder(*params)
encrypted_value = self.backend.encrypt(value)
return encrypted_value
def process_result_value(self, value: Any, dialect: Dialect) -> Any:
if value is None:
return value
self._refresh()
decrypted_value = self.backend.decrypt(value)
try:
return self._underlying_type.process_result_value(decrypted_value, dialect)
except AttributeError:
decoder, additional_parameter = self._get_coder_type_and_params(
coders=ormar.DECODERS_MAP
)
if decoder is not None:
params = [decrypted_value] + (
[additional_parameter] if additional_parameter else []
)
return decoder(*params) # type: ignore
return self._field_type.__type__(decrypted_value) # type: ignore
def _get_coder_type_and_params(
self, coders: Dict[type, Callable]
) -> Tuple[Optional[Callable], Optional[str]]:
coder = coders.get(self.type_, None)
additional_parameter: Optional[str] = None
if self.type_ in ADDITIONAL_PARAMETERS_MAP:
additional_parameter = getattr(
self._field_type, ADDITIONAL_PARAMETERS_MAP[self.type_]
)
return coder, additional_parameter
|