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:
+2
-14
@@ -10,7 +10,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import StatusMessage from '@/components/StatusMessage.vue'
|
||||
import ProfileView from '@/components/ProfileView.vue'
|
||||
@@ -25,17 +25,6 @@ const showBackMessage = ref(false)
|
||||
let validationTimer = null
|
||||
let authIframe = null
|
||||
|
||||
// Watch for auth required flag from store
|
||||
watch(() => store.authRequired, (required) => {
|
||||
if (required) {
|
||||
authenticated.value = false
|
||||
loading.value = true
|
||||
stopSessionValidation()
|
||||
showAuthIframe()
|
||||
store.clearAuthRequired()
|
||||
}
|
||||
})
|
||||
|
||||
async function tryLoadUserInfo() {
|
||||
try {
|
||||
await store.loadUserInfo()
|
||||
@@ -44,7 +33,7 @@ async function tryLoadUserInfo() {
|
||||
startSessionValidation()
|
||||
return true
|
||||
} catch (error) {
|
||||
// User info load failed - likely 401
|
||||
// User info load failed - apiFetch will show iframe if needed
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -83,7 +72,6 @@ function handleAuthMessage(event) {
|
||||
hideAuthIframe()
|
||||
loading.value = true
|
||||
loadingMessage.value = 'Loading user profile...'
|
||||
store.clearAuthRequired()
|
||||
tryLoadUserInfo()
|
||||
break
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import AdminUserDetail from '@/admin/AdminUserDetail.vue'
|
||||
import AdminDialogs from '@/admin/AdminDialogs.vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { getSettings, adminUiPath, makeUiHref } from '@/utils/settings'
|
||||
import { apiFetch } from '@/utils/api'
|
||||
|
||||
const info = ref(null)
|
||||
const loading = ref(true)
|
||||
@@ -38,15 +39,6 @@ const dialog = ref({ type: null, data: null, busy: false, error: '' })
|
||||
const safeIdRegex = /[^A-Za-z0-9:._~-]/g
|
||||
let authIframe = null
|
||||
|
||||
watch(() => authStore.authRequired, (required) => {
|
||||
if (required) {
|
||||
authenticated.value = false
|
||||
loading.value = true
|
||||
showAuthIframe()
|
||||
authStore.clearAuthRequired()
|
||||
}
|
||||
})
|
||||
|
||||
function sanitizeRenameId() { if (renameIdValue.value) renameIdValue.value = renameIdValue.value.replace(safeIdRegex, '') }
|
||||
|
||||
function handleGlobalClick(e) {
|
||||
@@ -114,7 +106,7 @@ async function attachPermissionToOrg(pid, orgUuid) {
|
||||
if (!orgUuid) return
|
||||
try {
|
||||
const params = new URLSearchParams({ permission_id: pid })
|
||||
const res = await fetch(`/auth/api/admin/orgs/${orgUuid}/permission?${params.toString()}`, { method: 'POST' })
|
||||
const res = await apiFetch(`/auth/api/admin/orgs/${orgUuid}/permission?${params.toString()}`, { method: 'POST' })
|
||||
const data = await res.json()
|
||||
if (data.detail) throw new Error(data.detail)
|
||||
await loadOrgs()
|
||||
@@ -127,7 +119,7 @@ async function detachPermissionFromOrg(pid, orgUuid) {
|
||||
openDialog('confirm', { message: 'Remove permission from this org?', action: async () => {
|
||||
try {
|
||||
const params = new URLSearchParams({ permission_id: pid })
|
||||
const res = await fetch(`/auth/api/admin/orgs/${orgUuid}/permission?${params.toString()}`, { method: 'DELETE' })
|
||||
const res = await apiFetch(`/auth/api/admin/orgs/${orgUuid}/permission?${params.toString()}`, { method: 'DELETE' })
|
||||
const data = await res.json()
|
||||
if (data.detail) throw new Error(data.detail)
|
||||
await loadOrgs()
|
||||
@@ -149,11 +141,7 @@ function parseHash() {
|
||||
}
|
||||
|
||||
async function loadOrgs() {
|
||||
const res = await fetch('/auth/api/admin/orgs')
|
||||
if (res.status === 401) {
|
||||
authStore.authRequired = true
|
||||
throw new Error('Authentication required')
|
||||
}
|
||||
const res = await apiFetch('/auth/api/admin/orgs')
|
||||
const data = await res.json()
|
||||
if (data.detail) throw new Error(data.detail)
|
||||
orgs.value = data.map(o => {
|
||||
@@ -167,11 +155,7 @@ async function loadOrgs() {
|
||||
}
|
||||
|
||||
async function loadPermissions() {
|
||||
const res = await fetch('/auth/api/admin/permissions')
|
||||
if (res.status === 401) {
|
||||
authStore.authRequired = true
|
||||
throw new Error('Authentication required')
|
||||
}
|
||||
const res = await apiFetch('/auth/api/admin/permissions')
|
||||
const data = await res.json()
|
||||
if (data.detail) throw new Error(data.detail)
|
||||
permissions.value = data
|
||||
@@ -182,12 +166,7 @@ async function load() {
|
||||
loadingMessage.value = 'Loading...'
|
||||
error.value = null
|
||||
try {
|
||||
const res = await fetch('/auth/api/user-info', { method: 'POST' })
|
||||
if (res.status === 401) {
|
||||
authStore.authRequired = true
|
||||
loading.value = true
|
||||
return
|
||||
}
|
||||
const res = await apiFetch('/auth/api/user-info', { method: 'POST' })
|
||||
const data = await res.json()
|
||||
if (data.detail) throw new Error(data.detail)
|
||||
info.value = data
|
||||
@@ -195,9 +174,9 @@ async function load() {
|
||||
|
||||
// Check if user has required permissions
|
||||
if (data.authenticated && !(data.is_global_admin || data.is_org_admin)) {
|
||||
// User is authenticated but lacks required permissions - show auth iframe
|
||||
authStore.authRequired = true
|
||||
loading.value = true
|
||||
// User is authenticated but lacks required permissions - show forbidden view
|
||||
error.value = 'You do not have permission to access this area.'
|
||||
loading.value = false
|
||||
return
|
||||
}
|
||||
|
||||
@@ -230,7 +209,7 @@ function editUserName(user) { openDialog('user-update-name', { user, name: user.
|
||||
function deleteOrg(org) {
|
||||
if (!info.value?.is_global_admin) { authStore.showMessage('Global admin only'); return }
|
||||
openDialog('confirm', { message: `Delete organization ${org.display_name}?`, action: async () => {
|
||||
const res = await fetch(`/auth/api/admin/orgs/${org.uuid}`, { method: 'DELETE' })
|
||||
const res = await apiFetch(`/auth/api/admin/orgs/${org.uuid}`, { method: 'DELETE' })
|
||||
const data = await res.json(); if (data.detail) throw new Error(data.detail)
|
||||
await Promise.all([loadOrgs(), loadPermissions()])
|
||||
} })
|
||||
@@ -240,7 +219,7 @@ function createUserInRole(org, role) { openDialog('user-create', { org, role })
|
||||
|
||||
async function moveUserToRole(org, user, targetRoleDisplayName) {
|
||||
if (user.role === targetRoleDisplayName) return
|
||||
const res = await fetch(`/auth/api/admin/orgs/${org.uuid}/users/${user.uuid}/role`, {
|
||||
const res = await apiFetch(`/auth/api/admin/orgs/${org.uuid}/users/${user.uuid}/role`, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ role: targetRoleDisplayName })
|
||||
@@ -282,7 +261,7 @@ function updateRole(role) { openDialog('role-update', { role, name: role.display
|
||||
|
||||
function deleteRole(role) {
|
||||
openDialog('confirm', { message: `Delete role ${role.display_name}?`, action: async () => {
|
||||
const res = await fetch(`/auth/api/admin/orgs/${role.org_uuid}/roles/${role.uuid}`, { method: 'DELETE' })
|
||||
const res = await apiFetch(`/auth/api/admin/orgs/${role.org_uuid}/roles/${role.uuid}`, { method: 'DELETE' })
|
||||
const data = await res.json(); if (data.detail) throw new Error(data.detail)
|
||||
await loadOrgs()
|
||||
} })
|
||||
@@ -299,7 +278,7 @@ async function toggleRolePermission(role, pid, checked) {
|
||||
role.permissions = newPermissions
|
||||
|
||||
try {
|
||||
const res = await fetch(`/auth/api/admin/orgs/${role.org_uuid}/roles/${role.uuid}`, {
|
||||
const res = await apiFetch(`/auth/api/admin/orgs/${role.org_uuid}/roles/${role.uuid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ display_name: role.display_name, permissions: newPermissions })
|
||||
@@ -319,7 +298,7 @@ function updatePermission(p) { openDialog('perm-display', { permission: p }) }
|
||||
function deletePermission(p) {
|
||||
openDialog('confirm', { message: `Delete permission ${p.id}?`, action: async () => {
|
||||
const params = new URLSearchParams({ permission_id: p.id })
|
||||
const res = await fetch(`/auth/api/admin/permission?${params.toString()}`, { method: 'DELETE' })
|
||||
const res = await apiFetch(`/auth/api/admin/permission?${params.toString()}`, { method: 'DELETE' })
|
||||
const data = await res.json(); if (data.detail) throw new Error(data.detail)
|
||||
await loadPermissions()
|
||||
} })
|
||||
@@ -449,7 +428,7 @@ const breadcrumbEntries = computed(() => {
|
||||
watch(selectedUser, async (u) => {
|
||||
if (!u) { userDetail.value = null; return }
|
||||
try {
|
||||
const res = await fetch(`/auth/api/admin/orgs/${u.org_uuid}/users/${u.uuid}`)
|
||||
const res = await apiFetch(`/auth/api/admin/orgs/${u.org_uuid}/users/${u.uuid}`)
|
||||
const data = await res.json()
|
||||
if (data.detail) throw new Error(data.detail)
|
||||
userDetail.value = data
|
||||
@@ -488,7 +467,7 @@ async function toggleOrgPermission(org, permId, checked) {
|
||||
org.permissions = next
|
||||
try {
|
||||
const params = new URLSearchParams({ permission_id: permId })
|
||||
const res = await fetch(`/auth/api/admin/orgs/${org.uuid}/permission?${params.toString()}`, { method: checked ? 'POST' : 'DELETE' })
|
||||
const res = await apiFetch(`/auth/api/admin/orgs/${org.uuid}/permission?${params.toString()}`, { method: checked ? 'POST' : 'DELETE' })
|
||||
const data = await res.json()
|
||||
if (data.detail) throw new Error(data.detail)
|
||||
await loadOrgs()
|
||||
@@ -505,7 +484,7 @@ async function refreshUserDetail() {
|
||||
await loadOrgs()
|
||||
if (selectedUser.value) {
|
||||
try {
|
||||
const r = await fetch(`/auth/api/admin/orgs/${selectedUser.value.org_uuid}/users/${selectedUser.value.uuid}`)
|
||||
const r = await apiFetch(`/auth/api/admin/orgs/${selectedUser.value.org_uuid}/users/${selectedUser.value.uuid}`)
|
||||
const jd = await r.json()
|
||||
if (!r.ok || jd.detail) throw new Error(jd.detail || 'Reload failed')
|
||||
userDetail.value = jd
|
||||
@@ -525,27 +504,27 @@ async function submitDialog() {
|
||||
const t = dialog.value.type
|
||||
if (t === 'org-create') {
|
||||
const name = dialog.value.data.name?.trim(); if (!name) throw new Error('Name required')
|
||||
const res = await fetch('/auth/api/admin/orgs', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name, permissions: [] }) })
|
||||
const res = await apiFetch('/auth/api/admin/orgs', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name, permissions: [] }) })
|
||||
const d = await res.json(); if (d.detail) throw new Error(d.detail); await Promise.all([loadOrgs(), loadPermissions()])
|
||||
} else if (t === 'org-update') {
|
||||
const { org } = dialog.value.data; const name = dialog.value.data.name?.trim(); if (!name) throw new Error('Name required')
|
||||
const res = await fetch(`/auth/api/admin/orgs/${org.uuid}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name, permissions: org.permissions }) })
|
||||
const res = await apiFetch(`/auth/api/admin/orgs/${org.uuid}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name, permissions: org.permissions }) })
|
||||
const d = await res.json(); if (d.detail) throw new Error(d.detail); await loadOrgs()
|
||||
} else if (t === 'role-create') {
|
||||
const { org } = dialog.value.data; const name = dialog.value.data.name?.trim(); if (!name) throw new Error('Name required')
|
||||
const res = await fetch(`/auth/api/admin/orgs/${org.uuid}/roles`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name, permissions: [] }) })
|
||||
const res = await apiFetch(`/auth/api/admin/orgs/${org.uuid}/roles`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name, permissions: [] }) })
|
||||
const d = await res.json(); if (d.detail) throw new Error(d.detail); await loadOrgs()
|
||||
} else if (t === 'role-update') {
|
||||
const { role } = dialog.value.data; const name = dialog.value.data.name?.trim(); if (!name) throw new Error('Name required')
|
||||
const res = await fetch(`/auth/api/admin/orgs/${role.org_uuid}/roles/${role.uuid}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name, permissions: role.permissions }) })
|
||||
const res = await apiFetch(`/auth/api/admin/orgs/${role.org_uuid}/roles/${role.uuid}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name, permissions: role.permissions }) })
|
||||
const d = await res.json(); if (d.detail) throw new Error(d.detail); await loadOrgs()
|
||||
} else if (t === 'user-create') {
|
||||
const { org, role } = dialog.value.data; const name = dialog.value.data.name?.trim(); if (!name) throw new Error('Name required')
|
||||
const res = await fetch(`/auth/api/admin/orgs/${org.uuid}/users`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name, role: role.display_name }) })
|
||||
const res = await apiFetch(`/auth/api/admin/orgs/${org.uuid}/users`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name, role: role.display_name }) })
|
||||
const d = await res.json(); if (d.detail) throw new Error(d.detail); await loadOrgs()
|
||||
} else if (t === 'user-update-name') {
|
||||
const { user } = dialog.value.data; const name = dialog.value.data.name?.trim(); if (!name) throw new Error('Name required')
|
||||
const res = await fetch(`/auth/api/admin/orgs/${user.org_uuid}/users/${user.uuid}/display-name`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name }) })
|
||||
const res = await apiFetch(`/auth/api/admin/orgs/${user.org_uuid}/users/${user.uuid}/display-name`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ display_name: name }) })
|
||||
const d = await res.json(); if (d.detail) throw new Error(d.detail); await onUserNameSaved()
|
||||
} else if (t === 'perm-display') {
|
||||
const { permission } = dialog.value.data
|
||||
@@ -557,20 +536,20 @@ async function submitDialog() {
|
||||
if (newId !== permission.id) {
|
||||
// ID changed, use rename endpoint
|
||||
const body = { old_id: permission.id, new_id: newId, display_name: newDisplay }
|
||||
const res = await fetch('/auth/api/admin/permission/rename', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
const res = await apiFetch('/auth/api/admin/permission/rename', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
let data; try { data = await res.json() } catch(_) { data = {} }
|
||||
if (!res.ok || data.detail) throw new Error(data.detail || data.error || `Failed (${res.status})`)
|
||||
} else if (newDisplay !== permission.display_name) {
|
||||
// Only display name changed
|
||||
const params = new URLSearchParams({ permission_id: permission.id, display_name: newDisplay })
|
||||
const res = await fetch(`/auth/api/admin/permission?${params.toString()}`, { method: 'PUT' })
|
||||
const res = await apiFetch(`/auth/api/admin/permission?${params.toString()}`, { method: 'PUT' })
|
||||
const d = await res.json(); if (d.detail) throw new Error(d.detail)
|
||||
}
|
||||
await loadPermissions()
|
||||
} else if (t === 'perm-create') {
|
||||
const id = dialog.value.data.id?.trim(); if (!id) throw new Error('ID required')
|
||||
const display_name = dialog.value.data.display_name?.trim(); if (!display_name) throw new Error('Display name required')
|
||||
const res = await fetch('/auth/api/admin/permissions', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id, display_name }) })
|
||||
const res = await apiFetch('/auth/api/admin/permissions', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id, display_name }) })
|
||||
const data = await res.json(); if (data.detail) throw new Error(data.detail)
|
||||
await loadPermissions(); dialog.value.data.display_name = ''; dialog.value.data.id = ''
|
||||
} else if (t === 'confirm') {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
@@ -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()
|
||||
|
||||
@@ -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
|
||||
@@ -92,6 +92,7 @@ class SessionContext:
|
||||
user: User
|
||||
org: Org
|
||||
role: Role
|
||||
credential: Credential | None = None
|
||||
permissions: list[Permission] | None = None
|
||||
|
||||
|
||||
|
||||
+11
-3
@@ -1314,19 +1314,23 @@ class DB(DatabaseInterface):
|
||||
Uses efficient JOINs to retrieve all related data in a single database query.
|
||||
"""
|
||||
async with self.session() as session:
|
||||
# Build a query that joins sessions, users, roles, organizations, and role_permissions
|
||||
# Build a query that joins sessions, users, roles, organizations, credentials and role_permissions
|
||||
stmt = (
|
||||
select(
|
||||
SessionModel,
|
||||
UserModel,
|
||||
RoleModel,
|
||||
OrgModel,
|
||||
CredentialModel,
|
||||
PermissionModel,
|
||||
)
|
||||
.select_from(SessionModel)
|
||||
.join(UserModel, SessionModel.user_uuid == UserModel.uuid)
|
||||
.join(RoleModel, UserModel.role_uuid == RoleModel.uuid)
|
||||
.join(OrgModel, RoleModel.org_uuid == OrgModel.uuid)
|
||||
.outerjoin(
|
||||
CredentialModel, SessionModel.credential_uuid == CredentialModel.uuid
|
||||
)
|
||||
.outerjoin(RolePermission, RoleModel.uuid == RolePermission.role_uuid)
|
||||
.outerjoin(
|
||||
PermissionModel, RolePermission.permission_id == PermissionModel.id
|
||||
@@ -1342,7 +1346,7 @@ class DB(DatabaseInterface):
|
||||
|
||||
# Extract the first row to get session and user data
|
||||
first_row = rows[0]
|
||||
session_model, user_model, role_model, org_model, _ = first_row
|
||||
session_model, user_model, role_model, org_model, credential_model, _ = first_row
|
||||
|
||||
# Create the session object
|
||||
if host is not None:
|
||||
@@ -1371,11 +1375,14 @@ class DB(DatabaseInterface):
|
||||
display_name=role_model.display_name,
|
||||
)
|
||||
|
||||
# Create credential object if available
|
||||
credential_obj = credential_model.as_dataclass() if credential_model else None
|
||||
|
||||
# Collect all unique permissions for the role
|
||||
permissions = []
|
||||
seen_permission_ids = set()
|
||||
for row in rows:
|
||||
_, _, _, _, permission_model = row
|
||||
_, _, _, _, _, permission_model = row
|
||||
if permission_model and permission_model.id not in seen_permission_ids:
|
||||
permissions.append(
|
||||
Permission(
|
||||
@@ -1405,5 +1412,6 @@ class DB(DatabaseInterface):
|
||||
user=user_obj,
|
||||
org=organization,
|
||||
role=role,
|
||||
credential=credential_obj,
|
||||
permissions=effective_permissions if effective_permissions else None,
|
||||
)
|
||||
|
||||
@@ -28,6 +28,22 @@ async def value_error_handler(_request, exc: ValueError): # pragma: no cover -
|
||||
return JSONResponse(status_code=400, content={"detail": str(exc)})
|
||||
|
||||
|
||||
@app.exception_handler(authz.AuthException)
|
||||
async def auth_exception_handler(_request, exc: authz.AuthException):
|
||||
"""Handle AuthException with auth info for UI."""
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
"detail": exc.detail,
|
||||
"auth": {
|
||||
"mode": exc.mode,
|
||||
"iframe": f"/auth/restricted/?mode={exc.mode}",
|
||||
**exc.metadata,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def general_exception_handler(_request, exc: Exception):
|
||||
logging.exception("Unhandled exception in admin app")
|
||||
@@ -157,6 +173,7 @@ async def admin_delete_org(org_uuid: UUID, request: Request, auth=AUTH_COOKIE):
|
||||
["auth:admin", f"auth:org:{org_uuid}"],
|
||||
match=permutil.has_any,
|
||||
host=request.headers.get("host"),
|
||||
max_age="5m",
|
||||
)
|
||||
if ctx.org.uuid == org_uuid:
|
||||
raise ValueError("Cannot delete the organization you belong to")
|
||||
@@ -306,6 +323,7 @@ async def admin_delete_role(
|
||||
["auth:admin", f"auth:org:{org_uuid}"],
|
||||
match=permutil.has_any,
|
||||
host=request.headers.get("host"),
|
||||
max_age="5m",
|
||||
)
|
||||
role = await db.instance.get_role(role_uuid)
|
||||
if role.org_uuid != org_uuid:
|
||||
@@ -419,12 +437,15 @@ async def admin_create_user_registration_link(
|
||||
["auth:admin", f"auth:org:{org_uuid}"],
|
||||
match=permutil.has_any,
|
||||
host=request.headers.get("host"),
|
||||
max_age="5m",
|
||||
)
|
||||
if (
|
||||
"auth:admin" not in ctx.role.permissions
|
||||
and f"auth:org:{org_uuid}" not in ctx.role.permissions
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
raise authz.AuthException(
|
||||
status_code=403, detail="Insufficient permissions", mode="forbidden"
|
||||
)
|
||||
|
||||
# Check if user has existing credentials
|
||||
credentials = await db.instance.get_credentials_by_user_uuid(user_uuid)
|
||||
@@ -474,7 +495,9 @@ async def admin_get_user_detail(
|
||||
"auth:admin" not in ctx.role.permissions
|
||||
and f"auth:org:{org_uuid}" not in ctx.role.permissions
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
raise authz.AuthException(
|
||||
status_code=403, detail="Insufficient permissions", mode="forbidden"
|
||||
)
|
||||
user = await db.instance.get_user_by_uuid(user_uuid)
|
||||
cred_ids = await db.instance.get_credentials_by_user_uuid(user_uuid)
|
||||
creds: list[dict] = []
|
||||
@@ -621,7 +644,9 @@ async def admin_update_user_display_name(
|
||||
"auth:admin" not in ctx.role.permissions
|
||||
and f"auth:org:{org_uuid}" not in ctx.role.permissions
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
raise authz.AuthException(
|
||||
status_code=403, detail="Insufficient permissions", mode="forbidden"
|
||||
)
|
||||
new_name = (payload.get("display_name") or "").strip()
|
||||
if not new_name:
|
||||
raise HTTPException(status_code=400, detail="display_name required")
|
||||
@@ -650,12 +675,15 @@ async def admin_delete_user_credential(
|
||||
["auth:admin", f"auth:org:{org_uuid}"],
|
||||
match=permutil.has_any,
|
||||
host=request.headers.get("host"),
|
||||
max_age="5m",
|
||||
)
|
||||
if (
|
||||
"auth:admin" not in ctx.role.permissions
|
||||
and f"auth:org:{org_uuid}" not in ctx.role.permissions
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
raise authz.AuthException(
|
||||
status_code=403, detail="Insufficient permissions", mode="forbidden"
|
||||
)
|
||||
await db.instance.delete_credential(credential_uuid, user_uuid)
|
||||
return {"status": "ok"}
|
||||
|
||||
@@ -684,7 +712,9 @@ async def admin_delete_user_session(
|
||||
"auth:admin" not in ctx.role.permissions
|
||||
and f"auth:org:{org_uuid}" not in ctx.role.permissions
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
raise authz.AuthException(
|
||||
status_code=403, detail="Insufficient permissions", mode="forbidden"
|
||||
)
|
||||
|
||||
try:
|
||||
target_key = tokens.decode_session_key(session_id)
|
||||
@@ -734,7 +764,11 @@ async def admin_create_permission(
|
||||
auth=AUTH_COOKIE,
|
||||
):
|
||||
await authz.verify(
|
||||
auth, ["auth:admin"], host=request.headers.get("host"), match=permutil.has_all
|
||||
auth,
|
||||
["auth:admin"],
|
||||
host=request.headers.get("host"),
|
||||
match=permutil.has_all,
|
||||
max_age="5m",
|
||||
)
|
||||
from ..db import Permission as PermDC
|
||||
|
||||
@@ -806,7 +840,11 @@ async def admin_delete_permission(
|
||||
auth=AUTH_COOKIE,
|
||||
):
|
||||
await authz.verify(
|
||||
auth, ["auth:admin"], host=request.headers.get("host"), match=permutil.has_all
|
||||
auth,
|
||||
["auth:admin"],
|
||||
host=request.headers.get("host"),
|
||||
match=permutil.has_all,
|
||||
max_age="5m",
|
||||
)
|
||||
querysafe.assert_safe(permission_id, field="permission_id")
|
||||
|
||||
|
||||
+52
-11
@@ -57,6 +57,22 @@ async def value_error_handler(_request: Request, exc: ValueError):
|
||||
return JSONResponse(status_code=400, content={"detail": str(exc)})
|
||||
|
||||
|
||||
@app.exception_handler(authz.AuthException)
|
||||
async def auth_exception_handler(_request: Request, exc: authz.AuthException):
|
||||
"""Handle AuthException with auth info for UI."""
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
"detail": exc.detail,
|
||||
"auth": {
|
||||
"mode": exc.mode,
|
||||
"iframe": f"/auth/restricted/?mode={exc.mode}",
|
||||
**exc.metadata,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def general_exception_handler(_request: Request, exc: Exception):
|
||||
logging.exception("Unhandled exception in API app")
|
||||
@@ -96,7 +112,9 @@ async def validate_token(
|
||||
renewed = True
|
||||
except ValueError:
|
||||
# Session disappeared, e.g. due to concurrent logout; global handler will clear
|
||||
raise HTTPException(status_code=401, detail="Session expired")
|
||||
raise authz.AuthException(
|
||||
status_code=401, detail="Session expired", mode="login"
|
||||
)
|
||||
return {
|
||||
"valid": True,
|
||||
"user_uuid": str(ctx.session.user_uuid),
|
||||
@@ -120,8 +138,11 @@ async def forward_authentication(
|
||||
is older than this, user must re-authenticate.
|
||||
|
||||
Success: 204 No Content with Remote-* headers describing the authenticated user.
|
||||
Failure (unauthenticated / unauthorized): 4xx with HTML page for authentication.
|
||||
The HTML includes data attributes for mode and other metadata.
|
||||
Failure (unauthenticated / unauthorized): 4xx response.
|
||||
- If Accept header contains "text/html": HTML page for authentication
|
||||
with data attributes for mode and other metadata.
|
||||
- Otherwise: JSON response with error details and an `iframe` field
|
||||
pointing to /auth/restricted/?mode=... for iframe-based authentication.
|
||||
"""
|
||||
try:
|
||||
ctx = await authz.verify(
|
||||
@@ -154,17 +175,37 @@ async def forward_authentication(
|
||||
}
|
||||
return Response(status_code=204, headers=remote_headers)
|
||||
except authz.AuthException as e:
|
||||
# Authentication/authorization failed - return HTML with metadata
|
||||
html = frontend.file("int", "forward", "index.html").read_bytes()
|
||||
# Inject mode and any additional metadata
|
||||
data_attrs = {"mode": e.mode, **e.metadata}
|
||||
html = htmlutil.patch_html_data_attrs(html, **data_attrs)
|
||||
# Clear cookie only if session is invalid (not for reauth)
|
||||
if e.clear_session:
|
||||
session.clear_session_cookie(response)
|
||||
return Response(
|
||||
html, status_code=e.status_code, media_type="text/html; charset=UTF-8"
|
||||
)
|
||||
|
||||
# Check Accept header to decide response format
|
||||
accept = request.headers.get("accept", "")
|
||||
wants_html = "text/html" in accept
|
||||
|
||||
if wants_html:
|
||||
# Browser request - return HTML with metadata
|
||||
html = frontend.file("int", "forward", "index.html").read_bytes()
|
||||
# Inject mode and any additional metadata
|
||||
data_attrs = {"mode": e.mode, **e.metadata}
|
||||
html = htmlutil.patch_html_data_attrs(html, **data_attrs)
|
||||
return Response(
|
||||
html, status_code=e.status_code, media_type="text/html; charset=UTF-8"
|
||||
)
|
||||
else:
|
||||
# API request - return JSON with iframe src link
|
||||
iframe_url = f"/auth/restricted/?mode={e.mode}"
|
||||
return JSONResponse(
|
||||
status_code=e.status_code,
|
||||
content={
|
||||
"detail": e.detail,
|
||||
"auth": {
|
||||
"mode": e.mode,
|
||||
"iframe": iframe_url,
|
||||
**e.metadata,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/settings")
|
||||
|
||||
@@ -63,7 +63,7 @@ async def verify(
|
||||
# Check max_age requirement if specified
|
||||
if max_age:
|
||||
try:
|
||||
if not sessionutil.check_session_age(ctx.session, max_age):
|
||||
if not sessionutil.check_session_age(ctx, max_age):
|
||||
raise AuthException(
|
||||
status_code=401,
|
||||
detail="Additional authentication required",
|
||||
|
||||
+43
-8
@@ -8,6 +8,7 @@ from fastapi import (
|
||||
Request,
|
||||
Response,
|
||||
)
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from ..authsession import (
|
||||
delete_credential,
|
||||
@@ -17,12 +18,28 @@ from ..authsession import (
|
||||
from ..globals import db
|
||||
from ..util import hostutil, passphrase, tokens
|
||||
from ..util.tokens import decode_session_key, session_key
|
||||
from . import session
|
||||
from . import authz, session
|
||||
from .session import AUTH_COOKIE
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.exception_handler(authz.AuthException)
|
||||
async def auth_exception_handler(_request, exc: authz.AuthException):
|
||||
"""Handle AuthException with auth info for UI."""
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
"detail": exc.detail,
|
||||
"auth": {
|
||||
"mode": exc.mode,
|
||||
"iframe": f"/auth/restricted/?mode={exc.mode}",
|
||||
**exc.metadata,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.put("/display-name")
|
||||
async def user_update_display_name(
|
||||
request: Request,
|
||||
@@ -31,11 +48,15 @@ async def user_update_display_name(
|
||||
auth=AUTH_COOKIE,
|
||||
):
|
||||
if not auth:
|
||||
raise HTTPException(status_code=401, detail="Authentication Required")
|
||||
raise authz.AuthException(
|
||||
status_code=401, detail="Authentication Required", mode="login"
|
||||
)
|
||||
try:
|
||||
s = await get_session(auth, host=request.headers.get("host"))
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=401, detail="Session expired") from e
|
||||
raise authz.AuthException(
|
||||
status_code=401, detail="Session expired", mode="login"
|
||||
) from e
|
||||
new_name = (payload.get("display_name") or "").strip()
|
||||
if not new_name:
|
||||
raise HTTPException(status_code=400, detail="display_name required")
|
||||
@@ -52,7 +73,9 @@ async def api_logout_all(request: Request, response: Response, auth=AUTH_COOKIE)
|
||||
try:
|
||||
s = await get_session(auth, host=request.headers.get("host"))
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=401, detail="Session expired")
|
||||
raise authz.AuthException(
|
||||
status_code=401, detail="Session expired", mode="login"
|
||||
)
|
||||
await db.instance.delete_sessions_for_user(s.user_uuid)
|
||||
session.clear_session_cookie(response)
|
||||
return {"message": "Logged out from all hosts"}
|
||||
@@ -66,11 +89,15 @@ async def api_delete_session(
|
||||
auth=AUTH_COOKIE,
|
||||
):
|
||||
if not auth:
|
||||
raise HTTPException(status_code=401, detail="Authentication Required")
|
||||
raise authz.AuthException(
|
||||
status_code=401, detail="Authentication Required", mode="login"
|
||||
)
|
||||
try:
|
||||
current_session = await get_session(auth, host=request.headers.get("host"))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=401, detail="Session expired") from exc
|
||||
raise authz.AuthException(
|
||||
status_code=401, detail="Session expired", mode="login"
|
||||
) from exc
|
||||
|
||||
try:
|
||||
target_key = decode_session_key(session_id)
|
||||
@@ -97,10 +124,14 @@ async def api_delete_credential(
|
||||
uuid: UUID,
|
||||
auth: str = AUTH_COOKIE,
|
||||
):
|
||||
# Require recent authentication for sensitive operation
|
||||
await authz.verify(auth, [], host=request.headers.get("host"), max_age="5m")
|
||||
try:
|
||||
await delete_credential(uuid, auth, host=request.headers.get("host"))
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=401, detail="Session expired") from e
|
||||
raise authz.AuthException(
|
||||
status_code=401, detail="Session expired", mode="login"
|
||||
) from e
|
||||
return {"message": "Credential deleted successfully"}
|
||||
|
||||
|
||||
@@ -110,10 +141,14 @@ async def api_create_link(
|
||||
response: Response,
|
||||
auth=AUTH_COOKIE,
|
||||
):
|
||||
# Require recent authentication for sensitive operation
|
||||
await authz.verify(auth, [], host=request.headers.get("host"), max_age="5m")
|
||||
try:
|
||||
s = await get_session(auth, host=request.headers.get("host"))
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=401, detail="Session expired") from e
|
||||
raise authz.AuthException(
|
||||
status_code=401, detail="Session expired", mode="login"
|
||||
) from e
|
||||
token = passphrase.generate()
|
||||
expiry = expires()
|
||||
await db.instance.create_reset_token(
|
||||
|
||||
+23
-2
@@ -123,10 +123,26 @@ async def websocket_register_add(
|
||||
|
||||
@app.websocket("/authenticate")
|
||||
@websocket_error_handler
|
||||
async def websocket_authenticate(ws: WebSocket):
|
||||
async def websocket_authenticate(ws: WebSocket, auth=AUTH_COOKIE):
|
||||
origin = ws.headers["origin"]
|
||||
host = origin.split("://", 1)[1]
|
||||
options, challenge = passkey.instance.auth_generate_options()
|
||||
|
||||
# If there's an existing session, restrict to that user's credentials (reauth)
|
||||
session_user_uuid = None
|
||||
credential_ids = None
|
||||
if auth:
|
||||
try:
|
||||
session = await get_session(auth, host=host)
|
||||
session_user_uuid = session.user_uuid
|
||||
credential_ids = await db.instance.get_credentials_by_user_uuid(
|
||||
session_user_uuid
|
||||
)
|
||||
except ValueError:
|
||||
pass # Invalid/expired session - allow normal authentication
|
||||
|
||||
options, challenge = passkey.instance.auth_generate_options(
|
||||
credential_ids=credential_ids
|
||||
)
|
||||
await ws.send_json(options)
|
||||
# Wait for the client to use his authenticator to authenticate
|
||||
credential = passkey.instance.auth_parse(await ws.receive_json())
|
||||
@@ -137,6 +153,11 @@ async def websocket_authenticate(ws: WebSocket):
|
||||
raise ValueError(
|
||||
f"This passkey is no longer registered with {passkey.instance.rp_name}"
|
||||
)
|
||||
|
||||
# If reauth mode, verify the credential belongs to the session's user
|
||||
if session_user_uuid and stored_cred.user_uuid != session_user_uuid:
|
||||
raise ValueError("This passkey belongs to a different account")
|
||||
|
||||
# Verify the credential matches the stored data
|
||||
passkey.instance.auth_verify(credential, challenge, stored_cred, origin=origin)
|
||||
# Update both credential and user's last_seen timestamp
|
||||
|
||||
@@ -2,19 +2,22 @@
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from ..db import Session
|
||||
from ..db import SessionContext
|
||||
from .timeutil import parse_duration
|
||||
|
||||
|
||||
def check_session_age(session: Session, max_age: str | None) -> bool:
|
||||
def check_session_age(ctx: SessionContext, max_age: str | None) -> bool:
|
||||
"""Check if a session satisfies the max_age requirement.
|
||||
|
||||
Uses the credential's last_used timestamp to determine authentication age,
|
||||
since session renewal can happen without re-authentication.
|
||||
|
||||
Args:
|
||||
session: The session record to check
|
||||
ctx: The session context containing session and credential info
|
||||
max_age: Maximum age string (e.g., "5m", "1h", "30s") or None
|
||||
|
||||
Returns:
|
||||
True if session is recent enough or max_age is None, False if too old
|
||||
True if authentication is recent enough or max_age is None, False if too old
|
||||
|
||||
Raises:
|
||||
ValueError: If max_age format is invalid
|
||||
@@ -23,5 +26,12 @@ def check_session_age(session: Session, max_age: str | None) -> bool:
|
||||
return True
|
||||
|
||||
max_age_delta = parse_duration(max_age)
|
||||
time_since_auth = datetime.now(timezone.utc) - session.renewed
|
||||
|
||||
# Use credential's last_used time if available, fall back to session renewed
|
||||
if ctx.credential and ctx.credential.last_used:
|
||||
auth_time = ctx.credential.last_used
|
||||
else:
|
||||
auth_time = ctx.session.renewed
|
||||
|
||||
time_since_auth = datetime.now(timezone.utc) - auth_time
|
||||
return time_since_auth <= max_age_delta
|
||||
|
||||
Reference in New Issue
Block a user