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

Add login and authentication token #684

Merged
merged 1 commit into from
Nov 20, 2023
Merged
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: 0 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
BROWSER=none
DB_URI=mongodb://localhost:27017/artyom-ganev-node
JWT_SECRET=
NEW_RELIC_KEY=
PORT=3000
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@
"ts-jest": "^29.1.1",
"ts-loader": "^9.5.1",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0"
"tsconfig-paths": "^4.2.0",
"zustand": "4.4.6"
},
"devDependencies": {
"@babel/core": "^7.18.6",
Expand Down
23 changes: 23 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions src/assets/styles.scss
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ h3 {
width: 100vw;
}

.ag-textAlign-center {
text-align: center;
}

::-webkit-scrollbar {
position: relative;
width: 15px;
Expand All @@ -77,12 +81,12 @@ h3 {

::-webkit-scrollbar-thumb {
background-clip: content-box;
background-color: #c7c7c7;
background-color: $purpleColor;
border-radius: 8px;
border: 4px solid transparent;

&:hover,
&:active {
background-color: #767676;
background-color: $darkBlueColor;
}
}
14 changes: 14 additions & 0 deletions src/client/features/auth/AuthForm.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
@import 'src/assets/variables';

.form {
padding: $padding-md;

&Item {
padding: $padding-sm 0;
text-align: center;
}
}

.error {
color: red;
}
61 changes: 61 additions & 0 deletions src/client/features/auth/AuthForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { ChangeEvent, JSX, useCallback, useState } from 'react';

import { Button } from '@mui/base/Button';
import { Input } from '@mui/base/Input';
import { useMutation } from '@tanstack/react-query';
import { useRouter } from 'next/router';
import { loginApi } from 'src/client/features/auth/auth-api';
import { useAuthToken } from 'src/client/features/auth/hooks/use-auth-token';

import styles from './AuthForm.module.scss';

const AuthForm = (): JSX.Element => {
const router = useRouter();
const [login, setLogin] = useState<string>('');
const [password, setPassword] = useState<string>('');
const [error, setError] = useState<string>('');
const { setToken } = useAuthToken();
const { mutate } = useMutation<string>({
mutationFn: async () => {
if (!login) {
setError('Invalid login');
return '';
}
if (!password) {
setError('Invalid password');
return '';
}
const { authToken } = await loginApi(login, password);
return authToken;
},
onSuccess: (token: string) => {
setToken(token);
void router.push('/');
},
onError: (error) => {
setError(error.message);
},
});
const handleLoginChange = useCallback(({ target }: ChangeEvent<HTMLInputElement>) => setLogin(target.value), []);
const handlePasswordChange = useCallback(
({ target }: ChangeEvent<HTMLInputElement>) => setPassword(target.value),
[]
);
const handleLogin = useCallback(() => mutate(), [mutate]);
return (
<div className={`ag-flexbox ag-flexColumn ag-flexColumn ag-justifyContent_center ${styles.form}`}>
<div className={styles.formItem}>
<Input placeholder='Login' onChange={handleLoginChange} />
</div>
<div className={styles.formItem}>
<Input placeholder='Password' type='password' onChange={handlePasswordChange} />
</div>
<div className={styles.formItem}>
<Button onClick={handleLogin}>Login</Button>
</div>
{error ? <div className={`${styles.formItem} ${styles.error}`}>{error}</div> : null}
</div>
);
};

export default AuthForm;
30 changes: 30 additions & 0 deletions src/client/features/auth/AuthWrapper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { JSX, PropsWithChildren } from 'react';

import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/router';
import { LOGIN_PAGE_URL } from 'src/common/common-constants';

import { checkAuthTokenApi } from './auth-api';
import { CHECK_AUTH_TOKEN_QUERY_KEY } from './auth-constants';
import { AuthStore } from './auth-types';
import { useAuthToken } from './hooks/use-auth-token';

const AuthWrapper = ({ children }: PropsWithChildren): JSX.Element => {
const router = useRouter();
const { isLoading } = useQuery<Record<string, unknown>>({
queryFn: async () => {
const { token, setToken }: AuthStore = useAuthToken.getState();
try {
return await checkAuthTokenApi(token);
} catch (e) {
setToken('');
void router.replace(LOGIN_PAGE_URL);
}
},
queryKey: [CHECK_AUTH_TOKEN_QUERY_KEY],
refetchOnMount: false,
});
return <>{isLoading ? 'Loading... ' : children}</>;
};

export default AuthWrapper;
23 changes: 23 additions & 0 deletions src/client/features/auth/LoginButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'use client';
import { JSX, useCallback } from 'react';

import { Button } from '@mui/base/Button';
import { useRouter } from 'next/router';
import { useAuthToken } from 'src/client/features/auth/hooks/use-auth-token';
import { useAuthorized } from 'src/client/features/auth/hooks/use-authorized';
import { LOGIN_PAGE_URL } from 'src/common/common-constants';

const LoginButton = (): JSX.Element => {
const router = useRouter();
const { setToken } = useAuthToken();
const isAuthorized = useAuthorized();
const handleLoginClick = useCallback(() => router.push(LOGIN_PAGE_URL), []);
const handleLogoutClick = useCallback(() => setToken(''), [setToken]);
return isAuthorized ? (
<Button onClick={handleLogoutClick}>Logout</Button>
) : (
<Button onClick={handleLoginClick}>Login</Button>
);
};

export default LoginButton;
30 changes: 17 additions & 13 deletions src/client/features/auth/auth-api.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
import httpClient from 'src/client/app/http-client';

export const auth = async (username, password) =>
httpClient.post(`auth`, {
json: {
username,
password,
},
});
export const loginApi = (username: string, password: string): Promise<{ authToken: string }> =>
httpClient
.post('auth/login', {
json: {
username,
password,
},
})
.json();

export const user = async (accessToken) =>
httpClient.get('user', {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
export const checkAuthTokenApi = (token: string): Promise<Promise<Record<string, unknown>>> =>
httpClient
.get('auth/check-token', {
headers: {
Authorization: `Bearer ${token}`,
},
})
.json();
3 changes: 3 additions & 0 deletions src/client/features/auth/auth-constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const AUTH_TOKEN_KEY = 'AUTH_TOKEN';

export const CHECK_AUTH_TOKEN_QUERY_KEY = 'CHECK_AUTH_TOKEN_QUERY_KEY';
4 changes: 4 additions & 0 deletions src/client/features/auth/auth-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface AuthStore {
setToken: (token: string) => void;
token: string;
}
19 changes: 19 additions & 0 deletions src/client/features/auth/hooks/use-auth-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { create } from 'zustand';
import { createJSONStorage, devtools, persist } from 'zustand/middleware';

import { AuthStore } from '../auth-types';

export const useAuthToken = create<AuthStore>()(
devtools(
persist(
(set) => ({
token: '',
setToken: (token: string) => set(() => ({ token: token })),
}),
{
name: 'auth-store',
storage: createJSONStorage(() => sessionStorage),
}
)
)
);
6 changes: 6 additions & 0 deletions src/client/features/auth/hooks/use-authorized.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { useAuthToken } from './use-auth-token';

export const useAuthorized = (): boolean => {
const { token } = useAuthToken();
return token.length > 0;
};
2 changes: 2 additions & 0 deletions src/common/common-constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ export const BLOG_PAGE_ID = 'blog';
export const BLOG_PAGE_URL = `/${BLOG_PAGE_ID}`;
export const CAREER_PAGE_ID = 'career';
export const CAREER_PAGE_URL = `/${CAREER_PAGE_ID}`;
export const LOGIN_PAGE_ID = 'login';
export const LOGIN_PAGE_URL = `/${LOGIN_PAGE_ID}`;

if (isDev) {
console.log('isServer', isServer);
Expand Down
2 changes: 2 additions & 0 deletions src/common/components/Layout.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

.header {
height: $headerHeight;
left: $padding-lg;
position: fixed;
right: $padding-lg;
}

.main {
Expand Down
24 changes: 13 additions & 11 deletions src/common/components/Navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,19 @@ import ApiLink from './ApiLink';
import styles from './Navigation.module.scss';

const Navigation = (): ReactElement => (
<nav className={`ag-flexbox ag-fullWidth ag-alignItems_center ag-justifyContent_center ${styles.nav}`}>
<span className={styles.navLink}>
<Link href='/'>Home</Link>
</span>
<span className={styles.navLink}>
<Link href={BLOG_PAGE_URL}>Blog</Link>
</span>
<span className={styles.navLink}>
<Link href={CAREER_PAGE_URL}>Career</Link>
</span>
<ApiLink className={styles.navLink}>API</ApiLink>
<nav className={`ag-flexbox ag-fullWidth ag-alignItems_center ag-justifyContent_between ${styles.nav}`}>
<div className='ag-flexbox ag-fullWidth ag-alignItems_center ag-justifyContent_center'>
<span className={styles.navLink}>
<Link href='/'>Home</Link>
</span>
<span className={styles.navLink}>
<Link href={BLOG_PAGE_URL}>Blog</Link>
</span>
<span className={styles.navLink}>
<Link href={CAREER_PAGE_URL}>Career</Link>
</span>
<ApiLink className={styles.navLink}>API</ApiLink>
</div>
</nav>
);

Expand Down
37 changes: 20 additions & 17 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { StrictMode } from 'react';
import { JSX, StrictMode } from 'react';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import Head from 'next/head';
import 'src/assets/styles.scss';
import AuthWrapper from 'src/client/features/auth/AuthWrapper';
import Layout from 'src/common/components/Layout';

import packageJson from '../../package.json';
Expand All @@ -18,20 +19,22 @@ const queryClient = new QueryClient({
},
});

export default function App({ Component, pageProps }) {
return (
<StrictMode>
<QueryClientProvider client={queryClient}>
<Head>
<title>{pageProps.title}</title>
<meta name='build version' content={packageJson.version} />
<meta name='viewport' content='initial-scale=1, width=device-width' />
<link rel='shortcut icon' href={favicon.src} type='image/x-icon' />
</Head>
<Layout>
const App = ({ Component, pageProps }): JSX.Element => (
<StrictMode>
<QueryClientProvider client={queryClient}>
<Head>
<title>{pageProps.title}</title>
<meta name='build version' content={packageJson.version} />
<meta name='viewport' content='initial-scale=1, width=device-width' />
<link rel='shortcut icon' href={favicon.src} type='image/x-icon' />
</Head>
<Layout>
<AuthWrapper>
<Component {...pageProps} />
</Layout>
</QueryClientProvider>
</StrictMode>
);
}
</AuthWrapper>
</Layout>
</QueryClientProvider>
</StrictMode>
);

export default App;
9 changes: 9 additions & 0 deletions src/pages/login.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { JSX } from 'react';

import AuthForm from 'src/client/features/auth/AuthForm';

const Login = (): JSX.Element => {
return <AuthForm />;
};

export default Login;
2 changes: 1 addition & 1 deletion src/server/app/app-module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import { AuthModule } from 'src/server/features/auth/auth.module';
import { AuthModule } from 'src/server/features/auth/auth-module';
import { BlogModule } from 'src/server/features/blog/blog-module';
import { CareerModule } from 'src/server/features/career/career-module';

Expand Down
Loading