feat: add user and session

This commit is contained in:
Daniel Soares committed 2021-12-15 14:05:27 -03:00
1 parent 5df44ceddc
commit e071c0a19b
11 files changed
+577 -9

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
import { User } from '@prisma/client'
import jwt from 'jsonwebtoken'
import { prisma } from '../services/prisma'
import { ExceptionError } from './error'
const EXPIRES_IN = 30 // days
const EXPIRES_IN_MS = EXPIRES_IN * 24 * 60 * 60 * 1000
export async function createSession(user: User) {
const { JWT_SECRET } = process.env
if (!JWT_SECRET) {
throw new ExceptionError('JWT_SECRET is not defined')
}
try {
const session = await prisma.session.create({
data: {
userId: user.id,
expiresAt: new Date(Date.now() + EXPIRES_IN_MS)
}
})
const payload = { role: user.role, sub: user.id }
const token = jwt.sign(payload, JWT_SECRET, {
expiresIn: '15m'
})
return { token, refreshToken: session.id }
} catch (err: any) {
throw new ExceptionError(err)
}
}
+9
View File
@@ -0,0 +1,9 @@
export class ExceptionError extends Error {
status: number
constructor(message: string, status: number = 400) {
super(message)
this.name = 'ExceptionError'
this.status = status
}
}