Last active
September 4, 2019 01:48
-
-
Save ranisalt/5365a3c24fb1b4f83d86b34cc182581e to your computer and use it in GitHub Desktop.
react context webauthn
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface PasswordCredential { | |
type: 'password' | |
id: Readonly<string> | |
iconURL: Readonly<string> | |
name: Readonly<string> | |
password: Readonly<string> | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
useEffect(() => { | |
const fetchCredential = async () => { | |
const storedCredential = await navigator.credentials.get({ | |
password: true, | |
mediation: 'silent', | |
} as any) | |
if (storedCredential == null) { | |
return | |
} | |
// valid credentials found | |
} | |
fetchCredential() | |
}, []) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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