Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,17 @@
:change-avatar="changeAvatar"
:delete-avatar="deleteAvatar"
:get-authenticated-user="getAuthenticatedUser"
:change-username="openUsernameSettings"
@profile-link-click="handleProfileLinkClick"
/>
</template>

<script setup lang="ts">
import type { Labrinth } from '@modrinth/api-client'
import { AccountProfileSettings, injectAuth } from '@modrinth/ui'
import { AccountProfileSettings, injectAuth, injectPageContext } from '@modrinth/ui'
import { onBeforeUnmount, onMounted, ref } from 'vue'

import { config } from '@/config'
import { injectAppSettingsModal } from '@/features/settings/app-settings-modal/context'
import {
change_user_avatar,
Expand All @@ -24,6 +26,11 @@ import {

const settingsModal = injectAppSettingsModal()
const auth = injectAuth()
const { openExternalUrl } = injectPageContext()

function openUsernameSettings(): void {
openExternalUrl(`${config.siteUrl}/settings/profile`)
}
const profileSettings = ref<InstanceType<typeof AccountProfileSettings> | null>(null)

onMounted(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ import { useQuery } from '@tanstack/vue-query'
import { useClipboard } from '@vueuse/core'
import { computed, ref } from 'vue'

import { runPrivileged } from '~/composables/reauth.ts'

defineOptions({ inheritAttrs: false })

const props = withDefaults(defineProps<{ user: Labrinth.Users.v3.User; size?: 'xs' | 'sm' }>(), {
Expand All @@ -74,8 +76,13 @@ provideUserProfile({
getProjects: (id: string) => client.labrinth.users_v3.getProjects(id),
getOrganizations: (id: string) => client.labrinth.users_v2.getOrganizations(id),
getCollections: (id: string) => client.labrinth.users_v2.getCollections(id),
patchUser: (id: string, patch: Parameters<UserProfileContext['patchUser']>[1]) =>
client.labrinth.users_v2.patch(id, patch),
patchUser: (id: string, patch: Parameters<UserProfileContext['patchUser']>[1]) => {
const request = () => client.labrinth.users_v2.patch(id, patch)
if (patch.username != null) {
return runPrivileged(request)
}
return request()
},
changeAvatar: (id: string, file: Blob, extension: string) =>
client.labrinth.users_v2.changeIcon(id, file, extension),
deleteAvatar: (id: string) => client.labrinth.users_v2.deleteIcon(id),
Expand Down
38 changes: 25 additions & 13 deletions apps/frontend/src/components/ui/auth/PasskeySettings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ import {
} from '@modrinth/ui'
import { computed, ref, useTemplateRef } from 'vue'

import { isReauthCancelled, runPrivileged } from '~/composables/reauth.ts'
import { createPasskeyCredential } from '~/helpers/passkey.ts'

const { labrinth } = injectModrinthClient()
Expand All @@ -230,6 +231,9 @@ const formatDateTime = useFormatDateTime({
})

function notifyError(err: unknown) {
if (isReauthCancelled(err)) {
return
}
addNotification({
title: formatMessage(commonMessages.errorNotificationTitle),
text: err instanceof Error ? err.message : String(err),
Expand Down Expand Up @@ -356,16 +360,19 @@ async function showPasskeyModal() {
async function registerPasskey() {
startLoading()
try {
const res = await labrinth.auth_v2.registerPasskeyStart()
await runPrivileged(async () => {
const res = await labrinth.auth_v2.registerPasskeyStart()

const credential = await createPasskeyCredential(res.options.publicKey)
pendingPasskey.value = {
flow: res.flow,
credential: credential,
name: '',
const credential = await createPasskeyCredential(res.options.publicKey)
pendingPasskey.value = {
flow: res.flow,
credential: credential,
name: '',
}
})
if (pendingPasskey.value) {
addPasskeyModal.value?.show()
}

addPasskeyModal.value?.show()
} catch (err) {
notifyError(err)
}
Expand All @@ -377,10 +384,15 @@ async function finishRegisterPasskey() {

startLoading()
try {
const passkey = await labrinth.auth_v2.registerPasskeyFinish(pendingPasskey.value)
passkeys.value.unshift(passkey)
pendingPasskey.value = null
addPasskeyModal.value?.hide()
await runPrivileged(async () => {
if (!pendingPasskey.value) {
return
}
const passkey = await labrinth.auth_v2.registerPasskeyFinish(pendingPasskey.value)
passkeys.value.unshift(passkey)
pendingPasskey.value = null
addPasskeyModal.value?.hide()
})
} catch (err) {
notifyError(err)
}
Expand Down Expand Up @@ -412,7 +424,7 @@ async function removePasskey() {

startLoading()
try {
await labrinth.auth_v2.deletePasskey(id)
await runPrivileged(() => labrinth.auth_v2.deletePasskey(id))
passkeys.value = passkeys.value.filter((passkey) => passkey.id !== id)
passkeyToRemove.value = null
} catch (err) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ import Turnstile from '@/components/ui/auth/Turnstile.vue'
import TwoFactorAuthCodeInput from '@/components/ui/auth/TwoFactorAuthCodeInput.vue'
import {
hydrateStoredAccounts,
rememberSessionCreated,
rememberStoredAccount,
setPendingAuthMethod,
type StoredAccountAuthMethod,
Expand All @@ -227,6 +228,11 @@ const client = injectModrinthClient()
const queryClient = useQueryClient()
const { addNotification } = injectNotificationManager()
const { formatMessage } = useVIntl()
const props = defineProps<{
accountId?: string
redirect?: string
}>()

const route = useAuthRoute()
const { go } = useAuthNavigation()
const embedded = isAuthEmbedded()
Expand Down Expand Up @@ -275,11 +281,32 @@ const messages = defineMessages({

useAuthPageTitle(() => formatMessage(messages.pageTitle))

const accountId = computed(() => authQueryString(route.query.account))
const account = computed(() => storedAccounts.value.find((stored) => stored.id === accountId.value))
const signedIn = await useAuth()
const accountId = computed(
() => props.accountId || authQueryString(route.query.account) || signedIn.value.user?.id || '',
)
const account = computed(() => {
const stored = storedAccounts.value.find((item) => item.id === accountId.value)
if (stored) {
return stored
}
const user = signedIn.value.user
if (!user || user.id !== accountId.value) {
return null
}
return {
id: user.id,
username: user.username,
avatarUrl: user.avatar_url,
token: signedIn.value.token,
authMethod: undefined,
}
})
const redirectTarget = computed(
() =>
props.redirect ||
authQueryString(route.query.redirect) ||
(route.path !== '/auth/reauthenticate' ? route.fullPath : '') ||
(account.value ? `/user/${account.value.username}` : ''),
)
const loginIdentifier = computed(() => account.value?.username || '')
Expand Down Expand Up @@ -331,7 +358,14 @@ function onOAuthProviderClick(provider: OAuthProviderId, event: MouseEvent) {
})
}

async function completeSignIn(sessionToken: string, authMethod: StoredAccountAuthMethod) {
async function completeSignIn(
sessionToken: string,
authMethod: StoredAccountAuthMethod,
created?: string,
) {
if (created) {
rememberSessionCreated(sessionToken, created)
}
await useAuth(sessionToken)
await useUser()
await queryClient.resetQueries()
Expand Down Expand Up @@ -367,7 +401,7 @@ async function beginPasswordSignIn() {
if (res.flow) {
flow.value = res.flow
} else if (res.session) {
await completeSignIn(res.session, 'password')
await completeSignIn(res.session, 'password', res.created)
}
} catch (err) {
notifyError(err)
Expand All @@ -387,7 +421,7 @@ async function begin2FASignIn(code: string) {
flow: flow.value,
code,
})
await completeSignIn(res.session, 'password')
await completeSignIn(res.session, 'password', res.created)
} catch {
twoFactorCode.value = ''
twoFactorError.value = true
Expand All @@ -411,7 +445,7 @@ async function beginPasskeySignIn() {
credential,
})
setPendingAuthMethod('passkey')
await completeSignIn(result.session, 'passkey')
await completeSignIn(result.session, 'passkey', result.created)
} catch (err) {
notifyError(err)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ import {
import CreateAccountView from '@/components/ui/auth/CreateAccount.vue'
import LauncherOpening from '@/components/ui/auth/LauncherOpening.vue'
import SignUpView from '@/components/ui/auth/SignUp.vue'
import { setPendingAuthMethod, useLastSignInAuthMethod } from '@/composables/accounts.ts'
import {
rememberSessionCreated,
setPendingAuthMethod,
useLastSignInAuthMethod,
} from '@/composables/accounts.ts'
import { promotePendingSignInOAuthProvider } from '@/composables/auth.ts'
import { authQueryString, getAuthErrorMessage } from '@/composables/auth-form.ts'
import { finishAuth, useAuthPageTitle, useAuthRoute } from '@/composables/auth-modal.ts'
Expand Down Expand Up @@ -225,6 +229,7 @@ async function createAccount(accountConsent: boolean) {
app_session: isProtocolV2,
})
rememberSessionCreated(res.session, res.created)
await useAuth(res.session)
await useUser()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ import {
type WithdrawStage,
} from '@/providers/creator-withdraw.ts'
import { useGeneratedState } from '~/composables/generated'
import { isReauthCancelled } from '~/composables/reauth.ts'
import CreatorTaxFormModal from './CreatorTaxFormModal.vue'
import CompletionStage from './withdraw-stages/CompletionStage.vue'
Expand Down Expand Up @@ -540,6 +541,9 @@ async function handleWithdraw() {
await submitWithdrawal()
setStage('completion')
} catch (error) {
if (isReauthCancelled(error)) {
return
}
console.error('Withdrawal failed:', error)
const { title, text, supportData } = getWithdrawalError(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
v-if="!isPayPalAuthenticated"
:href="paypalAuthUrl"
class="w-min"
@click="handlePayPalAuth"
@click.prevent="handlePayPalAuth"
>
<PayPalColorIcon class="size-5" />
{{ formatMessage(messages.signInWithPaypal) }}
Expand Down Expand Up @@ -122,7 +122,9 @@ import { computed, onMounted, ref, watch } from 'vue'
import RevenueInputField from '@/components/ui/dashboard/RevenueInputField.vue'
import WithdrawFeeBreakdown from '@/components/ui/dashboard/WithdrawFeeBreakdown.vue'
import { getAuthUrl, removeAuthProvider, useAuth } from '@/composables/auth.ts'
import { isSessionYoung } from '@/composables/accounts.ts'
import { getAuthUrl, removeAuthProvider, useAuth, useAuthState } from '@/composables/auth.ts'
import { isReauthCancelled, requestReauth } from '@/composables/reauth.ts'
import { useWithdrawContext } from '@/providers/creator-withdraw.ts'
const { withdrawData, maxWithdrawAmount, availableMethods, calculateFees, saveStateToStorage } =
Expand All @@ -147,22 +149,42 @@ const paypalEmail = computed(() => {
return (auth.value.user as any)?.payout_data?.paypal_address || ''
})
const paypalAuthUrl = computed(() => {
function paypalReturnUrl() {
const route = useRoute()
const authToken = useCookie('auth-token')
const separator = route.fullPath.includes('?') ? '&' : '?'
const returnUrl = `${route.fullPath}${separator}paypal_auth_return=true`
return `${getAuthUrl('paypal', returnUrl)}&auth_token=${authToken.value}`
return `${route.fullPath}${separator}paypal_auth_return=true`
}
const paypalAuthUrl = computed(() => {
const authToken = useCookie('auth-token')
return `${getAuthUrl('paypal', paypalReturnUrl())}&auth_token=${authToken.value}`
})
function handlePayPalAuth() {
async function handlePayPalAuth() {
let token = useAuthState().value.token
const authUrl = getAuthUrl('paypal', paypalReturnUrl())
if (isSessionYoung(token) !== true) {
try {
await requestReauth()
} catch (error) {
if (isReauthCancelled(error)) {
return
}
throw error
}
token = useAuthState().value.token
}
saveStateToStorage()
window.location.href = `${authUrl}&auth_token=${token}`
}
async function handleDisconnectPaypal() {
try {
await removeAuthProvider('paypal')
} catch (error) {
if (isReauthCancelled(error)) {
return
}
console.error('Failed to disconnect PayPal:', error)
}
}
Expand Down
Loading
Loading