Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(user): add utility hooks #823

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/i18n/src/locales/en/user.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
}
},
"messages": {
"error": "Could not change your password.",
"success": "Your password was successfully changed.",
"validation": {
"oldPassword": "Old password is required",
Expand Down
1 change: 1 addition & 0 deletions packages/i18n/src/locales/fr/user.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
}
},
"messages": {
"error": "Could not change your password. (fr)",
"success": "Your password was successfully changed. (fr)",
"validation": {
"oldPassword": "Old password is required (fr)",
Expand Down
20 changes: 20 additions & 0 deletions packages/user/src/api/user/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,31 @@
import client from "../axios";

import type {
ChangePasswordInputType,
LoginCredentials,
UpdateProfileInputType,
UserType,
} from "@/types";

export const changePassword = async (
{ newPassword, oldPassword }: ChangePasswordInputType,
apiBaseUrl: string,
) => {
const response = await client(apiBaseUrl).post(
"/change_password",
{ oldPassword, newPassword },
{
withCredentials: true,
},
);

if (response.data.status === "ERROR") {
throw new Error(response.data.message);
} else {
return response;
}
};

export const getIsFirstUser = async (
apiBaseUrl: string,
): Promise<{
Expand Down
51 changes: 10 additions & 41 deletions packages/user/src/components/Login/LoginWrapper.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
import { useTranslation } from "@dzangolab/react-i18n";
import { FC, useState } from "react";
import { toast } from "react-toastify";
import { FC } from "react";

import { LinkType } from "@/types/types";

import { LoginForm } from "./LoginForm";
import { ROUTES } from "../../constants";
import { useConfig, useUser } from "../../hooks";
import { verifySessionRoles } from "../../supertokens/helpers";
import login from "../../supertokens/login";
import { AuthLinks } from "../AuthLinks";
import { useConfig, useLogin } from "../../hooks";

import type { LoginCredentials, SignInUpPromise } from "../../types";

interface IProperties {
handleSubmit?: (credential: LoginCredentials) => void;
onLoginFailed?: (error: Error) => void;
onLoginSuccess?: (user: SignInUpPromise) => void;
onLoginFailed?: (error: Error) => Promise<void> | void;
onLoginSuccess?: (user: SignInUpPromise) => Promise<void> | void;
loading?: boolean;
showForgotPasswordLink?: boolean;
showSignupLink?: boolean;
Expand All @@ -31,9 +28,12 @@ export const LoginWrapper: FC<IProperties> = ({
showSignupLink = true,
}) => {
const { t } = useTranslation(["user", "errors"]);
const { setUser } = useUser();
const { user: userConfig } = useConfig();
const [loginLoading, setLoginLoading] = useState<boolean>(false);

const [loginUser, { isLoading: loginLoading }] = useLogin({
onSuccess: onLoginFailed,
onFailed: onLoginSuccess,
});

const links: Array<LinkType> = [
{
Expand All @@ -55,38 +55,7 @@ export const LoginWrapper: FC<IProperties> = ({
if (handleSubmit) {
handleSubmit(credentials);
} else {
setLoginLoading(true);

await login(credentials)
.then(async (result) => {
if (result?.user) {
if (
userConfig &&
(await verifySessionRoles(userConfig.supportedRoles))
) {
setUser(result.user);

onLoginSuccess && (await onLoginSuccess(result));

toast.success(`${t("login.messages.success")}`);
} else {
toast.error(t("login.messages.permissionDenied"));
}
}
})
.catch(async (error) => {
let errorMessage = "errors.otherErrors";

if (error.message) {
errorMessage = `errors.${error.message}`;
}

onLoginFailed && (await onLoginFailed(error));

toast.error(t(errorMessage, { ns: "errors" }));
});

setLoginLoading(false);
await loginUser(credentials);
}
};

Expand Down
4 changes: 4 additions & 0 deletions packages/user/src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
export * from "./useAcceptInvitation";
export * from "./useChangePassword";
export * from "./useConfig";
export * from "./useEmailVerification";
export * from "./useFirstUserSignup";
export * from "./useProfileCompletion";
export * from "./useUser";
export * from "./useLogin";
export * from "./useUser";
121 changes: 121 additions & 0 deletions packages/user/src/hooks/useAcceptInvitation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { useTranslation } from "@dzangolab/react-i18n";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { toast } from "react-toastify";

import {
acceptInvitation as acceptInvitationApi,
getInvitationByToken,
} from "@/api/invitation";

import { useConfig } from "./useConfig";
import { useLogin } from "./useLogin";

import type { Invitation, LoginCredentials } from "../types";

type UseAcceptInvitationConfig = {
autoLogin?: boolean;
showToasts?: boolean;
tokenParamKey?: string;
onSuccess?: (user: any) => Promise<void> | void;
onFailed?: (error?: any) => Promise<void> | void;
};

type UseAcceptInvitationMeta = {
isError: boolean;
isFetching: boolean;
isLoading: boolean;
isLoginLoading: boolean;
};

export function useAcceptInvitation(config?: UseAcceptInvitationConfig) {
const {
autoLogin = true,
showToasts = true,
tokenParamKey: tokenParameterKey = "token",
onSuccess,
onFailed,
} = config || {};

const { t } = useTranslation("invitations");
const appConfig: any = useConfig();

const parameters = useParams();
const token = parameters[tokenParameterKey];

const [isError, setIsError] = useState(false);
const [isFetching, setIsFetching] = useState(false);
const [invitation, setInvitation] = useState<Invitation | null>(null);
const [loginUser, { isLoading: isLoginLoading }] = useLogin({ showToasts });

const [isLoading, setIsLoading] = useState(false);

useEffect(() => {
if (token) {
setIsFetching(true);
getInvitationByToken(token, appConfig?.apiBaseUrl || "")
.then((response) => {
if ("data" in response && response.data.status === "ERROR") {
// TODO better handle errors
setIsError(true);
} else {
setInvitation(response as Invitation);
}
})
.catch(() => {
setIsError(true);
})
.finally(() => {
setIsFetching(false);
});
}
}, []);

const acceptInvitation = (credentials: LoginCredentials) => {
if (!token) {
return;
}

setIsLoading(true);

return acceptInvitationApi(token, credentials, appConfig?.apiBaseUrl || "")
.then(async (response) => {
setIsLoading(false);

if ("data" in response && response.data.status === "ERROR") {
// TODO better handle errors
setIsError(true);

onFailed && (await onFailed(response));

showToasts && toast.error(response.data.message);
} else {
onSuccess && (await onSuccess(response));

if (autoLogin) {
// TODO acceptInvitation should return authenticated user from api
await loginUser(credentials);
}
}
})
.catch(async (error) => {
setIsError(true);
setIsLoading(false);

onFailed && (await onFailed(error));

showToasts &&
toast.error(`${t("invitations.messages.errorAcceptingInvitation")}`);
});
};

return [
invitation,
acceptInvitation,
{ isError, isFetching, isLoading, isLoginLoading },
] as [
Invitation | null,
(credentials: LoginCredentials) => Promise<void>,
UseAcceptInvitationMeta,
];
}
64 changes: 64 additions & 0 deletions packages/user/src/hooks/useChangePassword.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { useTranslation } from "@dzangolab/react-i18n";
import { useState } from "react";
import { toast } from "react-toastify";

import { useConfig } from "./useConfig";
import { changePassword as changePasswordApi } from "../api/user";

import type { ChangePasswordInputType } from "../types";

type UseChangePasswordConfig = {
showToasts?: boolean;
onSuccess?: (user: any) => Promise<void> | void;
onFailed?: (error: any) => Promise<void> | void;
};

type UseChangePasswordMeta = {
isError: boolean;
isLoading: boolean;
};

export function useChangePassword(config?: UseChangePasswordConfig) {
const { showToasts = true, onFailed, onSuccess } = config || {};

const { t } = useTranslation(["user", "errors"]);
const appConfig = useConfig();

const [isError, setIsError] = useState(false);
const [isLoading, setIsLoading] = useState<boolean>(false);

const changePassword = (passwords: ChangePasswordInputType) => {
setIsLoading(true);

return changePasswordApi(passwords, appConfig?.apiBaseUrl || "")
.then(async (response) => {
setIsLoading(false);

if ("data" in response && response.data.status === "OK") {
onSuccess && (await onSuccess(response));

showToasts && toast.success(t("changePassword.messages.success"));
} else {
// TODO better handle errors
setIsError(true);

onFailed && (await onFailed(response));

showToasts && toast.error(response.data.message);
}
})
.catch(async (error) => {
setIsError(true);
setIsLoading(false);

onFailed && (await onFailed(error));

showToasts && toast.error(`${t("changePassword.messages.error")}`);
});
};

return [changePassword, { isError, isLoading }] as [
(passwords: ChangePasswordInputType) => Promise<any>,
UseChangePasswordMeta,
];
}
Loading
Loading