Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 176 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,182 @@ Topics:
* Promises
* Authentication tokens

![preview](project-preview.gif)

## Notes
* 🎥[GP](https://youtu.be/FHXLYqkItTw)
* 🎥[MP](https://www.loom.com/share/c669f5e7831741aaac192d50830735c0)

### Key Concepts
* [Authentication](https://www.youtube.com/watch?v=woNZJMSNbuo) - The process for identifying user identity.
* [Authorization](https://www.youtube.com/watch?v=I0poT4UxFxE) - The process for identifying user permissions.
* [http headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) - Additional data added to http requests for interperation within your backend code

### Key Terminology
* [...rest](https://medium.com/wesionary-team/spread-and-rest-operator-in-javascript-db3f15cec185) - A means to capture the remaining values within a javascript array or object easily.
* [Redirect Route](https://medium.com/@alexfarmer/redirects-in-react-router-dom-46198938eedc) - A redirect method used through react-router.
* [this.history redirect](https://www.codesd.com/item/react-this-props-history-push-does-not-redirect.html) - A redirect method used through Route props.
* [window.location redirect](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) - A redirect method used through the windows location object.
* [Route](https://reactrouter.com/web/api/Route) - A react router component that allows programmers to connect a component to a url path
* [axios.create](https://masteringjs.io/tutorials/axios/create) - A means to create a stub of an axios call with preset values attached
* [jwt tokens](https://dzone.com/articles/what-is-jwt-token) - The current web standard for encrypted authentication tokens

### Example flow
* LOGIN ⚙ user/pass sent login request ➡ server search db for user/pass ➡ if found, generate/store/return token ➡ receive/store token
* REQUEST ⚙ user sends request body/token ➡ server searches for active token ➡ if found, process/return request ➡ client receives/processes req
* LOGOUT ⚙ user del local token, sends token to server ➡ server deletes token

### handle authentication with tokens in a React app
Modern web services dealing with JSON data often use Jason Web Tokens (JWT)s - strings stored on client-side using local or session storage

* Server tells client it issued token, reads token, makes decisions for data transfer w client's permission
* Example: login endpoint, takes payload `username` and `password`. If the credentials are known, the server responds with a fresh JWT. From then on, it's the application's responsibility to add an `Authorization: <token>` header to every request, to be allowed access to protected resources that require authentication.

```js
import axios from 'axios';

export const axiosWithAuth =() => {
const token = localStorage.getItem('token');

return axios.create({
headers: {
Authorization: token,
},
});
};
```



* Whenever the application needs to exchange data with a protected endpoint, it imports this module, instead of `import axios from "axios";`
* Alternative: `Authorization: Bearer ${token},`
* Save token to local storage so `axiosWithAuth` can grab it for other calls that require Auth header

```js
const login = () => {
axios.post('endpoint/here', userCredentials)
.then(res => {
localStorage.setItem('token', res.data.token);
props.history.push('/dashboard');
}
}
```

AJAX request to endpoint using `axiosWithAuth`:

```js
import { axiosWithAuth } from '../../path/to/axiosAuth.js';
// etc
axiosWithAuth()
.get('endpoint/path/here')
.then(data => /* do something with the data */);
```

### implement protected routes using an authentication token and Redirect
"Protected" routes - routes that should only render with authentication.

```js
function App() {
return (
<div>
<ul>
<li>
<Link to="/public">Public Page</Link>
</li>
<li>
<Link to="/protected">Protected Page</Link>
</li>
</ul>
<Route path="/public" component={Public} />
<Route path="/login" component={Login} />
</div>
);
}
```

Anyone can click on the "Public Page" link, but if they click on the "Protected Page" link without authorization, they will be routed to the login page instead. Add a route:

```js
<Route path="/public" component={Public}/>
<Route path="/login" component={Login}/>
<PrivateRoute path='/protected' component={Protected} />
```

Build it out:

```js
// Requirement 1.
// It has the same API as `<Route />`
const PrivateRoute = ({ component: Component, ...rest }) => (
// Requirement 2.
// It renders a `<Route />` and passes all the props through to it.
<Route
{...rest}
render={
// Requirement 3.
// It checks if the user is authenticated
props =>
localStorage.getItem("token") ? (
// If they are, it renders the "component" prop.
<Component {...props} />
) : (
// If not, it redirects the user to /login.
<Redirect to="/login" />
)
}
/>
);
```

A login page takes in a user's credentials, calls login endpoint with POST req, then redirects user to protected route when login API call returns.

```js
import React, { useState } from 'react';
import { axiosWithAuth } from '../path/to/module';

const Login = (props) => {
const [credentials, setCredentials] = useState({});

const login = e => {
e.preventDefault();
axiosWithAuth().post('login/endpoint', credentials)
.then(res => {
localStorage.setItem('token', res.data.token);
this.props.history.push('/');
})
}

const handleChange = e => {
setCredentials: {
...credentials,
[e.target.name]: e.target.value,
}
}

return (
<div>
<form onSubmit={this.login}>
<input
type="text"
name="username"
value={credentials.username}
onChange={this.handleChange}
/>
<input
type="password"
name="password"
value={credentials.password}
onChange={this.handleChange}
/>
<button>Log in</button>
</form>
</div>
)
}

export default Login;
```

## Instructions

### Task 1: Set Up
Expand Down
23 changes: 23 additions & 0 deletions friends/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
70 changes: 70 additions & 0 deletions friends/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Getting Started with Create React App

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Available Scripts

In the project directory, you can run:

### `npm start`

Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

The page will reload if you make edits.\
You will also see any lint errors in the console.

### `npm test`

Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `npm run build`

Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).

### Code Splitting

This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)

### Analyzing the Bundle Size

This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)

### Making a Progressive Web App

This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)

### Advanced Configuration

This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)

### Deployment

This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)

### `npm run build` fails to minify

This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
Loading