Debian Codegraph @

examples/react-spa/frontend/src/mfa/AddWebAuthn.js

raw
1 import { useState } from 'react'
2 import { Navigate } from 'react-router-dom'
3 import FormErrors from '../components/FormErrors'
4 import Button from '../components/Button'
5 import * as allauth from '../lib/allauth'
6 import {
7 create,
8 parseCreationOptionsFromJSON
9 } from '@github/webauthn-json/browser-ponyfill'
10
11 export default function AddWebAuthn (props) {
12 const [passwordless, setPasswordless] = useState(false)
13 const [name, setName] = useState('')
14 const [response, setResponse] = useState({ fetching: false, content: null })
15
16 async function submit () {
17 setResponse({ ...response, fetching: true })
18 try {
19 const optResp = await allauth.getWebAuthnCreateOptions(passwordless)
20 if (optResp.status === 200) {
21 const jsonOptions = optResp.data.creation_options
22 const options = parseCreationOptionsFromJSON(jsonOptions)
23 const credential = await create(options)
24 const addResp = await allauth.addWebAuthnCredential(name, credential)
25 setResponse((r) => { return { ...r, content: addResp } })
26 } else {
27 setResponse((r) => { return { ...r, content: optResp } })
28 }
29 } catch (e) {
30 console.error(e)
31 window.alert(e)
32 }
33 setResponse((r) => { return { ...r, fetching: false } })
34 }
35
36 if (response.content?.status === 200) {
37 return <Navigate to={response.content.meta.recovery_codes_generated ? '/account/2fa/recovery-codes' : '/account/2fa/webauthn'} />
38 }
39 return (
40 <section>
41 <h1>Add Security Key</h1>
42
43 <div>
44 <label>
45 Name:
46 <input value={name} onChange={(e) => setName(e.target.value)} />
47 <FormErrors param='name' errors={response.content?.errors} />
48 <FormErrors errors={response.content?.errors} />
49 </label>
50 </div>
51 <div>
52 <label>
53 Passwordless
54 <input type='checkbox' onChange={(e) => setPasswordless(e.target.checked)} checked={passwordless} />
55 </label>
56 </div>
57 <Button disabled={response.fetching} onClick={() => submit()}>Add key</Button>
58 </section>
59 )
60 }