Skip to content
This repository has been archived by the owner on Jan 20, 2024. It is now read-only.

Commit

Permalink
Fix #20
Browse files Browse the repository at this point in the history
* Logout on invalid token stored in cache
  • Loading branch information
tdemin committed Jan 5, 2020
1 parent d3e1c7c commit 4e62f21
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
9 changes: 9 additions & 0 deletions src/actions/auth.ts
Expand Up @@ -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.
Expand Down
21 changes: 18 additions & 3 deletions src/main.tsx
Expand Up @@ -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";

Expand All @@ -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<typeof mapDispatchToProps> {
token?: string;
username?: string;
}
Expand Down Expand Up @@ -47,6 +55,13 @@ class App extends React.Component<Props, Props> {
});
}
};
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;
Expand All @@ -69,4 +84,4 @@ class App extends React.Component<Props, Props> {
};
}

export default connect(mapStateToProps)(App);
export default connect(mapStateToProps, mapDispatchToProps)(App);
2 changes: 2 additions & 0 deletions src/typings/api.ts
Expand Up @@ -12,3 +12,5 @@ export type VersionData = {
version: string;
signup: boolean;
};

export const HTTPSuccessCode = 200;

0 comments on commit 4e62f21

Please sign in to comment.