-
Notifications
You must be signed in to change notification settings - Fork 103
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
import { PrismaClient } from '@prisma/client' | ||
|
||
export default new PrismaClient() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import bcrypt from 'bcrypt' | ||
import jwt from 'jsonwebtoken' | ||
import cookie from 'cookie' | ||
import { NextApiRequest, NextApiResponse } from 'next' | ||
import prisma from '../../lib/prisma' | ||
|
||
export default async (req: NextApiRequest, res: NextApiResponse) => { | ||
const salt = bcrypt.genSaltSync() | ||
const { email, password } = req.body | ||
|
||
let user | ||
|
||
try { | ||
user = await prisma.user.create({ | ||
data: { | ||
email, | ||
password: bcrypt.hashSync(password, salt), | ||
}, | ||
}) | ||
} catch (e) { | ||
res.status(401) | ||
res.json({ error: 'User already exists' }) | ||
return | ||
} | ||
|
||
const token = jwt.sign( | ||
{ | ||
email: user.email, | ||
id: user.id, | ||
time: Date.now(), | ||
}, | ||
'hello', | ||
{ expiresIn: '8h' } | ||
) | ||
|
||
res.setHeader( | ||
'Set-Cookie', | ||
cookie.serialize('TRAX_ACCESS_TOKEN', token, { | ||
httpOnly: true, | ||
maxAge: 8 * 60 * 60, | ||
path: '/', | ||
sameSite: 'lax', | ||
secure: process.env.NODE_ENV === 'production', | ||
}) | ||
) | ||
|
||
res.json(user) | ||
} |