Authentication with Credentials is working and setup, same for OAuth with Google.

This commit is contained in:
charles-gauthereau
2024-11-09 21:38:18 +01:00
parent 6541cfcc26
commit 6d90bb23c1
24 changed files with 784 additions and 341 deletions
+43 -106
View File
@@ -1,137 +1,74 @@
// import {PrismaAdapter} from "@auth/prisma-adapter";
// import NextAuth from "next-auth";
// import {prisma} from "@/prisma";
// import Credentials from "next-auth/providers/credentials";
//
//
// export const {handlers, auth: baseAuth, signIn, signOut} = NextAuth({
// adapter: PrismaAdapter(prisma),
// theme: {
// logo: "/icon.png"
// },
// pages: {
// signIn: "/login",
// },
// debug: process.env.NODE_ENV !== "production",
// providers: [
// Credentials({
// credentials: { password: { label: "Password", type: "password" } },
// authorize(c) {
// if (c.password !== "password") return null
// return {
// id: "test",
// name: "Test User",
// email: "test@example.com",
// }
// },
// }),
// ],
// callbacks: {
// session({ session, user, token }) {
// session.user.role = user.role
//
// return session
// }
// },
// events: {
// createUser: async (message) => {
// const userId = message.user.id
// const userEmail = message.user.email
//
// if (!userId || !userEmail) {
// return;
// }
//
// // const stripeCustomer = await stripe.customers.create({
// // name: message.user.name ?? "",
// // email: userEmail,
// // })
// //
// // await prisma.user.update({
// // where: {
// // id: userId,
// // },
// // data: {
// // stripeCustomerId: stripeCustomer.id,
// // }
// // })
// }
// }
//
//
// });
//
// export const providerMap = providers
// .map((provider) => {
// if (typeof provider === "function") {
// const providerData = provider()
// return { id: providerData.id, name: providerData.name }
// } else {
// return { id: provider.id, name: provider.name }
// }
// })
// .filter((provider) => provider.id !== "credentials")
import NextAuth from "next-auth";
import NextAuth, {CredentialsSignin} from "next-auth";
import {prisma} from "@/prisma";
import {PrismaAdapter} from "@auth/prisma-adapter";
import Credentials from "next-auth/providers/credentials";
import {env} from "@/env.mjs";
import GoogleProvider from "next-auth/providers/google";
class InvalidLoginError extends CredentialsSignin {
code = "Invalid identifier or password"
}
export const {handlers, auth: baseAuth, signIn, signOut} = NextAuth({
adapter: PrismaAdapter(prisma),
theme: {
logo: "/icon.png"
logo: "/logo.png"
},
secret: env.NEXT_PUBLIC_SECRET,
debug: process.env.NODE_ENV !== "production",
providers: [
Credentials({
// You can specify which fields should be submitted, by adding keys to the `credentials` object.
// e.g. domain, username, password, 2FA token, etc.
name: "Credentials",
credentials: {
email: {},
password: {},
email: {label: "Email", type: "email"},
password: {label: "Password", type: "password"},
},
authorize: async (credentials) => {
let user = null
const argon2 = require('argon2');
console.log(credentials);
// // logic to salt and hash password
// const pwHash = saltAndHashPassword(credentials.password)
//
// // logic to verify if the user exists
// user = await getUserFromDb(credentials.email, pwHash)
//
// if (!user) {
// // No user found, so this is their first attempt to login
// // Optionally, this is also the place you could do a user registration
// throw new Error("Invalid credentials.")
// }
//
// // return user object with their profile data
return user
user = await prisma.user.findFirst({
where: {
email: credentials.email,
}
})
if (!user) {
return null
}
const isValid = await argon2.verify(user.password, credentials.password)
if (!isValid) {
return null
}
return user;
},
}),
GoogleProvider({
clientId: env.AUTH_GOOGLE_ID,
clientSecret: env.AUTH_GOOGLE_SECRET,
allowDangerousEmailAccountLinking: true,
profile(profile) {
return {
// role: profile.email === "soluce.technologies@gmail.com" ? "admin" : "user",
name: profile.name,
email: profile.email,
image: profile.picture,
}
},
// credentials: { password: { label: "Password", type: "password" } },
// authorize(c) {
// if (c.password !== "password") return null
// console.log(c)
// return {
// id: "test",
// name: "Test User",
// email: "test@example.com",
// }
// },
})
],
session: {
strategy: "jwt",
},
pages: {
signIn: "/login",
error: "/error"
},
callbacks: {
session({ session, user, token }) {
session.user.role = user.role
session({session, user, token}) {
// session.user.role = user.role
return session
}
},
});
-4
View File
@@ -3,20 +3,16 @@ import {User} from "@prisma/client";
export const currentUser = async () => {
const session = await baseAuth();
if (!session?.user) {
return null;
}
return session.user as User;
}
export const requiredCurrentUser = async () => {
const user = await currentUser();
if (!user) {
throw new Error("User not found");
}
return user;
}
@@ -0,0 +1,105 @@
"use client";
import {Card, CardContent, CardHeader} from "@/components/ui/card";
import {
FormControl, FormField, FormItem, FormLabel, FormMessage, useZodForm
} from "@/components/ui/form";
import {Input} from "@/components/ui/input";
import {Form} from "@/components/ui/form"
import {Button} from "@/components/ui/button";
import {toast} from "sonner";
import {useMutation} from "@tanstack/react-query";
import {TooltipProvider} from "@/components/ui/tooltip";
import Link from "next/link";
import {PasswordInput} from "@/components/wrappers/PaswordInput/password-input";
import {LoginSchema, LoginType} from "@/components/wrappers/Auth/Login/LoginForm/login-form-schema";
import {signInAction} from "@/features/auth/auth.action";
import {SocialAuthButton} from "@/components/wrappers/Auth/Login/SocialAuth/SocialAuthButtons/SocialAuthButton";
export type loginFormProps = {
defaultValues?: LoginType;
}
export const LoginForm = (props: loginFormProps) => {
const form = useZodForm({
schema: LoginSchema,
});
const mutation = useMutation({
mutationFn: async (values: LoginType) => {
const result = await signInAction("credentials", values)
if(result?.error){
toast.error(result.error)
}
}
})
return (
<TooltipProvider>
<Card>
<CardHeader>
<div className="grid gap-2 text-center mb-2">
<h1 className="text-3xl font-bold">Login</h1>
<p className="text-balance text-muted-foreground">
Enter your informations bellow to login
</p>
</div>
</CardHeader>
<CardContent>
<Form form={form}
className="flex flex-col gap-4"
onSubmit={async (values) => {
await mutation.mutateAsync(values);
}}
>
<FormField
control={form.control}
name="email"
render={({field}) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input
placeholder="exemple@portabase.com" {...field} />
</FormControl>
<FormMessage/>
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({field}) => (
<FormItem>
<div className="flex items-center">
<FormLabel>Password</FormLabel>
<Link
href="/forgot-password"
className="ml-auto inline-block text-sm underline"
>
Forgot your password?
</Link>
</div>
<FormControl>
<PasswordInput placeholder="Your password" {...field}/>
</FormControl>
<FormMessage/>
</FormItem>
)}
/>
<Button>
Sign in
</Button>
<div className="mt-4 text-center text-sm">
Don&apos;t have an account?{" "}
<Link href="/register" className="underline">
Sign up
</Link>
</div>
</Form>
<SocialAuthButton/>
</CardContent>
</Card>
</TooltipProvider>
)
}
@@ -0,0 +1,9 @@
import {z} from "zod";
export const LoginSchema = z.object({
email: z.string(),
password: z.string(),
});
export type LoginType = z.infer<typeof LoginSchema>;
@@ -0,0 +1,22 @@
"use client"
import {signInAction} from "@/features/auth/auth.action";
import {Button} from "@/components/ui/button";
import Image from "next/image";
export type SocialAuthButtonProps = {}
export const SocialAuthButton = (props: SocialAuthButtonProps) => {
return (
<div className="flex flex-col gap-4 mt-5">
<Button
onClick={(e) => {
e.preventDefault();
void signInAction("google")
}}
>
<Image src="/google-icon.png" alt="Google OAuth" width={25} height={25}/>
Sign in with google
</Button>
</div>
)
}
@@ -1,8 +1,8 @@
"use client";
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {Card, CardContent, CardHeader} from "@/components/ui/card";
import {
FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, useZodForm
FormControl, FormField, FormItem, FormLabel, FormMessage, useZodForm
} from "@/components/ui/form";
import {Input} from "@/components/ui/input";
import {Form} from "@/components/ui/form"
@@ -13,8 +13,6 @@ import {useMutation} from "@tanstack/react-query";
import {TooltipProvider, TooltipTrigger, Tooltip, TooltipContent} from "@/components/ui/tooltip";
import {RegisterSchema, RegisterType} from "@/components/wrappers/Auth/Register/RegisterForm/register-form.schema";
import {registerUserAction} from "@/components/wrappers/Auth/Register/RegisterForm/register-form.action";
import {Label} from "@/components/ui/label";
import Link from "next/link";
import {Info} from "lucide-react";
import {PasswordInput} from "@/components/wrappers/PaswordInput/password-input";
@@ -27,9 +25,7 @@ export const RegisterForm = (props: registerFormProps) => {
const form = useZodForm({
schema: RegisterSchema,
});
const router = useRouter();
const mutation = useMutation({
mutationFn: async (values: RegisterType) => {
console.log(values)
@@ -48,10 +44,8 @@ export const RegisterForm = (props: registerFormProps) => {
return (
<TooltipProvider>
<Card>
<CardHeader>
<div className="grid gap-2 text-center mb-2">
<h1 className="text-3xl font-bold">Create an account</h1>
<p className="text-balance text-muted-foreground">
@@ -66,7 +60,6 @@ export const RegisterForm = (props: registerFormProps) => {
await mutation.mutateAsync(values);
}}
>
<FormField
control={form.control}
name="name"
@@ -77,7 +70,6 @@ export const RegisterForm = (props: registerFormProps) => {
<Input
placeholder="Your name" {...field} />
</FormControl>
{/*<FormDescription>{t('tabs.general.data.name.description')}</FormDescription>*/}
<FormMessage/>
</FormItem>
)}
@@ -92,7 +84,6 @@ export const RegisterForm = (props: registerFormProps) => {
<Input
placeholder="exemple@portabase.com" {...field} />
</FormControl>
{/*<FormDescription>{t('tabs.general.data.name.description')}</FormDescription>*/}
<FormMessage/>
</FormItem>
)}
@@ -102,7 +93,6 @@ export const RegisterForm = (props: registerFormProps) => {
name="password"
render={({field}) => (
<FormItem>
<FormLabel className="flex">Password
<TooltipProvider>
<Tooltip>
@@ -115,18 +105,6 @@ export const RegisterForm = (props: registerFormProps) => {
</Tooltip>
</TooltipProvider>
</FormLabel>
{/*<div className="flex items-center">*/}
{/* <FormLabel>Password</FormLabel>*/}
{/* <Link*/}
{/* href="/forgot-password"*/}
{/* className="ml-auto inline-block text-sm underline"*/}
{/* >*/}
{/* Forgot your password?*/}
{/* </Link>*/}
{/*</div>*/}
<FormControl>
<PasswordInput placeholder="Your password" {...field}/>
</FormControl>
@@ -139,25 +117,11 @@ export const RegisterForm = (props: registerFormProps) => {
name="confirmPassword"
render={({field}) => (
<FormItem>
<FormLabel>Password Confirmation</FormLabel>
{/*<div className="flex items-center">*/}
{/* <FormLabel>Password</FormLabel>*/}
{/* <Link*/}
{/* href="/forgot-password"*/}
{/* className="ml-auto inline-block text-sm underline"*/}
{/* >*/}
{/* Forgot your password?*/}
{/* </Link>*/}
{/*</div>*/}
<FormControl>
<PasswordInput
placeholder="Conform your password" {...field} />
</FormControl>
{/*<FormDescription>{t('tabs.general.data.name.description')}</FormDescription>*/}
<FormMessage/>
</FormItem>
)}
@@ -165,14 +129,7 @@ export const RegisterForm = (props: registerFormProps) => {
<Button>
Sign up
</Button>
{/*<div className="mt-4 text-center text-sm">*/}
{/* Don&apos;t have an account?{" "}*/}
{/* /!*<Link to="#" className="underline">*!/*/}
{/* /!* Sign up*!/*/}
{/* /!*</Link>*!/*/}
{/*</div>*/}
</Form>
</CardContent>
</Card>
</TooltipProvider>
@@ -1,6 +1,5 @@
import {z} from "zod";
// Minimum 8 characters, at least one uppercase letter, one lowercase letter, one number and one special character
const passwordValidation = new RegExp(
/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/
@@ -2,7 +2,6 @@
import * as React from 'react'
import { EyeIcon, EyeOffIcon } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input, type InputProps } from '@/components/ui/input'
import { cn } from '@/lib/utils'
@@ -34,8 +33,6 @@ const PasswordInput = React.forwardRef<HTMLInputElement, InputProps>(({ classNam
)}
<span className="sr-only">{showPassword ? 'Hide password' : 'Show password'}</span>
</Button>
{/* hides browsers password toggles */}
<style>{`
.hide-password-toggle::-ms-reveal,
.hide-password-toggle::-ms-clear {
@@ -1,3 +1,5 @@
"use client"
import {
Sidebar,
SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupContent,
@@ -9,9 +11,8 @@ import {
} from "@/components/ui/sidebar"
import {DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger} from "@/components/ui/dropdown-menu";
import {Calendar, ChevronDown, ChevronUp, Home, Inbox, Search, Settings, User2} from "lucide-react";
import {Separator} from "@radix-ui/react-menu";
import {Breadcrumb} from "@/components/ui/breadcrumb";
import Link from "next/link";
import {signOutAction} from "@/features/auth/auth.action";
export function AppSidebar() {
@@ -46,10 +47,6 @@ export function AppSidebar() {
},
]
return (
<Sidebar collapsible="icon">
<SidebarHeader>
@@ -113,7 +110,9 @@ export function AppSidebar() {
<DropdownMenuItem>
<span>Billing</span>
</DropdownMenuItem>
<DropdownMenuItem>
<DropdownMenuItem onClick={() => {
signOutAction()
}}>
<span>Sign out</span>
</DropdownMenuItem>
</DropdownMenuContent>
+7 -1
View File
@@ -14,7 +14,10 @@ export const env = createEnv({
SMTP_HOST: z.string(),
SMTP_PORT: z.string(),
SMTP_USER: z.string(),
NEXT_PUBLIC_SECRET: z.string()
NEXT_PUBLIC_SECRET: z.string(),
NEXTAUTH_URL: z.string(),
AUTH_GOOGLE_ID: z.string(),
AUTH_GOOGLE_SECRET: z.string(),
},
/*
* Environment variables available on the client (and server).
@@ -32,6 +35,7 @@ export const env = createEnv({
*/
runtimeEnv: {
NEXT_PUBLIC_SECRET: process.env.NEXT_PUBLIC_SECRET,
NEXTAUTH_URL: process.env.NEXTAUTH_URL,
NODE_ENV: process.env.NODE_ENV,
NEXT_PUBLIC_DOMAIN_NAME: process.env.NEXT_PUBLIC_DOMAIN_NAME,
DATABASE_URL: process.env.DATABASE_URL,
@@ -40,5 +44,7 @@ export const env = createEnv({
SMTP_HOST: process.env.SMTP_HOST,
SMTP_PORT: process.env.SMTP_PORT,
SMTP_USER: process.env.SMTP_USER,
AUTH_GOOGLE_ID: process.env.AUTH_GOOGLE_ID,
AUTH_GOOGLE_SECRET: process.env.AUTH_GOOGLE_SECRET,
},
});
+26
View File
@@ -0,0 +1,26 @@
"use server"
import {signIn, signOut} from "@/auth/auth";
import {redirect} from "next/navigation";
export const signOutAction = async () => {
await signOut({redirectTo: '/', redirect: true})
window.location.reload();
}
export const signInAction = async (type: string, formData?: any) => {
if (type === "google") {
await signIn(type, {redirectTo: '/dashboard'})
} else {
try {
await signIn(type, {
redirect: false,
password: formData.password,
email: formData.email
});
} catch (error) {
// const signInError = error as CredentialsSignin
console.error(error);
return {error: "Error loging in, please try again or check your credentials !"};
}
redirect("/")
}
}
+11 -5
View File
@@ -1,8 +1,14 @@
export async function hashPassword(password: string): Promise<string> {
const argon2 = require('argon2');
const hashedPassword = await argon2.hash(password);
return hashedPassword;
return await argon2.hash(password);
}
//Do not delete
// export async function saltAndHashPassword(password: string) {
// // Generate a salt and hash the password
// const salt = await bcrypt.genSalt(10);
// const hashedPassword = await bcrypt.hash(password, salt);
//
// // Return the hashed password
// return hashedPassword;
// }