Merge pull request 'feature/loginlogout' (#16) from feature/loginlogout into develop

Reviewed-on: Netzbegruenung/candymat#16
This commit is contained in:
Christoph Lienhard 2020-08-23 15:08:52 +02:00
commit 8c199b1fdb
23 changed files with 2970 additions and 5611 deletions

3
.gitignore vendored
View file

@ -24,3 +24,6 @@ build
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# GraphQl plugin related
postgraphile-schema.graphql

View file

@ -0,0 +1,15 @@
{
"name": "Postgraphile Schema",
"schemaPath": "postgraphile-schema.graphql",
"extensions": {
"endpoints": {
"Remote SWAPI GraphQL Endpoint": {
"url": "http://localhost:5433/graphql",
"headers": {
"user-agent": "JS GraphQL"
},
"introspect": true
}
}
}
}

View file

@ -1,3 +1,18 @@
# Redaktions App
The "Redaktions App" or editor's app is the main gateway for editors and candidates to alter the database,
e.g. adding new questions (editors) and answering them (candidates).
## Development
The app is written in typescript and react and uses apollo to query the backend and as a local store.
### Setup
* Install `npm`
* In this directory run `npm ci` to install all dependencies according to the package.json and package-lock.json.
*
## Available Scripts
In the project directory, you can run:

File diff suppressed because it is too large Load diff

View file

@ -3,16 +3,21 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"typescript": "^3.6.2",
"@material-ui/core": "^4.4.0",
"@material-ui/icons": "^4.2.1",
"@types/jest": "24.0.18",
"@types/node": "12.7.3",
"@types/react": "16.9.2",
"@types/react-dom": "16.9.0",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-scripts": "^3.3.1"
"@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",
"@testing-library/user-event": "^7.2.1",
"@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"
},
"scripts": {
"start": "react-scripts start",
@ -34,6 +39,5 @@
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://graphql:5000"
}
}

View file

@ -10,7 +10,7 @@
content="App zum Erstellen von Fragen für den Candymat"
/>
<link rel="apple-touch-icon" href="logo192.png" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/

View file

@ -3,11 +3,16 @@
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;

View file

@ -1,9 +1,9 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { render } from '@testing-library/react';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
test('renders learn react link', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

View file

@ -1,39 +1,20 @@
import React from 'react';
import './App.css';
import { createStyles, WithStyles } from '@material-ui/core';
import { withStyles } from '@material-ui/styles';
import { CustomAppBar } from 'components/CustomAppBar/CustomAppBar';
import { Overview } from 'components/Overview/Overview';
import SignIn from "./components/SignIn";
import {ApolloProvider} from "@apollo/client";
import {client} from "./backend-connection/helper";
import Main from "./components/Main";
export const dataApi = 'http://localhost:5000/graphql'
function App() {
const styles = createStyles({
root: {
flexGrow: 1,
},
content: {
flexGrow: 1,
height: '100vh',
maxWidth: 1000,
marginLeft: 'auto',
marginRight: 'auto',
},
})
interface AppProps extends WithStyles<typeof styles> { }
class ProtoApp extends React.PureComponent<AppProps> {
public render() {
return (
<div className={this.props.classes.root}>
<CustomAppBar />
<main className={this.props.classes.content}>
<Overview />
</main>
</div>
);
}
return (
<ApolloProvider client={client}>
{localStorage.getItem("token")
? <Main />
: <SignIn/>}
</ApolloProvider>
);
}
export const App = withStyles(styles)(ProtoApp);
export default App;

View file

@ -0,0 +1,22 @@
import {ApolloClient, createHttpLink, InMemoryCache} from "@apollo/client";
import {setContext} from "@apollo/client/link/context";
const httpLink = createHttpLink({
uri: 'http://localhost:5433/graphql',
});
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem('token');
return token ? {
headers: {
...headers,
authorization: `Bearer ${token}`,
}
} : headers
});
export const client = new ApolloClient({
cache: new InMemoryCache(),
link: authLink.concat(httpLink),
});

View file

