Skip to content

Commit

Permalink
signup-auth
Browse files Browse the repository at this point in the history
  • Loading branch information
Hendrixer committed Dec 13, 2021
1 parent ad88728 commit 169b99d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/prisma.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { PrismaClient } from '@prisma/client'

export default new PrismaClient()
48 changes: 48 additions & 0 deletions pages/api/signup.ts
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)
}

0 comments on commit 169b99d

Please sign in to comment.