Skip to content
Open
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
34 changes: 22 additions & 12 deletions src/boot/apollo.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,39 @@
// import { currentOrg } from '@/utils';
import { AUTH_TOKEN } from '@/shared/constants/storage';
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import { AUTH_TOKEN, AUTH_STATUS } from '@/shared/constants/storage';
import { ApolloClient, InMemoryCache, ApolloLink, HttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

const httpLink = createHttpLink({
// uri: import.meta.env.VITE_DEV_SERVER_URL,
const httpLink = new HttpLink({
uri: process.env.NEXT_PUBLIC_DEV_SERVER_URL,
credentials: 'include',
});

const authLink = setContext((_, { headers }) => {
const token =
typeof window !== 'undefined'
? sessionStorage.getItem(AUTH_TOKEN) || localStorage.getItem(AUTH_TOKEN)
: null;
// const token = sessionStorage.getItem(AUTH_TOKEN) || localStorage.getItem(AUTH_TOKEN);
const accessToken = typeof window !== 'undefined' ? localStorage.getItem(AUTH_TOKEN) : null;
return {
headers: {
...headers,
Authorization: token ? `Bearer ${token}` : '',
Authorization: accessToken ? `Bearer ${accessToken}` : '',
},
};
});

const responseLink = new ApolloLink((operation, forward) => {
return forward(operation).map((response) => {
if (typeof window !== 'undefined') {
const context = operation.getContext();
const newAccessToken = context.response.headers.get('x-new-access-token');
const isRefreshTokenExpired = context.response.headers.get('x-auth-status');
console.log('newAccessToken from backend', newAccessToken);
console.log('isRefreshTokenExpired from backend', isRefreshTokenExpired);
newAccessToken && localStorage.setItem(AUTH_TOKEN, newAccessToken);
isRefreshTokenExpired && localStorage.setItem(AUTH_STATUS, isRefreshTokenExpired);
}
return response;
});
});

export const client = new ApolloClient({
link: authLink.concat(httpLink),
link: ApolloLink.from([authLink, responseLink, httpLink]),
defaultOptions: {
watchQuery: {
fetchPolicy: 'no-cache',
Expand Down
9 changes: 7 additions & 2 deletions src/containers/Layout/sidebar/SidebarContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
import { colorBorder, colorBackground, colorHover } from '@/styles/palette';
import { left } from '@/styles/directions';
import styled from 'styled-components';
import { AUTH_TOKEN, THEME } from '@/shared/constants/storage';
import { AUTH_TOKEN, THEME, AUTH_STATUS } from '@/shared/constants/storage';
import { useUserContext } from '@/hooks/userHooks';
import { ROUTE_KEY, getPublicRouteByKey, getRouteByKey } from '@/routes/routeConfig';
import SidebarCategory from './SidebarCategory';
import SidebarLink, { SidebarLinkTitle, SidebarNavLink } from './SidebarLink';
import { REVOKETOKENS } from '@/graphql/auth';
import { useMutation } from '@apollo/client';

type SidebarContentProps = {
onClick: () => void;
Expand All @@ -16,9 +18,12 @@ type SidebarContentProps = {

const SidebarContent = ({ onClick, $collapse }: SidebarContentProps) => {
const { store, setStore } = useUserContext();
const logout = () => {
const [revokeTokens] = useMutation(REVOKETOKENS);
const logout = async () => {
await revokeTokens();
sessionStorage.setItem(AUTH_TOKEN, '');
localStorage.setItem(AUTH_TOKEN, '');
localStorage.removeItem(AUTH_STATUS);
};

const changeTheme = (color: string) => {
Expand Down
9 changes: 7 additions & 2 deletions src/containers/Layout/topbar/TopbarProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,27 @@ import styled from 'styled-components';
import { marginLeft, right, left } from '@/styles/directions';
import { colorBackground, colorHover, colorText, colorBorder } from '@/styles/palette';
import { useUserContext } from '@/hooks/userHooks';
import { AUTH_TOKEN } from '@/shared/constants/storage';
import { AUTH_TOKEN, AUTH_STATUS } from '@/shared/constants/storage';
import Image from 'next/image';
import { TopbarBack, TopbarDownIcon } from './BasicTopbarComponents';
import TopbarMenuLink, { TopbarLink } from './TopbarMenuLink';
import { REVOKETOKENS } from '@/graphql/auth';
import { useMutation } from '@apollo/client';

const TopbarProfile = () => {
const { store } = useUserContext();
const [isCollapsed, setIsCollapsed] = useState(false);
const [revokeTokens] = useMutation(REVOKETOKENS);

const toggleCollapse = () => {
setIsCollapsed(!isCollapsed);
};

const logout = () => {
const logout = async () => {
await revokeTokens();
sessionStorage.setItem(AUTH_TOKEN, '');
localStorage.setItem(AUTH_TOKEN, '');
localStorage.removeItem(AUTH_STATUS);
};

return (
Expand Down
10 changes: 8 additions & 2 deletions src/graphql/auth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { gql } from './codegen/';
export const USER_LOGIN = gql(`
mutation Login($email: String!, $password: String!) {
login(email: $email, password: $password) {
mutation Login($email: String!, $password: String!, $isStaySignedIn: Boolean!) {
login(email: $email, password: $password, isStaySignedIn: $isStaySignedIn) {
code
message
data
Expand All @@ -18,3 +18,9 @@ export const USER_REGISTER = gql(`
}
}
`);

export const REVOKETOKENS = gql(`
mutation RevokeTokens {
revokeTokens
}
`);
13 changes: 10 additions & 3 deletions src/graphql/codegen/gql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ import { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/
* Therefore it is highly recommended to use the babel or swc plugin for production.
*/
const documents = {
'\n mutation Login($email: String!, $password: String!) {\n login(email: $email, password: $password) {\n code\n message\n data\n }\n }\n':
'\n mutation Login($email: String!, $password: String!, $isStaySignedIn: Boolean!) {\n login(email: $email, password: $password, isStaySignedIn: $isStaySignedIn) {\n code\n message\n data\n }\n }\n':
types.LoginDocument,
'\n mutation Register($input: CreateUserInput!) {\n register(input: $input) {\n code\n message\n data\n }\n }\n':
types.RegisterDocument,
'\n mutation RevokeTokens {\n revokeTokens\n }\n': types.RevokeTokensDocument,
'\n query getUserInfo {\n getUserInfo {\n id\n displayName\n }\n }\n':
types.GetUserInfoDocument,
'\n query getUserById($id: String!) {\n getUserById(id: $id) {\n id\n email\n realName\n displayName\n mobile\n }\n }\n':
Expand All @@ -43,14 +44,20 @@ export function gql(source: string): unknown;
* The gql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/
export function gql(
source: '\n mutation Login($email: String!, $password: String!) {\n login(email: $email, password: $password) {\n code\n message\n data\n }\n }\n'
): (typeof documents)['\n mutation Login($email: String!, $password: String!) {\n login(email: $email, password: $password) {\n code\n message\n data\n }\n }\n'];
source: '\n mutation Login($email: String!, $password: String!, $isStaySignedIn: Boolean!) {\n login(email: $email, password: $password, isStaySignedIn: $isStaySignedIn) {\n code\n message\n data\n }\n }\n'
): (typeof documents)['\n mutation Login($email: String!, $password: String!, $isStaySignedIn: Boolean!) {\n login(email: $email, password: $password, isStaySignedIn: $isStaySignedIn) {\n code\n message\n data\n }\n }\n'];
/**
* The gql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/
export function gql(
source: '\n mutation Register($input: CreateUserInput!) {\n register(input: $input) {\n code\n message\n data\n }\n }\n'
): (typeof documents)['\n mutation Register($input: CreateUserInput!) {\n register(input: $input) {\n code\n message\n data\n }\n }\n'];
/**
* The gql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/
export function gql(
source: '\n mutation RevokeTokens {\n revokeTokens\n }\n'
): (typeof documents)['\n mutation RevokeTokens {\n revokeTokens\n }\n'];
/**
* The gql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/
Expand Down
35 changes: 35 additions & 0 deletions src/graphql/codegen/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ export type Mutation = {
login: Result;
/** User register */
register: Result;
/** User logout */
revokeTokens: Scalars['Boolean']['output'];
/** Update exchange key info */
updateExchangeKey: Scalars['Boolean']['output'];
/** Update user info */
Expand All @@ -107,6 +109,7 @@ export type MutationDeleteUserArgs = {

export type MutationLoginArgs = {
email: Scalars['String']['input'];
isStaySignedIn?: InputMaybe<Scalars['Boolean']['input']>;
password: Scalars['String']['input'];
};

Expand Down Expand Up @@ -210,6 +213,7 @@ export type UserType = {
export type LoginMutationVariables = Exact<{
email: Scalars['String']['input'];
password: Scalars['String']['input'];
isStaySignedIn: Scalars['Boolean']['input'];
}>;

export type LoginMutation = {
Expand All @@ -226,6 +230,10 @@ export type RegisterMutation = {
register: { __typename?: 'Result'; code: number; message?: string | null; data?: string | null };
};

export type RevokeTokensMutationVariables = Exact<{ [key: string]: never }>;

export type RevokeTokensMutation = { __typename?: 'Mutation'; revokeTokens: boolean };

export type GetUserInfoQueryVariables = Exact<{ [key: string]: never }>;

export type GetUserInfoQuery = {
Expand Down Expand Up @@ -280,6 +288,14 @@ export const LoginDocument = {
type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } },
},
},
{
kind: 'VariableDefinition',
variable: { kind: 'Variable', name: { kind: 'Name', value: 'isStaySignedIn' } },
type: {
kind: 'NonNullType',
type: { kind: 'NamedType', name: { kind: 'Name', value: 'Boolean' } },
},
},
],
selectionSet: {
kind: 'SelectionSet',
Expand All @@ -298,6 +314,11 @@ export const LoginDocument = {
name: { kind: 'Name', value: 'password' },
value: { kind: 'Variable', name: { kind: 'Name', value: 'password' } },
},
{
kind: 'Argument',
name: { kind: 'Name', value: 'isStaySignedIn' },
value: { kind: 'Variable', name: { kind: 'Name', value: 'isStaySignedIn' } },
},
],
selectionSet: {
kind: 'SelectionSet',
Expand Down Expand Up @@ -357,6 +378,20 @@ export const RegisterDocument = {
},
],
} as unknown as DocumentNode<RegisterMutation, RegisterMutationVariables>;
export const RevokeTokensDocument = {
kind: 'Document',
definitions: [
{
kind: 'OperationDefinition',
operation: 'mutation',
name: { kind: 'Name', value: 'RevokeTokens' },
selectionSet: {
kind: 'SelectionSet',
selections: [{ kind: 'Field', name: { kind: 'Name', value: 'revokeTokens' } }],
},
},
],
} as unknown as DocumentNode<RevokeTokensMutation, RevokeTokensMutationVariables>;
export const GetUserInfoDocument = {
kind: 'Document',
definitions: [
Expand Down
4 changes: 4 additions & 0 deletions src/hooks/userHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useRouter, usePathname } from 'next/navigation';
import { useAppContext, connectFactory } from '@/shared/utils/contextFactory';
import { GET_USER } from '@/graphql/user';
import { IUser } from '@/shared/utils/types';
import { AUTH_STATUS } from '@/shared/constants/storage';

// import { useLocation, useHistory } from 'react-router-dom';

Expand All @@ -21,8 +22,10 @@ export const useLoadUser = () => {

const router = useRouter();
const pathName = usePathname();
const isLoginPage = pathName === '/login';

const { loading, refetch } = useQuery<{ getUserInfo: IUser }>(GET_USER, {
skip: isLoginPage,
onCompleted: (data) => {
if (data.getUserInfo) {
const { id, displayName } = data.getUserInfo;
Expand All @@ -43,6 +46,7 @@ export const useLoadUser = () => {
console.error('failed retrieving user info, backing to login');
if (!pathName.match('/login') && typeof window !== 'undefined') {
router.push(`/login?orgUrl=${pathName}`);
localStorage.removeItem(AUTH_STATUS);
}
},
});
Expand Down
2 changes: 1 addition & 1 deletion src/module/account/settings/SettingForm.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { DisplayErrorMsgs, EmailErrorMsgs, PasswordErrorMsgs } from '@/shared/utils/helpers';
import { DisplayErrorMsgs, EmailErrorMsgs } from '@/shared/utils/helpers';
import SettingForm from './SettingForm';

function renderSettingPage() {
Expand Down
21 changes: 9 additions & 12 deletions src/module/auth/login-form/FormLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { USER_LOGIN } from '@/graphql/auth';
import { useSearchParams } from '@/hooks/useSearchParams';
import { AccountButton, LoginForm } from '@/shared/components/account/AccountElements';
import { AUTH_TOKEN, EMAIL, REMEMBER_ME } from '@/shared/constants/storage';
import { AUTH_TOKEN, EMAIL, STAY_SIGNED_IN } from '@/shared/constants/storage';
import { useMutation } from '@apollo/client';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
Expand All @@ -12,25 +12,25 @@ import { Alert } from 'react-bootstrap';
import { FormProvider, useForm } from 'react-hook-form';
import LoginFormGroup from './LoginFormGroup';

type LoginData = { email: string; password: string; remember_me: boolean };
type LoginData = { email: string; password: string; isStaySignedIn: boolean };

const FormLayout = () => {
const methods = useForm({
defaultValues: {
email: '',
password: '',
remember_me: false,
isStaySignedIn: false,
},
});
const { handleSubmit, watch } = methods;

const rememberMe = watch('remember_me');
const isStaySignedIn = watch('isStaySignedIn');

useEffect(() => {
if (rememberMe !== undefined && typeof window !== 'undefined') {
localStorage.setItem(REMEMBER_ME, rememberMe.toString());
if (isStaySignedIn !== undefined && typeof window !== 'undefined') {
localStorage.setItem(STAY_SIGNED_IN, isStaySignedIn.toString());
}
}, [rememberMe]);
}, [isStaySignedIn]);

const router = useRouter();
const [error, setError] = useState('');
Expand All @@ -45,15 +45,12 @@ const FormLayout = () => {
// refresh store after login success
// store.refetchHandler();
if (typeof window !== 'undefined') {
if (data.remember_me) {
sessionStorage.setItem(AUTH_TOKEN, '');
if (data.isStaySignedIn) {
localStorage.setItem(EMAIL, data.email);
localStorage.setItem(AUTH_TOKEN, result.data.login.data ?? '');
} else {
localStorage.setItem(EMAIL, '');
localStorage.setItem(AUTH_TOKEN, '');
sessionStorage.setItem(AUTH_TOKEN, result.data.login.data ?? '');
}
localStorage.setItem(AUTH_TOKEN, result.data.login.data ?? '');
}
if (originUrl && originUrl !== '/') {
// history.push(originUrl);
Expand Down
14 changes: 8 additions & 6 deletions src/module/auth/login-form/LoginFormGroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
import AccountOutlineIcon from 'mdi-react/AccountOutlineIcon';
import FormField from '@/shared/components/form/FormHookField';
import { emailPattern } from '@/shared/utils/helpers';
import { EMAIL, REMEMBER_ME } from '@/shared/constants/storage';
import { EMAIL, STAY_SIGNED_IN } from '@/shared/constants/storage';
import { Controller, useFormContext } from 'react-hook-form';
import PasswordField from '@/shared/components/form/Password';
import { AccountForgotPassword } from '@/shared/components/account/AccountElements';
Expand Down Expand Up @@ -73,17 +73,19 @@ export default function LoginFormGroup() {
</FormGroupField>
</FormGroup>
<FormGroup>
<FormGroupField>
<FormGroupField className="gap-4">
<Controller
control={control}
name="remember_me"
name="isStaySignedIn"
defaultValue={
typeof window !== 'undefined' ? localStorage.getItem(REMEMBER_ME) === 'true' : false
typeof window !== 'undefined'
? localStorage.getItem(STAY_SIGNED_IN) === 'true'
: false
}
render={({ field: { onChange, value } }) => (
<CheckBoxField
name="remember_me"
label="Remember me"
name="isStaySignedIn"
label="Stay Signed in"
checked={value}
onChange={onChange}
/>
Expand Down
Loading