Merge remote-tracking branch 'origin/improve-auth-context-provider' into improve-auth-context-provider

# Conflicts:
#	src/hooks/use-user.ts
This commit is contained in:
Myzel394 2022-12-16 22:39:05 +01:00
commit a8799095cd
6 changed files with 150 additions and 96 deletions

View File

@ -22,6 +22,7 @@
"crypto-js": "^4.1.1",
"date-fns": "^2.29.3",
"deep-equal": "^2.0.5",
"fast-hash-code": "^2.1.0",
"formik": "^2.2.9",
"group-array": "^1.0.0",
"i18next": "^22.0.4",

View File

@ -1,18 +1,15 @@
import {ReactElement, ReactNode, useCallback, useEffect} from "react"
import {AxiosError} from "axios"
import {decrypt, readMessage, readPrivateKey} from "openpgp"
import {ReactElement, ReactNode, useCallback} from "react"
import {useLocalStorage} from "react-use"
import AuthContext from "./AuthContext"
import useExtensionHandler from "~/AuthContext/use-extension-handler"
import useMasterPassword from "~/AuthContext/use-master-password"
import fastHashCode from "fast-hash-code";
import {AuthenticationDetails, ServerUser, User} from "~/server-types"
import {REFRESH_TOKEN_URL, RefreshTokenResult, getMe, refreshToken} from "~/apis"
import {client} from "~/constants/axios-client"
import {useMutation, useQuery} from "@tanstack/react-query"
import PasswordShareConfirmationDialog from "~/AuthContext/PasswordShareConfirmationDialog"
import useContextValue from "~/AuthContext/use-context-value"
import {ServerUser, User} from "~/server-types"
import AuthContext from "./AuthContext"
import PasswordShareConfirmationDialog from "./PasswordShareConfirmationDialog"
import useContextValue from "./use-context-value"
import useExtensionHandler from "./use-extension-handler"
import useMasterPassword from "./use-master-password"
import useUser from "./use-user";
export interface AuthContextProviderProps {
children: ReactNode
@ -23,48 +20,23 @@ export default function AuthContextProvider({children}: AuthContextProviderProps
"_global-context-auth-user",
null,
)
const {
encryptUsingMasterPassword,
decryptUsingMasterPassword,
decryptUsingPrivateKey,
setDecryptionPassword,
_masterPassword,
logout: logoutMasterPassword,
} = useMasterPassword(user?.encryptedPassword || null)
} = useMasterPassword(user || null)
const {sharePassword, closeDialog, showDialog, dispatchPasswordStatus} = useExtensionHandler(
_masterPassword!,
user as User,
)
const logout = useCallback(() => {
logoutMasterPassword()
setUser(null)
}, [logoutMasterPassword])
const {mutateAsync: refresh} = useMutation<RefreshTokenResult, AxiosError, void>(refreshToken, {
onError: () => logout(),
})
const decryptUsingPrivateKey = useCallback(
async (message: string): Promise<string> => {
if (!user) {
throw new Error("User not set.")
}
if (!user.isDecrypted) {
throw new Error("User is not decrypted.")
}
return (
await decrypt({
message: await readMessage({
armoredMessage: message,
}),
decryptionKeys: await readPrivateKey({
armoredKey: user.notes.privateKey,
}),
})
).data.toString()
},
[user],
)
const contextValue = useContextValue({
decryptUsingPrivateKey,
@ -76,55 +48,14 @@ export default function AuthContextProvider({children}: AuthContextProviderProps
user: user || null,
})
useQuery<AuthenticationDetails, AxiosError>(["get_me"], getMe, {
refetchOnWindowFocus: "always",
refetchOnReconnect: "always",
retry: 2,
enabled: user !== null,
useUser({
logout,
decryptUsingMasterPassword,
user: user || null,
updateUser: setUser,
masterPasswordHash: _masterPassword ? fastHashCode(_masterPassword).toString() : null,
})
// Decrypt user notes
useEffect(() => {
if (user && !user.isDecrypted && user.encryptedPassword) {
const note = JSON.parse(decryptUsingMasterPassword(user.encryptedNotes!))
setUser(
prevUser =>
({
...(prevUser || {}),
notes: note,
isDecrypted: true,
} as User),
)
}
}, [user, decryptUsingMasterPassword])
// Refresh token and logout user if needed
useEffect(() => {
const interceptor = client.interceptors.response.use(
response => response,
async (error: AxiosError) => {
if (error.isAxiosError) {
if (error.response?.status === 401) {
// Check if error comes from refreshing the token.
// If yes, the user has been logged out completely.
const request: XMLHttpRequest = error.request
if (request.responseURL === REFRESH_TOKEN_URL) {
await logout()
} else {
await refresh()
}
}
}
throw error
},
)
return () => client.interceptors.response.eject(interceptor)
}, [logout, refresh])
return (
<>
<AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>

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

@ -1,20 +1,23 @@
import {useLocalStorage} from "react-use"
import {useCallback, useMemo} from "react"
import {decrypt, readMessage, readPrivateKey} from "openpgp";
import {decryptString, encryptString} from "~/utils"
import {ServerUser, User} from "~/server-types";
export interface UseMasterPasswordResult {
encryptUsingMasterPassword: (content: string) => string
decryptUsingMasterPassword: (content: string) => string
decryptUsingPrivateKey: (message: string) => Promise<string>
setDecryptionPassword: (password: string) => void
setDecryptionPassword: (password: string) => boolean
logout: () => void
// Use this cautiously
_masterPassword: string
}
export default function useMasterPassword(
encryptedPassword: string | null,
user: User | ServerUser | null,
): UseMasterPasswordResult {
const [decryptionPassword, setDecryptionPassword] = useLocalStorage<string | null>(
"_global-context-auth-decryption-password",
@ -22,12 +25,12 @@ export default function useMasterPassword(
)
const masterPassword = useMemo<string | null>(() => {
if (decryptionPassword === null || !encryptedPassword) {
if (decryptionPassword === null || !user?.encryptedPassword) {
return null
}
return decryptString(encryptedPassword, decryptionPassword!)
}, [decryptionPassword, encryptedPassword])
return decryptString(user.encryptedPassword, decryptionPassword!)
}, [decryptionPassword, user?.encryptedPassword])
const encryptUsingMasterPassword = useCallback(
(content: string) => {
@ -51,6 +54,46 @@ export default function useMasterPassword(
[masterPassword],
)
const decryptUsingPrivateKey = useCallback(
async (message: string): Promise<string> => {
if (!user) {
throw new Error("User not set.")
}
if (!user.isDecrypted) {
throw new Error("User is not decrypted.")
}
return (
await decrypt({
message: await readMessage({
armoredMessage: message,
}),
decryptionKeys: await readPrivateKey({
armoredKey: user.notes.privateKey,
}),
})
).data.toString()
},
[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)
}, [])
@ -58,8 +101,9 @@ export default function useMasterPassword(
return {
encryptUsingMasterPassword,
decryptUsingMasterPassword,
setDecryptionPassword,
decryptUsingPrivateKey,
logout,
setDecryptionPassword: updateDecryptionPassword,
_masterPassword: masterPassword!,
}
}

View File

@ -0,0 +1,77 @@
import {Dispatch, SetStateAction, useEffect} from "react";
import {AxiosError} from "axios";
import {useMutation, useQuery} from "@tanstack/react-query";
import {REFRESH_TOKEN_URL, RefreshTokenResult, getMe, refreshToken} from "~/apis"
import {AuthenticationDetails, ServerUser, User} from "~/server-types";
import {client} from "~/constants/axios-client";
export interface UseAuthData {
logout: () => void
masterPasswordHash: string | null
decryptUsingMasterPassword: (content: string) => string
user: User | ServerUser | null
updateUser: Dispatch<SetStateAction<User | ServerUser | null | undefined>>
}
export default function useUser({
logout,
masterPasswordHash,
decryptUsingMasterPassword,
user,
updateUser,
}: UseAuthData) {
const {mutateAsync: refresh} = useMutation<RefreshTokenResult, AxiosError, void>(refreshToken, {
onError: () => logout(),
})
useQuery<AuthenticationDetails, AxiosError>(["get_me"], getMe, {
refetchOnWindowFocus: "always",
refetchOnReconnect: "always",
retry: 2,
enabled: user !== null,
})
// Decrypt user notes
useEffect(() => {
if (user && !user.isDecrypted && user.encryptedPassword && masterPasswordHash) {
const note = JSON.parse(decryptUsingMasterPassword(user.encryptedNotes!))
updateUser(
prevUser =>
({
...(prevUser || {}),
notes: note,
isDecrypted: true,
} as User),
)
}
}, [user, decryptUsingMasterPassword, updateUser, masterPasswordHash])
// Refresh token and logout user if needed
useEffect(() => {
const interceptor = client.interceptors.response.use(
response => response,
async (error: AxiosError) => {
if (error.isAxiosError) {
if (error.response?.status === 401) {
// Check if error comes from refreshing the token.
// If yes, the user has been logged out completely.
const request: XMLHttpRequest = error.request
if (request.responseURL === REFRESH_TOKEN_URL) {
await logout()
} else {
await refresh()
}
}
}
throw error
},
)
return () => client.interceptors.response.eject(interceptor)
}, [logout, refresh])
}

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(