-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathemailAuth.server.tsx
More file actions
55 lines (48 loc) · 1.61 KB
/
emailAuth.server.tsx
File metadata and controls
55 lines (48 loc) · 1.61 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
import { EmailLinkStrategy } from "remix-auth-email-link";
import type { Authenticator } from "remix-auth";
import type { AuthUser } from "./authUser";
import { findOrCreateUser } from "~/models/user.server";
import { env } from "~/env.server";
import { sendMagicLinkEmail } from "~/services/email.server";
import { postAuthentication } from "./postAuth.server";
import { logger } from "./logger.server";
import { MfaRequiredError } from "./mfa/multiFactorAuthentication.server";
let secret = env.MAGIC_LINK_SECRET;
if (!secret) throw new Error("Missing MAGIC_LINK_SECRET env variable.");
const emailStrategy = new EmailLinkStrategy(
{
sendEmail: sendMagicLinkEmail,
secret,
callbackURL: "/magic",
sessionMagicLinkKey: "triggerdotdev:magiclink",
},
async ({
email,
form,
magicLinkVerify,
}: {
email: string;
form: FormData;
magicLinkVerify: boolean;
}) => {
logger.info("Magic link user authenticated", { email, magicLinkVerify });
try {
const { user, isNewUser } = await findOrCreateUser({
email,
authenticationMethod: "MAGIC_LINK",
});
await postAuthentication({ user, isNewUser, loginMethod: "MAGIC_LINK" });
return { userId: user.id };
} catch (error) {
// Skip logging the error if it's a MfaRequiredError
if (error instanceof MfaRequiredError) {
throw error;
}
logger.debug("Magic link user failed to authenticate", { error: JSON.stringify(error) });
throw error;
}
}
);
export function addEmailLinkStrategy(authenticator: Authenticator<AuthUser>) {
authenticator.use(emailStrategy);
}