Make auth/admin apps API calls use apiFetch, a new function that asks for permission by iframe if needed. Implement max-age checks for API authz.verify as well along with a custom exception type that carries metadata.

This commit is contained in:
2025-12-03 23:17:02 +00:00
parent deabee3b5c
commit 547a6cd923
15 changed files with 411 additions and 147 deletions
+14 -12
View File
@@ -5,6 +5,7 @@ import CredentialList from '@/components/CredentialList.vue'
import RegistrationLinkModal from '@/components/RegistrationLinkModal.vue'
import SessionList from '@/components/SessionList.vue'
import { useAuthStore } from '@/stores/auth'
import { apiFetch } from '@/utils/api'
const props = defineProps({
selectedUser: Object,
@@ -27,17 +28,18 @@ function handleEditName() {
emit('editUserName', props.selectedUser)
}
function handleDelete(credential) {
fetch(`/auth/api/admin/orgs/${props.selectedUser.org_uuid}/users/${props.selectedUser.uuid}/credentials/${credential.credential_uuid}`, { method: 'DELETE' })
.then(res => res.json())
.then(data => {
if (data.status === 'ok') {
emit('onUserNameSaved') // Reuse to refresh user detail
} else {
console.error('Failed to delete credential', data)
}
})
.catch(err => console.error('Delete credential error', err))
async function handleDelete(credential) {
try {
const res = await apiFetch(`/auth/api/admin/orgs/${props.selectedUser.org_uuid}/users/${props.selectedUser.uuid}/credentials/${credential.credential_uuid}`, { method: 'DELETE' })
const data = await res.json()
if (data.status === 'ok') {
emit('onUserNameSaved') // Reuse to refresh user detail
} else {
console.error('Failed to delete credential', data)
}
} catch (err) {
console.error('Delete credential error', err)
}
}
async function handleTerminateSession(session) {
@@ -45,7 +47,7 @@ async function handleTerminateSession(session) {
if (!sessionId) return
terminatingSessions.value = { ...terminatingSessions.value, [sessionId]: true }
try {
const res = await fetch(`/auth/api/admin/orgs/${props.selectedUser.org_uuid}/users/${props.selectedUser.uuid}/sessions/${sessionId}`, { method: 'DELETE' })
const res = await apiFetch(`/auth/api/admin/orgs/${props.selectedUser.org_uuid}/users/${props.selectedUser.uuid}/sessions/${sessionId}`, { method: 'DELETE' })
const data = await res.json()
if (data.status === 'ok') {
if (data.current_session_terminated) {
+2 -6
View File
@@ -101,6 +101,7 @@ import { useAuthStore } from '@/stores/auth'
import { adminUiPath, makeUiHref } from '@/utils/settings'
import passkey from '@/utils/passkey'
import { goBack } from '@/utils/helpers'
import { apiFetch } from '@/utils/api'
const authStore = useAuthStore()
const updateInterval = ref(null)
@@ -173,12 +174,7 @@ const saveName = async () => {
if (!name) { authStore.showMessage('Name cannot be empty', 'error'); return }
try {
saving.value = true
const res = await fetch('/auth/api/user/display-name', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name }) })
if (res.status === 401) {
authStore.authRequired = true
authStore.showMessage('Authentication required', 'error')
return
}
const res = await apiFetch('/auth/api/user/display-name', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name }) })
const data = await res.json()
if (!res.ok || data.detail) throw new Error(data.detail || 'Update failed')
showNameDialog.value = false
@@ -65,6 +65,7 @@ import { ref, onMounted, watch, computed, nextTick } from 'vue'
import QRCode from 'qrcode/lib/browser'
import { formatDate } from '@/utils/helpers'
import { useAuthStore } from '@/stores/auth'
import { apiFetch } from '@/utils/api'
const authStore = useAuthStore()
@@ -92,12 +93,7 @@ const expirationMessage = computed(() => {
async function fetchLink() {
try {
const res = await fetch(props.endpoint, { method: 'POST' })
if (res.status === 401) {
authStore.authRequired = true
emit('close')
return
}
const res = await apiFetch(props.endpoint, { method: 'POST' })
const data = await res.json()
if (data.detail) throw new Error(data.detail)
url.value = data.url
+11 -25
View File
@@ -1,13 +1,13 @@
import { defineStore } from 'pinia'
import { register, authenticate } from '@/utils/passkey'
import { getSettings } from '@/utils/settings'
import { apiFetch } from '@/utils/api'
export const useAuthStore = defineStore('auth', {
state: () => ({
// Auth State
userInfo: null, // Contains the full user info response: {user, credentials, aaguid_info}
isLoading: false,
authRequired: false, // Flag to trigger auth iframe
// Settings
settings: null,
@@ -26,9 +26,6 @@ export const useAuthStore = defineStore('auth', {
setLoading(flag) {
this.isLoading = !!flag
},
clearAuthRequired() {
this.authRequired = false
},
showMessage(message, type = 'info', duration = 3000) {
this.status = {
message,
@@ -86,43 +83,32 @@ export const useAuthStore = defineStore('auth', {
this.settings = await getSettings()
},
async loadUserInfo() {
const response = await fetch('/auth/api/user-info', { method: 'POST' })
const response = await apiFetch('/auth/api/user-info', { method: 'POST' })
let result = null
try {
result = await response.json()
} catch (_) {
// ignore JSON parse errors (unlikely)
}
if (response.status === 401) {
this.authRequired = true
throw new Error(result?.detail || 'Authentication required')
}
if (result?.detail) {
// Other error style
this.showMessage(result.detail, 'error', 5000)
throw new Error(result.detail)
if (!response.ok || result?.detail) {
const message = result?.detail || 'Failed to load user info'
this.showMessage(message, 'error', 5000)
throw new Error(message)
}
this.userInfo = result
console.log('User info loaded:', result)
},
async deleteCredential(uuid) {
const response = await fetch(`/auth/api/user/credential/${uuid}`, {method: 'Delete'})
if (response.status === 401) {
this.authRequired = true
throw new Error('Authentication required')
}
const response = await apiFetch(`/auth/api/user/credential/${uuid}`, { method: 'DELETE' })
const result = await response.json()
if (result.detail) throw new Error(result.detail)
if (!response.ok || result.detail) {
throw new Error(result.detail || 'Failed to delete credential')
}
await this.loadUserInfo()
},
async terminateSession(sessionId) {
try {
const res = await fetch(`/auth/api/user/session/${sessionId}`, { method: 'DELETE' })
if (res.status === 401) {
this.authRequired = true
throw new Error('Authentication required')
}
const res = await apiFetch(`/auth/api/user/session/${sessionId}`, { method: 'DELETE' })
let payload = null
try {
payload = await res.json()
+163
View File
@@ -0,0 +1,163 @@
/**
* API fetch wrapper that handles authentication errors with iframe-based re-authentication.
*
* When a 401 or 403 response is received with an `auth` object containing `iframe` URL,
* this wrapper shows an authentication iframe and retries the original request after
* successful authentication.
*/
let authIframe = null
let authPromise = null
let authResolve = null
let authReject = null
/**
* Show the authentication iframe and return a promise that resolves on success.
* @param {string} iframeSrc - The URL for the iframe src
* @returns {Promise<void>}
*/
function showAuthIframe(iframeSrc) {
// If already showing auth, return existing promise
if (authPromise) return authPromise
authPromise = new Promise((resolve, reject) => {
authResolve = resolve
authReject = reject
})
// Remove existing iframe if any
hideAuthIframe()
// Create new iframe for authentication
authIframe = document.createElement('iframe')
authIframe.id = 'auth-iframe'
authIframe.title = 'Authentication'
authIframe.src = iframeSrc
document.body.appendChild(authIframe)
return authPromise
}
function hideAuthIframe() {
if (authIframe) {
authIframe.remove()
authIframe = null
}
}
function handleAuthMessage(event) {
const data = event.data
if (!data?.type) return
switch (data.type) {
case 'auth-success':
hideAuthIframe()
if (authResolve) {
authResolve()
authPromise = null
authResolve = null
authReject = null
}
break
case 'auth-back':
case 'auth-close-request':
hideAuthIframe()
if (authReject) {
authReject(new Error('Authentication cancelled'))
authPromise = null
authResolve = null
authReject = null
}
break
case 'auth-error':
// Keep iframe open for retry, but if cancelled, treat as back
if (data.cancelled && authReject) {
hideAuthIframe()
authReject(new Error('Authentication cancelled'))
authPromise = null
authResolve = null
authReject = null
}
break
}
}
// Install global message listener
if (typeof window !== 'undefined') {
window.addEventListener('message', handleAuthMessage)
}
/**
* Fetch wrapper that handles auth errors with iframe-based re-authentication.
*
* @param {string|URL} url - The URL to fetch
* @param {RequestInit} [options] - Fetch options
* @returns {Promise<Response>} - The fetch response
* @throws {Error} - If authentication is cancelled or fails
*/
export async function apiFetch(url, options = {}) {
// Ensure credentials are included for cookie-based auth
const fetchOptions = {
...options,
credentials: options.credentials || 'include',
}
const response = await fetch(url, fetchOptions)
// Check for auth errors (401/403)
if (response.status === 401 || response.status === 403) {
// Try to parse the response to get the iframe URL
let authInfo = null
try {
const data = await response.clone().json()
authInfo = data.auth
} catch {
// If we can't parse JSON, fall back to default iframe URL
}
if (authInfo?.iframe) {
// Show auth iframe and wait for success
await showAuthIframe(authInfo.iframe)
// Retry the original request
return fetch(url, fetchOptions)
}
}
return response
}
/**
* Convenience method for JSON API calls.
* Automatically sets Content-Type for POST/PUT/PATCH with body.
*
* @param {string|URL} url - The URL to fetch
* @param {RequestInit} [options] - Fetch options
* @returns {Promise<any>} - Parsed JSON response
* @throws {Error} - If response has error detail or auth fails
*/
export async function apiJson(url, options = {}) {
const fetchOptions = { ...options }
// Set Content-Type for requests with JSON body
if (fetchOptions.body && typeof fetchOptions.body === 'object' && !(fetchOptions.body instanceof FormData)) {
fetchOptions.headers = {
'Content-Type': 'application/json',
...fetchOptions.headers,
}
fetchOptions.body = JSON.stringify(fetchOptions.body)
}
const response = await apiFetch(url, fetchOptions)
const data = await response.json()
if (!response.ok || data.detail) {
throw new Error(data.detail || `Request failed: ${response.status}`)
}
return data
}
export default apiFetch