Skip to content

Commit

Permalink
Include token into authorization header
Browse files Browse the repository at this point in the history
  • Loading branch information
Remchi committed Oct 8, 2017
1 parent 3d89eef commit 01945a8
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/actions/auth.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { USER_LOGGED_IN, USER_LOGGED_OUT } from "../types";
import api from "../api";
import setAuthorizationHeader from "../utils/setAuthorizationHeader";

export const userLoggedIn = user => ({
type: USER_LOGGED_IN,
Expand All @@ -13,11 +14,13 @@ export const userLoggedOut = () => ({
export const login = credentials => dispatch =>
api.user.login(credentials).then(user => {
localStorage.bookwormJWT = user.token;
setAuthorizationHeader(user.token);
dispatch(userLoggedIn(user));
});

export const logout = () => dispatch => {
localStorage.removeItem("bookwormJWT");
setAuthorizationHeader();
dispatch(userLoggedOut());
};

Expand Down
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import App from "./App";
import registerServiceWorker from "./registerServiceWorker";
import rootReducer from "./rootReducer";
import { userLoggedIn } from "./actions/auth";
import setAuthorizationHeader from "./utils/setAuthorizationHeader";

const store = createStore(
rootReducer,
Expand All @@ -24,6 +25,7 @@ if (localStorage.bookwormJWT) {
email: payload.email,
confirmed: payload.confirmed
};
setAuthorizationHeader(localStorage.bookwormJWT);
store.dispatch(userLoggedIn(user));
}

Expand Down
9 changes: 9 additions & 0 deletions src/utils/setAuthorizationHeader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import axios from "axios";

export default (token = null) => {
if (token) {
axios.defaults.headers.common.authorization = `Bearer ${token}`;
} else {
delete axios.defaults.headers.common.authorization;
}
};

0 comments on commit 01945a8

Please sign in to comment.