diff --git a/README.md b/README.md index 56ea97f2b1afc129c0221d36ce6978802a250d89..10a4debc16e5edc64dea58216139c2913884a0cd 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,3 @@ - - - - - - # Scoring system for Teknikåttan This is the scoring system for Teknikåttan! diff --git a/client/src/enum/ComponentTypes.ts b/client/src/enum/ComponentTypes.ts index c0aa738479a2c081ef0529bb6b4a317570b6841d..7ff75bd8d867762550dd9bcb6997038ac8d4b233 100644 --- a/client/src/enum/ComponentTypes.ts +++ b/client/src/enum/ComponentTypes.ts @@ -1,5 +1,5 @@ export enum ComponentTypes { Text = 1, Image, - QuestionAlternative, + Question, } diff --git a/client/src/interfaces/ApiModels.ts b/client/src/interfaces/ApiModels.ts index 2734884b7783b662113dc00f61d112f8a58f5dd6..9bcd24c1b916ff925a9472dffd8b2fabd5395bfb 100644 --- a/client/src/interfaces/ApiModels.ts +++ b/client/src/interfaces/ApiModels.ts @@ -94,6 +94,16 @@ export interface TextComponent extends Component { font: string } -export interface QuestionAlternativeComponent extends Component { +export interface QuestionComponent extends Component { + id: number + x: number + y: number + w: number + h: number + slide_id: number + type_id: number + view_type_id: number + text: string + media: Media question_id: number } diff --git a/client/src/pages/admin/competitions/CompetitionManager.tsx b/client/src/pages/admin/competitions/CompetitionManager.tsx index 982ae1114cbdd8da8f52f484d5ae31bc4602d0c6..9b72ae04055e5dccea5cbb6cd0826577a0f5068b 100644 --- a/client/src/pages/admin/competitions/CompetitionManager.tsx +++ b/client/src/pages/admin/competitions/CompetitionManager.tsx @@ -131,6 +131,7 @@ const CompetitionManager: React.FC = (props: any) => { } } + /** Start the competition by redirecting with URL with Code */ const handleStartCompetition = () => { const operatorCode = codes.find((code) => code.view_type_id === 4)?.code if (operatorCode) { @@ -138,6 +139,7 @@ const CompetitionManager: React.FC = (props: any) => { } } + /** Fetch all the connection codes from the server */ const getCodes = async (id: number) => { await axios .get(`/api/competitions/${id}/codes`) @@ -147,6 +149,7 @@ const CompetitionManager: React.FC = (props: any) => { .catch(console.log) } + /** Fetch all the teams from the server that is connected to a specific competition*/ const getTeams = async (id: number) => { await axios .get(`/api/competitions/${id}/teams`) @@ -159,6 +162,7 @@ const CompetitionManager: React.FC = (props: any) => { }) } + /** Fetch the copetition name from the server */ const getCompetitionName = async () => { await axios .get(`/api/competitions/${activeId}`) @@ -198,16 +202,18 @@ const CompetitionManager: React.FC = (props: any) => { return typeName } + /** Handles the opening of the code dialog box */ const handleOpenDialog = async () => { await getCompetitionName() setDialogIsOpen(true) } - + /** Handles the closing of the code dialog box */ const handleCloseDialog = () => { setDialogIsOpen(false) setAnchorEl(null) } + /** Function that copies an existing competition */ const handleDuplicateCompetition = async () => { if (activeId) { await axios diff --git a/client/src/pages/admin/dashboard/Dashboard.tsx b/client/src/pages/admin/dashboard/Dashboard.tsx index a0f569b066a8073a14f9342dcb7d988be63b93b9..51aa4f4084ebf016fefbb740dcb081ac20f0e7fe 100644 --- a/client/src/pages/admin/dashboard/Dashboard.tsx +++ b/client/src/pages/admin/dashboard/Dashboard.tsx @@ -6,6 +6,11 @@ import NumberOfCompetitions from './components/NumberOfCompetitions' import NumberOfRegions from './components/NumberOfRegions' import NumberOfUsers from './components/NumberOfUsers' +/** + * This is the first page that is shown after a user logs in. It shows som statistics about the site. + * + */ + const useStyles = makeStyles((theme: Theme) => createStyles({ root: { diff --git a/client/src/pages/admin/dashboard/components/CurrentUser.tsx b/client/src/pages/admin/dashboard/components/CurrentUser.tsx index a6480b70806664a9387e763206068cc7ed011cd4..933a320b30e637d8100e29226f4bd41a49a48572 100644 --- a/client/src/pages/admin/dashboard/components/CurrentUser.tsx +++ b/client/src/pages/admin/dashboard/components/CurrentUser.tsx @@ -2,6 +2,8 @@ import { Box, Typography } from '@material-ui/core' import React from 'react' import { useAppSelector } from '../../../../hooks' +/** This component show information about the currently logged in user */ + const CurrentUser: React.FC = () => { const currentUser = useAppSelector((state: { user: { userInfo: any } }) => state.user.userInfo) return ( diff --git a/client/src/pages/admin/dashboard/components/NumberOfCompetitions.tsx b/client/src/pages/admin/dashboard/components/NumberOfCompetitions.tsx index eb667ebd690f6013c184ac13e2038ce1a7726de9..1ebe9dfba3e888e9bf07b998cff321613ba035d3 100644 --- a/client/src/pages/admin/dashboard/components/NumberOfCompetitions.tsx +++ b/client/src/pages/admin/dashboard/components/NumberOfCompetitions.tsx @@ -2,6 +2,8 @@ import { Box, Typography } from '@material-ui/core' import React from 'react' import { useAppSelector } from '../../../../hooks' +/** Shows how many competitions is on the system */ + const NumberOfCompetitions: React.FC = () => { const competitions = useAppSelector((state) => state.statistics.competitions) diff --git a/client/src/pages/admin/dashboard/components/NumberOfRegions.tsx b/client/src/pages/admin/dashboard/components/NumberOfRegions.tsx index f3195f4c18969ed2ad1e4b185b2125ac2c15f782..5f9ecef5e60ff4fda27d6a42771c043b83e9dc8e 100644 --- a/client/src/pages/admin/dashboard/components/NumberOfRegions.tsx +++ b/client/src/pages/admin/dashboard/components/NumberOfRegions.tsx @@ -3,6 +3,8 @@ import React, { useEffect } from 'react' import { getCities } from '../../../../actions/cities' import { useAppDispatch, useAppSelector } from '../../../../hooks' +/** Shows how many regions is on the system */ + const NumberOfRegions: React.FC = () => { const regions = useAppSelector((state) => state.statistics.regions) const dispatch = useAppDispatch() diff --git a/client/src/pages/admin/dashboard/components/NumberOfUsers.tsx b/client/src/pages/admin/dashboard/components/NumberOfUsers.tsx index 0e75cf1b1069814801fadc010f30ac393dfe3b25..91291e689529c8c65a54ed63c7ae77ce489ebe2f 100644 --- a/client/src/pages/admin/dashboard/components/NumberOfUsers.tsx +++ b/client/src/pages/admin/dashboard/components/NumberOfUsers.tsx @@ -3,6 +3,8 @@ import React, { useEffect } from 'react' import { getSearchUsers } from '../../../../actions/searchUser' import { useAppDispatch, useAppSelector } from '../../../../hooks' +/** Shows how many users are on the system */ + const NumberOfUsers: React.FC = () => { const usersTotal = useAppSelector((state) => state.statistics.users) const dispatch = useAppDispatch() diff --git a/client/src/pages/admin/regions/AddRegion.tsx b/client/src/pages/admin/regions/AddRegion.tsx index a53c18adcdbf85a39575c9d10d60f4a7c9118bbc..10cb22bc5c4b7527b05d8dfeb9b0f748dd6f0c65 100644 --- a/client/src/pages/admin/regions/AddRegion.tsx +++ b/client/src/pages/admin/regions/AddRegion.tsx @@ -30,6 +30,7 @@ const useStyles = makeStyles((theme: Theme) => type formType = FormModel<AddCityModel> +/** add a region form with some constraints. */ const schema: Yup.SchemaOf<formType> = Yup.object({ model: Yup.object() .shape({ diff --git a/client/src/pages/admin/regions/Regions.tsx b/client/src/pages/admin/regions/Regions.tsx index 706d809266648b79e79e889048370e13f0f6f51d..5e2531bb44b6e2e6d7d6a3ce65941ecdc03a3ee3 100644 --- a/client/src/pages/admin/regions/Regions.tsx +++ b/client/src/pages/admin/regions/Regions.tsx @@ -14,6 +14,9 @@ import { getCities } from '../../../actions/cities' import { useAppDispatch, useAppSelector } from '../../../hooks' import { RemoveMenuItem, TopBar } from '../styledComp' import AddRegion from './AddRegion' + +/** shows all the regions in a list */ + const useStyles = makeStyles((theme: Theme) => createStyles({ table: { diff --git a/client/src/pages/admin/users/AddUser.tsx b/client/src/pages/admin/users/AddUser.tsx index a4c4d9bf6967a0b6e0f85d998067fd98c23cb66d..63549edcd3180033e897c8bfb3924e6a691225bd 100644 --- a/client/src/pages/admin/users/AddUser.tsx +++ b/client/src/pages/admin/users/AddUser.tsx @@ -1,3 +1,5 @@ +/** Add a user component */ + import { Button, FormControl, InputLabel, MenuItem, Popover, TextField } from '@material-ui/core' import PersonAddIcon from '@material-ui/icons/PersonAdd' import { Alert, AlertTitle } from '@material-ui/lab' @@ -16,6 +18,7 @@ type formType = FormModel<AddUserModel> const noRoleSelected = 'Välj roll' const noCitySelected = 'Välj stad' +/** Form when adding a user with some constraints */ const userSchema: Yup.SchemaOf<formType> = Yup.object({ model: Yup.object() .shape({ diff --git a/client/src/pages/login/LoginPage.tsx b/client/src/pages/login/LoginPage.tsx index 8f8e967c435af9c2611bc9ac3c1365b114a7666a..34c9c5ae6c5344666dc383d7f2df7586ecc13e10 100644 --- a/client/src/pages/login/LoginPage.tsx +++ b/client/src/pages/login/LoginPage.tsx @@ -1,3 +1,7 @@ +/** This is the login page, it contains two child components, one is + * to log in as an admin, the other is to connect to a competition using a code + */ + import { AppBar, Tab, Tabs } from '@material-ui/core' import React from 'react' import AdminLogin from './components/AdminLogin' diff --git a/client/src/pages/login/components/AdminLogin.tsx b/client/src/pages/login/components/AdminLogin.tsx index 7430866dbf3247d2d5bf9843a2d499af856f74d3..c33f338da69a6d2f0d1733a6d5bb777461cdefe4 100644 --- a/client/src/pages/login/components/AdminLogin.tsx +++ b/client/src/pages/login/components/AdminLogin.tsx @@ -1,3 +1,5 @@ +/** Component that handles the log in when a user is an admin */ + import { Button, TextField, Typography } from '@material-ui/core' import { Alert, AlertTitle } from '@material-ui/lab' import { Formik, FormikHelpers } from 'formik' diff --git a/client/src/pages/login/components/CompetitionLogin.tsx b/client/src/pages/login/components/CompetitionLogin.tsx index 8dbbee33b6962c5bcd21f346ee594b224719a9a7..444634740fa361ad6deb1493c6673427f5fb8717 100644 --- a/client/src/pages/login/components/CompetitionLogin.tsx +++ b/client/src/pages/login/components/CompetitionLogin.tsx @@ -1,3 +1,5 @@ +/** Component that handles the log in when a user connects to a competition through a code */ + import { Button, TextField, Typography } from '@material-ui/core' import { Alert, AlertTitle } from '@material-ui/lab' import { Formik } from 'formik' @@ -38,7 +40,7 @@ const CompetitionLogin: React.FC = () => { const handleCompetitionSubmit = async (values: CompetitionLoginFormModel) => { dispatch(loginCompetition(values.model.code, history, true)) } - + return ( <Formik initialValues={competitionInitialValues} diff --git a/client/src/pages/presentationEditor/components/QuestionComponentDisplay.tsx b/client/src/pages/presentationEditor/components/QuestionComponentDisplay.tsx new file mode 100644 index 0000000000000000000000000000000000000000..dd8e2fa85a8e2562595c85c7068b0073f744092a --- /dev/null +++ b/client/src/pages/presentationEditor/components/QuestionComponentDisplay.tsx @@ -0,0 +1,84 @@ +import { Card, Divider, ListItem, Typography } from '@material-ui/core' +import React from 'react' +import { useAppSelector } from '../../../hooks' +import AnswerMultiple from './answerComponents/AnswerMultiple' +import AnswerSingle from './answerComponents/AnswerSingle' +import AnswerText from './answerComponents/AnswerText' +import { Center } from './styled' + +type QuestionComponentProps = { + variant: 'editor' | 'presentation' +} + +const QuestionComponentDisplay = ({ variant }: QuestionComponentProps) => { + const activeSlide = useAppSelector((state) => { + if (variant === 'editor') + return state.editor.competition.slides.find((slide) => slide.id === state.editor.activeSlideId) + return state.presentation.competition.slides.find((slide) => slide.id === state.presentation.slide?.id) + }) + + const timer = activeSlide?.timer + const total_score = activeSlide?.questions[0].total_score + const questionName = activeSlide?.questions[0].name + + const questionTypeId = activeSlide?.questions[0].type_id + const questionTypeName = useAppSelector( + (state) => state.types.questionTypes.find((qType) => qType.id === questionTypeId)?.name + ) + + const getAlternatives = () => { + switch (questionTypeName) { + case 'Text': + if (activeSlide) { + return <AnswerText activeSlide={activeSlide} competitionId={activeSlide.competition_id.toString()} /> + } + return + + case 'Practical': + return + + case 'Multiple': + if (activeSlide) { + return ( + <AnswerMultiple + variant={variant} + activeSlide={activeSlide} + competitionId={activeSlide.competition_id.toString()} + /> + ) + } + return + + case 'Single': + if (activeSlide) { + return ( + <AnswerSingle + variant={variant} + activeSlide={activeSlide} + competitionId={activeSlide.competition_id.toString()} + /> + ) + } + return + + default: + break + } + } + + return ( + <Card style={{ maxHeight: '100%', overflowY: 'auto' }}> + <ListItem> + <Center style={{ justifyContent: 'space-evenly' }}> + <Typography>Poäng: {total_score}</Typography> + <Typography>{questionName}</Typography> + <Typography>Timer: {timer}</Typography> + </Center> + </ListItem> + <Divider /> + {getAlternatives()} + </Card> + ) +} + +export default QuestionComponentDisplay diff --git a/client/src/pages/presentationEditor/components/RndComponent.tsx b/client/src/pages/presentationEditor/components/RndComponent.tsx index a134ee14c9ac268159b6ae0013350012e638dc65..4c09280042bd038fee1e3adc4b5bf3b7aef8ef6a 100644 --- a/client/src/pages/presentationEditor/components/RndComponent.tsx +++ b/client/src/pages/presentationEditor/components/RndComponent.tsx @@ -9,6 +9,7 @@ import { Component, ImageComponent, TextComponent } from '../../../interfaces/Ap import { Position, Size } from '../../../interfaces/Components' import { RemoveMenuItem } from '../../admin/styledComp' import ImageComponentDisplay from './ImageComponentDisplay' +import QuestionComponentDisplay from './QuestionComponentDisplay' import { HoverContainer } from './styled' import TextComponentDisplay from './TextComponentDisplay' //import NestedMenuItem from 'material-ui-nested-menu-item' @@ -126,6 +127,12 @@ const RndComponent = ({ component, width, height, scale }: RndComponentProps) => /> </HoverContainer> ) + case ComponentTypes.Question: + return ( + <HoverContainer hover={hover}> + <QuestionComponentDisplay variant="editor" /> + </HoverContainer> + ) default: break } diff --git a/client/src/pages/presentationEditor/components/SlideDisplay.tsx b/client/src/pages/presentationEditor/components/SlideDisplay.tsx index aef4ca7c48d29bbfc47cac8f29b214ec6866f360..e6b60f290784627d9c5446428062f2e1042cacef 100644 --- a/client/src/pages/presentationEditor/components/SlideDisplay.tsx +++ b/client/src/pages/presentationEditor/components/SlideDisplay.tsx @@ -77,15 +77,7 @@ const SlideDisplay = ({ variant, activeViewTypeId }: SlideDisplayProps) => { scale={scale} /> ) - return ( - <PresentationComponent - height={height} - width={width} - key={component.id} - component={component} - scale={scale} - /> - ) + return <PresentationComponent key={component.id} component={component} scale={scale} /> })} </SlideEditorPaper> </SlideEditorContainerRatio> diff --git a/client/src/pages/presentationEditor/components/SlideSettings.tsx b/client/src/pages/presentationEditor/components/SlideSettings.tsx index d48b4565712d043d52d3b1e93e3633ec6b927d38..029187f49e06fcffbb147a82fc7e754ec09e3a0f 100644 --- a/client/src/pages/presentationEditor/components/SlideSettings.tsx +++ b/client/src/pages/presentationEditor/components/SlideSettings.tsx @@ -1,18 +1,19 @@ /* This file compiles and renders the right hand slide settings bar, under the tab "SIDA". */ -import { Divider, List, ListItem, ListItemText, TextField, Typography } from '@material-ui/core' -import React, { useState } from 'react' +import { Divider } from '@material-ui/core' +import React from 'react' import { useParams } from 'react-router-dom' import { useAppSelector } from '../../../hooks' +import BackgroundImageSelect from './BackgroundImageSelect' +import Images from './slideSettingsComponents/Images' import Instructions from './slideSettingsComponents/Instructions' import MultipleChoiceAlternatives from './slideSettingsComponents/MultipleChoiceAlternatives' +import QuestionSettings from './slideSettingsComponents/QuestionSettings' +import SingleChoiceAlternatives from './slideSettingsComponents/SingleChoiceAlternatives' import SlideType from './slideSettingsComponents/SlideType' -import { Center, ImportedImage, SettingsList, PanelContainer } from './styled' -import Timer from './slideSettingsComponents/Timer' -import Images from './slideSettingsComponents/Images' import Texts from './slideSettingsComponents/Texts' -import QuestionSettings from './slideSettingsComponents/QuestionSettings' -import BackgroundImageSelect from './BackgroundImageSelect' +import Timer from './slideSettingsComponents/Timer' +import { PanelContainer, SettingsList } from './styled' interface CompetitionParams { competitionId: string @@ -36,19 +37,21 @@ const SlideSettings: React.FC = () => { </SettingsList> {activeSlide?.questions[0] && <QuestionSettings activeSlide={activeSlide} competitionId={competitionId} />} + { - // Choose answer alternatives depending on the slide type + // Choose answer alternatives, depending on the slide type } - {activeSlide?.questions[0]?.type_id === 1 && ( - <Instructions activeSlide={activeSlide} competitionId={competitionId} /> - )} - {activeSlide?.questions[0]?.type_id === 2 && ( + {(activeSlide?.questions[0]?.type_id === 1 || activeSlide?.questions[0]?.type_id === 2) && ( <Instructions activeSlide={activeSlide} competitionId={competitionId} /> )} {activeSlide?.questions[0]?.type_id === 3 && ( <MultipleChoiceAlternatives activeSlide={activeSlide} competitionId={competitionId} /> )} + {activeSlide?.questions[0]?.type_id === 4 && ( + <SingleChoiceAlternatives activeSlide={activeSlide} competitionId={competitionId} /> + )} + {activeSlide && ( <Texts activeViewTypeId={activeViewTypeId} activeSlide={activeSlide} competitionId={competitionId} /> )} diff --git a/client/src/pages/presentationEditor/components/answerComponents/AnswerMultiple.tsx b/client/src/pages/presentationEditor/components/answerComponents/AnswerMultiple.tsx new file mode 100644 index 0000000000000000000000000000000000000000..7a2b1c59acf0277197d6126a7aba5b81a8799a37 --- /dev/null +++ b/client/src/pages/presentationEditor/components/answerComponents/AnswerMultiple.tsx @@ -0,0 +1,106 @@ +import { Checkbox, ListItem, ListItemText, Typography, withStyles } from '@material-ui/core' +import { CheckboxProps } from '@material-ui/core/Checkbox' +import { green, grey } from '@material-ui/core/colors' +import axios from 'axios' +import React from 'react' +import { getEditorCompetition } from '../../../../actions/editor' +import { getPresentationCompetition } from '../../../../actions/presentation' +import { useAppDispatch, useAppSelector } from '../../../../hooks' +import { QuestionAlternative } from '../../../../interfaces/ApiModels' +import { RichSlide } from '../../../../interfaces/ApiRichModels' +import { Center } from '../styled' + +type AnswerMultipleProps = { + variant: 'editor' | 'presentation' + activeSlide: RichSlide | undefined + competitionId: string +} + +const AnswerMultiple = ({ variant, activeSlide, competitionId }: AnswerMultipleProps) => { + const dispatch = useAppDispatch() + const teamId = useAppSelector((state) => state.competitionLogin.data?.team_id) + const team = useAppSelector((state) => state.presentation.competition.teams.find((team) => team.id === teamId)) + const answer = team?.question_answers.find((answer) => answer.question_id === activeSlide?.questions[0].id) + + const decideChecked = (alternative: QuestionAlternative) => { + const teamAnswer = team?.question_answers.find((answer) => answer.answer === alternative.text)?.answer + if (alternative.text === teamAnswer) return true + else return false + } + + const updateAnswer = async (alternative: QuestionAlternative) => { + // TODO: fix. Make list of alternatives and delete & post instead of put to allow multiple boxes checked. + if (activeSlide) { + if (team?.question_answers.find((answer) => answer.question_id === activeSlide.questions[0].id)) { + if (answer?.answer === alternative.text) { + // Uncheck checkbox + deleteAnswer() + } else { + // Check another box + // TODO + } + } else { + // Check first checkbox + await axios + .post(`/api/competitions/${competitionId}/teams/${teamId}/answers`, { + answer: alternative.text, + score: 0, + question_id: activeSlide.questions[0].id, + }) + .then(() => { + if (variant === 'editor') { + dispatch(getEditorCompetition(competitionId)) + } else { + dispatch(getPresentationCompetition(competitionId)) + } + }) + .catch(console.log) + } + } + } + + const deleteAnswer = async () => { + await axios + .delete(`/api/competitions/${competitionId}/teams/${teamId}/answers`) // TODO: fix + .then(() => { + dispatch(getEditorCompetition(competitionId)) + }) + .catch(console.log) + } + + const GreenCheckbox = withStyles({ + root: { + color: grey[900], + '&$checked': { + color: green[600], + }, + }, + checked: {}, + })((props: CheckboxProps) => <Checkbox color="default" {...props} />) + + return ( + <div> + <ListItem divider> + <Center> + <ListItemText primary="Välj ett eller flera svar:" /> + </Center> + </ListItem> + {activeSlide && + activeSlide.questions[0] && + activeSlide.questions[0].alternatives && + activeSlide.questions[0].alternatives.map((alt) => ( + <div key={alt.id}> + <ListItem divider> + { + //<GreenCheckbox checked={checkbox} onChange={(event) => updateAnswer(alt, event.target.checked)} /> + } + <GreenCheckbox checked={decideChecked(alt)} onChange={() => updateAnswer(alt)} /> + <Typography style={{ wordBreak: 'break-all' }}>{alt.text}</Typography> + </ListItem> + </div> + ))} + </div> + ) +} + +export default AnswerMultiple diff --git a/client/src/pages/presentationEditor/components/answerComponents/AnswerSingle.tsx b/client/src/pages/presentationEditor/components/answerComponents/AnswerSingle.tsx new file mode 100644 index 0000000000000000000000000000000000000000..8c2fad17395e9c602a7108a72301739064ab4533 --- /dev/null +++ b/client/src/pages/presentationEditor/components/answerComponents/AnswerSingle.tsx @@ -0,0 +1,132 @@ +import { Checkbox, ListItem, ListItemText, Typography, withStyles } from '@material-ui/core' +import { CheckboxProps } from '@material-ui/core/Checkbox' +import { green, grey } from '@material-ui/core/colors' +import RadioButtonCheckedIcon from '@material-ui/icons/RadioButtonCheckedOutlined' +import RadioButtonUncheckedIcon from '@material-ui/icons/RadioButtonUncheckedOutlined' +import axios from 'axios' +import React from 'react' +import { getEditorCompetition } from '../../../../actions/editor' +import { getPresentationCompetition } from '../../../../actions/presentation' +import { useAppDispatch, useAppSelector } from '../../../../hooks' +import { QuestionAlternative } from '../../../../interfaces/ApiModels' +import { RichSlide } from '../../../../interfaces/ApiRichModels' +import { Center, Clickable } from '../styled' + +type AnswerSingleProps = { + variant: 'editor' | 'presentation' + activeSlide: RichSlide | undefined + competitionId: string +} + +const AnswerSingle = ({ variant, activeSlide, competitionId }: AnswerSingleProps) => { + const dispatch = useAppDispatch() + const teamId = useAppSelector((state) => state.competitionLogin.data?.team_id) + const team = useAppSelector((state) => { + if (variant === 'editor') return state.editor.competition.teams.find((team) => team.id === teamId) + return state.presentation.competition.teams.find((team) => team.id === teamId) + }) + const answerId = team?.question_answers.find((answer) => answer.question_id === activeSlide?.questions[0].id)?.id + + const decideChecked = (alternative: QuestionAlternative) => { + const teamAnswer = team?.question_answers.find((answer) => answer.answer === alternative.text)?.answer + if (teamAnswer) return true + else return false + } + + const updateAnswer = async (alternative: QuestionAlternative) => { + if (activeSlide) { + // TODO: ignore API calls when an answer is already checked + if (team?.question_answers[0]) { + await axios + .put(`/api/competitions/${competitionId}/teams/${teamId}/answers/${answerId}`, { + answer: alternative.text, + }) + .then(() => { + if (variant === 'editor') { + dispatch(getEditorCompetition(competitionId)) + } else { + dispatch(getPresentationCompetition(competitionId)) + } + }) + .catch(console.log) + } else { + await axios + .post(`/api/competitions/${competitionId}/teams/${teamId}/answers`, { + answer: alternative.text, + score: 0, + question_id: activeSlide.questions[0].id, + }) + .then(() => { + if (variant === 'editor') { + dispatch(getEditorCompetition(competitionId)) + } else { + dispatch(getPresentationCompetition(competitionId)) + } + }) + .catch(console.log) + } + } + } + + const deleteAnswer = async () => { + await axios + .delete(`/api/competitions/${competitionId}/teams/${teamId}/answers`) + .then(() => { + dispatch(getEditorCompetition(competitionId)) + }) + .catch(console.log) + } + + const GreenCheckbox = withStyles({ + root: { + color: grey[900], + '&$checked': { + color: green[600], + }, + }, + checked: {}, + })((props: CheckboxProps) => <Checkbox color="default" {...props} />) + + const renderRadioButton = (alt: QuestionAlternative) => { + if (variant === 'presentation') { + if (decideChecked(alt)) { + return ( + <Clickable> + <RadioButtonCheckedIcon onClick={() => updateAnswer(alt)} /> + </Clickable> + ) + } else { + return ( + <Clickable> + <RadioButtonUncheckedIcon onClick={() => updateAnswer(alt)} /> + </Clickable> + ) + } + } else { + return <RadioButtonUncheckedIcon onClick={() => updateAnswer(alt)} /> + } + } + + return ( + <div> + <ListItem divider> + <Center> + <ListItemText primary="Välj ett svar:" /> + </Center> + </ListItem> + {activeSlide && + activeSlide.questions[0] && + activeSlide.questions[0].alternatives && + activeSlide.questions[0].alternatives.map((alt) => ( + <div key={alt.id}> + <ListItem divider> + {renderRadioButton(alt)} + <Typography style={{ wordBreak: 'break-all' }}>{alt.text}</Typography> + </ListItem> + </div> + ))} + </div> + ) +} + +export default AnswerSingle diff --git a/client/src/pages/presentationEditor/components/answerComponents/AnswerText.tsx b/client/src/pages/presentationEditor/components/answerComponents/AnswerText.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e54b0dd2fe56f3ebf96b65fa8a05e6af4467da9f --- /dev/null +++ b/client/src/pages/presentationEditor/components/answerComponents/AnswerText.tsx @@ -0,0 +1,80 @@ +import { ListItem, ListItemText, TextField } from '@material-ui/core' +import axios from 'axios' +import React from 'react' +import { getEditorCompetition } from '../../../../actions/editor' +import { useAppDispatch, useAppSelector } from '../../../../hooks' +import { RichSlide } from '../../../../interfaces/ApiRichModels' +import { Center } from '../styled' +import { AnswerTextFieldContainer } from './styled' + +type AnswerTextProps = { + activeSlide: RichSlide | undefined + competitionId: string +} + +const AnswerText = ({ activeSlide, competitionId }: AnswerTextProps) => { + const [timerHandle, setTimerHandle] = React.useState<number | undefined>(undefined) + const dispatch = useAppDispatch() + const teamId = useAppSelector((state) => state.competitionLogin.data?.team_id) + const team = useAppSelector((state) => state.presentation.competition.teams.find((team) => team.id === teamId)) + const answerId = team?.question_answers.find((answer) => answer.question_id === activeSlide?.questions[0].id)?.id + const onAnswerChange = (answer: string) => { + if (timerHandle) { + clearTimeout(timerHandle) + setTimerHandle(undefined) + } + //Only updates answer 100ms after last input was made + setTimerHandle(window.setTimeout(() => updateAnswer(answer), 100)) + } + + const updateAnswer = async (answer: string) => { + if (activeSlide && team) { + if (team?.question_answers.find((answer) => answer.question_id === activeSlide.questions[0].id)) { + await axios + .put(`/api/competitions/${competitionId}/teams/${teamId}/answers/${answerId}`, { + answer, + }) + .then(() => { + dispatch(getEditorCompetition(competitionId)) + }) + .catch(console.log) + } else { + await axios + .post(`/api/competitions/${competitionId}/teams/${teamId}/answers`, { + answer, + score: 0, + question_id: activeSlide.questions[0].id, + }) + .then(() => { + dispatch(getEditorCompetition(competitionId)) + }) + .catch(console.log) + } + } + } + + return ( + <AnswerTextFieldContainer> + <ListItem divider> + <Center> + <ListItemText primary="Skriv ditt svar nedan" /> + </Center> + </ListItem> + <ListItem style={{ height: '100%' }}> + <TextField + disabled={team === undefined} + defaultValue={ + team?.question_answers.find((questionAnswer) => questionAnswer.id === answerId)?.answer || 'Svar...' + } + style={{ height: '100%' }} + variant="outlined" + fullWidth={true} + multiline + onChange={(event) => onAnswerChange(event.target.value)} + /> + </ListItem> + </AnswerTextFieldContainer> + ) +} + +export default AnswerText diff --git a/client/src/pages/presentationEditor/components/answerComponents/styled.tsx b/client/src/pages/presentationEditor/components/answerComponents/styled.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9140e3c2776f5bda3d2f317740bb4bbb67f657ac --- /dev/null +++ b/client/src/pages/presentationEditor/components/answerComponents/styled.tsx @@ -0,0 +1,5 @@ +import styled from 'styled-components' + +export const AnswerTextFieldContainer = styled.div` + height: calc(100% - 90px); +` diff --git a/client/src/pages/presentationEditor/components/slideSettingsComponents/SingleChoiceAlternatives.tsx b/client/src/pages/presentationEditor/components/slideSettingsComponents/SingleChoiceAlternatives.tsx new file mode 100644 index 0000000000000000000000000000000000000000..6e38c39fe443b5c1e78810cb5731690870f8f614 --- /dev/null +++ b/client/src/pages/presentationEditor/components/slideSettingsComponents/SingleChoiceAlternatives.tsx @@ -0,0 +1,131 @@ +import { ListItem, ListItemText } from '@material-ui/core' +import CloseIcon from '@material-ui/icons/Close' +import RadioButtonCheckedIcon from '@material-ui/icons/RadioButtonCheckedOutlined' +import RadioButtonUncheckedIcon from '@material-ui/icons/RadioButtonUncheckedOutlined' +import axios from 'axios' +import React from 'react' +import { getEditorCompetition } from '../../../../actions/editor' +import { useAppDispatch, useAppSelector } from '../../../../hooks' +import { QuestionAlternative } from '../../../../interfaces/ApiModels' +import { RichSlide } from '../../../../interfaces/ApiRichModels' +import { AddButton, AlternativeTextField, Center, Clickable, SettingsList } from '../styled' + +type SingleChoiceAlternativeProps = { + activeSlide: RichSlide + competitionId: string +} + +const SingleChoiceAlternatives = ({ activeSlide, competitionId }: SingleChoiceAlternativeProps) => { + const dispatch = useAppDispatch() + const activeSlideId = useAppSelector((state) => state.editor.activeSlideId) + + const updateAlternativeValue = async (alternative: QuestionAlternative) => { + if (activeSlide && activeSlide.questions[0]) { + // Remove check from previously checked alternative + const previousCheckedAltId = activeSlide.questions[0].alternatives.find((alt) => alt.value === 1)?.id + if (previousCheckedAltId !== alternative.id) { + if (previousCheckedAltId) { + axios.put( + `/api/competitions/${competitionId}/slides/${activeSlide?.id}/questions/${activeSlide?.questions[0].id}/alternatives/${previousCheckedAltId}`, + { value: 0 } + ) + } + // Set new checked alternative + await axios + .put( + `/api/competitions/${competitionId}/slides/${activeSlide?.id}/questions/${activeSlide?.questions[0].id}/alternatives/${alternative.id}`, + { value: 1 } + ) + .then(() => { + dispatch(getEditorCompetition(competitionId)) + }) + .catch(console.log) + } + } + } + + const updateAlternativeText = async (alternative_id: number, newText: string) => { + if (activeSlide && activeSlide.questions[0]) { + await axios + .put( + `/api/competitions/${competitionId}/slides/${activeSlide?.id}/questions/${activeSlide?.questions[0].id}/alternatives/${alternative_id}`, + { text: newText } + ) + .then(() => { + dispatch(getEditorCompetition(competitionId)) + }) + .catch(console.log) + } + } + + const addAlternative = async () => { + if (activeSlide && activeSlide.questions[0]) { + await axios + .post( + `/api/competitions/${competitionId}/slides/${activeSlide?.id}/questions/${activeSlide?.questions[0].id}/alternatives`, + { text: '', value: 0 } + ) + .then(() => { + dispatch(getEditorCompetition(competitionId)) + }) + .catch(console.log) + } + } + + const handleCloseAnswerClick = async (alternative_id: number) => { + if (activeSlide && activeSlide.questions[0]) { + await axios + .delete( + `/api/competitions/${competitionId}/slides/${activeSlideId}/questions/${activeSlide?.questions[0].id}/alternatives/${alternative_id}` + ) + .then(() => { + dispatch(getEditorCompetition(competitionId)) + }) + .catch(console.log) + } + } + + const renderRadioButton = (alt: QuestionAlternative) => { + if (alt.value) return <RadioButtonCheckedIcon onClick={() => updateAlternativeValue(alt)} /> + else return <RadioButtonUncheckedIcon onClick={() => updateAlternativeValue(alt)} /> + } + + return ( + <SettingsList> + <ListItem divider> + <Center> + <ListItemText + primary="Svarsalternativ" + secondary="(Fyll i cirkeln höger om textfältet för att markera korrekt svar)" + /> + </Center> + </ListItem> + {activeSlide && + activeSlide.questions[0] && + activeSlide.questions[0].alternatives && + activeSlide.questions[0].alternatives.map((alt) => ( + <div key={alt.id}> + <ListItem divider> + <AlternativeTextField + id="outlined-basic" + defaultValue={alt.text} + onChange={(event) => updateAlternativeText(alt.id, event.target.value)} + variant="outlined" + /> + <Clickable>{renderRadioButton(alt)}</Clickable> + <Clickable> + <CloseIcon onClick={() => handleCloseAnswerClick(alt.id)} /> + </Clickable> + </ListItem> + </div> + ))} + <ListItem button onClick={addAlternative}> + <Center> + <AddButton variant="button">Lägg till svarsalternativ</AddButton> + </Center> + </ListItem> + </SettingsList> + ) +} + +export default SingleChoiceAlternatives diff --git a/client/src/pages/presentationEditor/components/slideSettingsComponents/SlideType.tsx b/client/src/pages/presentationEditor/components/slideSettingsComponents/SlideType.tsx index b68fee354a931234b496792e6b8c1662cabb2e7e..8fbae43816a55a2be1f1dcc838afffd9f3cf0b9e 100644 --- a/client/src/pages/presentationEditor/components/slideSettingsComponents/SlideType.tsx +++ b/client/src/pages/presentationEditor/components/slideSettingsComponents/SlideType.tsx @@ -15,7 +15,7 @@ import { import axios from 'axios' import React, { useState } from 'react' import { getEditorCompetition } from '../../../../actions/editor' -import { useAppDispatch } from '../../../../hooks' +import { useAppDispatch, useAppSelector } from '../../../../hooks' import { RichSlide } from '../../../../interfaces/ApiRichModels' import { Center, FirstItem } from '../styled' @@ -30,6 +30,11 @@ const SlideType = ({ activeSlide, competitionId }: SlideTypeProps) => { // For "slide type" dialog const [selectedSlideType, setSelectedSlideType] = useState(0) const [slideTypeDialog, setSlideTypeDialog] = useState(false) + const components = useAppSelector( + (state) => state.editor.competition.slides.find((slide) => slide.id === state.editor.activeSlideId)?.components + ) + const questionComponentId = components?.find((qCompId) => qCompId.type_id === 3)?.id + const openSlideTypeDialog = (type_id: number) => { setSelectedSlideType(type_id) setSlideTypeDialog(true) @@ -42,6 +47,7 @@ const SlideType = ({ activeSlide, competitionId }: SlideTypeProps) => { closeSlideTypeDialog() if (activeSlide) { if (activeSlide.questions?.[0] && activeSlide.questions[0].type_id !== selectedSlideType) { + deleteQuestionComponent(questionComponentId) if (selectedSlideType === 0) { // Change slide type from a question type to information await axios @@ -67,6 +73,7 @@ const SlideType = ({ activeSlide, competitionId }: SlideTypeProps) => { }) .then(() => { dispatch(getEditorCompetition(competitionId)) + createQuestionComponent() }) .catch(console.log) } @@ -80,11 +87,38 @@ const SlideType = ({ activeSlide, competitionId }: SlideTypeProps) => { }) .then(() => { dispatch(getEditorCompetition(competitionId)) + createQuestionComponent() }) .catch(console.log) } } } + + const createQuestionComponent = () => { + axios + .post(`/api/competitions/${competitionId}/slides/${activeSlide.id}/components`, { + x: 0, + y: 0, + w: 400, + h: 250, + type_id: 3, + view_type_id: 1, + question_id: activeSlide.questions[0].id, + }) + .then(() => { + dispatch(getEditorCompetition(competitionId)) + }) + .catch(console.log) + } + + const deleteQuestionComponent = (componentId: number | undefined) => { + if (componentId) { + axios + .delete(`/api/competitions/${competitionId}/slides/${activeSlide.id}/components/${componentId}`) + .catch(console.log) + } + } + return ( <FirstItem> <ListItem> @@ -108,7 +142,12 @@ const SlideType = ({ activeSlide, competitionId }: SlideTypeProps) => { </MenuItem> <MenuItem value={3}> <Typography variant="button" onClick={() => openSlideTypeDialog(3)}> - Flervalsfråga + Kryssfråga + </Typography> + </MenuItem> + <MenuItem value={4}> + <Typography variant="button" onClick={() => openSlideTypeDialog(4)}> + Alternativfråga </Typography> </MenuItem> </Select> diff --git a/client/src/pages/presentationEditor/components/styled.tsx b/client/src/pages/presentationEditor/components/styled.tsx index 6c1324bb54e81f9bc440dc1e746a3d73981a4fa4..31e40d51de8a4ecb45fbddf1cda9b7e96d4151f5 100644 --- a/client/src/pages/presentationEditor/components/styled.tsx +++ b/client/src/pages/presentationEditor/components/styled.tsx @@ -136,3 +136,7 @@ export const HoverContainer = styled.div<HoverContainerProps>` export const ImageNameText = styled(ListItemText)` word-break: break-all; ` + +export const QuestionComponent = styled.div` + outline-style: double; +` diff --git a/client/src/pages/views/OperatorViewPage.tsx b/client/src/pages/views/OperatorViewPage.tsx index fd3dd05b78403f3193e3eedd4543368fc7a92306..36aa64d23d16363e2f842a3958bdc30d309faaa1 100644 --- a/client/src/pages/views/OperatorViewPage.tsx +++ b/client/src/pages/views/OperatorViewPage.tsx @@ -27,6 +27,7 @@ import axios from 'axios' import React, { useEffect } from 'react' import { useHistory } from 'react-router-dom' import { useAppSelector } from '../../hooks' +import { RichTeam } from '../../interfaces/ApiRichModels' import { socketConnect, socketEndPresentation, @@ -112,14 +113,13 @@ const OperatorViewPage: React.FC = () => { useEffect(() => { socketConnect() - socketSetSlide // Behövs denna? + socketSetSlide handleOpenCodes() - setTimeout(startCompetition, 1000) // Ghetto, wait for everything to load - // console.log(id) + setTimeout(startCompetition, 1000) // Wait for socket to connect }, []) + /** Handles the browsers back button and if pressed cancels the ongoing competition */ window.onpopstate = () => { - //Handle browser back arrow alert('Tävlingen avslutas för alla') endCompetition() } @@ -135,11 +135,12 @@ const OperatorViewPage: React.FC = () => { } const startCompetition = () => { - socketStartPresentation() + socketStartPresentation() // Calls the socket to start competition console.log('started competition for') console.log(competitionId) } + /** Making sure the user wants to exit the competition by displaying a dialog box */ const handleVerifyExit = () => { setOpen(true) } @@ -154,7 +155,7 @@ const OperatorViewPage: React.FC = () => { setOpen(false) socketEndPresentation() history.push('/admin/tävlingshanterare') - window.location.reload(false) // TODO: fix this ugly hack, we "need" to refresh site to be able to run the competition correctly again + window.location.reload(false) // TODO: fix this, we "need" to refresh site to be able to run the competition correctly again } const getCodes = async () => { @@ -204,12 +205,11 @@ const OperatorViewPage: React.FC = () => { return typeName } - const addScore = (id: number) => { - // Sums the scores for the teams. id must be id-1 because it starts at 1 - + /** Sums the scores for the teams. */ + const addScore = (team: RichTeam) => { let totalScore = 0 - for (let j = 0; j < teams[id - 1].question_answers.length; j++) { - totalScore = totalScore + teams[id - 1].question_answers[j].score + for (let j = 0; j < team.question_answers.length; j++) { + totalScore = totalScore + team.question_answers[j].score } return totalScore } @@ -305,31 +305,6 @@ const OperatorViewPage: React.FC = () => { </OperatorButton> </Tooltip> - {/* - // Manual start button - <Tooltip title="Start Presentation" arrow> - <OperatorButton onClick={startCompetition} variant="contained"> - start - </OperatorButton> - </Tooltip> - - - // This creates a join button, but Operator should not join others, others should join Operator - <Tooltip title="Join Presentation" arrow> - <OperatorButton onClick={socketJoinPresentation} variant="contained"> - <GroupAddIcon fontSize="large" /> - </OperatorButton> - </Tooltip> - - - // This creates another end button, it might not be needed since we already have one - <Tooltip title="End Presentation" arrow> - <OperatorButton onClick={socketEndPresentation} variant="contained"> - <CancelIcon fontSize="large" /> - </OperatorButton> - </Tooltip> - */} - <Tooltip title="Starta Timer" arrow> <OperatorButton onClick={socketStartTimer} variant="contained"> <TimerIcon fontSize="large" /> @@ -373,7 +348,7 @@ const OperatorViewPage: React.FC = () => { {teams && teams.map((team) => ( <ListItem key={team.id}> - {team.name} score:{addScore(team.id)} + {team.name} score:{addScore(team)} </ListItem> ))} </List> diff --git a/client/src/pages/views/components/PresentationComponent.tsx b/client/src/pages/views/components/PresentationComponent.tsx index a41f7912469256a6e946522790f4f8203f8da60f..0a688dc1c1bec3373cbf7a4e782b57fdab58d411 100644 --- a/client/src/pages/views/components/PresentationComponent.tsx +++ b/client/src/pages/views/components/PresentationComponent.tsx @@ -1,21 +1,17 @@ -import { Typography } from '@material-ui/core' import React from 'react' import { Rnd } from 'react-rnd' import { ComponentTypes } from '../../../enum/ComponentTypes' -import { useAppSelector } from '../../../hooks' import { Component, ImageComponent, TextComponent } from '../../../interfaces/ApiModels' import ImageComponentDisplay from '../../presentationEditor/components/ImageComponentDisplay' +import QuestionComponentDisplay from '../../presentationEditor/components/QuestionComponentDisplay' import TextComponentDisplay from '../../presentationEditor/components/TextComponentDisplay' -import { SlideContainer } from './styled' type PresentationComponentProps = { component: Component - width: number - height: number scale: number } -const PresentationComponent = ({ component, width, height, scale }: PresentationComponentProps) => { +const PresentationComponent = ({ component, scale }: PresentationComponentProps) => { const renderInnerComponent = () => { switch (component.type_id) { case ComponentTypes.Text: @@ -28,6 +24,8 @@ const PresentationComponent = ({ component, width, height, scale }: Presentation component={component as ImageComponent} /> ) + case ComponentTypes.Question: + return <QuestionComponentDisplay variant="presentation" /> default: break } diff --git a/client/src/reducers/citiesReducer.ts b/client/src/reducers/citiesReducer.ts index 7f5555b3eb002559df3952dfbac31d178ffd6271..4fbc5a1cc559fe11994b41fed5073dde304472aa 100644 --- a/client/src/reducers/citiesReducer.ts +++ b/client/src/reducers/citiesReducer.ts @@ -2,11 +2,14 @@ import { AnyAction } from 'redux' import Types from '../actions/types' import { City } from '../interfaces/ApiModels' +// Define a type for the city state interface CityState { cities: City[] total: number count: number } + +// Define initial values for the city state const initialState: CityState = { cities: [], total: 0, diff --git a/client/src/reducers/competitionLoginReducer.ts b/client/src/reducers/competitionLoginReducer.ts index 72e5e22ee81aa98b735f670a581ad0c39a810ea9..d06f8e3029f11298dfe905bfd71041d0a06bf8b9 100644 --- a/client/src/reducers/competitionLoginReducer.ts +++ b/client/src/reducers/competitionLoginReducer.ts @@ -1,16 +1,18 @@ import { AnyAction } from 'redux' import Types from '../actions/types' +// Define a type for the competition login data interface CompetitionLoginData { competition_id: number team_id: number | null view: string } - +// Define a type for UI error interface UIError { message: string } +// Define a type for the competition login state interface CompetitionLoginState { loading: boolean errors: null | UIError @@ -19,6 +21,7 @@ interface CompetitionLoginState { initialized: boolean } +// Define the initial values for the competition login state const initialState: CompetitionLoginState = { loading: false, errors: null, diff --git a/client/src/reducers/competitionsReducer.ts b/client/src/reducers/competitionsReducer.ts index bb788da5439874f8f9963dfbb756a222012697e6..8a99b29bfcea7f10ab7e6b83393b76bc16756fa5 100644 --- a/client/src/reducers/competitionsReducer.ts +++ b/client/src/reducers/competitionsReducer.ts @@ -10,6 +10,7 @@ interface CompetitionState { filterParams: CompetitionFilterParams } +// Define the initial values for the competition state const initialState: CompetitionState = { competitions: [], total: 0, diff --git a/client/src/reducers/presentationReducer.ts b/client/src/reducers/presentationReducer.ts index b0c4791e9ab1f0ef05c931caa1fc4e9fe8268917..578b0a279c824210892be87bd69e0f62b74d7c89 100644 --- a/client/src/reducers/presentationReducer.ts +++ b/client/src/reducers/presentationReducer.ts @@ -1,9 +1,10 @@ import { AnyAction } from 'redux' import Types from '../actions/types' -import { Slide, Team } from '../interfaces/ApiModels' +import { Slide } from '../interfaces/ApiModels' import { Timer } from '../interfaces/Timer' import { RichCompetition } from './../interfaces/ApiRichModels' +// Define a type for the presentation state interface PresentationState { competition: RichCompetition slide: Slide @@ -11,6 +12,7 @@ interface PresentationState { timer: Timer } +// Define the initial values for the presentation state const initialState: PresentationState = { competition: { name: '', diff --git a/client/src/reducers/rolesReducer.ts b/client/src/reducers/rolesReducer.ts index 5028ae04cb13a4b1bf44536cd42bf3f8935b268c..8fc1465ae10f50dbf25d52b0f013c72647f5321a 100644 --- a/client/src/reducers/rolesReducer.ts +++ b/client/src/reducers/rolesReducer.ts @@ -2,9 +2,12 @@ import { AnyAction } from 'redux' import Types from '../actions/types' import { Role } from '../interfaces/ApiModels' +// Define a type for the role state interface RoleState { roles: Role[] } + +// Define the initial values for the role state const initialState: RoleState = { roles: [], } diff --git a/client/src/reducers/searchUserReducer.ts b/client/src/reducers/searchUserReducer.ts index e0c1250683ae273318a4bcd6e4a3f5ae5f6324bd..38269dfb604ddd5072293f8c101088012ce8f7f5 100644 --- a/client/src/reducers/searchUserReducer.ts +++ b/client/src/reducers/searchUserReducer.ts @@ -3,6 +3,7 @@ import Types from '../actions/types' import { User } from '../interfaces/ApiModels' import { UserFilterParams } from '../interfaces/FilterParams' +// Define a type for the search user state interface SearchUserState { users: User[] total: number @@ -10,6 +11,7 @@ interface SearchUserState { filterParams: UserFilterParams } +// Define the initial values for the search user state const initialState: SearchUserState = { users: [], total: 0, diff --git a/client/src/reducers/statisticsReducer.ts b/client/src/reducers/statisticsReducer.ts index 78a06e1157f6428c10ea17073afbdf46cf8609e5..bc957ccb97f2fde20eca5d44bf818650a7a01eb7 100644 --- a/client/src/reducers/statisticsReducer.ts +++ b/client/src/reducers/statisticsReducer.ts @@ -1,12 +1,14 @@ import { AnyAction } from 'redux' import Types from '../actions/types' +// Define a type for the statistics state interface StatisticsState { users: number competitions: number regions: number } +// Define the initial values for the statistics state const initialState: StatisticsState = { users: 0, competitions: 0, diff --git a/client/src/reducers/typesReducer.ts b/client/src/reducers/typesReducer.ts index 3540ef86fbd4a921738d896b2b0bebb14b3216e0..10ea1c63b3f9f8f2b47f997d1036f71bc51450ac 100644 --- a/client/src/reducers/typesReducer.ts +++ b/client/src/reducers/typesReducer.ts @@ -2,12 +2,14 @@ import { AnyAction } from 'redux' import Types from '../actions/types' import { ComponentType, MediaType, QuestionType, ViewType } from '../interfaces/ApiModels' +// Define a type for the Types state interface TypesState { componentTypes: ComponentType[] viewTypes: ViewType[] questionTypes: QuestionType[] mediaTypes: MediaType[] } +// Define the initial values for the types state const initialState: TypesState = { componentTypes: [], viewTypes: [], diff --git a/client/src/reducers/uiReducer.ts b/client/src/reducers/uiReducer.ts index 4d06d1e298bab88cbfe2f41a54284a2557660a33..350f7b8e8aaa08752252343a95f4703770d2bb77 100644 --- a/client/src/reducers/uiReducer.ts +++ b/client/src/reducers/uiReducer.ts @@ -1,15 +1,18 @@ import { AnyAction } from 'redux' import Types from '../actions/types' +// Define a type for the UI error interface UIError { message: string } +// Define a type for the UI state interface UIState { loading: boolean errors: null | UIError } +// Define the initial values for the UI state const initialState: UIState = { loading: false, errors: null, diff --git a/client/src/reducers/userReducer.ts b/client/src/reducers/userReducer.ts index 91c056d3f0a55383fed0a0e40d0e94240d14a947..6b4f985b43a80a8f2cd91213a6b4c938f6543560 100644 --- a/client/src/reducers/userReducer.ts +++ b/client/src/reducers/userReducer.ts @@ -1,6 +1,7 @@ import { AnyAction } from 'redux' import Types from '../actions/types' +// Define a type for users info interface UserInfo { name: string email: string @@ -9,12 +10,14 @@ interface UserInfo { id: number } +// Define a type for the users state interface UserState { authenticated: boolean userInfo: UserInfo | null loading: boolean } +// Define the initial values for the users state const initialState: UserState = { authenticated: false, loading: false, diff --git a/client/src/utils/renderSlideIcon.tsx b/client/src/utils/renderSlideIcon.tsx index ba1eafcb8052469dd8b627b95d2eee518bfd5fe8..22f6405abbc8574ae17bf86dd8b745ba98e3b4cf 100644 --- a/client/src/utils/renderSlideIcon.tsx +++ b/client/src/utils/renderSlideIcon.tsx @@ -1,9 +1,10 @@ -import { RichSlide } from '../interfaces/ApiRichModels' -import React from 'react' import BuildOutlinedIcon from '@material-ui/icons/BuildOutlined' +import CheckBoxOutlinedIcon from '@material-ui/icons/CheckBoxOutlined' import CreateOutlinedIcon from '@material-ui/icons/CreateOutlined' -import DnsOutlinedIcon from '@material-ui/icons/DnsOutlined' import InfoOutlinedIcon from '@material-ui/icons/InfoOutlined' +import RadioButtonCheckedIcon from '@material-ui/icons/RadioButtonChecked' +import React from 'react' +import { RichSlide } from '../interfaces/ApiRichModels' export const renderSlideIcon = (slide: RichSlide) => { if (slide.questions && slide.questions[0] && slide.questions[0].type_id) { @@ -13,7 +14,9 @@ export const renderSlideIcon = (slide: RichSlide) => { case 2: return <BuildOutlinedIcon /> // practical qustion case 3: - return <DnsOutlinedIcon /> // multiple choice question + return <CheckBoxOutlinedIcon /> // multiple choice question + case 4: + return <RadioButtonCheckedIcon /> // single choice question } } else { return <InfoOutlinedIcon /> // information slide diff --git a/server/app/apis/alternatives.py b/server/app/apis/alternatives.py index 94f6d6b1725106a3cf5994570e4d3d5829ba2dbe..1827b358769441fd5d4748fabacf4221573c3346 100644 --- a/server/app/apis/alternatives.py +++ b/server/app/apis/alternatives.py @@ -1,10 +1,14 @@ +""" +All API calls concerning question alternatives. +Default route: /api/competitions/<competition_id>/slides/<slide_id>/questions/<question_id>/alternatives +""" + import app.core.http_codes as codes import app.database.controller as dbc from app.apis import item_response, list_response, protect_route from app.core.dto import QuestionAlternativeDTO -from flask_restx import Resource -from flask_restx import reqparse from app.core.parsers import sentinel +from flask_restx import Resource, reqparse api = QuestionAlternativeDTO.api schema = QuestionAlternativeDTO.schema @@ -24,11 +28,22 @@ alternative_parser_edit.add_argument("value", type=int, default=sentinel, locati class QuestionAlternativeList(Resource): @protect_route(allowed_roles=["*"], allowed_views=["*"]) def get(self, competition_id, slide_id, question_id): - items = dbc.get.question_alternative_list(competition_id, slide_id, question_id) + """ Gets the all question alternatives to the specified question. """ + + items = dbc.get.question_alternative_list( + competition_id, + slide_id, + question_id, + ) return list_response(list_schema.dump(items)) @protect_route(allowed_roles=["*"]) def post(self, competition_id, slide_id, question_id): + """ + Posts a new question alternative to the specified + question using the provided arguments. + """ + args = alternative_parser_add.parse_args(strict=True) item = dbc.add.question_alternative(**args, question_id=question_id) return item_response(schema.dump(item)) @@ -39,18 +54,41 @@ class QuestionAlternativeList(Resource): class QuestionAlternatives(Resource): @protect_route(allowed_roles=["*"], allowed_views=["*"]) def get(self, competition_id, slide_id, question_id, alternative_id): - items = dbc.get.question_alternative(competition_id, slide_id, question_id, alternative_id) + """ Gets the specified question alternative. """ + + items = dbc.get.question_alternative( + competition_id, + slide_id, + question_id, + alternative_id, + ) return item_response(schema.dump(items)) @protect_route(allowed_roles=["*"]) def put(self, competition_id, slide_id, question_id, alternative_id): + """ + Edits the specified question alternative using the provided arguments. + """ + args = alternative_parser_edit.parse_args(strict=True) - item = dbc.get.question_alternative(competition_id, slide_id, question_id, alternative_id) + item = dbc.get.question_alternative( + competition_id, + slide_id, + question_id, + alternative_id, + ) item = dbc.edit.default(item, **args) return item_response(schema.dump(item)) @protect_route(allowed_roles=["*"]) def delete(self, competition_id, slide_id, question_id, alternative_id): - item = dbc.get.question_alternative(competition_id, slide_id, question_id, alternative_id) + """ Deletes the specified question alternative. """ + + item = dbc.get.question_alternative( + competition_id, + slide_id, + question_id, + alternative_id, + ) dbc.delete.default(item) return {}, codes.NO_CONTENT diff --git a/server/app/apis/answers.py b/server/app/apis/answers.py index 6d0490a9328af2b903522fbeefe5224dcc645e06..c1ccd68b94d8d86faa0c214b5248670db260a73d 100644 --- a/server/app/apis/answers.py +++ b/server/app/apis/answers.py @@ -1,9 +1,13 @@ +""" +All API calls concerning question answers. +Default route: /api/competitions/<competition_id>/teams/<team_id>/answers +""" + import app.database.controller as dbc from app.apis import item_response, list_response, protect_route from app.core.dto import QuestionAnswerDTO -from flask_restx import Resource -from flask_restx import reqparse from app.core.parsers import sentinel +from flask_restx import Resource, reqparse api = QuestionAnswerDTO.api schema = QuestionAnswerDTO.schema @@ -24,11 +28,18 @@ answer_parser_edit.add_argument("score", type=int, default=sentinel, location="j class QuestionAnswerList(Resource): @protect_route(allowed_roles=["*"], allowed_views=["*"]) def get(self, competition_id, team_id): + """ Gets all question answers that the specified team has given. """ + items = dbc.get.question_answer_list(competition_id, team_id) return list_response(list_schema.dump(items)) @protect_route(allowed_roles=["*"], allowed_views=["*"]) def post(self, competition_id, team_id): + """ + Posts a new question answer to the specified + question using the provided arguments. + """ + args = answer_parser_add.parse_args(strict=True) item = dbc.add.question_answer(**args, team_id=team_id) return item_response(schema.dump(item)) @@ -39,12 +50,19 @@ class QuestionAnswerList(Resource): class QuestionAnswers(Resource): @protect_route(allowed_roles=["*"], allowed_views=["*"]) def get(self, competition_id, team_id, answer_id): + """ Gets the specified question answer. """ + item = dbc.get.question_answer(competition_id, team_id, answer_id) return item_response(schema.dump(item)) @protect_route(allowed_roles=["*"], allowed_views=["*"]) def put(self, competition_id, team_id, answer_id): + """ Edits the specified question answer with the provided arguments. """ + args = answer_parser_edit.parse_args(strict=True) item = dbc.get.question_answer(competition_id, team_id, answer_id) item = dbc.edit.default(item, **args) return item_response(schema.dump(item)) + + # No need to delete an answer. It only needs to be deleted + # together with the question or the team. diff --git a/server/app/apis/auth.py b/server/app/apis/auth.py index bf9eeefde781f3fcacfd4bdafade8829db24acaa..e6a5345bd0346eb9959a94bb7d28f3a9e15f0097 100644 --- a/server/app/apis/auth.py +++ b/server/app/apis/auth.py @@ -1,4 +1,9 @@ -from datetime import timedelta +""" +All API calls concerning question answers. +Default route: /api/auth +""" + +from datetime import datetime, timedelta import app.core.http_codes as codes import app.database.controller as dbc @@ -6,7 +11,8 @@ from app.apis import item_response, protect_route, text_response from app.core import sockets from app.core.codes import verify_code from app.core.dto import AuthDTO -from app.database.models import Whitelist +from app.database.models import User, Whitelist +from flask import current_app from flask_jwt_extended import create_access_token, get_jti, get_raw_jwt from flask_jwt_extended.utils import get_jti from flask_restx import Resource, inputs, reqparse @@ -26,12 +32,19 @@ create_user_parser.add_argument("role_id", type=int, required=True, location="js login_code_parser = reqparse.RequestParser() login_code_parser.add_argument("code", type=str, required=True, location="json") +USER_LOGIN_LOCKED_ATTEMPTS = current_app.config["USER_LOGIN_LOCKED_ATTEMPTS"] +USER_LOGIN_LOCKED_EXPIRES = current_app.config["USER_LOGIN_LOCKED_EXPIRES"] + def get_user_claims(item_user): + """ Gets user details for jwt-token. """ + return {"role": item_user.role.name, "city_id": item_user.city_id} def get_code_claims(item_code): + """ Gets code details for jwt-token. """ + return { "view": item_code.view_type.name, "competition_id": item_code.competition_id, @@ -44,6 +57,8 @@ def get_code_claims(item_code): class AuthSignup(Resource): @protect_route(allowed_roles=["Admin"], allowed_views=["*"]) def get(self): + """ Tests that the user is an admin. """ + return "ok" @@ -51,12 +66,16 @@ class AuthSignup(Resource): class AuthSignup(Resource): @protect_route(allowed_roles=["Admin"]) def post(self): + """ Creates a new user if the user does not already exist. """ + args = create_user_parser.parse_args(strict=True) email = args.get("email") + # Check if email is already used if dbc.get.user_exists(email): api.abort(codes.BAD_REQUEST, "User already exists") + # Add user item_user = dbc.add.user(**args) return item_response(schema.dump(item_user)) @@ -66,28 +85,65 @@ class AuthSignup(Resource): class AuthDelete(Resource): @protect_route(allowed_roles=["Admin"]) def delete(self, user_id): - item_user = dbc.get.user(user_id) + """ Deletes the specified user and adds their token to the blacklist. """ + + item_user = dbc.get.one(User, user_id) + + # Blacklist all the whitelisted tokens + # in use for the user that will be deleted dbc.delete.whitelist_to_blacklist(Whitelist.user_id == user_id) - dbc.delete.default(item_user) + # Delete user + dbc.delete.default(item_user) return text_response(f"User {user_id} deleted") @api.route("/login") class AuthLogin(Resource): def post(self): + """ Logs in the specified user and creates a jwt-token. """ + args = login_parser.parse_args(strict=True) email = args.get("email") password = args.get("password") + item_user = dbc.get.user_by_email(email) - if not item_user or not item_user.is_correct_password(password): + # Login with unkown email + if not item_user: api.abort(codes.UNAUTHORIZED, "Invalid email or password") + # Login with existing email but with wrong password + if not item_user.is_correct_password(password): + # Increase the login attempts every time the user tries to login with wrong password + item_user.login_attempts += 1 + + # Lock the user out for some time + if item_user.login_attempts == USER_LOGIN_LOCKED_ATTEMPTS: + item_user.locked = datetime.now() + USER_LOGIN_LOCKED_EXPIRES + + dbc.utils.commit() + api.abort(codes.UNAUTHORIZED, "Invalid email or password") + + # Otherwise if login was successful but the user is locked + if item_user.locked: + # Check if locked is greater than now + if item_user.locked > datetime.now(): + api.abort(codes.UNAUTHORIZED, f"Try again in {item_user.locked} hours.") + else: + item_user.locked = None + + # If everything else was successful, set login_attempts to 0 + item_user.login_attempts = 0 + dbc.utils.commit() + + # Create the jwt with user.id as the identifier access_token = create_access_token(item_user.id, user_claims=get_user_claims(item_user)) - # refresh_token = create_refresh_token(item_user.id) + # Login response includes the id and jwt for the user response = {"id": item_user.id, "access_token": access_token} + + # Whitelist the created jwt dbc.add.whitelist(get_jti(access_token), item_user.id) return response @@ -95,9 +151,12 @@ class AuthLogin(Resource): @api.route("/login/code") class AuthLoginCode(Resource): def post(self): + """ Logs in using the provided competition code. """ + args = login_code_parser.parse_args() code = args["code"] + # Check so the code string is valid if not verify_code(code): api.abort(codes.UNAUTHORIZED, "Invalid code") @@ -107,10 +166,12 @@ class AuthLoginCode(Resource): if item_code.competition_id not in sockets.presentations: api.abort(codes.UNAUTHORIZED, "Competition not active") + # Create jwt that is only valid for 8 hours access_token = create_access_token( item_code.id, user_claims=get_code_claims(item_code), expires_delta=timedelta(hours=8) ) + # Whitelist the created jwt dbc.add.whitelist(get_jti(access_token), competition_id=item_code.competition_id) response = { "competition_id": item_code.competition_id, @@ -125,9 +186,16 @@ class AuthLoginCode(Resource): class AuthLogout(Resource): @protect_route(allowed_roles=["*"], allowed_views=["*"]) def post(self): + """ Logs out. """ + jti = get_raw_jwt()["jti"] + + # Blacklist the token so the user cannot access the api anymore dbc.add.blacklist(jti) + + # Remove the the token from the whitelist since it's blacklisted now Whitelist.query.filter(Whitelist.jti == jti).delete() + dbc.utils.commit() return text_response("Logout") diff --git a/server/app/apis/codes.py b/server/app/apis/codes.py index 6409109ef875efc13a5c12040a100b28822ed6ae..45f9578280e82c306ff716a646505dbffd62be3b 100644 --- a/server/app/apis/codes.py +++ b/server/app/apis/codes.py @@ -1,3 +1,8 @@ +""" +All API calls concerning competition codes. +Default route: /api/competitions/<competition_id>/codes +""" + import app.database.controller as dbc from app.apis import item_response, list_response, protect_route from app.core.dto import CodeDTO @@ -14,6 +19,8 @@ list_schema = CodeDTO.list_schema class CodesList(Resource): @protect_route(allowed_roles=["*"], allowed_views=["Operator"]) def get(self, competition_id): + """ Gets the all competition codes. """ + items = dbc.get.code_list(competition_id) return list_response(list_schema.dump(items), len(items)) @@ -23,6 +30,8 @@ class CodesList(Resource): class CodesById(Resource): @protect_route(allowed_roles=["*"]) def put(self, competition_id, code_id): + """ Generates a new competition code. """ + item = dbc.get.one(Code, code_id) item.code = dbc.utils.generate_unique_code() dbc.utils.commit_and_refresh(item) diff --git a/server/app/apis/competitions.py b/server/app/apis/competitions.py index bfd06fac35c811fe276787b3027cad5d0d1f99a9..2d381425c9e5d3f41bba347128aab7b659bf8885 100644 --- a/server/app/apis/competitions.py +++ b/server/app/apis/competitions.py @@ -1,10 +1,14 @@ +""" +All API calls concerning competitions. +Default route: /api/competitions +""" + import app.database.controller as dbc from app.apis import item_response, list_response, protect_route from app.core.dto import CompetitionDTO -from app.database.models import Competition -from flask_restx import Resource -from flask_restx import reqparse from app.core.parsers import search_parser, sentinel +from app.database.models import Competition +from flask_restx import Resource, reqparse api = CompetitionDTO.api schema = CompetitionDTO.schema @@ -32,6 +36,8 @@ competition_parser_search.add_argument("city_id", type=int, default=sentinel, lo class CompetitionsList(Resource): @protect_route(allowed_roles=["*"]) def post(self): + """ Posts a new competition. """ + args = competition_parser_add.parse_args(strict=True) # Add competition @@ -47,12 +53,16 @@ class CompetitionsList(Resource): class Competitions(Resource): @protect_route(allowed_roles=["*"], allowed_views=["*"]) def get(self, competition_id): + """ Gets the specified competition. """ + item = dbc.get.competition(competition_id) return item_response(rich_schema.dump(item)) @protect_route(allowed_roles=["*"]) def put(self, competition_id): + """ Edits the specified competition with the specified arguments. """ + args = competition_parser_edit.parse_args(strict=True) item = dbc.get.one(Competition, competition_id) item = dbc.edit.default(item, **args) @@ -61,6 +71,8 @@ class Competitions(Resource): @protect_route(allowed_roles=["*"]) def delete(self, competition_id): + """ Deletes the specified competition. """ + item = dbc.get.one(Competition, competition_id) dbc.delete.competition(item) @@ -71,6 +83,8 @@ class Competitions(Resource): class CompetitionSearch(Resource): @protect_route(allowed_roles=["*"]) def get(self): + """ Finds a specific competition based on the provided arguments. """ + args = competition_parser_search.parse_args(strict=True) items, total = dbc.search.competition(**args) return list_response(list_schema.dump(items), total) @@ -81,6 +95,8 @@ class CompetitionSearch(Resource): class SlidesOrder(Resource): @protect_route(allowed_roles=["*"]) def post(self, competition_id): + """ Creates a deep copy of the specified competition. """ + item_competition = dbc.get.competition(competition_id) item_competition_copy = dbc.copy.competition(item_competition) diff --git a/server/app/apis/components.py b/server/app/apis/components.py index 38227a46d90fe2afb5ea4a2fc7924412661c5259..39e1932824f6e6ab103f773402bb1c3feb331e43 100644 --- a/server/app/apis/components.py +++ b/server/app/apis/components.py @@ -1,17 +1,21 @@ +""" +All API calls concerning competitions. +Default route: /api/competitions/<competition_id>/slides/<slide_id>/components +""" + import app.core.http_codes as codes import app.database.controller as dbc from app.apis import item_response, list_response, protect_route from app.core.dto import ComponentDTO -from flask_restx import Resource -from flask_restx import reqparse from app.core.parsers import sentinel +from flask_restx import Resource, reqparse api = ComponentDTO.api schema = ComponentDTO.schema list_schema = ComponentDTO.list_schema component_parser_add = reqparse.RequestParser() -component_parser_add.add_argument("x", type=str, default=0, location="json") +component_parser_add.add_argument("x", type=int, default=0, location="json") component_parser_add.add_argument("y", type=int, default=0, location="json") component_parser_add.add_argument("w", type=int, default=1, location="json") component_parser_add.add_argument("h", type=int, default=1, location="json") @@ -22,7 +26,7 @@ component_parser_add.add_argument("media_id", type=int, default=None, location=" component_parser_add.add_argument("question_id", type=int, default=None, location="json") component_parser_edit = reqparse.RequestParser() -component_parser_edit.add_argument("x", type=str, default=sentinel, location="json") +component_parser_edit.add_argument("x", type=int, default=sentinel, location="json") component_parser_edit.add_argument("y", type=int, default=sentinel, location="json") component_parser_edit.add_argument("w", type=int, default=sentinel, location="json") component_parser_edit.add_argument("h", type=int, default=sentinel, location="json") @@ -31,16 +35,39 @@ component_parser_edit.add_argument("media_id", type=int, default=sentinel, locat component_parser_edit.add_argument("question_id", type=int, default=sentinel, location="json") +@api.route("") +@api.param("competition_id, slide_id") +class ComponentList(Resource): + @protect_route(allowed_roles=["*"], allowed_views=["*"]) + def get(self, competition_id, slide_id): + """ Gets all components in the specified slide and competition. """ + + items = dbc.get.component_list(competition_id, slide_id) + return list_response(list_schema.dump(items)) + + @protect_route(allowed_roles=["*"]) + def post(self, competition_id, slide_id): + """ Posts a new component to the specified slide. """ + + args = component_parser_add.parse_args() + item = dbc.add.component(slide_id=slide_id, **args) + return item_response(schema.dump(item)) + + @api.route("/<component_id>") @api.param("competition_id, slide_id, component_id") class ComponentByID(Resource): @protect_route(allowed_roles=["*"], allowed_views=["*"]) def get(self, competition_id, slide_id, component_id): + """ Gets the specified component. """ + item = dbc.get.component(competition_id, slide_id, component_id) return item_response(schema.dump(item)) @protect_route(allowed_roles=["*"]) def put(self, competition_id, slide_id, component_id): + """ Edits the specified component using the provided arguments. """ + args = component_parser_edit.parse_args(strict=True) item = dbc.get.component(competition_id, slide_id, component_id) args_without_sentinel = {key: value for key, value in args.items() if value is not sentinel} @@ -49,6 +76,8 @@ class ComponentByID(Resource): @protect_route(allowed_roles=["*"]) def delete(self, competition_id, slide_id, component_id): + """ Deletes the specified component. """ + item = dbc.get.component(competition_id, slide_id, component_id) dbc.delete.component(item) return {}, codes.NO_CONTENT @@ -59,21 +88,12 @@ class ComponentByID(Resource): class ComponentList(Resource): @protect_route(allowed_roles=["*"]) def post(self, competition_id, slide_id, component_id, view_type_id): - item_component = dbc.get.component(competition_id, slide_id, component_id) - item = dbc.copy.component(item_component, slide_id, view_type_id) - return item_response(schema.dump(item)) - - -@api.route("") -@api.param("competition_id, slide_id") -class ComponentList(Resource): - @protect_route(allowed_roles=["*"], allowed_views=["*"]) - def get(self, competition_id, slide_id): - items = dbc.get.component_list(competition_id, slide_id) - return list_response(list_schema.dump(items)) + """ Creates a deep copy of the specified component. """ - @protect_route(allowed_roles=["*"]) - def post(self, competition_id, slide_id): - args = component_parser_add.parse_args() - item = dbc.add.component(slide_id=slide_id, **args) + item_component = dbc.get.component( + competition_id, + slide_id, + component_id, + ) + item = dbc.copy.component(item_component, slide_id, view_type_id) return item_response(schema.dump(item)) diff --git a/server/app/apis/media.py b/server/app/apis/media.py index 49d20608840e320ef3d73d9df848748e6da33617..c59589a60afb5944fdd45fea0b230187d8d8da8b 100644 --- a/server/app/apis/media.py +++ b/server/app/apis/media.py @@ -1,16 +1,20 @@ +""" +All API calls concerning media. +Default route: /api/media +""" + +import app.core.files as files import app.core.http_codes as codes import app.database.controller as dbc from app.apis import item_response, list_response, protect_route from app.core.dto import MediaDTO -from app.core.parsers import search_parser +from app.core.parsers import search_parser, sentinel from app.database.models import Media from flask import request from flask_jwt_extended import get_jwt_identity from flask_restx import Resource from flask_uploads import UploadNotAllowed from sqlalchemy import exc -import app.core.files as files -from app.core.parsers import sentinel api = MediaDTO.api image_set = MediaDTO.image_set @@ -25,12 +29,16 @@ media_parser_search.add_argument("filename", type=str, default=sentinel, locatio class ImageList(Resource): @protect_route(allowed_roles=["*"]) def get(self): + """ Gets a list of all images with the specified filename. """ + args = media_parser_search.parse_args(strict=True) items, total = dbc.search.image(**args) return list_response(list_schema.dump(items), total) @protect_route(allowed_roles=["*"]) def post(self): + """ Posts the specified image. """ + if "image" not in request.files: api.abort(codes.BAD_REQUEST, "Missing image in request.files") try: @@ -51,11 +59,15 @@ class ImageList(Resource): class ImageList(Resource): @protect_route(allowed_roles=["*"], allowed_views=["*"]) def get(self, ID): + """ Gets the specified image. """ + item = dbc.get.one(Media, ID) return item_response(schema.dump(item)) @protect_route(allowed_roles=["*"]) def delete(self, ID): + """ Deletes the specified image. """ + item = dbc.get.one(Media, ID) try: files.delete_image_and_thumbnail(item.filename) diff --git a/server/app/apis/misc.py b/server/app/apis/misc.py index a9069f6dd916af90b764b6703f83bb227fbcc2a4..552a0ad0c4848c33a08bcb63ccc3e870acd6af48 100644 --- a/server/app/apis/misc.py +++ b/server/app/apis/misc.py @@ -1,10 +1,14 @@ +""" +All misc API calls. +Default route: /api/misc +""" + import app.database.controller as dbc from app.apis import list_response, protect_route from app.core import http_codes from app.core.dto import MiscDTO from app.database.models import City, Competition, ComponentType, MediaType, QuestionType, Role, User, ViewType from flask_restx import Resource, reqparse -from flask_restx import reqparse api = MiscDTO.api @@ -24,6 +28,8 @@ name_parser.add_argument("name", type=str, required=True, location="json") @api.route("/types") class TypesList(Resource): def get(self): + """ Gets a list of all types. """ + result = {} result["media_types"] = media_type_schema.dump(dbc.get.all(MediaType)) result["component_types"] = component_type_schema.dump(dbc.get.all(ComponentType)) @@ -36,6 +42,8 @@ class TypesList(Resource): class RoleList(Resource): @protect_route(allowed_roles=["*"]) def get(self): + """ Gets a list of all roles. """ + items = dbc.get.all(Role) return list_response(role_schema.dump(items)) @@ -44,11 +52,15 @@ class RoleList(Resource): class CitiesList(Resource): @protect_route(allowed_roles=["*"]) def get(self): + """ Gets a list of all cities. """ + items = dbc.get.all(City) return list_response(city_schema.dump(items)) @protect_route(allowed_roles=["Admin"]) def post(self): + """ Posts the specified city. """ + args = name_parser.parse_args(strict=True) dbc.add.city(args["name"]) items = dbc.get.all(City) @@ -60,6 +72,8 @@ class CitiesList(Resource): class Cities(Resource): @protect_route(allowed_roles=["Admin"]) def put(self, ID): + """ Edits the specified city with the provided arguments. """ + item = dbc.get.one(City, ID) args = name_parser.parse_args(strict=True) item.name = args["name"] @@ -69,6 +83,8 @@ class Cities(Resource): @protect_route(allowed_roles=["Admin"]) def delete(self, ID): + """ Deletes the specified city. """ + item = dbc.get.one(City, ID) dbc.delete.default(item) items = dbc.get.all(City) @@ -79,6 +95,8 @@ class Cities(Resource): class Statistics(Resource): @protect_route(allowed_roles=["*"]) def get(self): + """ Gets statistics. """ + user_count = User.query.count() competition_count = Competition.query.count() region_count = City.query.count() diff --git a/server/app/apis/questions.py b/server/app/apis/questions.py index 94df2a36456baf6e8a492250944dc4156b5aa21f..6ba32382fa524180c76eef35bd02a68382e552c6 100644 --- a/server/app/apis/questions.py +++ b/server/app/apis/questions.py @@ -1,10 +1,14 @@ +""" +All API calls concerning question answers. +Default route: /api/competitions/<competition_id> +""" + import app.core.http_codes as codes import app.database.controller as dbc from app.apis import item_response, list_response, protect_route from app.core.dto import QuestionDTO -from flask_restx import Resource -from flask_restx import reqparse from app.core.parsers import sentinel +from flask_restx import Resource, reqparse api = QuestionDTO.api schema = QuestionDTO.schema @@ -28,6 +32,8 @@ question_parser_edit.add_argument("correcting_instructions", type=str, default=s class QuestionList(Resource): @protect_route(allowed_roles=["*"]) def get(self, competition_id): + """ Gets all questions in the specified competition. """ + items = dbc.get.question_list_for_competition(competition_id) return list_response(list_schema.dump(items)) @@ -37,11 +43,15 @@ class QuestionList(Resource): class QuestionListForSlide(Resource): @protect_route(allowed_roles=["*"]) def get(self, competition_id, slide_id): + """ Gets all questions in the specified competition and slide. """ + items = dbc.get.question_list(competition_id, slide_id) return list_response(list_schema.dump(items)) @protect_route(allowed_roles=["*"]) def post(self, competition_id, slide_id): + """ Posts a new question to the specified slide using the provided arguments. """ + args = question_parser_add.parse_args(strict=True) item = dbc.add.question(slide_id=slide_id, **args) return item_response(schema.dump(item)) @@ -52,11 +62,17 @@ class QuestionListForSlide(Resource): class QuestionById(Resource): @protect_route(allowed_roles=["*"]) def get(self, competition_id, slide_id, question_id): + """ + Gets the specified question using the specified competition and slide. + """ + item_question = dbc.get.question(competition_id, slide_id, question_id) return item_response(schema.dump(item_question)) @protect_route(allowed_roles=["*"]) def put(self, competition_id, slide_id, question_id): + """ Edits the specified question with the provided arguments. """ + args = question_parser_edit.parse_args(strict=True) item_question = dbc.get.question(competition_id, slide_id, question_id) @@ -66,6 +82,8 @@ class QuestionById(Resource): @protect_route(allowed_roles=["*"]) def delete(self, competition_id, slide_id, question_id): + """ Deletes the specified question. """ + item_question = dbc.get.question(competition_id, slide_id, question_id) dbc.delete.question(item_question) return {}, codes.NO_CONTENT diff --git a/server/app/apis/slides.py b/server/app/apis/slides.py index aa5bee3cad42e58e83b067eb1970f6b60d2cca27..ee9689b51ad13a95941b7b9033ec3556d33f74b6 100644 --- a/server/app/apis/slides.py +++ b/server/app/apis/slides.py @@ -1,3 +1,8 @@ +""" +All API calls concerning question alternatives. +Default route: /api/competitions/<competition_id>/slides +""" + import app.core.http_codes as codes import app.database.controller as dbc from app.apis import item_response, list_response, protect_route @@ -21,25 +26,33 @@ slide_parser_edit.add_argument("background_image_id", default=sentinel, type=int class SlidesList(Resource): @protect_route(allowed_roles=["*"]) def get(self, competition_id): + """ Gets all slides from the specified competition. """ + items = dbc.get.slide_list(competition_id) return list_response(list_schema.dump(items)) @protect_route(allowed_roles=["*"]) def post(self, competition_id): + """ Posts a new slide to the specified competition. """ + item_slide = dbc.add.slide(competition_id) return item_response(schema.dump(item_slide)) @api.route("/<slide_id>") -@api.param("competition_id,slide_id") +@api.param("competition_id, slide_id") class Slides(Resource): @protect_route(allowed_roles=["*"]) def get(self, competition_id, slide_id): + """ Gets the specified slide. """ + item_slide = dbc.get.slide(competition_id, slide_id) return item_response(schema.dump(item_slide)) @protect_route(allowed_roles=["*"]) def put(self, competition_id, slide_id): + """ Edits the specified slide using the provided arguments. """ + args = slide_parser_edit.parse_args(strict=True) item_slide = dbc.get.slide(competition_id, slide_id) @@ -49,6 +62,8 @@ class Slides(Resource): @protect_route(allowed_roles=["*"]) def delete(self, competition_id, slide_id): + """ Deletes the specified slide. """ + item_slide = dbc.get.slide(competition_id, slide_id) dbc.delete.slide(item_slide) @@ -56,10 +71,12 @@ class Slides(Resource): @api.route("/<slide_id>/order") -@api.param("competition_id,slide_id") +@api.param("competition_id, slide_id") class SlideOrder(Resource): @protect_route(allowed_roles=["*"]) def put(self, competition_id, slide_id): + """ Edits the specified slide order using the provided arguments. """ + args = slide_parser_edit.parse_args(strict=True) order = args.get("order") @@ -89,8 +106,9 @@ class SlideOrder(Resource): class SlideCopy(Resource): @protect_route(allowed_roles=["*"]) def post(self, competition_id, slide_id): - item_slide = dbc.get.slide(competition_id, slide_id) + """ Creates a deep copy of the specified slide. """ + item_slide = dbc.get.slide(competition_id, slide_id) item_slide_copy = dbc.copy.slide(item_slide) return item_response(schema.dump(item_slide_copy)) diff --git a/server/app/apis/teams.py b/server/app/apis/teams.py index 71ca715d55d21de75f07db4241e5ef0bb14e1050..913deeb789340939c3dcb37f4a3edefbd7d06e95 100644 --- a/server/app/apis/teams.py +++ b/server/app/apis/teams.py @@ -1,9 +1,14 @@ +""" +All API calls concerning question alternatives. +Default route: /api/competitions/<competition_id>/teams +""" + import app.core.http_codes as codes import app.database.controller as dbc from app.apis import item_response, list_response, protect_route from app.core.dto import TeamDTO -from flask_restx import Resource, reqparse from app.core.parsers import sentinel +from flask_restx import Resource, reqparse api = TeamDTO.api schema = TeamDTO.schema @@ -21,11 +26,15 @@ team_parser_edit.add_argument("name", type=str, default=sentinel, location="json class TeamsList(Resource): @protect_route(allowed_roles=["*"]) def get(self, competition_id): + """ Gets all teams to the specified competition. """ + items = dbc.get.team_list(competition_id) return list_response(list_schema.dump(items)) @protect_route(allowed_roles=["*"]) def post(self, competition_id): + """ Posts a new team to the specified competition. """ + args = team_parser_add.parse_args(strict=True) item_team = dbc.add.team(args["name"], competition_id) return item_response(schema.dump(item_team)) @@ -36,18 +45,15 @@ class TeamsList(Resource): class Teams(Resource): @protect_route(allowed_roles=["*"]) def get(self, competition_id, team_id): + """ Gets the specified team. """ + item = dbc.get.team(competition_id, team_id) return item_response(schema.dump(item)) - @protect_route(allowed_roles=["*"]) - def delete(self, competition_id, team_id): - item_team = dbc.get.team(competition_id, team_id) - - dbc.delete.team(item_team) - return {}, codes.NO_CONTENT - @protect_route(allowed_roles=["*"]) def put(self, competition_id, team_id): + """ Edits the specified team using the provided arguments. """ + args = team_parser_edit.parse_args(strict=True) name = args.get("name") @@ -55,3 +61,12 @@ class Teams(Resource): item_team = dbc.edit.default(item_team, name=name, competition_id=competition_id) return item_response(schema.dump(item_team)) + + @protect_route(allowed_roles=["*"]) + def delete(self, competition_id, team_id): + """ Deletes the specified team. """ + + item_team = dbc.get.team(competition_id, team_id) + + dbc.delete.team(item_team) + return {}, codes.NO_CONTENT diff --git a/server/app/apis/users.py b/server/app/apis/users.py index dc26ac5b64e9a4270215374de84f3c71cae66f9e..bf393a89abcc0f85d4885e8333afab1e0df8b56f 100644 --- a/server/app/apis/users.py +++ b/server/app/apis/users.py @@ -1,11 +1,16 @@ +""" +All API calls concerning question alternatives. +Default route: /api/users +""" + import app.core.http_codes as codes import app.database.controller as dbc from app.apis import item_response, list_response, protect_route from app.core.dto import UserDTO -from flask_jwt_extended import get_jwt_identity -from flask_restx import Resource -from flask_restx import inputs, reqparse from app.core.parsers import search_parser, sentinel +from app.database.models import User +from flask_jwt_extended import get_jwt_identity +from flask_restx import Resource, inputs, reqparse api = UserDTO.api schema = UserDTO.schema @@ -25,13 +30,14 @@ user_search_parser.add_argument("role_id", type=int, default=sentinel, location= def _edit_user(item_user, args): + """ Edits a user using the provided arguments. """ + email = args.get("email") name = args.get("name") if email: if dbc.get.user_exists(email): api.abort(codes.BAD_REQUEST, "Email is already in use") - if name: args["name"] = args["name"].title() @@ -42,13 +48,17 @@ def _edit_user(item_user, args): class UsersList(Resource): @protect_route(allowed_roles=["*"]) def get(self): - item = dbc.get.user(get_jwt_identity()) + """ Gets all users. """ + + item = dbc.get.one(User, get_jwt_identity()) return item_response(schema.dump(item)) @protect_route(allowed_roles=["*"]) def put(self): + """ Posts a new user using the specified arguments. """ + args = user_parser_edit.parse_args(strict=True) - item = dbc.get.user(get_jwt_identity()) + item = dbc.get.one(User, get_jwt_identity()) item = _edit_user(item, args) return item_response(schema.dump(item)) @@ -58,13 +68,17 @@ class UsersList(Resource): class Users(Resource): @protect_route(allowed_roles=["*"]) def get(self, ID): - item = dbc.get.user(ID) + """ Gets the specified user. """ + + item = dbc.get.one(User, ID) return item_response(schema.dump(item)) @protect_route(allowed_roles=["Admin"]) def put(self, ID): + """ Edits the specified team using the provided arguments. """ + args = user_parser_edit.parse_args(strict=True) - item = dbc.get.user(ID) + item = dbc.get.one(User, ID) item = _edit_user(item, args) return item_response(schema.dump(item)) @@ -73,6 +87,8 @@ class Users(Resource): class UserSearch(Resource): @protect_route(allowed_roles=["*"]) def get(self): + """ Finds a specific user based on the provided arguments. """ + args = user_search_parser.parse_args(strict=True) items, total = dbc.search.user(**args) return list_response(list_schema.dump(items), total) diff --git a/server/app/database/controller/add.py b/server/app/database/controller/add.py index 3aa0ab709324e21ed69e8db5f1902f9447c9c5f3..d0adf5a00e9bdbd610b4892837edc345e3dc20be 100644 --- a/server/app/database/controller/add.py +++ b/server/app/database/controller/add.py @@ -49,25 +49,34 @@ def db_add(item): except (exc.SQLAlchemyError, exc.DBAPIError): db.session.rollback() # SQL errors such as item already exists - abort(codes.INTERNAL_SERVER_ERROR, f"Item of type {type(item)} could not be created") + abort( + codes.INTERNAL_SERVER_ERROR, + f"Item of type {type(item)} could not be created", + ) except: db.session.rollback() # Catching other errors - abort(codes.INTERNAL_SERVER_ERROR, f"Something went wrong when creating {type(item)}") + abort( + codes.INTERNAL_SERVER_ERROR, + f"Something went wrong when creating {type(item)}", + ) return item def component(type_id, slide_id, view_type_id, x=0, y=0, w=0, h=0, **data): """ - Adds a component to the slide at the specified coordinates with the - provided size and data . + Adds a component to the slide at the specified + coordinates with the provided size and data. """ if type_id == 2: # 2 is image item_image = get.one(Media, data["media_id"]) filename = item_image.filename - path = os.path.join(current_app.config["UPLOADED_PHOTOS_DEST"], filename) + path = os.path.join( + current_app.config["UPLOADED_PHOTOS_DEST"], + filename, + ) with Image.open(path) as im: h = im.height w = im.width @@ -79,13 +88,19 @@ def component(type_id, slide_id, view_type_id, x=0, y=0, w=0, h=0, **data): h *= ratio if type_id == ID_TEXT_COMPONENT: - item = db_add(TextComponent(slide_id, type_id, view_type_id, x, y, w, h)) + item = db_add( + TextComponent(slide_id, type_id, view_type_id, x, y, w, h), + ) item.text = data.get("text") elif type_id == ID_IMAGE_COMPONENT: - item = db_add(ImageComponent(slide_id, type_id, view_type_id, x, y, w, h)) + item = db_add( + ImageComponent(slide_id, type_id, view_type_id, x, y, w, h), + ) item.media_id = data.get("media_id") elif type_id == ID_QUESTION_COMPONENT: - item = db_add(QuestionComponent(slide_id, type_id, view_type_id, x, y, w, h)) + item = db_add( + QuestionComponent(slide_id, type_id, view_type_id, x, y, w, h), + ) item.question_id = data.get("question_id") else: abort(codes.BAD_REQUEST, f"Invalid type_id{type_id}") @@ -122,7 +137,7 @@ def slide(competition_id): item_slide = db_add(Slide(order, competition_id)) # Add default question - question(f"Fråga {item_slide.order + 1}", 10, 0, item_slide.id) + question(f"Fråga {item_slide.order + 1}", 10, 1, item_slide.id) item_slide = utils.refresh(item_slide) return item_slide @@ -258,8 +273,18 @@ def question(name, total_score, type_id, slide_id, correcting_instructions=None) def question_alternative(text, value, question_id): + """ + Adds a question alternative to the specified + question using the provided arguments. + """ + return db_add(QuestionAlternative(text, value, question_id)) def question_answer(answer, score, question_id, team_id): + """ + Adds a question answer to the specified team + and question using the provided arguments. + """ + return db_add(QuestionAnswer(answer, score, question_id, team_id)) diff --git a/server/app/database/controller/copy.py b/server/app/database/controller/copy.py index 48dab2db79c33cb1ca819a59f0e934ab23dcc191..dd8073342ecfb0460e54783e70e50c0e194d437a 100644 --- a/server/app/database/controller/copy.py +++ b/server/app/database/controller/copy.py @@ -8,7 +8,9 @@ from app.database.types import ID_IMAGE_COMPONENT, ID_QUESTION_COMPONENT, ID_TEX def _alternative(item_old, question_id): - """Internal function. Makes a copy of the provided question alternative""" + """ + Internal function. Makes a copy of the provided question alternative. + """ return add.question_alternative(item_old.text, item_old.value, question_id) @@ -73,7 +75,7 @@ def component(item_component, slide_id_new, view_type_id): def slide(item_slide_old): """ Deep copies a slide to the same competition. - Does not copy team, question answers. + Does not copy team and question answers. """ item_competition = get.competition(item_slide_old.competition_id) @@ -98,7 +100,6 @@ def slide_to_competition(item_slide_old, item_competition): for item_component in item_slide_old.components: _component(item_component, item_slide_new) - for item_question in item_slide_old.questions: _question(item_question, item_slide_new.id) @@ -123,7 +124,7 @@ def competition(item_competition_old): item_competition_old.city_id, item_competition_old.font, ) - # TODO: Add background image + item_competition_new.background_image_id = item_competition_old.background_image_id for item_slide in item_competition_old.slides: diff --git a/server/app/database/controller/delete.py b/server/app/database/controller/delete.py index b0b36fbaf79843eac05bd4340d0a633a61e325d0..65737cb69d3ace8af493d71d245805b8f4869446 100644 --- a/server/app/database/controller/delete.py +++ b/server/app/database/controller/delete.py @@ -11,19 +11,25 @@ from flask_restx import abort def default(item): """ Deletes item and commits. """ + try: db.session.delete(item) db.session.commit() except: db.session.rollback() - abort(codes.INTERNAL_SERVER_ERROR, f"Item of type {type(item)} could not be deleted") + abort( + codes.INTERNAL_SERVER_ERROR, + f"Item of type {type(item)} could not be deleted", + ) def whitelist_to_blacklist(filters): """ - Remove whitelist by condition(filters) and insert those into blacklist - Example: When delete user all whitelisted tokens for that user should be blacklisted + Remove whitelist by condition(filters) and insert those into blacklist. + Example: When delete user all whitelisted tokens for that user should + be blacklisted. """ + whitelist = Whitelist.query.filter(filters).all() for item in whitelist: dbc.add.blacklist(item.jti) @@ -43,7 +49,6 @@ def _slide(item_slide): for item_question in item_slide.questions: question(item_question) - for item_component in item_slide.components: default(item_component) @@ -85,6 +90,7 @@ def question(item_question): question_answers(item_question_answer) for item_alternative in item_question.alternatives: alternatives(item_alternative) + default(item_question) diff --git a/server/app/database/controller/get.py b/server/app/database/controller/get.py index b6701ca5579940c9e4545d5542f41cf4b5b431fc..abdb9e15d1d815d80a48d7e80256e6595c7d7620 100644 --- a/server/app/database/controller/get.py +++ b/server/app/database/controller/get.py @@ -2,7 +2,6 @@ This file contains functionality to get data from the database. """ -from sqlalchemy.orm.util import with_polymorphic from app.core import db from app.core import http_codes as codes from app.database.models import ( @@ -18,11 +17,12 @@ from app.database.models import ( TextComponent, User, ) -from sqlalchemy.orm import joinedload, subqueryload +from sqlalchemy.orm import joinedload +from sqlalchemy.orm.util import with_polymorphic def all(db_type): - """ Gets lazy db-item in the provided table. """ + """ Gets a list of all lazy db-items in the provided table. """ return db_type.query.all() @@ -43,7 +43,10 @@ def code_by_code(code): def code_list(competition_id): - """ Gets a list of all code objects associated with a the provided competition. """ + """ + Gets a list of all code objects associated with the provided competition. + """ + # team_view_id = 1 join_competition = Competition.id == Code.competition_id filters = Competition.id == competition_id @@ -57,20 +60,18 @@ def user_exists(email): return User.query.filter(User.email == email).count() > 0 -def user(user_id): - """ Gets the user object associated with the provided id. """ - - return User.query.filter(User.id == user_id).first_extended() - - def user_by_email(email): """ Gets the user object associated with the provided email. """ + return User.query.filter(User.email == email).first_extended(error_code=codes.UNAUTHORIZED) ### Slides ### def slide(competition_id, slide_id): - """ Gets the slide object associated with the provided id and order. """ + """ + Gets the slide object associated with the provided competition and slide. + """ + join_competition = Competition.id == Slide.competition_id filters = (Competition.id == competition_id) & (Slide.id == slide_id) @@ -78,7 +79,10 @@ def slide(competition_id, slide_id): def slide_list(competition_id): - """ Gets a list of all slide objects associated with a the provided competition. """ + """ + Gets a list of all slide objects associated with the provided competition. + """ + join_competition = Competition.id == Slide.competition_id filters = Competition.id == competition_id @@ -91,15 +95,10 @@ def slide_count(competition_id): return Slide.query.filter(Slide.competition_id == competition_id).count() -def slide_count(competition_id): - """ Gets the number of slides in the provided competition. """ - - return Slide.query.filter(Slide.competition_id == competition_id).count() - - ### Teams ### def team(competition_id, team_id): - """ Gets the team object associated with the provided id and competition id. """ + """ Gets the team object associated with the competition and team. """ + join_competition = Competition.id == Team.competition_id filters = (Competition.id == competition_id) & (Team.id == team_id) @@ -107,19 +106,22 @@ def team(competition_id, team_id): def team_list(competition_id): - """ Gets a list of all team objects associated with a the provided competition. """ + """ + Gets a list of all team objects associated with the provided competition. + """ join_competition = Competition.id == Team.competition_id filters = Competition.id == competition_id return Team.query.join(Competition, join_competition).filter(filters).all() - return Team.query.join(Competition, join_competition).filter(filters).all() - ### Questions ### def question(competition_id, slide_id, question_id): - """ Gets the question object associated with the provided id, slide order and competition id. """ + """ + Gets the question object associated with the + provided, competition, slide and question. + """ join_competition = Competition.id == Slide.competition_id join_slide = Slide.id == Question.slide_id @@ -129,7 +131,10 @@ def question(competition_id, slide_id, question_id): def question_list(competition_id, slide_id): - """ Gets a list of all question objects associated with a the provided competition and slide. """ + """ + Gets a list of all question objects associated + with the provided competition and slide. + """ join_competition = Competition.id == Slide.competition_id join_slide = Slide.id == Question.slide_id @@ -139,7 +144,10 @@ def question_list(competition_id, slide_id): def question_list_for_competition(competition_id): - """ Gets a list of all question objects associated with a the provided competition. """ + """ + Gets a list of all question objects associated + with the provided competition. + """ join_competition = Competition.id == Slide.competition_id join_slide = Slide.id == Question.slide_id @@ -149,8 +157,16 @@ def question_list_for_competition(competition_id): ### Question Alternative ### -def question_alternative(competition_id, slide_id, question_id, alternative_id): - """ Get question alternative for a given question based on its competition and slide and ID. """ +def question_alternative( + competition_id, + slide_id, + question_id, + alternative_id, +): + """ + Get a question alternative for a given question + based on its competition, slide and question. + """ join_competition = Competition.id == Slide.competition_id join_slide = Slide.id == Question.slide_id @@ -172,7 +188,11 @@ def question_alternative(competition_id, slide_id, question_id, alternative_id): def question_alternative_list(competition_id, slide_id, question_id): - """ Get all question alternatives for a given question based on its competition and slide. """ + """ + Get a list of all question alternative objects for a + given question based on its competition and slide. + """ + join_competition = Competition.id == Slide.competition_id join_slide = Slide.id == Question.slide_id join_question = Question.id == QuestionAlternative.question_id @@ -186,18 +206,13 @@ def question_alternative_list(competition_id, slide_id, question_id): .all() ) - return ( - QuestionAlternative.query.join(Competition, join_competition) - .join(Slide, join_slide) - .join(Question, join_question) - .filter(filters) - .all() - ) - ### Question Answers ### def question_answer(competition_id, team_id, answer_id): - """ Get question answer for a given team based on its competition and ID. """ + """ + Get question answer for a given team based on its competition. + """ + join_competition = Competition.id == Team.competition_id join_team = Team.id == QuestionAnswer.team_id filters = (Competition.id == competition_id) & (Team.id == team_id) & (QuestionAnswer.id == answer_id) @@ -207,7 +222,10 @@ def question_answer(competition_id, team_id, answer_id): def question_answer_list(competition_id, team_id): - """ Get question answer for a given team based on its competition. """ + """ + Get a list of question answers for a given team based on its competition. + """ + join_competition = Competition.id == Team.competition_id join_team = Team.id == QuestionAnswer.team_id filters = (Competition.id == competition_id) & (Team.id == team_id) @@ -216,7 +234,10 @@ def question_answer_list(competition_id, team_id): ### Components ### def component(competition_id, slide_id, component_id): - """ Gets a list of all component objects associated with a the provided competition id and slide order. """ + """ + Gets a component object associated with + the provided competition id and slide order. + """ join_competition = Competition.id == Slide.competition_id join_slide = Slide.id == Component.slide_id @@ -233,7 +254,10 @@ def component(competition_id, slide_id, component_id): def component_list(competition_id, slide_id): - """ Gets a list of all component objects associated with a the provided competition id and slide order. """ + """ + Gets a list of all component objects associated with + the provided competition and slide. + """ join_competition = Competition.id == Slide.competition_id join_slide = Slide.id == Component.slide_id @@ -243,7 +267,8 @@ def component_list(competition_id, slide_id): ### Competitions ### def competition(competition_id): - """ Get Competition and all it's sub-entities """ + """ Get Competition and all it's sub-entities. """ + os1 = joinedload(Competition.slides).joinedload(Slide.components) os2 = joinedload(Competition.slides).joinedload(Slide.questions).joinedload(Question.alternatives) ot = joinedload(Competition.teams).joinedload(Team.question_answers) diff --git a/server/app/database/controller/utils.py b/server/app/database/controller/utils.py index 14eaa48d0295515e3f53c93dae963eb0ebc6bc92..f27ce32bae1429ec606f1b895535f3e0aea74d50 100644 --- a/server/app/database/controller/utils.py +++ b/server/app/database/controller/utils.py @@ -10,6 +10,8 @@ from flask_restx import abort def move_slides(item_competition, start_order, end_order): + """ Changes a slide order and then arranges other affected slides. """ + slides = item_competition.slides # Move up if start_order < end_order: @@ -40,6 +42,7 @@ def generate_unique_code(): def refresh(item): """ Refreshes the provided item. """ + try: db.session.refresh(item) except Exception as e: @@ -49,7 +52,8 @@ def refresh(item): def commit(): - """ Commits. """ + """ Commits to the database. """ + try: db.session.commit() except Exception as e: diff --git a/server/app/database/models.py b/server/app/database/models.py index a54a77c24b6b77a22187c386e8cd59c1cd006f49..97eb6097c2403cf4d32d01106e2ae906d9d788d5 100644 --- a/server/app/database/models.py +++ b/server/app/database/models.py @@ -61,8 +61,9 @@ class User(db.Model): _password = db.Column(db.LargeBinary(60), nullable=False) authenticated = db.Column(db.Boolean, default=False) - # twoAuthConfirmed = db.Column(db.Boolean, default=True) - # twoAuthCode = db.Column(db.String(STRING_SIZE), nullable=True) + + login_attempts = db.Column(db.Integer, nullable=False, default=0) + locked = db.Column(db.DateTime(timezone=True), nullable=True, default=None) role_id = db.Column(db.Integer, db.ForeignKey("role.id"), nullable=False) city_id = db.Column(db.Integer, db.ForeignKey("city.id"), nullable=False) diff --git a/server/configmodule.py b/server/configmodule.py index 93d21cbe84a5847ed4927a4d2b3d002b487d1f69..e38c4e04cf1b90ffff4edbe0cbcffffb347c5b4a 100644 --- a/server/configmodule.py +++ b/server/configmodule.py @@ -17,6 +17,8 @@ class Config: THUMBNAIL_SIZE = (120, 120) SECRET_KEY = os.urandom(24) SQLALCHEMY_ECHO = False + USER_LOGIN_LOCKED_ATTEMPTS = 12 + USER_LOGIN_LOCKED_EXPIRES = timedelta(hours=3) class DevelopmentConfig(Config): @@ -34,6 +36,8 @@ class DevelopmentConfig(Config): class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = "sqlite:///test.db" + USER_LOGIN_LOCKED_ATTEMPTS = 4 + USER_LOGIN_LOCKED_EXPIRES = timedelta(seconds=4) class ProductionConfig(Config): diff --git a/server/populate.py b/server/populate.py index 34f73822f789ddfdabe1092192c6dede7af85355..9981f0c02f430d56c88738a9b67e89d5fc17af89 100644 --- a/server/populate.py +++ b/server/populate.py @@ -11,8 +11,8 @@ from app.database.models import City, QuestionType, Role def _add_items(): media_types = ["Image", "Video"] - question_types = ["Boolean", "Multiple", "Text"] - component_types = ["Text", "Image"] + question_types = ["Text", "Practical", "Multiple", "Single"] + component_types = ["Text", "Image", "Question"] view_types = ["Team", "Judge", "Audience", "Operator"] roles = ["Admin", "Editor"] diff --git a/server/tests/test_app.py b/server/tests/test_app.py index 2152a6d4c7236f57d099f50dccec3a090ce94c5d..880a41bd82a3b6cac8795a3cf61eaed6569dbadb 100644 --- a/server/tests/test_app.py +++ b/server/tests/test_app.py @@ -2,15 +2,37 @@ This file tests the api function calls. """ +import time + import app.core.http_codes as codes -from app.database.controller.add import competition -from app.database.models import Slide +import pytest from app.core import sockets from tests import app, client, db from tests.test_helpers import add_default_values, change_order_test, delete, get, post, put +# @pytest.mark.skip(reason="Takes long time") +def test_locked_api(client): + add_default_values() + + # Login in with default user but wrong password until blocked + for i in range(4): + response, body = post(client, "/api/auth/login", {"email": "test@test.se", "password": "password1"}) + assert response.status_code == codes.UNAUTHORIZED + + # Login with right password, user should be locked + response, body = post(client, "/api/auth/login", {"email": "test@test.se", "password": "password"}) + assert response.status_code == codes.UNAUTHORIZED + + # Sleep for 4 secounds + time.sleep(4) + + # Check so the user is no longer locked + response, body = post(client, "/api/auth/login", {"email": "test@test.se", "password": "password"}) + assert response.status_code == codes.OK + + def test_misc_api(client): add_default_values() @@ -125,6 +147,10 @@ def test_auth_and_user_api(client): assert response.status_code == codes.OK headers = {"Authorization": "Bearer " + body["access_token"]} + # Login in with default user but wrong password + response, body = post(client, "/api/auth/login", {"email": "test@test.se", "password": "password1"}) + assert response.status_code == codes.UNAUTHORIZED + # Create user register_data = {"email": "test1@test.se", "password": "abc123", "role_id": 2, "city_id": 1} response, body = post(client, "/api/auth/signup", register_data, headers) @@ -211,7 +237,6 @@ def test_auth_and_user_api(client): assert response.status_code == codes.OK # TODO: Check if current users jwt (jti) is in blacklist after logging out - response, body = get(client, "/api/users", headers=headers) assert response.status_code == codes.UNAUTHORIZED @@ -479,4 +504,4 @@ def test_authorization(client): # Also get antoher teams answers response, body = get(client, f"/api/competitions/{competition_id}/teams/{team_id+1}/answers", headers=headers) - assert response.status_code == codes.OK \ No newline at end of file + assert response.status_code == codes.OK