-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.server.ts
143 lines (128 loc) · 3.94 KB
/
session.server.ts
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
import { createCookieSessionStorage, redirect } from "@remix-run/node";
import { Authenticator } from "remix-auth";
import { EmailLinkStrategy } from "remix-auth-email-link";
import { FormStrategy } from "remix-auth-form";
import { FacebookStrategy, SocialsProvider } from "remix-auth-socials";
import invariant from "tiny-invariant";
import { sendEmail } from "~/email.server";
import type { User } from "~/models/user.server";
import {
createSocialUser,
findOrCreateUser,
getUserByEmail,
getUserById,
markLastLogin,
verifySocialLogin,
} from "~/models/user.server";
invariant(process.env.SESSION_SECRET, "SESSION_SECRET must be set");
export const sessionStorage = createCookieSessionStorage({
cookie: {
name: "__session",
httpOnly: true,
path: "/",
sameSite: "lax",
secrets: [process.env.SESSION_SECRET],
secure: process.env.NODE_ENV === "production",
},
});
export async function getUserId(
request: Request,
): Promise<User["id"] | undefined> {
const user = await authenticator.isAuthenticated(request);
return user?.id;
}
export async function requireUserId(
request: Request,
redirectTo: string = new URL(request.url).pathname,
) {
const user = await authenticator.isAuthenticated(request);
if (!user) {
const searchParams = new URLSearchParams([["redirectTo", redirectTo]]);
throw redirect(`/login?${searchParams}`);
}
return user.id;
}
export async function requireUser(request: Request) {
const userId = await requireUserId(request);
const user = await getUserById(userId);
if (user) return user;
throw await logout(request);
}
export async function requireAdmin(request: Request) {
const userId = await requireUserId(request);
const user = await getUserById(userId);
if (user?.isAdmin) {
return user;
}
throw await logout(request);
}
export async function logout(request: Request) {
return authenticator.logout(request, { redirectTo: "/" });
}
export const authenticator = new Authenticator<User>(sessionStorage, {
sessionKey: "_session",
});
const getCallback = (provider: SocialsProvider) => {
return `${process.env.FACEBOOK_CALLBACK_URL}/auth/${provider}/callback`;
};
const secret = process.env.MAGIC_LINK_SECRET;
if (!secret) throw new Error("Missing MAGIC_LINK_SECRET env variable.");
authenticator
.use(
new FacebookStrategy(
{
clientID: process.env.FACEBOOK_APP_ID || "",
clientSecret: process.env.FACEBOOK_CLIENT_SECRET || "",
callbackURL: getCallback(SocialsProvider.FACEBOOK),
},
async ({ profile }) => {
let user = await verifySocialLogin(
SocialsProvider.FACEBOOK,
profile.id,
);
if (!user) {
user = await createSocialUser({
socialId: profile._json.id,
authProvider: SocialsProvider.FACEBOOK,
email: profile._json.email,
firstName: profile._json.first_name,
lastName: profile._json.last_name,
});
}
return user;
},
),
)
.use(
new FormStrategy(async ({ form }) => {
const email = form.get("email") as string; // validation is handled by the actions
const password = form.get("password") as string | undefined;
return findOrCreateUser({ email, password });
}),
"email-pass",
)
.use(
new EmailLinkStrategy(
{ sendEmail, secret, callbackURL: `/auth/email-link/callback` },
async ({
email,
form,
magicLinkVerify,
}: {
email: string;
form: FormData;
magicLinkVerify: boolean;
}) => {
if (magicLinkVerify) {
const user = await getUserByEmail(email);
if (!user) throw new Error("User not found");
await markLastLogin(user.id);
return user;
} else {
const name = form.get("name") as string;
if (!name) throw new Error("Missing name");
return findOrCreateUser({ email, name });
}
},
),
);