Skip to content

Commit

Permalink
fix: auth redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
ridhlab committed Dec 28, 2023
1 parent b2fc0bf commit 7169b6d
Show file tree
Hide file tree
Showing 10 changed files with 86 additions and 34 deletions.
21 changes: 21 additions & 0 deletions src/components/layout/Avatar.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,25 @@
import { removeAuthCookie } from "@/helpers/cookie";
import { modalConfirm } from "@/helpers/modal-confirm";
import { prompNotification } from "@/helpers/notification";
import { Routes } from "@/routes/routes";
import { useLogoutMutation } from "@/services/mutation/Auth";
import { colorConfig } from "@/themes/config";
import { LogoutOutlined, UserOutlined } from "@ant-design/icons";
import { Avatar as AvatarAntd, Dropdown, Space } from "antd";
import { ItemType } from "antd/es/menu/hooks/useItems";
import React from "react";

const Avatar: React.FC = () => {
const logoutMutation = useLogoutMutation({
onSuccess: (response) => {
removeAuthCookie();
setTimeout(() => {
window.location.replace(Routes.Login);
}, 1000);
prompNotification({ method: "success", message: response.message });
},
});

const items: ItemType[] = [
{
key: "profile",
Expand All @@ -25,6 +40,12 @@ const Avatar: React.FC = () => {
Logout
</Space>
),
onClick: () =>
modalConfirm({
onOk: () => {
logoutMutation.mutate({});
},
}),
},
];

Expand Down
13 changes: 5 additions & 8 deletions src/components/modules/Auth/Login/LoginCard.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useAuthContext } from "@/contexts/AuthContext";
import { setAuthCookie } from "@/helpers/cookie";
import { getMinCharMessage, getRequiredMessage } from "@/helpers/form";
import { prompNotification } from "@/helpers/notification";
Expand All @@ -8,7 +7,7 @@ import { ILoginRequest } from "@/interfaces/requests/Auth";
import { Routes } from "@/routes/routes";
import { useLoginMutation } from "@/services/mutation/Auth";
import { Button, Card, Input, Row, Space, Typography, Form } from "antd";
import { Link, useNavigate } from "react-router-dom";
import { Link } from "react-router-dom";
import * as yup from "yup";

