Skip to content

Commit

Permalink
bug fixes + edit transactions
Browse files Browse the repository at this point in the history
  • Loading branch information
Tkaixiang committed Sep 20, 2021
1 parent b8cde91 commit 6b35eaa
Show file tree
Hide file tree
Showing 6 changed files with 243 additions and 11 deletions.
1 change: 1 addition & 0 deletions api/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ const main = async () => {
app.post('/v1/adminSettings/', misc.adminSettings)
app.get('/v1/submissions', submissions.submissions);
app.post('/v1/submissions/new', submissions.newSubmission);
app.post('/v1/submissions/edit', submissions.editSubmission);
app.post('/v1/submissions/delete', submissions.deleteSubmission);
app.get('/v1/about', misc.about);
app.post('/v1/profile/upload', misc.profileUpload)
Expand Down
4 changes: 2 additions & 2 deletions api/controllers/Scoreboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const scoreboard = async (req, res, next) => {
if (req.app.get("adminShowDisable")) {
for (let i = 0; i < transactionsCache.length; i++) {
const current = transactionsCache[i]
const document = { points: current.points, challenge: current.challenge, timestamp: current.timestamp, challengeID: current.challengeID }
const document = {_id: current._id, points: current.points, challenge: current.challenge, timestamp: current.timestamp, challengeID: current.challengeID }

if (checkUsernamePerms(current.author) !== 2) {
if (current.author in changes) changes[current.author].changes.push(document)
Expand All @@ -21,7 +21,7 @@ const scoreboard = async (req, res, next) => {
else {
for (let i = 0; i < transactionsCache.length; i++) {
const current = transactionsCache[i]
const document = { points: current.points, challenge: current.challenge, timestamp: current.timestamp, challengeID: current.challengeID }
const document = {_id: current._id, points: current.points, challenge: current.challenge, timestamp: current.timestamp, challengeID: current.challengeID }


if (current.author in changes) changes[current.author].changes.push(document)
Expand Down
58 changes: 55 additions & 3 deletions api/controllers/Submissions.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const newSubmission = async (req, res, next) => {
points: req.body.points
}
if (req.body.type === "hint") {
insertDoc.hint_id = req.body.hint_id-1
insertDoc.hint_id = req.body.hint_id - 1
}
else {
insertDoc.correct = req.body.correct
Expand All @@ -59,6 +59,58 @@ const newSubmission = async (req, res, next) => {
}
}

const editSubmission = async (req, res, next) => {
const collections = Connection.collections
try {
if (res.locals.perms < 2) throw new Error('Permissions');
let latestSolveSubmissionID = req.app.get("latestSolveSubmissionID")
latestSolveSubmissionID += 1
req.app.set("latestSolveSubmissionID", latestSolveSubmissionID)
let updateDoc = {
author: req.body.author,
challenge: req.body.challenge,
challengeID: MongoDB.ObjectID(req.body.challengeID),
type: req.body.type,
lastChallengeID: latestSolveSubmissionID,
points: req.body.points
}
if (req.body.type === "hint") {
updateDoc.hint_id = req.body.hint_id - 1
}
else {
updateDoc.correct = req.body.correct
updateDoc.submission = req.body.submission
}
await collections.transactions.updateOne({ _id: MongoDB.ObjectID(req.body.id) }, { $set: updateDoc })
let transactionsCache = req.app.get("transactionsCache")
let time = null
for (let i = 0; i < transactionsCache.length; i++) {
if (transactionsCache[i]._id.toString() === req.body.id) {
time = transactionsCache[i].timestamp
for (key in updateDoc) {
transactionsCache[i][key] = updateDoc[key]
}
break
}
}
req.app.set("transactionsCache", transactionsCache)


broadCastNewSolve([{
_id: req.body.id,
username: req.body.author,
timestamp: time,
points: req.body.points,
lastChallengeID: latestSolveSubmissionID
}])
res.send({ success: true })
}
catch (err) {
console.error(err)
next(err);
}
}

const deleteSubmission = async (req, res, next) => {
const collections = Connection.collections
try {
Expand All @@ -71,7 +123,7 @@ const deleteSubmission = async (req, res, next) => {
else {
delReq = delReq.value
//const challengeID = MongoDB.ObjectID(delReq.challengeID.toString())
const challDoc = await collections.challs.findOne({ _id: delReq.challengeID})
const challDoc = await collections.challs.findOne({ _id: delReq.challengeID })
if (delReq.type === "hint") {
const hints = challDoc.hints
const hintsArray = hints[delReq.hint_id].purchased
Expand Down Expand Up @@ -120,4 +172,4 @@ const deleteSubmission = async (req, res, next) => {
}
}

module.exports = { submissions, newSubmission, deleteSubmission }
module.exports = { submissions, newSubmission, deleteSubmission, editSubmission }
4 changes: 2 additions & 2 deletions client/src/AdminPanel/adminChallenges.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
EyeOutlined,
EyeInvisibleOutlined,
RedoOutlined,
SearchOutlined
SearchOutlined,
} from '@ant-design/icons';
import AdminChallengeCreate from "./adminChallengeCreate.js";
import AdminChallengeEdit from "./adminChallengeEdit.js";
Expand Down Expand Up @@ -527,7 +527,7 @@ class AdminChallenges extends React.Component {
title=""
key="edit"
render={(text, record) => (
<Button icon={<EditOutlined />} onClick={() => { this.setState({ editChallenge: true, id: record._id }, this.props.history.push("/Admin/Challenges/Edit")) }}> Edit</Button>
<Button icon={<EditOutlined />} onClick={() => { this.setState({ editChallenge: true, id: record._id }); this.props.history.push("/Admin/Challenges/Edit") }}> Edit</Button>
)}
/>
</Table>
Expand Down
184 changes: 182 additions & 2 deletions client/src/AdminPanel/adminSubmissions.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import {
FileOutlined,
UserOutlined,
DeleteOutlined,
ExclamationCircleOutlined
ExclamationCircleOutlined,
EditOutlined
} from '@ant-design/icons';
import { orderBy } from "lodash";
import { Ellipsis } from 'react-spinners-css';
Expand Down Expand Up @@ -165,6 +166,165 @@ const CreateT = (props) => {
);
};

const EditT = (props) => {
const [isHint, setIsHint] = useState(false)
const [isNonZero, setNonZero] = useState(false)
const [correctValue, setCorrectValue] = useState(true)
const [form] = Form.useForm();



if (typeof form.getFieldValue("author") === "undefined") {
let initialData = JSON.parse(JSON.stringify(props.initialData))
initialData.challenge = ["", [props.initialData.challenge, props.initialData.challengeID]]
if (initialData.type === "hint") setIsHint(true)
if (initialData.points !== 0) setNonZero(true)
form.setFieldsValue(initialData)
}


return (
<Form
form={form}
onFinish={async (values) => {
// must use correctValue state value instead
await fetch(window.ipAddress + "/v1/submissions/edit", {
method: 'post',
headers: { 'Content-Type': 'application/json', "Authorization": window.IRSCTFToken },
body: JSON.stringify({
"id": props.initialData._id,
"author": values.author,
"challenge": values.challenge[1][0],
"challengeID": values.challenge[1][1],
"type": values.type,
"points": values.points,
"correct": correctValue,
"submission": values.submission,
"hint_id": values.hint_id
})
}).then((results) => {
return results.json(); //return data in JSON (since its JSON data)
}).then((data) => {
if (data.success === true) {
message.success({ content: "Edited transaction successfully!" })
setNonZero(false)
setCorrectValue(false)
setIsHint(false)
props.setState({ editTModal: false })
props.refresh()
form.resetFields()
}
else {
message.error({ content: "Oops. Unknown error" })
}


}).catch((error) => {
console.log(error)
message.error({ content: "Oops. There was an issue connecting with the server" });
})
}}
>
<h4>Select an Account</h4>
<Form.Item
name="author"
rules={[{ required: true, message: 'Please enter an author' }]}
>
<Input allowClear prefix={<UserOutlined />} placeholder="Account which this transaction will belong to" />
</Form.Item>

<h4>Select a Challenge</h4>
<Form.Item
name="challenge"
rules={[{ required: true, message: 'Please select a challenge' }]}
>
<Cascader
options={props.challengeList}
allowClear
showSearch
placeholder="Select an existing challenge which this transaction will belong to" />
</Form.Item>

<h4>Select a Type</h4>
<Form.Item
name="type"
rules={[{ required: true, message: 'Please select the type of transaction' }]}
initialValue="submission"
>
<Select onSelect={(type) => { type === "hint" ? setIsHint(true) : setIsHint(false) }}>
<Option value="submission">Submission</Option>
<Option value="hint">Hint</Option>
<Option value="blocked_submission">Blocked Submission</Option>
</Select>

</Form.Item>

<h4>Input Amount of Points</h4>
<Form.Item
name="points"
rules={[{ required: true, message: 'Please input the amount of points' }]}
initialValue={0}
>
<InputNumber onChange={(value) => {
if (value !== 0) {
setNonZero(true)
setCorrectValue(true)
}
else setNonZero(false)
}} min={-100000} max={100000} ></InputNumber>

</Form.Item>

{!isHint ?
<div>


<h4>Choose whether this is a "Correct" submission</h4>
<Form.Item
name="correct"
rules={[{ required: true, message: 'Please select whether it is correct' }]}
initialValue={true}
valuePropName={correctValue}
>
<Select value={correctValue} onSelect={(value) => setCorrectValue(value)} disabled={isNonZero}>
<Option value={true}>Correct</Option>
<Option value={false}>Wrong</Option>
</Select>

</Form.Item>

<h4>Enter a Submission</h4>
<Form.Item
name="submission"
rules={[{ required: true, message: 'Please enter a submission' }]}
>
<Input allowClear placeholder="The user's flag input" />
</Form.Item>
</div>
:
<div>
<h4>Enter a hint ID (hint number of the challenge from <code>1-n</code>)</h4>
<Form.Item
name="hint_id"
rules={[{ required: true, message: 'Please enter a hint ID' }]}
initialValue={1}
>
<InputNumber min={-100000} max={100000}></InputNumber>

</Form.Item>
</div>}


<Form.Item>
<div style={{ display: "flex", justifyContent: "space-between" }}>
<Button style={{ marginRight: "1.5vw" }} onClick={() => { props.setState({ editTModal: false }) }}>Cancel</Button>
<Button type="primary" htmlType="submit" className="login-form-button" style={{ marginBottom: "1.5vh" }}>Edit Transaction</Button>
</div>
</Form.Item>
</Form>
);
};

class AdminSubmissions extends React.Component {
constructor(props) {
super(props);
Expand All @@ -175,7 +335,9 @@ class AdminSubmissions extends React.Component {
createTModal: false,
challengeList: [],
selectedTableKeys: [],
disableEditButtons: true
disableEditButtons: true,
editTModal: false,
initialData: {}
}
}

Expand Down Expand Up @@ -324,6 +486,17 @@ class AdminSubmissions extends React.Component {
<CreateT refresh={this.refresh.bind(this)} challengeList={this.state.challengeList} setState={this.setState.bind(this)}></CreateT>
</Modal>

<Modal
title="Edit Transaction"
visible={this.state.editTModal}
footer={null}
destroyOnClose
onCancel={() => { this.setState({ editTModal: false }) }}
>

<EditT initialData={this.state.initialData} refresh={this.refresh.bind(this)} challengeList={this.state.challengeList} setState={this.setState.bind(this)}></EditT>
</Modal>

<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<div style={{ display: "flex", alignItems: "center", height: "2ch" }}>
<Button type="primary" style={{ marginBottom: "2vh", marginRight: "1ch" }} icon={<FileOutlined />} onClick={() => { this.setState({ createTModal: true }) }}>Create New Transaction</Button>
Expand Down Expand Up @@ -419,6 +592,13 @@ class AdminSubmissions extends React.Component {
<Column title="Points Awarded" dataIndex="points" key="points" sorter={(a, b) => a.points - b.points} />
<Column title="Flag Submitted" dataIndex="submission" key="submission" />
<Column title="Correct" dataIndex="correct" key="correct" filters={[{ text: "True", value: "True" }, { text: "False", value: "False" }]} onFilter={(value, record) => { return value === record.correct }} />
<Column
title=""
key="edit"
render={(text, record) => (
<Button icon={<EditOutlined />} onClick={() => { this.setState({ editTModal: true, initialData: record }) }}> Edit</Button>
)}
/>
</Table>
</Layout >
);
Expand Down
3 changes: 1 addition & 2 deletions client/src/Scoreboard/Scoreboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,7 @@ class Scoreboard extends React.Component {
changes.users.push({ _id: payload.username, changes: [{ points: payload.points, timestamp: payload.timestamp, _id: payload._id }] })
}
}



window.scoreboardData = changes
window.lastChallengeID = payloadArray[0].lastChallengeID
this.sortPlotRenderData(JSON.parse(JSON.stringify(changes)))
Expand Down

0 comments on commit 6b35eaa

Please sign in to comment.