diff --git a/src/actions/auth.ts b/src/actions/auth.ts index ffc69aa..d41b8eb 100644 --- a/src/actions/auth.ts +++ b/src/actions/auth.ts @@ -46,6 +46,15 @@ export const logout = () => (dispatch: Dispatch) => { }); }; +/** Redux action creator. Performs a logout locally without making an API call. + * */ +export const localLogout = () => { + resetToken(); + return { + type: Actions.LoggedOut, + } as AuthAction; +}; + /** * Signup function. Performs an HTTP POST request, calls the provided functions * on success/fail. diff --git a/src/main.tsx b/src/main.tsx index ce90846..59267eb 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -2,14 +2,18 @@ import React from "react"; import { connect } from "react-redux"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; +import req from "./axios"; + import { Store } from "./typings/store"; +import { Dispatch } from "./typings/react"; +import { HTTPSuccessCode } from "./typings/api"; import LoginForm from "./views/loginForm"; import SignupForm from "./views/signupForm"; import MainView from "./views/mainView"; import EditorView from "./views/editorView"; -import { setToken, resetToken } from "./actions/auth"; +import { setToken, resetToken, localLogout } from "./actions/auth"; import "./views/styles/common.scss"; @@ -18,7 +22,11 @@ const mapStateToProps = (state: Store) => ({ username: state.auth.username, }); -interface Props { +const mapDispatchToProps = (dispatch: Dispatch) => ({ + logout: () => dispatch(localLogout()), +}); + +interface Props extends ReturnType { token?: string; username?: string; } @@ -47,6 +55,13 @@ class App extends React.Component { }); } }; + componentDidMount = () => { + req.head("/session").then((res) => { + if (res.status !== HTTPSuccessCode) { + this.props.logout(); + } + }); + }; render = () => { const token = this.state.token as string; const loggedIn = token.length !== 0; @@ -69,4 +84,4 @@ class App extends React.Component { }; } -export default connect(mapStateToProps)(App); +export default connect(mapStateToProps, mapDispatchToProps)(App); diff --git a/src/typings/api.ts b/src/typings/api.ts index 37960b5..f4e22ee 100644 --- a/src/typings/api.ts +++ b/src/typings/api.ts @@ -12,3 +12,5 @@ export type VersionData = { version: string; signup: boolean; }; + +export const HTTPSuccessCode = 200;