From 313ef146dd0effdcb4147e8fbf0f56ca77b2a209 Mon Sep 17 00:00:00 2001 From: benjaminramey Date: Fri, 13 Nov 2020 16:24:00 -0600 Subject: [PATCH] Run 'format' --- site/config.js | 8 +- site/src/components/Auth/Auth.js | 467 +++++++++++---------- site/src/components/Dashboard/Dashboard.js | 125 +++--- site/src/pages/index.js | 8 +- site/src/utils/api.js | 83 ++-- site/src/utils/helpers.js | 95 +++-- site/src/utils/index.js | 4 +- 7 files changed, 409 insertions(+), 381 deletions(-) diff --git a/site/config.js b/site/config.js index 9772078..c3e57d6 100644 --- a/site/config.js +++ b/site/config.js @@ -2,10 +2,10 @@ * Global Config */ -const config = {} +const config = {}; // Domains -config.domains = {} +config.domains = {}; /** * API Domain @@ -13,6 +13,6 @@ config.domains = {} * This will enable your front-end to communicate with your back-end. * (e.g. 'https://api.mydomain.com' or 'https://091jafsl10.execute-api.us-east-1.amazonaws.com') */ -config.domains.api = 'https://13gtp0hrak.execute-api.us-east-1.amazonaws.com' +config.domains.api = "https://13gtp0hrak.execute-api.us-east-1.amazonaws.com"; -export default config \ No newline at end of file +export default config; diff --git a/site/src/components/Auth/Auth.js b/site/src/components/Auth/Auth.js index b3d499d..024f993 100644 --- a/site/src/components/Auth/Auth.js +++ b/site/src/components/Auth/Auth.js @@ -1,247 +1,284 @@ -import React, { Component } from 'react' -import { - Link -} from 'gatsby' -import styles from './Auth.module.css' -import { - userRegister, - userLogin, - userGet, - saveSession, -} from '../../utils' +import React, { Component } from "react"; +import { Link } from "gatsby"; +import styles from "./Auth.module.css"; +import { userRegister, userLogin, userGet, saveSession } from "../../utils"; class Auth extends Component { + constructor(props) { + super(props); - constructor(props) { - super(props) + const pathName = window.location.pathname.replace("/", ""); - const pathName = window.location.pathname.replace('/', '') + this.state = {}; + this.state.state = pathName; + this.state.loading = true; + this.state.error = null; + this.state.formEmail = ""; + this.state.formPassword = ""; - this.state = {} - this.state.state = pathName - this.state.loading = true - this.state.error = null - this.state.formEmail = '' - this.state.formPassword = '' + // Bindings + this.handleFormInput = this.handleFormInput.bind(this); + this.handleFormSubmit = this.handleFormSubmit.bind(this); + this.handleFormTypeChange = this.handleFormTypeChange.bind(this); + } - // Bindings - this.handleFormInput = this.handleFormInput.bind(this) - this.handleFormSubmit = this.handleFormSubmit.bind(this) - this.handleFormTypeChange = this.handleFormTypeChange.bind(this) - } + /** + * Component did mount + */ + componentDidMount() { + this.setState({ + loading: false, + }); - /** - * Component did mount - */ - componentDidMount() { - this.setState({ - loading: false - }) + // Clear query params + const url = document.location.href; + window.history.pushState({}, "", url.split("?")[0]); + } - // Clear query params - const url = document.location.href - window.history.pushState({}, '', url.split('?')[0]) - } + /** + * Handles a form change + */ + handleFormTypeChange(type) { + this.setState({ state: type }, () => { + this.props.history.push(`/${type}`); + }); + } - /** - * Handles a form change - */ - handleFormTypeChange(type) { - this.setState({ state: type }, - () => { - this.props.history.push(`/${type}`) - }) - } + /** + * Handle text changes within form fields + */ + handleFormInput(field, value) { + value = value.trim(); - /** - * Handle text changes within form fields - */ - handleFormInput(field, value) { - value = value.trim() + const nextState = {}; + nextState[field] = value; - const nextState = {} - nextState[field] = value + this.setState(Object.assign(this.state, nextState)); + } - this.setState(Object.assign(this.state, nextState)) - } + /** + * Handles form submission + * @param {object} evt + */ + async handleFormSubmit(evt) { + evt.preventDefault(); - /** - * Handles form submission - * @param {object} evt - */ - async handleFormSubmit(evt) { - evt.preventDefault() + this.setState({ loading: true }); - this.setState({ loading: true }) + // Validate email + if (!this.state.formEmail) { + return this.setState({ + loading: false, + formError: "email is required", + }); + } - // Validate email - if (!this.state.formEmail) { - return this.setState({ - loading: false, - formError: 'email is required' - }) - } + // Validate password + if (!this.state.formPassword) { + return this.setState({ + loading: false, + formError: "password is required", + }); + } - // Validate password - if (!this.state.formPassword) { - return this.setState({ - loading: false, - formError: 'password is required' - }) - } + let token; + try { + if (this.state.state === "register") { + token = await userRegister( + this.state.formEmail, + this.state.formPassword + ); + } else { + token = await userLogin( + this.state.formEmail, + this.state.formPassword + ); + } + } catch (error) { + console.log(error); + if (error.message) { + this.setState({ + formError: error.message, + loading: false, + }); + } else { + this.setState({ + formError: + "Sorry, something unknown went wrong. Please try again.", + loading: false, + }); + } + return; + } - let token - try { - if (this.state.state === 'register') { - token = await userRegister(this.state.formEmail, this.state.formPassword) - } else { - token = await userLogin(this.state.formEmail, this.state.formPassword) - } - } catch (error) { - console.log(error) - if (error.message) { - this.setState({ - formError: error.message, - loading: false - }) - } else { - this.setState({ - formError: 'Sorry, something unknown went wrong. Please try again.', - loading: false - }) - } - return - } + // Fetch user record and set session in cookie + let user = await userGet(token.token); + user = user.user; + saveSession(user.id, user.email, token.token); - // Fetch user record and set session in cookie - let user = await userGet(token.token) - user = user.user - saveSession(user.id, user.email, token.token) + window.location.replace("/"); + } - window.location.replace('/') - } + render() { + return ( +
+
+ {/* Logo */} - render() { + + serverless-fullstack-application + - return ( -
-
+ {/* Loading */} - { /* Logo */} + {this.state.loading &&
loading, man!
} - - serverless-fullstack-application - + {/* Registration Form */} - { /* Loading */} + {!this.state.loading && ( +
+
{ + this.handleFormTypeChange("register"); + }} + > + Register +
+
{ + this.handleFormTypeChange("login"); + }} + > + Sign-In +
+
+ )} - {this.state.loading && ( -
- loading, man! -
- )} + {this.state.state === "register" && !this.state.loading && ( +
+
+
+ + { + this.handleFormInput( + "formEmail", + e.target.value + ); + }} + /> +
+
+ + { + this.handleFormInput( + "formPassword", + e.target.value + ); + }} + /> +
- { /* Registration Form */} + {this.state.formError && ( +
+ {this.state.formError} +
+ )} - {!this.state.loading && ( -
-
{ this.handleFormTypeChange('register') }}> - Register -
-
{ this.handleFormTypeChange('login') }}> - Sign-In -
-
- )} + +
+
+ )} - {this.state.state === 'register' && !this.state.loading && ( -
+ {this.state.state === "login" && !this.state.loading && ( +
+
+
+ + { + this.handleFormInput( + "formEmail", + e.target.value + ); + }} + /> +
+
+ + { + this.handleFormInput( + "formPassword", + e.target.value + ); + }} + /> +
- -
- - { this.handleFormInput('formEmail', e.target.value) }} - /> -
-
- - { this.handleFormInput('formPassword', e.target.value) }} - /> -
+ {this.state.formError && ( +
+ {this.state.formError} +
+ )} - {this.state.formError && ( -
{this.state.formError}
- )} - - - -
-
- )} - - {this.state.state === 'login' && !this.state.loading && ( -
- -
-
- - { this.handleFormInput('formEmail', e.target.value) }} - /> -
-
- - { this.handleFormInput('formPassword', e.target.value) }} - /> -
- - {this.state.formError && ( -
{this.state.formError}
- )} - - -
-
- )} -
-
- ) - } + + +
+ )} +
+
+ ); + } } -export default Auth +export default Auth; diff --git a/site/src/components/Dashboard/Dashboard.js b/site/src/components/Dashboard/Dashboard.js index 20dfd8d..b27ac09 100644 --- a/site/src/components/Dashboard/Dashboard.js +++ b/site/src/components/Dashboard/Dashboard.js @@ -1,82 +1,69 @@ -import React, { Component } from 'react' -import { - withRouter -} from 'react-router-dom' -import styles from './Dashboard.module.css' -import { - getSession, - deleteSession -} from '../../utils' +import React, { Component } from "react"; +import { withRouter } from "react-router-dom"; +import styles from "./Dashboard.module.css"; +import { getSession, deleteSession } from "../../utils"; class Dashboard extends Component { + constructor(props) { + super(props); + this.state = {}; - constructor(props) { - super(props) - this.state = {} + // Bindings + this.logout = this.logout.bind(this); + } - // Bindings - this.logout = this.logout.bind(this) - } + async componentDidMount() { + const userSession = getSession(); - async componentDidMount() { + this.setState({ + session: userSession, + }); + } - const userSession = getSession() + /** + * Log user out by clearing cookie and redirecting + */ + logout() { + deleteSession(); + this.props.history.push(`/`); + } - this.setState({ - session: userSession, - }) - } + render() { + return ( +
+
+ {/* Navigation */} - /** - * Log user out by clearing cookie and redirecting - */ - logout() { - deleteSession() - this.props.history.push(`/`) - } +
+
+ {this.state.session + ? this.state.session.userEmail + : ""} +
+
+ logout +
+
- render() { + {/* Content */} - return ( -
-
+
+
+ serverless-fullstack-application +
- { /* Navigation */ } - -
-
- { this.state.session ? this.state.session.userEmail : '' } -
-
- logout -
-
- - { /* Content */ } - -
- -
- serverless-fullstack-application -
- -
- Welcome to your serverless fullstack dashboard... -
- -
- -
-
- ) - } +
+ Welcome to your serverless fullstack dashboard... +
+
+
+
+ ); + } } -export default withRouter(Dashboard) \ No newline at end of file +export default withRouter(Dashboard); diff --git a/site/src/pages/index.js b/site/src/pages/index.js index 5f3f7f3..00217e2 100644 --- a/site/src/pages/index.js +++ b/site/src/pages/index.js @@ -3,9 +3,9 @@ import Auth from "../components/Auth/Auth"; export default function Home() { return ( -
-

Hello world!

- -
+
+

Hello world!

+ +
); } diff --git a/site/src/utils/api.js b/site/src/utils/api.js index ce0c617..6edee91 100644 --- a/site/src/utils/api.js +++ b/site/src/utils/api.js @@ -2,70 +2,69 @@ * Utils: Back-end */ -import config from '../../config' +import config from "../../config"; /** * Register a new user */ export const userRegister = async (email, password) => { - return await requestApi('/users/register', 'POST', { email, password }) -} + return await requestApi("/users/register", "POST", { email, password }); +}; /** * Login a new user */ export const userLogin = async (email, password) => { - return await requestApi('/users/login', 'POST', { email, password }) -} + return await requestApi("/users/login", "POST", { email, password }); +}; /** * userGet */ export const userGet = async (token) => { - return await requestApi('/user', 'POST', null, { - Authorization: `Bearer ${token}` - }) -} + return await requestApi("/user", "POST", null, { + Authorization: `Bearer ${token}`, + }); +}; /** * API request to call the backend */ export const requestApi = async ( - path = '', - method = 'GET', - data = null, - headers = {}) => { + path = "", + method = "GET", + data = null, + headers = {} +) => { + // Check if API URL has been set + if (!config?.domains?.api) { + throw new Error( + `Error: Missing API Domain – Please add the API domain from your serverless Express.js back-end to this front-end application. You can do this in the "site" folder, in the "./config.js" file. Instructions are listed there and in the documentation.` + ); + } - // Check if API URL has been set - if (!config?.domains?.api) { - throw new Error(`Error: Missing API Domain – Please add the API domain from your serverless Express.js back-end to this front-end application. You can do this in the "site" folder, in the "./config.js" file. Instructions are listed there and in the documentation.`) - } + // Prepare URL + if (!path.startsWith("/")) { + path = `/${path}`; + } + const url = `${config.domains.api}${path}`; - // Prepare URL - if (!path.startsWith('/')) { - path = `/${path}` - } - const url = `${config.domains.api}${path}` + // Set headers + headers = Object.assign({ "Content-Type": "application/json" }, headers); - // Set headers - headers = Object.assign( - { 'Content-Type': 'application/json' }, - headers - ) + // Default options are marked with * + const response = await fetch(url, { + method: method.toUpperCase(), + mode: "cors", + cache: "no-cache", + headers, + body: data ? JSON.stringify(data) : null, + }); - // Default options are marked with * - const response = await fetch(url, { - method: method.toUpperCase(), - mode: 'cors', - cache: 'no-cache', - headers, - body: data ? JSON.stringify(data) : null - }) + if (response.status < 200 || response.status >= 300) { + const error = await response.json(); + throw new Error(error.error); + } - if (response.status < 200 || response.status >= 300) { - const error = await response.json() - throw new Error(error.error) - } - - return await response.json() -} + return await response.json(); +}; diff --git a/site/src/utils/helpers.js b/site/src/utils/helpers.js index 73c63ac..df3875e 100644 --- a/site/src/utils/helpers.js +++ b/site/src/utils/helpers.js @@ -1,76 +1,81 @@ -import Cookies from 'js-cookie' +import Cookies from "js-cookie"; /** * Format Org and Username correctly for the Serverless Platform backend */ -export const formatOrgAndUsername = (name = '') => { - name = name.toString().toLowerCase().replace(/[^a-z\d-]+/gi, '-') - // Remove multiple instances of hyphens - name = name.replace(/-{2,}/g, '-') - if (name.length > 40) { - name = name.substring(0, 40) - } - return name -} +export const formatOrgAndUsername = (name = "") => { + name = name + .toString() + .toLowerCase() + .replace(/[^a-z\d-]+/gi, "-"); + // Remove multiple instances of hyphens + name = name.replace(/-{2,}/g, "-"); + if (name.length > 40) { + name = name.substring(0, 40); + } + return name; +}; /** * Parse query parameters in a URL - * @param {*} searchString + * @param {*} searchString */ export const parseQueryParams = (searchString = null) => { - if (!searchString) { - return null - } + if (!searchString) { + return null; + } - // Clone string - let clonedParams = (' ' + searchString).slice(1) + // Clone string + let clonedParams = (" " + searchString).slice(1); - return clonedParams - .substr(1) - .split('&') - .filter((el) => el.length) - .map((el) => el.split('=')) - .reduce( - (accumulator, currentValue) => - Object.assign(accumulator, { - [decodeURIComponent(currentValue.shift())]: decodeURIComponent(currentValue.pop()) - }), - {} - ) -} + return clonedParams + .substr(1) + .split("&") + .filter((el) => el.length) + .map((el) => el.split("=")) + .reduce( + (accumulator, currentValue) => + Object.assign(accumulator, { + [decodeURIComponent( + currentValue.shift() + )]: decodeURIComponent(currentValue.pop()), + }), + {} + ); +}; /** * Parse hash fragment parameters in a URL */ export const parseHashFragment = (hashString) => { - const hashData = {} - let hash = decodeURI(hashString) - hash = hash.split('&') - hash.forEach((val) => { - val = val.replace('#', '') - hashData[val.split('=')[0]] = val.split('=')[1] - }) - return hashData -} + const hashData = {}; + let hash = decodeURI(hashString); + hash = hash.split("&"); + hash.forEach((val) => { + val = val.replace("#", ""); + hashData[val.split("=")[0]] = val.split("=")[1]; + }); + return hashData; +}; /** * Save session in browser cookie */ export const saveSession = (userId, userEmail, userToken) => { - Cookies.set('serverless', { userId, userEmail, userToken }) -} + Cookies.set("serverless", { userId, userEmail, userToken }); +}; /** * Get session in browser cookie */ export const getSession = () => { - const data = Cookies.get('serverless') - return data ? JSON.parse(data) : null -} + const data = Cookies.get("serverless"); + return data ? JSON.parse(data) : null; +}; /** * Delete session in browser cookie */ export const deleteSession = () => { - Cookies.remove('serverless') -} \ No newline at end of file + Cookies.remove("serverless"); +}; diff --git a/site/src/utils/index.js b/site/src/utils/index.js index 5bfa17a..189da4d 100644 --- a/site/src/utils/index.js +++ b/site/src/utils/index.js @@ -1,2 +1,2 @@ -export * from './helpers' -export * from './api' \ No newline at end of file +export * from "./helpers"; +export * from "./api";