This commit is contained in:
Pablo Lara
2024-10-02 16:09:26 +02:00
parent 6e37d8d850
commit a72b33597d
17 changed files with 133 additions and 135 deletions
-55
View File
@@ -1,55 +0,0 @@
"use server";
import { AuthError } from "next-auth";
import { z } from "zod";
import { signIn, signOut } from "@/auth.config";
import { authFormSchema } from "@/types";
const formSchemaSignIn = authFormSchema("sign-in");
const defaultValues: z.infer<typeof formSchemaSignIn> = {
email: "",
password: "",
};
export async function authenticate(
prevState: unknown,
formData: z.infer<typeof formSchemaSignIn>,
) {
try {
await new Promise((resolve) => setTimeout(resolve, 2000));
await signIn("credentials", {
...formData,
redirect: false,
});
return {
message: "Success",
};
} catch (error) {
if (error instanceof AuthError) {
switch (error.type) {
case "CredentialsSignin":
return {
message: "Credentials error",
errors: {
...defaultValues,
credentials: "Incorrect email or password",
},
};
default:
return {
message: "Unknown error",
errors: {
...defaultValues,
unknown: "Unknown error",
},
};
}
}
}
}
export async function logOut() {
await signOut();
}
+102
View File
@@ -0,0 +1,102 @@
"use server";
import { AuthError } from "next-auth";
import { z } from "zod";
import { signIn, signOut } from "@/auth.config";
import { authFormSchema } from "@/types";
const formSchemaSignIn = authFormSchema("sign-in");
// const formSchemaSignUp = authFormSchema("sign-up");
const defaultValues: z.infer<typeof formSchemaSignIn> = {
email: "",
password: "",
};
export async function authenticate(
prevState: unknown,
formData: z.infer<typeof formSchemaSignIn>,
) {
try {
await signIn("credentials", {
...formData,
redirect: false,
});
return {
message: "Success",
};
} catch (error) {
if (error instanceof AuthError) {
switch (error.type) {
case "CredentialsSignin":
return {
message: "Credentials error",
errors: {
...defaultValues,
credentials: "Incorrect email or password",
},
};
default:
return {
message: "Unknown error",
errors: {
...defaultValues,
unknown: "Unknown error",
},
};
}
}
}
}
export const getToken = async (formData: z.infer<typeof formSchemaSignIn>) => {
const keyServer = process.env.API_BASE_URL;
const url = new URL(`${keyServer}/tokens`);
const bodyData = {
data: {
type: "Token",
attributes: {
email: formData.email,
password: formData.password,
},
},
};
try {
const response = await fetch(url.toString(), {
method: "POST",
headers: {
"Content-Type": "application/vnd.api+json",
Accept: "application/vnd.api+json",
},
body: JSON.stringify(bodyData),
});
if (!response.ok) {
return null;
}
const data = await response.json();
// 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,
// 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;
}
};
export async function logOut() {
await signOut();
}
+1
View File
@@ -0,0 +1 @@
export * from "./auth";
@@ -1,2 +1 @@
export * from "./auth";
export * from "./providers";
@@ -11,8 +11,6 @@ export const getProviders = async ({
sort = "",
filters = {},
}) => {
// const session = await auth();
if (isNaN(Number(page)) || page < 1) redirect("/providers");
const keyServer = process.env.API_BASE_URL;
@@ -46,7 +44,6 @@ export const getProviders = async ({
};
export const getProvider = async (formData: FormData) => {
// const session = await auth();
const providerId = formData.get("id");
const keyServer = process.env.API_BASE_URL;
@@ -69,7 +66,6 @@ export const getProvider = async (formData: FormData) => {
};
export const updateProvider = async (formData: FormData) => {
// const session = await auth();
const keyServer = process.env.API_BASE_URL;
const providerId = formData.get("providerId");
@@ -106,7 +102,6 @@ export const updateProvider = async (formData: FormData) => {
};
export const addProvider = async (formData: FormData) => {
// const session = await auth();
const keyServer = process.env.API_BASE_URL;
const providerType = formData.get("providerType");
@@ -145,7 +140,6 @@ export const addProvider = async (formData: FormData) => {
};
export const checkConnectionProvider = async (formData: FormData) => {
// const session = await auth();
const keyServer = process.env.API_BASE_URL;
const providerId = formData.get("id");
@@ -170,7 +164,6 @@ export const checkConnectionProvider = async (formData: FormData) => {
};
export const deleteProvider = async (formData: FormData) => {
// const session = await auth();
const keyServer = process.env.API_BASE_URL;
const providerId = formData.get("id");
+1 -1
View File
@@ -1,7 +1,7 @@
import { Spacer } from "@nextui-org/react";
import { Suspense } from "react";
import { getProviders } from "@/actions";
import { getProviders } from "@/actions/providers";
import { FilterControls, filtersProviders } from "@/components/filters";
import { AddProvider } from "@/components/providers";
import {
+6 -34
View File
@@ -1,34 +1,8 @@
import bcryptjs from "bcryptjs";
import NextAuth, { type NextAuthConfig } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { z } from "zod";
import { userMockData } from "./lib";
// const key = new TextEncoder().encode(process.env.AUTH_SECRET);
// const SALT_ROUNDS = 10;
// export async function hashPassword(password: string) {
// return hash(password, SALT_ROUNDS);
// }
async function getUser(email: string, password: string): Promise<any | null> {
// Check if the user exists in the userMockData array.
const user = userMockData.find((user) => user.email === email);
if (!user) return null;
if (!bcryptjs.compareSync(password, user.password)) return null;
return {
id: user.id,
tenantId: user.tenantId,
name: user.name,
companyName: user.companyName,
email: user.email,
role: user.role,
image: user.image,
};
}
import { getToken } from "./actions/auth";
export const authConfig = {
session: {
@@ -65,6 +39,7 @@ export const authConfig = {
session({ session, token }) {
session.user = token.data as any;
console.log("session", session);
return session;
},
},
@@ -83,15 +58,12 @@ export const authConfig = {
})
.safeParse(credentials);
if (!parsedCredentials.success) {
return null;
}
const { email, password } = parsedCredentials.data;
console.log("email", email);
console.log("password", password);
if (!parsedCredentials.success) return null;
const user = await getToken(parsedCredentials.data);
const user = await getUser(email, password);
if (!user) return null;
return user;
},
}),
+1 -3
View File
@@ -9,7 +9,7 @@ import { useFormState } from "react-dom";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { authenticate } from "@/actions";
import { authenticate } from "@/actions/auth";
import {
Form,
FormControl,
@@ -53,14 +53,12 @@ export const AuthForm = ({ type }: { type: string }) => {
try {
// Sign-up logic will be here.
if (type === "sign-in") {
console.log(data);
dispatch({
email: data.email.toLowerCase(),
password: data.password,
});
}
if (type === "sign-up") {
console.log(data);
// const newUser = await signUp(data);
}
} catch (error) {
@@ -2,7 +2,7 @@
import { useRef } from "react";
import { checkConnectionProvider } from "@/actions";
import { checkConnectionProvider } from "@/actions/providers";
import { CustomButtonClientAction } from "../ui/custom";
import { useToast } from "../ui/toast";
+1 -1
View File
@@ -5,7 +5,7 @@ import { Dispatch, SetStateAction } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { addProvider } from "@/actions";
import { addProvider } from "@/actions/providers";
import { SaveIcon } from "@/components/icons";
import { useToast } from "@/components/ui";
import { CustomButton, CustomInput } from "@/components/ui/custom";
+1 -1
View File
@@ -5,7 +5,7 @@ import React, { Dispatch, SetStateAction } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { deleteProvider } from "@/actions";
import { deleteProvider } from "@/actions/providers";
import { DeleteIcon } from "@/components/icons";
import { useToast } from "@/components/ui";
import { CustomButton } from "@/components/ui/custom";
+1 -1
View File
@@ -5,7 +5,7 @@ import { Dispatch, SetStateAction } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { updateProvider } from "@/actions";
import { updateProvider } from "@/actions/providers";
import { SaveIcon } from "@/components/icons";
import { useToast } from "@/components/ui";
import { CustomButton, CustomInput } from "@/components/ui/custom";
+1 -1
View File
@@ -9,7 +9,7 @@ import { useSession } from "next-auth/react";
import React, { useCallback } from "react";
import { useMediaQuery } from "usehooks-ts";
import { logOut } from "@/actions";
import { logOut } from "@/actions/auth";
import { useUIStore } from "@/store";
import {
-1
View File
@@ -1,3 +1,2 @@
export * from "./custom";
export * from "./seed";
export * from "./utils";
-25
View File
@@ -1,25 +0,0 @@
import bcryptjs from "bcryptjs";
import { v4 as uuidv4 } from "uuid";
export const userMockData = [
{
id: uuidv4(), // Generate a unique UUID.
tenantId: "12646005-9067-4d2a-a098-8bb378604362",
email: "admin@prowler.com",
name: "Admin Prowler",
companyName: "Prowler",
password: bcryptjs.hashSync("123123", 10),
role: "admin",
image: null,
},
{
id: uuidv4(), // Generate a unique UUID.
tenantId: "12646005-9067-4d2a-a098-8bb378604362",
email: "user@prowler.com",
name: "User Prowler",
companyName: "Prowler",
password: bcryptjs.hashSync("123123", 10),
role: "user",
image: null,
},
];
+15 -3
View File
@@ -32,6 +32,8 @@
"date-fns": "^3.6.0",
"framer-motion": "~11.1.1",
"intl-messageformat": "^10.5.0",
"jose": "^5.9.3",
"jwt-decode": "^4.0.0",
"lucide-react": "^0.417.0",
"next": "^14.2.12",
"next-auth": "^5.0.0-beta.20",
@@ -9423,9 +9425,10 @@
}
},
"node_modules/jose": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/jose/-/jose-5.7.0.tgz",
"integrity": "sha512-3P9qfTYDVnNn642LCAqIKbTGb9a1TBxZ9ti5zEVEr48aDdflgRjhspWFb6WM4PzAfFbGMJYC4+803v8riCRAKw==",
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/jose/-/jose-5.9.3.tgz",
"integrity": "sha512-egLIoYSpcd+QUF+UHgobt5YzI2Pkw/H39ou9suW687MY6PmCwPmkNV/4TNjn1p2tX5xO3j0d0sq5hiYE24bSlg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
@@ -9507,6 +9510,15 @@
"node": ">=4.0"
}
},
"node_modules/jwt-decode": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
+2
View File
@@ -24,6 +24,8 @@
"date-fns": "^3.6.0",
"framer-motion": "~11.1.1",
"intl-messageformat": "^10.5.0",
"jose": "^5.9.3",
"jwt-decode": "^4.0.0",
"lucide-react": "^0.417.0",
"next": "^14.2.12",
"next-auth": "^5.0.0-beta.20",