Run 'format'

This commit is contained in:
2020-11-13 16:24:00 -06:00
parent 0190b0a30e
commit 313ef146dd
7 changed files with 409 additions and 381 deletions

View File

@@ -2,10 +2,10 @@
* Global Config * Global Config
*/ */
const config = {} const config = {};
// Domains // Domains
config.domains = {} config.domains = {};
/** /**
* API Domain * API Domain
@@ -13,6 +13,6 @@ config.domains = {}
* This will enable your front-end to communicate with your back-end. * 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') * (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 export default config;

View File

@@ -1,33 +1,25 @@
import React, { Component } from 'react' import React, { Component } from "react";
import { import { Link } from "gatsby";
Link import styles from "./Auth.module.css";
} from 'gatsby' import { userRegister, userLogin, userGet, saveSession } from "../../utils";
import styles from './Auth.module.css'
import {
userRegister,
userLogin,
userGet,
saveSession,
} from '../../utils'
class Auth extends Component { class Auth extends Component {
constructor(props) { constructor(props) {
super(props) super(props);
const pathName = window.location.pathname.replace('/', '') const pathName = window.location.pathname.replace("/", "");
this.state = {} this.state = {};
this.state.state = pathName this.state.state = pathName;
this.state.loading = true this.state.loading = true;
this.state.error = null this.state.error = null;
this.state.formEmail = '' this.state.formEmail = "";
this.state.formPassword = '' this.state.formPassword = "";
// Bindings // Bindings
this.handleFormInput = this.handleFormInput.bind(this) this.handleFormInput = this.handleFormInput.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this) this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleFormTypeChange = this.handleFormTypeChange.bind(this) this.handleFormTypeChange = this.handleFormTypeChange.bind(this);
} }
/** /**
@@ -35,34 +27,33 @@ class Auth extends Component {
*/ */
componentDidMount() { componentDidMount() {
this.setState({ this.setState({
loading: false loading: false,
}) });
// Clear query params // Clear query params
const url = document.location.href const url = document.location.href;
window.history.pushState({}, '', url.split('?')[0]) window.history.pushState({}, "", url.split("?")[0]);
} }
/** /**
* Handles a form change * Handles a form change
*/ */
handleFormTypeChange(type) { handleFormTypeChange(type) {
this.setState({ state: type }, this.setState({ state: type }, () => {
() => { this.props.history.push(`/${type}`);
this.props.history.push(`/${type}`) });
})
} }
/** /**
* Handle text changes within form fields * Handle text changes within form fields
*/ */
handleFormInput(field, value) { handleFormInput(field, value) {
value = value.trim() value = value.trim();
const nextState = {} const nextState = {};
nextState[field] = value nextState[field] = value;
this.setState(Object.assign(this.state, nextState)) this.setState(Object.assign(this.state, nextState));
} }
/** /**
@@ -70,178 +61,224 @@ class Auth extends Component {
* @param {object} evt * @param {object} evt
*/ */
async handleFormSubmit(evt) { async handleFormSubmit(evt) {
evt.preventDefault() evt.preventDefault();
this.setState({ loading: true }) this.setState({ loading: true });
// Validate email // Validate email
if (!this.state.formEmail) { if (!this.state.formEmail) {
return this.setState({ return this.setState({
loading: false, loading: false,
formError: 'email is required' formError: "email is required",
}) });
} }
// Validate password // Validate password
if (!this.state.formPassword) { if (!this.state.formPassword) {
return this.setState({ return this.setState({
loading: false, loading: false,
formError: 'password is required' formError: "password is required",
}) });
} }
let token let token;
try { try {
if (this.state.state === 'register') { if (this.state.state === "register") {
token = await userRegister(this.state.formEmail, this.state.formPassword) token = await userRegister(
this.state.formEmail,
this.state.formPassword
);
} else { } else {
token = await userLogin(this.state.formEmail, this.state.formPassword) token = await userLogin(
this.state.formEmail,
this.state.formPassword
);
} }
} catch (error) { } catch (error) {
console.log(error) console.log(error);
if (error.message) { if (error.message) {
this.setState({ this.setState({
formError: error.message, formError: error.message,
loading: false loading: false,
}) });
} else { } else {
this.setState({ this.setState({
formError: 'Sorry, something unknown went wrong. Please try again.', formError:
loading: false "Sorry, something unknown went wrong. Please try again.",
}) loading: false,
});
} }
return return;
} }
// Fetch user record and set session in cookie // Fetch user record and set session in cookie
let user = await userGet(token.token) let user = await userGet(token.token);
user = user.user user = user.user;
saveSession(user.id, user.email, token.token) saveSession(user.id, user.email, token.token);
window.location.replace('/') window.location.replace("/");
} }
render() { render() {
return ( return (
<div className={`${styles.container} animateFadeIn`}> <div className={`${styles.container} animateFadeIn`}>
<div className={styles.containerInner}> <div className={styles.containerInner}>
{/* Logo */}
{ /* Logo */} <Link to="/" className={`${styles.logo}`}>
<Link to='/' className={`${styles.logo}`}>
<img <img
draggable='false' draggable="false"
src={'./fullstack-app-title.png'} src={"./fullstack-app-title.png"}
alt='serverless-fullstack-application' alt="serverless-fullstack-application"
/> />
</Link> </Link>
{ /* Loading */} {/* Loading */}
{this.state.loading && ( {this.state.loading && <div>loading, man!</div>}
<div>
loading, man!
</div>
)}
{ /* Registration Form */} {/* Registration Form */}
{!this.state.loading && ( {!this.state.loading && (
<div className={styles.formType}> <div className={styles.formType}>
<div <div
className={ className={`${styles.formTypeRegister}
`${styles.formTypeRegister} ${
${this.state.state === 'register' ? styles.formTypeActive : ''}`} this.state.state === "register" ? styles.formTypeActive : ""
onClick={(e) => { this.handleFormTypeChange('register') }}> }`}
onClick={(e) => {
this.handleFormTypeChange("register");
}}
>
Register Register
</div> </div>
<div <div
className={ className={`${styles.formTypeSignIn}
`${styles.formTypeSignIn} ${this.state.state === "login" ? styles.formTypeActive : ""}`}
${this.state.state === 'login' ? styles.formTypeActive : ''}`} onClick={(e) => {
onClick={(e) => { this.handleFormTypeChange('login') }}> this.handleFormTypeChange("login");
}}
>
Sign-In Sign-In
</div> </div>
</div> </div>
)} )}
{this.state.state === 'register' && !this.state.loading && ( {this.state.state === "register" && !this.state.loading && (
<div className={styles.containerRegister}> <div className={styles.containerRegister}>
<form
<form className={styles.form} onSubmit={this.handleFormSubmit}> className={styles.form}
onSubmit={this.handleFormSubmit}
>
<div className={styles.formField}> <div className={styles.formField}>
<label className={styles.formLabel}>email</label> <label className={styles.formLabel}>
email
</label>
<input <input
type='text' type="text"
placeholder='yours@example.com' placeholder="yours@example.com"
className={styles.formInput} className={styles.formInput}
value={this.state.formEmail} value={this.state.formEmail}
onChange={(e) => { this.handleFormInput('formEmail', e.target.value) }} onChange={(e) => {
this.handleFormInput(
"formEmail",
e.target.value
);
}}
/> />
</div> </div>
<div className={styles.formField}> <div className={styles.formField}>
<label className={styles.formLabel}>password</label> <label className={styles.formLabel}>
password
</label>
<input <input
type='password' type="password"
placeholder='your password' placeholder="your password"
className={styles.formInput} className={styles.formInput}
value={this.state.formPassword} value={this.state.formPassword}
onChange={(e) => { this.handleFormInput('formPassword', e.target.value) }} onChange={(e) => {
this.handleFormInput(
"formPassword",
e.target.value
);
}}
/> />
</div> </div>
{this.state.formError && ( {this.state.formError && (
<div className={styles.formError}>{this.state.formError}</div> <div className={styles.formError}>
{this.state.formError}
</div>
)} )}
<input <input
className={`buttonPrimaryLarge ${styles.formButton}`} className={`buttonPrimaryLarge ${styles.formButton}`}
type='submit' type="submit"
value='Register' value="Register"
/> />
</form> </form>
</div> </div>
)} )}
{this.state.state === 'login' && !this.state.loading && ( {this.state.state === "login" && !this.state.loading && (
<div className={styles.containerSignIn}> <div className={styles.containerSignIn}>
<form
<form className={styles.form} onSubmit={this.handleFormSubmit}> className={styles.form}
onSubmit={this.handleFormSubmit}
>
<div className={styles.formField}> <div className={styles.formField}>
<label className={styles.formLabel}>email</label> <label className={styles.formLabel}>
email
</label>
<input <input
type='text' type="text"
placeholder='yours@example.com' placeholder="yours@example.com"
className={styles.formInput} className={styles.formInput}
value={this.state.formEmail} value={this.state.formEmail}
onChange={(e) => { this.handleFormInput('formEmail', e.target.value) }} onChange={(e) => {
this.handleFormInput(
"formEmail",
e.target.value
);
}}
/> />
</div> </div>
<div className={styles.formField}> <div className={styles.formField}>
<label className={styles.formLabel}>password</label> <label className={styles.formLabel}>
password
</label>
<input <input
type='password' type="password"
placeholder='your password' placeholder="your password"
className={styles.formInput} className={styles.formInput}
value={this.state.formPassword} value={this.state.formPassword}
onChange={(e) => { this.handleFormInput('formPassword', e.target.value) }} onChange={(e) => {
this.handleFormInput(
"formPassword",
e.target.value
);
}}
/> />
</div> </div>
{this.state.formError && ( {this.state.formError && (
<div className={styles.formError}>{this.state.formError}</div> <div className={styles.formError}>
{this.state.formError}
</div>
)} )}
<input className={`buttonPrimaryLarge ${styles.formButton}`} type='submit' value='Sign In' /> <input
className={`buttonPrimaryLarge ${styles.formButton}`}
type="submit"
value="Sign In"
/>
</form> </form>
</div> </div>
)} )}
</div> </div>
</div> </div>
) );
} }
} }
export default Auth export default Auth;

View File

@@ -1,82 +1,69 @@
import React, { Component } from 'react' import React, { Component } from "react";
import { import { withRouter } from "react-router-dom";
withRouter import styles from "./Dashboard.module.css";
} from 'react-router-dom' import { getSession, deleteSession } from "../../utils";
import styles from './Dashboard.module.css'
import {
getSession,
deleteSession
} from '../../utils'
class Dashboard extends Component { class Dashboard extends Component {
constructor(props) { constructor(props) {
super(props) super(props);
this.state = {} this.state = {};
// Bindings // Bindings
this.logout = this.logout.bind(this) this.logout = this.logout.bind(this);
} }
async componentDidMount() { async componentDidMount() {
const userSession = getSession();
const userSession = getSession()
this.setState({ this.setState({
session: userSession, session: userSession,
}) });
} }
/** /**
* Log user out by clearing cookie and redirecting * Log user out by clearing cookie and redirecting
*/ */
logout() { logout() {
deleteSession() deleteSession();
this.props.history.push(`/`) this.props.history.push(`/`);
} }
render() { render() {
return ( return (
<div className={`${styles.container} animateFadeIn`}> <div className={`${styles.container} animateFadeIn`}>
<div className={styles.containerInner}> <div className={styles.containerInner}>
{/* Navigation */}
{ /* Navigation */ }
<div className={styles.navigationContainer}> <div className={styles.navigationContainer}>
<div <div className={`link`}>
className={`link`}> {this.state.session
{ this.state.session ? this.state.session.userEmail : '' } ? this.state.session.userEmail
: ""}
</div> </div>
<div <div className={`link`} onClick={this.logout}>
className={`link`}
onClick={this.logout}>
logout logout
</div> </div>
</div> </div>
{ /* Content */ } {/* Content */}
<div className={`${styles.contentContainer}`}> <div className={`${styles.contentContainer}`}>
<div className={`${styles.artwork} animateFlicker`}> <div className={`${styles.artwork} animateFlicker`}>
<img <img
draggable='false' draggable="false"
src={'./fullstack-app-artwork.png'} src={"./fullstack-app-artwork.png"}
alt='serverless-fullstack-application' alt="serverless-fullstack-application"
/> />
</div> </div>
<div className={`${styles.welcomeMessage}`}> <div className={`${styles.welcomeMessage}`}>
Welcome to your serverless fullstack dashboard... Welcome to your serverless fullstack dashboard...
</div> </div>
</div>
</div> </div>
</div> </div>
) </div>
);
} }
} }
export default withRouter(Dashboard) export default withRouter(Dashboard);

View File

@@ -5,7 +5,7 @@ export default function Home() {
return ( return (
<div> <div>
<p>Hello world!</p> <p>Hello world!</p>
<Auth/> <Auth />
</div> </div>
); );
} }

