50 lines
1.2 KiB
TypeScript
50 lines
1.2 KiB
TypeScript
import { FastifyInstance, FastifyReply } from 'fastify';
|
|
import { CookieSerializeOptions } from '@fastify/cookie';
|
|
import { User } from '@prisma/client';
|
|
import jwt from 'jsonwebtoken';
|
|
|
|
const cookieSettings: CookieSerializeOptions = {
|
|
httpOnly: true,
|
|
path: '/api/auth/refresh_token',
|
|
sameSite: 'strict',
|
|
maxAge: 2629800, //1 month
|
|
secure: process.env.NODE_ENV === 'production'
|
|
};
|
|
|
|
declare module 'fastify' {
|
|
interface FastifyReply {
|
|
sendTokens: (user: User) => FastifyReply;
|
|
clearTokens: () => FastifyReply;
|
|
}
|
|
}
|
|
|
|
export default async (server: FastifyInstance) =>
|
|
server
|
|
.decorateReply('sendTokens', function (this: FastifyReply, { id, nickname }: User) {
|
|
return this.setCookie(
|
|
'owo',
|
|
jwt.sign({ tokenVersion: 0, id }, process.env.JWT_REFRESH_SECRET, {
|
|
expiresIn: '30d'
|
|
}),
|
|
cookieSettings
|
|
).send({
|
|
user: {
|
|
id,
|
|
nickname
|
|
},
|
|
token: jwt.sign(
|
|
{
|
|
id,
|
|
nickname
|
|
},
|
|
process.env.JWT_ACCESS_SECRET,
|
|
{
|
|
expiresIn: '15m'
|
|
}
|
|
)
|
|
});
|
|
})
|
|
.decorateReply('clearTokens', function (this: FastifyReply) {
|
|
return this.clearCookie('owo', cookieSettings);
|
|
});
|