This commit is contained in:
Pablo Lara
2024-10-02 17:22:34 +02:00
parent a72b33597d
commit 8e7dfcaa76
3 changed files with 21 additions and 12 deletions
+18 -7
View File
@@ -1,11 +1,17 @@
"use server";
import { jwtDecode, JwtPayload } from "jwt-decode";
import { AuthError } from "next-auth";
import { z } from "zod";
import { signIn, signOut } from "@/auth.config";
import { parseStringify } from "@/lib";
import { authFormSchema } from "@/types";
interface CustomJwtPayload extends JwtPayload {
user_id: string;
}
const formSchemaSignIn = authFormSchema("sign-in");
// const formSchemaSignUp = authFormSchema("sign-up");
@@ -75,25 +81,30 @@ export const getToken = async (formData: z.infer<typeof formSchemaSignIn>) => {
});
if (!response.ok) {
return null;
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const parsedData = parseStringify(data);
const accessToken = parsedData.data.attributes.access;
const refreshToken = parsedData.data.attributes.refresh;
const decodedToken = jwtDecode<CustomJwtPayload>(accessToken);
const userId = decodedToken.user_id;
// Verify if the response contains the expected data
if (data && data.data && data.data.attributes) {
// const token = data.data.attributes.access;
// const decodedToken = jwtDecode(token);
return {
// userId: decodedToken.user_id,
email: formData.email,
// token: token,
accessToken,
refreshToken,
userId,
// Add here other user fields we need in the session
};
}
} catch (error) {
// eslint-disable-next-line no-console
console.error("Error en getToken:", error);
return null;
console.error("Error en trying to get token:", error);
}
};
+2 -2
View File
@@ -18,12 +18,12 @@ export const authConfig = {
const isOnDashboard = nextUrl.pathname.startsWith("/");
const isSignUpPage = nextUrl.pathname === "/sign-up";
// Permitir acceso a /sign-up incluso si no está autenticado
// Allow access to sign-up page
if (isSignUpPage) return true;
if (isOnDashboard) {
if (isLoggedIn) return true;
return false; // Redirigir usuarios no autenticados a la página de login
return false; // Redirect users who are not logged in to the login page
} else if (isLoggedIn) {
return Response.redirect(new URL("/", nextUrl));
}
+1 -3
View File
@@ -48,8 +48,6 @@ export const AuthForm = ({ type }: { type: string }) => {
}, [state]);
const onSubmit = async (data: z.infer<typeof formSchema>) => {
// Do something with the form values
// this will be type-safe and validated
try {
// Sign-up logic will be here.
if (type === "sign-in") {
@@ -183,7 +181,7 @@ export const AuthForm = ({ type }: { type: string }) => {
{state?.message === "Credentials error" && (
<div className="flex flex-row items-center gap-2 text-system-error">
<NotificationIcon size={16} />
<p className="text-s">Incorrect email or password</p>
<p className="text-s">No user found</p>
</div>
)}