Convert Requester to attrs (#9586)

... because namedtuples suck

Fix up a couple of other annotations to keep mypy happy.
This commit is contained in:
Richard van der Hoff 2021-03-10 18:15:56 +00:00 committed by GitHub
parent 1107214a1d
commit a7a3790066
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 37 additions and 35 deletions

1
changelog.d/9586.misc Normal file
View File

@ -0,0 +1 @@
Convert `synapse.types.Requester` to an `attrs` class.

View File

@ -337,7 +337,8 @@ class AuthHandler(BaseHandler):
user is too high to proceed user is too high to proceed
""" """
if not requester.access_token_id:
raise ValueError("Cannot validate a user without an access token")
if self._ui_auth_session_timeout: if self._ui_auth_session_timeout:
last_validated = await self.store.get_access_token_last_validated( last_validated = await self.store.get_access_token_last_validated(
requester.access_token_id requester.access_token_id
@ -1213,7 +1214,7 @@ class AuthHandler(BaseHandler):
async def delete_access_tokens_for_user( async def delete_access_tokens_for_user(
self, self,
user_id: str, user_id: str,
except_token_id: Optional[str] = None, except_token_id: Optional[int] = None,
device_id: Optional[str] = None, device_id: Optional[str] = None,
): ):
"""Invalidate access tokens belonging to a user """Invalidate access tokens belonging to a user

View File

@ -35,6 +35,7 @@ from synapse.api.errors import (
from synapse.config._base import ConfigError from synapse.config._base import ConfigError
from synapse.logging.context import defer_to_thread from synapse.logging.context import defer_to_thread
from synapse.metrics.background_process_metrics import run_as_background_process from synapse.metrics.background_process_metrics import run_as_background_process
from synapse.types import UserID
from synapse.util.async_helpers import Linearizer from synapse.util.async_helpers import Linearizer
from synapse.util.retryutils import NotRetryingDestination from synapse.util.retryutils import NotRetryingDestination
from synapse.util.stringutils import random_string from synapse.util.stringutils import random_string
@ -145,7 +146,7 @@ class MediaRepository:
upload_name: Optional[str], upload_name: Optional[str],
content: IO, content: IO,
content_length: int, content_length: int,
auth_user: str, auth_user: UserID,
) -> str: ) -> str:
"""Store uploaded content for a local user and return the mxc URL """Store uploaded content for a local user and return the mxc URL

View File

@ -16,7 +16,7 @@
# limitations under the License. # limitations under the License.
import logging import logging
import re import re
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
import attr import attr
@ -1510,7 +1510,7 @@ class RegistrationStore(StatsStore, RegistrationBackgroundUpdateStore):
async def user_delete_access_tokens( async def user_delete_access_tokens(
self, self,
user_id: str, user_id: str,
except_token_id: Optional[str] = None, except_token_id: Optional[int] = None,
device_id: Optional[str] = None, device_id: Optional[str] = None,
) -> List[Tuple[str, int, Optional[str]]]: ) -> List[Tuple[str, int, Optional[str]]]:
""" """
@ -1533,7 +1533,7 @@ class RegistrationStore(StatsStore, RegistrationBackgroundUpdateStore):
items = keyvalues.items() items = keyvalues.items()
where_clause = " AND ".join(k + " = ?" for k, _ in items) where_clause = " AND ".join(k + " = ?" for k, _ in items)
values = [v for _, v in items] values = [v for _, v in items] # type: List[Union[str, int]]
if except_token_id: if except_token_id:
where_clause += " AND id != ?" where_clause += " AND id != ?"
values.append(except_token_id) values.append(except_token_id)

View File

@ -83,33 +83,32 @@ class ISynapseReactor(
"""The interfaces necessary for Synapse to function.""" """The interfaces necessary for Synapse to function."""
class Requester( @attr.s(frozen=True, slots=True)
namedtuple( class Requester:
"Requester",
[
"user",
"access_token_id",
"is_guest",
"shadow_banned",
"device_id",
"app_service",
"authenticated_entity",
],
)
):
""" """
Represents the user making a request Represents the user making a request
Attributes: Attributes:
user (UserID): id of the user making the request user: id of the user making the request
access_token_id (int|None): *ID* of the access token used for this access_token_id: *ID* of the access token used for this
request, or None if it came via the appservice API or similar request, or None if it came via the appservice API or similar
is_guest (bool): True if the user making this request is a guest user is_guest: True if the user making this request is a guest user
shadow_banned (bool): True if the user making this request has been shadow-banned. shadow_banned: True if the user making this request has been shadow-banned.
device_id (str|None): device_id which was set at authentication time device_id: device_id which was set at authentication time
app_service (ApplicationService|None): the AS requesting on behalf of the user app_service: the AS requesting on behalf of the user
authenticated_entity: The entity that authenticated when making the request.
This is different to the user_id when an admin user or the server is
"puppeting" the user.
""" """
user = attr.ib(type="UserID")
access_token_id = attr.ib(type=Optional[int])
is_guest = attr.ib(type=bool)
shadow_banned = attr.ib(type=bool)
device_id = attr.ib(type=Optional[str])
app_service = attr.ib(type=Optional["ApplicationService"])
authenticated_entity = attr.ib(type=str)
def serialize(self): def serialize(self):
"""Converts self to a type that can be serialized as JSON, and then """Converts self to a type that can be serialized as JSON, and then
deserialized by `deserialize` deserialized by `deserialize`
@ -157,23 +156,23 @@ class Requester(
def create_requester( def create_requester(
user_id: Union[str, "UserID"], user_id: Union[str, "UserID"],
access_token_id: Optional[int] = None, access_token_id: Optional[int] = None,
is_guest: Optional[bool] = False, is_guest: bool = False,
shadow_banned: Optional[bool] = False, shadow_banned: bool = False,
device_id: Optional[str] = None, device_id: Optional[str] = None,
app_service: Optional["ApplicationService"] = None, app_service: Optional["ApplicationService"] = None,
authenticated_entity: Optional[str] = None, authenticated_entity: Optional[str] = None,
): ) -> Requester:
""" """
Create a new ``Requester`` object Create a new ``Requester`` object
Args: Args:
user_id (str|UserID): id of the user making the request user_id: id of the user making the request
access_token_id (int|None): *ID* of the access token used for this access_token_id: *ID* of the access token used for this
request, or None if it came via the appservice API or similar request, or None if it came via the appservice API or similar
is_guest (bool): True if the user making this request is a guest user is_guest: True if the user making this request is a guest user
shadow_banned (bool): True if the user making this request is shadow-banned. shadow_banned: True if the user making this request is shadow-banned.
device_id (str|None): device_id which was set at authentication time device_id: device_id which was set at authentication time
app_service (ApplicationService|None): the AS requesting on behalf of the user app_service: the AS requesting on behalf of the user
authenticated_entity: The entity that authenticated when making the request. authenticated_entity: The entity that authenticated when making the request.
This is different to the user_id when an admin user or the server is This is different to the user_id when an admin user or the server is
"puppeting" the user. "puppeting" the user.