/
change-password.tsx
112 lines (101 loc) · 2.95 KB
/
change-password.tsx
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
import { resetPasswordForUser } from '~/api/supabase-auth.server';
import authenticated from '~/policies/authenticated.server';
import { authCookie } from '~/services/supabase.server';
import type {
ActionFunction,
LoaderFunction,
MetaFunction,
} from '@remix-run/node';
import { json } from '@remix-run/node';
import {
Form,
Link,
useActionData,
} from '@remix-run/react';
export const meta: MetaFunction = () => {
return { title: "Supabase x Remix | Change password" };
};
export const loader: LoaderFunction = async ({ request }) => {
return await authenticated(
request,
() => {
return json({});
},
() => {
throw new Response("Unauthorized", { status: 401 });
}
)
};
type ActionData = {
message?: string;
formError?: string;
}
export const action: ActionFunction = async ({ request }) => {
return await authenticated(
request,
async () => {
let session = await authCookie.getSession(request.headers.get("Cookie"));
const form = await request.formData();
const password = form.get("password");
const confirmPassword = form.get("confirm-password");
if (!password || !confirmPassword || typeof password !== "string" || typeof confirmPassword !== "string") {
return json<ActionData>({
formError: "Form not submitted correctly.",
}, 403);
}
if (password !== confirmPassword) {
return json<ActionData>({
formError: "Passwords do not match.",
}, 403);
}
const { user: newUser, error } = await resetPasswordForUser({
password,
session,
});
if (error || !newUser) {
return json<ActionData>(
{ formError: error || "Something went wrong" },
403
);
}
return json<ActionData>({
message: "Your password has successfully been reset.",
});
},
() => {
throw new Response("Unauthorized", { status: 401 });
}
)
};
export default function ChangePassword() {
const actionData = useActionData<ActionData>();
return (
<div>
<h1>Change password</h1>
<Form method="post">
<fieldset>
<legend>Change password</legend>
<div style={{ margin: 5 }}>
<label>
Password <input type="password" minLength={8} name="password" />
</label>
</div>
<div style={{ margin: 5 }}>
<label>
Confirm password <input type="password" minLength={8} name="confirm-password" />
</label>
</div>
<div style={{ margin: 5 }}>
<button type="submit">Change password</button>
</div>
</fieldset>
</Form>
{actionData?.formError ? (
<p style={{ color: "red" }}>{actionData.formError}</p>
) : null}
{actionData?.message ? (
<p style={{ color: "green" }}>{actionData.message} Go to your <Link to="/profile">profile</Link></p>
) : null}
</div>
)
}