Skip to content

Commit

Permalink
refactor(client): auth client layer
Browse files Browse the repository at this point in the history
  • Loading branch information
Jozwiaczek committed Mar 11, 2021
1 parent 978a840 commit c5c763c
Show file tree
Hide file tree
Showing 20 changed files with 77 additions and 61 deletions.
7 changes: 0 additions & 7 deletions packages/client/src/constants/enviroment.ts

This file was deleted.

5 changes: 5 additions & 0 deletions packages/client/src/constants/enviroments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
PROD: 'production',
DEV: 'development',
TEST: 'test',
};
3 changes: 2 additions & 1 deletion packages/client/src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { default as Environment } from './enviroment';
export { default as environments } from './enviroments';
export { default as localStorageKeys } from './localStorageKeys';
export { default as routes } from './routes';
3 changes: 3 additions & 0 deletions packages/client/src/constants/localStorageKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
LOGIN_EXPIRATION_DATE: 'loginExpirationDate',
};
6 changes: 3 additions & 3 deletions packages/client/src/constants/routes.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const routes = {
home: '/',
login: '/login',
registration: '/registration',
HOME: '/',
LOGIN: '/login',
REGISTRATION: '/registration',
};

export default routes;
2 changes: 1 addition & 1 deletion packages/client/src/containers/Login/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const Login = () => {
try {
await login(values);
reset();
history.push(routes.home);
history.push(routes.HOME);
} catch (error) {
onlyOnDevEnv(() => console.error(error));
showSnackbar({ message: t('form.errors.onSubmitError'), severity: 'error' });
Expand Down
4 changes: 2 additions & 2 deletions packages/client/src/containers/Registration/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const Registration = () => {
const { confirmPassword, ...formValues } = values;
await registerUser(formValues);
reset();
history.push(routes.home);
history.push(routes.HOME);
} catch (error) {
onlyOnDevEnv(() => console.error(error));
showSnackbar({ message: t('form.errors.onSubmitError'), severity: 'error' });
Expand Down Expand Up @@ -105,7 +105,7 @@ const Registration = () => {
</StyledButton>
<p>
{t('routes.registration.alreadyHaveAccount')}&nbsp;
<Link to={routes.login} colorVariant="colour">
<Link to={routes.LOGIN} colorVariant="colour">
{t('routes.registration.login')}
</Link>
</p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const GlobalLayout = ({ children }: GlobalLayoutProps) => {
return (
<Container>
<main>{children}</main>
{pathname === routes.login && (
{pathname === routes.LOGIN && (
<footer>
<Copyright />
</footer>
Expand Down
4 changes: 2 additions & 2 deletions packages/client/src/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import { initReactI18next } from 'react-i18next';

import { Environment } from '../constants';
import { environments } from '../constants';
import resources from './resources';

export enum SGLocale {
Expand All @@ -17,7 +17,7 @@ i18n
resources,
fallbackLng: SGLocale.en,
supportedLngs: Object.values(SGLocale),
debug: process.env.NODE_ENV === Environment.dev,
debug: process.env.NODE_ENV === environments.DEV,
});

export default i18n;
3 changes: 2 additions & 1 deletion packages/client/src/providers/api/AuthProvider/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { AxiosResponse } from 'axios';
import React, { useCallback, useEffect } from 'react';

import { localStorageKeys } from '../../../constants';
import { useCurrentUser } from '../../../hooks';
import useAxios from '../../../hooks/useAxios';
import useLocalStorage from '../../../hooks/useLocalStorage';
Expand All @@ -16,7 +17,7 @@ import {
const AuthProvider = ({ children }: AuthProviderProps) => {
const axios = useAxios();
const [currentUser, setCurrentUser] = useCurrentUser();
const [expiration] = useLocalStorage('loginExpirationDate', undefined);
const [expiration] = useLocalStorage(localStorageKeys.LOGIN_EXPIRATION_DATE, undefined);

const checkAuth = useCallback(async () => {
if (currentUser) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { ReactNode } from 'react';

export interface AxiosProviderProps {
children: ReactNode;
}
5 changes: 3 additions & 2 deletions packages/client/src/providers/api/AxiosProvider/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import axios, { AxiosError } from 'axios';
import React, { PropsWithChildren, ReactNode } from 'react';
import React from 'react';

import { useCurrentUser } from '../../../hooks';
import { AxiosContext } from './AxiosProvider.context';
import { AxiosProviderProps } from './AxiosProvider.types';

const AxiosProvider = ({ children }: { children: ReactNode }) => {
const AxiosProvider = ({ children }: AxiosProviderProps) => {
const API_URL = process.env.REACT_APP_API_URL;
const [, setUser] = useCurrentUser();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { ReactNode } from 'react';

import { Role } from '../../../enums/role.enum';

export interface User {
Expand All @@ -7,6 +9,10 @@ export interface User {
roles: Array<Role>;
}

export interface CurrentUserProviderProps {
children: ReactNode;
}

export type CurrentUserContextValue = [
User | undefined,
(newUser: User | undefined, expirationDate: number | undefined = undefined) => void,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import React, { PropsWithChildren, useMemo, useState } from 'react';
import React, { useMemo, useState } from 'react';

import useLocalStorage from '../../../hooks/useLocalStorage';
import { CurrentUserContext } from './CurrentUserProvider.context';
import { User } from './CurrentUserProvider.types';
import { CurrentUserProviderProps, User } from './CurrentUserProvider.types';

const CurrentUserProvider = ({ children }: PropsWithChildren<unknown>) => {
const CurrentUserProvider = ({ children }: CurrentUserProviderProps) => {
const [storeUser, setStoreUser] = useState<User | undefined>();
const [expiration, setExpiration, removeExpiration] = useLocalStorage<number | undefined>(
'loginExpirationDate',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import React from 'react';
import { RouteProps } from 'react-router';
import { Redirect, Route } from 'react-router-dom';

import { routes } from '../../constants';
import { useCurrentUser } from '../../hooks';
import { routes } from '../constants';
import { useCurrentUser } from '../hooks';

const RouteGuard = (props: RouteProps) => {
const [currentUser] = useCurrentUser();
Expand All @@ -12,7 +12,7 @@ const RouteGuard = (props: RouteProps) => {
return <Route {...props} />;
}

return <Redirect to={{ pathname: routes.login }} />;
return <Redirect to={{ pathname: routes.LOGIN }} />;
};

export default RouteGuard;
2 changes: 1 addition & 1 deletion packages/client/src/routes/PublicRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const PublicGuard = (props: RouteProps) => {
const [currentUser] = useCurrentUser();

if (currentUser) {
return <Redirect to={{ pathname: routes.home }} />;
return <Redirect to={{ pathname: routes.HOME }} />;
}

return <Route {...props} />;
Expand Down
34 changes: 4 additions & 30 deletions packages/client/src/routes/index.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,16 @@
import React from 'react';
import { RouteProps as RouterRouteProps } from 'react-router';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

import { routes } from '../constants';
import { Dashboard, Login, Registration } from '../containers';
import { GlobalLayout } from '../elements';
import { useCurrentUser } from '../hooks';
import { AuthProvider } from '../providers/api';
import PrivateRoute from './PrivateRoute';
import PublicRoute from './PublicRoute';
import RouteGuard from './RouteGuard';

interface RouteProps extends RouterRouteProps {
path: string;
}

export const unauthorizedRoutes: Array<RouteProps> = [
{
path: routes.login,
component: Login,
},
{
path: routes.registration,
component: Registration,
},
];

export const authorizedRoutes = [
{
path: routes.home,
component: Dashboard,
exact: true,
},
];
import { authorizedRoutes, unauthorizedRoutes } from './routesConfig';

const NotFoundPage = () => {
const [currentUser] = useCurrentUser();
console.log('L:37 | currentUser: ', currentUser);
return <p>NotFoundPage</p>;
return <p>NotFoundPage - {currentUser?.email}</p>;
};

const Routes = () => (
Expand All @@ -48,7 +22,7 @@ const Routes = () => (
<PublicRoute key={routeProps.path} {...routeProps} />
))}
{authorizedRoutes.map((routeProps) => (
<RouteGuard key={routeProps.path} {...routeProps} />
<PrivateRoute key={routeProps.path} {...routeProps} />
))}
<Route component={NotFoundPage} />
</Switch>
Expand Down
27 changes: 27 additions & 0 deletions packages/client/src/routes/routesConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { RouteProps as RouterRouteProps } from 'react-router';

import { routes } from '../constants';
import { Dashboard, Login, Registration } from '../containers';

interface RouteProps extends RouterRouteProps {
path: string;
}

export const authorizedRoutes = [
{
path: routes.HOME,
component: Dashboard,
exact: true,
},
];

export const unauthorizedRoutes: Array<RouteProps> = [
{
path: routes.LOGIN,
component: Login,
},
{
path: routes.REGISTRATION,
component: Registration,
},
];
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://cra.link/PWA

import { Environment } from '../constants';
import { environments } from '../constants';

const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
Expand All @@ -26,7 +26,7 @@ type Config = {
};

export function register(config?: Config) {
if (process.env.NODE_ENV === Environment.prod && 'serviceWorker' in navigator) {
if (process.env.NODE_ENV === environments.PROD && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
Expand Down
4 changes: 2 additions & 2 deletions packages/client/src/utils/onlyOnDevEnv.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Environment from '../constants/enviroment';
import environments from '../constants/enviroments';

const onlyOnDevEnv = (callback: () => void) => {
const isDev = process.env.NODE_ENV === Environment.dev;
const isDev = process.env.NODE_ENV === environments.DEV;
if (isDev) {
callback();
}
Expand Down

0 comments on commit c5c763c

Please sign in to comment.