Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fixed magic link issues in dev environment #32

Closed
wants to merge 24 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions business-registry-dashboard/app/middleware/01.auth.global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ export default defineNuxtRouteMiddleware((to) => {
if (process.client) {
const { $keycloak } = useNuxtApp()
const localePath = useLocalePath()

// If it's an invitation acceptance URL, handle it differently
if (to.path.includes('/affiliationInvitation/acceptToken/')) {
// Option 1: Force reload
window.location.href = localePath('/')
return
}

// Regular auth check
if (to.meta.order !== 0 && !$keycloak.authenticated) {
return navigateTo(localePath('/'))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this old function do anything extra (like set URL parameters)?

Does it matter that the old code sometimes returns something and the new code doesn't?

Copy link
Collaborator Author

@JazzarKarim JazzarKarim Dec 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I changed this Sev to use the new window.location.href only if the URL has a token.

What the old one is doing basically is the same as the new one except for the fact that window.location.href = localePath('/') causes a full page reload which is needed in this case.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this still needed?

}
Expand Down
12 changes: 12 additions & 0 deletions business-registry-dashboard/app/middleware/02.magic-link.global.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export default defineNuxtRouteMiddleware((to) => {
const localePath = useLocalePath()

// Check if path contains affiliationInvitation and extract token
if (to.path.includes('affiliationInvitation/acceptToken/')) {
const token = to.path.split('acceptToken/')[1]
if (token) {
sessionStorage.setItem('affiliationToken', token)
}
window.location.href = localePath('/')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, if the path contains a token then you save it to session storage and then reload everything?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, exactly.

Copy link
Collaborator

@severinbeauvais severinbeauvais Dec 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why so complicated? Why can't the token be handled directly? Why is a reload needed? Could you just push a new route?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because any route that is not that the main route will give a page 404 error:
image

Whenever that link is pressed, we will get an error if we don't handle it using a middleware or something else. It's not possible to handle it from the index.vue file directly as we won't even make it to that file.

When I tried handling that via an actual route, I was getting that error as well since the email returned has a double slash //. The browser was standardizing the URL and removing org ID part. It's a weird thing really. That's why I moved away from that design as I tried countless things but couldn't manage to deal with all the edge cases properly.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shouldn't be an issue now

Copy link
Collaborator

@severinbeauvais severinbeauvais Dec 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I love the new design!

Please resolve this conversation.

I want to understand the new design.

}
})

This file was deleted.

73 changes: 73 additions & 0 deletions business-registry-dashboard/app/pages/index.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,80 @@
<script setup lang="ts">
import { StatusCodes } from 'http-status-codes'

const { t } = useI18n()
const affStore = useAffiliationsStore()
const brdModal = useBrdModals()
const toast = useToast()

definePageMeta({
order: 0
})

// Token parsing
const parseToken = (encodedToken: string): AffiliationToken => {
try {
const tokenObject = encodedToken.split('.')[0]
const decoded = atob(tokenObject as string)
return JSON.parse(decoded)
} catch (error) {
console.error('Failed to parse token:', error)
throw new Error('Invalid token format')
}
}

onMounted(async () => {
// Check for affiliation token from session storage
if (sessionStorage.getItem('affiliationToken')) {
const affiliationToken = sessionStorage.getItem('affiliationToken') as string
// Remove the token from session storage after it's used
sessionStorage.removeItem('affiliationToken')
try {
const parsedToken = parseToken(affiliationToken)
// Parse the URL and try to add the affiliation
parseUrlAndAddAffiliation(parsedToken, affiliationToken)
// Load affiliations to update the table
await affStore.loadAffiliations()
} catch (e) {
console.error('Error accepting affiliation invitation:', e)
}
}
})
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't love this design of "check URL parameters + set session storage + reload + check session storage + handle token". It feels complicated and I keep thinking there are edge cases.

Can you check this design with someone else, like Travis?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, will check with Travis now and see what he thinks.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shouldn't be an issue now

Copy link
Collaborator

@severinbeauvais severinbeauvais Dec 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I love the new design!

Please resolve this conversation.

So what's the new design? Does it still update the URL, reload everything, etc?


// Function to parse the URL and extract the parameters, used for magic link email
const parseUrlAndAddAffiliation = async (token: any, base64Token: string) => {
const { businessIdentifier: identifier, id: invitationId } = token

try {
// 1. Accept invitation
const response = await affiliationInvitationService.acceptInvitation(invitationId, base64Token)

// 2. Adding magic link success
if (response.status === AffiliationInvitationStatus.Accepted) {
toast.add({ title: t('modal.manageBusiness.success.toast', { identifier }) }) // add success toast
}
} catch (error: any) {
console.error(error)
// 3. Unauthorized
if (error.response?.status === StatusCodes.UNAUTHORIZED) {
brdModal.openMagicLinkModal(t('error.magicLinkUnauthorized.title'), t('error.magicLinkUnauthorized.description'))
return
}
// 4. Expired
if (error.response?.status === StatusCodes.BAD_REQUEST &&
error.response?._data.code === MagicLinkInvitationStatus.EXPIRED_AFFILIATION_INVITATION) {
brdModal.openMagicLinkModal(t('error.magicLinkExpired.title'), t('error.magicLinkExpired.description', { identifier }))
return
}
// 5. Already Added
if (error.response?.status === StatusCodes.BAD_REQUEST &&
error.response?._data.code === MagicLinkInvitationStatus.ACTIONED_AFFILIATION_INVITATION) {
brdModal.openMagicLinkModal(t('error.magicLinkAlreadyAdded.title'), t('error.magicLinkAlreadyAdded.description', { identifier }))
return
}
// 6. Generic Error
brdModal.openBusinessAddError()
}
}
</script>
<template>
<NuxtLayout name="dashboard">
Expand Down
2 changes: 1 addition & 1 deletion business-registry-dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "business-registry-dashboard",
"private": true,
"type": "module",
"version": "0.0.4",
"version": "0.0.5",
"scripts": {
"build-check": "nuxt build",
"build": "nuxt generate",
Expand Down
84 changes: 0 additions & 84 deletions business-registry-dashboard/tests/unit/pages/[token].test.ts

This file was deleted.

35 changes: 34 additions & 1 deletion business-registry-dashboard/tests/unit/pages/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { describe, it, expect } from 'vitest'
import { describe, it, expect, vi } from 'vitest'
import { BusinessLookup, TableAffiliatedEntity } from '#components'
import Dashboard from '~/layouts/dashboard.vue'
import { enI18n } from '~~/tests/mocks/i18n'
import Index from '~/pages/index.vue'

// Sample parsed token data structure for testing
const mockParsedToken = {
fromOrgId: '12345',
businessIdentifier: 'BC12345',
id: '87654'
}

describe('Index Page', () => {
function mountPage () {
return mountSuspended(Index, {
Expand All @@ -29,4 +36,30 @@ describe('Index Page', () => {
expect(wrapper.findComponent(BusinessLookup).exists()).toBe(true)
expect(wrapper.findComponent(TableAffiliatedEntity).exists()).toBe(true)
})

describe('Token Parsing', () => {
it('successfully parses a valid token', async () => {
const wrapper = await mountPage()
const component = wrapper.vm as any

// Mock parseToken to return expected data structure
vi.spyOn(component, 'parseToken').mockReturnValue(mockParsedToken)

const token = component.parseToken('dummy-token')
expect(token).toEqual(mockParsedToken)
})

it('throws error for invalid token', async () => {
const wrapper = await mountPage()
const component = wrapper.vm as any

// Mock parseToken to simulate parsing failure
vi.spyOn(component, 'parseToken').mockImplementation(() => {
throw new Error('Invalid token format')
})

expect(() => component.parseToken('invalid-token'))
.toThrow('Invalid token format')
})
})
})
Loading