@ -0,0 +1,55 @@
import React from 'react';
import {createStyles, makeStyles, Theme} from '@material-ui/core/styles';
import CircularProgress from '@material-ui/core/CircularProgress';
import {green} from '@material-ui/core/colors';
import Button from '@material-ui/core/Button';
const useStyles = makeStyles((theme: Theme) =>
createStyles({
wrapper: {
margin: theme.spacing(1),
position: 'relative',
},
buttonProgress: {
color: green[500],
position: 'absolute',
top: '50%',
left: '50%',
marginTop: -12,
marginLeft: -12,
},
button: {
margin: theme.spacing(3, 0, 2),
},
}),
);
interface ButtonWithSpinnerProps {
children: string,
handleClick: () => void,
loading: boolean
type?: "button" | "submit",
fullWidth?: boolean,
}
export default function ButtonWithSpinner(props: ButtonWithSpinnerProps) {
const classes = useStyles();
return (
<div className={classes.wrapper}>
<Button
className={classes.button}
variant="contained"
color="primary"
fullWidth={!!props.fullWidth}
type={props.type}
disabled={props.loading}
onClick={props.handleClick}
>
{props.children}
</Button>
{props.loading && <CircularProgress size={24} className={classes.buttonProgress} />}
</div>
);
}

View file

@ -0,0 +1,16 @@
import Typography from "@material-ui/core/Typography";
import Link from "@material-ui/core/Link";
import React from "react";
export function Copyright() {
return (
<Typography variant="body2" color="textSecondary" align="center">
{'Copyright © '}
<Link color="inherit" href="https://blog.netzbegruenung.de/">
Netzbegruenung e.V.
</Link>{' '}
{new Date().getFullYear()}
{'.'}
</Typography>
);
}

View file

@ -1,123 +0,0 @@
import React from 'react';
import { createStyles, WithStyles } from '@material-ui/core/styles';
import Modal from '@material-ui/core/Modal';
import { TextField, Button } from '@material-ui/core';
import { withStyles } from '@material-ui/styles';
import { dataApi } from 'App';
const styles = createStyles({
paper: {
margin: 'auto',
width: 400,
backgroundColor: 'white',
border: '2px solid #000',
padding: 8,
},
textField: {
width: '100%',
},
buttonBar: {
display: 'flex',
flexDirection: 'row',
},
button: {
margin: 2,
},
})
interface OwnState {
frageText: string,
kategorieText: string,
}
interface OwnProps {
open?: boolean,
handleClose(): void,
}
interface CreateQuestionModalProps extends OwnProps, WithStyles<typeof styles> { }
class ProtoCreateQuestionModal extends React.PureComponent<CreateQuestionModalProps, OwnState> {
public constructor(props: CreateQuestionModalProps) {
super(props)
this.state = {
frageText: '',
kategorieText: '',
}
}
public render() {
return (
<Modal
aria-labelledby="simple-modal-title"
aria-describedby="simple-modal-description"
open={this.props.open ? true : false}
onClose={this.props.handleClose}
>
<div className={this.props.classes.paper}>
<h2 id="simple-modal-title">Neue Frage erstellen</h2>
<TextField
id="frage-text"
label="Frage"
multiline
rows="4"
className={this.props.classes.textField}
margin="normal"
variant="outlined"
value={this.state.frageText}
onChange={(e) => this.setState({ frageText: e.target.value })}
/>
<TextField
id="kategorie-name"
label="Kategorie"
className={this.props.classes.textField}
margin="normal"
variant="outlined"
value={this.state.kategorieText}
onChange={(e) => this.setState({ kategorieText: e.target.value })}
/>
<div className={this.props.classes.buttonBar}>
<Button
className={this.props.classes.button}
variant='contained'
color='primary'
onClick={this.createFrage}
>
Erstellen
</Button>
<Button
className={this.props.classes.button}
variant='contained'
color='primary'
onClick={this.props.handleClose}
>
Abbrechen
</Button>
</div>
</div>
</Modal>
);
};
private readonly createFrage = () => {
fetch(`${dataApi}/fragen`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
})
.then(res => {
if (res.status === 200) {
this.props.handleClose();
alert("Frage wurde erfolgreich erstellt");
} else {
alert(`Es ist etwas schief gelaufen. Response: ${res.text}`);
}
})
.catch(err => alert(`Es ist etwas schief gelaufen. Fehler: ${err}`))
};
}
export const CreateQuestionModal = withStyles(styles)(ProtoCreateQuestionModal)

View file

