Skip to content

Commit

Permalink
feat: fix some issues
Browse files Browse the repository at this point in the history
Co-authored-by: Mateus Maia <mateusmaiamaia@hotmail.com>
Co-authored-by: Matheus Monteiro <matheusyanmonteiro@gmail.com>
  • Loading branch information
3 people committed Dec 9, 2024
1 parent 681a002 commit ba3643b
Show file tree
Hide file tree
Showing 14 changed files with 76 additions and 48 deletions.
4 changes: 2 additions & 2 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="icon" type="image/svg+xml" href="/logo.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
<title>Livro Livre</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
Expand Down
Binary file added public/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 0 additions & 1 deletion public/vite.svg

This file was deleted.

1 change: 1 addition & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ function App() {
<BrowserRouter>
<Routes>
<Route path="*" element={<NotFound />} />
<Route path="/" element={<PrivateRoute><Home /></PrivateRoute>} />
<Route path="/login" element={<SignIn />} />
<Route path="/cadastro" element={<SignUp />} />
<Route path="/recuperar-senha" element={<RecoverPassword />} />
Expand Down
6 changes: 3 additions & 3 deletions src/PrivateRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import { useEffect } from "react";

const PrivateRoute = ({ children }: { children: any }) => {
const navigate = useNavigate();
const { token } = useAuth();
const { isAuthenticated } = useAuth();

useEffect(() => {
if (token) return;
if (isAuthenticated) return;
navigate('/login');
})
}, [isAuthenticated])

return children;
}
Expand Down
20 changes: 14 additions & 6 deletions src/hooks/useApi/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const useApi = () => {
);

