auth/meAt this point, we have the ability to create an account, log a user in, and get a valid JSON web token. So now we need to check with our server that the token is valid to determine whether or not the user has access to certain views and data.
userAuth actionThe way we do this is by sending a request to the auth/me route we set up in our Phoenix server. If you recall, the auth/me route takes the token from the Authorization header and checks to make sure it's valid. If it is, it returns the data we requested (in this case, username and email).
This should look familiar, with the exception of the Authorization header line. The standard syntax for sending an Authorization header is in the syntax: Bearer <token>, as you can see if you search for the word bearer in this handy introduction to jwt. If there is no token, it passes an empty string.
Actions.userAuth = function userAuth() { return dispatch => fetch("http://localhost:4000/auth/me", { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: `Bearer ${localStorage.token}` || "", }, }) .then(res => { return res.json() }) .then(res => { dispatch({ type: "USER_AUTH", payload: { user: res.data, }, }) }) .catch(err => { console.warn(err) })}Then we have to add our USER_AUTH action as a case to our user reducer.
... case "USER_AUTH": return Object.assign({}, state, { email: action.payload.user.email, username: action.payload.user.username, id: action.payload.user.id }) ...There are a few times in which we would like to automatically check to see if a user is logged in. The first is when the app initially renders, as the user might have come from another session and still has a valid token. The other times we want to automatically log a user in are when we have a change in user status, such as after we run userNew or userLogin.
Since we want to do this for the whole app, we should run this when the App component renders. So the first thing we should do is refactor our App component into it's own directory so we can access its componentDidMount function and un-muddle our app/index.js file.
$ mkdir app/components/App$ touch app/components/App/{index.js,spec.js,style.css,README.md}Then create our component and dispatch our userAuth action within componentDidMount.
import React from "react"import { connect } from "react-redux"import Actions from "../../redux/actions"export class App extends React.Component { componentDidMount() { this.props.dispatch(Actions.userAuth()) } render() { return <div>{this.props.children}</div> }}export default connect()(App)And lets add that functionality to both of our actions as well, since we want to authenticate the user immediately after login and account creation. Remember, when we create an account or login, all we're doing is adding a web token to localStorage. We have to use auth/me to actually validate that user.
...Actions.userNew = function userNew(user) { ... .then((res) => { /* If success, log the user in */ localStorage.token = res.data.token /* Then send action to reducer */ dispatch({ type: "USER_NEW", payload: { user: res.data } }) dispatch(Actions.userAuth()) }) ...}Actions.userLogin = function userLogin(user) { ... .then((res) => { /* If success, log the user in */ localStorage.token = res.data.token /* Then send action to reducer */ dispatch({ type: "USER_LOGIN", payload: { user: res.data } }) dispatch(Actions.userAuth()) }) ...}While we're at it, let's write a few tests for this component. We want to make sure that the component:
componentDidMountActions.userAuth() on componentDidMountWe will need to import our Actions in order to run these tests and make ample use of our spy. More details about each test below the codeblock.
import React from "react"import expect from "expect"import { shallow, mount } from "enzyme"import Actions from "../../redux/actions"import { App } from "./"const props = {}describe("<App />", () => { it("should render", () => { const renderedComponent = shallow(<App {...props} />) expect(renderedComponent.is("div")).toEqual(true) }) it("calls dispatch on componentDidMount", () => { const spy = expect.createSpy() const renderedComponent = mount(<App dispatch={spy} />) expect(spy).toHaveBeenCalled() }) it("calls dispatch with Actions.userAuth", () => { const spy = expect.createSpy() const renderedComponent = mount(<App dispatch={spy} />) expect(spy).toHaveBeenCalledWith(Actions.userAuth()) })})The first test is simple and it's something you've seen before.
The second test is a little bit more complicated. The first difference is that we're rendering the component with mount rather than shallow. This takes longer, but it's necessary since a shallow render does not give you access to the lifecycle methods such as componentDidMount. Then we're passing in our spy as this.props.dispatch, so when componentDidMount is triggered, it calls our spy rather than what would have ordinarily been passed in as the dispatch function from redux.
The third test is similar to the second test, but we are making a different assertion. In this case, we are checking to make sure that componentDidMount attempted to call our dispatch function with the right parameter. If it called it with Actions.userAuth(), then the test will pass.
In theory, we could also test that componentDidMount was called, but at that point we'd be testing that React itself is working, and that's outside the scope of our unit tests. It's safe to assume that anything implicit in React will work properly.
So now we need to change our app/index.js file to take in the new App component. All we have to do is import our new App component and delete the old one.
...import { default as App } from "./components/App"...And that's that. Your user is now being authenticated automatically when the page renders. You can check this by using console.log on your props to a connected component, such as the Login component (for now).
So now that we can determine whether a user is logged in, we can give that user access to pages that only logged in users would have.
In this case, if a user is logged in, we want them to see the Chat component rather than the login/signup screen when they get to the Home page.
The first step is to connect our Home component to redux so it knows whether or not the user is signed in.
...import { connect } from "react-redux"...const mapStateToProps = state => ({ user: state.user})export default connect(mapStateToProps)(cssModules(Home, style))Then import our Chat component and have it render if the user is currently logged in.
import { default as Chat } from "../Chat"... render() { if (this.props.user.email) { return (<Chat />) } return ( <div className={style.leader}> ... ) } ...And since we're already logged in, when you refresh the page, you should see our Chat component instead of the login screen.
At this point, we effectively have the outline of what will become our interface for a company representative. This is the primary means by which an administrator can communicate with an anonymous customer visiting the site.
You might be thinking, "But is it really safe to determine the authentication status based on props.user?" If you were, kudos.
Security does not happen on the client. The best you can do on the client is give the appearance of security by disabling links and guiding the user to the proper view. Someone can always jump into the console and do whatever they want on the client since our entire app is available in our bundle.js file.
That said, an app with this architecture is still secure because our data is secure and comes from our server. Sure, someone can spend a lot of time figuring out how to get access to the Chat component even though they're not supposed to have access, but what can they do with it? They can only get the data to populate that component if they have a valid token and pass that to the server, which only then will respond with the data.
So keep in mind that whatever you put in a view, you cannot hide from your users. Take this tutorial series, for example. You could, in theory, change the links on the course list into something valid and potentially be able to click on it. But since the data does not live on the client, but in markdown files on the server, the page will be empty when you get there and you have no way to get access to the data without a valid token, which you can only get if you are authorized by the server.
In short, that's a long-winded way of saying that security is on the server not the client.
Previous: Move Logic to ReduxNext: NPM Package for a React Component: Part 1