View File

@@ -2,70 +2,69 @@
* Utils: Back-end * Utils: Back-end
*/ */
import config from '../../config' import config from "../../config";
/** /**
* Register a new user * Register a new user
*/ */
export const userRegister = async (email, password) => { 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 * Login a new user
*/ */
export const userLogin = async (email, password) => { export const userLogin = async (email, password) => {
return await requestApi('/users/login', 'POST', { email, password }) return await requestApi("/users/login", "POST", { email, password });
} };
/** /**
* userGet * userGet
*/ */
export const userGet = async (token) => { export const userGet = async (token) => {
return await requestApi('/user', 'POST', null, { return await requestApi("/user", "POST", null, {
Authorization: `Bearer ${token}` Authorization: `Bearer ${token}`,
}) });
} };
/** /**
* API request to call the backend * API request to call the backend
*/ */
export const requestApi = async ( export const requestApi = async (
path = '', path = "",
method = 'GET', method = "GET",
data = null, data = null,
headers = {}) => { headers = {}
) => {
// Check if API URL has been set // Check if API URL has been set
if (!config?.domains?.api) { 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.`) 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 // Prepare URL
if (!path.startsWith('/')) { if (!path.startsWith("/")) {
path = `/${path}` path = `/${path}`;
} }
const url = `${config.domains.api}${path}` const url = `${config.domains.api}${path}`;
// Set headers // Set headers
headers = Object.assign( headers = Object.assign({ "Content-Type": "application/json" }, headers);
{ 'Content-Type': 'application/json' },
headers
)
// Default options are marked with * // Default options are marked with *
const response = await fetch(url, { const response = await fetch(url, {
method: method.toUpperCase(), method: method.toUpperCase(),
mode: 'cors', mode: "cors",
cache: 'no-cache', cache: "no-cache",
headers, headers,
body: data ? JSON.stringify(data) : null body: data ? JSON.stringify(data) : null,
}) });
if (response.status < 200 || response.status >= 300) { if (response.status < 200 || response.status >= 300) {
const error = await response.json() const error = await response.json();
throw new Error(error.error) throw new Error(error.error);
} }
return await response.json() return await response.json();
} };

View File

@@ -1,17 +1,20 @@
import Cookies from 'js-cookie' import Cookies from "js-cookie";
/** /**
* Format Org and Username correctly for the Serverless Platform backend * Format Org and Username correctly for the Serverless Platform backend
*/ */
export const formatOrgAndUsername = (name = '') => { export const formatOrgAndUsername = (name = "") => {
name = name.toString().toLowerCase().replace(/[^a-z\d-]+/gi, '-') name = name
.toString()
.toLowerCase()
.replace(/[^a-z\d-]+/gi, "-");
// Remove multiple instances of hyphens // Remove multiple instances of hyphens
name = name.replace(/-{2,}/g, '-') name = name.replace(/-{2,}/g, "-");
if (name.length > 40) { if (name.length > 40) {
name = name.substring(0, 40) name = name.substring(0, 40);
} }
return name return name;
} };
/** /**
* Parse query parameters in a URL * Parse query parameters in a URL
@@ -19,58 +22,60 @@ export const formatOrgAndUsername = (name = '') => {
*/ */
export const parseQueryParams = (searchString = null) => { export const parseQueryParams = (searchString = null) => {
if (!searchString) { if (!searchString) {
return null return null;
} }
// Clone string // Clone string
let clonedParams = (' ' + searchString).slice(1) let clonedParams = (" " + searchString).slice(1);
return clonedParams return clonedParams
.substr(1) .substr(1)
.split('&') .split("&")
.filter((el) => el.length) .filter((el) => el.length)
.map((el) => el.split('=')) .map((el) => el.split("="))
.reduce( .reduce(
(accumulator, currentValue) => (accumulator, currentValue) =>
Object.assign(accumulator, { Object.assign(accumulator, {
[decodeURIComponent(currentValue.shift())]: decodeURIComponent(currentValue.pop()) [decodeURIComponent(
currentValue.shift()
)]: decodeURIComponent(currentValue.pop()),
}), }),
{} {}
) );
} };
/** /**
* Parse hash fragment parameters in a URL * Parse hash fragment parameters in a URL
*/ */
export const parseHashFragment = (hashString) => { export const parseHashFragment = (hashString) => {
const hashData = {} const hashData = {};
let hash = decodeURI(hashString) let hash = decodeURI(hashString);
hash = hash.split('&') hash = hash.split("&");
hash.forEach((val) => { hash.forEach((val) => {
val = val.replace('#', '') val = val.replace("#", "");
hashData[val.split('=')[0]] = val.split('=')[1] hashData[val.split("=")[0]] = val.split("=")[1];
}) });
return hashData return hashData;
} };
/** /**
* Save session in browser cookie * Save session in browser cookie
*/ */
export const saveSession = (userId, userEmail, userToken) => { export const saveSession = (userId, userEmail, userToken) => {
Cookies.set('serverless', { userId, userEmail, userToken }) Cookies.set("serverless", { userId, userEmail, userToken });
} };
/** /**
* Get session in browser cookie * Get session in browser cookie
*/ */
export const getSession = () => { export const getSession = () => {
const data = Cookies.get('serverless') const data = Cookies.get("serverless");
return data ? JSON.parse(data) : null return data ? JSON.parse(data) : null;
} };
/** /**
* Delete session in browser cookie * Delete session in browser cookie
*/ */
export const deleteSession = () => { export const deleteSession = () => {
Cookies.remove('serverless') Cookies.remove("serverless");
} };

View File

@@ -1,2 +1,2 @@
export * from './helpers' export * from "./helpers";
export * from './api' export * from "./api";