-
Notifications
You must be signed in to change notification settings - Fork 516
Expand file tree
/
Copy pathverification-code-handler.tsx
More file actions
156 lines (145 loc) · 5.14 KB
/
verification-code-handler.tsx
File metadata and controls
156 lines (145 loc) · 5.14 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { VerificationCodeType } from "@/generated/prisma/client";
import { getAuthContactChannelWithEmailNormalization } from "@/lib/contact-channel";
import { sendEmailFromDefaultTemplate } from "@/lib/emails";
import { getSoleTenancyFromProjectBranch, Tenancy } from "@/lib/tenancies";
import { createAuthTokens } from "@/lib/tokens";
import { createOrUpgradeAnonymousUserWithRules } from "@/lib/users";
import { getPrismaClientForTenancy } from "@/prisma-client";
import { createVerificationCodeHandler } from "@/route-handlers/verification-code-handler";
import { KnownErrors } from "@stackframe/stack-shared";
import { UsersCrud } from "@stackframe/stack-shared/dist/interface/crud/users";
import { emailSchema, signInResponseSchema, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { usersCrudHandlers } from "../../../users/crud";
import { createMfaRequiredError } from "../../mfa/sign-in/verification-code-handler";
export async function ensureUserForEmailAllowsOtp(tenancy: Tenancy, email: string): Promise<UsersCrud["Admin"]["Read"] | null> {
const prisma = await getPrismaClientForTenancy(tenancy);
const contactChannel = await getAuthContactChannelWithEmailNormalization(
prisma,
{
tenancyId: tenancy.id,
type: "EMAIL",
value: email,
}
);
if (contactChannel) {
const otpAuthMethod = contactChannel.projectUser.authMethods.find((m) => m.otpAuthMethod)?.otpAuthMethod;
if (contactChannel.isVerified) {
if (!otpAuthMethod) {
// automatically merge the otp auth method with the existing account
await prisma.authMethod.create({
data: {
projectUserId: contactChannel.projectUser.projectUserId,
tenancyId: tenancy.id,
otpAuthMethod: {
create: {
projectUserId: contactChannel.projectUser.projectUserId,
}
}
},
});
}
return await usersCrudHandlers.adminRead({
tenancy,
user_id: contactChannel.projectUser.projectUserId,
});
} else {
throw new KnownErrors.UserWithEmailAlreadyExists(contactChannel.value, true);
}
} else {
if (!tenancy.config.auth.allowSignUp) {
throw new KnownErrors.SignUpNotEnabled();
}
return null;
}
}
export const signInVerificationCodeHandler = createVerificationCodeHandler({
metadata: {
post: {
summary: "Sign in with a code",
description: "",
tags: ["OTP"],
},
check: {
summary: "Check sign in code",
description: "Check if a sign in code is valid without using it",
tags: ["OTP"],
},
codeDescription: `A 45-character verification code. For magic links, this is the code found in the "code" URL query parameter. For OTP, this is formed by concatenating the 6-digit code entered by the user with the nonce (received during code creation)`,
},
type: VerificationCodeType.ONE_TIME_PASSWORD,
data: yupObject({}),
method: yupObject({
email: emailSchema.defined(),
}),
response: yupObject({
statusCode: yupNumber().oneOf([200]).defined(),
bodyType: yupString().oneOf(["json"]).defined(),
body: signInResponseSchema.defined(),
}),
async send(codeObj, createOptions, sendOptions: { email: string }) {
const tenancy = await getSoleTenancyFromProjectBranch(createOptions.project.id, createOptions.branchId);
await sendEmailFromDefaultTemplate({
tenancy,
email: createOptions.method.email,
user: null,
templateType: "magic_link",
extraVariables: {
magicLink: codeObj.link.toString(),
otp: codeObj.code.slice(0, 6).toUpperCase(),
},
shouldSkipDeliverabilityCheck: true,
});
return {
nonce: codeObj.code.slice(6),
};
},
async handler(tenancy, { email }, data, requestBody, currentUser) {
let user = await ensureUserForEmailAllowsOtp(tenancy, email);
let isNewUser = false;
if (!user) {
// Note: Request context (IP, user agent) is not available in verification code handler
// The rule evaluation will proceed with limited context
user = await createOrUpgradeAnonymousUserWithRules(
tenancy,
currentUser ?? null,
{
primary_email: email,
primary_email_verified: true,
primary_email_auth_enabled: true,
otp_auth_enabled: true,
},
[],
{
authMethod: 'otp',
oauthProvider: null,
ipAddress: null,
countryCode: null,
// TODO: Pass request context when available in verification code handler
}
);
isNewUser = true;
}
if (user.requires_totp_mfa) {
throw await createMfaRequiredError({
project: tenancy.project,
branchId: tenancy.branchId,
userId: user.id,
isNewUser,
});
}
const { refreshToken, accessToken } = await createAuthTokens({
tenancy,
projectUserId: user.id,
});
return {
statusCode: 200,
bodyType: "json",
body: {
refresh_token: refreshToken,
access_token: accessToken,
is_new_user: isNewUser,
user_id: user.id,
},
};
},
});