|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from bunq import ApiEnvironmentType |
| 4 | +from bunq.sdk.context.bunq_context import BunqContext |
| 5 | +from bunq.sdk.exception.bunq_exception import BunqException |
| 6 | +from bunq.sdk.http.http_util import HttpUtil |
| 7 | +from bunq.sdk.model.core.bunq_model import BunqModel |
| 8 | +from bunq.sdk.model.core.oauth_response_type import OauthResponseType |
| 9 | +from bunq.sdk.model.generated.endpoint import OauthClient |
| 10 | + |
| 11 | + |
| 12 | +class OauthAuthorizationUri(BunqModel): |
| 13 | + # Auth constants. |
| 14 | + AUTH_URI_FORMAT_SANDBOX = "https://oauth.sandbox.bunq.com/auth?%s" |
| 15 | + AUTH_URI_FORMAT_PRODUCTION = "https://oauth.bunq.com/auth?%s" |
| 16 | + |
| 17 | + # Field constants |
| 18 | + FIELD_RESPONSE_TYPE = "response_type" |
| 19 | + FIELD_REDIRECT_URI = "redirect_uri" |
| 20 | + FIELD_STATE = "state" |
| 21 | + FIELD_CLIENT_ID = "client_id" |
| 22 | + |
| 23 | + # Error constants. |
| 24 | + ERROR_ENVIRONMENT_TYPE_NOT_SUPPORTED = "You are trying to use an unsupported environment type." |
| 25 | + |
| 26 | + def __init__(self, authorization_uri: str) -> None: |
| 27 | + self._authorization_uri = authorization_uri |
| 28 | + |
| 29 | + @property |
| 30 | + def authorization_uri(self) -> str: |
| 31 | + return self._authorization_uri |
| 32 | + |
| 33 | + @classmethod |
| 34 | + def create(cls, |
| 35 | + response_type: OauthResponseType, |
| 36 | + redirect_uri: str, |
| 37 | + client: OauthClient, |
| 38 | + state: str = None) -> OauthAuthorizationUri: |
| 39 | + all_request_parameter = { |
| 40 | + cls.FIELD_REDIRECT_URI: redirect_uri, |
| 41 | + cls.FIELD_RESPONSE_TYPE: response_type.value, |
| 42 | + cls.FIELD_CLIENT_ID: client.client_id |
| 43 | + } |
| 44 | + |
| 45 | + if state is not None: |
| 46 | + all_request_parameter[cls.FIELD_STATE] = state |
| 47 | + |
| 48 | + return OauthAuthorizationUri( |
| 49 | + cls.determine_auth_uri_format().format(HttpUtil.create_query_string(all_request_parameter)) |
| 50 | + ) |
| 51 | + |
| 52 | + def is_all_field_none(self) -> bool: |
| 53 | + if self._authorization_uri is None: |
| 54 | + return True |
| 55 | + else: |
| 56 | + return False |
| 57 | + |
| 58 | + @classmethod |
| 59 | + def determine_auth_uri_format(cls) -> str: |
| 60 | + environment_type = BunqContext.api_context().environment_type |
| 61 | + |
| 62 | + if ApiEnvironmentType.PRODUCTION == environment_type: |
| 63 | + return cls.AUTH_URI_FORMAT_PRODUCTION |
| 64 | + |
| 65 | + if ApiEnvironmentType.SANDBOX == environment_type: |
| 66 | + return cls.AUTH_URI_FORMAT_SANDBOX |
| 67 | + |
| 68 | + raise BunqException(cls.ERROR_ENVIRONMENT_TYPE_NOT_SUPPORTED) |
0 commit comments