Skip to content

Commit 4ede781

Browse files
committed
refactor(auth): change upload image so dont need auth
1 parent c51f6db commit 4ede781

11 files changed

+437
-142
lines changed

Diff for: package.json

+2
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
"dependencies": {
1212
"@radix-ui/react-dialog": "^1.0.4",
1313
"@radix-ui/react-dropdown-menu": "^2.0.5",
14+
"@tailwindcss/forms": "^0.5.6",
1415
"@types/node": "20.6.2",
1516
"@types/react": "18.2.21",
1617
"@types/react-dom": "18.2.7",
@@ -21,6 +22,7 @@
2122
"google-libphonenumber": "^3.2.33",
2223
"lucide-react": "^0.279.0",
2324
"next": "13.4.19",
25+
"nookies": "^2.5.2",
2426
"postcss": "8.4.29",
2527
"react": "18.2.0",
2628
"react-dom": "18.2.0",

Diff for: pnpm-lock.yaml

+36
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Diff for: src/components/AuthContext.tsx

+38-12
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { environment } from "@/utils/environment";
2+
import { setCookie, parseCookies } from "nookies";
23
import {
34
ReactNode,
45
createContext,
@@ -13,15 +14,19 @@ type User = {
1314
whatsapp: string;
1415
isAuthenticated: boolean;
1516
};
17+
type IOpenLogin = {
18+
status?: boolean;
19+
reset?: boolean;
20+
};
1621
type IContext = {
1722
user: User | null;
1823
isLogged: boolean;
1924
isOpen: boolean;
20-
openLogin: (status?: boolean) => Promise<void>;
25+
openLogin: (data?: IOpenLogin) => Promise<void>;
26+
changeNumber: () => Promise<void>;
2127
logout: () => Promise<void>;
2228
setPin: (token: string) => Promise<void>;
2329
login: ({ whatsapp }: { whatsapp: string }) => Promise<void>;
24-
token: string | null;
2530
};
2631

2732
const Context = createContext({ user: null } as IContext);
@@ -31,16 +36,22 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
3136
const [user, setUser] = useState<User | null>(null);
3237
const [isLogged, setIsLogged] = useState(false);
3338
const [isOpen, setOpen] = useState(false);
34-
const [token, setToken] = useState(null);
3539

3640
const getSession = useCallback(async () => {
41+
const cookies = parseCookies();
42+
const token = cookies.phone_token;
43+
3744
if (!token) return;
38-
const session = await fetch("/session", {
45+
const session = await fetch(`${environment.APIURL}/session`, {
3946
headers: {
4047
"x-auth-token": token,
4148
},
4249
}).then((res) => res.json());
4350

51+
if (session.error) {
52+
alert(session.error);
53+
return;
54+
}
4455
setUser(session.data);
4556
setIsLogged(true);
4657
}, []);
@@ -50,17 +61,23 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
5061
setUser(null);
5162
}, []);
5263

53-
const openLogin = useCallback(async (status = true) => {
54-
setOpen(status);
55-
}, []);
64+
const openLogin = useCallback(
65+
async ({ status = true, reset = false } = {} as IOpenLogin) => {
66+
if (reset) {
67+
setUser(null);
68+
setIsLogged(false);
69+
}
70+
setOpen(status);
71+
},
72+
[]
73+
);
5674

5775
const login = async ({ whatsapp }: { whatsapp: string }) => {
5876
try {
5977
const response = await fetch(`${environment.APIURL}/login`, {
6078
method: "POST",
6179
body: JSON.stringify({
62-
name,
63-
whatsapp: `55${whatsapp}@c.us`,
80+
whatsapp,
6481
}),
6582
headers: {
6683
"Content-Type": "application/json",
@@ -109,16 +126,25 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
109126
alert(response.message);
110127
const { id, isAuthenticated, whatsapp } = response.data;
111128
setUser({ id, isAuthenticated, whatsapp });
112-
setToken(response.token);
129+
130+
setCookie(null, "phone_token", response.token, {
131+
maxAge: 86400 * 7,
132+
path: "/",
133+
});
113134
} catch (error) {
114135
console.log(error);
115136
alert("Ocorreu um erro, tente mais tarde");
116137
}
117138
};
118139

140+
const changeNumber = async () => {
141+
setUser(null);
142+
setIsLogged(false);
143+
};
144+
119145
useEffect(() => {
120146
getSession();
121-
}, []);
147+
}, [getSession]);
122148

123149
return (
124150
<Context.Provider
@@ -130,7 +156,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
130156
isOpen,
131157
login,
132158
setPin,
133-
token,
159+
changeNumber,
134160
}}
135161
>
136162
{children}

Diff for: src/components/LoginButton.tsx

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
2-
import { useState } from "react";
32
import { useAuth } from "./AuthContext";
3+
import { hiddenPhone } from "@/utils/hiddenNumber";
44

55
export const LoginButton = () => {
66
const { isLogged, openLogin, user, logout } = useAuth();
@@ -16,7 +16,7 @@ export const LoginButton = () => {
1616
}
1717
}}
1818
>
19-
{isLogged && user?.whatsapp ? user?.whatsapp : "Entrar"}
19+
{isLogged && user?.whatsapp ? hiddenPhone(user?.whatsapp) : "Entrar"}
2020
</button>
2121
</DropdownMenu.Trigger>
2222

Diff for: src/components/LoginForm.tsx

+75-24
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import * as Dialog from "@radix-ui/react-dialog";
22

33
import { Controller, useForm } from "react-hook-form";
44
import { useAuth } from "./AuthContext";
5+
import { DDI } from "@/utils/DDI";
6+
import { useEffect } from "react";
57

68
export const LoginForm = () => {
79
const { isLogged, openLogin, user, login, isOpen } = useAuth();
@@ -10,22 +12,35 @@ export const LoginForm = () => {
1012
control,
1113
handleSubmit,
1214
formState: { isSubmitting },
15+
watch,
16+
reset,
1317
} = useForm({
1418
defaultValues: {
1519
whatsapp: "",
20+
country: "+55",
1621
},
1722
});
1823

1924
const onSubmit = async (data: any) => {
20-
await new Promise((resolve) => setTimeout(resolve, 1500));
21-
login({ whatsapp: data.whatsapp });
25+
try {
26+
const whatsapp = [data.country, data.whatsapp].join("");
27+
login({ whatsapp });
28+
} catch (error) {
29+
console.log(error);
30+
}
2231
};
32+
33+
useEffect(() => {
34+
if (!isOpen) {
35+
reset();
36+
}
37+
}, [isOpen, reset]);
2338
return (
2439
<Dialog.Root
2540
open={isOpen}
2641
onOpenChange={(state) => {
2742
if (!isSubmitting) {
28-
openLogin(state);
43+
openLogin({ status: state });
2944
}
3045
}}
3146
>
@@ -38,32 +53,68 @@ export const LoginForm = () => {
3853
>
3954
<form noValidate onSubmit={handleSubmit(onSubmit)}>
4055
<Dialog.Title className="text-zinc-900 m-0 text-[17px] font-medium">
41-
Acesso ao Sistema
56+
Bem-vindo ao nosso gerador
4257
</Dialog.Title>
4358
<Dialog.Description className="text-zinc-600 mt-[10px] mb-5 text-[15px] leading-normal">
44-
Bem-vindo ao nosso sistema! Para proporcionar uma experiência
45-
personalizada e segura, solicitamos seu nome e número de contato.
59+
Para proporcionar uma experiência personalizada e segura,
60+
solicitamos seu número de whatsapp{" "}
61+
<strong>apenas para te enviar a figurinha</strong>.
4662
</Dialog.Description>
4763

4864
<Controller
4965
control={control}
5066
name="whatsapp"
51-
render={(props) => (
52-
<fieldset className="mb-[15px] flex items-center gap-5">
53-
<label
54-
className="text-violet11 w-[90px] text-right text-[15px]"
55-
htmlFor={props.field.name}
56-
>
57-
Whatsapp
58-
</label>
59-
<input
60-
id={props.field.name}
61-
className="text-violet11 shadow-violet7 focus:shadow-violet8 inline-flex h-[35px] w-full flex-1 items-center justify-center rounded-[4px] px-[10px] text-[15px] leading-none shadow-[0_0_0_1px] outline-none focus:shadow-[0_0_0_2px]"
62-
disabled={!user?.isAuthenticated && isLogged}
63-
{...props.field}
64-
/>
65-
</fieldset>
66-
)}
67+
render={(props) => {
68+
const country = watch("country");
69+
const placeholder = DDI.find((ddi) => ddi.ddi === country);
70+
return (
71+
<div>
72+
<label
73+
className="block text-sm font-medium leading-6 text-gray-900"
74+
htmlFor={props.field.name}
75+
>
76+
Whatsapp
77+
</label>
78+
<div className="relative mt-2 rounded-md shadow-sm">
79+
<Controller
80+
control={control}
81+
name="country"
82+
render={(selectProps) => {
83+
return (
84+
<div className="absolute inset-y-0 left-0 flex items-center">
85+
<label htmlFor="country" className="sr-only">
86+
Country
87+
</label>
88+
<select
89+
id="country"
90+
autoComplete="country"
91+
className="h-full rounded-md border-0 bg-transparent py-0 pl-3 pr-7 text-gray-500 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm"
92+
disabled={!user?.isAuthenticated && isLogged}
93+
{...selectProps.field}
94+
>
95+
{DDI.map(({ ddi, sigla }) => (
96+
<option value={ddi} key={ddi}>
97+
{sigla}
98+
</option>
99+
))}
100+
</select>
101+
</div>
102+
);
103+
}}
104+
/>
105+
106+
<input
107+
type="text"
108+
id={props.field.name}
109+
className="block w-full rounded-md border-0 py-1.5 pl-20 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
110+
placeholder={placeholder?.placeholder}
111+
disabled={!user?.isAuthenticated && isLogged}
112+
{...props.field}
113+
/>
114+
</div>
115+
</div>
116+
);
117+
}}
67118
/>
68119

69120
<span className="text-xs text-zinc-400 leading-none">
@@ -76,7 +127,7 @@ export const LoginForm = () => {
76127
data-loading={isSubmitting}
77128
type="button"
78129
className="inline-flex h-[35px] border items-center justify-center rounded-[4px] px-[15px] font-medium leading-none focus:shadow-[0_0_0_2px] focus:outline-none data-[loading=true]:cursor-not-allowed"
79-
onClick={() => openLogin(false)}
130+
onClick={() => openLogin({ status: false })}
80131
disabled={isSubmitting}
81132
>
82133
Voltar
@@ -87,7 +138,7 @@ export const LoginForm = () => {
87138
className="bg-indigo-600 text-white hover:bg-indigo-400 focus:shadow-green7 inline-flex h-[35px] items-center justify-center rounded-[4px] px-[15px] font-medium leading-none focus:shadow-[0_0_0_2px] focus:outline-none data-[loading=true]:cursor-not-allowed"
88139
disabled={isSubmitting}
89140
>
90-
{isSubmitting ? "Enviando...." : "Cadastrar"}
141+
{isSubmitting ? "Enviando...." : "Próximo"}
91142
</button>
92143
</div>
93144
<Dialog.Close asChild>

0 commit comments

Comments
 (0)