-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.server.ts
206 lines (181 loc) · 4.69 KB
/
auth.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import { json, redirect } from "@remix-run/node";
import type {
ApiError,
Session,
SupabaseClient,
User,
} from "@supabase/supabase-js";
import type { Session as NodeSession } from "@remix-run/node";
import {
commitSession,
destroySession,
getSession,
sessionKey,
} from "./session.server";
import { supabaseAdmin, supabaseClient } from "./supabase.server";
import type { BaseResponse } from "./types";
export const getCookieSession = async (
request: Request
): Promise<NodeSession> => {
return await getSession(request.headers.get("Cookie"));
};
export async function getUser(accessToken: string): Promise<{
user: User | null;
data: User | null;
error: ApiError | null;
}> {
return await supabaseClient.auth.api.getUser(accessToken);
}
export async function isAuthenticated(request: Request): Promise<boolean> {
const session = await getCookieSession(request);
const authSessionData = session.get(sessionKey);
const isSessionExpired = authSessionData
? Date.now() / 1000 > authSessionData?.expires_at!
: true;
if (!authSessionData || !authSessionData.access_token || isSessionExpired) {
return false;
}
return true;
}
export const handleSignOutSession = async (
request: Request,
redirectTo: string = "/"
) => {
const session = await getSession(request.headers.get("Cookie"));
return redirect(redirectTo, {
headers: {
"Set-Cookie": await destroySession(session),
},
});
};
export const handleForgotPassword = async (
request: Request,
email: string
): Promise<Response> => {
const { data, error } = await supabaseClient.auth.api.resetPasswordForEmail(
email,
{
redirectTo: `${process.env.SERVER_URL}/reset-password`,
}
);
return handleResponse(request, { data, error });
};
export const handleResetPassword = async (
request: Request,
{ accessToken, newPassword }: { accessToken: string; newPassword: string }
): Promise<Response> => {
const { data, error } = await supabaseClient.auth.api.updateUser(
accessToken,
{
password: newPassword,
}
);
return handleResponse(request, { data, error });
};
export const handleResponse = async (
request: Request,
{
data,
error,
}: {
data: any;
error: any;
}
): Promise<Response> => {
const session = await getCookieSession(request);
const response: BaseResponse = {
success: true,
data: null,
errors: [],
};
response.data = data;
if (error) {
session.flash("error", error);
response.success = false;
response.errors.push(error.message);
if (error.status !== undefined)
return json(response, {
status: error.status,
headers: {
"Set-Cookie": await commitSession(session),
},
});
}
return json(response);
};
export const handleCreateUser = async (
request: Request,
{
email,
password,
}: {
email: string;
password: string;
}
): Promise<Response> => {
const { data, error } = await supabaseAdmin.auth.api.createUser({
email,
password,
email_confirm: true,
});
return handleResponse(request, { data, error });
};
export const handleSignInWithEmailAndPassword = async (
request: Request,
{
email,
password,
}: {
email: string;
password: string;
},
successRedirect: string = "/"
): Promise<Response> => {
const { data, error } = await supabaseClient.auth.api.signInWithEmail(
email,
password
);
const session = await getCookieSession(request);
if (error) {
return handleResponse(request, { data, error });
}
session.set(sessionKey, data);
return redirect(successRedirect, {
headers: {
"Set-Cookie": await commitSession(session),
},
});
};
export async function handleAuthSession(
request: Request,
successRedirect?: string,
auth: boolean = true
): Promise<{
session: NodeSession;
sessionData: Session | null;
supabaseClient: SupabaseClient;
}> {
const url = new URL(request.url);
const pathname = url.pathname;
const isLoginPath = pathname === "/login";
const session = await getCookieSession(request);
const authSessionData = session.get(sessionKey);
const isSessionExpired = authSessionData
? Date.now() / 1000 > authSessionData?.expires_at!
: true;
if (!authSessionData || isSessionExpired) {
if (!isLoginPath && auth) {
throw redirect("/login");
} else {
return { session, supabaseClient, sessionData: authSessionData };
}
}
if (successRedirect) {
throw redirect(successRedirect);
}
const supabaseClientSession = await supabaseClient.auth.setAuth(
authSessionData?.access_token!
);
session.set(sessionKey, supabaseClientSession);
return { session, sessionData: supabaseClientSession, supabaseClient };
}