Built Twitter Like App - 9

Install bcrypt & type

1
2
npm install bcrypt
npm install -D @types/bcrypt

Install next-auth

1
2
npm install next-auth
npm install @next-auth/prisma-adapter

Add Auth Code

Add file pages/api/auth/[..nextauth].ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import bcrypt from 'bcrypt';
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { PrismaAdapter } from '@next-auth/prisma-adapter';

import prisma from "../../../libs/prismadb";

export default NextAuth({
adapter: PrismaAdapter(prisma),
providers: [
CredentialsProvider({
name: 'credentials',
credentials: {
email : { label: 'email', type: 'text'},
password : { label: 'password', type: 'password'},
},
async authorize(credentials) {
if (!credentials?.email || !credentials.password ) {
throw new Error('Invalid Credentials');
}

const user = await prisma.user.findUnique({
where: {
email: credentials.email
}
});

if(!user || !user?.hashedPassword ){
throw new Error('Invalid Credentials');
}

const isCorrectPassword = await bcrypt.compare(
credentials.password,
user.hashedPassword
);

if(!isCorrectPassword) {
throw new Error('Invalid Credentials');
}

return user;
}
})
],
debug: process.env.NODE_ENV === 'development',
session:{
strategy: 'jwt'
},
jwt:{
secret: process.env.NEXTAUTH_JWT_SECRET
},
secret: process.env.NEXTAUTH_SECRET
})

Modify file .env

1
2
3
4
DATABASE_URL="mysql://<user>:<password>@192.168.50.188:3501/TWDB"
NEXTAUTH_JWT_SECRET="NEXTAUTH_JWT_SECRET"
NEXTAUTH_SECRET="NEXTAUTH_SECRET"
NEXTAUTH_URL ="http://192.168.50.199:3000/"

请我喝杯咖啡吧~

支付宝
微信