{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/check-login-status","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Check Login Status\",\n  \"order\": 22,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"react\", \"redux\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Check Login Status\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, mdx(\"inlineCode\", {\n    \"parentName\": \"li\"\n  }, \"auth/me\")), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Grant special access\")), mdx(\"p\", null, \"At 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.\"), mdx(\"h2\", null, \"Setting up \", mdx(\"inlineCode\", {\n    \"parentName\": \"h2\"\n  }, \"userAuth\"), \" action\"), mdx(\"p\", null, \"The way we do this is by sending a request to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"auth/me\"), \" route we set up in our Phoenix server. If you recall, the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"auth/me\"), \" route takes the token from the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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).\"), mdx(\"p\", null, \"This should look familiar, with the exception of the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Authorization\"), \" header line. The standard syntax for sending an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Authorization\"), \" header is in the syntax: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Bearer <token>\"), \", as you can see if you search for the word \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"bearer\"), \" in \", mdx(\"a\", {\n    \"href\": \"https://jwt.io/introduction/\",\n    \"parentName\": \"p\"\n  }, \"this handy introduction to jwt\"), \". If there is no token, it passes an empty string.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"Actions.userAuth = function userAuth() {\\n  return dispatch =>\\n    fetch(\\\"http://localhost:4000/auth/me\\\", {\\n      method: \\\"GET\\\",\\n      headers: {\\n        Accept: \\\"application/json\\\",\\n        \\\"Content-Type\\\": \\\"application/json\\\",\\n        Authorization: `Bearer ${localStorage.token}` || \\\"\\\",\\n      },\\n    })\\n      .then(res => {\\n        return res.json()\\n      })\\n      .then(res => {\\n        dispatch({\\n          type: \\\"USER_AUTH\\\",\\n          payload: {\\n            user: res.data,\\n          },\\n        })\\n      })\\n      .catch(err => {\\n        console.warn(err)\\n      })\\n}\\n\")), mdx(\"p\", null, \"Then we have to add our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"USER_AUTH\"), \" action as a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"case\"), \" to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" reducer.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n    case \\\"USER_AUTH\\\":\\n      return Object.assign({}, state, {\\n        email: action.payload.user.email,\\n        username: action.payload.user.username,\\n        id: action.payload.user.id\\n      })\\n  ...\\n\")), mdx(\"h2\", null, \"Automatic authentication\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userNew\"), \" or \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userLogin\"), \".\"), mdx(\"p\", null, \"Since we want to do this for the whole app, we should run this when the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"componentDidMount\"), \" function and un-muddle our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"app/index.js\"), \" file.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mkdir app/components/App\\n$ touch app/components/App/{index.js,spec.js,style.css,README.md}\\n\")), mdx(\"p\", null, \"Then create our component and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"dispatch\"), \" our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userAuth\"), \" action within \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"componentDidMount\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import React from \\\"react\\\"\\nimport { connect } from \\\"react-redux\\\"\\nimport Actions from \\\"../../redux/actions\\\"\\n\\nexport class App extends React.Component {\\n  componentDidMount() {\\n    this.props.dispatch(Actions.userAuth())\\n  }\\n\\n  render() {\\n    return <div>{this.props.children}</div>\\n  }\\n}\\n\\nexport default connect()(App)\\n\")), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localStorage\"), \". We have to use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"auth/me\"), \" to actually validate that user.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\nActions.userNew = function userNew(user) {\\n  ...\\n  .then((res) => {\\n    /* If success, log the user in */\\n    localStorage.token = res.data.token\\n    /* Then send action to reducer */\\n    dispatch({\\n      type: \\\"USER_NEW\\\",\\n      payload: {\\n        user: res.data\\n      }\\n    })\\n    dispatch(Actions.userAuth())\\n  })\\n  ...\\n}\\n\\nActions.userLogin = function userLogin(user) {\\n  ...\\n  .then((res) => {\\n    /* If success, log the user in */\\n    localStorage.token = res.data.token\\n    /* Then send action to reducer */\\n    dispatch({\\n      type: \\\"USER_LOGIN\\\",\\n      payload: {\\n        user: res.data\\n      }\\n    })\\n    dispatch(Actions.userAuth())\\n  })\\n  ...\\n}\\n\")), mdx(\"p\", null, \"While we're at it, let's write a few tests for this component. We want to make sure that the component:\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"renders\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"dispatches on \", mdx(\"inlineCode\", {\n    \"parentName\": \"li\"\n  }, \"componentDidMount\")), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"dispatches \", mdx(\"inlineCode\", {\n    \"parentName\": \"li\"\n  }, \"Actions.userAuth()\"), \" on \", mdx(\"inlineCode\", {\n    \"parentName\": \"li\"\n  }, \"componentDidMount\"))), mdx(\"p\", null, \"We will need to import our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Actions\"), \" in order to run these tests and make ample use of our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"spy\"), \". More details about each test below the codeblock.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import React from \\\"react\\\"\\nimport expect from \\\"expect\\\"\\nimport { shallow, mount } from \\\"enzyme\\\"\\n\\nimport Actions from \\\"../../redux/actions\\\"\\n\\nimport { App } from \\\"./\\\"\\n\\nconst props = {}\\n\\ndescribe(\\\"<App />\\\", () => {\\n  it(\\\"should render\\\", () => {\\n    const renderedComponent = shallow(<App {...props} />)\\n    expect(renderedComponent.is(\\\"div\\\")).toEqual(true)\\n  })\\n  it(\\\"calls dispatch on componentDidMount\\\", () => {\\n    const spy = expect.createSpy()\\n    const renderedComponent = mount(<App dispatch={spy} />)\\n    expect(spy).toHaveBeenCalled()\\n  })\\n  it(\\\"calls dispatch with Actions.userAuth\\\", () => {\\n    const spy = expect.createSpy()\\n    const renderedComponent = mount(<App dispatch={spy} />)\\n    expect(spy).toHaveBeenCalledWith(Actions.userAuth())\\n  })\\n})\\n\")), mdx(\"p\", null, \"The first test is simple and it's something you've seen before.\"), mdx(\"p\", null, \"The second test is a little bit more complicated. The first difference is that we're rendering the component with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mount\"), \" rather than \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"shallow\"), \". This takes longer, but it's necessary since a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"shallow\"), \" render does not give you access to the \", mdx(\"a\", {\n    \"href\": \"https://facebook.github.io/react/docs/component-specs.html\",\n    \"parentName\": \"p\"\n  }, \"lifecycle methods\"), \" such as \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"componentDidMount\"), \". Then we're passing in our spy as \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.props.dispatch\"), \", so when \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"componentDidMount\"), \" is triggered, it calls our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"spy\"), \" rather than what would have ordinarily been passed in as the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"dispatch\"), \" function from redux.\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"componentDidMount\"), \" attempted to call our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"dispatch\"), \" function with the right parameter. If it called it with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Actions.userAuth()\"), \", then the test will pass.\"), mdx(\"p\", null, \"In theory, we could also test that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"So now we need to change our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"app/index.js\"), \" file to take in the new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"App\"), \" component. All we have to do is import our new App component and delete the old one.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\nimport { default as App } from \\\"./components/App\\\"\\n...\\n\")), mdx(\"p\", null, \"And that's that. Your user is now being authenticated automatically when the page renders. You can check this by using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"console.log\"), \" on your props to a connected component, such as the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Login\"), \" component (for now).\"), mdx(\"h2\", null, \"Authenticated pages\"), mdx(\"p\", null, \"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.\"), mdx(\"p\", null, \"In this case, if a user is logged in, we want them to see the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Chat\"), \" component rather than the login/signup screen when they get to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Home\"), \" page.\"), mdx(\"p\", null, \"The first step is to connect our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Home\"), \" component to redux so it knows whether or not the user is signed in.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\nimport { connect } from \\\"react-redux\\\"\\n\\n...\\n\\nconst mapStateToProps = state => ({\\n  user: state.user\\n})\\n\\nexport default connect(mapStateToProps)(cssModules(Home, style))\\n\\n\")), mdx(\"p\", null, \"Then import our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Chat\"), \" component and have it render if the user is currently logged in.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import { default as Chat } from \\\"../Chat\\\"\\n\\n...\\n\\n  render() {\\n    if (this.props.user.email) {\\n      return (<Chat />)\\n    }\\n    return (\\n      <div className={style.leader}>\\n        ...\\n    )\\n  }\\n  ...\\n\")), mdx(\"p\", null, \"And since we're already logged in, when you refresh the page, you should see our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Chat\"), \" component instead of the login screen.\"), mdx(\"p\", null, \"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.\"), mdx(\"h2\", null, \"A Note on Frontend Security\"), mdx(\"p\", null, \"You might be thinking, \\\"But is it really safe to determine the authentication status based on \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"props.user\"), \"?\\\" If you were, kudos.\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"bundle.js\"), \" file.\"), mdx(\"p\", null, \"That said, an app with this architecture is still secure because our \", mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"data\"), \" is secure and comes from our server. Sure, someone can spend a lot of time figuring out how to get access to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"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.\"), mdx(\"p\", null, \"In short, that's a long-winded way of saying that security is on the server not the client.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Check Login Status auth/me Grant special access At this point, we have the ability to create an account, log a user in, and get a valid JSON…","frontmatter":{"title":"Check Login Status","order":22,"active":true,"free":false,"tech":["react","redux"]}}},"pageContext":{"slug":"check-login-status","prevNode":{"frontmatter":{"title":"Move Logic to Redux","active":true,"free":false,"order":21,"tech":["react","redux"]},"fields":{"slug":"move-logic-to-redux"}},"nextNode":{"frontmatter":{"title":"NPM Package for a React Component: Part 1","active":true,"free":false,"order":23,"tech":["react","npm"]},"fields":{"slug":"npm-package-for-a-react-component-part-1"}}}},"staticQueryHashes":["1723017916"]}