-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.ts
More file actions
108 lines (92 loc) · 2.41 KB
/
Copy pathsession.ts
File metadata and controls
108 lines (92 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import { cache } from 'react';
import { auth } from './auth';
import { headers } from 'next/headers';
import { db } from './db';
import { teamMembers, teams } from '@/drizzle/schema';
import { eq } from 'drizzle-orm';
/**
* Get current user session
* Cached per-request to avoid multiple auth calls
*/
export const getCurrentSession = cache(async () => {
return auth.api.getSession({
headers: await headers(),
});
});
/**
* Get current user's team with full details
* Cached per-request to avoid multiple DB queries
*
* Returns the user's team from DB instead of relying on session.user.currentTeamId
* which may not be up-to-date after onboarding
*
* Includes retry logic to handle potential DB timing issues after login
*/
export const getCurrentTeam = cache(async () => {
const session = await getCurrentSession();
if (!session?.user) {
return null;
}
// Retry logic to handle DB timing issues
const maxRetries = 3;
const retryDelay = 100; // ms
for (let attempt = 0; attempt < maxRetries; attempt++) {
// Get user's team from DB
const userTeam = await db.query.teamMembers.findFirst({
where: eq(teamMembers.userId, session.user.id),
with: {
team: {
with: {
organization: true,
},
},
},
});
if (userTeam?.team) {
return userTeam.team;
}
// Wait before retrying (except on last attempt)
if (attempt < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, retryDelay));
}
}
return null;
});
/**
* Get current team ID
* Convenience wrapper for getCurrentTeam
*/
export const getCurrentTeamId = cache(async () => {
const team = await getCurrentTeam();
return team?.id || null;
});
/**
* Get current organization ID
* Convenience wrapper for getCurrentTeam
*/
export const getCurrentOrganizationId = cache(async () => {
const team = await getCurrentTeam();
return team?.organizationId || null;
});
/**
* Require authentication
* Throws error if user is not authenticated
*/
export async function requireAuth() {
const session = await getCurrentSession();
if (!session?.user) {
throw new Error('Unauthorized');
}
return session;
}
/**
* Require team membership
* Throws error if user doesn't have a team
*/
export async function requireTeam() {
const team = await getCurrentTeam();
if (!team) {
throw new Error('No team found');
}
return team;
}