|
| 1 | +import os |
| 2 | +import datetime |
| 3 | +from typing import Tuple |
| 4 | + |
| 5 | +import msal |
| 6 | +import flask |
| 7 | + |
| 8 | + |
| 9 | +class Oauth2: |
| 10 | + """Oauth2 authorization Code grant flow""" |
| 11 | + |
| 12 | + def __init__(self, app: flask.app.Flask): |
| 13 | + self._app = app |
| 14 | + |
| 15 | + # Azure AD app registration info (currently the values are taken from environment variables) |
| 16 | + self._tenant_id = os.environ["WEBVIZ_TENANT_ID"] |
| 17 | + self._client_id = os.environ["WEBVIZ_CLIENT_ID"] |
| 18 | + self._client_secret = os.environ["WEBVIZ_CLIENT_SECRET"] |
| 19 | + self._scope = os.environ["WEBVIZ_SCOPE"] |
| 20 | + |
| 21 | + # Initiate msal |
| 22 | + self._msal_app = msal.ConfidentialClientApplication( |
| 23 | + client_id=self._client_id, |
| 24 | + client_credential=self._client_secret, |
| 25 | + authority=f"https://login.microsoftonline.com/{self._tenant_id}", |
| 26 | + ) |
| 27 | + self._accounts = self._msal_app.get_accounts() |
| 28 | + |
| 29 | + # Initiate oauth2 endpoints |
| 30 | + self.set_oauth2_endpoints() |
| 31 | + |
| 32 | + def set_oauth2_endpoints(self) -> None: |
| 33 | + """/login and /auth-return endpoints are added for Oauth2 authorization |
| 34 | + code flow. |
| 35 | +
|
| 36 | + At the end of the flow, a session cookie containing a valid access token |
| 37 | + and its expiration date is created. This flask session object can be |
| 38 | + accessed from Webviz plugin. |
| 39 | +
|
| 40 | + To get the access token: flask.session.get("access_token") |
| 41 | + To get the expiration date: flask.session.get("expiration_date") |
| 42 | +
|
| 43 | + An Azure AD application should be registered, and the following environment |
| 44 | + variables should be set: WEBVIZ_TENANT_ID, WEBVIZ_CLIENT_ID, |
| 45 | + WEBVIZ_CLIENT_SECRET, WEBVIZ_SCOPE. |
| 46 | + """ |
| 47 | + |
| 48 | + @self._app.route("/login") |
| 49 | + def _login_controller(): # type: ignore[no-untyped-def] |
| 50 | + redirect_uri = get_auth_redirect_uri(flask.request.url_root) |
| 51 | + |
| 52 | + # First leg of Oauth2 authorization code flow |
| 53 | + auth_url = self._msal_app.get_authorization_request_url( |
| 54 | + scopes=[self._scope], redirect_uri=redirect_uri |
| 55 | + ) |
| 56 | + return flask.redirect(auth_url) |
| 57 | + |
| 58 | + @self._app.route("/auth-return") |
| 59 | + def _auth_return_controller(): # type: ignore[no-untyped-def] |
| 60 | + redirect_uri = get_auth_redirect_uri(flask.request.url_root) |
| 61 | + returned_query_params = flask.request.args |
| 62 | + |
| 63 | + # There is an error from the first leg of Oauth2 authorization code flow |
| 64 | + if "error" in returned_query_params: |
| 65 | + error_description = returned_query_params.get("error_description") |
| 66 | + print("Error description:", error_description) |
| 67 | + redirect_error_uri = flask.url_for("error_controller") |
| 68 | + return flask.redirect(redirect_error_uri) |
| 69 | + |
| 70 | + code = returned_query_params.get("code") |
| 71 | + |
| 72 | + # Second leg of Oauth2 authorization code flow |
| 73 | + tokens_result = self._msal_app.acquire_token_by_authorization_code( |
| 74 | + code=code, scopes=[self._scope], redirect_uri=redirect_uri |
| 75 | + ) |
| 76 | + expires_in = tokens_result.get("expires_in") |
| 77 | + expiration_date = datetime.datetime.now() + datetime.timedelta( |
| 78 | + seconds=expires_in - 60 |
| 79 | + ) |
| 80 | + print("Access token expiration date:", expiration_date) |
| 81 | + |
| 82 | + # Set expiration date in the session |
| 83 | + flask.session["expiration_date"] = expiration_date |
| 84 | + |
| 85 | + # Set access token in the session |
| 86 | + flask.session["access_token"] = tokens_result.get("access_token") |
| 87 | + |
| 88 | + return flask.redirect(flask.request.url_root) |
| 89 | + |
| 90 | + @self._app.route("/error") |
| 91 | + def _error_controller(): # type: ignore[no-untyped-def] |
| 92 | + return "Error" |
| 93 | + |
| 94 | + def set_oauth2_before_request_decorator(self) -> None: |
| 95 | + """Check access token existence in session cookie before every request. |
| 96 | + If it does not exist, the browser is redirected to /login endpoint. |
| 97 | +
|
| 98 | + If access token exists, its expiration date is checked in session cookie. |
| 99 | + If the current date exceeds its expiration date, a new access token is |
| 100 | + retrieved and set in the session cookie. A new expiration date is also |
| 101 | + set in the session cookie. |
| 102 | + """ |
| 103 | + |
| 104 | + # pylint: disable=inconsistent-return-statements |
| 105 | + @self._app.before_request |
| 106 | + def _check_access_token(): # type: ignore[no-untyped-def] |
| 107 | + # The session of the request does not contain access token, redirect to /login |
| 108 | + is_redirected, redirect_url = self.is_empty_token() |
| 109 | + if is_redirected: |
| 110 | + return flask.redirect(redirect_url) |
| 111 | + |
| 112 | + # The session contains access token, check its expiration date |
| 113 | + self.check_and_set_token_expiry() |
| 114 | + |
| 115 | + @staticmethod |
| 116 | + def is_empty_token() -> Tuple[bool, str]: |
| 117 | + if ( |
| 118 | + not flask.session.get("access_token") |
| 119 | + and flask.request.path != "/login" |
| 120 | + and flask.request.path != "/auth-return" |
| 121 | + ): |
| 122 | + login_uri = get_login_uri(flask.request.url_root) |
| 123 | + return True, login_uri |
| 124 | + |
| 125 | + return False, "" |
| 126 | + |
| 127 | + def check_and_set_token_expiry(self) -> None: |
| 128 | + if flask.session.get("access_token"): |
| 129 | + expiration_date = flask.session.get("expiration_date") |
| 130 | + current_date = datetime.datetime.now() |
| 131 | + if current_date > expiration_date: |
| 132 | + # Access token has expired |
| 133 | + print("Access token has expired.") |
| 134 | + if not self._accounts: |
| 135 | + self._accounts = self._msal_app.get_accounts() |
| 136 | + renewed_tokens_result = self._msal_app.acquire_token_silent( |
| 137 | + scopes=[self._scope], account=self._accounts[0] |
| 138 | + ) |
| 139 | + expires_in = renewed_tokens_result.get("expires_in") |
| 140 | + new_expiration_date = datetime.datetime.now() + datetime.timedelta( |
| 141 | + seconds=expires_in - 60 |
| 142 | + ) |
| 143 | + print("New access token expiration date:", new_expiration_date) |
| 144 | + |
| 145 | + # Set new expiration date in the session |
| 146 | + flask.session["expiration_date"] = new_expiration_date |
| 147 | + |
| 148 | + # Set new access token in the session |
| 149 | + flask.session["access_token"] = renewed_tokens_result.get( |
| 150 | + "access_token" |
| 151 | + ) |
| 152 | + |
| 153 | + |
| 154 | +def get_login_uri(url_root: str) -> str: |
| 155 | + return url_root + "login" |
| 156 | + |
| 157 | + |
| 158 | +def get_auth_redirect_uri(url_root: str) -> str: |
| 159 | + return url_root + "auth-return" |
0 commit comments