Skip to content

Instantly share code, notes, and snippets.

@ranisalt
Last active September 4, 2019 01:48
Show Gist options
  • Save ranisalt/5365a3c24fb1b4f83d86b34cc182581e to your computer and use it in GitHub Desktop.
Save ranisalt/5365a3c24fb1b4f83d86b34cc182581e to your computer and use it in GitHub Desktop.
react context webauthn
interface PasswordCredential {
type: 'password'
id: Readonly<string>
iconURL: Readonly<string>
name: Readonly<string>
password: Readonly<string>
}
import React, { createContext, useState } from 'react'
const AuthContext = createContext<PasswordCredential | undefined>(undefined)
export const AuthProvider: React.FC = ({ children }) => {
const [credential, setCredential] = useState<PasswordCredential>()
return (
<AuthContext.Provider value={credential}>{children}</AuthContext.Provider>
)
}
useEffect(() => {
const fetchCredential = async () => {
const storedCredential = await navigator.credentials.get({
password: true,
mediation: 'silent',
} as any)
if (storedCredential == null) {
return
}
// valid credentials found
}
fetchCredential()
}, [])
const passwordCredential = storedCredential as PasswordCredential
const { name, password } = passwordCredential
const body = new FormData()
body.append('name', name)
body.append('password', password)
const res = await fetch('/auth/login', { body, method: 'POST' })
if (res.ok) {
setCredential(passwordCredential)
}
// silently fail on login error (maybe credentials are incorrect)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment