├── .gitignore
├── README.md
├── package-lock.json
├── package.json
├── public
├── energy.jpg
├── hexal-logo-sm.png
├── hexal-logo.png
├── hexal.ico
├── index.html
└── manifest.json
├── src
├── App.css
├── App.js
├── App.test.js
├── components
│ ├── Footer.js
│ ├── FormErrors.js
│ ├── Hero.js
│ ├── Home.js
│ ├── HomeContent.js
│ ├── Navbar.js
│ ├── Product.js
│ ├── ProductAdmin.js
│ ├── Products.js
│ ├── auth
│ │ ├── ChangePassword.js
│ │ ├── ChangePasswordConfirm.js
│ │ ├── ForgotPassword.js
│ │ ├── ForgotPasswordVerification.js
│ │ ├── LogIn.js
│ │ ├── Register.js
│ │ └── Welcome.js
│ └── utility
│ │ └── FormValidation.js
├── config.json
├── index.css
├── index.js
├── logo.svg
└── serviceWorker.js
└── yarn.lock
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Hexal Energy app
2 |
3 | This is a starter ReactJS UI for my 'Create a Serverless App' tutorial series.
4 |
5 | ## Application Info
6 |
7 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
8 |
9 | ## Available Scripts
10 |
11 | In the project directory, you can run:
12 |
13 | ### `npm start`
14 |
15 | Runs the app in the development mode.
16 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
17 |
18 | The page will reload if you make edits.
19 | You will also see any lint errors in the console.
20 |
21 | ### `npm test`
22 |
23 | Launches the test runner in the interactive watch mode.
24 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
25 |
26 | ### `npm run build`
27 |
28 | Builds the app for production to the `build` folder.
29 | It correctly bundles React in production mode and optimizes the build for the best performance.
30 |
31 | The build is minified and the filenames include the hashes.
32 | Your app is ready to be deployed!
33 |
34 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
35 |
36 | ### `npm run eject`
37 |
38 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
39 |
40 | 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.
41 |
42 | 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.
43 |
44 | 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.
45 |
46 | ## Learn More
47 |
48 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
49 |
50 | To learn React, check out the [React documentation](https://reactjs.org/).
51 |
52 | ### Code Splitting
53 |
54 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
55 |
56 | ### Analyzing the Bundle Size
57 |
58 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
59 |
60 | ### Making a Progressive Web App
61 |
62 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
63 |
64 | ### Advanced Configuration
65 |
66 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
67 |
68 | ### Deployment
69 |
70 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
71 |
72 | ### `npm run build` fails to minify
73 |
74 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
75 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "hexal-serverless-starter",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@fortawesome/fontawesome-svg-core": "^1.2.15",
7 | "@fortawesome/free-solid-svg-icons": "^5.7.2",
8 | "@fortawesome/react-fontawesome": "^0.1.4",
9 | "aws-amplify": "^1.1.22",
10 | "axios": "^0.18.0",
11 | "bulma": "^0.7.2",
12 | "react": "^16.7.0",
13 | "react-dom": "^16.7.0",
14 | "react-router-dom": "^4.3.1",
15 | "react-scripts": "^2.1.3"
16 | },
17 | "scripts": {
18 | "start": "react-scripts start",
19 | "build": "react-scripts build",
20 | "test": "react-scripts test",
21 | "eject": "react-scripts eject"
22 | },
23 | "eslintConfig": {
24 | "extends": "react-app"
25 | },
26 | "browserslist": [
27 | ">0.2%",
28 | "not dead",
29 | "not ie <= 11",
30 | "not op_mini all"
31 | ]
32 | }
33 |
--------------------------------------------------------------------------------
/public/energy.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jspruance/aws-cognito-tutorial-complete/2eedd15239c299dfc0cea92017f261869b188878/public/energy.jpg
--------------------------------------------------------------------------------
/public/hexal-logo-sm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jspruance/aws-cognito-tutorial-complete/2eedd15239c299dfc0cea92017f261869b188878/public/hexal-logo-sm.png
--------------------------------------------------------------------------------
/public/hexal-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jspruance/aws-cognito-tutorial-complete/2eedd15239c299dfc0cea92017f261869b188878/public/hexal-logo.png
--------------------------------------------------------------------------------
/public/hexal.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jspruance/aws-cognito-tutorial-complete/2eedd15239c299dfc0cea92017f261869b188878/public/hexal.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
9 |
10 |
11 |
12 | Hexal Energy
13 |
14 |
15 | You need to enable JavaScript to run this app.
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "hexal.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | }
10 | ],
11 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | h1 {
2 | font-size: 2em;
3 | }
4 |
5 | .product-title {
6 | font-weight: bold;
7 | font-size: 1.2em;
8 | }
9 |
10 | .product-id {
11 | font-size: .8em;
12 | margin: 1em 0;
13 | }
14 |
15 | .product-edit-icon {
16 | opacity: .7;
17 | position: absolute;
18 | right: 2.3rem;
19 | top: .4rem;
20 | }
21 |
22 | .product-edit-icon:hover {
23 | opacity: 1;
24 | }
25 |
26 | .navbar, .navbar-end, .navbar-menu, .navbar-start {
27 | align-items: stretch !important;
28 | display: flex !important;
29 | }
30 |
31 | .navbar-menu {
32 | flex-grow: 1 !important;
33 | flex-shrink: 0 !important;
34 | box-shadow: none !important;
35 | padding: 0 !important;
36 | }
37 |
38 | .navbar-item {
39 | display: flex !important;
40 | }
41 |
42 | .navbar-end {
43 | justify-content: flex-end !important;
44 | margin-left: auto !important;
45 | }
46 |
47 | .features {
48 | padding-bottom: 3em;
49 | }
50 |
51 | body {
52 | visibility: visible !important;
53 | }
54 |
55 |
56 | .auth form {
57 | margin-top: 1em;
58 | max-width: 50%;
59 | }
60 |
61 | .buttons {
62 | margin-left: 1em;
63 | }
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
3 | import './App.css';
4 | import Navbar from './components/Navbar';
5 | import Home from './components/Home';
6 | import Products from './components/Products';
7 | import ProductAdmin from './components/ProductAdmin';
8 | import LogIn from './components/auth/LogIn';
9 | import Register from './components/auth/Register';
10 | import ForgotPassword from './components/auth/ForgotPassword';
11 | import ForgotPasswordVerification from './components/auth/ForgotPasswordVerification';
12 | import ChangePassword from './components/auth/ChangePassword';
13 | import ChangePasswordConfirm from './components/auth/ChangePasswordConfirm';
14 | import Welcome from './components/auth/Welcome';
15 | import Footer from './components/Footer';
16 | import { Auth } from 'aws-amplify';
17 | import { library } from '@fortawesome/fontawesome-svg-core';
18 | import { faEdit } from '@fortawesome/free-solid-svg-icons';
19 | library.add(faEdit);
20 |
21 | class App extends Component {
22 |
23 | state = {
24 | isAuthenticated: false,
25 | isAuthenticating: true,
26 | user: null
27 | }
28 |
29 | setAuthStatus = authenticated => {
30 | this.setState({ isAuthenticated: authenticated });
31 | }
32 |
33 | setUser = user => {
34 | this.setState({ user: user });
35 | }
36 |
37 | async componentDidMount() {
38 | try {
39 | const session = await Auth.currentSession();
40 | this.setAuthStatus(true);
41 | console.log(session);
42 | const user = await Auth.currentAuthenticatedUser();
43 | this.setUser(user);
44 | } catch(error) {
45 | if (error !== 'No current user') {
46 | console.log(error);
47 | }
48 | }
49 |
50 | this.setState({ isAuthenticating: false });
51 | }
52 |
53 | render() {
54 | const authProps = {
55 | isAuthenticated: this.state.isAuthenticated,
56 | user: this.state.user,
57 | setAuthStatus: this.setAuthStatus,
58 | setUser: this.setUser
59 | }
60 | return (
61 | !this.state.isAuthenticating &&
62 |
63 |
64 |
65 |
66 |
67 | } />
68 | } />
69 | } />
70 | } />
71 | } />
72 | } />
73 | } />
74 | } />
75 | } />
76 | } />
77 |
78 |
79 |
80 |
81 |
82 | );
83 | }
84 | }
85 |
86 | export default App;
87 |
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 |
5 | it('renders without crashing', () => {
6 | const div = document.createElement('div');
7 | ReactDOM.render( , div);
8 | ReactDOM.unmountComponentAtNode(div);
9 | });
10 |
--------------------------------------------------------------------------------
/src/components/Footer.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | export default function Footer() {
4 | return (
5 |
12 | )
13 | }
14 |
--------------------------------------------------------------------------------
/src/components/FormErrors.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 |
3 | function FormErrors(props) {
4 | if (
5 | props.formerrors &&
6 | (props.formerrors.blankfield || props.formerrors.passwordmatch)
7 | ) {
8 | return (
9 |
10 |
11 | {props.formerrors.passwordmatch
12 | ? "Password value does not match confirm password value"
13 | : ""}
14 |
15 |
16 | {props.formerrors.blankfield ? "All fields are required" : ""}
17 |
18 |
19 | );
20 | } else if (props.apierrors) {
21 | return (
22 |
23 |
{props.apierrors}
24 |
25 | );
26 | } else if (props.formerrors && props.formerrors.cognito) {
27 | return (
28 |
29 |
30 | {props.formerrors.cognito.message}
31 |
32 |
33 | );
34 | } else {
35 | return
;
36 | }
37 | }
38 |
39 | export default FormErrors;
--------------------------------------------------------------------------------
/src/components/Hero.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | export default function Hero() {
4 | return (
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | )
13 | }
14 |
--------------------------------------------------------------------------------
/src/components/Home.js:
--------------------------------------------------------------------------------
1 | import React, { Fragment } from 'react';
2 | import Hero from './Hero';
3 | import HomeContent from './HomeContent';
4 |
5 | export default function Home() {
6 | return (
7 |
8 |
9 |
10 |
11 | New Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
12 |
13 |
14 |
15 |
16 | )
17 | }
18 |
--------------------------------------------------------------------------------
/src/components/HomeContent.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | export default function HomeContent() {
4 | return (
5 |
6 |
7 |
8 |
9 |
10 |
11 |
Energy conservation
12 |
Purus semper eget duis at tellus at urna condimentum mattis. Non blandit massa enim nec. Integer enim neque volutpat ac tincidunt vitae semper quis. Accumsan tortor posuere ac ut consequat semper viverra nam.
13 |
Learn more
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
Water conservation
23 |
Ut venenatis tellus in metus vulputate. Amet consectetur adipiscing elit pellentesque. Sed arcu non odio euismod lacinia at quis risus. Faucibus turpis in eu mi bibendum neque egestas cmonsu songue. Phasellus vestibulum lorem
24 | sed risus.
25 |
Learn more
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
Solar energy
35 |
Imperdiet dui accumsan sit amet nulla facilisi morbi. Fusce ut placerat orci nulla pellentesque dignissim enim. Libero id faucibus nisl tincidunt eget nullam. Commodo viverra maecenas accumsan lacus vel facilisis.
36 |
Learn more
37 |
38 |
39 |
40 |
41 |
42 |
43 | )
44 | }
45 |
--------------------------------------------------------------------------------
/src/components/Navbar.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { Auth } from 'aws-amplify';
3 |
4 | export default class Navbar extends Component {
5 | handleLogOut = async event => {
6 | event.preventDefault();
7 | try {
8 | Auth.signOut();
9 | this.props.auth.setAuthStatus(false);
10 | this.props.auth.setUser(null);
11 | }catch(error) {
12 | console.log(error.message);
13 | }
14 | }
15 | render() {
16 | return (
17 |
18 |
23 |
24 |
25 |
36 |
37 |
38 |
39 | {this.props.auth.isAuthenticated && this.props.auth.user && (
40 |
41 | Hello {this.props.auth.user.username}
42 |
43 | )}
44 |
45 | {!this.props.auth.isAuthenticated && (
46 |
54 | )}
55 | {this.props.auth.isAuthenticated && (
56 |
57 | Log out
58 |
59 | )}
60 |
61 |
62 |
63 |
64 |
65 | )
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/components/Product.js:
--------------------------------------------------------------------------------
1 | import React, { Component, Fragment } from 'react';
2 | import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
3 |
4 | export default class ProductAdmin extends Component {
5 |
6 | state = {
7 | isEditMode: false,
8 | updatedproductname: this.props.name
9 | }
10 |
11 | handleProductEdit = event => {
12 | event.preventDefault();
13 | this.setState({ isEditMode: true });
14 | }
15 |
16 | handleEditSave = event => {
17 | event.preventDefault();
18 | this.setState({ isEditMode: false });
19 | this.props.handleUpdateProduct(this.props.id, this.state.updatedproductname);
20 | }
21 |
22 | onAddProductNameChange = event => this.setState({ "updatedproductname": event.target.value });
23 |
24 | render() {
25 | return (
26 |
27 | {
28 | this.props.isAdmin &&
29 |
30 |
31 |
32 |
33 | this.props.handleDeleteProduct(this.props.id, event)} className="delete">
34 |
35 | }
36 | {
37 | this.state.isEditMode
38 | ?
39 |
Edit product name
40 |
47 |
id: { this.props.id }
48 |
save
52 |
53 | :
54 |
{ this.props.name }
55 |
id: { this.props.id }
56 |
57 | }
58 |
59 | )
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/components/ProductAdmin.js:
--------------------------------------------------------------------------------
1 | import React, { Component, Fragment } from 'react';
2 | import Product from './Product';
3 | import axios from "axios";
4 | const config = require('../config.json');
5 |
6 | export default class ProductAdmin extends Component {
7 |
8 | state = {
9 | newproduct: {
10 | "productname": "",
11 | "id": ""
12 | },
13 | products: []
14 | }
15 |
16 | handleAddProduct = async (id, event) => {
17 | event.preventDefault();
18 | // add call to AWS API Gateway add product endpoint here
19 | try {
20 | const params = {
21 | "id": id,
22 | "productname": this.state.newproduct.productname
23 | };
24 | await axios.post(`${config.api.invokeUrl}/products/${id}`, params);
25 | this.setState({ products: [...this.state.products, this.state.newproduct] });
26 | this.setState({ newproduct: { "productname": "", "id": "" }});
27 | }catch (err) {
28 | console.log(`An error has occurred: ${err}`);
29 | }
30 | }
31 |
32 | handleUpdateProduct = async (id, name) => {
33 | // add call to AWS API Gateway update product endpoint here
34 | try {
35 | const params = {
36 | "id": id,
37 | "productname": name
38 | };
39 | await axios.patch(`${config.api.invokeUrl}/products/${id}`, params);
40 | const productToUpdate = [...this.state.products].find(product => product.id === id);
41 | const updatedProducts = [...this.state.products].filter(product => product.id !== id);
42 | productToUpdate.productname = name;
43 | updatedProducts.push(productToUpdate);
44 | this.setState({products: updatedProducts});
45 | }catch (err) {
46 | console.log(`Error updating product: ${err}`);
47 | }
48 | }
49 |
50 | handleDeleteProduct = async (id, event) => {
51 | event.preventDefault();
52 | // add call to AWS API Gateway delete product endpoint here
53 | try {
54 | await axios.delete(`${config.api.invokeUrl}/products/${id}`);
55 | const updatedProducts = [...this.state.products].filter(product => product.id !== id);
56 | this.setState({products: updatedProducts});
57 | }catch (err) {
58 | console.log(`Unable to delete product: ${err}`);
59 | }
60 | }
61 |
62 | fetchProducts = async () => {
63 | // add call to AWS API Gateway to fetch products here
64 | // then set them in state
65 | try {
66 | const res = await axios.get(`${config.api.invokeUrl}/products`);
67 | const products = res.data;
68 | this.setState({ products: products });
69 | } catch (err) {
70 | console.log(`An error has occurred: ${err}`);
71 | }
72 | }
73 |
74 | onAddProductNameChange = event => this.setState({ newproduct: { ...this.state.newproduct, "productname": event.target.value } });
75 | onAddProductIdChange = event => this.setState({ newproduct: { ...this.state.newproduct, "id": event.target.value } });
76 |
77 | componentDidMount = () => {
78 | this.fetchProducts();
79 | }
80 |
81 | render() {
82 | return (
83 |
84 |
85 |
86 |
Product Admin
87 |
Add and remove products using the form below:
88 |
89 |
90 |
119 |
120 |
121 |
122 | {
123 | this.state.products.map((product, index) =>
124 |
)
132 | }
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 | )
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/src/components/Products.js:
--------------------------------------------------------------------------------
1 | import React, { Component, Fragment } from 'react';
2 | import Product from './Product';
3 | import axios from "axios";
4 | const config = require('../config.json');
5 |
6 | export default class Products extends Component {
7 |
8 | state = {
9 | newproduct: null,
10 | products: []
11 | }
12 |
13 | fetchProducts = async () => {
14 | // add call to AWS API Gateway to fetch products here
15 | // then set them in state
16 | try {
17 | const res = await axios.get(`${config.api.invokeUrl}/products`);
18 | const products = res.data;
19 | this.setState({ products: products });
20 | } catch (err) {
21 | console.log(`An error has occurred: ${err}`);
22 | }
23 | }
24 |
25 | componentDidMount = () => {
26 | this.fetchProducts();
27 | }
28 |
29 | render() {
30 | return (
31 |
32 |
33 |
34 |
Energy Products
35 |
Invest in a clean future with our efficient and cost-effective green energy products:
36 |
37 |
38 |
39 |
40 |
41 | {
42 | this.state.products && this.state.products.length > 0
43 | ? this.state.products.map(product =>
)
44 | :
No products available
45 | }
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | )
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/components/auth/ChangePassword.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import FormErrors from "../FormErrors";
3 | import Validate from "../utility/FormValidation";
4 | import { Auth } from 'aws-amplify';
5 |
6 | class ChangePassword extends Component {
7 | state = {
8 | oldpassword: "",
9 | newpassword: "",
10 | confirmpassword: "",
11 | errors: {
12 | cognito: null,
13 | blankfield: false,
14 | passwordmatch: false
15 | }
16 | }
17 |
18 | clearErrorState = () => {
19 | this.setState({
20 | errors: {
21 | cognito: null,
22 | blankfield: false,
23 | passwordmatch: false
24 | }
25 | });
26 | }
27 |
28 | handleSubmit = async event => {
29 | event.preventDefault();
30 |
31 | // Form validation
32 | this.clearErrorState();
33 | const error = Validate(event, this.state);
34 | if (error) {
35 | this.setState({
36 | errors: { ...this.state.errors, ...error }
37 | });
38 | }
39 |
40 | // AWS Cognito integration here
41 | try {
42 | const user = await Auth.currentAuthenticatedUser();
43 | console.log(user);
44 | await Auth.changePassword(
45 | user,
46 | this.state.oldpassword,
47 | this.state.newpassword
48 | );
49 | this.props.history.push("/changepasswordconfirmation");
50 | } catch (error) {
51 | let err = null;
52 | !error.message ? err = { "message": error } : err = error;
53 | this.setState({
54 | errors: { ...this.state.errors, cognito: err }
55 | });
56 | console.log(err);
57 | }
58 | }
59 |
60 | onInputChange = event => {
61 | this.setState({
62 | [event.target.id]: event.target.value
63 | });
64 | document.getElementById(event.target.id).classList.remove("is-danger");
65 | }
66 |
67 | render() {
68 | return (
69 |
70 |
71 |
Change Password
72 |
73 |
74 |
133 |
134 |
135 | );
136 | }
137 | }
138 |
139 | export default ChangePassword;
--------------------------------------------------------------------------------
/src/components/auth/ChangePasswordConfirm.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from "react";
2 |
3 | class ChangePasswordConfirmation extends Component {
4 | render() {
5 | return (
6 |
7 |
8 |
Change Password
9 |
Your password has been successfully updated!
10 |
11 |
12 | );
13 | }
14 | }
15 |
16 | export default ChangePasswordConfirmation;
--------------------------------------------------------------------------------
/src/components/auth/ForgotPassword.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import FormErrors from "../FormErrors";
3 | import Validate from "../utility/FormValidation";
4 | import { Auth } from 'aws-amplify';
5 |
6 | class ForgotPassword extends Component {
7 | state = {
8 | email: "",
9 | errors: {
10 | cognito: null,
11 | blankfield: false
12 | }
13 | }
14 |
15 | clearErrorState = () => {
16 | this.setState({
17 | errors: {
18 | cognito: null,
19 | blankfield: false
20 | }
21 | });
22 | }
23 |
24 | forgotPasswordHandler = async event => {
25 | event.preventDefault();
26 |
27 | // Form validation
28 | this.clearErrorState();
29 | const error = Validate(event, this.state);
30 | if (error) {
31 | this.setState({
32 | errors: { ...this.state.errors, ...error }
33 | });
34 | }
35 |
36 | // AWS Cognito integration here
37 | try {
38 | await Auth.forgotPassword(this.state.email);
39 | this.props.history.push('/forgotpasswordverification');
40 | }catch(error) {
41 | console.log(error);
42 | }
43 | }
44 |
45 | onInputChange = event => {
46 | this.setState({
47 | [event.target.id]: event.target.value
48 | });
49 | document.getElementById(event.target.id).classList.remove("is-danger");
50 | }
51 |
52 | render() {
53 | return (
54 |
55 |
56 |
Forgot your password?
57 |
58 | Please enter the email address associated with your account and we'll
59 | email you a password reset link.
60 |
61 |
62 |
63 |
93 |
94 |
95 | );
96 | }
97 | }
98 |
99 | export default ForgotPassword;
--------------------------------------------------------------------------------
/src/components/auth/ForgotPasswordVerification.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import FormErrors from "../FormErrors";
3 | import Validate from "../utility/FormValidation";
4 | import { Auth } from 'aws-amplify';
5 |
6 | class ForgotPasswordVerification extends Component {
7 | state = {
8 | verificationcode: "",
9 | email: "",
10 | newpassword: "",
11 | errors: {
12 | cognito: null,
13 | blankfield: false
14 | }
15 | };
16 |
17 | clearErrorState = () => {
18 | this.setState({
19 | errors: {
20 | cognito: null,
21 | blankfield: false
22 | }
23 | });
24 | };
25 |
26 | passwordVerificationHandler = async event => {
27 | event.preventDefault();
28 |
29 | // Form validation
30 | this.clearErrorState();
31 | const error = Validate(event, this.state);
32 | if (error) {
33 | this.setState({
34 | errors: { ...this.state.errors, ...error }
35 | });
36 | }
37 |
38 | // AWS Cognito integration here
39 | try {
40 | await Auth.forgotPasswordSubmit(
41 | this.state.email,
42 | this.state.verificationcode,
43 | this.state.newpassword
44 | );
45 | this.props.history.push("/changepasswordconfirmation");
46 | }catch(error) {
47 | console.log(error);
48 | }
49 | };
50 |
51 | onInputChange = event => {
52 | this.setState({
53 | [event.target.id]: event.target.value
54 | });
55 | document.getElementById(event.target.id).classList.remove("is-danger");
56 | };
57 |
58 | render() {
59 | return (
60 |
61 |
62 |
Set new password
63 |
64 | Please enter the verification code sent to your email address below,
65 | your email address and a new password.
66 |
67 |
68 |
69 |
122 |
123 |
124 | );
125 | }
126 | }
127 |
128 | export default ForgotPasswordVerification;
--------------------------------------------------------------------------------
/src/components/auth/LogIn.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import FormErrors from "../FormErrors";
3 | import Validate from "../utility/FormValidation";
4 | import { Auth } from "aws-amplify";
5 |
6 | class LogIn extends Component {
7 | state = {
8 | username: "",
9 | password: "",
10 | errors: {
11 | cognito: null,
12 | blankfield: false
13 | }
14 | };
15 |
16 | clearErrorState = () => {
17 | this.setState({
18 | errors: {
19 | cognito: null,
20 | blankfield: false
21 | }
22 | });
23 | };
24 |
25 | handleSubmit = async event => {
26 | event.preventDefault();
27 |
28 | // Form validation
29 | this.clearErrorState();
30 | const error = Validate(event, this.state);
31 | if (error) {
32 | this.setState({
33 | errors: { ...this.state.errors, ...error }
34 | });
35 | }
36 |
37 | // AWS Cognito integration here
38 | try {
39 | const user = await Auth.signIn(this.state.username, this.state.password);
40 | console.log(user);
41 | this.props.auth.setAuthStatus(true);
42 | this.props.auth.setUser(user);
43 | this.props.history.push("/");
44 | }catch(error) {
45 | let err = null;
46 | !error.message ? err = { "message": error } : err = error;
47 | this.setState({
48 | errors: {
49 | ...this.state.errors,
50 | cognito: err
51 | }
52 | });
53 | }
54 | };
55 |
56 | onInputChange = event => {
57 | this.setState({
58 | [event.target.id]: event.target.value
59 | });
60 | document.getElementById(event.target.id).classList.remove("is-danger");
61 | };
62 |
63 | render() {
64 | return (
65 |
66 |
67 |
Log in
68 |
69 |
70 |
112 |
113 |
114 | );
115 | }
116 | }
117 |
118 | export default LogIn;
--------------------------------------------------------------------------------
/src/components/auth/Register.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import FormErrors from "../FormErrors";
3 | import Validate from "../utility/FormValidation";
4 | import { Auth } from "aws-amplify";
5 |
6 | class Register extends Component {
7 | state = {
8 | username: "",
9 | email: "",
10 | password: "",
11 | confirmpassword: "",
12 | errors: {
13 | cognito: null,
14 | blankfield: false,
15 | passwordmatch: false
16 | }
17 | }
18 |
19 | clearErrorState = () => {
20 | this.setState({
21 | errors: {
22 | cognito: null,
23 | blankfield: false,
24 | passwordmatch: false
25 | }
26 | });
27 | }
28 |
29 | handleSubmit = async event => {
30 | event.preventDefault();
31 |
32 | // Form validation
33 | this.clearErrorState();
34 | const error = Validate(event, this.state);
35 | if (error) {
36 | this.setState({
37 | errors: { ...this.state.errors, ...error }
38 | });
39 | }
40 |
41 | // AWS Cognito integration here
42 | const { username, email, password } = this.state;
43 | try {
44 | const signUpResponse = await Auth.signUp({
45 | username,
46 | password,
47 | attributes: {
48 | email: email
49 | }
50 | });
51 | this.props.history.push("/welcome");
52 | console.log(signUpResponse);
53 | } catch (error) {
54 | let err = null;
55 | !error.message ? err = { "message": error } : err = error;
56 | this.setState({
57 | errors: {
58 | ...this.state.errors,
59 | cognito: err
60 | }
61 | });
62 | }
63 | }
64 |
65 | onInputChange = event => {
66 | this.setState({
67 | [event.target.id]: event.target.value
68 | });
69 | document.getElementById(event.target.id).classList.remove("is-danger");
70 | }
71 |
72 | render() {
73 | return (
74 |
75 |
76 |
Register
77 |
78 |
79 |
152 |
153 |
154 | );
155 | }
156 | }
157 |
158 | export default Register;
--------------------------------------------------------------------------------
/src/components/auth/Welcome.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | export default function Welcome() {
4 | return (
5 |
6 |
7 |
Welcome!
8 |
You have successfully registered a new account.
9 |
We've sent you a email. Please click on the confirmation link to verify your account.
10 |
11 |
12 | )
13 | }
14 |
--------------------------------------------------------------------------------
/src/components/utility/FormValidation.js:
--------------------------------------------------------------------------------
1 | function validateForm(event, state) {
2 | // clear all error messages
3 | const inputs = document.getElementsByClassName("is-danger");
4 | for (let i = 0; i < inputs.length; i++) {
5 | if (!inputs[i].classList.contains("error")) {
6 | inputs[i].classList.remove("is-danger");
7 | }
8 | }
9 |
10 | if (state.hasOwnProperty("username") && state.username === "") {
11 | document.getElementById("username").classList.add("is-danger");
12 | return { blankfield: true };
13 | }
14 | if (state.hasOwnProperty("firstname") && state.firstname === "") {
15 | document.getElementById("firstname").classList.add("is-danger");
16 | return { blankfield: true };
17 | }
18 | if (state.hasOwnProperty("lastname") && state.lastname === "") {
19 | document.getElementById("lastname").classList.add("is-danger");
20 | return { blankfield: true };
21 | }
22 | if (state.hasOwnProperty("email") && state.email === "") {
23 | document.getElementById("email").classList.add("is-danger");
24 | return { blankfield: true };
25 | }
26 | if (
27 | state.hasOwnProperty("verificationcode") &&
28 | state.verificationcode === ""
29 | ) {
30 | document.getElementById("verificationcode").classList.add("is-danger");
31 | return { blankfield: true };
32 | }
33 | if (state.hasOwnProperty("password") && state.password === "") {
34 | document.getElementById("password").classList.add("is-danger");
35 | return { blankfield: true };
36 | }
37 | if (state.hasOwnProperty("oldpassword") && state.oldpassword === "") {
38 | document.getElementById("oldpassword").classList.add("is-danger");
39 | return { blankfield: true };
40 | }
41 | if (state.hasOwnProperty("newpassword") && state.newpassword === "") {
42 | document.getElementById("newpassword").classList.add("is-danger");
43 | return { blankfield: true };
44 | }
45 | if (state.hasOwnProperty("confirmpassword") && state.confirmpassword === "") {
46 | document.getElementById("confirmpassword").classList.add("is-danger");
47 | return { blankfield: true };
48 | }
49 | if (
50 | state.hasOwnProperty("password") &&
51 | state.hasOwnProperty("confirmpassword") &&
52 | state.password !== state.confirmpassword
53 | ) {
54 | document.getElementById("password").classList.add("is-danger");
55 | document.getElementById("confirmpassword").classList.add("is-danger");
56 | return { passwordmatch: true };
57 | }
58 | if (
59 | state.hasOwnProperty("newpassword") &&
60 | state.hasOwnProperty("confirmpassword") &&
61 | state.newpassword !== state.confirmpassword
62 | ) {
63 | document.getElementById("newpassword").classList.add("is-danger");
64 | document.getElementById("confirmpassword").classList.add("is-danger");
65 | return { passwordmatch: true };
66 | }
67 | return;
68 | }
69 |
70 | export default validateForm;
--------------------------------------------------------------------------------
/src/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "api": {
3 | "invokeUrl": "https://5bltcq602h.execute-api.us-west-2.amazonaws.com/prod"
4 | },
5 | "cognito": {
6 | "REGION": "us-west-2",
7 | "USER_POOL_ID": "us-west-2_flCJaoDig",
8 | "APP_CLIENT_ID": "159ufjrihgehb67sn373aotli7"
9 | }
10 | }
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jspruance/aws-cognito-tutorial-complete/2eedd15239c299dfc0cea92017f261869b188878/src/index.css
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import 'bulma/css/bulma.min.css';
4 | import './index.css';
5 | import App from './App';
6 | import Amplify from "aws-amplify";
7 | import config from "./config";
8 | import * as serviceWorker from './serviceWorker';
9 |
10 | Amplify.configure({
11 | Auth: {
12 | mandatorySignIn: true,
13 | region: config.cognito.REGION,
14 | userPoolId: config.cognito.USER_POOL_ID,
15 | userPoolWebClientId: config.cognito.APP_CLIENT_ID
16 | }
17 | });
18 |
19 | ReactDOM.render( , document.getElementById('root'));
20 |
21 | // If you want your app to work offline and load faster, you can change
22 | // unregister() to register() below. Note this comes with some pitfalls.
23 | // Learn more about service workers: http://bit.ly/CRA-PWA
24 | serviceWorker.unregister();
25 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read http://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.1/8 is considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl)
104 | .then(response => {
105 | // Ensure service worker exists, and that we really are getting a JS file.
106 | const contentType = response.headers.get('content-type');
107 | if (
108 | response.status === 404 ||
109 | (contentType != null && contentType.indexOf('javascript') === -1)
110 | ) {
111 | // No service worker found. Probably a different app. Reload the page.
112 | navigator.serviceWorker.ready.then(registration => {
113 | registration.unregister().then(() => {
114 | window.location.reload();
115 | });
116 | });
117 | } else {
118 | // Service worker found. Proceed as normal.
119 | registerValidSW(swUrl, config);
120 | }
121 | })
122 | .catch(() => {
123 | console.log(
124 | 'No internet connection found. App is running in offline mode.'
125 | );
126 | });
127 | }
128 |
129 | export function unregister() {
130 | if ('serviceWorker' in navigator) {
131 | navigator.serviceWorker.ready.then(registration => {
132 | registration.unregister();
133 | });
134 | }
135 | }
136 |
--------------------------------------------------------------------------------