Coverage for bc/kwai-bc-identity/src/kwai_bc_identity/tokens/refresh_token.py: 100%
21 statements
« prev ^ index » next coverage.py v7.11.0, created at 2024-01-01 00:00 +0000
« prev ^ index » next coverage.py v7.11.0, created at 2024-01-01 00:00 +0000
1"""Module for a refresh token entity."""
3from dataclasses import dataclass, field, replace
4from typing import ClassVar, Self, Type
6from kwai_core.domain.entity import DataclassEntity
7from kwai_core.domain.value_objects.identifier import IntIdentifier
8from kwai_core.domain.value_objects.timestamp import Timestamp
10from kwai_bc_identity.tokens.access_token import AccessTokenEntity
11from kwai_bc_identity.tokens.token_identifier import TokenIdentifier
14class RefreshTokenIdentifier(IntIdentifier):
15 """Identifier for a refresh token."""
18@dataclass(kw_only=True, eq=False, slots=True, frozen=True)
19class RefreshTokenEntity(DataclassEntity):
20 """A refresh token entity.
22 Attributes:
23 access_token: The access token associated with this refresh token.
24 identifier: The actual token.
25 expiration: The expiration timestamp of the token.
26 revoked: Whether the token has been revoked.
27 """
29 ID: ClassVar[Type] = RefreshTokenIdentifier
31 access_token: AccessTokenEntity
32 identifier: TokenIdentifier = field(default_factory=TokenIdentifier.generate)
33 expiration: Timestamp = field(default_factory=Timestamp.create_now)
34 revoked: bool = field(default=False)
36 @property
37 def expired(self) -> bool:
38 """Return True when the token is expired."""
39 return self.expiration.is_past
41 def revoke(self) -> Self:
42 """Revoke the refresh token.
44 Returns:
45 A revoked refresh token.
46 """
47 return replace(
48 self, revoked=True, traceable_time=self.traceable_time.mark_for_update()
49 )
51 def renew(self, expiry_minutes: int, access_token_expiry_minutes: int) -> Self:
52 """Renew the refresh token.
54 The access token will also be renewed.
56 Args:
57 expiry_minutes: The number of minutes until the refresh token expires.
58 access_token_expiry_minutes:
59 The number of minutes until the access token expires.
60 """
61 return replace(
62 self,
63 identifier=TokenIdentifier.generate(),
64 expiration=Timestamp.create_with_delta(minutes=expiry_minutes),
65 access_token=self.access_token.renew(access_token_expiry_minutes),
66 traceable_time=self.traceable_time.mark_for_update(),
67 )