Merge pull request #17 from jedmund/auth-cleanup

Cleanup sign up and login modals
This commit is contained in:
Justin Edmund 2022-02-28 16:42:14 -08:00 committed by GitHub
commit 210b30ac2b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 340 additions and 264 deletions

View file

@ -132,5 +132,7 @@
.text {
color: inherit;
display: block;
width: 100%;
}
}

View file

@ -12,7 +12,7 @@ interface Props {
const Fieldset = React.forwardRef<HTMLInputElement, Props>(function fieldSet(props, ref) {
const fieldType = (['password', 'confirm_password'].includes(props.fieldName)) ? 'password' : 'text'
return (
<fieldset className="Fieldset">
<input

View file

@ -19,10 +19,6 @@ interface Props {
}
const HeaderMenu = (props: Props) => {
const { open: signupOpen, openModal: openSignupModal, closeModal: closeSignupModal } = useSignupModal()
const { open: loginOpen, openModal: openLoginModal, closeModal: closeLoginModal } = useLoginModal()
const { open: aboutOpen, openModal: openAboutModal, closeModal: closeAboutModal } = useAboutModal()
function authItems() {
return (
<nav>
@ -74,25 +70,9 @@ const HeaderMenu = (props: Props) => {
</li>
</div>
<div className="MenuGroup">
<li className="MenuItem" onClick={openLoginModal}>
<span>Log in</span>
</li>
{loginOpen ? (
<LoginModal
close={closeLoginModal}
/>
) : null}
<li className="MenuItem" onClick={openSignupModal}>
<span>Sign up</span>
</li>
{signupOpen ? (
<SignupModal
close={closeSignupModal}
/>
) : null}
<LoginModal />
<SignupModal />
</div>
</ul>
)
}

View file

@ -1,14 +1,31 @@
.LoginForm {
#fields {
display: flex;
flex-direction: column;
gap: $unit;
}
.fieldset {
display: flex;
flex-direction: column;
gap: 4px;
margin-bottom: 8px;
}
}
.Login.Dialog form {
display: flex;
flex-direction: column;
gap: $unit / 2;
margin-bottom: $unit;
.Button {
font-size: $font-regular;
padding: ($unit * 1.5) ($unit * 2);
width: 100%;
&.btn-disabled {
background: $grey-90;
color: $grey-70;
cursor: not-allowed;
}
&:not(.btn-disabled) {
background: $grey-90;
color: $grey-40;
&:hover {
background: $grey-80;
}
}
}
input {
background: $grey-90;
}
}

View file

@ -1,21 +1,18 @@
import React, { useState } from 'react'
import { withCookies, Cookies } from 'react-cookie'
import { createPortal } from 'react-dom'
import { useCookies } from 'react-cookie'
import * as Dialog from '@radix-ui/react-dialog'
import api from '~utils/api'
import { accountState } from '~utils/accountState'
import Button from '~components/Button'
import Fieldset from '~components/Fieldset'
import Modal from '~components/Modal'
import Overlay from '~components/Overlay'
import CrossIcon from '~public/icons/Cross.svg'
import './index.scss'
interface Props {
cookies: Cookies
close: () => void
}
interface Props {}
interface ErrorMap {
[index: string]: string
@ -26,31 +23,40 @@ interface ErrorMap {
const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
const LoginModal = (props: Props) => {
const emailInput: React.RefObject<HTMLInputElement> = React.createRef()
const passwordInput: React.RefObject<HTMLInputElement> = React.createRef()
const form: React.RefObject<HTMLInputElement>[] = [emailInput, passwordInput]
// Set up form states and error handling
const [formValid, setFormValid] = useState(false)
const [errors, setErrors] = useState<ErrorMap>({
email: '',
password: ''
})
function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
event.preventDefault()
// Cookies
const [cookies, setCookies] = useCookies()
// States
const [open, setOpen] = useState(false)
// Set up form refs
const emailInput: React.RefObject<HTMLInputElement> = React.createRef()
const passwordInput: React.RefObject<HTMLInputElement> = React.createRef()
const form: React.RefObject<HTMLInputElement>[] = [emailInput, passwordInput]
function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
const { name, value } = event.target
let newErrors = errors
let newErrors = {...errors}
switch(name) {
case 'email':
errors.email = emailRegex.test(value)
? ''
: 'That email address is not valid'
if (value.length == 0)
newErrors.email = 'Please enter your email'
else if (!emailRegex.test(value))
newErrors.email = 'That email address is not valid'
else
newErrors.email = ''
break
case 'password':
errors.password = value.length == 0
newErrors.password = value.length == 0
? 'Please enter your password'
: ''
break
@ -60,10 +66,10 @@ const LoginModal = (props: Props) => {
}
setErrors(newErrors)
setFormValid(validateForm())
setFormValid(validateForm(newErrors))
}
function validateForm() {
function validateForm(errors: ErrorMap) {
let valid = true
Object.values(form).forEach(
@ -73,11 +79,11 @@ const LoginModal = (props: Props) => {
Object.values(errors).forEach(
(error) => error.length > 0 && (valid = false)
)
return valid
}
function submit(event: React.FormEvent) {
function login(event: React.FormEvent) {
event.preventDefault()
const body = {
@ -89,65 +95,76 @@ const LoginModal = (props: Props) => {
if (formValid) {
api.login(body)
.then((response) => {
const cookies = props.cookies
const cookieObj = {
user_id: response.data.user.id,
username: response.data.user.username,
access_token: response.data.access_token
}
cookies.set('user', cookieObj, { path: '/'})
setCookies('user', cookieObj, { path: '/'})
accountState.account.authorized = true
accountState.account.user = {
id: cookieObj.user_id,
username: cookieObj.username
}
props.close()
setOpen(false)
}, (error) => {
console.error(error)
})
}
}
return (
createPortal(
<div>
<Modal
title="Log in"
styleName="LoginForm"
close={ () => {} }
>
<form className="form" onSubmit={submit}>
<div id="fields">
<Fieldset
fieldName="email"
placeholder="Email address"
onChange={handleChange}
error={errors.email}
ref={emailInput}
/>
function openChange(open: boolean) {
setOpen(open)
setErrors({
email: '',
password: ''
})
}
<Fieldset
fieldName="password"
placeholder="Password"
onChange={handleChange}
error={errors.password}
ref={passwordInput}
/>
</div>
<div id="ModalBottom">
<a>Forgot your password?</a>
<Button disabled={!formValid}>Log in</Button>
</div>
return (
<Dialog.Root open={open} onOpenChange={openChange}>
<Dialog.Trigger asChild>
<li className="MenuItem">
<span>Log in</span>
</li>
</Dialog.Trigger>
<Dialog.Portal>
<Dialog.Content className="Login Dialog" onOpenAutoFocus={ (event) => event.preventDefault() }>
<div className="DialogHeader">
<Dialog.Title className="DialogTitle">Log in</Dialog.Title>
<Dialog.Close className="DialogClose" asChild>
<span>
<CrossIcon />
</span>
</Dialog.Close>
</div>
<form className="form" onSubmit={login}>
<Fieldset
fieldName="email"
placeholder="Email address"
onChange={handleChange}
error={errors.email}
ref={emailInput}
/>
<Fieldset
fieldName="password"
placeholder="Password"
onChange={handleChange}
error={errors.password}
ref={passwordInput}
/>
<Button disabled={!formValid}>Log in</Button>
</form>
</Modal>
<Overlay onClick={props.close} />
</div>,
document.body
)
</Dialog.Content>
<Dialog.Overlay className="Overlay" />
</Dialog.Portal>
</Dialog.Root>
)
}
export default withCookies(LoginModal)
export default LoginModal

View file

@ -1,67 +1,47 @@
.SignupForm {
padding: 16px;
}
.SignupForm form {
margin: 0;
}
.SignupForm #fields {
.Signup.Dialog form {
display: flex;
flex-direction: column;
gap: 4px;
margin-bottom: 8px;
}
gap: $unit / 2;
margin-bottom: $unit;
#ModalTop {
display: flex;
flex-direction: row;
align-items: center;
margin-bottom: 16px;
margin-right: -8px;
}
.Button {
font-size: $font-regular;
padding: ($unit * 1.5) ($unit * 2);
width: 100%;
#ModalTop h1 {
margin: 0;
font-size: $font-xlarge;
text-align: left;
flex-grow: 1;
}
&.btn-disabled {
background: $grey-90;
color: $grey-70;
cursor: not-allowed;
}
#ModalTop i {
padding: 8px;
}
&:not(.btn-disabled) {
background: $grey-90;
color: $grey-40;
#ModalTop i:hover {
cursor: pointer;
}
&:hover {
background: $grey-80;
}
}
}
#ModalTop i:hover svg {
color: #444;
}
.terms {
color: $grey-40;
font-size: $font-small;
line-height: 1.2;
margin-top: $unit;
text-align: center;
#ModalTop svg {
color: #888;
height: 18px;
width: 18px;
transform: rotate(45deg);
}
a {
color: $blue;
#ModalBottom {
display: flex;
flex-direction: row;
justify-content: flex-end;
}
&:hover {
color: darken($blue, 30);
}
}
}
#ModalBottom a {
color: #666;
font-size: $font-regular;
font-weight: 500;
flex-grow: 1;
display: flex;
align-items: center;
}
#ModalBottom .Button {
min-width: 88px;
input {
background: $grey-90;
}
}

View file

@ -1,21 +1,18 @@
import React, { useState } from 'react'
import { withCookies, Cookies } from 'react-cookie'
import { createPortal } from 'react-dom'
import { useCookies } from 'react-cookie'
import * as Dialog from '@radix-ui/react-dialog'
import api from '~utils/api'
import { accountState } from '~utils/accountState'
import Button from '~components/Button'
import Fieldset from '~components/Fieldset'
import Modal from '~components/Modal'
import Overlay from '~components/Overlay'
import CrossIcon from '~public/icons/Cross.svg'
import './index.scss'
interface Props {
cookies: Cookies
close: () => void
}
interface Props {}
interface ErrorMap {
[index: string]: string
@ -28,6 +25,7 @@ interface ErrorMap {
const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
const SignupModal = (props: Props) => {
// Set up form states and error handling
const [formValid, setFormValid] = useState(false)
const [errors, setErrors] = useState<ErrorMap>({
username: '',
@ -35,34 +33,21 @@ const SignupModal = (props: Props) => {
password: '',
passwordConfirmation: ''
})
// Cookies
const [cookies, setCookies] = useCookies()
// States
const [open, setOpen] = useState(false)
// Set up form refs
const usernameInput = React.createRef<HTMLInputElement>()
const emailInput = React.createRef<HTMLInputElement>()
const passwordInput = React.createRef<HTMLInputElement>()
const passwordConfirmationInput = React.createRef<HTMLInputElement>()
const form = [usernameInput, emailInput, passwordInput, passwordConfirmationInput]
function check(event: React.ChangeEvent<HTMLInputElement>) {
const name = event.target.name
const value = event.target.value
if (value.length > 0 && errors[name].length == 0) {
const newErrors = {...errors}
api.check(name, value)
.then((response) => {
if (!response.data.available) {
newErrors[name] = `This ${name} is already in use`
}
setErrors(newErrors)
}, (error) => {
console.error(error)
})
}
}
function process(event: React.FormEvent) {
function register(event: React.FormEvent) {
event.preventDefault()
const body = {
@ -74,50 +59,76 @@ const SignupModal = (props: Props) => {
}
}
if (formValid) {
if (formValid)
api.endpoints.users.create(body)
.then((response) => {
const cookies = props.cookies
cookies.set('user', response.data.user, { path: '/'})
// Set cookies
setCookies('user', response.data.user, { path: '/'})
// Set states
accountState.account.authorized = true
accountState.account.user = {
id: response.data.user.id,
username: response.data.user.username
}
props.close()
// Close the modal
setOpen(false)
}, (error) => {
console.error(error)
})
.catch(error => {
console.error(error)
})
}
function handleNameChange(event: React.ChangeEvent<HTMLInputElement>) {
event.preventDefault()
const fieldName = event.target.name
const value = event.target.value
if (value.length >= 3) {
api.check(fieldName, value)
.then((response) => {
processNameCheck(fieldName, value, response.data.available)
}, (error) => {
console.error(error)
})
} else {
validateName(fieldName, value)
}
}
function validateForm() {
let valid = true
function processNameCheck(fieldName: string, value: string, available: boolean) {
const newErrors = {...errors}
Object.values(form).forEach(
(input) => input.current?.value.length == 0 && (valid = false)
)
if (available) {
// Continue checking for errors
newErrors[fieldName] = ''
setErrors(newErrors)
setFormValid(true)
Object.values(errors).forEach(
(error) => error.length > 0 && (valid = false)
)
return valid
validateName(fieldName, value)
} else {
newErrors[fieldName] = `This ${fieldName} is already in use`
setErrors(newErrors)
setFormValid(false)
}
}
function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
event.preventDefault()
const { name, value } = event.target
function validateName(fieldName: string, value: string) {
let newErrors = {...errors}
switch(name) {
switch(fieldName) {
case 'username':
newErrors.username = value.length < 3
? 'Username must be at least 3 characters'
: ''
if (value.length < 3)
newErrors.username = 'Username must be at least 3 characters'
else if (value.length > 20)
newErrors.username = 'Username must be less than 20 characters'
else
newErrors.username = ''
break
case 'email':
@ -126,6 +137,21 @@ const SignupModal = (props: Props) => {
: 'That email address is not valid'
break
default:
break
}
setErrors(newErrors)
setFormValid(validateForm(newErrors))
}
function handlePasswordChange(event: React.ChangeEvent<HTMLInputElement>) {
event.preventDefault()
const { name, value } = event.target
let newErrors = {...errors}
switch(name) {
case 'password':
newErrors.password = passwordInput.current?.value.includes(usernameInput.current?.value!)
? 'Your password should not contain your username'
@ -149,64 +175,96 @@ const SignupModal = (props: Props) => {
}
setErrors(newErrors)
setFormValid(validateForm())
setFormValid(validateForm(newErrors))
}
function validateForm(errors: ErrorMap) {
let valid = true
Object.values(form).forEach(
(input) => input.current?.value.length == 0 && (valid = false)
)
Object.values(errors).forEach(
(error) => error.length > 0 && (valid = false)
)
return valid
}
function openChange(open: boolean) {
setOpen(open)
setErrors({
username: '',
email: '',
password: '',
passwordConfirmation: ''
})
}
return (
createPortal(
<div>
<Modal
title="Sign up"
styleName="SignupForm"
close={ () => {} }
>
<form className="form" onSubmit={process}>
<div id="fields">
<Fieldset
fieldName="username"
placeholder="Username"
onBlur={check}
onChange={handleChange}
error={errors.username}
ref={usernameInput}
/>
<Dialog.Root open={open} onOpenChange={openChange}>
<Dialog.Trigger asChild>
<li className="MenuItem">
<span>Sign up</span>
</li>
</Dialog.Trigger>
<Dialog.Portal>
<Dialog.Content className="Signup Dialog" onOpenAutoFocus={ (event) => event.preventDefault() }>
<div className="DialogHeader">
<Dialog.Title className="DialogTitle">Sign up</Dialog.Title>
<Dialog.Close className="DialogClose" asChild>
<span>
<CrossIcon />
</span>
</Dialog.Close>
</div>
<Fieldset
fieldName="email"
placeholder="Email address"
onBlur={check}
onChange={handleChange}
error={errors.email}
ref={emailInput}
/>
<form className="form" onSubmit={register}>
<Fieldset
fieldName="username"
placeholder="Username"
onChange={handleNameChange}
error={errors.username}
ref={usernameInput}
/>
<Fieldset
fieldName="password"
placeholder="Password"
onChange={handleChange}
error={errors.password}
ref={passwordInput}
/>
<Fieldset
fieldName="email"
placeholder="Email address"
onChange={handleNameChange}
error={errors.email}
ref={emailInput}
/>
<Fieldset
fieldName="confirm_password"
placeholder="Password (again)"
onChange={handleChange}
error={errors.passwordConfirmation}
ref={passwordConfirmationInput}
/>
</div>
<div id="ModalBottom">
<Button disabled={!formValid}>Sign up</Button>
</div>
<Fieldset
fieldName="password"
placeholder="Password"
onChange={handlePasswordChange}
error={errors.password}
ref={passwordInput}
/>
<Fieldset
fieldName="confirm_password"
placeholder="Password (again)"
onChange={handlePasswordChange}
error={errors.passwordConfirmation}
ref={passwordConfirmationInput}
/>
<Button disabled={!formValid}>Sign up</Button>
<Dialog.Description className="terms">
By signing up, I agree to the<br /><a href="#">Terms and Conditions</a> and <a href="#">Usage Guidelines</a>.
</Dialog.Description>
</form>
</Modal>
<Overlay onClick={props.close} />
</div>,
document.body
)
</Dialog.Content>
<Dialog.Overlay className="Overlay" />
</Dialog.Portal>
</Dialog.Root>
)
}
export default withCookies(SignupModal)
export default SignupModal

View file

@ -5,7 +5,7 @@ import clonedeep from 'lodash.clonedeep'
import { useSnapshot } from 'valtio'
import api from '~utils/api'
import { accountState } from '~utils/accountState'
import { accountState, initialAccountState } from '~utils/accountState'
import { appState, initialAppState } from '~utils/appState'
import Header from '~components/Header'
@ -51,10 +51,15 @@ const TopHeader = () => {
function logout() {
removeCookie('user')
accountState.authorized = false
// Clean state
const resetState = clonedeep(initialAccountState)
Object.keys(resetState).forEach((key) => {
if (key !== 'language')
accountState[key] = resetState[key]
})
appState.party.editable = false
// TODO: How can we log out without navigating to root
router.push('/')
return false
}

View file

@ -90,16 +90,18 @@ select {
}
.Dialog {
$multiplier: 4;
animation: 0.5s cubic-bezier(0.16, 1, 0.3, 1) 0s 1 normal none running openModal;
background: white;
border-radius: $unit;
display: flex;
flex-direction: column;
gap: $unit * 3;
gap: $unit * $multiplier;
height: auto;
min-width: $unit * 48;
min-height: $unit * 12;
padding: $unit * 3;
padding: $unit * $multiplier;
position: absolute;
top: 50%;
left: 50%;
@ -108,28 +110,43 @@ select {
.DialogHeader {
display: flex;
gap: $unit;
.left {
display: flex;
flex-direction: column;
flex-grow: 1;
gap: $unit;
p {
color: $grey-40;
font-size: $font-small;
line-height: 1.25;
}
}
}
.DialogClose {
background: transparent;
height: 21px;
width: 21px;
&:hover {
cursor: pointer;
svg {
fill: $grey-00;
fill: $error;
}
}
svg {
fill: $grey-40;
float: right;
height: 24px;
width: 24px;
}
}
.DialogTitle {
font-size: $font-large;
font-size: $font-xlarge;
flex-grow: 1;
}