Skip to content

Commit

Permalink
Merge pull request #28 from boringContributor/auth-form
Browse files Browse the repository at this point in the history
refactor: improve the auth component
  • Loading branch information
MaxLeiter committed Mar 14, 2022
2 parents 80bcf68 + a361b16 commit 10c8b02
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 69 deletions.
17 changes: 9 additions & 8 deletions client/components/auth/auth.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,18 @@
}

.form {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
display: grid;
place-items: center;
}

.formGroup {
margin-bottom: 1rem;
display: flex;
flex-direction: column;
place-items: center;
gap: 10px;
}

.formHeader {
.formContentSpace {
margin-bottom: 1rem;
}
text-align: center;
}
100 changes: 46 additions & 54 deletions client/components/auth/index.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
import { FormEvent, useState } from 'react'
import { Button, Card, Input, Text } from '@geist-ui/core'
import { Button, Input, Text, useToasts, Note } from '@geist-ui/core'
import styles from './auth.module.css'
import { useRouter } from 'next/router'
import Link from '../Link'

const NO_EMPTY_SPACE_REGEX = /^\S*$/;
const ERROR_MESSAGE = "Provide a non empty username and a password with at least 6 characters";

const Auth = ({ page }: { page: "signup" | "signin" }) => {
const router = useRouter();

const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [errorMsg, setErrorMsg] = useState('');

const signingIn = page === 'signin'
const { setToast } = useToasts();

const NO_EMPTY_SPACE_REGEX = /^\S*$/;
const signingIn = page === 'signin'

const handleJson = (json: any) => {
if (json.error) return setError(json.error.message)

localStorage.setItem('drift-token', json.token)
localStorage.setItem('drift-userid', json.userId)
router.push('/')
Expand All @@ -27,11 +28,8 @@ const Auth = ({ page }: { page: "signup" | "signin" }) => {
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault()

if (!username.match(NO_EMPTY_SPACE_REGEX))
return setError("Username can't be empty")

if (!password.match(NO_EMPTY_SPACE_REGEX))
return setError("Password can't be empty")
if (!NO_EMPTY_SPACE_REGEX.test(username) || password.length < 6) return setErrorMsg(ERROR_MESSAGE)
else setErrorMsg('');

const reqOpts = {
method: 'POST',
Expand All @@ -50,58 +48,52 @@ const Auth = ({ page }: { page: "signup" | "signin" }) => {

handleJson(json)
} catch (err: any) {
setError(err.message || "Something went wrong")
setToast({ text: "Something went wrong", type: 'error' })
}
}

return (
<div className={styles.container}>
<div className={styles.form}>
<div className={styles.formHeader}>
<div className={styles.formContentSpace}>
<h1>{signingIn ? 'Sign In' : 'Sign Up'}</h1>
</div>
<form onSubmit={handleSubmit}>
<Card>
<div className={styles.formGroup}>
<Input
htmlType="text"
id="username"
value={username}
onChange={(event) => setUsername(event.target.value)}
placeholder="Username"
required
label='Username'
/>
</div>
<div className={styles.formGroup}>
<Input
htmlType='password'
id="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
placeholder="Password"
required
label='Password'
/>
</div>
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Button type="success" ghost htmlType="submit">{signingIn ? 'Sign In' : 'Sign Up'}</Button>
</div>
<div className={styles.formGroup}>
{signingIn ? (
<Text>
Don&apos;t have an account?{" "}
<Link color href="/signup">Sign up</Link>
</Text>
) : (
<Text>
Already have an account?{" "}
<Link color href="/signin">Sign in</Link>
</Text>
)}
</div>
{error && <Text type='error'>{error}</Text>}
</Card>
<div className={styles.formGroup}>
<Input
htmlType="text"
id="username"
value={username}
onChange={(event) => setUsername(event.target.value)}
placeholder="Username"
required
scale={4 / 3}
/>
<Input
htmlType='password'
id="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
placeholder="Password"
required
scale={4 / 3}
/>
<Button type="success" htmlType="submit">{signingIn ? 'Sign In' : 'Sign Up'}</Button>
</div>
<div className={styles.formContentSpace}>
{signingIn ? (
<Text>
Don&apos;t have an account?{" "}
<Link color href="/signup">Sign up</Link>
</Text>
) : (
<Text>
Already have an account?{" "}
<Link color href="/signin">Sign in</Link>
</Text>
)}
</div>
{errorMsg && <Note scale={0.75} type='error'>{errorMsg}</Note>}
</form>
</div>
</div >
Expand Down
17 changes: 10 additions & 7 deletions server/src/routes/auth.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
import { Router } from 'express'
// import { Movie } from '../models/Post'
import { genSalt, hash, compare } from "bcrypt"
import { User } from '../../lib/models/User'
import { sign } from 'jsonwebtoken'
import config from '../../lib/config'
import jwt from '../../lib/middleware/jwt'

const NO_EMPTY_SPACE_REGEX = /^\S*$/

export const auth = Router()

const validateAuthPayload = (username: string, password: string): void => {
if (!NO_EMPTY_SPACE_REGEX.test(username) || password.length < 6) {
throw new Error("Authentication data does not fulfill requirements")
}
}

auth.post('/signup', async (req, res, next) => {
try {
if (!req.body.username || !req.body.password) {
throw new Error("Please provide a username and password")
}
validateAuthPayload(req.body.username, req.body.password)

const username = req.body.username.toLowerCase();

Expand All @@ -39,9 +44,7 @@ auth.post('/signup', async (req, res, next) => {

auth.post('/signin', async (req, res, next) => {
try {
if (!req.body.username || !req.body.password) {
throw new Error("Missing username or password")
}
validateAuthPayload(req.body.username, req.body.password)

const username = req.body.username.toLowerCase();
const user = await User.findOne({ where: { username: username } });
Expand Down

1 comment on commit 10c8b02

@vercel
Copy link

@vercel vercel bot commented on 10c8b02 Mar 14, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.