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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
import 'pinia'
import { MaybeRef, ref, shallowRef, watch } from 'vue';
import { MfaMethod, PkiPublicKey, apiCall, useMfaConfig, usePkiConfig, usePkiAuth, MfaApi } from '@vnuge/vnlib.browser';
import { useToggle, get, set } from '@vueuse/core';
import { PiniaPluginContext, PiniaPlugin, storeToRefs } from 'pinia'
import { includes } from 'lodash-es';
import { storeExport, } from './index';
interface PkiStore {
publicKeys: PkiPublicKey[]
pkiConfig: ReturnType<typeof usePkiConfig>
pkiAuth: ReturnType<typeof usePkiAuth>
refresh: () => void
}
export interface MfaSettingsStore{
mfa:{
enabledMethods: MfaMethod[]
refresh: () => void
} & MfaApi
pki?: PkiStore
}
declare module 'pinia' {
export interface PiniaCustomProperties extends MfaSettingsStore {
}
}
export const mfaSettingsPlugin = (mfaEndpoint: MaybeRef<string>, pkiEndpoint?:MaybeRef<string>): PiniaPlugin => {
return ({ store }: PiniaPluginContext): MfaSettingsStore => {
const { loggedIn } = storeToRefs(store)
const mfaConfig = useMfaConfig(mfaEndpoint)
const [onRefresh, refresh] = useToggle()
const enabledMethods = ref<MfaMethod[]>([])
const usePki = () => {
const publicKeys = shallowRef<PkiPublicKey[]>([])
const pkiConfig = usePkiConfig(pkiEndpoint || '/')
const pkiAuth = usePkiAuth(pkiEndpoint || '/')
//Watch for changes to mfa methods (refresh) and update the pki keys
watch([enabledMethods], ([methods]) => {
if (!includes(methods, 'pki' as MfaMethod) || !get(pkiEndpoint)) {
set(publicKeys, [])
return
}
//load the pki keys if pki is enabled
apiCall(async () => publicKeys.value = await pkiConfig.getAllKeys())
})
return{
publicKeys,
pkiConfig,
pkiAuth,
refresh
}
}
watch([loggedIn, onRefresh], ([ li ]) => {
if(!li){
set(enabledMethods, [])
return
}
//load the mfa methods if the user is logged in
apiCall(async () => enabledMethods.value = await mfaConfig.getMethods())
})
//Only return the pki store if pki is enabled
if(get(pkiEndpoint)){
return storeExport({
mfa:{
enabledMethods,
refresh,
...mfaConfig
},
pki: usePki()
})
}
else{
return storeExport({
mfa:{
enabledMethods,
refresh,
...mfaConfig
},
})
}
}
}
|