|
1 | 1 | import { usersCrudHandlers } from "@/app/api/latest/users/crud"; |
2 | 2 | import { getProvider } from "@/oauth"; |
3 | | -import { TokenSet } from "@/oauth/providers/base"; |
4 | 3 | import { getPrismaClientForTenancy } from "@/prisma-client"; |
5 | 4 | import { createCrudHandlers } from "@/route-handlers/crud-handler"; |
6 | 5 | import { KnownErrors } from "@stackframe/stack-shared"; |
7 | 6 | import { connectedAccountAccessTokenCrud } from "@stackframe/stack-shared/dist/interface/crud/connected-accounts"; |
8 | 7 | import { userIdOrMeSchema, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields"; |
9 | 8 | import { getEnvVariable, getNodeEnvironment } from "@stackframe/stack-shared/dist/utils/env"; |
10 | | -import { StackAssertionError, StatusError, captureError } from "@stackframe/stack-shared/dist/utils/errors"; |
| 9 | +import { StatusError } from "@stackframe/stack-shared/dist/utils/errors"; |
11 | 10 | import { createLazyProxy } from "@stackframe/stack-shared/dist/utils/proxies"; |
12 | | -import { Result } from "@stackframe/stack-shared/dist/utils/results"; |
13 | | -import { extractScopes } from "@stackframe/stack-shared/dist/utils/strings"; |
| 11 | +import { retrieveOrRefreshAccessToken } from "../../../access-token-helpers"; |
14 | 12 |
|
15 | 13 |
|
16 | 14 | export const connectedAccountAccessTokenCrudHandlers = createLazyProxy(() => createCrudHandlers(connectedAccountAccessTokenCrud, { |
@@ -40,136 +38,34 @@ export const connectedAccountAccessTokenCrudHandlers = createLazyProxy(() => cre |
40 | 38 | } |
41 | 39 |
|
42 | 40 | const providerInstance = await getProvider(provider); |
43 | | - |
44 | | - // ====================== retrieve access token if it exists ====================== |
45 | 41 | const prisma = await getPrismaClientForTenancy(auth.tenancy); |
46 | | - const accessTokens = await prisma.oAuthAccessToken.findMany({ |
| 42 | + |
| 43 | + // Legacy endpoint: search tokens across ALL accounts for this provider and user |
| 44 | + const oauthAccounts = await prisma.projectUserOAuthAccount.findMany({ |
47 | 45 | where: { |
48 | 46 | tenancyId: auth.tenancy.id, |
49 | | - projectUserOAuthAccount: { |
50 | | - projectUserId: params.user_id, |
51 | | - configOAuthProviderId: params.provider_id, |
52 | | - }, |
53 | | - expiresAt: { |
54 | | - // is at least 5 minutes in the future |
55 | | - gt: new Date(Date.now() + 5 * 60 * 1000), |
56 | | - }, |
57 | | - isValid: true, |
58 | | - }, |
59 | | - include: { |
60 | | - projectUserOAuthAccount: true, |
| 47 | + projectUserId: params.user_id, |
| 48 | + configOAuthProviderId: params.provider_id, |
61 | 49 | }, |
| 50 | + select: { id: true }, |
62 | 51 | }); |
63 | | - const filteredTokens = accessTokens.filter((t) => { |
64 | | - return extractScopes(data.scope || "").every((scope) => t.scopes.includes(scope)); |
65 | | - }); |
66 | | - for (const token of filteredTokens) { |
67 | | - // some providers (particularly GitHub) invalidate access tokens on the server-side, in which case we want to request a new access token |
68 | | - if (await providerInstance.checkAccessTokenValidity(token.accessToken)) { |
69 | | - return { access_token: token.accessToken }; |
70 | | - } else { |
71 | | - // mark the token as invalid |
72 | | - await prisma.oAuthAccessToken.update({ |
73 | | - where: { |
74 | | - id: token.id, |
75 | | - }, |
76 | | - data: { |
77 | | - isValid: false, |
78 | | - }, |
79 | | - }); |
80 | | - } |
81 | | - } |
82 | 52 |
|
83 | | - // ============== no valid access token found, try to refresh the token ============== |
| 53 | + if (oauthAccounts.length === 0) { |
| 54 | + throw new KnownErrors.OAuthConnectionNotConnectedToUser(); |
| 55 | + } |
84 | 56 |
|
85 | | - const refreshTokens = await prisma.oAuthToken.findMany({ |
86 | | - where: { |
| 57 | + return await retrieveOrRefreshAccessToken({ |
| 58 | + prisma, |
| 59 | + providerInstance, |
| 60 | + tenancyId: auth.tenancy.id, |
| 61 | + oauthAccountIds: oauthAccounts.map(a => a.id), |
| 62 | + scope: data.scope, |
| 63 | + errorContext: { |
87 | 64 | tenancyId: auth.tenancy.id, |
88 | | - projectUserOAuthAccount: { |
89 | | - projectUserId: params.user_id, |
90 | | - configOAuthProviderId: params.provider_id, |
91 | | - }, |
92 | | - isValid: true, |
93 | | - }, |
94 | | - include: { |
95 | | - projectUserOAuthAccount: true, |
| 65 | + providerId: params.provider_id, |
| 66 | + userId: params.user_id, |
| 67 | + scope: data.scope, |
96 | 68 | }, |
97 | 69 | }); |
98 | | - |
99 | | - const filteredRefreshTokens = refreshTokens.filter((t) => { |
100 | | - return extractScopes(data.scope || "").every((scope) => t.scopes.includes(scope)); |
101 | | - }); |
102 | | - |
103 | | - if (filteredRefreshTokens.length === 0) { |
104 | | - throw new KnownErrors.OAuthConnectionDoesNotHaveRequiredScope(); |
105 | | - } |
106 | | - |
107 | | - for (const token of filteredRefreshTokens) { |
108 | | - let tokenSetResult: Result<TokenSet, string>; |
109 | | - try { |
110 | | - tokenSetResult = await providerInstance.getAccessToken({ |
111 | | - refreshToken: token.refreshToken, |
112 | | - scope: data.scope, |
113 | | - }); |
114 | | - } catch (error) { |
115 | | - // Unexpected errors (not handled by the provider) are logged and we continue to the next token |
116 | | - captureError('oauth-access-token-refresh-unexpected-error', new StackAssertionError('Unexpected error refreshing access token — this may indicate a bug or misconfiguration', { |
117 | | - error, |
118 | | - tenancyId: auth.tenancy.id, |
119 | | - providerId: params.provider_id, |
120 | | - userId: params.user_id, |
121 | | - scope: data.scope, |
122 | | - })); |
123 | | - |
124 | | - tokenSetResult = Result.error("Unexpected error refreshing access token"); |
125 | | - } |
126 | | - |
127 | | - if (tokenSetResult.status === "error") { |
128 | | - await prisma.oAuthToken.update({ |
129 | | - where: { id: token.id }, |
130 | | - data: { isValid: false }, |
131 | | - }); |
132 | | - |
133 | | - continue; |
134 | | - } |
135 | | - |
136 | | - const tokenSet = tokenSetResult.data; |
137 | | - if (tokenSet.accessToken) { |
138 | | - await prisma.oAuthAccessToken.create({ |
139 | | - data: { |
140 | | - tenancyId: auth.tenancy.id, |
141 | | - accessToken: tokenSet.accessToken, |
142 | | - oauthAccountId: token.projectUserOAuthAccount.id, |
143 | | - scopes: token.scopes, |
144 | | - expiresAt: tokenSet.accessTokenExpiredAt |
145 | | - } |
146 | | - }); |
147 | | - |
148 | | - if (tokenSet.refreshToken) { |
149 | | - // mark the old token as invalid, add the new token to the DB |
150 | | - const oldToken = token; |
151 | | - await prisma.oAuthToken.update({ |
152 | | - where: { id: oldToken.id }, |
153 | | - data: { isValid: false }, |
154 | | - }); |
155 | | - await prisma.oAuthToken.create({ |
156 | | - data: { |
157 | | - tenancyId: auth.tenancy.id, |
158 | | - refreshToken: tokenSet.refreshToken, |
159 | | - oauthAccountId: oldToken.projectUserOAuthAccount.id, |
160 | | - scopes: oldToken.scopes, |
161 | | - } |
162 | | - }); |
163 | | - } |
164 | | - |
165 | | - return { access_token: tokenSet.accessToken }; |
166 | | - } else { |
167 | | - throw new StackAssertionError("No access token returned"); |
168 | | - } |
169 | | - } |
170 | | - |
171 | | - throw new KnownErrors.OAuthConnectionDoesNotHaveRequiredScope(); |
172 | 70 | }, |
173 | 71 | })); |
174 | | - |
175 | | - |
0 commit comments