v0.166.0
  1from datetime import datetime
  2from typing import TYPE_CHECKING, Any
  3
  4import psycopg
  5from app.users.models import User
  6from plain.exceptions import ValidationError
  7from plain.postgres import EncryptedField, Field, transaction, types
  8from plain.utils import timezone
  9
 10from plain import postgres
 11
 12from .exceptions import OAuthUserAlreadyExistsError
 13
 14if TYPE_CHECKING:
 15    from .providers import OAuthToken, OAuthUser
 16
 17__all__ = ["OAuthConnection"]
 18
 19
 20@postgres.register_model
 21class OAuthConnection(postgres.Model):
 22    created_at: Field[datetime] = types.DateTimeField(create_now=True)
 23    updated_at: Field[datetime] = types.DateTimeField(create_now=True, update_now=True)
 24
 25    user: Field[User] = types.ForeignKeyField(
 26        "users.User",
 27        on_delete=postgres.CASCADE,
 28    )
 29
 30    # The key used to refer to this provider type (in settings)
 31    provider_key: Field[str] = types.TextField(max_length=100)
 32
 33    # The unique ID of the user on the provider's system
 34    provider_user_id: Field[str] = types.TextField(max_length=100)
 35
 36    # Token data
 37    access_token: EncryptedField[str] = types.EncryptedTextField(max_length=2000)
 38    refresh_token: EncryptedField[str] = types.EncryptedTextField(
 39        max_length=2000, required=False, default=""
 40    )
 41    access_token_expires_at: Field[datetime | None] = types.DateTimeField(
 42        required=False, allow_null=True, default=None
 43    )
 44    refresh_token_expires_at: Field[datetime | None] = types.DateTimeField(
 45        required=False, allow_null=True, default=None
 46    )
 47
 48    model_options = postgres.Options(
 49        indexes=[
 50            postgres.Index(
 51                name="plainoauth_oauthconnection_user_id_idx", fields=["user"]
 52            ),
 53        ],
 54        constraints=[
 55            postgres.UniqueConstraint(
 56                fields=["provider_key", "provider_user_id"],
 57                name="plainoauth_oauthconnection_unique_provider_key_user_id",
 58            )
 59        ],
 60        ordering=("provider_key",),
 61    )
 62
 63    def __str__(self) -> str:
 64        return f"{self.provider_key}[{self.user}:{self.provider_user_id}]"
 65
 66    def refresh_access_token(self) -> None:
 67        """Get a new access token from the provider and save it.
 68
 69        Safe to call from concurrent requests. Many providers (GitHub among
 70        them) make refresh tokens single-use, so two requests refreshing at
 71        once would both send the same refresh token and the provider would
 72        refuse the second. The row is locked for the refresh, and a request
 73        that finds another one already replaced the token uses that instead.
 74
 75        The provider retires the old refresh token as soon as it answers, so
 76        call this outside a transaction that might roll back, or the new one
 77        is lost with it.
 78        """
 79        from .providers import get_oauth_provider_instance
 80
 81        with transaction.atomic():
 82            locked = OAuthConnection.query.for_update().get(id=self.id)
 83            if (
 84                locked.access_token == self.access_token
 85                or locked.access_token_expired()
 86            ):
 87                provider_instance = get_oauth_provider_instance(
 88                    provider_key=self.provider_key
 89                )
 90                locked.set_token_fields(
 91                    provider_instance.refresh_oauth_token(
 92                        oauth_token=locked._stored_oauth_token()
 93                    )
 94                )
 95                # Saved through the freshly locked row, so the write doesn't
 96                # put back any other columns this instance has stale.
 97                locked.update()
 98
 99        self.set_token_fields(locked._stored_oauth_token())
100        self.updated_at = locked.updated_at
101
102    def _stored_oauth_token(self) -> OAuthToken:
103        from .providers import OAuthToken
104
105        return OAuthToken(
106            access_token=self.access_token,
107            refresh_token=self.refresh_token,
108            access_token_expires_at=self.access_token_expires_at,
109            refresh_token_expires_at=self.refresh_token_expires_at,
110        )
111
112    def set_token_fields(self, oauth_token: OAuthToken) -> None:
113        self.access_token = oauth_token.access_token
114        self.refresh_token = oauth_token.refresh_token
115        self.access_token_expires_at = oauth_token.access_token_expires_at
116        self.refresh_token_expires_at = oauth_token.refresh_token_expires_at
117
118    def set_user_fields(self, oauth_user: OAuthUser) -> None:
119        self.provider_user_id = oauth_user.provider_id
120
121    def access_token_expired(self) -> bool:
122        return (
123            self.access_token_expires_at is not None
124            and self.access_token_expires_at < timezone.now()
125        )
126
127    def refresh_token_expired(self) -> bool:
128        return (
129            self.refresh_token_expires_at is not None
130            and self.refresh_token_expires_at < timezone.now()
131        )
132
133    @classmethod
134    def get_or_create_user(
135        cls, *, provider_key: str, oauth_token: OAuthToken, oauth_user: OAuthUser
136    ) -> OAuthConnection:
137        try:
138            connection = cls.query.get(
139                cls.provider_key.equals(provider_key),
140                cls.provider_user_id.equals(oauth_user.provider_id),
141            )
142            connection.set_token_fields(oauth_token)
143            connection.update()
144            return connection
145        except cls.DoesNotExist:
146            # If email needs to be unique, then we expect
147            # that to be taken care of on the user model itself
148            with transaction.atomic():
149                try:
150                    with transaction.atomic():
151                        user = User(
152                            **oauth_user.user_model_fields,
153                        )
154                        user.create()
155                except psycopg.IntegrityError, ValidationError:
156                    raise OAuthUserAlreadyExistsError(
157                        provider_key=provider_key,
158                        user_model_fields=oauth_user.user_model_fields,
159                    )
160
161                return cls.connect(
162                    user=user,
163                    provider_key=provider_key,
164                    oauth_token=oauth_token,
165                    oauth_user=oauth_user,
166                )
167
168    @classmethod
169    def connect(
170        cls,
171        *,
172        user: Any,
173        provider_key: str,
174        oauth_token: OAuthToken,
175        oauth_user: OAuthUser,
176    ) -> OAuthConnection:
177        """
178        Connect will either create a new connection or update an existing connection
179        """
180        try:
181            # Conditions in the order get() sorted its kwargs, so the SQL is
182            # byte-identical to the string form this replaced.
183            connection = cls.query.get(
184                cls.provider_key.equals(provider_key),
185                cls.provider_user_id.equals(oauth_user.provider_id),
186                cls.user.id.equals(user.id),
187            )
188        except cls.DoesNotExist:
189            # Create our own instance (not using get_or_create)
190            # so that any created signals contain the token fields too
191            connection = cls(
192                user=user,
193                provider_key=provider_key,
194                provider_user_id=oauth_user.provider_id,
195                access_token=oauth_token.access_token,
196                refresh_token=oauth_token.refresh_token,
197            )
198
199        connection.set_user_fields(oauth_user)
200        connection.set_token_fields(oauth_token)
201        if connection._state.adding:
202            connection.create()
203        else:
204            connection.update()
205
206        return connection