Skip to content

Commit

Permalink
Merge pull request #253 from lincbrain/ak-ui-wk
Browse files Browse the repository at this point in the history
Resolve UI AppBar fix for WebKNOSSOS, logout of WebKNOSSOS during logout
  • Loading branch information
aaronkanzer authored Oct 2, 2024
2 parents 634c9ba + 1dbe44f commit 4df1feb
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 45 deletions.
14 changes: 7 additions & 7 deletions dandiapi/api/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def should_register_webknossos_account(self, api_url=None) -> bool:
not self.webknossos_credential and
api_url)

def register_webknossos_account(self, webknossos_api_url: str) -> None:
def register_webknossos_account(self, webknossos_api_url: str, webknossos_credential: str) -> None:

webknossos_organization_name = os.getenv('WEBKNOSSOS_ORGANIZATION_NAME', None)
webknossos_organization_display_name = os.getenv('WEBKNOSSOS_ORGANIZATION_DISPLAY_NAME',
Expand All @@ -38,16 +38,16 @@ def register_webknossos_account(self, webknossos_api_url: str) -> None:

register_external_api_request_task.delay(
method='POST',
external_endpoint=f'{webknossos_api_url}/api/auth/register',
external_endpoint='https://webknossos.lincbrain.org/api/auth/register',
payload={
"firstName": self.user.first_name,
"lastName": self.user.last_name,
"email": self.user.email,
"organization": webknossos_organization_name,
"organizationDisplayName": webknossos_organization_display_name,
"organization": "LINC",
"organizationName": "LINC",
"password": {
"password1": self.webknossos_credential,
"password2": self.webknossos_credential
"password1": webknossos_credential,
"password2": webknossos_credential
}
}
)
Expand All @@ -66,7 +66,7 @@ def save(self, *args, **kwargs):

random_password = get_random_string(length=12)
self.webknossos_credential = random_password
self.register_webknossos_account(webknossos_api_url=webknossos_api_url)
self.register_webknossos_account(webknossos_api_url=webknossos_api_url, webknossos_credential=random_password)
# Slightly recursive call, but will halt with WebKNOSSOS logic
super().save(*args, **kwargs)

Expand Down
37 changes: 15 additions & 22 deletions dandiapi/api/tasks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,39 +81,32 @@ def publish_dandiset_task(dandiset_id: int):

@shared_task
def register_external_api_request_task(method: str, external_endpoint: str, payload: dict = None,
query_params: dict = None):
"""
Register a celery task that performs an API request to an external service.
:param method: HTTP method to use for the request ('GET' or 'POST')
:param external_endpoint: URL of the external API endpoint
:param payload: Dictionary payload to send in the POST request (for 'POST' method)
:param query_params: Dictionary of query parameters to send in the GET request
(for 'GET' method)
"""
query_params: dict = None):
headers = {
'Content-Type': 'application/json',
}
try:
if method.upper() == 'POST':
requests.post(external_endpoint, json=payload, headers=headers, timeout=10)
response = requests.post(external_endpoint, json=payload, headers=headers, timeout=10)
response.raise_for_status()
logger.info(f"POST to {external_endpoint} successful with payload: {payload}")
logger.info(f"Response: {response.status_code}, {response.text}")
elif method.upper() == 'GET':
response = requests.get(external_endpoint, params=query_params, headers=headers,
timeout=10)
try:
return {'status_code': response.status_code, 'headers': response.headers}
except Exception:
logger.warning("Issue with GET response to %s", external_endpoint)
logger.info(f"GET to {external_endpoint} successful")
logger.info(f"Response: {response.status_code}, {response.headers}")
return {'status_code': response.status_code, 'headers': response.headers}
else:
logger.error("Unsupported HTTP method: %s", method)
return

except requests.exceptions.HTTPError:
logger.exception("HTTP error occurred")
except requests.exceptions.RequestException:
logger.exception("Request exception occurred")
except Exception:
logger.exception("An unexpected error occurred")
except requests.exceptions.HTTPError as http_err:
logger.error(f"HTTP error occurred: {http_err}")
logger.error(f"Response content: {response.text}") # Log response in case of error
except requests.exceptions.RequestException as req_err:
logger.error(f"Request exception occurred: {req_err}")
except Exception as err:
logger.error(f"An unexpected error occurred: {err}")

@shared_task(soft_time_limit=1200)
def unembargo_dandiset_task(dandiset_id: int):
Expand Down
25 changes: 14 additions & 11 deletions web/src/components/AppBar/AppBar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -94,17 +94,19 @@

<div v-if="!insideIFrame">
<template v-if="loggedIn">
<v-btn
:disabled="!user?.approved"
:to="{ name: 'createDandiset' }"
exact
class="mx-3"
color="#c44fc4"
rounded
>
New Dataset
</v-btn>
<UserMenu />
<div class="d-flex align-center">
<v-btn
:disabled="!user?.approved"
:to="{ name: 'createDandiset' }"
exact
class="mx-3"
color="#c44fc4"
rounded
>
New Dataset
</v-btn>
<UserMenu />
</div>
</template>
<template v-else>
<v-tooltip
Expand Down Expand Up @@ -210,5 +212,6 @@ function login() {
function handleWebKNOSSOSClick() {
dandiRest.loginWebKnossos();
window.open(lincWebKNOSSOSUrl, '_blank');
window.location.href = lincWebKNOSSOSUrl;
}
</script>
3 changes: 2 additions & 1 deletion web/src/components/AppBar/UserMenu.vue
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@

<script setup lang="ts">
import { computed, ref } from 'vue';
import { user, dandiRest } from '@/rest';
import {user, dandiRest, webknossosRest} from '@/rest';
import ApiKeyItem from '@/components/AppBar/ApiKeyItem.vue';
const userInitials = computed(() => {
Expand Down Expand Up @@ -90,6 +90,7 @@ async function getNeuroglancerCookies() {
async function logout() {
await webknossosRest.logout()
await dandiRest.logout();
}
</script>
17 changes: 13 additions & 4 deletions web/src/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,18 @@ const webknossosRest = {
const response = await webKnossosClient.get('api/datasets', { params });
return response;
},
async logout(params?: any): Promise<any> {
if (!params) {
params = {};
}

const response = await webKnossosClient.get('api/auth/logout', {
params,
withCredentials: true, // This ensures cookies are sent with the request
});

return response;
}
}

const dandiRest = {
Expand Down Expand Up @@ -111,18 +123,15 @@ const dandiRest = {
withCredentials: true, // Ensure credentials (cookies) are sent and handled
});

console.log(headers)

// If the server sends a Set-Cookie header, it may not be automatically handled by the browser
if (headers['set-cookie']) {
console.log('Received Set-Cookie:', headers['set-cookie']);
// Handle the Set-Cookie here if needed, such as saving it to localStorage or manually setting cookies
}

console.log('Login successful:', data);
// You can proceed with any further actions after login, like redirecting the user
} catch (error) {
console.error('Login failed:', error);
console.error('WebKNOSSOS login failed');
}
},
async me(): Promise<User> {
Expand Down

0 comments on commit 4df1feb

Please sign in to comment.