const schema: yup.ObjectSchema<ILoginRequest> = yup.object({
Expand All @@ -28,21 +27,19 @@ const schema: yup.ObjectSchema<ILoginRequest> = yup.object({
export const LoginCard = () => {
const { form, yupSync } = useFormUtility<ILoginRequest>({ schema });
const watch = Form.useWatch([], form);
const { afterLoginRegister } = useAuthContext();

const navigate = useNavigate();

const mutation = useLoginMutation({
onError: (error) => {
prompNotification({ method: "error", message: error.message });
},
onSuccess: (response) => {
const {
data: { token, user },
data: { token },
} = response;
setAuthCookie(token);
afterLoginRegister(user);
navigate(Routes.Dashboard, { replace: true });
setTimeout(() => {
window.location.replace(Routes.Dashboard);
}, 1000);
prompNotification({
method: "success",
message: "Login successfully",
Expand Down
13 changes: 5 additions & 8 deletions src/components/modules/Auth/Register/RegisterCard.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useAuthContext } from "@/contexts/AuthContext";
import { setAuthCookie } from "@/helpers/cookie";
import { getMinCharMessage, getRequiredMessage } from "@/helpers/form";
import { prompNotification } from "@/helpers/notification";
Expand All @@ -8,7 +7,7 @@ import { IRegisterRequest } from "@/interfaces/requests/Auth";
import { Routes } from "@/routes/routes";
import { useRegisterMutation } from "@/services/mutation/Auth";
import { Button, Card, Input, Row, Space, Typography, Form } from "antd";
import { Link, useNavigate } from "react-router-dom";
import { Link } from "react-router-dom";
import * as yup from "yup";

interface IRegisterForm extends IRegisterRequest {
Expand Down Expand Up @@ -37,21 +36,19 @@ const schema: yup.ObjectSchema<IRegisterForm> = yup.object({
export const RegisterCard = () => {
const { form, yupSync } = useFormUtility<IRegisterForm>({ schema });
const watch = Form.useWatch([], form);
const { afterLoginRegister } = useAuthContext();

const navigate = useNavigate();

const mutation = useRegisterMutation({
onError: (error) => {
prompNotification({ method: "error", message: error.message });
},
onSuccess: (response) => {
const {
data: { token, user },
data: { token },
} = response;
setAuthCookie(token);
afterLoginRegister(user);
navigate(Routes.Dashboard, { replace: true });
setTimeout(() => {
window.location.replace(Routes.Dashboard);
}, 1000);
prompNotification({
method: "success",
message: "Register successfully",
Expand Down
17 changes: 1 addition & 16 deletions src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ interface IAuthContextData {
isLoading: boolean;
isError: boolean;
error: IBaseResponse<unknown>;
afterLoginRegister: (user: IUser) => void;
afterLogout: () => void;
}

const AuthContext = React.createContext<IAuthContextData>({
Expand All @@ -21,34 +19,21 @@ const AuthContext = React.createContext<IAuthContextData>({
isLoading: false,
isError: false,
error: null,
afterLoginRegister: () => {},
afterLogout: () => {},
});

interface IProps {
children: React.ReactNode;
}

export const AuthContextProvider: React.FC<IProps> = ({ children }) => {
const [user, setUser] = React.useState<IUser>(null);
const queryUser = useGetUser();

const afterLoginRegister = (user: IUser) => {
setUser(user);
};

const afterLogout = () => {
setUser(null);
};

const authState: IAuthContextData = {
isLoading: queryUser.isLoading,
user: user ?? queryUser.data,
user: queryUser.data,
error: queryUser.error,
isError: !!queryUser.error,
isAuthenticate: !!getCookie(AUTH_TOKEN_NAME),
afterLoginRegister,
afterLogout,
};

return (
Expand Down
2 changes: 2 additions & 0 deletions src/helpers/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ import Cookies from "js-cookie";
export const getCookie = (key: string) => Cookies.get(key);
export const setAuthCookie = (authToken: string) =>
Cookies.set(AUTH_TOKEN_NAME, authToken, { expires: 1 });

export const removeAuthCookie = () => Cookies.remove(AUTH_TOKEN_NAME);
18 changes: 18 additions & 0 deletions src/helpers/modal-confirm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { colorConfig } from "@/themes/config";
import { ExclamationCircleFilled } from "@ant-design/icons";
import { ModalFuncProps } from "antd";
import confirm from "antd/es/modal/confirm";

export const modalConfirm = (config?: ModalFuncProps) => {
return confirm({
title: "Are you sure?",
icon: (
<ExclamationCircleFilled
style={{ color: colorConfig.feedback.warning }}
/>
),
closable: true,
centered: true,
...config,
});
};
1 change: 1 addition & 0 deletions src/routes/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ export enum Routes {
export enum EndpointApi {
Login = "/login",
Register = "/register",
Logout = "/logout",
GetUser = "/user",
}
11 changes: 10 additions & 1 deletion src/services/apis/Auth/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { EndpointApi } from "@/routes/routes";
import { axiosInstance } from "..";
import { axiosAuthInstance, axiosInstance } from "..";
import { ILoginRequest, IRegisterRequest } from "@/interfaces/requests/Auth";
import { AxiosError } from "axios";

Expand All @@ -23,3 +23,12 @@ export const register = async (payload: IRegisterRequest) => {
throw (error as AxiosError).response.data;
}
};

export const logout = async () => {
try {
const response = await axiosAuthInstance.post(EndpointApi.Logout);
return response.data;
} catch (error) {
throw (error as AxiosError).response.data;
}
};
19 changes: 18 additions & 1 deletion src/services/mutation/Auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { ILoginRequest, IRegisterRequest } from "@/interfaces/requests/Auth";
import { ILoginResponse, IRegisterResponse } from "@/interfaces/responses/Auth";
import { IBaseResponse } from "@/interfaces/responses/base";
import { login, register } from "@/services/apis/Auth";
import { login, logout, register } from "@/services/apis/Auth";
import { UseMutationOptions, useMutation } from "@tanstack/react-query";

export const useRegisterMutation = (
Expand Down Expand Up @@ -38,3 +38,20 @@ export const useLoginMutation = (
...options,
});
};

export const useLogoutMutation = (
options?: UseMutationOptions<
IBaseResponse<unknown>,
IBaseResponse<unknown>,
unknown,
unknown
>
) => {
return useMutation({
mutationKey: ["logout"],
mutationFn: () => {
return logout();
},
...options,
});
};
5 changes: 5 additions & 0 deletions src/themes/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,9 @@ export const colorConfig = {
lightGray: "#E7E7E7",
white: "#FFFFFF",
},
feedback: {
success: "#52C41A",
warning: "#faad14",
error: "#ff4d4f",
},
};

0 comments on commit 7169b6d

Please sign in to comment.