Skip to content

Commit

Permalink
chore: work continues on authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
Franqsanz committed Jan 4, 2024
1 parent 83217c3 commit 38c23bf
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 60 deletions.
25 changes: 16 additions & 9 deletions src/hooks/querys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
useInfiniteQuery,
QueryClient,
} from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';

import {
getAllBooks,
Expand All @@ -20,6 +21,7 @@ import {
postRegister,
getUserAndBooks,
} from '../services/api';
import { logOut } from '../services/firebase/auth';
import { keys } from '../utils/utils';
import { BookType } from '../components/types';

Expand Down Expand Up @@ -148,10 +150,19 @@ function useBook(pathUrl: string | undefined) {

// Usuarios

function useUserRegister(token: string) {
function useUserRegister() {
const navigate = useNavigate();

return useMutation({
mutationKey: ['post-token', token],
mutationFn: () => postRegister(token),
mutationKey: [keys.userRegister],
mutationFn: (token: string) => postRegister(token),
onSuccess: (data) => {
if (data) return navigate(`/profile/${data.info.user.uid}`);
},
onError: async (error) => {
console.error('Error en el servidor:', error);
await logOut();
},
});
}

Expand All @@ -160,12 +171,8 @@ function useProfile(
// token: string | undefined
) {
return useSuspenseQuery({
queryKey: ['profile', id],
queryFn: () =>
getUserAndBooks(
id,
// token
),
queryKey: [keys.profile, id],
queryFn: () => getUserAndBooks(id),
gcTime: 3000,
});
}
Expand Down
10 changes: 5 additions & 5 deletions src/pages/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import { SignIn } from '../services/firebase/auth';
export function Login() {
return (
<>
<MainHead title='Iniciar Sesión | XBuniverse' />
<ContainerTitle title='Iniciar Sesión' />
<MainHead title='Ingresar | XBuniverse' />
<ContainerTitle title='Ingresar' />
<Flex justify='center' py={{ base: '10vh', md: '31vh' }}>
<Stack direction='column' spacing='5'>
<Stack direction='column' spacing='3'>
<SignIn />
{/* <Button
fontWeight='normal'
Expand All @@ -26,9 +26,9 @@ export function Login() {
_hover={{ bg: '#242424' }}
_active={{ bg: 'black' }}
>
<Box fontSize='md'>(ex Twitter)</Box>
Continuar con X
</Button>
<Button
<Button
fontWeight='normal'
leftIcon={<BsFacebook />}
colorScheme='facebook'
Expand Down
2 changes: 0 additions & 2 deletions src/services/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ async function postRegister(token: string) {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'content-type': 'application/json',
},
});

Expand All @@ -100,7 +99,6 @@ async function getUserAndBooks(
// method: 'GET',
// headers: {
// Authorization: `Bearer ${token}`,
// 'Content-Type': 'application/json',
// },
// }
);
Expand Down
58 changes: 14 additions & 44 deletions src/services/firebase/auth.tsx
Original file line number Diff line number Diff line change
@@ -1,53 +1,30 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, useColorModeValue } from '@chakra-ui/react';
import { GrGoogle } from 'react-icons/gr';
import {
GoogleAuthProvider,
signInWithPopup,
// signInWithRedirect,
// getRedirectResult,
signOut,
} from 'firebase/auth';
import { GoogleAuthProvider, signInWithPopup, signOut } from 'firebase/auth';

import { logIn } from './config';
import { API_URL } from '../../config';
// import { useUserRegister } from '../../hooks/querys';
import { useUserRegister } from '../../hooks/querys';
// import { useAuth } from '../../store/AuthContext';

const provider = new GoogleAuthProvider();

provider.setCustomParameters({ prompt: 'select_account ' });

function SignIn() {
const navigate = useNavigate();
// const { mutate } = useUserRegister(token);
const { mutateAsync, isPending, isError, isSuccess } = useUserRegister();
let errorUI;

if (isError) {
errorUI = <h1>error de conexion</h1>;
}

async function signInWithGoogle() {
try {
const result = await signInWithPopup(logIn, provider);
const token = await result.user.getIdToken();
// await signInWithRedirect(logIn, provider);

// Obtener el resultado de la redirección
// const result = await getRedirectResult(logIn);

// mutate(token);
const serverResponse = await fetch(`${API_URL}/auth/register`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'content-type': 'application/json',
},
});

if (serverResponse.ok) {
// El registro en el servidor fue exitoso, navegar a la página de perfil
navigate(`/profile/${result.user.uid}`);
} else {
console.error('Error en el servidor:', serverResponse.statusText);
await DisconnectFirebaseAccount();
}
return mutateAsync(token);
} catch (error) {
await DisconnectFirebaseAccount();
console.warn(error);
Expand All @@ -71,7 +48,7 @@ function SignIn() {
return (
<>
<Button
w='250px'
w='275px'
fontWeight='normal'
leftIcon={<GrGoogle />}
bg={useColorModeValue('#EA4335', '#EE685D')}
Expand All @@ -82,23 +59,16 @@ function SignIn() {
_hover={{ bg: '#D23C2F' }}
_active={{ bg: '#BB352A' }}
onClick={signInWithGoogle}
loadingText='Redirigiendo...'
isLoading={isPending}
>
Google
Continuar con Google
</Button>
<div>{errorUI}</div>
</>
);
}

// async function login() {
// try {
// const result = await signInWithPopup(logIn, provider);
// const token = await result.user.getIdToken();
// console.log(result);
// } catch (error) {
// console.log(error);
// }
// }

async function logOut() {
try {
await signOut(logIn);
Expand Down
2 changes: 2 additions & 0 deletions src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ const keys = {
random: 'BooksRandom',
relatedBooks: 'RelatedBooks',
moreBooksAuthors: 'MoreBooksAuthors',
userRegister: 'UserRegister',
profile: 'Profile',
};

function handleImageLoad(e: React.SyntheticEvent) {
Expand Down

1 comment on commit 38c23bf

@vercel
Copy link

@vercel vercel bot commented on 38c23bf Jan 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

xbu – ./

xbu-git-main-franqsanz.vercel.app
xbu.vercel.app
xbu-franqsanz.vercel.app

Please sign in to comment.