Built Twitter Like App - 10

Add Register Function Code

Add file pages/api/register.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
import bcrypt, { compareSync } from 'bcrypt';

import prisma from '../../libs/prismadb';
import { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if ( req.method !== 'POST'){
return res.status(405).end();
}

try{
const { email,username, name, password } = req.body

const hashedPassword = await bcrypt.hash(password, 12);

const user = await prisma.user.create({
data: {
email,
username,
name,
hashedPassword
}
});

return res.status(200).json(user)
} catch (error){
console.log(error);
return res.status(400).end();
}
}

Add CurrentLog Code

Add file libs/serverAuth.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
import { NextApiRequest } from "next";
import { getSession } from 'next-auth/react'

import prisma from "../libs/prismadb"

const serverAuth = async (req: NextApiRequest) => {
const session = await getSession({req})

if(!session?.user?.email){
throw new Error('Not signed in');
}

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

if(!currentUser){
throw new Error('Not signed in');
}

return { currentUser};
}

export default serverAuth;"

Add file pages/api/current.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { NextApiRequest, NextApiResponse } from 'next';
import serverAuth from '../../libs/serverAuth';

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if ( req.method !== 'GET'){
return res.status(405).end();
}

try{
const { currentUser } = await serverAuth(req);

return res.status(200).json(currentUser);
} catch (error){
console.log(error);
return res.status(400).end();
}
}

请我喝杯咖啡吧~

支付宝
微信