feat: address changes on the client

This commit is contained in:
lemmyMwaura
2024-08-07 16:13:29 +03:00
parent 56f2a3afa4
commit f12d4d80c6
4 changed files with 77 additions and 48 deletions
@@ -56,6 +56,9 @@ export const useGetActiveSharedSecretById = ({
params params
} }
); );
if (!data) return null;
return { return {
encryptedValue: data.encryptedValue, encryptedValue: data.encryptedValue,
password: data.password, password: data.password,
@@ -68,7 +71,8 @@ export const useGetActiveSharedSecretById = ({
}); });
}; };
export const fetchIsSecretPasswordValid = async ( // returns a secret (secret or undefined if password doesn't match)
export const fetchSecretIfPasswordIsValid = async (
sharedSecretId: string, sharedSecretId: string,
hashedHex: string, hashedHex: string,
password: string, password: string,
@@ -156,9 +156,10 @@ export const ShareSecretForm = ({ isPublic, value }: Props) => {
name="password" name="password"
render={({ field, fieldState: { error } }) => ( render={({ field, fieldState: { error } }) => (
<FormControl <FormControl
label="Password (Optional)" label="Password"
isError={Boolean(error)} isError={Boolean(error)}
errorText={error?.message} errorText={error?.message}
isOptional={true}
> >
<Input {...field} placeholder="Password" type="password" /> <Input {...field} placeholder="Password" type="password" />
</FormControl> </FormControl>
@@ -1,4 +1,4 @@
import { useState, useCallback } from 'react' import { useState, useCallback, useEffect } from 'react'
import Image from "next/image"; import Image from "next/image";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
@@ -10,7 +10,7 @@ import { useGetActiveSharedSecretById } from "@app/hooks/api/secretSharing";
import { SecretContainer, SecretErrorContainer, PasswordContainer } from "./components"; import { SecretContainer, SecretErrorContainer, PasswordContainer } from "./components";
export const ViewSecretPublicPage = () => { export const ViewSecretPublicPage = () => {
const [passMatches, setPassMatch] = useState(false) const [secret, setSecret] = useState(null)
const router = useRouter(); const router = useRouter();
const { id, key: urlEncodedPublicKey } = router.query; const { id, key: urlEncodedPublicKey } = router.query;
@@ -18,14 +18,18 @@ export const ViewSecretPublicPage = () => {
? urlEncodedPublicKey.toString().split("-") ? urlEncodedPublicKey.toString().split("-")
: ["", ""]; : ["", ""];
const { data: secret, error } = useGetActiveSharedSecretById({ const { data, error } = useGetActiveSharedSecretById({
sharedSecretId: id as string, sharedSecretId: id as string,
hashedHex hashedHex
}); });
const handlePassMatch = useCallback((val: boolean) => { useEffect(() => {
setPassMatch(val) if (data) setSecret(data)
}, [setPassMatch]) }, [data])
const handleSecret = useCallback((val: any) => {
setSecret(val)
}, [setSecret])
return ( return (
<div className="flex h-screen flex-col justify-between overflow-auto bg-gradient-to-tr from-mineshaft-700 to-bunker-800 text-gray-200 dark:[color-scheme:dark]"> <div className="flex h-screen flex-col justify-between overflow-auto bg-gradient-to-tr from-mineshaft-700 to-bunker-800 text-gray-200 dark:[color-scheme:dark]">
@@ -58,13 +62,12 @@ export const ViewSecretPublicPage = () => {
</a> </a>
</p> </p>
</div> </div>
{secret && ( {!secret ? (
!passMatches && secret.password ? ( <PasswordContainer secretId={id as string} hashedHex={hashedHex} handleSecret={handleSecret} />
<PasswordContainer secretId={id as string} hashedHex={hashedHex} handlePassMatch={handlePassMatch} />
) : ( ) : (
key && <SecretContainer secret={secret} secretKey={key} /> key && <SecretContainer secret={secret} secretKey={key} />
) )
)} }
{error && <SecretErrorContainer />} {error && <SecretErrorContainer />}
<div className="m-auto my-8 flex w-full"> <div className="m-auto my-8 flex w-full">
<div className="w-full border-t border-mineshaft-600" /> <div className="w-full border-t border-mineshaft-600" />
@@ -1,43 +1,52 @@
import { useState, ChangeEvent } from "react"; import { z } from "zod";
import { Controller, useForm } from "react-hook-form";
import { faArrowRight, faSpinner } from "@fortawesome/free-solid-svg-icons"; import { faArrowRight, faSpinner } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, IconButton, Input } from "@app/components/v2"; import { Button, FormControl, IconButton, Input } from "@app/components/v2";
import { fetchIsSecretPasswordValid } from "@app/hooks/api/secretSharing"; import { fetchSecretIfPasswordIsValid } from "@app/hooks/api/secretSharing";
import { createNotification } from "@app/components/notifications"; import { createNotification } from "@app/components/notifications";
type Props = { type Props = {
secretId: string; secretId: string;
hashedHex: string; hashedHex: string;
handlePassMatch: (val: boolean) => void; handleSecret: (val: any) => void;
}; };
export const PasswordContainer = ({ secretId, hashedHex, handlePassMatch }: Props) => { const formSchema = z.object({
const [password, setPassword] = useState<string>('') password: z.string()
const [isLoading, setLoading] = useState(false) })
const handleChange = (e: ChangeEvent<HTMLInputElement>) => { export type FormData = z.infer<typeof formSchema>;
setPassword(e.target.value)
}
const validatePassword = async () => { export const PasswordContainer = ({ secretId, hashedHex, handleSecret }: Props) => {
setLoading(true); const {
control,
reset,
handleSubmit,
formState: { isSubmitting }
} = useForm<FormData>({
resolver: zodResolver(formSchema),
});
const onFormSubmit = async ({ password }: FormData) => {
try { try {
const data = await fetchIsSecretPasswordValid( const secret = await fetchSecretIfPasswordIsValid(
secretId, secretId,
hashedHex, hashedHex,
password, password,
) )
if (data?.isValid === true) { if (secret) {
handlePassMatch(true); handleSecret(secret);
} else { } else {
createNotification({ createNotification({
text: "Password is Invalid. Try again", text: "Password is Invalid. Try again",
type: "error" type: "error"
}) })
reset();
} }
} catch (error) { } catch (error) {
console.error("Failed to validate password:", error); console.error("Failed to validate password:", error);
@@ -45,31 +54,43 @@ export const PasswordContainer = ({ secretId, hashedHex, handlePassMatch }: Prop
text: "Failed to validate password", text: "Failed to validate password",
type: "error" type: "error"
}) })
} finally {
setLoading(false);
} }
} };
return ( return (
<div className="rounded-lg border border-mineshaft-600 bg-mineshaft-800 p-4"> <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-800 p-4">
<div className="flex items-center gap-2 justify-between rounded-md"> <form onSubmit={handleSubmit(onFormSubmit)}>
<Input onChange={handleChange} placeholder="Enter Password to view secret"></Input> <Controller
<div className="flex"> control={control}
<IconButton name="password"
ariaLabel="copy icon" render={({ field, fieldState: { error } }) => (
colorSchema="secondary" <FormControl
className="group relative" isError={Boolean(error)}
onClick={() => { errorText={error?.message}
validatePassword() isRequired
}} label="Password"
> >
<FontAwesomeIcon <div className="flex items-center gap-2 justify-between rounded-md">
className={isLoading ? 'fa-spin' : ''} <Input {...field} placeholder="Enter Password to view secret"></Input>
icon={isLoading ? faSpinner : faArrowRight} <div className="flex">
/> <IconButton
</IconButton> ariaLabel="copy icon"
</div> colorSchema="secondary"
</div> className="group relative"
onClick={handleSubmit(onFormSubmit)}
>
<FontAwesomeIcon
className={isSubmitting ? 'fa-spin' : ''}
icon={isSubmitting ? faSpinner : faArrowRight}
/>
</IconButton>
</div>
</div>
</FormControl>
)}
/>
</form>
<Button <Button
className="mt-4 w-full bg-mineshaft-700 py-3 text-bunker-200" className="mt-4 w-full bg-mineshaft-700 py-3 text-bunker-200"
colorSchema="primary" colorSchema="primary"