mirror of
https://github.com/docmost/docmost.git
synced 2025-11-14 09:11:15 +10:00
fix: refactor forgot password system (#329)
* refactor forgot password system * ready
This commit is contained in:
@ -25,6 +25,7 @@ import Layout from "@/components/layouts/global/layout.tsx";
|
|||||||
import { ErrorBoundary } from "react-error-boundary";
|
import { ErrorBoundary } from "react-error-boundary";
|
||||||
import InviteSignup from "@/pages/auth/invite-signup.tsx";
|
import InviteSignup from "@/pages/auth/invite-signup.tsx";
|
||||||
import ForgotPassword from "@/pages/auth/forgot-password.tsx";
|
import ForgotPassword from "@/pages/auth/forgot-password.tsx";
|
||||||
|
import PasswordReset from "./pages/auth/password-reset";
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
const [, setSocket] = useAtom(socketAtom);
|
const [, setSocket] = useAtom(socketAtom);
|
||||||
@ -62,9 +63,10 @@ export default function App() {
|
|||||||
<Routes>
|
<Routes>
|
||||||
<Route index element={<Navigate to="/home" />} />
|
<Route index element={<Navigate to="/home" />} />
|
||||||
<Route path={"/login"} element={<LoginPage />} />
|
<Route path={"/login"} element={<LoginPage />} />
|
||||||
<Route path={"/forgotPassword"} element={<ForgotPassword />} />
|
|
||||||
<Route path={"/invites/:invitationId"} element={<InviteSignup />} />
|
<Route path={"/invites/:invitationId"} element={<InviteSignup />} />
|
||||||
<Route path={"/setup/register"} element={<SetupWorkspace />} />
|
<Route path={"/setup/register"} element={<SetupWorkspace />} />
|
||||||
|
<Route path={"/forgot-password"} element={<ForgotPassword />} />
|
||||||
|
<Route path={"/password-reset"} element={<PasswordReset />} />
|
||||||
|
|
||||||
<Route path={"/p/:pageSlug"} element={<PageRedirect />} />
|
<Route path={"/p/:pageSlug"} element={<PageRedirect />} />
|
||||||
|
|
||||||
|
|||||||
@ -1,19 +1,25 @@
|
|||||||
import { Title, Text, Button, Container, Group } from "@mantine/core";
|
import { Title, Text, Button, Container, Group } from "@mantine/core";
|
||||||
import classes from "./error-404.module.css";
|
import classes from "./error-404.module.css";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
|
import { Helmet } from "react-helmet-async";
|
||||||
|
|
||||||
export function Error404() {
|
export function Error404() {
|
||||||
return (
|
return (
|
||||||
<Container className={classes.root}>
|
<>
|
||||||
<Title className={classes.title}>404 Page Not Found</Title>
|
<Helmet>
|
||||||
<Text c="dimmed" size="lg" ta="center" className={classes.description}>
|
<title>404 page not found - Docmost</title>
|
||||||
Sorry, we can't find the page you are looking for.
|
</Helmet>
|
||||||
</Text>
|
<Container className={classes.root}>
|
||||||
<Group justify="center">
|
<Title className={classes.title}>404 Page Not Found</Title>
|
||||||
<Button component={Link} to={"/home"} variant="subtle" size="md">
|
<Text c="dimmed" size="lg" ta="center" className={classes.description}>
|
||||||
Take me back to homepage
|
Sorry, we can't find the page you are looking for.
|
||||||
</Button>
|
</Text>
|
||||||
</Group>
|
<Group justify="center">
|
||||||
</Container>
|
<Button component={Link} to={"/home"} variant="subtle" size="md">
|
||||||
|
Take me back to homepage
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
</Container>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,12 +3,3 @@
|
|||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
background: light-dark(var(--mantine-color-body), rgba(0, 0, 0, 0.1));
|
background: light-dark(var(--mantine-color-body), rgba(0, 0, 0, 0.1));
|
||||||
}
|
}
|
||||||
|
|
||||||
.forgotPasswordBtn {
|
|
||||||
font-size: var(--input-label-size, var(--mantine-font-size-sm));
|
|
||||||
text-decoration: underline;
|
|
||||||
}
|
|
||||||
|
|
||||||
.formElemWithTopMargin {
|
|
||||||
margin-top: var(--mantine-spacing-md);
|
|
||||||
}
|
|
||||||
|
|||||||
@ -1,109 +1,70 @@
|
|||||||
import * as React from "react";
|
import { useState } from "react";
|
||||||
import {useState} from "react";
|
|
||||||
import * as z from "zod";
|
import * as z from "zod";
|
||||||
import {useForm, zodResolver} from "@mantine/form";
|
import { useForm, zodResolver } from "@mantine/form";
|
||||||
import useAuth from "@/features/auth/hooks/use-auth";
|
import useAuth from "@/features/auth/hooks/use-auth";
|
||||||
import {IForgotPassword} from "@/features/auth/types/auth.types";
|
import { IForgotPassword } from "@/features/auth/types/auth.types";
|
||||||
import {Box, Button, Container, PasswordInput, TextInput, Title,} from "@mantine/core";
|
import { Box, Button, Container, Text, TextInput, Title } from "@mantine/core";
|
||||||
import classes from "./auth.module.css";
|
import classes from "./auth.module.css";
|
||||||
import {useRedirectIfAuthenticated} from "@/features/auth/hooks/use-redirect-if-authenticated.ts";
|
import { useRedirectIfAuthenticated } from "@/features/auth/hooks/use-redirect-if-authenticated.ts";
|
||||||
import {notifications} from "@mantine/notifications";
|
|
||||||
|
|
||||||
const stepOneSchema = z.object({
|
const formSchema = z.object({
|
||||||
email: z
|
email: z
|
||||||
.string()
|
.string()
|
||||||
.min(1, {message: "Email is required"})
|
.min(1, { message: "Email is required" })
|
||||||
.email({message: "Invalid email address"}),
|
.email({ message: "Invalid email address" }),
|
||||||
});
|
|
||||||
|
|
||||||
const stepTwoSchema = z.object({
|
|
||||||
email: z
|
|
||||||
.string()
|
|
||||||
.min(1, {message: "Email is required"})
|
|
||||||
.email({message: "Invalid email address"}),
|
|
||||||
token: z.string().min(1, {message: 'Token is required'}),
|
|
||||||
newPassword: z.string().min(8, {message: 'Password must contain at least 8 character(s)'}),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export function ForgotPasswordForm() {
|
export function ForgotPasswordForm() {
|
||||||
const {forgotPassword, isLoading} = useAuth();
|
const { forgotPassword, isLoading } = useAuth();
|
||||||
const [isTokenSend, setIsTokenSend] = useState<boolean>(false)
|
const [isTokenSent, setIsTokenSent] = useState<boolean>(false);
|
||||||
useRedirectIfAuthenticated();
|
useRedirectIfAuthenticated();
|
||||||
|
|
||||||
const form = useForm<IForgotPassword>({
|
const form = useForm<IForgotPassword>({
|
||||||
validate: isTokenSend ? zodResolver(stepTwoSchema) : zodResolver(stepOneSchema),
|
validate: zodResolver(formSchema),
|
||||||
initialValues: {
|
initialValues: {
|
||||||
email: "",
|
email: "",
|
||||||
token: null,
|
},
|
||||||
newPassword: null,
|
});
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
async function onSubmit(data: IForgotPassword) {
|
async function onSubmit(data: IForgotPassword) {
|
||||||
const success = await forgotPassword(data);
|
if (await forgotPassword(data)) {
|
||||||
|
setIsTokenSent(true);
|
||||||
if (success) {
|
|
||||||
if (isTokenSend) {
|
|
||||||
notifications.show({
|
|
||||||
message: 'Password updated',
|
|
||||||
color: "green",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isTokenSend) {
|
|
||||||
setIsTokenSend(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container size={420} my={40} className={classes.container}>
|
<Container size={420} my={40} className={classes.container}>
|
||||||
<Box p="xl" mt={200}>
|
<Box p="xl" mt={200}>
|
||||||
<Title order={2} ta="center" fw={500} mb="md">
|
<Title order={2} ta="center" fw={500} mb="md">
|
||||||
Forgot password
|
Forgot password
|
||||||
</Title>
|
</Title>
|
||||||
|
|
||||||
<form onSubmit={form.onSubmit(onSubmit)}>
|
<form onSubmit={form.onSubmit(onSubmit)}>
|
||||||
<TextInput
|
{!isTokenSent && (
|
||||||
id="email"
|
<TextInput
|
||||||
type="email"
|
id="email"
|
||||||
label="Email"
|
type="email"
|
||||||
placeholder="email@example.com"
|
label="Email"
|
||||||
variant="filled"
|
placeholder="email@example.com"
|
||||||
disabled={isTokenSend}
|
variant="filled"
|
||||||
{...form.getInputProps("email")}
|
{...form.getInputProps("email")}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{
|
{isTokenSent && (
|
||||||
isTokenSend
|
<Text>
|
||||||
&& (
|
A password reset link has been sent to your email. Please check
|
||||||
<>
|
your inbox.
|
||||||
<TextInput
|
</Text>
|
||||||
id="token"
|
)}
|
||||||
className={classes.formElemWithTopMargin}
|
|
||||||
type="text"
|
|
||||||
label="Token"
|
|
||||||
placeholder="token"
|
|
||||||
variant="filled"
|
|
||||||
{...form.getInputProps("token")}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<PasswordInput
|
{!isTokenSent && (
|
||||||
label="Password"
|
<Button type="submit" fullWidth mt="xl" loading={isLoading}>
|
||||||
placeholder="Your password"
|
Send reset link
|
||||||
variant="filled"
|
</Button>
|
||||||
mt="md"
|
)}
|
||||||
{...form.getInputProps("newPassword")}
|
</form>
|
||||||
/>
|
</Box>
|
||||||
</>
|
</Container>
|
||||||
)
|
);
|
||||||
}
|
|
||||||
|
|
||||||
<Button type="submit" fullWidth mt="xl" loading={isLoading}>
|
|
||||||
{isTokenSend ? 'Set password' : 'Send Token'}
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
</Box>
|
|
||||||
</Container>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,4 +1,3 @@
|
|||||||
import * as React from "react";
|
|
||||||
import * as z from "zod";
|
import * as z from "zod";
|
||||||
import { useForm, zodResolver } from "@mantine/form";
|
import { useForm, zodResolver } from "@mantine/form";
|
||||||
import useAuth from "@/features/auth/hooks/use-auth";
|
import useAuth from "@/features/auth/hooks/use-auth";
|
||||||
@ -10,12 +9,12 @@ import {
|
|||||||
Button,
|
Button,
|
||||||
PasswordInput,
|
PasswordInput,
|
||||||
Box,
|
Box,
|
||||||
UnstyledButton,
|
|
||||||
|
Anchor,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import classes from "./auth.module.css";
|
import classes from "./auth.module.css";
|
||||||
import { useRedirectIfAuthenticated } from "@/features/auth/hooks/use-redirect-if-authenticated.ts";
|
import { useRedirectIfAuthenticated } from "@/features/auth/hooks/use-redirect-if-authenticated.ts";
|
||||||
import clsx from "clsx";
|
import { Link, useNavigate } from "react-router-dom";
|
||||||
import {useNavigate} from "react-router-dom";
|
|
||||||
import APP_ROUTE from "@/lib/app-route.ts";
|
import APP_ROUTE from "@/lib/app-route.ts";
|
||||||
|
|
||||||
const formSchema = z.object({
|
const formSchema = z.object({
|
||||||
@ -28,7 +27,6 @@ const formSchema = z.object({
|
|||||||
|
|
||||||
export function LoginForm() {
|
export function LoginForm() {
|
||||||
const { signIn, isLoading } = useAuth();
|
const { signIn, isLoading } = useAuth();
|
||||||
const navigate = useNavigate();
|
|
||||||
useRedirectIfAuthenticated();
|
useRedirectIfAuthenticated();
|
||||||
|
|
||||||
const form = useForm<ILogin>({
|
const form = useForm<ILogin>({
|
||||||
@ -68,17 +66,19 @@ export function LoginForm() {
|
|||||||
{...form.getInputProps("password")}
|
{...form.getInputProps("password")}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<UnstyledButton
|
|
||||||
onClick={() => navigate(APP_ROUTE.AUTH.FORGOT_PASSWORD)}
|
|
||||||
className = {clsx(classes.forgotPasswordBtn, classes.formElemWithTopMargin)}>
|
|
||||||
<div>
|
|
||||||
<span>Forgot Password</span>
|
|
||||||
</div>
|
|
||||||
</UnstyledButton>
|
|
||||||
<Button type="submit" fullWidth mt="xl" loading={isLoading}>
|
<Button type="submit" fullWidth mt="xl" loading={isLoading}>
|
||||||
Sign In
|
Sign In
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
<Anchor
|
||||||
|
to={APP_ROUTE.AUTH.FORGOT_PASSWORD}
|
||||||
|
component={Link}
|
||||||
|
underline="never"
|
||||||
|
size="sm"
|
||||||
|
>
|
||||||
|
Forgot your password?
|
||||||
|
</Anchor>
|
||||||
</Box>
|
</Box>
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
|
|||||||
@ -0,0 +1,67 @@
|
|||||||
|
import * as z from "zod";
|
||||||
|
import { useForm, zodResolver } from "@mantine/form";
|
||||||
|
import useAuth from "@/features/auth/hooks/use-auth";
|
||||||
|
import { IPasswordReset } from "@/features/auth/types/auth.types";
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Button,
|
||||||
|
Container,
|
||||||
|
PasswordInput,
|
||||||
|
Text,
|
||||||
|
Title,
|
||||||
|
} from "@mantine/core";
|
||||||
|
import classes from "./auth.module.css";
|
||||||
|
import { useRedirectIfAuthenticated } from "@/features/auth/hooks/use-redirect-if-authenticated.ts";
|
||||||
|
|
||||||
|
const formSchema = z.object({
|
||||||
|
newPassword: z
|
||||||
|
.string()
|
||||||
|
.min(8, { message: "Password must contain at least 8 characters" }),
|
||||||
|
});
|
||||||
|
|
||||||
|
interface PasswordResetFormProps {
|
||||||
|
resetToken?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PasswordResetForm({ resetToken }: PasswordResetFormProps) {
|
||||||
|
const { passwordReset, isLoading } = useAuth();
|
||||||
|
useRedirectIfAuthenticated();
|
||||||
|
|
||||||
|
const form = useForm<IPasswordReset>({
|
||||||
|
validate: zodResolver(formSchema),
|
||||||
|
initialValues: {
|
||||||
|
newPassword: "",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
async function onSubmit(data: IPasswordReset) {
|
||||||
|
await passwordReset({
|
||||||
|
token: resetToken,
|
||||||
|
newPassword: data.newPassword
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Container size={420} my={40} className={classes.container}>
|
||||||
|
<Box p="xl" mt={200}>
|
||||||
|
<Title order={2} ta="center" fw={500} mb="md">
|
||||||
|
Password Reset
|
||||||
|
</Title>
|
||||||
|
|
||||||
|
<form onSubmit={form.onSubmit(onSubmit)}>
|
||||||
|
<PasswordInput
|
||||||
|
label="New password"
|
||||||
|
placeholder="Your new password"
|
||||||
|
variant="filled"
|
||||||
|
mt="md"
|
||||||
|
{...form.getInputProps("newPassword")}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Button type="submit" fullWidth mt="xl" loading={isLoading}>
|
||||||
|
Set password
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</Box>
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,10 +1,22 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import {forgotPassword, login, setupWorkspace} from "@/features/auth/services/auth-service";
|
import {
|
||||||
|
forgotPassword,
|
||||||
|
login,
|
||||||
|
passwordReset,
|
||||||
|
setupWorkspace,
|
||||||
|
verifyUserToken,
|
||||||
|
} from "@/features/auth/services/auth-service";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useAtom } from "jotai";
|
import { useAtom } from "jotai";
|
||||||
import { authTokensAtom } from "@/features/auth/atoms/auth-tokens-atom";
|
import { authTokensAtom } from "@/features/auth/atoms/auth-tokens-atom";
|
||||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
||||||
import {IForgotPassword, ILogin, ISetupWorkspace} from "@/features/auth/types/auth.types";
|
import {
|
||||||
|
IForgotPassword,
|
||||||
|
ILogin,
|
||||||
|
IPasswordReset,
|
||||||
|
ISetupWorkspace,
|
||||||
|
IVerifyUserToken,
|
||||||
|
} from "@/features/auth/types/auth.types";
|
||||||
import { notifications } from "@mantine/notifications";
|
import { notifications } from "@mantine/notifications";
|
||||||
import { IAcceptInvite } from "@/features/workspace/types/workspace.types.ts";
|
import { IAcceptInvite } from "@/features/workspace/types/workspace.types.ts";
|
||||||
import { acceptInvitation } from "@/features/workspace/services/workspace-service.ts";
|
import { acceptInvitation } from "@/features/workspace/services/workspace-service.ts";
|
||||||
@ -76,6 +88,28 @@ export default function useAuth() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handlePasswordReset = async (data: IPasswordReset) => {
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await passwordReset(data);
|
||||||
|
setIsLoading(false);
|
||||||
|
|
||||||
|
setAuthToken(res.tokens);
|
||||||
|
|
||||||
|
navigate(APP_ROUTE.HOME);
|
||||||
|
notifications.show({
|
||||||
|
message: "Password reset was successful",
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
setIsLoading(false);
|
||||||
|
notifications.show({
|
||||||
|
message: err.response?.data.message,
|
||||||
|
color: "red",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleIsAuthenticated = async () => {
|
const handleIsAuthenticated = async () => {
|
||||||
if (!authToken) {
|
if (!authToken) {
|
||||||
return false;
|
return false;
|
||||||
@ -109,7 +143,7 @@ export default function useAuth() {
|
|||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await forgotPassword(data);
|
await forgotPassword(data);
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
@ -125,13 +159,31 @@ export default function useAuth() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleVerifyUserToken = async (data: IVerifyUserToken) => {
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await verifyUserToken(data);
|
||||||
|
setIsLoading(false);
|
||||||
|
} catch (err) {
|
||||||
|
console.log(err);
|
||||||
|
setIsLoading(false);
|
||||||
|
notifications.show({
|
||||||
|
message: err.response?.data.message,
|
||||||
|
color: "red",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
signIn: handleSignIn,
|
signIn: handleSignIn,
|
||||||
invitationSignup: handleInvitationSignUp,
|
invitationSignup: handleInvitationSignUp,
|
||||||
setupWorkspace: handleSetupWorkspace,
|
setupWorkspace: handleSetupWorkspace,
|
||||||
isAuthenticated: handleIsAuthenticated,
|
isAuthenticated: handleIsAuthenticated,
|
||||||
logout: handleLogout,
|
|
||||||
forgotPassword: handleForgotPassword,
|
forgotPassword: handleForgotPassword,
|
||||||
|
passwordReset: handlePasswordReset,
|
||||||
|
verifyUserToken: handleVerifyUserToken,
|
||||||
|
logout: handleLogout,
|
||||||
hasTokens,
|
hasTokens,
|
||||||
isLoading,
|
isLoading,
|
||||||
};
|
};
|
||||||
|
|||||||
14
apps/client/src/features/auth/queries/auth-query.tsx
Normal file
14
apps/client/src/features/auth/queries/auth-query.tsx
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import { useQuery, UseQueryResult } from "@tanstack/react-query";
|
||||||
|
import { verifyUserToken } from "../services/auth-service";
|
||||||
|
import { IVerifyUserToken } from "../types/auth.types";
|
||||||
|
|
||||||
|
export function useVerifyUserTokenQuery(
|
||||||
|
verify: IVerifyUserToken,
|
||||||
|
): UseQueryResult<any, Error> {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["verify-token", verify],
|
||||||
|
queryFn: () => verifyUserToken(verify),
|
||||||
|
enabled: !!verify.token,
|
||||||
|
staleTime: 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -3,9 +3,11 @@ import {
|
|||||||
IChangePassword,
|
IChangePassword,
|
||||||
IForgotPassword,
|
IForgotPassword,
|
||||||
ILogin,
|
ILogin,
|
||||||
|
IPasswordReset,
|
||||||
IRegister,
|
IRegister,
|
||||||
ISetupWorkspace,
|
ISetupWorkspace,
|
||||||
ITokenResponse,
|
ITokenResponse,
|
||||||
|
IVerifyUserToken,
|
||||||
} from "@/features/auth/types/auth.types";
|
} from "@/features/auth/types/auth.types";
|
||||||
|
|
||||||
export async function login(data: ILogin): Promise<ITokenResponse> {
|
export async function login(data: ILogin): Promise<ITokenResponse> {
|
||||||
@ -20,21 +22,30 @@ export async function register(data: IRegister): Promise<ITokenResponse> {
|
|||||||
}*/
|
}*/
|
||||||
|
|
||||||
export async function changePassword(
|
export async function changePassword(
|
||||||
data: IChangePassword,
|
data: IChangePassword
|
||||||
): Promise<IChangePassword> {
|
): Promise<IChangePassword> {
|
||||||
const req = await api.post<IChangePassword>("/auth/change-password", data);
|
const req = await api.post<IChangePassword>("/auth/change-password", data);
|
||||||
return req.data;
|
return req.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function setupWorkspace(
|
export async function setupWorkspace(
|
||||||
data: ISetupWorkspace,
|
data: ISetupWorkspace
|
||||||
): Promise<ITokenResponse> {
|
): Promise<ITokenResponse> {
|
||||||
const req = await api.post<ITokenResponse>("/auth/setup", data);
|
const req = await api.post<ITokenResponse>("/auth/setup", data);
|
||||||
return req.data;
|
return req.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function forgotPassword(data: IForgotPassword): Promise<any> {
|
export async function forgotPassword(data: IForgotPassword): Promise<void> {
|
||||||
const req = await api.post<any>("/auth/forgot-password", data);
|
await api.post<any>("/auth/forgot-password", data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function passwordReset(
|
||||||
|
data: IPasswordReset
|
||||||
|
): Promise<ITokenResponse> {
|
||||||
|
const req = await api.post<any>("/auth/password-reset", data);
|
||||||
return req.data;
|
return req.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function verifyUserToken(data: IVerifyUserToken): Promise<any> {
|
||||||
|
return api.post<any>("/auth/verify-token", data);
|
||||||
|
}
|
||||||
|
|||||||
@ -3,12 +3,6 @@ export interface ILogin {
|
|||||||
password: string;
|
password: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IForgotPassword {
|
|
||||||
email: string;
|
|
||||||
token: string;
|
|
||||||
newPassword: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IRegister {
|
export interface IRegister {
|
||||||
name?: string;
|
name?: string;
|
||||||
email: string;
|
email: string;
|
||||||
@ -35,3 +29,17 @@ export interface IChangePassword {
|
|||||||
oldPassword: string;
|
oldPassword: string;
|
||||||
newPassword: string;
|
newPassword: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface IForgotPassword {
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IPasswordReset {
|
||||||
|
token?: string;
|
||||||
|
newPassword: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IVerifyUserToken {
|
||||||
|
token: string;
|
||||||
|
type: string;
|
||||||
|
}
|
||||||
|
|||||||
@ -20,6 +20,7 @@ import {
|
|||||||
removeSpaceMember,
|
removeSpaceMember,
|
||||||
createSpace,
|
createSpace,
|
||||||
updateSpace,
|
updateSpace,
|
||||||
|
deleteSpace,
|
||||||
} from '@/features/space/services/space-service.ts';
|
} from '@/features/space/services/space-service.ts';
|
||||||
import { notifications } from '@mantine/notifications';
|
import { notifications } from '@mantine/notifications';
|
||||||
import { IPagination, QueryParams } from '@/lib/types.ts';
|
import { IPagination, QueryParams } from '@/lib/types.ts';
|
||||||
|
|||||||
@ -4,7 +4,8 @@ const APP_ROUTE = {
|
|||||||
LOGIN: "/login",
|
LOGIN: "/login",
|
||||||
SIGNUP: "/signup",
|
SIGNUP: "/signup",
|
||||||
SETUP: "/setup/register",
|
SETUP: "/setup/register",
|
||||||
FORGOT_PASSWORD: "/forgotPassword",
|
FORGOT_PASSWORD: "/forgot-password",
|
||||||
|
PASSWORD_RESET: "/password-reset",
|
||||||
},
|
},
|
||||||
SETTINGS: {
|
SETTINGS: {
|
||||||
ACCOUNT: {
|
ACCOUNT: {
|
||||||
|
|||||||
@ -1,11 +1,11 @@
|
|||||||
|
import { ForgotPasswordForm } from "@/features/auth/components/forgot-password-form";
|
||||||
import { Helmet } from "react-helmet-async";
|
import { Helmet } from "react-helmet-async";
|
||||||
import {ForgotPasswordForm} from "@/features/auth/components/forgot-password-form.tsx";
|
|
||||||
|
|
||||||
export default function ForgotPassword() {
|
export default function ForgotPassword() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Helmet>
|
<Helmet>
|
||||||
<title>Forgot Password</title>
|
<title>Forgot Password - Docmost</title>
|
||||||
</Helmet>
|
</Helmet>
|
||||||
<ForgotPasswordForm />
|
<ForgotPasswordForm />
|
||||||
</>
|
</>
|
||||||
|
|||||||
@ -5,7 +5,7 @@ export default function InviteSignup() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Helmet>
|
<Helmet>
|
||||||
<title>Invitation signup</title>
|
<title>Invitation signup - Docmost</title>
|
||||||
</Helmet>
|
</Helmet>
|
||||||
<InviteSignUpForm />
|
<InviteSignUpForm />
|
||||||
</>
|
</>
|
||||||
|
|||||||
@ -5,7 +5,7 @@ export default function LoginPage() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Helmet>
|
<Helmet>
|
||||||
<title>Login</title>
|
<title>Login - Docmost</title>
|
||||||
</Helmet>
|
</Helmet>
|
||||||
<LoginForm />
|
<LoginForm />
|
||||||
</>
|
</>
|
||||||
|
|||||||
53
apps/client/src/pages/auth/password-reset.tsx
Normal file
53
apps/client/src/pages/auth/password-reset.tsx
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
import { Helmet } from "react-helmet-async";
|
||||||
|
import { PasswordResetForm } from "@/features/auth/components/password-reset-form";
|
||||||
|
import { Link, useSearchParams } from "react-router-dom";
|
||||||
|
import { useVerifyUserTokenQuery } from "@/features/auth/queries/auth-query";
|
||||||
|
import { Button, Container, Group, Text } from "@mantine/core";
|
||||||
|
import APP_ROUTE from "@/lib/app-route";
|
||||||
|
|
||||||
|
export default function PasswordReset() {
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
|
const { data, isLoading, isError } = useVerifyUserTokenQuery({
|
||||||
|
token: searchParams.get("token"),
|
||||||
|
type: "forgot-password",
|
||||||
|
});
|
||||||
|
const resetToken = searchParams.get("token");
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return <div></div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isError || !resetToken) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Helmet>
|
||||||
|
<title>Password Reset - Docmost</title>
|
||||||
|
</Helmet>
|
||||||
|
<Container my={40}>
|
||||||
|
<Text size="lg" ta="center">
|
||||||
|
Invalid or expired password reset link
|
||||||
|
</Text>
|
||||||
|
<Group justify="center">
|
||||||
|
<Button
|
||||||
|
component={Link}
|
||||||
|
to={APP_ROUTE.AUTH.LOGIN}
|
||||||
|
variant="subtle"
|
||||||
|
size="md"
|
||||||
|
>
|
||||||
|
Goto login page
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
</Container>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Helmet>
|
||||||
|
<title>Password Reset - Docmost</title>
|
||||||
|
</Helmet>
|
||||||
|
<PasswordResetForm resetToken={resetToken} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -32,7 +32,7 @@ export default function SetupWorkspace() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Helmet>
|
<Helmet>
|
||||||
<title>Setup workspace</title>
|
<title>Setup workspace - Docmost</title>
|
||||||
</Helmet>
|
</Helmet>
|
||||||
<SetupWorkspaceForm />
|
<SetupWorkspaceForm />
|
||||||
</>
|
</>
|
||||||
|
|||||||
3
apps/server/src/core/auth/auth.constants.ts
Normal file
3
apps/server/src/core/auth/auth.constants.ts
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
export enum UserTokenType {
|
||||||
|
FORGOT_PASSWORD = 'forgot-password',
|
||||||
|
}
|
||||||
@ -10,7 +10,6 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { LoginDto } from './dto/login.dto';
|
import { LoginDto } from './dto/login.dto';
|
||||||
import { AuthService } from './services/auth.service';
|
import { AuthService } from './services/auth.service';
|
||||||
import { CreateUserDto } from './dto/create-user.dto';
|
|
||||||
import { SetupGuard } from './guards/setup.guard';
|
import { SetupGuard } from './guards/setup.guard';
|
||||||
import { EnvironmentService } from '../../integrations/environment/environment.service';
|
import { EnvironmentService } from '../../integrations/environment/environment.service';
|
||||||
import { CreateAdminUserDto } from './dto/create-admin-user.dto';
|
import { CreateAdminUserDto } from './dto/create-admin-user.dto';
|
||||||
@ -20,6 +19,8 @@ import { User, Workspace } from '@docmost/db/types/entity.types';
|
|||||||
import { AuthWorkspace } from '../../common/decorators/auth-workspace.decorator';
|
import { AuthWorkspace } from '../../common/decorators/auth-workspace.decorator';
|
||||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||||
import { ForgotPasswordDto } from './dto/forgot-password.dto';
|
import { ForgotPasswordDto } from './dto/forgot-password.dto';
|
||||||
|
import { PasswordResetDto } from './dto/password-reset.dto';
|
||||||
|
import { VerifyUserTokenDto } from './dto/verify-user-token.dto';
|
||||||
|
|
||||||
@Controller('auth')
|
@Controller('auth')
|
||||||
export class AuthController {
|
export class AuthController {
|
||||||
@ -34,18 +35,6 @@ export class AuthController {
|
|||||||
return this.authService.login(loginInput, req.raw.workspaceId);
|
return this.authService.login(loginInput, req.raw.workspaceId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('forgot-password')
|
|
||||||
async forgotPassword(
|
|
||||||
@Req() req,
|
|
||||||
@Body() forgotPasswordDto: ForgotPasswordDto,
|
|
||||||
) {
|
|
||||||
return this.authService.forgotPassword(
|
|
||||||
forgotPasswordDto,
|
|
||||||
req.raw.workspaceId,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* @HttpCode(HttpStatus.OK)
|
/* @HttpCode(HttpStatus.OK)
|
||||||
@Post('register')
|
@Post('register')
|
||||||
async register(@Req() req, @Body() createUserDto: CreateUserDto) {
|
async register(@Req() req, @Body() createUserDto: CreateUserDto) {
|
||||||
@ -74,4 +63,31 @@ export class AuthController {
|
|||||||
) {
|
) {
|
||||||
return this.authService.changePassword(dto, user.id, workspace.id);
|
return this.authService.changePassword(dto, user.id, workspace.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
@Post('forgot-password')
|
||||||
|
async forgotPassword(
|
||||||
|
@Body() forgotPasswordDto: ForgotPasswordDto,
|
||||||
|
@AuthWorkspace() workspace: Workspace,
|
||||||
|
) {
|
||||||
|
return this.authService.forgotPassword(forgotPasswordDto, workspace.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
@Post('password-reset')
|
||||||
|
async passwordReset(
|
||||||
|
@Body() passwordResetDto: PasswordResetDto,
|
||||||
|
@AuthWorkspace() workspace: Workspace,
|
||||||
|
) {
|
||||||
|
return this.authService.passwordReset(passwordResetDto, workspace.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
@Post('verify-token')
|
||||||
|
async verifyResetToken(
|
||||||
|
@Body() verifyUserTokenDto: VerifyUserTokenDto,
|
||||||
|
@AuthWorkspace() workspace: Workspace,
|
||||||
|
) {
|
||||||
|
return this.authService.verifyUserToken(verifyUserTokenDto, workspace.id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,16 +1,7 @@
|
|||||||
import { IsEmail, IsNotEmpty, IsOptional, IsString, MinLength } from 'class-validator';
|
import { IsEmail, IsNotEmpty } from 'class-validator';
|
||||||
|
|
||||||
export class ForgotPasswordDto {
|
export class ForgotPasswordDto {
|
||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
@IsEmail()
|
@IsEmail()
|
||||||
email: string;
|
email: string;
|
||||||
|
|
||||||
@IsOptional()
|
|
||||||
@IsString()
|
|
||||||
token: string;
|
|
||||||
|
|
||||||
@IsOptional()
|
|
||||||
@IsString()
|
|
||||||
@MinLength(8)
|
|
||||||
newPassword: string;
|
|
||||||
}
|
}
|
||||||
|
|||||||
10
apps/server/src/core/auth/dto/password-reset.dto.ts
Normal file
10
apps/server/src/core/auth/dto/password-reset.dto.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
import { IsString, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class PasswordResetDto {
|
||||||
|
@IsString()
|
||||||
|
token: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(8)
|
||||||
|
newPassword: string;
|
||||||
|
}
|
||||||
9
apps/server/src/core/auth/dto/verify-user-token.dto.ts
Normal file
9
apps/server/src/core/auth/dto/verify-user-token.dto.ts
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import { IsString, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class VerifyUserTokenDto {
|
||||||
|
@IsString()
|
||||||
|
token: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
type: string;
|
||||||
|
}
|
||||||
@ -11,13 +11,25 @@ import { TokensDto } from '../dto/tokens.dto';
|
|||||||
import { SignupService } from './signup.service';
|
import { SignupService } from './signup.service';
|
||||||
import { CreateAdminUserDto } from '../dto/create-admin-user.dto';
|
import { CreateAdminUserDto } from '../dto/create-admin-user.dto';
|
||||||
import { UserRepo } from '@docmost/db/repos/user/user.repo';
|
import { UserRepo } from '@docmost/db/repos/user/user.repo';
|
||||||
import { comparePasswordHash, hashPassword, nanoIdGen } from '../../../common/helpers';
|
import {
|
||||||
|
comparePasswordHash,
|
||||||
|
hashPassword,
|
||||||
|
nanoIdGen,
|
||||||
|
} from '../../../common/helpers';
|
||||||
import { ChangePasswordDto } from '../dto/change-password.dto';
|
import { ChangePasswordDto } from '../dto/change-password.dto';
|
||||||
import { MailService } from '../../../integrations/mail/mail.service';
|
import { MailService } from '../../../integrations/mail/mail.service';
|
||||||
import ChangePasswordEmail from '@docmost/transactional/emails/change-password-email';
|
import ChangePasswordEmail from '@docmost/transactional/emails/change-password-email';
|
||||||
import { ForgotPasswordDto } from '../dto/forgot-password.dto';
|
import { ForgotPasswordDto } from '../dto/forgot-password.dto';
|
||||||
import ForgotPasswordEmail from '@docmost/transactional/emails/forgot-password-email';
|
import ForgotPasswordEmail from '@docmost/transactional/emails/forgot-password-email';
|
||||||
import { UserTokensRepo } from '@docmost/db/repos/user-tokens/user-tokens.repo';
|
import { UserTokenRepo } from '@docmost/db/repos/user-token/user-token.repo';
|
||||||
|
import { PasswordResetDto } from '../dto/password-reset.dto';
|
||||||
|
import { UserToken } from '@docmost/db/types/entity.types';
|
||||||
|
import { UserTokenType } from '../auth.constants';
|
||||||
|
import { KyselyDB } from '@docmost/db/types/kysely.types';
|
||||||
|
import { InjectKysely } from 'nestjs-kysely';
|
||||||
|
import { executeTx } from '@docmost/db/utils';
|
||||||
|
import { VerifyUserTokenDto } from '../dto/verify-user-token.dto';
|
||||||
|
import { EnvironmentService } from 'src/integrations/environment/environment.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
@ -25,8 +37,10 @@ export class AuthService {
|
|||||||
private signupService: SignupService,
|
private signupService: SignupService,
|
||||||
private tokenService: TokenService,
|
private tokenService: TokenService,
|
||||||
private userRepo: UserRepo,
|
private userRepo: UserRepo,
|
||||||
private userTokensRepo: UserTokensRepo,
|
private userTokenRepo: UserTokenRepo,
|
||||||
private mailService: MailService,
|
private mailService: MailService,
|
||||||
|
private environmentService: EnvironmentService,
|
||||||
|
@InjectKysely() private readonly db: KyselyDB,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async login(loginDto: LoginDto, workspaceId: string) {
|
async login(loginDto: LoginDto, workspaceId: string) {
|
||||||
@ -50,94 +64,6 @@ export class AuthService {
|
|||||||
return { tokens };
|
return { tokens };
|
||||||
}
|
}
|
||||||
|
|
||||||
async forgotPassword(
|
|
||||||
forgotPasswordDto: ForgotPasswordDto,
|
|
||||||
workspaceId: string,
|
|
||||||
) {
|
|
||||||
const user = await this.userRepo.findByEmail(
|
|
||||||
forgotPasswordDto.email,
|
|
||||||
workspaceId,
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
if (!user) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
forgotPasswordDto.token == null ||
|
|
||||||
forgotPasswordDto.newPassword == null
|
|
||||||
) {
|
|
||||||
// Generate 5-character user token
|
|
||||||
const code = nanoIdGen(5).toUpperCase();
|
|
||||||
const hashedToken = await hashPassword(code);
|
|
||||||
await this.userTokensRepo.insertUserToken({
|
|
||||||
token: hashedToken,
|
|
||||||
user_id: user.id,
|
|
||||||
workspace_id: user.workspaceId,
|
|
||||||
expires_at: new Date(new Date().getTime() + 3_600_000), // should expires in 1 hour
|
|
||||||
type: "forgot-password",
|
|
||||||
});
|
|
||||||
|
|
||||||
const emailTemplate = ForgotPasswordEmail({
|
|
||||||
username: user.name,
|
|
||||||
code: code,
|
|
||||||
});
|
|
||||||
await this.mailService.sendToQueue({
|
|
||||||
to: user.email,
|
|
||||||
subject: 'Reset your password',
|
|
||||||
template: emailTemplate,
|
|
||||||
});
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get all user tokens that are not expired
|
|
||||||
const userTokens = await this.userTokensRepo.findByUserId(
|
|
||||||
user.id,
|
|
||||||
user.workspaceId,
|
|
||||||
"forgot-password"
|
|
||||||
);
|
|
||||||
// Limit to the last 3 token, so we have a total time window of 15 minutes
|
|
||||||
const validUserTokens = userTokens
|
|
||||||
.filter((token) => token.expires_at > new Date() && token.used_at == null)
|
|
||||||
.slice(0, 3);
|
|
||||||
|
|
||||||
for (const token of validUserTokens) {
|
|
||||||
const validated = await comparePasswordHash(
|
|
||||||
forgotPasswordDto.token,
|
|
||||||
token.token,
|
|
||||||
);
|
|
||||||
if (validated) {
|
|
||||||
await Promise.all([
|
|
||||||
this.userTokensRepo.deleteUserToken(user.id, user.workspaceId, "forgot-password"),
|
|
||||||
this.userTokensRepo.deleteExpiredUserTokens(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const newPasswordHash = await hashPassword(
|
|
||||||
forgotPasswordDto.newPassword,
|
|
||||||
);
|
|
||||||
await this.userRepo.updateUser(
|
|
||||||
{
|
|
||||||
password: newPasswordHash,
|
|
||||||
},
|
|
||||||
user.id,
|
|
||||||
workspaceId,
|
|
||||||
);
|
|
||||||
|
|
||||||
const emailTemplate = ChangePasswordEmail({ username: user.name });
|
|
||||||
await this.mailService.sendToQueue({
|
|
||||||
to: user.email,
|
|
||||||
subject: 'Your password has been changed',
|
|
||||||
template: emailTemplate,
|
|
||||||
});
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new BadRequestException('Incorrect code');
|
|
||||||
}
|
|
||||||
|
|
||||||
async register(createUserDto: CreateUserDto, workspaceId: string) {
|
async register(createUserDto: CreateUserDto, workspaceId: string) {
|
||||||
const user = await this.signupService.signup(createUserDto, workspaceId);
|
const user = await this.signupService.signup(createUserDto, workspaceId);
|
||||||
|
|
||||||
@ -192,4 +118,108 @@ export class AuthService {
|
|||||||
template: emailTemplate,
|
template: emailTemplate,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async forgotPassword(
|
||||||
|
forgotPasswordDto: ForgotPasswordDto,
|
||||||
|
workspaceId: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const user = await this.userRepo.findByEmail(
|
||||||
|
forgotPasswordDto.email,
|
||||||
|
workspaceId,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = nanoIdGen(16);
|
||||||
|
const resetLink = `${this.environmentService.getAppUrl()}/password-reset?token=${token}`;
|
||||||
|
|
||||||
|
await this.userTokenRepo.insertUserToken({
|
||||||
|
token: token,
|
||||||
|
userId: user.id,
|
||||||
|
workspaceId: user.workspaceId,
|
||||||
|
expiresAt: new Date(new Date().getTime() + 60 * 60 * 1000), // 1 hour
|
||||||
|
type: UserTokenType.FORGOT_PASSWORD,
|
||||||
|
});
|
||||||
|
|
||||||
|
const emailTemplate = ForgotPasswordEmail({
|
||||||
|
username: user.name,
|
||||||
|
resetLink: resetLink,
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.mailService.sendToQueue({
|
||||||
|
to: user.email,
|
||||||
|
subject: 'Reset your password',
|
||||||
|
template: emailTemplate,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async passwordReset(passwordResetDto: PasswordResetDto, workspaceId: string) {
|
||||||
|
const userToken = await this.userTokenRepo.findById(
|
||||||
|
passwordResetDto.token,
|
||||||
|
workspaceId,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (
|
||||||
|
!userToken ||
|
||||||
|
userToken.type !== UserTokenType.FORGOT_PASSWORD ||
|
||||||
|
userToken.expiresAt < new Date()
|
||||||
|
) {
|
||||||
|
throw new BadRequestException('Invalid or expired token');
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await this.userRepo.findById(userToken.userId, workspaceId);
|
||||||
|
if (!user) {
|
||||||
|
throw new NotFoundException('User not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const newPasswordHash = await hashPassword(passwordResetDto.newPassword);
|
||||||
|
|
||||||
|
await executeTx(this.db, async (trx) => {
|
||||||
|
await this.userRepo.updateUser(
|
||||||
|
{
|
||||||
|
password: newPasswordHash,
|
||||||
|
},
|
||||||
|
user.id,
|
||||||
|
workspaceId,
|
||||||
|
trx,
|
||||||
|
);
|
||||||
|
|
||||||
|
trx
|
||||||
|
.deleteFrom('userTokens')
|
||||||
|
.where('userId', '=', user.id)
|
||||||
|
.where('type', '=', UserTokenType.FORGOT_PASSWORD)
|
||||||
|
.execute();
|
||||||
|
});
|
||||||
|
|
||||||
|
const emailTemplate = ChangePasswordEmail({ username: user.name });
|
||||||
|
await this.mailService.sendToQueue({
|
||||||
|
to: user.email,
|
||||||
|
subject: 'Your password has been changed',
|
||||||
|
template: emailTemplate,
|
||||||
|
});
|
||||||
|
|
||||||
|
const tokens: TokensDto = await this.tokenService.generateTokens(user);
|
||||||
|
|
||||||
|
return { tokens };
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifyUserToken(
|
||||||
|
userTokenDto: VerifyUserTokenDto,
|
||||||
|
workspaceId: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const userToken = await this.userTokenRepo.findById(
|
||||||
|
userTokenDto.token,
|
||||||
|
workspaceId,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (
|
||||||
|
!userToken ||
|
||||||
|
userToken.type !== userTokenDto.type ||
|
||||||
|
userToken.expiresAt < new Date()
|
||||||
|
) {
|
||||||
|
throw new BadRequestException('Invalid or expired token');
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -22,7 +22,7 @@ import { AttachmentRepo } from './repos/attachment/attachment.repo';
|
|||||||
import { KyselyDB } from '@docmost/db/types/kysely.types';
|
import { KyselyDB } from '@docmost/db/types/kysely.types';
|
||||||
import * as process from 'node:process';
|
import * as process from 'node:process';
|
||||||
import { MigrationService } from '@docmost/db/services/migration.service';
|
import { MigrationService } from '@docmost/db/services/migration.service';
|
||||||
import { UserTokensRepo } from './repos/user-tokens/user-tokens.repo';
|
import { UserTokenRepo } from './repos/user-token/user-token.repo';
|
||||||
|
|
||||||
// https://github.com/brianc/node-postgres/issues/811
|
// https://github.com/brianc/node-postgres/issues/811
|
||||||
types.setTypeParser(types.builtins.INT8, (val) => Number(val));
|
types.setTypeParser(types.builtins.INT8, (val) => Number(val));
|
||||||
@ -67,7 +67,7 @@ types.setTypeParser(types.builtins.INT8, (val) => Number(val));
|
|||||||
PageHistoryRepo,
|
PageHistoryRepo,
|
||||||
CommentRepo,
|
CommentRepo,
|
||||||
AttachmentRepo,
|
AttachmentRepo,
|
||||||
UserTokensRepo,
|
UserTokenRepo,
|
||||||
],
|
],
|
||||||
exports: [
|
exports: [
|
||||||
WorkspaceRepo,
|
WorkspaceRepo,
|
||||||
@ -80,7 +80,7 @@ types.setTypeParser(types.builtins.INT8, (val) => Number(val));
|
|||||||
PageHistoryRepo,
|
PageHistoryRepo,
|
||||||
CommentRepo,
|
CommentRepo,
|
||||||
AttachmentRepo,
|
AttachmentRepo,
|
||||||
UserTokensRepo,
|
UserTokenRepo,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class DatabaseModule implements OnModuleDestroy, OnApplicationBootstrap {
|
export class DatabaseModule implements OnModuleDestroy, OnApplicationBootstrap {
|
||||||
|
|||||||
@ -7,13 +7,13 @@ export async function up(db: Kysely<any>): Promise<void> {
|
|||||||
col.primaryKey().defaultTo(sql`gen_uuid_v7()`),
|
col.primaryKey().defaultTo(sql`gen_uuid_v7()`),
|
||||||
)
|
)
|
||||||
.addColumn('token', 'varchar', (col) => col.notNull())
|
.addColumn('token', 'varchar', (col) => col.notNull())
|
||||||
|
.addColumn('type', 'varchar', (col) => col.notNull())
|
||||||
.addColumn('user_id', 'uuid', (col) =>
|
.addColumn('user_id', 'uuid', (col) =>
|
||||||
col.notNull().references('users.id').onDelete('cascade'),
|
col.notNull().references('users.id').onDelete('cascade'),
|
||||||
)
|
)
|
||||||
.addColumn('workspace_id', 'uuid', (col) =>
|
.addColumn('workspace_id', 'uuid', (col) =>
|
||||||
col.references('workspaces.id').onDelete('cascade'),
|
col.references('workspaces.id').onDelete('cascade'),
|
||||||
)
|
)
|
||||||
.addColumn('type', 'varchar', (col) => col.notNull())
|
|
||||||
.addColumn('expires_at', 'timestamptz')
|
.addColumn('expires_at', 'timestamptz')
|
||||||
.addColumn('used_at', 'timestamptz', (col) => col)
|
.addColumn('used_at', 'timestamptz', (col) => col)
|
||||||
.addColumn('created_at', 'timestamptz', (col) =>
|
.addColumn('created_at', 'timestamptz', (col) =>
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
InsertableUserToken,
|
InsertableUserToken,
|
||||||
UpdatableUserToken,
|
UpdatableUserToken,
|
||||||
|
UserToken,
|
||||||
} from '@docmost/db/types/entity.types';
|
} from '@docmost/db/types/entity.types';
|
||||||
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
||||||
import { dbOrTx } from '@docmost/db/utils';
|
import { dbOrTx } from '@docmost/db/utils';
|
||||||
@ -8,9 +9,33 @@ import { Injectable } from '@nestjs/common';
|
|||||||
import { InjectKysely } from 'nestjs-kysely';
|
import { InjectKysely } from 'nestjs-kysely';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class UserTokensRepo {
|
export class UserTokenRepo {
|
||||||
constructor(@InjectKysely() private readonly db: KyselyDB) {}
|
constructor(@InjectKysely() private readonly db: KyselyDB) {}
|
||||||
|
|
||||||
|
async findById(
|
||||||
|
token: string,
|
||||||
|
workspaceId: string,
|
||||||
|
trx?: KyselyTransaction,
|
||||||
|
): Promise<UserToken> {
|
||||||
|
const db = dbOrTx(this.db, trx);
|
||||||
|
|
||||||
|
return db
|
||||||
|
.selectFrom('userTokens')
|
||||||
|
.select([
|
||||||
|
'id',
|
||||||
|
'token',
|
||||||
|
'userId',
|
||||||
|
'workspaceId',
|
||||||
|
'type',
|
||||||
|
'expiresAt',
|
||||||
|
'usedAt',
|
||||||
|
'createdAt',
|
||||||
|
])
|
||||||
|
.where('token', '=', token)
|
||||||
|
.where('workspaceId', '=', workspaceId)
|
||||||
|
.executeTakeFirst();
|
||||||
|
}
|
||||||
|
|
||||||
async insertUserToken(
|
async insertUserToken(
|
||||||
insertableUserToken: InsertableUserToken,
|
insertableUserToken: InsertableUserToken,
|
||||||
trx?: KyselyTransaction,
|
trx?: KyselyTransaction,
|
||||||
@ -28,24 +53,24 @@ export class UserTokensRepo {
|
|||||||
workspaceId: string,
|
workspaceId: string,
|
||||||
tokenType: string,
|
tokenType: string,
|
||||||
trx?: KyselyTransaction,
|
trx?: KyselyTransaction,
|
||||||
) {
|
): Promise<UserToken[]> {
|
||||||
const db = dbOrTx(this.db, trx);
|
const db = dbOrTx(this.db, trx);
|
||||||
return db
|
return db
|
||||||
.selectFrom('userTokens')
|
.selectFrom('userTokens')
|
||||||
.select([
|
.select([
|
||||||
'id',
|
'id',
|
||||||
'token',
|
'token',
|
||||||
'user_id',
|
'userId',
|
||||||
'workspace_id',
|
'workspaceId',
|
||||||
'type',
|
'type',
|
||||||
'expires_at',
|
'expiresAt',
|
||||||
'used_at',
|
'usedAt',
|
||||||
'created_at',
|
'createdAt',
|
||||||
])
|
])
|
||||||
.where('user_id', '=', userId)
|
.where('userId', '=', userId)
|
||||||
.where('workspace_id', '=', workspaceId)
|
.where('workspaceId', '=', workspaceId)
|
||||||
.where('type', '=', tokenType)
|
.where('type', '=', tokenType)
|
||||||
.orderBy('expires_at desc')
|
.orderBy('expiresAt desc')
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -57,33 +82,21 @@ export class UserTokensRepo {
|
|||||||
const db = dbOrTx(this.db, trx);
|
const db = dbOrTx(this.db, trx);
|
||||||
return db
|
return db
|
||||||
.updateTable('userTokens')
|
.updateTable('userTokens')
|
||||||
.set({ ...updatableUserToken })
|
.set(updatableUserToken)
|
||||||
.where('id', '=', userTokenId)
|
.where('id', '=', userTokenId)
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteUserToken(
|
async deleteToken(token: string, trx?: KyselyTransaction): Promise<void> {
|
||||||
userId: string,
|
|
||||||
workspaceId: string,
|
|
||||||
tokenType: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
) {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
const db = dbOrTx(this.db, trx);
|
||||||
return db
|
await db.deleteFrom('userTokens').where('token', '=', token).execute();
|
||||||
.deleteFrom('userTokens')
|
|
||||||
.where('user_id', '=', userId)
|
|
||||||
.where('workspace_id', '=', workspaceId)
|
|
||||||
.where('type', '=', tokenType)
|
|
||||||
.execute();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteExpiredUserTokens(
|
async deleteExpiredUserTokens(trx?: KyselyTransaction): Promise<void> {
|
||||||
trx?: KyselyTransaction,
|
|
||||||
) {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
const db = dbOrTx(this.db, trx);
|
||||||
return db
|
await db
|
||||||
.deleteFrom('userTokens')
|
.deleteFrom('userTokens')
|
||||||
.where('expires_at', '<', new Date())
|
.where('expiresAt', '<', new Date())
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
46
apps/server/src/database/types/db.d.ts
vendored
46
apps/server/src/database/types/db.d.ts
vendored
@ -1,22 +1,22 @@
|
|||||||
import type { ColumnType } from 'kysely';
|
/**
|
||||||
|
* This file was generated by kysely-codegen.
|
||||||
|
* Please do not edit it manually.
|
||||||
|
*/
|
||||||
|
|
||||||
export type Generated<T> =
|
import type { ColumnType } from "kysely";
|
||||||
T extends ColumnType<infer S, infer I, infer U>
|
|
||||||
? ColumnType<S, I | undefined, U>
|
|
||||||
: ColumnType<T, T | undefined, T>;
|
|
||||||
|
|
||||||
export type Int8 = ColumnType<
|
export type Generated<T> = T extends ColumnType<infer S, infer I, infer U>
|
||||||
string,
|
? ColumnType<S, I | undefined, U>
|
||||||
bigint | number | string,
|
: ColumnType<T, T | undefined, T>;
|
||||||
bigint | number | string
|
|
||||||
>;
|
export type Int8 = ColumnType<string, bigint | number | string, bigint | number | string>;
|
||||||
|
|
||||||
export type Json = JsonValue;
|
export type Json = JsonValue;
|
||||||
|
|
||||||
export type JsonArray = JsonValue[];
|
export type JsonArray = JsonValue[];
|
||||||
|
|
||||||
export type JsonObject = {
|
export type JsonObject = {
|
||||||
[K in string]?: JsonValue;
|
[x: string]: JsonValue | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type JsonPrimitive = boolean | number | string | null;
|
export type JsonPrimitive = boolean | number | string | null;
|
||||||
@ -162,6 +162,17 @@ export interface Users {
|
|||||||
workspaceId: string | null;
|
workspaceId: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface UserTokens {
|
||||||
|
createdAt: Generated<Timestamp>;
|
||||||
|
expiresAt: Timestamp | null;
|
||||||
|
id: Generated<string>;
|
||||||
|
token: string;
|
||||||
|
type: string;
|
||||||
|
usedAt: Timestamp | null;
|
||||||
|
userId: string;
|
||||||
|
workspaceId: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface WorkspaceInvitations {
|
export interface WorkspaceInvitations {
|
||||||
createdAt: Generated<Timestamp>;
|
createdAt: Generated<Timestamp>;
|
||||||
email: string | null;
|
email: string | null;
|
||||||
@ -190,17 +201,6 @@ export interface Workspaces {
|
|||||||
updatedAt: Generated<Timestamp>;
|
updatedAt: Generated<Timestamp>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserTokens {
|
|
||||||
id: Generated<string>;
|
|
||||||
token: string;
|
|
||||||
user_id: string;
|
|
||||||
workspace_id: string;
|
|
||||||
type: string;
|
|
||||||
expires_at: Timestamp | null;
|
|
||||||
used_at: Timestamp | null;
|
|
||||||
created_at: Generated<Timestamp>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DB {
|
export interface DB {
|
||||||
attachments: Attachments;
|
attachments: Attachments;
|
||||||
comments: Comments;
|
comments: Comments;
|
||||||
@ -211,7 +211,7 @@ export interface DB {
|
|||||||
spaceMembers: SpaceMembers;
|
spaceMembers: SpaceMembers;
|
||||||
spaces: Spaces;
|
spaces: Spaces;
|
||||||
users: Users;
|
users: Users;
|
||||||
|
userTokens: UserTokens;
|
||||||
workspaceInvitations: WorkspaceInvitations;
|
workspaceInvitations: WorkspaceInvitations;
|
||||||
workspaces: Workspaces;
|
workspaces: Workspaces;
|
||||||
userTokens: UserTokens;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -73,7 +73,7 @@ export type Attachment = Selectable<Attachments>;
|
|||||||
export type InsertableAttachment = Insertable<Attachments>;
|
export type InsertableAttachment = Insertable<Attachments>;
|
||||||
export type UpdatableAttachment = Updateable<Omit<Attachments, 'id'>>;
|
export type UpdatableAttachment = Updateable<Omit<Attachments, 'id'>>;
|
||||||
|
|
||||||
// User Tokens
|
// User Token
|
||||||
export type UserToken = Selectable<UserTokens>;
|
export type UserToken = Selectable<UserTokens>;
|
||||||
export type InsertableUserToken = Insertable<UserTokens>;
|
export type InsertableUserToken = Insertable<UserTokens>;
|
||||||
export type UpdatableUserToken = Updateable<Omit<UserTokens, 'id'>>;
|
export type UpdatableUserToken = Updateable<Omit<UserTokens, 'id'>>;
|
||||||
@ -1,27 +1,28 @@
|
|||||||
import { Section, Text } from '@react-email/components';
|
import { Button, Link, Section, Text } from '@react-email/components';
|
||||||
import * as React from 'react';
|
import * as React from 'react';
|
||||||
import { content, paragraph } from '../css/styles';
|
import { button, content, paragraph } from '../css/styles';
|
||||||
import { MailBody } from '../partials/partials';
|
import { MailBody } from '../partials/partials';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
username: string;
|
username: string;
|
||||||
code: string;
|
resetLink: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ForgotPasswordEmail = ({ username, code }: Props) => {
|
export const ForgotPasswordEmail = ({ username, resetLink }: Props) => {
|
||||||
return (
|
return (
|
||||||
<MailBody>
|
<MailBody>
|
||||||
<Section style={content}>
|
<Section style={content}>
|
||||||
<Text style={paragraph}>Hi {username},</Text>
|
<Text style={paragraph}>Hi {username},</Text>
|
||||||
<Text style={paragraph}>
|
<Text style={paragraph}>
|
||||||
The code for resetting your password is: <strong>{code}</strong>.
|
We received a request from you to reset your password.
|
||||||
</Text>
|
</Text>
|
||||||
<Text style={paragraph}>
|
<Link href={resetLink}> Click here to set a new password</Link>
|
||||||
If you did not request a password reset, please ignore this email.
|
<Text style={paragraph}>
|
||||||
</Text>
|
If you did not request a password reset, please ignore this email.
|
||||||
</Section>
|
</Text>
|
||||||
</MailBody>
|
</Section>
|
||||||
);
|
</MailBody>
|
||||||
}
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export default ForgotPasswordEmail;
|
export default ForgotPasswordEmail;
|
||||||
Reference in New Issue
Block a user