return {
getProfile: (token: string): Promise<{ data: User }> => {
getProfile: (token: string | null): Promise<{ data: User }> => {
return new Promise((resolve) => {
api
.get('/auth/profile', {
Expand Down Expand Up @@ -91,29 +91,37 @@ const useApi = () => {
.catch((err) => resolve(getDefaultErrorUseAPIMessage(err)));
});
},
editProfile: async (id: string, data: {
editProfile: async (data: {
firstName: string;
lastName: string;
email: string;
phone: string;
oldPassword?: string
newPassword?: string
}): Promise<{ data: {
}, token: string | null): Promise<{ data: {
id: string;
} }> => {
return new Promise((resolve) => {
api
.put(`/users/${id}`, data)
.put('/users', data, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => resolve(res))
.catch((err) => resolve(getDefaultErrorUseAPIMessage(err)));
});
},
deleteProfile: async (id: string): Promise<{ data: {
deleteProfile: async (token: string | null): Promise<{ data: {
id: string;
} }> => {
return new Promise((resolve) => {
api
.delete(`/users/${id}`)
.delete('/users', {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => resolve(res))
.catch((err) => resolve(getDefaultErrorUseAPIMessage(err)));
});
Expand Down
21 changes: 15 additions & 6 deletions src/hooks/useAuth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { createContext, useState, useContext, ReactNode } from 'react';

import useApi from './useApi';
import { toaster } from '../components/ui/toaster';
import { User } from '../interfaces/user';

interface SignUpParams {
firstName: string;
Expand Down Expand Up @@ -33,9 +34,10 @@ type AuthContextType = {
signOut: () => void;
signUp: (userToSignUp: SignUpParams) => Promise<boolean>;
signIn: (userToSignIn: SignInParams) => Promise<boolean>;
editProfile: (id: string, profileToEdit: EditProfileParams) => Promise<boolean>;
editProfile: (profileToEdit: EditProfileParams) => Promise<boolean>;
recoverPassword: (email: string) => Promise<boolean>;
changePassword: (password: string, token: string) => Promise<boolean>;
changePassword: (password: string, mailToken: string) => Promise<boolean>;
getProfile: () => Promise<User>;
};

const AuthContext = createContext({} as AuthContextType);
Expand All @@ -47,6 +49,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
editProfile: authEditProfile,
recoverPassword: authRecoverPassword,
changePassword: authChangePassword,
getProfile: authGetProfile,
} = useApi();

const localToken =
Expand Down Expand Up @@ -91,6 +94,11 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
return true;
}

async function getProfile(): Promise<User> {
const { data } = await authGetProfile(token);
return data;
}

async function recoverPassword(email: string): Promise<boolean> {
const { data } = await authRecoverPassword(email);
if (data.success) {
Expand All @@ -108,8 +116,8 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
return false;
}

async function changePassword(password: string, token: string): Promise<boolean> {
const { data } = await authChangePassword(password, token);
async function changePassword(password: string, mailToken: string): Promise<boolean> {
const { data } = await authChangePassword(password, mailToken);
if (data.success) {
toaster.create({
title: 'Senha alterada com sucesso! Você será redirecionado para o login...',
Expand All @@ -125,8 +133,8 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
return false;
}

async function editProfile(id: string, profileToEdit: EditProfileParams): Promise<boolean> {
const { data } = await authEditProfile(id, profileToEdit);
async function editProfile(profileToEdit: EditProfileParams): Promise<boolean> {
const { data } = await authEditProfile(profileToEdit, token);
if (data.id) {
toaster.create({
title: 'Perfil editado com sucesso!',
Expand Down Expand Up @@ -160,6 +168,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
signIn,
recoverPassword,
changePassword,
getProfile,
}}
>
{children}
Expand Down
10 changes: 4 additions & 6 deletions src/pages/Profile/DeleteProfileDialog/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,12 @@ import { useNavigate } from "react-router"

const DeleteProfileDialog = () => {
const navigate = useNavigate();
const { deleteProfile, getProfile } = useApi();
const { token, signOut } = useAuth();
const { deleteProfile } = useApi();
const { signOut, getProfile } = useAuth();

const handleDelete = async () => {
console.log('maia', 123)
if (!token) return;
const { data } = await getProfile(token);
await deleteProfile(data.id);
const profile = await getProfile();
await deleteProfile(profile.id);
signOut();
navigate('/login');
}
Expand Down
25 changes: 11 additions & 14 deletions src/pages/ProfileEdit/ProfileEditForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { Input, Stack } from '@chakra-ui/react';
import { useForm } from 'react-hook-form';
import { PasswordInput } from '../../../components/ui/password-input';
import { Button } from '../../../components/ui/button';
import useApi from '../../../hooks/useApi';
import { Field } from '../../../components/ui/field';

interface FormValues {
Expand All @@ -18,7 +17,6 @@ interface FormValues {
}

function SignUpForm() {
const [userId, setUserId] = useState('');
const [loading, setLoading] = useState(false);

const {
Expand All @@ -27,19 +25,18 @@ function SignUpForm() {
setValue,
watch,
formState: { errors, isValid },
trigger,
} = useForm<FormValues>();

const { editProfile, token } = useAuth();
const { getProfile } = useApi();
const { editProfile, getProfile } = useAuth();

const getUserData = async () => {
if (!token) return;
const { data } = await getProfile(token);
setValue('firstName', data.firstName);
setValue('lastName', data.lastName);
setValue('email', data.email);
setValue('phone', data.phone);
setUserId(data.id)
const profile = await getProfile();
setValue('firstName', profile.firstName);
setValue('lastName', profile.lastName);
setValue('email', profile.email);
setValue('phone', profile.phone);
trigger();
}

useEffect(() => {
Expand All @@ -48,7 +45,7 @@ function SignUpForm() {

const onSubmit = handleSubmit(async (data: FormValues) => {
setLoading(true);
await editProfile(userId, {
await editProfile({
firstName: data.firstName,
lastName: data.lastName,
email: data.email,
Expand Down Expand Up @@ -111,14 +108,14 @@ function SignUpForm() {
<PasswordInput
size={'2xl'}
placeholder={'Senha nova'}
{...register('newPassword', { required: watch('oldPassword') !== '' })}
{...register('newPassword', { required: !!watch('oldPassword') })}
/>
<Field invalid={!!errors.newPasswordConfirmation} errorText={errors.newPasswordConfirmation?.message}>
<PasswordInput
size={'2xl'}
placeholder={'Confirmar senha nova'}
{...register('newPasswordConfirmation', {
required: watch('newPassword') !== '',
required: !!watch('newPassword'),
validate: value => value === watch('newPassword') || 'As senhas não coincidem.',
})}
/>
Expand Down
6 changes: 3 additions & 3 deletions src/pages/SignIn/SignInForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ function SignInForm() {
formState: { errors, isValid },
} = useForm<FormValues>();

const { signIn, token } = useAuth();
const { signIn, isAuthenticated } = useAuth();

const onSubmit = handleSubmit(async (data: FormValues) => {
setLoading(true);
Expand All @@ -34,9 +34,9 @@ function SignInForm() {
})

useEffect(() => {
if (!token) return;
if (!isAuthenticated) return;
navigate('/inicio');
}, [token])
}, [isAuthenticated])

return (
<form onSubmit={onSubmit}>
Expand Down
10 changes: 10 additions & 0 deletions src/pages/SignIn/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,18 @@ import { Box, Center, Stack } from '@chakra-ui/react';
import SignInForm from './SignInForm';
import SignUpButton from './SignUpButton';
import SignInHeader from './SignInHeader';
import { useNavigate } from 'react-router';
import { useAuth } from '../../hooks/useAuth';
import { useEffect } from 'react';

function SignIn() {
const navigate = useNavigate();
const { isAuthenticated } = useAuth();

useEffect(() => {
if (isAuthenticated) navigate('/inicio');
}, [isAuthenticated])

return (
<Box padding='40px'>
<Center>
Expand Down
6 changes: 3 additions & 3 deletions src/pages/SignUp/SignUpForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function SignUpForm() {
formState: { errors, isValid },
} = useForm<FormValues>();

const { signUp, token } = useAuth();
const { signUp, isAuthenticated } = useAuth();

const onSubmit = handleSubmit(async (data: FormValues) => {
setLoading(true);
Expand All @@ -41,9 +41,9 @@ function SignUpForm() {
})

useEffect(() => {
if (!token) return;
if (!isAuthenticated) return;
navigate('/inicio');
}, [token])
}, [isAuthenticated])

return (
<form onSubmit={onSubmit}>
Expand Down
10 changes: 10 additions & 0 deletions src/pages/SignUp/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,18 @@ import { Box, Center, Stack } from '@chakra-ui/react';
import SignUpForm from './SignUpForm';
import LoginButton from './LoginButton';
import SignUpHeader from './SignUpHeader';
import { useAuth } from '../../hooks/useAuth';
import { useNavigate } from 'react-router';
import { useEffect } from 'react';

function SignUp() {
const navigate = useNavigate();
const { isAuthenticated } = useAuth();

useEffect(() => {
if (isAuthenticated) navigate('/inicio');
}, [isAuthenticated])

return (
<Box padding='40px'>
<Center>
Expand Down
4 changes: 0 additions & 4 deletions test/App.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import React from "react";
import '@testing-library/jest-dom'
import { render } from "@testing-library/react"
import App from "../src/App"

test("Renders the main page", () => {
render(<App />)
expect(true).toBeTruthy()
})

0 comments on commit ba3643b

Please sign in to comment.