|
| 1 | +"""BitBucket SSO Oauth Helper class""" |
| 2 | + |
| 3 | +from typing import TYPE_CHECKING, ClassVar, List, Optional, Union |
| 4 | + |
| 5 | +import pydantic |
| 6 | + |
| 7 | +from fastapi_sso.sso.base import DiscoveryDocument, OpenID, SSOBase |
| 8 | + |
| 9 | +if TYPE_CHECKING: |
| 10 | + import httpx # pragma: no cover |
| 11 | + |
| 12 | + |
| 13 | +class BitbucketSSO(SSOBase): |
| 14 | + """Class providing login using BitBucket OAuth""" |
| 15 | + |
| 16 | + provider = "bitbucket" |
| 17 | + scope: ClassVar = ["account", "email"] |
| 18 | + version = "2.0" |
| 19 | + |
| 20 | + def __init__( |
| 21 | + self, |
| 22 | + client_id: str, |
| 23 | + client_secret: str, |
| 24 | + redirect_uri: Optional[Union[pydantic.AnyHttpUrl, str]] = None, |
| 25 | + allow_insecure_http: bool = False, |
| 26 | + scope: Optional[List[str]] = None, |
| 27 | + ): |
| 28 | + super().__init__( |
| 29 | + client_id=client_id, |
| 30 | + client_secret=client_secret, |
| 31 | + redirect_uri=redirect_uri, |
| 32 | + allow_insecure_http=allow_insecure_http, |
| 33 | + scope=scope, |
| 34 | + ) |
| 35 | + |
| 36 | + async def get_useremail(self, session: Optional["httpx.AsyncClient"] = None) -> dict: |
| 37 | + """Get user email""" |
| 38 | + if session is None: |
| 39 | + raise ValueError("Session is required to make HTTP requests") |
| 40 | + |
| 41 | + response = await session.get(f"https://api.bitbucket.org/{self.version}/user/emails") |
| 42 | + return response.json() |
| 43 | + |
| 44 | + async def get_discovery_document(self) -> DiscoveryDocument: |
| 45 | + return { |
| 46 | + "authorization_endpoint": "https://bitbucket.org/site/oauth2/authorize", |
| 47 | + "token_endpoint": "https://bitbucket.org/site/oauth2/access_token", |
| 48 | + "userinfo_endpoint": f"https://api.bitbucket.org/{self.version}/user", |
| 49 | + } |
| 50 | + |
| 51 | + async def openid_from_response(self, response: dict, session: Optional["httpx.AsyncClient"] = None) -> OpenID: |
| 52 | + email = await self.get_useremail(session=session) |
| 53 | + return OpenID( |
| 54 | + email=email["values"][0]["email"], |
| 55 | + display_name=response.get("display_name"), |
| 56 | + provider=self.provider, |
| 57 | + id=str(response.get("uuid")).strip("{}"), |
| 58 | + first_name=response.get("nickname"), |
| 59 | + picture=response.get("links", {}).get("avatar", {}).get("href"), |
| 60 | + ) |
0 commit comments