├── .gitignore ├── README.md ├── package-lock.json ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── src ├── App.tsx ├── api │ ├── auth │ │ ├── index.ts │ │ └── types.ts │ ├── endpoints.ts │ ├── index.ts │ └── instance.ts ├── components │ └── Header │ │ ├── Header.tsx │ │ └── index.ts ├── index.css ├── index.tsx ├── pages │ ├── Dashboard │ │ ├── Dashboard.tsx │ │ └── index.ts │ └── Main │ │ ├── Main.tsx │ │ ├── components │ │ └── Login │ │ │ ├── Login.tsx │ │ │ └── index.ts │ │ └── index.ts ├── react-app-env.d.ts ├── reportWebVitals.ts ├── setupTests.ts ├── store │ ├── auth │ │ ├── actionCreators.ts │ │ └── authReducer.ts │ └── index.ts └── utils │ ├── date.ts │ ├── history.ts │ └── jwt.ts └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 13 | 14 | The page will reload if you make edits.\ 15 | You will also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 35 | 36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 39 | 40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jwt_frontend", 3 | "version": "0.1.0", 4 | "private": true, 5 | "proxy": "http://localhost:3001", 6 | "dependencies": { 7 | "@reduxjs/toolkit": "^1.8.3", 8 | "@testing-library/jest-dom": "^5.16.4", 9 | "@testing-library/react": "^13.3.0", 10 | "@testing-library/user-event": "^13.5.0", 11 | "@types/jest": "^27.5.2", 12 | "@types/node": "^16.11.41", 13 | "@types/react": "^18.0.14", 14 | "@types/react-dom": "^18.0.5", 15 | "@types/redux-logger": "^3.0.9", 16 | "axios": "^0.27.2", 17 | "react": "^18.2.0", 18 | "react-dom": "^18.2.0", 19 | "react-redux": "^8.0.2", 20 | "react-router-dom": "^6.3.0", 21 | "react-scripts": "5.0.1", 22 | "redux-logger": "^3.0.6", 23 | "typescript": "^4.7.4", 24 | "web-vitals": "^2.1.4" 25 | }, 26 | "scripts": { 27 | "start": "react-scripts start", 28 | "build": "react-scripts build", 29 | "test": "react-scripts test", 30 | "eject": "react-scripts eject" 31 | }, 32 | "eslintConfig": { 33 | "extends": [ 34 | "react-app", 35 | "react-app/jest" 36 | ] 37 | }, 38 | "browserslist": { 39 | "production": [ 40 | ">0.2%", 41 | "not dead", 42 | "not op_mini all" 43 | ], 44 | "development": [ 45 | "last 1 chrome version", 46 | "last 1 firefox version", 47 | "last 1 safari version" 48 | ] 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chebotaevroman/jwt_example_frontend/918b8af9a2b5e177c7eb4e8c1aa3f0fefdb33c87/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chebotaevroman/jwt_example_frontend/918b8af9a2b5e177c7eb4e8c1aa3f0fefdb33c87/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chebotaevroman/jwt_example_frontend/918b8af9a2b5e177c7eb4e8c1aa3f0fefdb33c87/public/logo512.png -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from "react"; 2 | import { useSelector } from "react-redux"; 3 | import { 4 | BrowserRouter as Router, 5 | Routes, 6 | Route, 7 | Navigate, 8 | } from "react-router-dom"; 9 | import Header from "./components/Header"; 10 | import Dashboard from "./pages/Dashboard"; 11 | import Main from "./pages/Main"; 12 | import { IRootState, useAppDispatch } from "./store"; 13 | import { getProfile } from "./store/auth/actionCreators"; 14 | 15 | function App() { 16 | const isLoggedIn = useSelector( 17 | (state: IRootState) => !!state.auth.authData.accessToken 18 | ); 19 | 20 | const dispatch = useAppDispatch(); 21 | 22 | useEffect(() => { 23 | dispatch(getProfile()); 24 | }, [dispatch]); 25 | 26 | return ( 27 | 28 |
29 | 30 | } /> 31 | : } 34 | /> 35 | 36 | 37 | ); 38 | } 39 | 40 | export default App; 41 | -------------------------------------------------------------------------------- /src/api/auth/index.ts: -------------------------------------------------------------------------------- 1 | import { AxiosPromise } from "axios"; 2 | import Endpoints from "../endpoints"; 3 | import { axiosInstance } from "../instance"; 4 | import { ILoginResponse, ILoginRequest } from "./types"; 5 | 6 | export const login = (params: ILoginRequest): AxiosPromise => 7 | axiosInstance.post(Endpoints.AUTH.LOGIN, params) 8 | 9 | export const refreshToken = (): AxiosPromise => axiosInstance.get(Endpoints.AUTH.REFRESH) 10 | 11 | export const logout = (): AxiosPromise => axiosInstance.get(Endpoints.AUTH.LOGOUT) 12 | 13 | export const getProfile = (): AxiosPromise => axiosInstance.get(Endpoints.AUTH.PROFILE) -------------------------------------------------------------------------------- /src/api/auth/types.ts: -------------------------------------------------------------------------------- 1 | // login 2 | 3 | export interface ILoginRequest { 4 | login: string 5 | password: string 6 | } 7 | 8 | export interface ILoginResponse { 9 | accessToken: string 10 | } -------------------------------------------------------------------------------- /src/api/endpoints.ts: -------------------------------------------------------------------------------- 1 | const Endpoints = { 2 | AUTH: { 3 | LOGIN: '/login', 4 | REFRESH: '/refresh', 5 | LOGOUT: '/logout', 6 | PROFILE: '/profile', 7 | } 8 | } 9 | 10 | export default Endpoints 11 | -------------------------------------------------------------------------------- /src/api/index.ts: -------------------------------------------------------------------------------- 1 | import * as auth from './auth' 2 | 3 | const api = { 4 | auth 5 | } 6 | 7 | export default api 8 | -------------------------------------------------------------------------------- /src/api/instance.ts: -------------------------------------------------------------------------------- 1 | import axios, { AxiosError } from 'axios' 2 | import {store} from '../store' 3 | import { getAccessToken, logoutUser } from '../store/auth/actionCreators' 4 | 5 | import Endpoints from './endpoints' 6 | 7 | export const axiosInstance = axios.create({}) 8 | 9 | const urlsSkipAuth = [Endpoints.AUTH.LOGIN, Endpoints.AUTH.REFRESH, Endpoints.AUTH.LOGOUT] 10 | 11 | axiosInstance.interceptors.request.use(async (config) => { 12 | if (config.url && urlsSkipAuth.includes(config.url)) { 13 | return config 14 | } 15 | 16 | const accessToken = await store.dispatch(getAccessToken()) 17 | 18 | if (accessToken) { 19 | const autharization = `Bearer ${accessToken}` 20 | 21 | config.headers = { 22 | ...config.headers, 23 | authorization: autharization 24 | } 25 | } 26 | 27 | return config 28 | }) 29 | 30 | axiosInstance.interceptors.response.use( 31 | (response) => response, 32 | (error: AxiosError) => { 33 | const isLoggedIn = !!store.getState().auth.authData.accessToken 34 | 35 | if ((error.response?.status === 401) && isLoggedIn && error.request.url !== Endpoints.AUTH.LOGOUT) { 36 | store.dispatch(logoutUser()) 37 | } 38 | 39 | throw error 40 | } 41 | ) -------------------------------------------------------------------------------- /src/components/Header/Header.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { useSelector } from "react-redux"; 3 | import { Link } from "react-router-dom"; 4 | import { IRootState } from "../../store"; 5 | 6 | const Header = () => { 7 | const isLoggedIn = useSelector( 8 | (state: IRootState) => !!state.auth.authData.accessToken 9 | ); 10 | 11 | return ( 12 | 24 | ); 25 | }; 26 | 27 | export default Header; 28 | -------------------------------------------------------------------------------- /src/components/Header/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './Header' -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom/client"; 3 | import "./index.css"; 4 | import App from "./App"; 5 | import reportWebVitals from "./reportWebVitals"; 6 | import { Provider } from "react-redux"; 7 | import { store } from "./store"; 8 | 9 | const root = ReactDOM.createRoot( 10 | document.getElementById("root") as HTMLElement 11 | ); 12 | root.render( 13 | 14 | 15 | 16 | ); 17 | 18 | // If you want to start measuring performance in your app, pass a function 19 | // to log results (for example: reportWebVitals(console.log)) 20 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 21 | reportWebVitals(); 22 | -------------------------------------------------------------------------------- /src/pages/Dashboard/Dashboard.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const Dashboard = () => { 4 | return ( 5 |
6 |

