({
ctx,
}: InferProcedureOpts<typeof baseProcedure>)
| 12 | export const refreshProcedure = once(() => baseProcedure.mutation(refresh)); |
| 13 | |
| 14 | export async function refresh({ |
| 15 | ctx, |
| 16 | }: InferProcedureOpts<typeof baseProcedure>) { |
| 17 | // Check if loggedIn cookie exists |
| 18 | |
| 19 | if (ctx.req.cookies.loggedIn == null) { |
| 20 | throw new TRPCError({ |
| 21 | message: 'User not logged in.', |
| 22 | code: 'UNAUTHORIZED', |
| 23 | }); |
| 24 | } |
| 25 | |
| 26 | // Check if refresh token exists |
| 27 | |
| 28 | if (ctx.req.cookies.refreshToken == null) { |
| 29 | throw new TRPCError({ |
| 30 | message: 'No refresh token received.', |
| 31 | code: 'UNAUTHORIZED', |
| 32 | }); |
| 33 | } |
| 34 | |
| 35 | // Verify JWT |
| 36 | |
| 37 | let jwtPayload = verifyRefreshJWT<RefreshTokenPayload>( |
| 38 | ctx.req.cookies.refreshToken, |
| 39 | ); |
| 40 | |
| 41 | if (jwtPayload == null) { |
| 42 | jwtPayload = decodeRefreshJWT<RefreshTokenPayload>( |
| 43 | ctx.req.cookies.refreshToken, |
| 44 | ); |
| 45 | |
| 46 | if (jwtPayload != null) { |
| 47 | await ctx.dataAbstraction.patch('session', jwtPayload.sid, { |
| 48 | invalidated: true, |
| 49 | }); |
| 50 | } |
| 51 | |
| 52 | throw new TRPCError({ |
| 53 | message: 'Invalid refresh token.', |
| 54 | code: 'UNAUTHORIZED', |
| 55 | }); |
| 56 | } |
| 57 | |
| 58 | // Get session data |
| 59 | |
| 60 | const session = await SessionModel.query() |
| 61 | .where('refresh_code', jwtPayload.rfc) |
| 62 | .first(); |
| 63 | |
| 64 | // Check if session is valid |
| 65 | |
| 66 | if ( |
| 67 | session == null || |
| 68 | session.invalidated || |
| 69 | new Date() > session.expiration_date |
| 70 | ) { |
| 71 | throw new TRPCError({ |
nothing calls this directly
no test coverage detected