Merge pull request 'feature/#7' (#18) from feature/#7 into develop
Reviewed-on: Netzbegruenung/candymat#18
This commit is contained in:
commit
9cb707eede
|
@ -2,8 +2,8 @@
|
|||
create table candymat_data.person
|
||||
(
|
||||
id serial primary key,
|
||||
first_name character varying(200),
|
||||
last_name character varying(200),
|
||||
first_name character varying(200) check (first_name <> ''),
|
||||
last_name character varying(200) check (last_name <> ''),
|
||||
about character varying(2000),
|
||||
created_at timestamp default now(),
|
||||
role candymat_data.role not null default 'candymat_person'
|
||||
|
|
|
@ -16,13 +16,23 @@ grant execute on function candymat_data.current_person() to candymat_person;
|
|||
|
||||
create function candymat_data.register_person(
|
||||
first_name text,
|
||||
last_name text,
|
||||
email text,
|
||||
password text
|
||||
) returns candymat_data.person as $$
|
||||
last_name text,
|
||||
email text,
|
||||
password text
|
||||
) returns candymat_data.person as
|
||||
$$
|
||||
declare
|
||||
person candymat_data.person;
|
||||
begin
|
||||
if (trim(register_person.first_name) <> '') is not true then
|
||||
raise 'Invalid first name: ''%''', register_person.first_name;
|
||||
end if;
|
||||
if (trim(register_person.last_name) <> '') is not true then
|
||||
raise 'Invalid last name: ''%''', register_person.last_name;
|
||||
end if;
|
||||
if (trim(register_person.password) <> '') is not true then
|
||||
raise 'Invalid password.';
|
||||
end if;
|
||||
insert into candymat_data.person (first_name, last_name)
|
||||
values ($1, $2)
|
||||
returning * into person;
|
||||
|
@ -31,8 +41,10 @@ begin
|
|||
values (person.id, $3, crypt($4, gen_salt('bf')));
|
||||
|
||||
return person;
|
||||
end;
|
||||
$$ language plpgsql strict security definer;
|
||||
end ;
|
||||
$$ language plpgsql strict
|
||||
security definer;
|
||||
|
||||
grant execute on function candymat_data.register_person(text, text, text, text) to candymat_anonymous;
|
||||
|
||||
create function candymat_data.authenticate(
|
||||
|
|
|
@ -11,13 +11,26 @@ The app is written in typescript and react and uses apollo to query the backend
|
|||
|
||||
* Install `npm`
|
||||
* In this directory run `npm ci` to install all dependencies according to the package.json and package-lock.json.
|
||||
*
|
||||
|
||||
## Available Scripts
|
||||
### Develop locally
|
||||
|
||||
* In the parent directory run
|
||||
```shell script
|
||||
docker-compose up
|
||||
```
|
||||
which will start the whole setup including this app in a dockerfile.
|
||||
However, rebuilding and restarting this image can be cumbersome and is not necessary in the development setup.
|
||||
* Instead run
|
||||
```shell script
|
||||
npm start
|
||||
```
|
||||
and access the app at [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
#### Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
##### `npm start`
|
||||
|
||||
Runs the app in the development mode.<br>
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||
|
@ -28,12 +41,12 @@ You will also see any lint errors in the console.
|
|||
Running the app without the backend server makes little sense.
|
||||
Start it under [http://localhost:5000](http://localhost:5000) as specified in the Readme of the backend server (../backend)
|
||||
|
||||
### `npm test`
|
||||
##### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.<br>
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
##### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.<br>
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
@ -43,7 +56,7 @@ Your app is ready to be deployed!
|
|||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
##### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@ WORKDIR /app
|
|||
|
||||
COPY package*.json ./
|
||||
|
||||
RUN npm install
|
||||
RUN npm ci
|
||||
|
||||
COPY public ./public
|
||||
COPY tsconfig.json logo.svg ./
|
||||
|
|
2404
redaktions-app/package-lock.json
generated
2404
redaktions-app/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
@ -6,23 +6,29 @@
|
|||
"@apollo/client": "^3.1.3",
|
||||
"@material-ui/core": "^4.11.0",
|
||||
"@material-ui/icons": "^4.9.1",
|
||||
"@testing-library/jest-dom": "^4.2.4",
|
||||
"@testing-library/react": "^9.5.0",
|
||||
"@material-ui/lab": "^4.0.0-alpha.57",
|
||||
"@testing-library/user-event": "^7.2.1",
|
||||
"graphql": "^15.3.0",
|
||||
"react": "^16.13.1",
|
||||
"react-dom": "^16.13.1",
|
||||
"react-router-dom": "^5.2.0",
|
||||
"react-scripts": "^3.4.4",
|
||||
"typescript": "^3.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/jest-dom": "^5.11.4",
|
||||
"@testing-library/react": "^11.1.0",
|
||||
"@types/jest": "^24.9.1",
|
||||
"@types/node": "^12.12.54",
|
||||
"@types/react": "^16.9.46",
|
||||
"@types/react-dom": "^16.9.8",
|
||||
"graphql": "^15.3.0",
|
||||
"react": "^16.13.1",
|
||||
"react-dom": "^16.13.1",
|
||||
"react-scripts": "3.4.3",
|
||||
"typescript": "^3.7.5"
|
||||
"@types/react-router-dom": "^5.1.5",
|
||||
"jest-environment-jsdom-sixteen": "^1.0.3"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"test": "react-scripts test --env=jest-environment-jsdom-sixteen",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
|
|
|
@ -1,9 +0,0 @@
|
|||
import React from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import App from './App';
|
||||
|
||||
test('renders learn react link', () => {
|
||||
const { getByText } = render(<App />);
|
||||
const linkElement = getByText(/learn react/i);
|
||||
expect(linkElement).toBeInTheDocument();
|
||||
});
|
|
@ -1,19 +1,61 @@
|
|||
import React from 'react';
|
||||
import './App.css';
|
||||
import SignIn from "./components/SignIn";
|
||||
import {ApolloProvider} from "@apollo/client";
|
||||
import {client} from "./backend-connection/helper";
|
||||
import React from "react";
|
||||
import Main from "./components/Main";
|
||||
import {Redirect, Route, Switch} from "react-router-dom";
|
||||
import SignIn from "./components/SignIn";
|
||||
import SignUp from "./components/SignUp";
|
||||
|
||||
|
||||
function App() {
|
||||
|
||||
return (
|
||||
<ApolloProvider client={client}>
|
||||
{localStorage.getItem("token")
|
||||
? <Main />
|
||||
: <SignIn/>}
|
||||
</ApolloProvider>
|
||||
<Switch>
|
||||
<PrivateRoute exact path={"/"}><Main /></PrivateRoute>
|
||||
<NotLoggedInOnlyRoute path={"/login"}><SignIn /></NotLoggedInOnlyRoute>
|
||||
<NotLoggedInOnlyRoute path={"/signup"}><SignUp /></NotLoggedInOnlyRoute>
|
||||
</Switch>
|
||||
)
|
||||
}
|
||||
|
||||
export const isLoggedIn = () => !!localStorage.getItem("token")
|
||||
|
||||
// @ts-ignore
|
||||
function PrivateRoute({ children, ...rest }) {
|
||||
return (
|
||||
<Route
|
||||
{...rest}
|
||||
render={({ location }) =>
|
||||
isLoggedIn() ? (
|
||||
children
|
||||
) : (
|
||||
<Redirect
|
||||
to={{
|
||||
pathname: "/login",
|
||||
state: { from: location }
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
function NotLoggedInOnlyRoute({ children, ...rest }) {
|
||||
return (
|
||||
<Route
|
||||
{...rest}
|
||||
render={({ location }) =>
|
||||
!isLoggedIn() ? (
|
||||
children
|
||||
) : (
|
||||
<Redirect
|
||||
to={{
|
||||
pathname: "/",
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
@ -27,7 +27,7 @@ const useStyles = makeStyles((theme: Theme) =>
|
|||
|
||||
interface ButtonWithSpinnerProps {
|
||||
children: string,
|
||||
handleClick: () => void,
|
||||
handleClick?: () => void,
|
||||
loading: boolean
|
||||
type?: "button" | "submit",
|
||||
fullWidth?: boolean,
|
||||
|
|
|
@ -5,6 +5,7 @@ import MenuIcon from '@material-ui/icons/Menu';
|
|||
import Menu from '@material-ui/core/Menu';
|
||||
import AccountCircle from '@material-ui/icons/AccountCircle';
|
||||
import {makeStyles} from "@material-ui/core/styles";
|
||||
import {useHistory} from 'react-router-dom';
|
||||
|
||||
|
||||
const useStyles = makeStyles({
|
||||
|
@ -20,6 +21,7 @@ function CustomAppBar() {
|
|||
const classes = useStyles()
|
||||
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
|
||||
const open = Boolean(anchorEl);
|
||||
const history = useHistory();
|
||||
|
||||
const handleMenu = (event: React.MouseEvent<HTMLElement>) => {
|
||||
setAnchorEl(event.currentTarget);
|
||||
|
@ -27,7 +29,7 @@ function CustomAppBar() {
|
|||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('token')
|
||||
window.location.href = window.location.origin
|
||||
history.replace("/login")
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import CustomAppBar from "./CustomAppBar";
|
||||
import {Box, Container, Grid, Paper} from "@material-ui/core";
|
||||
import {Container, Paper} from "@material-ui/core";
|
||||
import React from "react";
|
||||
import clsx from "clsx";
|
||||
import {makeStyles} from "@material-ui/core/styles";
|
||||
|
|
|
@ -4,10 +4,11 @@ import CssBaseline from '@material-ui/core/CssBaseline';
|
|||
import TextField from '@material-ui/core/TextField';
|
||||
import FormControlLabel from '@material-ui/core/FormControlLabel';
|
||||
import Checkbox from '@material-ui/core/Checkbox';
|
||||
import Link from '@material-ui/core/Link';
|
||||
import Grid from '@material-ui/core/Grid';
|
||||
import Box from '@material-ui/core/Box';
|
||||
import {Alert} from '@material-ui/lab';
|
||||
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
|
||||
import {Link, useHistory, useLocation} from 'react-router-dom';
|
||||
import Typography from '@material-ui/core/Typography';
|
||||
import {makeStyles} from '@material-ui/core/styles';
|
||||
import Container from '@material-ui/core/Container';
|
||||
|
@ -33,30 +34,42 @@ const useStyles = makeStyles((theme) => ({
|
|||
submit: {
|
||||
margin: theme.spacing(3, 0, 2),
|
||||
},
|
||||
error: {
|
||||
color: 'red',
|
||||
alert: {
|
||||
margin: theme.spacing(1)
|
||||
}
|
||||
}));
|
||||
|
||||
|
||||
export default function SignIn() {
|
||||
const history = useHistory();
|
||||
const queryParams = new URLSearchParams(useLocation().search);
|
||||
const classes = useStyles();
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [login, { loading, error, data }] = useMutation(loginMutation);
|
||||
const classes = useStyles();
|
||||
|
||||
if (data && data.authenticate.jwtToken) {
|
||||
localStorage.setItem("token", data.authenticate.jwtToken)
|
||||
window.location.reload()
|
||||
return <span>{`Success!`}</span>
|
||||
}
|
||||
const [error, setError] = useState("");
|
||||
const [login, {loading}] = useMutation<LoginMutationResponse, LoginMutationVariables>(
|
||||
loginMutation,
|
||||
{
|
||||
onCompleted(data) {
|
||||
if (data.authenticate.jwtToken) {
|
||||
localStorage.setItem("token", data.authenticate.jwtToken)
|
||||
history.replace("/")
|
||||
} else {
|
||||
setError("Wrong username or password.")
|
||||
}
|
||||
},
|
||||
onError(e) {
|
||||
setError(`Error while trying to log in: ${e.message}`)
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return (
|
||||
<Container component="main" maxWidth="xs">
|
||||
<CssBaseline />
|
||||
<CssBaseline/>
|
||||
<div className={classes.paper}>
|
||||
<Avatar className={classes.avatar}>
|
||||
<LockOutlinedIcon />
|
||||
<LockOutlinedIcon/>
|
||||
</Avatar>
|
||||
<Typography component="h1" variant="h5">
|
||||
Sign in
|
||||
|
@ -66,7 +79,7 @@ export default function SignIn() {
|
|||
noValidate
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
login({variables: {email: email, password: password}})
|
||||
login({variables: {email: email, password: password}}).catch(error => console.log(error))
|
||||
}}
|
||||
>
|
||||
<TextField
|
||||
|
@ -80,7 +93,10 @@ export default function SignIn() {
|
|||
autoComplete="email"
|
||||
autoFocus
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setEmail(e.target.value);
|
||||
setError("");
|
||||
}}
|
||||
/>
|
||||
<TextField
|
||||
variant="outlined"
|
||||
|
@ -93,51 +109,67 @@ export default function SignIn() {
|
|||
id="password"
|
||||
value={password}
|
||||
autoComplete="current-password"
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setPassword(e.target.value);
|
||||
setError("");
|
||||
}}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={<Checkbox value="remember" color="primary" />}
|
||||
disabled={true}
|
||||
control={<Checkbox value="remember" color="primary"/>}
|
||||
label="Remember me"
|
||||
/>
|
||||
<ButtonWithSpinner
|
||||
handleClick={() => {}}
|
||||
loading={loading}
|
||||
type="submit"
|
||||
fullWidth
|
||||
>Sign In</ButtonWithSpinner>
|
||||
<p className={classes.error}>
|
||||
{error
|
||||
? `Error while trying to log in: ${error.message}`
|
||||
: data && !data.authenticate.jwtToken ? "Wrong username or password" : ""}
|
||||
</p>
|
||||
>Sign In</ButtonWithSpinner>
|
||||
<Grid container>
|
||||
<Grid item xs>
|
||||
<Link href="#" variant="body2">
|
||||
Forgot password?
|
||||
</Link>
|
||||
{/* todo: see issue #17*/}
|
||||
{/*<Link to="/restore-password" aria-disabled={true}>*/}
|
||||
{/* Forgot password?*/}
|
||||
{/*</Link>*/}
|
||||
</Grid>
|
||||
<Grid item>
|
||||
<Link href="#" variant="body2">
|
||||
<Link to="/signup">
|
||||
{"Don't have an account? Sign Up"}
|
||||
</Link>
|
||||
</Grid>
|
||||
</Grid>
|
||||
{queryParams.get("recent-sign-up-success")
|
||||
? <Alert className={classes.alert} severity="success" onClose={() => history.push("/login")}>
|
||||
Sign-Up was successful. Log in to continue
|
||||
</Alert>
|
||||
: null}
|
||||
{error ? <Alert className={classes.alert} severity="error" onClose={() => setError("")}>{error}</Alert> : null}
|
||||
</form>
|
||||
</div>
|
||||
<Box mt={8}>
|
||||
<Copyright />
|
||||
<Copyright/>
|
||||
</Box>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
const loginMutation = gql`
|
||||
export const loginMutation = gql`
|
||||
mutation Login($email: String!, $password: String!) {
|
||||
authenticate(input: {email: $email, password: $password}) {
|
||||
jwtToken
|
||||
}
|
||||
}`
|
||||
|
||||
interface LoginMutationVariables {
|
||||
email: string,
|
||||
password: string
|
||||
}
|
||||
|
||||
export interface LoginMutationResponse {
|
||||
authenticate: {
|
||||
jwtToken: string | null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
226
redaktions-app/src/components/SignUp.tsx
Normal file
226
redaktions-app/src/components/SignUp.tsx
Normal file
|
@ -0,0 +1,226 @@
|
|||
import React, {ChangeEvent, useState} from 'react';
|
||||
import Avatar from '@material-ui/core/Avatar';
|
||||
import CssBaseline from '@material-ui/core/CssBaseline';
|
||||
import TextField from '@material-ui/core/TextField';
|
||||
import {Link, useHistory} from 'react-router-dom';
|
||||
import Grid from '@material-ui/core/Grid';
|
||||
import Box from '@material-ui/core/Box';
|
||||
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
|
||||
import Typography from '@material-ui/core/Typography';
|
||||
import {makeStyles} from '@material-ui/core/styles';
|
||||
import Container from '@material-ui/core/Container';
|
||||
import {Copyright} from "./Copyright";
|
||||
import {gql, useMutation} from "@apollo/client";
|
||||
import ButtonWithSpinner from "./ButtonWithSpinner";
|
||||
import {errorHandler, SignUpError} from "./SignUpErrorHandler";
|
||||
import {Alert} from "@material-ui/lab";
|
||||
|
||||
|
||||
const useStyles = makeStyles((theme) => ({
|
||||
paper: {
|
||||
marginTop: theme.spacing(8),
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
},
|
||||
avatar: {
|
||||
margin: theme.spacing(1),
|
||||
backgroundColor: theme.palette.secondary.main,
|
||||
},
|
||||
form: {
|
||||
width: '100%', // Fix IE 11 issue.
|
||||
marginTop: theme.spacing(3),
|
||||
},
|
||||
submit: {
|
||||
margin: theme.spacing(3, 0, 2),
|
||||
},
|
||||
error: {
|
||||
color: 'red',
|
||||
},
|
||||
alert: {
|
||||
margin: theme.spacing(1)
|
||||
}
|
||||
}));
|
||||
|
||||
export default function SignUp() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [firstName, setFirstName] = useState("");
|
||||
const [lastName, setLastName] = useState("");
|
||||
const [error, setError] = useState<SignUpError | undefined>(undefined)
|
||||
const history = useHistory();
|
||||
const [createAccount, {loading}] = useMutation<RegisterMutationResponse, RegisterMutationVariables>(
|
||||
registerMutation,
|
||||
{
|
||||
onCompleted() {
|
||||
history.push("/login?recent-sign-up-success=true")
|
||||
},
|
||||
onError(e) {
|
||||
console.error(e);
|
||||
setPassword("");
|
||||
setError(errorHandler(e))
|
||||
}
|
||||
}
|
||||
);
|
||||
const classes = useStyles();
|
||||
|
||||
|
||||
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
createAccount({variables: {firstName, lastName, email, password}});
|
||||
}
|
||||
|
||||
const onFirstNameChange = (e: ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
|
||||
setFirstName(e.target.value)
|
||||
if (error?.firstNameInvalid) {
|
||||
setError(undefined)
|
||||
}
|
||||
}
|
||||
|
||||
const onLastNameChange = (e: ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
|
||||
setLastName(e.target.value)
|
||||
if (error?.lastNameInvalid) {
|
||||
setError(undefined)
|
||||
}
|
||||
}
|
||||
|
||||
const onEmailChange = (e: ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
|
||||
setEmail(e.target.value)
|
||||
if (error?.emailInvalid) {
|
||||
setError(undefined)
|
||||
}
|
||||
}
|
||||
|
||||
const onPasswordChange = (e: ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
|
||||
setPassword(e.target.value)
|
||||
if (error?.passwordInvalid) {
|
||||
setError(undefined)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Container component="main" maxWidth="xs">
|
||||
<CssBaseline/>
|
||||
<div className={classes.paper}>
|
||||
<Avatar className={classes.avatar}>
|
||||
<LockOutlinedIcon/>
|
||||
</Avatar>
|
||||
<Typography component="h1" variant="h5">
|
||||
Sign up
|
||||
</Typography>
|
||||
<form className={classes.form} noValidate onSubmit={onSubmit}>
|
||||
<Grid container spacing={2}>
|
||||
<Grid item xs={12} sm={6}>
|
||||
<TextField
|
||||
autoComplete="fname"
|
||||
name="firstName"
|
||||
variant="outlined"
|
||||
required
|
||||
fullWidth
|
||||
id="firstName"
|
||||
label="First Name"
|
||||
autoFocus
|
||||
value={firstName}
|
||||
onChange={onFirstNameChange}
|
||||
error={error?.firstNameInvalid}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid item xs={12} sm={6}>
|
||||
<TextField
|
||||
variant="outlined"
|
||||
required
|
||||
fullWidth
|
||||
id="lastName"
|
||||
label="Last Name"
|
||||
name="lastName"
|
||||
autoComplete="lname"
|
||||
value={lastName}
|
||||
onChange={onLastNameChange}
|
||||
error={error?.lastNameInvalid}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid item xs={12}>
|
||||
<TextField
|
||||
variant="outlined"
|
||||
required
|
||||
fullWidth
|
||||
id="email"
|
||||
label="Email Address"
|
||||
name="email"
|
||||
autoComplete="email"
|
||||
value={email}
|
||||
onChange={onEmailChange}
|
||||
error={error?.emailInvalid}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid item xs={12}>
|
||||
<TextField
|
||||
variant="outlined"
|
||||
required
|
||||
fullWidth
|
||||
name="password"
|
||||
label="Password"
|
||||
type="password"
|
||||
id="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={onPasswordChange}
|
||||
error={error?.passwordInvalid}
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
<ButtonWithSpinner
|
||||
loading={loading}
|
||||
type="submit"
|
||||
fullWidth
|
||||
>
|
||||
Sign Up
|
||||
</ButtonWithSpinner>
|
||||
<Grid container justify="flex-end">
|
||||
<Grid item>
|
||||
<Link to="/login">
|
||||
Already have an account? Sign in
|
||||
</Link>
|
||||
</Grid>
|
||||
</Grid>
|
||||
{
|
||||
error
|
||||
? <Alert className={classes.alert} severity="error" onClose={() => setError(undefined)}>
|
||||
{error.message}
|
||||
</Alert>
|
||||
: null
|
||||
}
|
||||
</form>
|
||||
</div>
|
||||
<Box mt={5}>
|
||||
<Copyright/>
|
||||
</Box>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
const registerMutation = gql`
|
||||
mutation CreateAccount($firstName: String!, $lastName: String!, $email: String!, $password: String!) {
|
||||
registerPerson(input: {firstName: $firstName, lastName: $lastName, email: $email, password: $password}) {
|
||||
person {
|
||||
nodeId
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
interface RegisterMutationVariables {
|
||||
firstName: string,
|
||||
lastName: string,
|
||||
email: string,
|
||||
password: string,
|
||||
}
|
||||
|
||||
interface RegisterMutationResponse {
|
||||
registerPerson: {
|
||||
person: {
|
||||
nodeId: string
|
||||
}
|
||||
}
|
||||
}
|
||||
|
62
redaktions-app/src/components/SignUpErrorHandler.ts
Normal file
62
redaktions-app/src/components/SignUpErrorHandler.ts
Normal file
|
@ -0,0 +1,62 @@
|
|||
import {ApolloError} from "@apollo/client";
|
||||
|
||||
|
||||
export interface SignUpError {
|
||||
message: string,
|
||||
emailInvalid: boolean,
|
||||
firstNameInvalid: boolean,
|
||||
lastNameInvalid: boolean,
|
||||
passwordInvalid: boolean
|
||||
}
|
||||
|
||||
const parseErrorMessage = (error: ApolloError): string => {
|
||||
let result = "Sign-up failed because of the following reason(s): ";
|
||||
if (isEmailAlreadyUsed(error)) {
|
||||
result += "The E-Mail is already in use. "
|
||||
}
|
||||
if (isFirstNameInvalid(error)) {
|
||||
result += "The provided 'First Name' is invalid. "
|
||||
}
|
||||
if (isLastNameInvalid(error)) {
|
||||
result += "The provided 'Last Name' is invalid. "
|
||||
}
|
||||
if (isPasswordInvalid(error)) {
|
||||
result += "The provided password is invalid. "
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
const isEmailAlreadyUsed = (error: ApolloError): boolean => {
|
||||
const errorMessage = error.message.toLowerCase();
|
||||
|
||||
return errorMessage.includes("unique-constraint") && errorMessage.includes("email");
|
||||
}
|
||||
|
||||
const isFirstNameInvalid = (error: ApolloError): boolean => {
|
||||
const errorMessage = error.message.toLowerCase();
|
||||
|
||||
return errorMessage.includes("invalid") && errorMessage.includes("first name");
|
||||
}
|
||||
|
||||
const isLastNameInvalid = (error: ApolloError): boolean => {
|
||||
const errorMessage = error.message.toLowerCase();
|
||||
|
||||
return errorMessage.includes("invalid") && errorMessage.includes("last name");
|
||||
}
|
||||
|
||||
const isPasswordInvalid = (error: ApolloError): boolean => {
|
||||
const errorMessage = error.message.toLowerCase();
|
||||
|
||||
return errorMessage.includes("invalid") && errorMessage.includes("password");
|
||||
}
|
||||
|
||||
export const errorHandler = (error: undefined | ApolloError): undefined | SignUpError => {
|
||||
return error ? {
|
||||
message: parseErrorMessage(error),
|
||||
emailInvalid: isEmailAlreadyUsed(error),
|
||||
firstNameInvalid: isFirstNameInvalid(error),
|
||||
lastNameInvalid: isLastNameInvalid(error),
|
||||
passwordInvalid: isPasswordInvalid(error)
|
||||
} : undefined
|
||||
}
|
||||
|
|
@ -3,11 +3,16 @@ import ReactDOM from 'react-dom';
|
|||
import './index.css';
|
||||
import App from './App';
|
||||
import * as serviceWorker from './serviceWorker';
|
||||
import {ApolloProvider} from "@apollo/client";
|
||||
import {client} from "./backend-connection/helper";
|
||||
import {BrowserRouter as Router} from "react-router-dom";
|
||||
|
||||
ReactDOM.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
<ApolloProvider client={client}>
|
||||
<Router>
|
||||
<App/>
|
||||
</Router>
|
||||
</ApolloProvider>,
|
||||
document.getElementById('root')
|
||||
);
|
||||
|
||||
|
|
|
@ -0,0 +1,62 @@
|
|||
import React from 'react';
|
||||
import {render, screen} from '@testing-library/react'
|
||||
import {MockedProvider} from '@apollo/client/testing';
|
||||
import {MemoryRouter} from 'react-router-dom';
|
||||
import App from "../App";
|
||||
|
||||
beforeEach(() => localStorage.clear())
|
||||
|
||||
describe('The root path /', () => {
|
||||
|
||||
test('renders user\'s home page if they are logged in',() => {
|
||||
localStorage.setItem("token", "asdfasdfasdf")
|
||||
render(<MockedProvider><MemoryRouter initialEntries={['/']}><App/></MemoryRouter></MockedProvider>);
|
||||
|
||||
expect(() => screen.getByLabelText(/current user/)).not.toThrow()
|
||||
});
|
||||
|
||||
test('redirects to login page if user not logged in', () => {
|
||||
render(<MockedProvider><MemoryRouter initialEntries={['/']}><App/></MemoryRouter></MockedProvider>);
|
||||
|
||||
const emailField = screen.getByRole('textbox', {name: 'Email Address'});
|
||||
const passwordField = screen.getByLabelText(/Password/);
|
||||
expect(emailField).toHaveValue("");
|
||||
expect(passwordField).toHaveValue("");
|
||||
});
|
||||
});
|
||||
|
||||
describe('The /login path', () => {
|
||||
test('renders the signin page if the user is not logged in', () => {
|
||||
render(<MockedProvider><MemoryRouter initialEntries={['/login']}><App/></MemoryRouter></MockedProvider>);
|
||||
|
||||
const emailField = screen.getByRole('textbox', {name: 'Email Address'});
|
||||
const passwordField = screen.getByLabelText(/Password/);
|
||||
expect(emailField).toHaveValue("");
|
||||
expect(passwordField).toHaveValue("");
|
||||
});
|
||||
|
||||
test('redirects to root / and the user\'s home page if the user is logged in', () => {
|
||||
localStorage.setItem("token", "asdfasdfasdf")
|
||||
render(<MockedProvider><MemoryRouter initialEntries={['/login']}><App/></MemoryRouter></MockedProvider>);
|
||||
|
||||
expect(() => screen.getByLabelText(/current user/)).not.toThrow()
|
||||
});
|
||||
});
|
||||
|
||||
describe('The /signup path', () => {
|
||||
test('renders the signup page if the user is not logged in', () => {
|
||||
render(<MockedProvider><MemoryRouter initialEntries={['/signup']}><App/></MemoryRouter></MockedProvider>);
|
||||
|
||||
expect(() => screen.getByRole('textbox', {name: 'Email Address'})).not.toThrow()
|
||||
expect(() => screen.getByLabelText(/Password/)).not.toThrow()
|
||||
expect(() => screen.getByLabelText(/First Name/)).not.toThrow()
|
||||
expect(() => screen.getByLabelText(/Last Name/)).not.toThrow()
|
||||
});
|
||||
|
||||
test('redirects to root / and the user\'s home page if the user is logged in', () => {
|
||||
localStorage.setItem("token", "asdfasdfasdf")
|
||||
render(<MockedProvider><MemoryRouter initialEntries={['/signup']}><App/></MemoryRouter></MockedProvider>);
|
||||
|
||||
expect(() => screen.getByLabelText(/current user/)).not.toThrow()
|
||||
});
|
||||
});
|
|
@ -0,0 +1,119 @@
|
|||
import React from 'react';
|
||||
import SignIn, {loginMutation, LoginMutationResponse} from "../components/SignIn";
|
||||
import {fireEvent, render, screen, waitFor} from '@testing-library/react'
|
||||
import {MockedProvider, MockedResponse} from '@apollo/client/testing';
|
||||
import {MemoryRouter} from 'react-router-dom';
|
||||
|
||||
const mockHistoryReplace = jest.fn();
|
||||
|
||||
jest.mock('react-router-dom', () => ({
|
||||
...jest.requireActual('react-router-dom'),
|
||||
useHistory: () => ({
|
||||
replace: mockHistoryReplace,
|
||||
}),
|
||||
}));
|
||||
|
||||
const mocks: Array<MockedResponse<LoginMutationResponse>> = [
|
||||
{
|
||||
request: {
|
||||
query: loginMutation,
|
||||
variables: {
|
||||
email: "test@email.com",
|
||||
password: "password",
|
||||
}
|
||||
},
|
||||
result: {
|
||||
data: {
|
||||
authenticate: {
|
||||
jwtToken: "123"
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
request: {
|
||||
query: loginMutation,
|
||||
variables: {
|
||||
email: "test@email.com",
|
||||
password: "wrong-password",
|
||||
}
|
||||
},
|
||||
result: {
|
||||
data: {
|
||||
authenticate: {
|
||||
jwtToken: null
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
describe('SignIn page', () => {
|
||||
beforeEach(() => mockHistoryReplace.mockReset())
|
||||
|
||||
test('initial state', () => {
|
||||
render(<MockedProvider mocks={mocks}><MemoryRouter><SignIn/></MemoryRouter></MockedProvider>);
|
||||
|
||||
// it renders empty email and passsword fields
|
||||
const emailField = screen.getByRole('textbox', {name: 'Email Address'});
|
||||
expect(emailField).toHaveValue('');
|
||||
const passwordField = screen.getByLabelText(/Password/);
|
||||
expect(passwordField).toHaveValue('');
|
||||
|
||||
// it renders enabled submit button
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).not.toBeDisabled();
|
||||
expect(button).toHaveTextContent('Sign In');
|
||||
expect(mockHistoryReplace).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('successful login', async () => {
|
||||
render(<MockedProvider mocks={mocks}><MemoryRouter><SignIn/></MemoryRouter></MockedProvider>);
|
||||
|
||||
const emailField = screen.getByRole('textbox', {name: 'Email Address'});
|
||||
const passwordField = screen.getByLabelText(/Password/);
|
||||
const button = screen.getByRole('button');
|
||||
|
||||
// fill out and submit form
|
||||
fireEvent.change(emailField, {target: {value: 'test@email.com'}});
|
||||
fireEvent.change(passwordField, {target: {value: 'password'}});
|
||||
|
||||
fireEvent.click(button);
|
||||
|
||||
await waitFor(() => {
|
||||
// it hides form elements
|
||||
expect(button).not.toBeInTheDocument();
|
||||
expect(emailField).not.toBeInTheDocument();
|
||||
expect(passwordField).not.toBeInTheDocument();
|
||||
|
||||
// it displays success text and email address
|
||||
const loggedInText = screen.getByText(/Success/);
|
||||
expect(loggedInText).toBeInTheDocument();
|
||||
expect(mockHistoryReplace).toHaveBeenCalledWith("/");
|
||||
});
|
||||
});
|
||||
|
||||
test('error login', async () => {
|
||||
render(<MockedProvider mocks={mocks}><MemoryRouter><SignIn/></MemoryRouter></MockedProvider>);
|
||||
|
||||
const emailField = screen.getByRole('textbox', {name: 'Email Address'});
|
||||
const passwordField = screen.getByLabelText(/Password/);
|
||||
const button = screen.getByRole('button');
|
||||
|
||||
// fill out and submit form
|
||||
fireEvent.change(emailField, {target: {value: 'test@email.com'}});
|
||||
fireEvent.change(passwordField, {target: {value: 'wrong-password'}});
|
||||
fireEvent.click(button);
|
||||
|
||||
await waitFor(() => {
|
||||
// it resets button
|
||||
expect(button).not.toBeDisabled();
|
||||
expect(button).toHaveTextContent('Sign In');
|
||||
|
||||
// it displays error text
|
||||
const errorText = screen.getByText(/Wrong username or password/);
|
||||
expect(errorText).toBeInTheDocument();
|
||||
expect(mockHistoryReplace).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
Loading…
Reference in a new issue