improving AuthContextProvider

This commit is contained in:
Myzel394 2022-12-12 15:56:35 +01:00
parent caa1a108d8
commit c89ad41602
5 changed files with 22 additions and 6 deletions

View File

@ -8,7 +8,7 @@ export interface UseContextValueData {
encryptUsingMasterPassword: (content: string) => string
decryptUsingMasterPassword: (content: string) => string
decryptUsingPrivateKey: (message: string) => Promise<string>
setDecryptionPassword: (password: string) => void
setDecryptionPassword: (password: string) => boolean
}
export default function useContextValue({

View File

@ -10,7 +10,7 @@ export interface UseMasterPasswordResult {
decryptUsingMasterPassword: (content: string) => string
decryptUsingPrivateKey: (message: string) => Promise<string>
setDecryptionPassword: (password: string) => void
setDecryptionPassword: (password: string) => boolean
logout: () => void
// Use this cautiously
_masterPassword: string
@ -78,6 +78,22 @@ export default function useMasterPassword(
[user],
)
const updateDecryptionPassword = useCallback((password: string) => {
if (!user || !user.encryptedPassword) {
throw new Error("User not set.")
}
try {
const masterPassword = decryptString(user.encryptedPassword, password)
JSON.parse(decryptString((user as ServerUser).encryptedNotes, masterPassword))
setDecryptionPassword(password)
} catch {
return false;
}
return true;
}, [user, masterPassword])
const logout = useCallback(() => {
setDecryptionPassword(null)
}, [])
@ -86,8 +102,8 @@ export default function useMasterPassword(
encryptUsingMasterPassword,
decryptUsingMasterPassword,
decryptUsingPrivateKey,
setDecryptionPassword,
logout,
setDecryptionPassword: updateDecryptionPassword,
_masterPassword: masterPassword!,
}
}

View File

@ -22,7 +22,6 @@ export default function useUser({
user,
updateUser,
}: UseAuthData) {
const {mutateAsync: refresh} = useMutation<RefreshTokenResult, AxiosError, void>(refreshToken, {
onError: () => logout(),
})

View File

@ -1,5 +1,5 @@
import {useLocation, useNavigate} from "react-router-dom"
import {useContext, useLayoutEffect} from "react"
import {useContext, useEffect, useLayoutEffect} from "react"
import {ServerUser, User} from "~/server-types"
import AuthContext from "~/AuthContext/AuthContext"
@ -17,7 +17,7 @@ export default function useUser(): ServerUser | User {
const navigate = useNavigate()
const {user, isAuthenticated} = useContext(AuthContext)
useLayoutEffect(() => {
useEffect(() => {
if (
!isAuthenticated &&
!AUTHENTICATION_PATHS.includes(location.pathname)

View File

@ -36,6 +36,7 @@ export default function EnterDecryptionPassword(): ReactElement {
onSubmit: async ({password}, {setErrors}) => {
const decryptionPassword = buildEncryptionPassword(password, user.email.address)
console.log("decryptionPassword", decryptionPassword)
if (!_setDecryptionPassword(decryptionPassword)) {
setErrors({
password: t(