Dashboard

7 |
8 | ); 9 | }; 10 | 11 | export default Dashboard; 12 | -------------------------------------------------------------------------------- /src/pages/Dashboard/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './Dashboard' -------------------------------------------------------------------------------- /src/pages/Main/Main.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { useSelector } from "react-redux"; 3 | import { IRootState, useAppDispatch } from "../../store"; 4 | import { getProfile, logoutUser } from "../../store/auth/actionCreators"; 5 | import Login from "./components/Login"; 6 | 7 | const Main = () => { 8 | const dispatch = useAppDispatch(); 9 | 10 | const profile = useSelector( 11 | (state: IRootState) => state.auth.profileData.profile 12 | ); 13 | const isLoggedIn = useSelector( 14 | (state: IRootState) => !!state.auth.authData.accessToken 15 | ); 16 | 17 | const renderProfile = () => ( 18 |
19 |
Вы успушно авторизовались, {profile}
20 | 21 | 22 |
23 | ); 24 | 25 | return ( 26 |
27 |

Main

28 | {isLoggedIn ? renderProfile() : } 29 |
30 | ); 31 | }; 32 | 33 | export default Main; 34 | -------------------------------------------------------------------------------- /src/pages/Main/components/Login/Login.tsx: -------------------------------------------------------------------------------- 1 | import React, { FormEvent, useState } from "react"; 2 | import { useAppDispatch } from "../../../../store"; 3 | import { loginUser } from "../../../../store/auth/actionCreators"; 4 | 5 | const Login = () => { 6 | const dispatch = useAppDispatch(); 7 | 8 | const [login, setLogin] = useState(""); 9 | const [password, setPassword] = useState(""); 10 | 11 | const handleSubmit = (e: FormEvent) => { 12 | e.preventDefault(); 13 | 14 | dispatch(loginUser({ login, password })); 15 | }; 16 | 17 | return ( 18 |
19 |
20 |
21 | 22 | setLogin(e.target.value)} 27 | /> 28 |
29 |
30 | 31 | setPassword(e.target.value)} 36 | /> 37 |
38 | 39 |
40 |
41 | ); 42 | }; 43 | 44 | export default Login; 45 | -------------------------------------------------------------------------------- /src/pages/Main/components/Login/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './Login' -------------------------------------------------------------------------------- /src/pages/Main/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './Main' -------------------------------------------------------------------------------- /src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /src/reportWebVitals.ts: -------------------------------------------------------------------------------- 1 | import { ReportHandler } from 'web-vitals'; 2 | 3 | const reportWebVitals = (onPerfEntry?: ReportHandler) => { 4 | if (onPerfEntry && onPerfEntry instanceof Function) { 5 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 6 | getCLS(onPerfEntry); 7 | getFID(onPerfEntry); 8 | getFCP(onPerfEntry); 9 | getLCP(onPerfEntry); 10 | getTTFB(onPerfEntry); 11 | }); 12 | } 13 | }; 14 | 15 | export default reportWebVitals; 16 | -------------------------------------------------------------------------------- /src/setupTests.ts: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /src/store/auth/actionCreators.ts: -------------------------------------------------------------------------------- 1 | import { Dispatch } from "@reduxjs/toolkit" 2 | import api from "../../api" 3 | import { ILoginRequest, ILoginResponse } from "../../api/auth/types" 4 | import { loginStart, loginSucess, loginFailure, logoutSuccess,loadProfileStart, loadProfileFailure, loadProfileSucess } from "./authReducer" 5 | import { history } from '../../utils/history' 6 | import { store } from ".." 7 | import { AxiosPromise } from "axios" 8 | import { isTokenExpired } from "../../utils/jwt" 9 | 10 | export const loginUser = 11 | (data: ILoginRequest) => 12 | async (dispatch: Dispatch): Promise => { 13 | try { 14 | dispatch(loginStart()) 15 | 16 | const res = await api.auth.login(data) 17 | 18 | dispatch(loginSucess(res.data.accessToken)) 19 | dispatch(getProfile()) 20 | 21 | } catch (e: any) { 22 | console.error(e) 23 | 24 | dispatch(loginFailure(e.message)) 25 | } 26 | } 27 | 28 | export const logoutUser = 29 | () => 30 | async (dispatch: Dispatch): Promise => { 31 | try { 32 | await api.auth.logout() 33 | 34 | dispatch(logoutSuccess()) 35 | 36 | history.push('/') 37 | } catch (e) { 38 | console.error(e) 39 | } 40 | } 41 | 42 | export const getProfile = () => 43 | async (dispatch: Dispatch): Promise => { 44 | try { 45 | dispatch(loadProfileStart()) 46 | 47 | const res = await api.auth.getProfile() 48 | 49 | dispatch(loadProfileSucess(res.data)) 50 | } catch (e: any) { 51 | console.error(e) 52 | 53 | dispatch(loadProfileFailure(e.message)) 54 | } 55 | } 56 | 57 | // переменная для хранения запроса токена (для избежания race condition) 58 | let refreshTokenRequest: AxiosPromise | null = null 59 | 60 | export const getAccessToken = 61 | () => 62 | async (dispatch: Dispatch): Promise => { 63 | try { 64 | const accessToken = store.getState().auth.authData.accessToken 65 | 66 | if (!accessToken || isTokenExpired(accessToken)) { 67 | if (refreshTokenRequest === null) { 68 | refreshTokenRequest = api.auth.refreshToken() 69 | } 70 | 71 | const res = await refreshTokenRequest 72 | refreshTokenRequest = null 73 | 74 | dispatch(loginSucess(res.data.accessToken)) 75 | 76 | return res.data.accessToken 77 | } 78 | 79 | return accessToken 80 | } catch (e) { 81 | console.error(e) 82 | 83 | return null 84 | } 85 | } -------------------------------------------------------------------------------- /src/store/auth/authReducer.ts: -------------------------------------------------------------------------------- 1 | import { createSlice, PayloadAction } from '@reduxjs/toolkit' 2 | 3 | export interface AuthState { 4 | authData: { 5 | accessToken: string | null 6 | isLoading: boolean 7 | error: string | null, 8 | } 9 | profileData: { 10 | profile: string | null, 11 | isLoading: boolean 12 | error: string | null, 13 | } 14 | } 15 | 16 | const initialState: AuthState = { 17 | authData: { 18 | accessToken: null, 19 | isLoading: false, 20 | error: null, 21 | }, 22 | profileData: { 23 | profile: null, 24 | isLoading: false, 25 | error: null, 26 | } 27 | } 28 | 29 | export const authReducer = createSlice({ 30 | name: 'auth', 31 | initialState, 32 | reducers: { 33 | loginStart: (state): AuthState => ({ 34 | ...state, 35 | authData: { 36 | ...state.authData, 37 | isLoading: true, 38 | } 39 | }), 40 | loginSucess: (state, action: PayloadAction): AuthState => ({ 41 | ...state, 42 | authData: { 43 | ...state.authData, 44 | accessToken: action.payload, 45 | isLoading: false, 46 | error: null, 47 | } 48 | }), 49 | loginFailure: (state, action: PayloadAction): AuthState => ({ 50 | ...state, 51 | authData: { 52 | ...state.authData, 53 | isLoading: false, 54 | error: action.payload, 55 | } 56 | }), 57 | loadProfileStart: (state): AuthState => ({ 58 | ...state, 59 | profileData: { 60 | ...state.profileData, 61 | isLoading: true, 62 | } 63 | }), 64 | loadProfileSucess: (state, action: PayloadAction): AuthState => ({ 65 | ...state, 66 | profileData: { 67 | ...state.profileData, 68 | profile: action.payload, 69 | isLoading: false, 70 | error: null, 71 | } 72 | }), 73 | loadProfileFailure: (state, action: PayloadAction): AuthState => ({ 74 | ...state, 75 | profileData: { 76 | ...state.profileData, 77 | isLoading: false, 78 | error: action.payload, 79 | } 80 | }), 81 | logoutSuccess: (): AuthState => initialState, 82 | }, 83 | }) 84 | 85 | export const { loadProfileStart, loadProfileSucess, loadProfileFailure, loginStart, loginSucess, loginFailure, logoutSuccess } = authReducer.actions 86 | 87 | export default authReducer.reducer -------------------------------------------------------------------------------- /src/store/index.ts: -------------------------------------------------------------------------------- 1 | import { configureStore } from '@reduxjs/toolkit' 2 | import authReducer from './auth/authReducer' 3 | import { useDispatch } from 'react-redux' 4 | 5 | import logger from 'redux-logger' 6 | 7 | export const store = configureStore({ 8 | reducer: { 9 | auth: authReducer, 10 | }, 11 | middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(...(process.env.NODE_ENV !== 'production' ? [logger] : [])), 12 | }) 13 | 14 | 15 | export type IRootState = ReturnType 16 | export type AppDispatch = typeof store.dispatch 17 | export const useAppDispatch: () => AppDispatch = useDispatch // Export a hook that can be reused to resolve types 18 | -------------------------------------------------------------------------------- /src/utils/date.ts: -------------------------------------------------------------------------------- 1 | export const getUnixTime = () => Math.round(+ new Date() / 1000) -------------------------------------------------------------------------------- /src/utils/history.ts: -------------------------------------------------------------------------------- 1 | import { createBrowserHistory } from 'history' 2 | 3 | export const history = createBrowserHistory() 4 | -------------------------------------------------------------------------------- /src/utils/jwt.ts: -------------------------------------------------------------------------------- 1 | import { getUnixTime } from "./date" 2 | 3 | export interface IAuthTokenInfo { 4 | exp: number 5 | iat: number 6 | login: string 7 | } 8 | 9 | const LIFE_TIME_TO_UPDATE_MULTIPLIER = 0.5 10 | 11 | export const isTokenExpired = (token: string | null): boolean => { 12 | if (!token) { 13 | return true 14 | } 15 | 16 | try { 17 | const tokenInfo = token.split('.')[1] 18 | const tokenInfoDecoded = window.atob(tokenInfo) 19 | const { exp, iat }: IAuthTokenInfo = JSON.parse(tokenInfoDecoded) 20 | 21 | const tokenLeftTime = exp - getUnixTime() 22 | 23 | const minLifeTimeForUpdate = (exp - iat) * LIFE_TIME_TO_UPDATE_MULTIPLIER 24 | 25 | return tokenLeftTime < minLifeTimeForUpdate 26 | } catch (e) { 27 | console.error(e) 28 | return true 29 | } 30 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "noFallthroughCasesInSwitch": true, 16 | "module": "esnext", 17 | "moduleResolution": "node", 18 | "resolveJsonModule": true, 19 | "isolatedModules": true, 20 | "noEmit": true, 21 | "jsx": "react-jsx" 22 | }, 23 | "include": [ 24 | "src" 25 | ] 26 | } 27 | --------------------------------------------------------------------------------