Skip to content

Commit

Permalink
Update auth
Browse files Browse the repository at this point in the history
  • Loading branch information
salimi-my committed Apr 22, 2024
1 parent 276e71d commit b6f86a5
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 69 deletions.
36 changes: 21 additions & 15 deletions auth.config.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,38 @@
import { compare } from 'bcryptjs';
import type { NextAuthConfig } from 'next-auth';
import credentials from 'next-auth/providers/credentials';
import Credentials from 'next-auth/providers/credentials';

import prismadb from '@/lib/prismadb';
import { LoginSchema } from '@/schemas';
import { getUserByEmail } from '@/data/user';

export default {
providers: [
credentials({
Credentials({
credentials: {
email: {
label: 'Email',
type: 'email'
},
password: {
label: 'Password',
type: 'password'
}
},
async authorize(credentials) {
if (
!credentials.email ||
!credentials.password ||
typeof credentials.email !== 'string' ||
typeof credentials.password !== 'string'
) {
const validatedFields = LoginSchema.safeParse(credentials);

if (!validatedFields.success) {
return null;
}

const user = await prismadb.user.findUnique({
where: {
email: credentials.email
}
});
const { email, password } = validatedFields.data;

const user = await getUserByEmail(email);

if (
!user ||
!user.hashedPassword ||
!(await compare(credentials.password, user.hashedPassword))
!(await compare(password, user.hashedPassword))
) {
return null;
}
Expand Down
32 changes: 5 additions & 27 deletions auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { PrismaAdapter } from '@auth/prisma-adapter';

import prismadb from '@/lib/prismadb';
import authConfig from '@/auth.config';
import { getUserById } from '@/data/user';

export const {
handlers: { GET, POST },
Expand All @@ -16,7 +17,7 @@ export const {
error: '/auth/sign-in'
},
callbacks: {
async session({ token, session, trigger, newSession }) {
async session({ token, session }) {
if (token.sub && session.user) {
session.user.id = token.sub;
}
Expand All @@ -26,32 +27,14 @@ export const {
session.user.email = token.email;
}

if (
session.user &&
trigger === 'update' &&
newSession?.name &&
newSession?.email
) {
session.user.name = newSession.name;
session.user.email = newSession.email;
}

return session;
},
async jwt({ user, token, trigger, session }) {
if (user) {
token.sub = user.id;
}

if (!user) {
async jwt({ token }) {
if (!token.sub) {
return token;
}

const existingUser = await prismadb.user.findUnique({
where: {
id: token.sub
}
});
const existingUser = await getUserById(token.sub);

if (!existingUser) {
return token;
Expand All @@ -60,11 +43,6 @@ export const {
token.name = existingUser.name;
token.email = existingUser.email;

if (trigger === 'update' && session?.name && session?.email) {
token.name = session.name;
token.email = session.email;
}

return token;
}
},
Expand Down
12 changes: 4 additions & 8 deletions components/auth/sign-in-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { useSearchParams } from 'next/navigation';
import { AlertTriangle, Loader2 } from 'lucide-react';
import { zodResolver } from '@hookform/resolvers/zod';

import { LoginSchema } from '@/schemas';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { DEFAULT_SIGNIN_REDIRECT } from '@/routes';
Expand All @@ -29,11 +30,6 @@ import {
FormMessage
} from '@/components/ui/form';

const formSchema = z.object({
email: z.string().email({ message: 'Please enter valid email address.' }),
password: z.string().min(1, { message: 'Please enter password.' })
});

export default function SignInForm() {
const searchParams = useSearchParams();
const callbackUrl = searchParams.get('callbackUrl');
Expand All @@ -45,15 +41,15 @@ export default function SignInForm() {
error = 'Invalid email or password.';
}

const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
const form = useForm<z.infer<typeof LoginSchema>>({
resolver: zodResolver(LoginSchema),
defaultValues: {
email: '',
password: ''
}
});

const onSubmit = async (values: z.infer<typeof formSchema>) => {
const onSubmit = async (values: z.infer<typeof LoginSchema>) => {
try {
setLoading(true);

Expand Down
23 changes: 4 additions & 19 deletions components/auth/sign-up-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import axios, { AxiosError } from 'axios';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

import { RegisterSchema } from '@/schemas';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/ui/use-toast';
Expand All @@ -28,28 +29,12 @@ import {
CardTitle
} from '@/components/ui/card';

const formSchema = z
.object({
name: z.string().min(1, { message: 'Please enter name.' }),
email: z.string().email({ message: 'Please enter valid email address.' }),
password: z
.string()
.min(8, { message: 'Please enter at least 8 characters.' }),
confirm: z
.string()
.min(8, { message: 'Please enter at least 8 characters.' })
})
.refine((data) => data.password === data.confirm, {
message: 'Passwords does not match.',
path: ['confirm']
});

export default function SignUpForm() {
const { toast } = useToast();
const [loading, setLoading] = useState(false);

const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
const form = useForm<z.infer<typeof RegisterSchema>>({
resolver: zodResolver(RegisterSchema),
defaultValues: {
name: '',
email: '',
Expand All @@ -58,7 +43,7 @@ export default function SignUpForm() {
}
});

const onSubmit = async (values: z.infer<typeof formSchema>) => {
const onSubmit = async (values: z.infer<typeof RegisterSchema>) => {
try {
setLoading(true);

Expand Down
29 changes: 29 additions & 0 deletions data/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import prismadb from '@/lib/prismadb';

export async function getUserByEmail(email: string) {
try {
const user = await prismadb.user.findUnique({
where: {
email
}
});

return user;
} catch {
return null;
}
}

export async function getUserById(id: string) {
try {
const user = await prismadb.user.findUnique({
where: {
id
}
});

return user;
} catch {
return null;
}
}
23 changes: 23 additions & 0 deletions schemas/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as z from 'zod';

export const LoginSchema = z.object({
email: z.string().email({ message: 'Please enter valid email address.' }),
password: z.string().min(1, { message: 'Please enter password.' }),
code: z.optional(z.string())
});

export const RegisterSchema = z
.object({
name: z.string().min(1, { message: 'Please enter name.' }),
email: z.string().email({ message: 'Please enter valid email address.' }),
password: z
.string()
.min(8, { message: 'Please enter at least 8 characters.' }),
confirm: z
.string()
.min(8, { message: 'Please enter at least 8 characters.' })
})
.refine((data) => data.password === data.confirm, {
message: 'Passwords does not match.',
path: ['confirm']
});

0 comments on commit b6f86a5

Please sign in to comment.