-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathdraft-processor.ts
More file actions
70 lines (61 loc) · 1.77 KB
/
Copy pathdraft-processor.ts
File metadata and controls
70 lines (61 loc) · 1.77 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
import { db } from '@sim/db'
import * as schema from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { and, eq, sql } from 'drizzle-orm'
import {
handleCreateCredentialFromDraft,
handleReconnectCredential,
} from '@/lib/credentials/draft-hooks'
const logger = createLogger('CredentialDraftProcessor')
interface ProcessCredentialDraftParams {
userId: string
providerId: string
accountId: string
}
/**
* Looks up a pending credential draft for the given user/provider and processes it.
* Creates a new credential or reconnects an existing one depending on the draft state.
* Used by Better Auth's `account.create.after` hook and custom OAuth flows (Shopify, Trello).
*/
export async function processCredentialDraft(params: ProcessCredentialDraftParams): Promise<void> {
const { userId, providerId, accountId } = params
const [draft] = await db
.select()
.from(schema.pendingCredentialDraft)
.where(
and(
eq(schema.pendingCredentialDraft.userId, userId),
eq(schema.pendingCredentialDraft.providerId, providerId),
sql`${schema.pendingCredentialDraft.expiresAt} > NOW()`
)
)
.limit(1)
if (!draft) return
const now = new Date()
if (draft.credentialId) {
await handleReconnectCredential({
draft,
newAccountId: accountId,
workspaceId: draft.workspaceId,
userId,
now,
})
} else {
await handleCreateCredentialFromDraft({
draft,
accountId,
providerId,
userId,
now,
})
}
await db
.delete(schema.pendingCredentialDraft)
.where(eq(schema.pendingCredentialDraft.id, draft.id))
logger.info('Processed credential draft', {
draftId: draft.id,
userId,
providerId,
isReconnect: Boolean(draft.credentialId),
})
}