-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (54 loc) · 1.59 KB
/
index.js
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
import React, { createContext, useContext, useState } from 'react'
import { AuthStatusCode, SimpleOTP } from '@simpleotp/core'
const SimpleOTPContext = createContext()
class ReactSimpleOTP extends SimpleOTP {
constructor(siteID, apiURL = null) {
super(siteID, apiURL)
this._userRef = React.createRef()
this._isAuthenticatedRef = React.createRef(Boolean(this.userRef.current))
}
_setAuthDetailsIfSuccessful(resp) {
if (resp.code === AuthStatusCode.OK.description) {
this._isAuthenticatedRef.current = true
this._userRef.current = this.getUser()
}
}
async auth(code) {
const resp = await super.auth(code)
this._setAuthDetailsIfSuccessful(resp)
return resp
}
async authWithWebAuthnCredentials() {
const resp = await super.authWithWebAuthnCredentials()
this._setAuthDetailsIfSuccessful(resp)
return resp
}
async authWithURLCode() {
const resp = await super.authWithURLCode()
this._setAuthDetailsIfSuccessful(resp)
return resp
}
getIsAuthenticatedRef() {
return this.isAuthenticatedRef
}
getUserRef() {
return this.userRef
}
signOut() {
super.signOut()
this.isAuthenticatedRef.current = false
this.userRef.current = null
}
}
export function useSimpleOTP() {
return useContext(SimpleOTPContext)
}
export function SimpleOTPProvider({ siteID, apiURL, children }) {
const [simpleOTPInstance] = useState(() => new ReactSimpleOTP(siteID, apiURL))
return (
<SimpleOTPContext.Provider value={simpleOTPInstance}>
{children}
</SimpleOTPContext.Provider>
)
}
export default SimpleOTPProvider