@ -0,0 +1,77 @@
import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import {IconButton, MenuItem, Toolbar, Typography} from '@material-ui/core';
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";
const useStyles = makeStyles({
menuButton: {
marginRight: 16,
},
title: {
flexGrow: 1,
},
})
function CustomAppBar() {
const classes = useStyles()
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const handleMenu = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
};
const handleLogout = () => {
localStorage.removeItem('token')
window.location.href = window.location.origin
}
const handleClose = () => {
setAnchorEl(null);
};
return (
<AppBar>
<Toolbar>
<IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
<MenuIcon />
</IconButton>
<Typography variant="h6" className={classes.title}>
Candymat Redaktion
</Typography>
<IconButton
aria-label="account of current user"
aria-controls="menu-appbar"
aria-haspopup="true"
onClick={handleMenu}
color="inherit"
>
<AccountCircle />
</IconButton>
<Menu
id="menu-appbar"
anchorEl={anchorEl}
anchorOrigin={{
vertical: 'top',
horizontal: 'right',
}}
keepMounted
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
open={open}
onClose={handleClose}
>
<MenuItem onClick={handleClose}>Profil</MenuItem>
<MenuItem onClick={handleLogout}>Logout</MenuItem>
</Menu>
</Toolbar>
</AppBar>
);
}
export default CustomAppBar

View file

@ -1,39 +0,0 @@
import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import { Toolbar, IconButton, Typography, createStyles, WithStyles } from '@material-ui/core';
import MenuIcon from '@material-ui/icons/Menu';
import AccountCircle from '@material-ui/icons/AccountCircle';
import { withStyles } from '@material-ui/styles';
const styles = createStyles({
menuButton: {
marginRight: 16,
},
title: {
flexGrow: 1,
},
})
interface AppBarProps extends WithStyles<typeof styles> { }
class ProtoCustomAppBar extends React.PureComponent<AppBarProps> {
public render() {
return (
<AppBar>
<Toolbar>
<IconButton edge="start" className={this.props.classes.menuButton} color="inherit" aria-label="menu">
<MenuIcon />
</IconButton>
<Typography variant="h6" className={this.props.classes.title}>
Candymat Redaktion
</Typography>
<IconButton edge="start" className={this.props.classes.menuButton} color="inherit" aria-label="user">
<AccountCircle />
</IconButton>
</Toolbar>
</AppBar>
);
}
}
export const CustomAppBar = withStyles(styles)(ProtoCustomAppBar);

View file

@ -1,63 +0,0 @@
import { WithStyles, createStyles, withStyles } from "@material-ui/core";
import React from "react";
import { dataApi } from "App";
const styles = createStyles({
root: {
padding: '20px 0'
},
questionBar: {
margin: '6px 0',
padding: 7,
border: 'solid black 1px',
width: '100%',
}
})
interface Question {
id: number,
text: string,
kategorie: string,
}
interface StateProps {
existingQuestions: Array<Question>,
}
interface ExistingQuestionsProps extends WithStyles<typeof styles> { }
class ProtoExistingQuestions extends React.PureComponent<ExistingQuestionsProps, StateProps> {
public constructor(props: ExistingQuestionsProps) {
super(props)
this.state = {
existingQuestions: [],
}
}
componentDidMount() {
fetch(`${dataApi}/fragen`, {method: 'GET'})
.then(res => res.json())
.then(json => this.setState({ existingQuestions: json }))
}
public render() {
const questions = this.state.existingQuestions;
return (
<div className={this.props.classes.root}>
{questions.length > 0 ? this.getQuestions() : <span>Es wurden noch keine Fragen erstellt.</span>}
</div>
)
}
private readonly getQuestions = () => this.state.existingQuestions.map(question => (
<div key={question.id} className={this.props.classes.questionBar}>
<span>{question.text}</span>
</div>
))
}
export const ExistingQuestions = withStyles(styles)(ProtoExistingQuestions)

View file

