( token: string | null | undefined )
| 66 | }; |
| 67 | |
| 68 | export async function validateSessionToken( |
| 69 | token: string | null | undefined |
| 70 | ): Promise<SessionValidationResult> { |
| 71 | if (process.env.DEMO_USER_ID) { |
| 72 | return createDemoSession(process.env.DEMO_USER_ID); |
| 73 | } |
| 74 | |
| 75 | if (!token) { |
| 76 | return EMPTY_SESSION; |
| 77 | } |
| 78 | const sessionId = decodeSessionToken(token); |
| 79 | if (!sessionId) { |
| 80 | return EMPTY_SESSION; |
| 81 | } |
| 82 | const result = await db.session.findUnique({ |
| 83 | where: { |
| 84 | id: sessionId, |
| 85 | }, |
| 86 | include: { |
| 87 | user: true, |
| 88 | }, |
| 89 | }); |
| 90 | if (result === null) { |
| 91 | return EMPTY_SESSION; |
| 92 | } |
| 93 | const { user, ...session } = result; |
| 94 | if (Date.now() >= session.expiresAt.getTime()) { |
| 95 | await db.session.delete({ where: { id: sessionId } }); |
| 96 | return EMPTY_SESSION; |
| 97 | } |
| 98 | if (Date.now() >= session.expiresAt.getTime() - 1000 * 60 * 60 * 24 * 15) { |
| 99 | session.expiresAt = new Date(Date.now() + 1000 * 60 * 60 * 24 * 30); |
| 100 | await db.session.update({ |
| 101 | where: { |
| 102 | id: session.id, |
| 103 | }, |
| 104 | data: { |
| 105 | expiresAt: session.expiresAt, |
| 106 | }, |
| 107 | }); |
| 108 | } |
| 109 | return { session, user, userId: user.id }; |
| 110 | } |
| 111 | |
| 112 | export async function invalidateSession(sessionId: string): Promise<void> { |
| 113 | await db.session.delete({ where: { id: sessionId } }); |
no test coverage detected