Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | 5x 5x 5x 5x 5x 5x 3x 3x 3x 3x 2x 2x 3x 5x | import { useState, useEffect, useCallback } from 'react'
import { api } from '../api/client'
import type { PasskeyCredential } from '../api/types'
import {
prepareRegistrationOptions,
serializeRegistrationCredential,
} from '../lib/webauthn'
export default function usePasskeys() {
const [credentials, setCredentials] = useState<PasskeyCredential[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [adding, setAdding] = useState(false)
const loadCredentials = useCallback(async () => {
try {
const data = await api.passkey.listCredentials()
setCredentials(data.credentials)
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load passkeys')
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
let cancelled = false
;(async () => {
try {
const data = await api.passkey.listCredentials()
Eif (!cancelled) setCredentials(data.credentials)
} catch (err) {
if (!cancelled) setError(err instanceof Error ? err.message : 'Failed to load passkeys')
} finally {
Eif (!cancelled) setLoading(false)
}
})()
return () => { cancelled = true }
}, [])
async function handleAdd() {
setError('')
setAdding(true)
try {
const options = await api.passkey.addCredentialOptions()
const publicKeyOptions = prepareRegistrationOptions(options)
const credential = await navigator.credentials.create({
publicKey: publicKeyOptions,
})
if (!credential) {
setError('Adding passkey was cancelled.')
return
}
await api.passkey.addCredentialVerify(
serializeRegistrationCredential(credential as PublicKeyCredential)
)
await loadCredentials()
} catch (err) {
if (err instanceof DOMException && err.name === 'NotAllowedError') {
setError('Adding passkey was cancelled.')
} else {
setError(err instanceof Error ? err.message : 'Failed to add passkey')
}
} finally {
setAdding(false)
}
}
async function handleDelete(credentialId: number) {
if (!window.confirm('Are you sure you want to delete this passkey? This cannot be undone.')) {
return
}
setError('')
try {
await api.passkey.deleteCredential(credentialId)
await loadCredentials()
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to delete passkey')
}
}
return { credentials, loading, error, adding, handleAdd, handleDelete }
}
|