@ -0,0 +1,54 @@
import CustomAppBar from "./CustomAppBar";
import {Box, Container, Grid, Paper} from "@material-ui/core";
import React from "react";
import clsx from "clsx";
import {makeStyles} from "@material-ui/core/styles";
import {Copyright} from "./Copyright";
const useStyles = makeStyles((theme) => ({
appBarSpacer: theme.mixins.toolbar,
content: {
flexGrow: 1,
height: '100vh',
overflow: 'auto',
},
container: {
paddingTop: theme.spacing(4),
paddingBottom: theme.spacing(4),
flexDirection: 'column',
},
paper: {
margin: 5,
padding: theme.spacing(2),
display: 'flex',
overflow: 'auto',
flexDirection: 'column',
},
fixedHeight: {
height: 240,
},
}));
function Main() {
const classes = useStyles();
const fixedHeightPaper = clsx(classes.paper, classes.fixedHeight);
return (
<div>
<CustomAppBar/>
<main className={classes.content}>
<div className={classes.appBarSpacer}/>
<Container maxWidth="lg" className={classes.container}>
<Paper className={fixedHeightPaper}>
blablablubb
</Paper>
<Paper className={fixedHeightPaper}>
blablaj
</Paper>
<Copyright/>
</Container>
</main>
</div>
)
}
export default Main;

View file

@ -1,54 +0,0 @@
import { WithStyles, createStyles, Paper, Typography, Button, withStyles } from "@material-ui/core";
import React from "react";
import { ExistingQuestions } from "components/ExistingQuestions/ExistingQuestions";
import { CreateQuestionModal } from "components/CreateQuestionModal/CreateQuestionModal";
const styles = createStyles({
mainPaper: {
height: '100%',
margin: '100px 50px 30px',
backgroundColor: 'white',
padding: '50px 30px 30px',
},
})
interface OverviewProps extends WithStyles<typeof styles> { }
interface OwnState {
modalOpen: boolean,
}
class ProtoOverview extends React.PureComponent<OverviewProps, OwnState> {
public constructor(props: OverviewProps) {
super(props)
this.state = {
modalOpen: false,
}
}
public render() {
return (
<Paper className={this.props.classes.mainPaper}>
<Typography component="h1" variant="h4" align="center">
Existierende Fragen
</Typography>
<ExistingQuestions />
<Button variant='contained' color='primary' onClick={this.createFrage}>
Neue Frage erstellen
</Button>
<CreateQuestionModal open={this.state.modalOpen} handleClose={this.onModalClose}/>
</Paper>
)
};
private readonly createFrage = () => {
this.setState({modalOpen: true})
}
private readonly onModalClose = () => {
this.setState({modalOpen: false})
}
}
export const Overview = withStyles(styles)(ProtoOverview)

View file

@ -0,0 +1,144 @@
import React, {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 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 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 {gql, useMutation} from "@apollo/client";
import ButtonWithSpinner from "./ButtonWithSpinner";
import {Copyright} from "./Copyright";
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(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
error: {
color: 'red',
}
}));
export default function SignIn() {
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>
}
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form
className={classes.form}
noValidate
onSubmit={event => {
event.preventDefault();
login({variables: {email: email, password: password}})
}}
>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
value={password}
autoComplete="current-password"
onChange={(e) => setPassword(e.target.value)}
/>
<FormControlLabel
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>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<Link href="#" variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={8}>
<Copyright />
</Box>
</Container>
);
}
const loginMutation = gql`
mutation Login($email: String!, $password: String!) {
authenticate(input: {email: $email, password: $password}) {
jwtToken
}
}`

View file

@ -1,10 +1,15 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { App } from 'App';
ReactDOM.render(<App />, document.getElementById('root'));
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.

View file

@ -14,7 +14,7 @@ const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
@ -29,7 +29,7 @@ export function register(config?: Config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(
(process as { env: { [key: string]: string } }).env.PUBLIC_URL,
process.env.PUBLIC_URL,
window.location.href
);
if (publicUrl.origin !== window.location.origin) {
@ -108,7 +108,9 @@ function registerValidSW(swUrl: string, config?: Config) {
function checkValidServiceWorker(swUrl: string, config?: Config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
fetch(swUrl, {
headers: { 'Service-Worker': 'script' }
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
@ -136,8 +138,12 @@ function checkValidServiceWorker(swUrl: string, config?: Config) {
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}

View file

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';

View file

@ -1,29 +1,24 @@
{
"compilerOptions": {
"module": "esnext",
"target": "es5",
"lib": [
"es6",
"dom"
"dom",
"dom.iterable",
"esnext"
],
"jsx": "preserve",
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noEmit": true,
"experimentalDecorators": true,
"baseUrl": "src",
"allowSyntheticDefaultImports": true,
"noErrorTruncation": true,
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"exclude": [
"**/build/"
],
"include": [
"src"
]