Skip to content
Draft

WIP #115

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createContext, useEffect, useState } from "react";
import { destroyCookie, parseCookies, setCookie } from "nookies";

import { signInRequest, updateUserProfile, userMe } from "../services/auth";
import { Toast } from "@/components/Toast";

type SignInData = {
email: string;
Expand Down Expand Up @@ -43,6 +44,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [token, setToken] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const { addToast } = Toast();

const isAuthenticated = !!user;

Expand All @@ -68,6 +70,11 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
});
})
.catch(() => {
addToast({
title: "Erro ao carregar usuário.",
message: "Ocorreu um erro ao carregar seus dados.",
type: "error"
});
signOut();
});
} catch (error) {
Expand Down
15 changes: 15 additions & 0 deletions src/pages/auth/signin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,11 @@ export default function SignIn() {
}
};

const handleGoogleSignIn = () => {
const strapiGoogleSignInUrl = `${process.env.NEXT_PUBLIC_STRAPI_URL}/api/connect/google`;
router.push(strapiGoogleSignInUrl);
};

return (
<>
<Head>
Expand Down Expand Up @@ -200,6 +205,16 @@ export default function SignIn() {
>
Entrar
</Button>
<ChakraLink
onClick={handleGoogleSignIn}
color="gray.600"
mt="4"
textAlign="center"
textDecoration="underline"
fontWeight="medium"
>
Entrar com Google
</ChakraLink>
<ChakraLink
onClick={() => router.push("/auth/forgot-password")}
color="gray.600"
Expand Down
123 changes: 123 additions & 0 deletions src/pages/auth/signin_bkp.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// import * as yup from "yup";
import { Input } from "../../components/Form/Input";
import { signIn } from "next-auth/react";
import { useRouter } from "next/router";
// import { yupResolver } from "@hookform/resolvers/yup";
import { LogoSkateHub } from "@/components/LogoSkateHub";
import { SubmitHandler, useForm } from "react-hook-form";
import { Button, Flex, Stack, Text } from "@chakra-ui/react";

import { Toast } from "@/components/Toast";

type SignInFormData = {
email: string;
password: string;
};

// const signInFormSchema = yup.object().shape({
// email: yup.string().required("E-mail obrigatório").email("E-mail inválido"),
// password: yup.string().required("Password obrigatório")
// });

export default function SignIn() {
const router = useRouter();
// const { data: session } = useSession();
const { addToast } = Toast();

const { register, handleSubmit, formState } = useForm({
// resolver: yupResolver(signInFormSchema)
});

const { errors } = formState;

const handleSignIn: SubmitHandler<SignInFormData> = async values => {
const result = await signIn("credentials", {
redirect: false,
email: values.email,
password: values.password
});

if (result?.status === 200) {
router.replace("/dashboard");
return;
} else {
addToast({
title: "Erro de autenticação.",
message: "Verifique seus dados de login e tente novamente.",
type: "error"
});
}
};

// useEffect(() => {
// if (session === null) return;
// console.log("session.jwt...", session?.jwt);
// }, [session]);

return (
<Flex w="100vw" h="100vh" alignItems="center" justifyContent="center" flexDirection="column">
{/* <div className="">
<h1>{session ? "Authenticated" : "Not authenticated"}</h1>
<div className="">
{session && (
<>
<h3>Session data</h3>
<p>E-mail: {session.user.email}</p>
<p>JWT from Strapi: Check console</p>
</>
)}
</div>
{session ? (
<button onClick={() => signOut()}>Sign out</button>
) : (
<Link href="/auth/signin">
<button>Sign In</button>
</Link>
)}
</div> */}

<Flex
as="form"
w="100%"
maxWidth={360}
bg="gray.800"
p="8"
borderRadius={8}
flexDir="column"
// onSubmit={handleSubmit(handleSignIn)}
>
<Stack spacing={4}>
<Flex justifyContent="center" mb="4">
<LogoSkateHub />
</Flex>

<Flex flexDir="column">
<Input
id="email"
type="email"
label="E-mail"
{...register("email")}
// error={errors.email}
/>
</Flex>
<Flex flexDir="column">
<Input
id="password"
type="password"
label="Senha"
{...register("password")}
// error={errors.password}
/>
</Flex>
</Stack>

<Button type="submit" mt="6" colorScheme="green" size="lg" isLoading={formState.isSubmitting}>
Entrar
</Button>
<Text as="a" href="#" color="gray.600" mt="4" align={"center"} textDecoration={"underline"}>
Esqueci minha senha
</Text>
</Flex>
</Flex>
);
}
19 changes: 19 additions & 0 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,20 @@ import { redirectIfAuthenticated } from "@/utils/auth";
export default function Home() {
const router = useRouter();

// useEffect(() => {
// // insert nookies to remove cache
// const handleSessionExpired = () => {
// destroyCookie(undefined, "auth.token");
// };

// const checkSessionValidity = () => {
// const { "auth.token": token } = parseCookies();
// console.log(token);
// };

// checkSessionValidity();
// }, []);

return (
<>
<Head>
Expand Down Expand Up @@ -70,6 +84,11 @@ export default function Home() {
Criar uma conta
</Button>
</Flex>
<Flex>
Nós usamos cookies e outras tecnologias semelhantes para melhorar a sua experiência em nossos serviços,
personalizar publicidade e recomendar conteúdo de seu interesse. Ao utilizar nossos serviços, você
concorda com tal monitoramento. Para mais informações, consulte a nossa nova política de privacidade.
</Flex>
</Flex>
<Flex alignItems="center" justifyContent="center" flexDirection="row">
<Text
Expand Down
4 changes: 4 additions & 0 deletions src/services/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,17 @@ export async function signInRequest({ email, password }: SignInData) {
}

export async function userMe(token: string) {
// use qs library to stringify the url with params
// npm i qs
const res = await axios.get(`${API}/api/users/me?populate[avatar][fields][0]=url`, {
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
}
});

console.log("res...", res);

if (!res.data) {
throw new Error("Failed to fetch user.");
}
Expand Down
20 changes: 20 additions & 0 deletions src/services/auth_bkp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import axios from "axios";

const strapiUrl = process.env.STRAPI_URL;

// export async function signIn({ email, password }) {
// const response = await fetch(`${strapiUrl}/api/auth/local`, {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ identifier: email, password }),
// });
// return response.json();
// }

export async function signIn({ email, password }: { email: string; password: string }) {
const res = await axios.post(`${strapiUrl}/api/auth/local`, {
identifier: email,
password
});
return res.data;
}