├── .eslintignore ├── src ├── controllers │ ├── standing │ │ ├── index.ts │ │ └── getAllStandings.ts │ ├── user │ │ ├── index.ts │ │ ├── signin.ts │ │ └── signup.ts │ ├── submission │ │ ├── index.ts │ │ ├── getMySubmissions.ts │ │ ├── getSubmission.ts │ │ ├── getAllSubmissions.ts │ │ └── createSubmission.ts │ ├── contest │ │ ├── index.ts │ │ ├── getAllContests.ts │ │ ├── getContest.ts │ │ ├── deleteContest.ts │ │ ├── createContest.ts │ │ └── updateContest.ts │ ├── problem │ │ ├── index.ts │ │ ├── getProblem.ts │ │ ├── deleteProblem.ts │ │ ├── updateProblem.ts │ │ ├── createProblem.ts │ │ └── getAllProblems.ts │ └── verifyController.ts ├── middlewares │ ├── index.ts │ ├── authorization.ts │ ├── AuthenticatedUser.ts │ └── authentication.ts ├── utils │ ├── types.ts │ ├── enumToArray.ts │ ├── noId.ts │ └── APIResponse.ts ├── routes │ ├── standings.route.ts │ ├── verify.route.ts │ ├── user.route.ts │ ├── problems.route.ts │ ├── index.ts │ ├── submissions.route.ts │ └── contests.route.ts ├── lib │ ├── judge │ │ ├── LocalJudge.ts │ │ ├── Judge0Judge.ts │ │ ├── JudgeFactory.ts │ │ ├── CodeforcesJudge.ts │ │ └── BaseJudge.ts │ ├── submission-consumers │ │ ├── judged.ts │ │ ├── SubmissionsQ.ts │ │ └── pending.ts │ └── problem-scrapper │ │ └── CodeforcesProblemScrapper.ts ├── index.ts ├── config.ts ├── database.ts ├── adminInit.ts ├── server.ts └── models │ ├── standing.ts │ ├── contest.ts │ ├── user.ts │ ├── problem.ts │ └── submission.ts ├── .nodemonrc ├── Dockerfile ├── .prettierrc ├── .travis.yml ├── .editorconfig ├── .vscode └── tasks.json ├── .env.example ├── README.md ├── tslint.json ├── tsconfig.json ├── .github └── workflows │ └── nodejs.yml ├── .eslintrc ├── insertNames.py ├── LICENSE ├── .dockerignore ├── .gitignore └── package.json /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | dist/ 3 | -------------------------------------------------------------------------------- /src/controllers/standing/index.ts: -------------------------------------------------------------------------------- 1 | export * from './getAllStandings'; 2 | -------------------------------------------------------------------------------- /src/controllers/user/index.ts: -------------------------------------------------------------------------------- 1 | export * from './signin'; 2 | export * from './signup'; 3 | -------------------------------------------------------------------------------- /.nodemonrc: -------------------------------------------------------------------------------- 1 | { 2 | "watch": ["src"], 3 | "ext": "ts,js,json", 4 | "exec": "npm start" 5 | } -------------------------------------------------------------------------------- /src/middlewares/index.ts: -------------------------------------------------------------------------------- 1 | export * from './authentication'; 2 | export * from './authorization'; 3 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:13-alpine 2 | WORKDIR /app 3 | COPY . /app 4 | RUN npm i 5 | EXPOSE 5000 6 | CMD ["npm", "start"] 7 | -------------------------------------------------------------------------------- /src/utils/types.ts: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose'; 2 | 3 | export type PossibleDocumentOrObjectID = {} | string | mongoose.Types.ObjectId; 4 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": true, 3 | "singleQuote": true, 4 | "printWidth": 80, 5 | "tabWidth": 2, 6 | "bracketSpacing": false, 7 | "trailingComma": "all" 8 | } 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | node_js: 4 | - 'node' 5 | - '10' 6 | - '12' 7 | 8 | git: 9 | depth: 1 10 | 11 | install: 12 | - npm install 13 | - npm run build 14 | -------------------------------------------------------------------------------- /src/controllers/submission/index.ts: -------------------------------------------------------------------------------- 1 | export * from './createSubmission'; 2 | export * from './getSubmission'; 3 | export * from './getAllSubmissions'; 4 | export * from './getMySubmissions'; 5 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | 2 | root = true 3 | 4 | [*.{ts,json,js}] 5 | end_of_line = crlf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | indent_style = space 10 | indent_size = 2 11 | -------------------------------------------------------------------------------- /src/utils/enumToArray.ts: -------------------------------------------------------------------------------- 1 | export function enumToArray(enumObject: any): string[] { 2 | const keys = Object.keys(enumObject).filter( 3 | (key) => typeof enumObject[key as any] === 'number', 4 | ); 5 | return keys; 6 | } 7 | -------------------------------------------------------------------------------- /src/controllers/contest/index.ts: -------------------------------------------------------------------------------- 1 | export * from './createContest'; 2 | export * from './getContest'; 3 | export * from './getAllContests'; 4 | export * from './updateContest'; 5 | export * from './updateContest'; 6 | export * from './deleteContest'; 7 | -------------------------------------------------------------------------------- /src/controllers/problem/index.ts: -------------------------------------------------------------------------------- 1 | export * from './createProblem'; 2 | export * from './getProblem'; 3 | export * from './getAllProblems'; 4 | export * from './updateProblem'; 5 | export * from './updateProblem'; 6 | export * from './deleteProblem'; 7 | -------------------------------------------------------------------------------- /src/routes/standings.route.ts: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import * as standingController from '../controllers/standing'; 3 | 4 | const router = express.Router(); 5 | 6 | router.get('/', standingController.getAll); 7 | 8 | export default router; 9 | -------------------------------------------------------------------------------- /src/routes/verify.route.ts: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import * as verifyController from '../controllers/verifyController'; 3 | 4 | const router = express.Router(); 5 | 6 | router.get('/:token', verifyController.verify); 7 | 8 | export default router; 9 | -------------------------------------------------------------------------------- /src/routes/user.route.ts: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import * as userController from '../controllers/user'; 3 | 4 | const router = express.Router(); 5 | 6 | router.post('/signin', userController.signin); 7 | router.post('/signup', userController.signup); 8 | 9 | export default router; 10 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "type": "npm", 8 | "script": "dev", 9 | "group": "build", 10 | "problemMatcher": [] 11 | } 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | PORT=5000 2 | MONGODB_URL=mongodb://localhost/jx 3 | JWT_SECRET_KEY=very-secret-key 4 | EMAIL_VERIFICATION= 5 | EMAIL= 6 | EMAIL_PASSWORD= 7 | ADMIN_EMAIL=admin@admin.com 8 | ADMIN_PASSWORD=admin@admin 9 | CF_SUBMITTER_URL=http://localhost:5200 10 | CF_SUBMITTER_API_KEY=test 11 | CF_PROBLEM_SCRAPPER_URL=http://localhost:5300 12 | RABBITMQ_URL=amqp://localhost 13 | -------------------------------------------------------------------------------- /src/utils/noId.ts: -------------------------------------------------------------------------------- 1 | import {Model, Document} from 'mongoose'; 2 | 3 | /** 4 | * Returns a string reporting no with 5 | * @param model The model you want to use its name 6 | * @param id The document id you want to use 7 | */ 8 | export default function (model: Model, id: string): string { 9 | return `No ${model.modelName.toUpperCase()} with id ${id}`; 10 | } 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # backend 2 | 3 | [![GitHub Workflow Status](https://github.com/JudgeX-JX/backend/workflows/NodeCI/badge.svg)](https://github.com/JudgeX-JX/backend/actions) 4 | [![Build Status](https://img.shields.io/travis/JudgeX-JX/backend/master?logo=travis)](https://travis-ci.com/JudgeX-JX/backend) 5 | [![License](https://img.shields.io/github/license/JudgeX-JX/backend)](https://github.com/JudgeX-JX/backend/blob/master/LICENSE) 6 | 7 | for documentation please check: [docs](https://JudgeX-JX.github.io/docs/) 8 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "defaultSeverity": "error", 3 | "extends": ["tslint:recommended"], 4 | "jsRules": {}, 5 | "rules": { 6 | "quotemark": [true, "single"], 7 | "object-literal-sort-keys": false, 8 | "no-console": false, 9 | "object-literal-key-quotes": false, 10 | "variable-name": [true, "allow-leading-underscore"], 11 | "arrow-return-shorthand": true, 12 | "arrow-parens": false, 13 | "curly": false 14 | }, 15 | "rulesDirectory": [] 16 | } 17 | -------------------------------------------------------------------------------- /src/lib/judge/LocalJudge.ts: -------------------------------------------------------------------------------- 1 | import {IJudge, ISubmitterResponse} from './JudgeFactory'; 2 | import {BaseJudge} from './BaseJudge'; 3 | import {ISubmission} from '../../models/submission'; 4 | 5 | export class LocalJudge extends BaseJudge implements IJudge { 6 | constructor(s: ISubmission) { 7 | super(s); 8 | } 9 | submit(): Promise { 10 | throw new Error('Method not implemented.'); 11 | } 12 | getVerdict(): Promise { 13 | throw new Error('Method not implemented.'); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/lib/judge/Judge0Judge.ts: -------------------------------------------------------------------------------- 1 | import {IJudge, ISubmitterResponse} from './JudgeFactory'; 2 | import {BaseJudge} from './BaseJudge'; 3 | import {ISubmission} from '../../models/submission'; 4 | 5 | export class Judge0Judge extends BaseJudge implements IJudge { 6 | constructor(s: ISubmission) { 7 | super(s); 8 | } 9 | submit(): Promise { 10 | throw new Error('Method not implemented.'); 11 | } 12 | getVerdict(): Promise { 13 | throw new Error('Method not implemented.'); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "esModuleInterop": true, 5 | "allowSyntheticDefaultImports": true, 6 | "target": "ES6", 7 | "noImplicitAny": true, 8 | "moduleResolution": "node", 9 | "sourceMap": true, 10 | "rootDir": "src", 11 | "outDir": "dist", 12 | "experimentalDecorators": true, 13 | "emitDecoratorMetadata": true, 14 | "resolveJsonModule": true, 15 | "strict": true 16 | }, 17 | "include": ["src/**/*"], 18 | "exclude": ["node_modules", "dist"] 19 | } 20 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import clrs from 'colors'; 2 | import * as config from './config'; 3 | import * as database from './database'; 4 | import * as server from './server'; 5 | import adminInit from './adminInit'; 6 | import judgedSubmissionConsumer from './lib/submission-consumers/judged'; 7 | 8 | config.check(); 9 | database 10 | .connect() 11 | .then(adminInit) 12 | .then(judgedSubmissionConsumer) 13 | .then(server.run) 14 | .then(() => console.info(clrs.green('Enjoy!'))) 15 | .catch((err) => { 16 | console.error(err); 17 | process.exit(1); 18 | }); 19 | -------------------------------------------------------------------------------- /src/lib/submission-consumers/judged.ts: -------------------------------------------------------------------------------- 1 | import SubmissionsQ from './SubmissionsQ'; 2 | import {Submission} from '../../models/submission'; 3 | 4 | export default async (): Promise => { 5 | await SubmissionsQ.init(); 6 | console.log('listening for judged submissions'); 7 | SubmissionsQ.channel.consume(SubmissionsQ.judgedQ, async (msg) => { 8 | if (!msg) { 9 | return; 10 | } 11 | const sub = JSON.parse(msg.content.toString()); 12 | await Submission.findByIdAndUpdate(sub._id, sub); 13 | SubmissionsQ.channel.ack(msg); 14 | }); 15 | }; 16 | -------------------------------------------------------------------------------- /src/controllers/problem/getProblem.ts: -------------------------------------------------------------------------------- 1 | import {Problem} from '../../models/problem'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | import noId from '../../utils/noId'; 5 | 6 | export async function getWithId( 7 | req: Request, 8 | res: Response, 9 | ): Promise { 10 | const problemId = req.params.id; 11 | 12 | const problem = await Problem.findById(problemId); 13 | 14 | return problem 15 | ? APIResponse.Ok(res, problem) 16 | : APIResponse.NotFound(res, noId(Problem, problemId)); 17 | } 18 | -------------------------------------------------------------------------------- /src/controllers/problem/deleteProblem.ts: -------------------------------------------------------------------------------- 1 | import {Problem} from '../../models/problem'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | import noId from '../../utils/noId'; 5 | 6 | export async function deleteWithId( 7 | req: Request, 8 | res: Response, 9 | ): Promise { 10 | const problemId = req.params.id; 11 | const problem = await Problem.findById(problemId); 12 | if (!problem) { 13 | return APIResponse.NotFound(res, noId(Problem, problemId)); 14 | } 15 | problem.remove(); 16 | return APIResponse.Ok(res, problem); 17 | } 18 | -------------------------------------------------------------------------------- /src/controllers/standing/getAllStandings.ts: -------------------------------------------------------------------------------- 1 | import {Standing} from '../../models/standing'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | 5 | export async function getAll(req: Request, res: Response): Promise { 6 | const filter = req.query; 7 | const standings = await Standing.find(filter); 8 | standings.sort((first: any, second: any) => { 9 | return first.solved === second.solved 10 | ? first.penality - second.penality 11 | : first.solved - second.solved; 12 | }); 13 | return APIResponse.Ok(res, standings); 14 | } 15 | -------------------------------------------------------------------------------- /.github/workflows/nodejs.yml: -------------------------------------------------------------------------------- 1 | name: NodeCI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | strategy: 10 | matrix: 11 | node-version: [8.x, 10.x, 12.x] 12 | 13 | steps: 14 | - uses: actions/checkout@v1 15 | - name: Use Node.js ${{ matrix.node-version }} 16 | uses: actions/setup-node@v1 17 | with: 18 | node-version: ${{ matrix.node-version }} 19 | - name: npm install, build, and test 20 | run: | 21 | npm ci 22 | npm run build --if-present 23 | npm test 24 | env: 25 | CI: true 26 | -------------------------------------------------------------------------------- /src/controllers/submission/getMySubmissions.ts: -------------------------------------------------------------------------------- 1 | import {Submission} from '../../models/submission'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | import {IAuthenticatedRequest} from '../../middlewares'; 5 | 6 | export async function getMySubmissions( 7 | req: Request, 8 | res: Response, 9 | ): Promise { 10 | const user = (req as IAuthenticatedRequest).authenticatedUser._id; 11 | const filter = req.query; 12 | const submissions = await Submission.find({ 13 | user, 14 | ...filter, 15 | }); 16 | 17 | return APIResponse.Ok(res, submissions); 18 | } 19 | -------------------------------------------------------------------------------- /src/middlewares/authorization.ts: -------------------------------------------------------------------------------- 1 | import {Response, NextFunction, Request} from 'express'; 2 | import {Roles} from '../models/user'; 3 | import {IAuthenticatedRequest} from '.'; 4 | 5 | export function authorize(roles: Roles[]) { 6 | return (req: Request, res: Response, next: NextFunction): unknown => { 7 | const allowedRoles = roles.map((k) => Roles[k]); 8 | const {role} = (req as IAuthenticatedRequest).authenticatedUser; 9 | if (allowedRoles.includes(role)) { 10 | next(); 11 | } else { 12 | return res 13 | .status(403) 14 | .json({message: `Only allowed for ${allowedRoles}!`}); 15 | } 16 | }; 17 | } 18 | -------------------------------------------------------------------------------- /src/controllers/contest/getAllContests.ts: -------------------------------------------------------------------------------- 1 | import {Contest} from '../../models/contest'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | 5 | export async function getAll(req: Request, res: Response): Promise { 6 | const options = { 7 | page: parseInt(req.query.pageNumber, 10) || 1, 8 | limit: parseInt(req.query.pageSize, 10) || 10, 9 | populate: { 10 | path: 'setter problems', 11 | select: 'name', 12 | }, 13 | customLabels: { 14 | docs: 'contests', 15 | }, 16 | }; 17 | const contests = await Contest.paginate({}, options); 18 | return APIResponse.Ok(res, contests); 19 | } 20 | -------------------------------------------------------------------------------- /src/controllers/contest/getContest.ts: -------------------------------------------------------------------------------- 1 | import {Contest} from '../../models/contest'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | import noId from '../../utils/noId'; 5 | 6 | export async function getWithId( 7 | req: Request, 8 | res: Response, 9 | ): Promise { 10 | const contestId = req.params.id; 11 | 12 | const contest = await Contest.findById(contestId) 13 | .populate({ 14 | path: 'setter', 15 | select: 'name', 16 | }) 17 | .populate('problems'); 18 | 19 | return contest 20 | ? APIResponse.Ok(res, contest) 21 | : APIResponse.NotFound(res, noId(Contest, contestId)); 22 | } 23 | -------------------------------------------------------------------------------- /src/controllers/submission/getSubmission.ts: -------------------------------------------------------------------------------- 1 | import {Submission} from '../../models/submission'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | import noId from '../../utils/noId'; 5 | 6 | export async function getWithId( 7 | req: Request, 8 | res: Response, 9 | ): Promise { 10 | const submissionId = req.params.id; 11 | 12 | const submission = await Submission.findById(submissionId).populate({ 13 | path: 'user problem', 14 | select: '-sourceCode', 15 | }); 16 | 17 | return submission 18 | ? APIResponse.Ok(res, submission) 19 | : APIResponse.NotFound(res, noId(Submission, submissionId)); 20 | } 21 | -------------------------------------------------------------------------------- /src/controllers/contest/deleteContest.ts: -------------------------------------------------------------------------------- 1 | import {Contest} from '../../models/contest'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | import noId from '../../utils/noId'; 5 | 6 | export async function deleteWithId( 7 | req: Request, 8 | res: Response, 9 | ): Promise { 10 | const contestId = req.params.id; 11 | 12 | const contest = await Contest.findById(contestId).populate({ 13 | path: 'setter problems', 14 | select: 'name', 15 | }); 16 | if (!contest) { 17 | return APIResponse.NotFound(res, noId(Contest, contestId)); 18 | } 19 | await contest.remove(); 20 | return APIResponse.Ok(res, contest); 21 | } 22 | -------------------------------------------------------------------------------- /src/controllers/submission/getAllSubmissions.ts: -------------------------------------------------------------------------------- 1 | import {Submission} from '../../models/submission'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | 5 | export async function getAll(req: Request, res: Response): Promise { 6 | const options = { 7 | page: parseInt(req.query.pageNumber) || 1, 8 | limit: parseInt(req.query.pageSize) || 10, 9 | populate: { 10 | path: 'user problem', 11 | }, 12 | select: '-sourceCode', 13 | customLabels: { 14 | docs: 'submissions', 15 | }, 16 | }; 17 | const submissions = await Submission.paginate({}, options); 18 | 19 | return APIResponse.Ok(res, submissions); 20 | } 21 | -------------------------------------------------------------------------------- /src/controllers/verifyController.ts: -------------------------------------------------------------------------------- 1 | import {Request, Response} from 'express'; 2 | import {User} from '../models/user'; 3 | 4 | export async function verify(req: Request, res: Response): Promise { 5 | const token = req.params.token; 6 | const user = await User.findOne({ 7 | verificationToken: token, 8 | }); 9 | 10 | if (!user) { 11 | return res.status(400).send('Invalid token'); 12 | } 13 | if (user.isVerified) { 14 | return res.json({ 15 | message: 'You email has been already verified!', 16 | }); 17 | } 18 | user.isVerified = true; 19 | user.save(); 20 | return res.json({ 21 | message: 'You email has been verified successfully!', 22 | }); 23 | } 24 | -------------------------------------------------------------------------------- /src/routes/problems.route.ts: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import * as problemController from '../controllers/problem'; 3 | import {authenticate} from '../middlewares/authentication'; 4 | import {authorize} from '../middlewares/authorization'; 5 | import {Roles} from '../models/user'; 6 | 7 | const router = express.Router(); 8 | 9 | router.use(authenticate); 10 | 11 | router.get('/', problemController.getAll); 12 | router.get('/:id', problemController.getWithId); 13 | 14 | router.use(authorize([Roles.ADMIN])); 15 | 16 | router.post('/', problemController.create); 17 | router.put('/:id', problemController.updateWithId); 18 | router.delete('/:id', problemController.deleteWithId); 19 | 20 | export default router; 21 | -------------------------------------------------------------------------------- /src/config.ts: -------------------------------------------------------------------------------- 1 | import clrs from 'colors'; 2 | 3 | const requiredEnv = [ 4 | 'MONGODB_URL', 5 | 'JWT_SECRET_KEY', 6 | 'EMAIL', 7 | 'EMAIL_PASSWORD', 8 | 'CF_SUBMITTER_URL', 9 | 'CF_SUBMITTER_API_KEY', 10 | 'CF_PROBLEM_SCRAPPER_URL', 11 | 'ADMIN_EMAIL', 12 | 'ADMIN_PASSWORD', 13 | ]; 14 | 15 | export function check(): void { 16 | const unsetEnv = requiredEnv.filter((env) => process.env[env] === undefined); 17 | if (unsetEnv.length > 0) { 18 | const errMsg = clrs.red( 19 | `Required env variables are not set: [${clrs.yellow( 20 | unsetEnv.join(', '.red), 21 | )}]`, 22 | ); 23 | throw new Error(errMsg); 24 | } 25 | console.info(clrs.green(`Configuration OKAY!`)); 26 | } 27 | -------------------------------------------------------------------------------- /src/routes/index.ts: -------------------------------------------------------------------------------- 1 | import exp from 'express'; 2 | import user from './user.route'; 3 | import problems from './problems.route'; 4 | import contests from './contests.route'; 5 | import submissions from './submissions.route'; 6 | import verify from './verify.route'; 7 | import standing from './standings.route'; 8 | 9 | const router = exp.Router(); 10 | 11 | router.use('/user', user); 12 | router.use('/problems', problems); 13 | router.use('/contests', contests); 14 | router.use('/submissions', submissions); 15 | router.use('/verify', verify); 16 | router.use('/standings', standing); 17 | 18 | // 404 19 | router.all('*', (_, res) => 20 | res.status(404).json({message: '🤔 Are you lost ?!'}), 21 | ); 22 | 23 | export default router; 24 | -------------------------------------------------------------------------------- /src/routes/submissions.route.ts: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import * as submissionController from '../controllers/submission'; 3 | import {authenticate} from '../middlewares/authentication'; 4 | import {authorize} from '../middlewares/authorization'; 5 | import {Roles} from '../models/user'; 6 | 7 | const router = express.Router(); 8 | 9 | router.get('/', submissionController.getAll); 10 | 11 | router.use(authenticate); 12 | router.get('/my', submissionController.getMySubmissions); 13 | // router.get('/:id', submissionController.getWithId); 14 | 15 | router.use(authorize([Roles.ADMIN])); 16 | // router.put('/:id', submissionController.updateWithId); 17 | // router.delete('/:id', submissionController.deleteWithId); 18 | 19 | export default router; 20 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "parserOptions": { 5 | "project": ["./tsconfig.json"] 6 | }, 7 | "plugins": ["@typescript-eslint", "prettier"], 8 | "extends": [ 9 | "eslint:recommended", 10 | "plugin:@typescript-eslint/eslint-recommended", 11 | "plugin:@typescript-eslint/recommended", 12 | "plugin:@typescript-eslint/recommended-requiring-type-checking", 13 | "plugin:prettier/recommended", 14 | "prettier/@typescript-eslint" 15 | ], 16 | "rules": { 17 | "curly": 1, 18 | "no-empty": 0, 19 | "no-unused-vars": 1, 20 | "@typescript-eslint/no-empty-function": [1, {"allow": ["constructors"]}], 21 | "@typescript-eslint/interface-name-prefix": [2, {"prefixWithI": "always"}] 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/controllers/problem/updateProblem.ts: -------------------------------------------------------------------------------- 1 | import {Problem, validateProblem} from '../../models/problem'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | import noId from '../../utils/noId'; 5 | 6 | export async function updateWithId( 7 | req: Request, 8 | res: Response, 9 | ): Promise { 10 | const problemId = req.params.id; 11 | 12 | const problem = await Problem.findById(problemId); 13 | 14 | if (!problem) { 15 | return APIResponse.NotFound(res, noId(Problem, problemId)); 16 | } 17 | 18 | const {error} = validateProblem(req.body); 19 | if (error) { 20 | return APIResponse.UnprocessableEntity(res, error.message); 21 | } 22 | 23 | await problem.set(req.body).save(); 24 | return APIResponse.Ok(res, problem); 25 | } 26 | -------------------------------------------------------------------------------- /src/database.ts: -------------------------------------------------------------------------------- 1 | import clrs from 'colors'; 2 | import mongoose from 'mongoose'; 3 | 4 | export async function connect(): Promise { 5 | const mongoURL = process.env.MONGODB_URL; 6 | if (!mongoURL) { 7 | const errMsg = clrs.red( 8 | `${clrs.yellow('MONGODB_URL')} environment variable was not set`, 9 | ); 10 | throw new Error(errMsg); 11 | } 12 | 13 | try { 14 | await mongoose.connect(mongoURL, { 15 | useUnifiedTopology: true, 16 | useNewUrlParser: true, 17 | useCreateIndex: true, 18 | useFindAndModify: false, 19 | }); 20 | 21 | console.info( 22 | clrs.green(`Successfully connected to ${clrs.yellow(mongoURL)}`), 23 | ); 24 | } catch (err) { 25 | console.error(clrs.red(`Failed to connect to ${clrs.yellow(mongoURL)}`)); 26 | throw err; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/middlewares/AuthenticatedUser.ts: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose'; 2 | 3 | import {User, IUser} from '../models/user'; 4 | import {IDecodedToken} from './authentication'; 5 | 6 | export class AuthenticatedUser { 7 | public readonly _id: string; 8 | public readonly role: string; 9 | 10 | constructor({role, _id}: IDecodedToken) { 11 | this._id = _id; 12 | this.role = role; 13 | } 14 | 15 | public async getUserFromDB(): Promise { 16 | return await User.findById(this._id); 17 | } 18 | 19 | public async isVerified(): Promise { 20 | const user = await User.findById(this._id).select('isVerified'); 21 | return !!user && user.isVerified; 22 | } 23 | 24 | public getObjectID(str: string): mongoose.Types.ObjectId { 25 | return mongoose.Types.ObjectId.createFromHexString(str); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/adminInit.ts: -------------------------------------------------------------------------------- 1 | import {User, Roles} from './models/user'; 2 | import bcrypt from 'bcryptjs'; 3 | import {yellow, green} from 'colors/safe'; 4 | 5 | export default async (): Promise => { 6 | // In a separate variable because findOne doesn't need password 7 | const password = process.env.ADMIN_PASSWORD || ''; 8 | 9 | const admin = { 10 | name: 'admin', 11 | email: process.env.ADMIN_EMAIL || '', 12 | role: Roles[Roles.ADMIN], 13 | fromInit: true, 14 | }; 15 | 16 | const user = await User.findOne(admin); 17 | 18 | if (user) { 19 | if (!(await bcrypt.compare(password, user.password))) { 20 | throw new Error("Found existing Admin but did't match password!"); 21 | } 22 | } else { 23 | await new User({...admin, password}).save(); 24 | } 25 | console.log(green(`Admin is ${yellow(admin.email)}`)); 26 | }; 27 | -------------------------------------------------------------------------------- /src/controllers/contest/createContest.ts: -------------------------------------------------------------------------------- 1 | import {Contest, validateContest, validProblemIDs} from '../../models/contest'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | import {IAuthenticatedRequest} from '../../middlewares'; 5 | 6 | export async function create(req: Request, res: Response): Promise { 7 | const {error} = validateContest(req.body); 8 | if (error) { 9 | return APIResponse.UnprocessableEntity(res, error.message); 10 | } 11 | 12 | if (!(await validProblemIDs(req.body.problems))) { 13 | return APIResponse.UnprocessableEntity(res, 'Invalid problem id'); 14 | } 15 | 16 | const contest = new Contest(req.body); 17 | contest.setter = (req as IAuthenticatedRequest).authenticatedUser._id; 18 | await contest.save(); 19 | return APIResponse.Ok(res, contest); 20 | } 21 | -------------------------------------------------------------------------------- /src/routes/contests.route.ts: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import * as contestController from '../controllers/contest'; 3 | import * as submissionController from '../controllers/submission'; 4 | import {authenticate} from '../middlewares/authentication'; 5 | import {authorize} from '../middlewares/authorization'; 6 | 7 | import {Roles} from '../models/user'; 8 | 9 | const router = express.Router(); 10 | 11 | router.get('/', contestController.getAll); 12 | router.get('/:id', contestController.getWithId); 13 | 14 | router.use(authenticate); 15 | 16 | router.post('/:contestID/submit/:problemID', submissionController.create); 17 | 18 | router.use(authorize([Roles.ADMIN])); 19 | 20 | router.post('/', contestController.create); 21 | router.put('/:id', contestController.updateWithId); 22 | router.delete('/:id', contestController.deleteWithId); 23 | 24 | export default router; 25 | -------------------------------------------------------------------------------- /insertNames.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import secrets 3 | import string 4 | import requests 5 | 6 | alphabet = string.ascii_uppercase + string.digits 7 | 8 | 9 | def randPass(length): 10 | password = ''.join(secrets.choice(alphabet) for i in range(length)) 11 | return password 12 | 13 | 14 | if __name__ == "__main__": 15 | 16 | with open('./data.txt') as csv_file: 17 | 18 | csv_reader = csv.DictReader(csv_file, delimiter=',') 19 | categories_dictionary = dict() 20 | for user in csv_reader: 21 | name = user["name"].strip() 22 | email = user["email"].strip() 23 | password = randPass(8) 24 | print("{}, {}, {}".format(name, email, password)) 25 | response = requests.post("http://localhost:5000/user/signup", { 26 | "name": name, 27 | "email": email, 28 | "password": password 29 | }) 30 | # print(response.json()) 31 | -------------------------------------------------------------------------------- /src/lib/submission-consumers/SubmissionsQ.ts: -------------------------------------------------------------------------------- 1 | import amqplib from 'amqplib'; 2 | import {ISubmission} from '../../models/submission'; 3 | 4 | export default class SubmissionsQ { 5 | private static isInit = false; 6 | static channel: amqplib.Channel; 7 | static pendingQ = 'pending'; 8 | static judgedQ = 'judged'; 9 | 10 | private constructor() {} 11 | 12 | public static async init(): Promise { 13 | if (this.isInit == false) { 14 | const URL = process.env.RABBITMQ_URL || ''; 15 | const connection = await amqplib.connect(URL); 16 | this.channel = await connection.createChannel(); 17 | await this.channel.assertQueue(this.pendingQ); 18 | await this.channel.assertQueue(this.judgedQ); 19 | this.isInit = true; 20 | } 21 | } 22 | 23 | public static send(qName: string, data: ISubmission): void { 24 | this.channel.sendToQueue(qName, Buffer.from(JSON.stringify(data))); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/controllers/contest/updateContest.ts: -------------------------------------------------------------------------------- 1 | import {Contest, validateContest, validProblemIDs} from '../../models/contest'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | import noId from '../../utils/noId'; 5 | 6 | export async function updateWithId( 7 | req: Request, 8 | res: Response, 9 | ): Promise { 10 | const contestId = req.params.id; 11 | 12 | const contest = await Contest.findById(contestId); 13 | 14 | if (!contest) { 15 | return APIResponse.NotFound(res, noId(Contest, contestId)); 16 | } 17 | 18 | const {error} = validateContest(req.body); 19 | if (error) { 20 | return APIResponse.UnprocessableEntity(res, error.message); 21 | } 22 | 23 | if (!(await validProblemIDs(req.body.problems))) { 24 | return APIResponse.UnprocessableEntity(res, 'Invalid problem id'); 25 | } 26 | await contest.set(req.body).save(); 27 | return APIResponse.Ok(res, contest); 28 | } 29 | -------------------------------------------------------------------------------- /src/controllers/problem/createProblem.ts: -------------------------------------------------------------------------------- 1 | import {Problem, validateProblem} from '../../models/problem'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | import {CodeforcesProblemScrapper} from '../../lib/problem-scrapper/CodeforcesProblemScrapper'; 5 | 6 | export async function create(req: Request, res: Response): Promise { 7 | const {error} = validateProblem(req.body); 8 | if (error) { 9 | return APIResponse.UnprocessableEntity(res, error.message); 10 | } 11 | try { 12 | const problem = new Problem(req.body); 13 | if (problem.judge.type === 'CODEFORCES' && problem.judge.cfID) { 14 | const cfScrapper = new CodeforcesProblemScrapper(); 15 | problem.description = await cfScrapper.parseProblem(problem.judge.cfID); 16 | } 17 | await problem.save(); 18 | return APIResponse.Created(res, problem); 19 | } catch (err) { 20 | return APIResponse.ServerError(res, err); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/lib/submission-consumers/pending.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file runs separately as a consumer gets submissions from the pending Q and process them 3 | */ 4 | 5 | import {JudgeFactory} from '../judge/JudgeFactory'; 6 | import SubmissionsQ from './SubmissionsQ'; 7 | 8 | (async (): Promise => { 9 | await SubmissionsQ.init(); 10 | SubmissionsQ.channel.consume(SubmissionsQ.pendingQ, async (msg) => { 11 | if (!msg) { 12 | return; 13 | } 14 | let submission = JSON.parse(msg.content.toString()); 15 | const response = await new JudgeFactory(submission.problem) 16 | .createJudge(submission) 17 | .getVerdict(); 18 | SubmissionsQ.channel.ack(msg); // remove the submission from the Q 19 | let q = SubmissionsQ.pendingQ; 20 | if (response.isJudged) { 21 | submission = { 22 | ...submission, 23 | ...response, 24 | }; 25 | q = SubmissionsQ.judgedQ; 26 | } 27 | setTimeout(() => SubmissionsQ.send(q, submission), 5000); 28 | }); 29 | })(); 30 | -------------------------------------------------------------------------------- /src/lib/problem-scrapper/CodeforcesProblemScrapper.ts: -------------------------------------------------------------------------------- 1 | import Axios from 'axios'; 2 | import {IProblem} from '../../models/problem'; 3 | 4 | export class CodeforcesProblemScrapper { 5 | private readonly BASE_URL: string; 6 | constructor() { 7 | this.BASE_URL = process.env.CF_PROBLEM_SCRAPPER_URL || ''; 8 | } 9 | async parseProblem(problemID: string): Promise { 10 | const resp = await Axios.get(`${this.BASE_URL}/?id=${problemID}`); 11 | if (resp.status === 200) { 12 | const {timeLimit, memoryLimit} = resp.data; 13 | if ( 14 | timeLimit.unit.startsWith('second') && 15 | memoryLimit.unit.startsWith('mega') 16 | ) { 17 | // only store values 18 | resp.data.timeLimit = timeLimit.value; 19 | resp.data.memoryLimit = memoryLimit.value; 20 | return resp.data; 21 | } else { 22 | throw new Error(`Unkown unit type ${timeLimit} ${memoryLimit}`); 23 | } 24 | } else { 25 | console.error(resp); 26 | throw new Error(resp.data); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/controllers/user/signin.ts: -------------------------------------------------------------------------------- 1 | import {User} from '../../models/user'; 2 | import {Request, Response} from 'express'; 3 | import bcrypt from 'bcryptjs'; 4 | import Joi from '@hapi/joi'; 5 | import APIResponse from '../../utils/APIResponse'; 6 | 7 | export async function signin(req: Request, res: Response): Promise { 8 | const {error} = validateSignin(req.body); 9 | 10 | if (error) { 11 | return APIResponse.UnprocessableEntity(res, error.message); 12 | } 13 | 14 | const user = await User.findOne({ 15 | email: req.body.email, 16 | }); 17 | 18 | if (!user || !(await bcrypt.compare(req.body.password, user.password))) { 19 | return APIResponse.Unauthorized(res, 'Invalid email or password!'); 20 | } 21 | 22 | return APIResponse.Ok(res, { 23 | token: user.generateAuthToken(), 24 | user, 25 | }); 26 | } 27 | 28 | // prettier-ignore 29 | function validateSignin(user: {}): Joi.ValidationResult { 30 | const schema = Joi.object({ 31 | email: Joi.string().email().required(), 32 | password: Joi.string().required() 33 | }) 34 | return schema.validate(user); 35 | } 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Amr Salama, Kerollos Magdy 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/lib/judge/JudgeFactory.ts: -------------------------------------------------------------------------------- 1 | import {CodeforcesJudge} from './CodeforcesJudge'; 2 | import {Judge0Judge} from './Judge0Judge'; 3 | import {LocalJudge} from './LocalJudge'; 4 | import {IProblem, JudgeType} from '../../models/problem'; 5 | import {ISubmission} from '../../models/submission'; 6 | import {BaseJudge} from './BaseJudge'; 7 | 8 | export interface ISubmitterResponse { 9 | judgeSubmissionID: string; 10 | verdict: string; 11 | isJudged: boolean; 12 | time: number; 13 | memory: number; 14 | } 15 | 16 | export interface IJudge extends BaseJudge { 17 | submit(): Promise; 18 | getVerdict(): Promise; 19 | } 20 | 21 | export class JudgeFactory { 22 | constructor(public readonly problem: IProblem) {} 23 | 24 | createJudge(submission: ISubmission): IJudge { 25 | switch (JudgeType[this.problem.judge.type]) { 26 | case JudgeType.CODEFORCES: 27 | return new CodeforcesJudge(submission); 28 | case JudgeType.JUDGE0: 29 | return new Judge0Judge(submission); 30 | case JudgeType.LOCAL: 31 | return new LocalJudge(submission); 32 | default: 33 | throw new Error('unkown judge: ' + this.problem.judge.type); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/server.ts: -------------------------------------------------------------------------------- 1 | import http from 'http'; 2 | import clrs from 'colors'; 3 | import express from 'express'; 4 | import cors from 'cors'; 5 | import helmet from 'helmet'; 6 | import morgan from 'morgan'; 7 | import bearerToken from 'express-bearer-token'; 8 | import routes from './routes'; 9 | 10 | const app = express(); 11 | 12 | const logger = 13 | app.get('env') === 'development' 14 | ? morgan('dev') 15 | : morgan('combined', { 16 | skip: (_, res) => res.statusCode < 500, 17 | }); 18 | 19 | app.use(logger); 20 | app.use(express.json({limit: '5mb'})); 21 | app.use(express.urlencoded({limit: '5mb', extended: true})); 22 | app.use(cors()); 23 | app.use(helmet()); 24 | app.use(bearerToken()); 25 | app.use(routes); 26 | 27 | export function run(): Promise { 28 | return new Promise((resolve, reject) => { 29 | const port = process.env.PORT || 5000; 30 | const server = app.listen(port); 31 | 32 | server.once('listening', () => { 33 | console.info( 34 | clrs.green(`Server is listening on port ${clrs.yellow(port + '')}`), 35 | ); 36 | resolve(server); 37 | }); 38 | 39 | server.once('error', (err) => { 40 | console.error( 41 | clrs.red(`Server failed to listen on port ${clrs.yellow(port + '')}`), 42 | ); 43 | reject(err); 44 | }); 45 | }); 46 | } 47 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | 24 | # nyc test coverage 25 | .nyc_output 26 | 27 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 28 | .grunt 29 | 30 | # Bower dependency directory (https://bower.io/) 31 | bower_components 32 | 33 | # node-waf configuration 34 | .lock-wscript 35 | 36 | # Compiled binary addons (https://nodejs.org/api/addons.html) 37 | build/Release 38 | 39 | # Dependency directories 40 | node_modules/ 41 | jspm_packages/ 42 | 43 | # TypeScript v1 declaration files 44 | typings/ 45 | 46 | # Optional npm cache directory 47 | .npm 48 | 49 | # Optional eslint cache 50 | .eslintcache 51 | 52 | # Optional REPL history 53 | .node_repl_history 54 | 55 | # Output of 'npm pack' 56 | *.tgz 57 | 58 | # Yarn Integrity file 59 | .yarn-integrity 60 | 61 | # dotenv environment variables file 62 | .env 63 | .env.test 64 | 65 | # parcel-bundler cache (https://parceljs.org/) 66 | .cache 67 | 68 | # next.js build output 69 | .next 70 | 71 | # nuxt.js build output 72 | .nuxt 73 | 74 | # vuepress build output 75 | .vuepress/dist 76 | 77 | # Serverless directories 78 | .serverless/ 79 | 80 | # FuseBox cache 81 | .fusebox/ 82 | 83 | # DynamoDB Local files 84 | .dynamodb/ 85 | 86 | dist/ -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | 24 | # nyc test coverage 25 | .nyc_output 26 | 27 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 28 | .grunt 29 | 30 | # Bower dependency directory (https://bower.io/) 31 | bower_components 32 | 33 | # node-waf configuration 34 | .lock-wscript 35 | 36 | # Compiled binary addons (https://nodejs.org/api/addons.html) 37 | build/Release 38 | 39 | # Dependency directories 40 | node_modules/ 41 | jspm_packages/ 42 | 43 | # TypeScript v1 declaration files 44 | typings/ 45 | 46 | # Optional npm cache directory 47 | .npm 48 | 49 | # Optional eslint cache 50 | .eslintcache 51 | 52 | # Optional REPL history 53 | .node_repl_history 54 | 55 | # Output of 'npm pack' 56 | *.tgz 57 | 58 | # Yarn Integrity file 59 | .yarn-integrity 60 | 61 | # dotenv environment variables file 62 | .env 63 | .env.test 64 | 65 | # parcel-bundler cache (https://parceljs.org/) 66 | .cache 67 | 68 | # next.js build output 69 | .next 70 | 71 | # nuxt.js build output 72 | .nuxt 73 | 74 | # vuepress build output 75 | .vuepress/dist 76 | 77 | # Serverless directories 78 | .serverless/ 79 | 80 | # FuseBox cache 81 | .fusebox/ 82 | 83 | # DynamoDB Local files 84 | .dynamodb/ 85 | 86 | dist/ -------------------------------------------------------------------------------- /src/controllers/problem/getAllProblems.ts: -------------------------------------------------------------------------------- 1 | import {Request, Response} from 'express'; 2 | import {Contest} from '../../models/contest'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | import {IAuthenticatedRequest} from '../../middlewares'; 5 | 6 | export async function getAll(req: Request, res: Response): Promise { 7 | // only return problems that their contest has not started yet 8 | const problems = await Contest.aggregate([ 9 | { 10 | $match: { 11 | startDate: {$lt: new Date()}, 12 | }, 13 | }, 14 | { 15 | $lookup: { 16 | from: 'problems', 17 | localField: 'problems', 18 | foreignField: '_id', 19 | as: 'problems', 20 | }, 21 | }, 22 | { 23 | $unwind: '$problems', 24 | }, 25 | { 26 | $replaceRoot: { 27 | newRoot: '$problems', 28 | }, 29 | }, 30 | { 31 | $lookup: { 32 | from: 'submissions', 33 | localField: (req as IAuthenticatedRequest).authenticatedUser._id, 34 | foreignField: 'user', 35 | as: 'submissions', 36 | }, 37 | }, 38 | ]); 39 | 40 | // for (const problem of problems) { 41 | // problem.submissions = await Submission.find({ 42 | // user: (req as IAuthenticatedRequest).authenticatedUser._id, 43 | // problem 44 | // }); 45 | // problem.isSolved = await Submission.exists({ 46 | // user: (req as IAuthenticatedRequest).authenticatedUser._id, 47 | // problem, 48 | // verdict: "Accepted" 49 | // }) 50 | // } 51 | 52 | return APIResponse.Ok(res, problems); 53 | } 54 | -------------------------------------------------------------------------------- /src/middlewares/authentication.ts: -------------------------------------------------------------------------------- 1 | import {NextFunction, Request, Response} from 'express'; 2 | import jwt from 'jsonwebtoken'; 3 | 4 | import APIResponse from '../utils/APIResponse'; 5 | import {AuthenticatedUser} from './AuthenticatedUser'; 6 | import noId from '../utils/noId'; 7 | import {User} from '../models/user'; 8 | 9 | export interface IDecodedToken { 10 | readonly _id: string; 11 | readonly role: string; 12 | } 13 | 14 | export interface IAuthenticatedRequest extends Request { 15 | authenticatedUser: AuthenticatedUser; 16 | } 17 | /** 18 | * returns the authenticated user 19 | * @param token the token in the request 20 | */ 21 | export function _auth(token: string): AuthenticatedUser { 22 | const decodedToken = jwt.verify( 23 | token, 24 | process.env.JWT_SECRET_KEY || '', 25 | ) as IDecodedToken; 26 | return new AuthenticatedUser(decodedToken); 27 | } 28 | 29 | export async function authenticate( 30 | req: Request, 31 | res: Response, 32 | next: NextFunction, 33 | ): Promise { 34 | const token = req.token; 35 | 36 | if (!token) { 37 | return APIResponse.Unauthorized(res, 'Access denied! No token provided.'); 38 | } 39 | 40 | try { 41 | const authenticatedUser = _auth(token); 42 | if ((await authenticatedUser.getUserFromDB()) === null) { 43 | return APIResponse.Unauthorized(res, noId(User, authenticatedUser._id)); 44 | } 45 | (req as IAuthenticatedRequest).authenticatedUser = authenticatedUser; 46 | 47 | next(); 48 | } catch (error) { 49 | console.error(error); 50 | return APIResponse.BadRequest(res); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/models/standing.ts: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose'; 2 | import {IContest} from './contest'; 3 | import {IUser} from './user'; 4 | import {IProblem} from './problem'; 5 | import {ISubmission} from './submission'; 6 | 7 | export interface IStanding extends mongoose.Document { 8 | contest: IContest; 9 | user: IUser; 10 | problems: { 11 | problem: IProblem; 12 | isAccepted: boolean; 13 | isFirstAccepted: boolean; 14 | failedSubmissions: number; 15 | solvedAt: Date; 16 | submissions: ISubmission[]; 17 | }[]; 18 | solved: number; 19 | penality: number; 20 | } 21 | 22 | const standingSchema = new mongoose.Schema({ 23 | contest: { 24 | type: mongoose.Types.ObjectId, 25 | required: true, 26 | ref: 'Contest', 27 | }, 28 | user: { 29 | type: mongoose.Types.ObjectId, 30 | required: true, 31 | ref: 'User', 32 | }, 33 | problems: [ 34 | { 35 | problem: { 36 | type: mongoose.Types.ObjectId, 37 | required: true, 38 | ref: 'Problem', 39 | }, 40 | isAccepted: { 41 | type: Boolean, 42 | default: false, 43 | }, 44 | isFirstAccepted: { 45 | type: Boolean, 46 | default: false, 47 | }, 48 | failedSubmissions: { 49 | type: Number, 50 | default: 0, 51 | }, 52 | submissions: { 53 | type: [mongoose.Types.ObjectId], 54 | ref: 'Submission', 55 | default: [], 56 | }, 57 | solvedAt: { 58 | type: Date, 59 | }, 60 | _id: false, 61 | }, 62 | ], 63 | solved: { 64 | type: Number, 65 | default: 0, 66 | }, 67 | penality: { 68 | type: Number, 69 | default: 0, 70 | }, 71 | }); 72 | 73 | export const Standing = mongoose.model('Standing', standingSchema); 74 | -------------------------------------------------------------------------------- /src/controllers/submission/createSubmission.ts: -------------------------------------------------------------------------------- 1 | import {Submission, validateSubmission} from '../../models/submission'; 2 | import {Request, Response} from 'express'; 3 | import APIResponse from '../../utils/APIResponse'; 4 | import {IAuthenticatedRequest} from '../../middlewares'; 5 | import {BaseJudge} from '../../lib/judge/BaseJudge'; 6 | import {JudgeFactory} from '../../lib/judge/JudgeFactory'; 7 | import noId from '../../utils/noId'; 8 | import {Problem} from '../../models/problem'; 9 | import {Contest} from '../../models/contest'; 10 | 11 | export async function create(req: Request, res: Response): Promise { 12 | req.body.problem = req.params.problemID; 13 | req.body.contest = req.params.contestID; 14 | req.body.user = (req as IAuthenticatedRequest).authenticatedUser._id; 15 | 16 | const {error} = validateSubmission(req.body); 17 | if (error) { 18 | return APIResponse.UnprocessableEntity(res, error.message); 19 | } 20 | 21 | const submission = await new Submission(req.body) 22 | .populate({ 23 | path: 'problem', 24 | select: 'judge', 25 | }) 26 | .populate({ 27 | path: 'contest', 28 | select: 'startDate duration problems', 29 | }) 30 | .execPopulate(); 31 | 32 | if (!submission.contest) { 33 | return APIResponse.NotFound(res, noId(Contest, req.params.contestID)); 34 | } 35 | if (!submission.problem) { 36 | return APIResponse.NotFound(res, noId(Problem, req.params.problemID)); 37 | } 38 | // can submit? 39 | if (!BaseJudge.contestStarted(submission.contest)) { 40 | return APIResponse.Forbidden( 41 | res, 42 | 'You cannot submit to this contest! contest has not started yet!', 43 | ); 44 | } 45 | 46 | try { 47 | new JudgeFactory(submission.problem).createJudge(submission).submit(); 48 | } catch (err) { 49 | console.error(err); 50 | } 51 | 52 | return APIResponse.Created(res, submission); 53 | } 54 | -------------------------------------------------------------------------------- /src/lib/judge/CodeforcesJudge.ts: -------------------------------------------------------------------------------- 1 | import {IJudge, ISubmitterResponse} from './JudgeFactory'; 2 | import {BaseJudge} from './BaseJudge'; 3 | import {ISubmission} from '../../models/submission'; 4 | import Axios, {AxiosRequestConfig} from 'axios'; 5 | import SubmissionsQ from '../submission-consumers/SubmissionsQ'; 6 | 7 | export class CodeforcesJudge extends BaseJudge implements IJudge { 8 | cfSubmitterBaseUrl: string; 9 | cfSubmitterApiKey: string; 10 | cfContestID: string; 11 | cfProblemID: string; 12 | 13 | constructor(submission: ISubmission) { 14 | super(submission); 15 | this.cfSubmitterBaseUrl = process.env.CF_SUBMITTER_URL || ''; 16 | this.cfSubmitterApiKey = process.env.CF_SUBMITTER_API_KEY || ''; 17 | const cfID = this.problem.judge.cfID?.split('/'); 18 | if (!cfID) { 19 | throw new Error('Not valid cfID' + cfID); 20 | } 21 | [this.cfContestID, this.cfProblemID] = cfID; 22 | } 23 | 24 | async submit(): Promise { 25 | const submission = { 26 | sourceCode: this.submission.sourceCode, 27 | langId: this.submission.languageID, 28 | contestId: this.cfContestID, 29 | problem: this.cfProblemID, 30 | }; 31 | const response = await Axios.post( 32 | `${this.cfSubmitterBaseUrl}/submit`, 33 | submission, 34 | this.getConfig(), 35 | ); 36 | this.submission.set(response.data); 37 | await this.submission.save(); 38 | if (this.submission.isJudged === false) { 39 | SubmissionsQ.send(SubmissionsQ.pendingQ, this.submission); 40 | } 41 | } 42 | 43 | async getVerdict(): Promise { 44 | const url = `${this.cfSubmitterBaseUrl}/submission/${this.cfContestID}/${this.submission.judgeSubmissionID}`; 45 | const resp = await Axios.get(url, this.getConfig()); 46 | return resp.data; 47 | } 48 | 49 | getConfig(): AxiosRequestConfig { 50 | return { 51 | headers: { 52 | 'x-api-key': this.cfSubmitterApiKey, 53 | }, 54 | }; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jx-api", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "dist/index.js", 6 | "scripts": { 7 | "start": "node -r dotenv/config -r source-map-support/register .", 8 | "start:submission-getter": "nodemon --exec 'node -r dotenv/config -r source-map-support/register dist/lib/submissionGetter.js'", 9 | "postinstall": "npm run build", 10 | "dev": "tsc -w & nodemon --config .nodemonrc", 11 | "build": "tsc", 12 | "lint": "eslint . --ext .ts --fix" 13 | }, 14 | "repository": { 15 | "type": "git", 16 | "url": "git+https://github.com/JudgeX-JX/backend.git" 17 | }, 18 | "license": "MIT", 19 | "bugs": { 20 | "url": "https://github.com/JudgeX-JX/backend/issues" 21 | }, 22 | "homepage": "https://github.com/JudgeX-JX/backend#readme", 23 | "dependencies": { 24 | "@hapi/joi": "^17.1.1", 25 | "amqplib": "^0.10.3", 26 | "axios": "^0.21.2", 27 | "bcryptjs": "^2.4.3", 28 | "colors": "^1.4.0", 29 | "cors": "^2.8.5", 30 | "dotenv": "^8.2.0", 31 | "express": "^4.18.2", 32 | "express-bearer-token": "^2.4.0", 33 | "helmet": "^3.22.0", 34 | "jsonwebtoken": "^9.0.0", 35 | "mongoose": "^5.13.20", 36 | "mongoose-paginate-v2": "^1.3.52", 37 | "morgan": "^1.10.0", 38 | "nodemailer": "^6.6.1", 39 | "source-map-support": "^0.5.16", 40 | "typescript": "^3.8.3" 41 | }, 42 | "devDependencies": { 43 | "@types/amqplib": "^0.5.13", 44 | "@types/bcryptjs": "^2.4.2", 45 | "@types/cors": "^2.8.6", 46 | "@types/express": "^4.17.4", 47 | "@types/hapi__joi": "^16.0.12", 48 | "@types/helmet": "0.0.45", 49 | "@types/jsonwebtoken": "^8.3.8", 50 | "@types/mongoose": "^5.7.8", 51 | "@types/mongoose-paginate-v2": "^1.3.1", 52 | "@types/morgan": "^1.9.0", 53 | "@types/node": "^13.11.0", 54 | "@types/nodemailer": "^6.4.0", 55 | "@typescript-eslint/eslint-plugin": "^2.27.0", 56 | "@typescript-eslint/parser": "^2.27.0", 57 | "eslint": "^6.8.0", 58 | "eslint-config-prettier": "^6.10.1", 59 | "eslint-plugin-prettier": "^3.1.2", 60 | "nodemon": "^2.0.20", 61 | "prettier": "2.0.4" 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/utils/APIResponse.ts: -------------------------------------------------------------------------------- 1 | import {Response} from 'express'; 2 | 3 | export default { 4 | // Custom response 5 | CustomResponse: ( 6 | res: Response, 7 | status: number, 8 | messsage: string, 9 | ): Response => { 10 | return res.status(status).json(messsage); 11 | }, 12 | 13 | // 200 Ok 14 | Ok: (res: Response, data = {}): Response => { 15 | return res.status(200).json(data); 16 | }, 17 | 18 | // 201 Ok 19 | Created: (res: Response, data = {}): Response => { 20 | return res.status(201).json(data); 21 | }, 22 | 23 | // 204 No Content 24 | NoContent: (res: Response): Response => { 25 | return res.status(204).json(); 26 | }, 27 | 28 | // 400 Bad request 29 | BadRequest: (res: Response, message = 'Bad request'): Response => { 30 | return res.status(400).json({message}); 31 | }, 32 | 33 | // 401 Unauthorized 34 | Unauthorized: (res: Response, message = 'Unauthorized access'): Response => { 35 | return res.status(401).json({message}); 36 | }, 37 | 38 | // 402 PaymentRequired 39 | PaymentRequired: (res: Response, message = 'Payment Required'): Response => { 40 | return res.status(402).json({message}); 41 | }, 42 | 43 | // 403 Forbidden 44 | Forbidden: (res: Response, message = 'Forbidden Access'): Response => { 45 | return res.status(403).json({message}); 46 | }, 47 | 48 | // 404 Not found 49 | NotFound: (res: Response, message = 'Not found'): Response => { 50 | return res.status(404).json({message}); 51 | }, 52 | 53 | // 415 Unsupported media type 54 | UnsupportedMediaType: ( 55 | res: Response, 56 | message = 'Unsupported media type', 57 | ): Response => { 58 | return res.status(415).json({message}); 59 | }, 60 | 61 | // 422 Unprocessable Entity 62 | UnprocessableEntity: (res: Response, message: string): Response => { 63 | return res.status(422).json({message}); 64 | }, 65 | 66 | // 500 Server error 67 | ServerError: ( 68 | res: Response, 69 | err: Error, 70 | message = 'Internal server error', 71 | ): Response => { 72 | console.error(err.message.red); 73 | return res.status(500).json({message}); 74 | }, 75 | }; 76 | -------------------------------------------------------------------------------- /src/controllers/user/signup.ts: -------------------------------------------------------------------------------- 1 | import {User, validateUser} from '../../models/user'; 2 | import {Request, Response} from 'express'; 3 | import nodemailer from 'nodemailer'; 4 | import colors from 'colors/safe'; 5 | import APIResponse from '../../utils/APIResponse'; 6 | 7 | export async function signup(req: Request, res: Response): Promise { 8 | const {error} = validateUser(req.body); 9 | 10 | if (error) { 11 | return APIResponse.UnprocessableEntity(res, error.message); 12 | } 13 | 14 | if (await User.findOne({email: req.body.email})) { 15 | return APIResponse.UnprocessableEntity(res, 'This email already exists!'); 16 | } 17 | 18 | const user = new User(req.body); 19 | 20 | if (process.env.EMAIL_VERIFICATION?.toLowerCase() === 'true') { 21 | user.generateEmailVerificationToken(); 22 | 23 | sendVerificationEmail( 24 | user.verificationToken, 25 | user.email, 26 | req.headers.host || '', 27 | ); 28 | } 29 | 30 | await user.save(); 31 | return APIResponse.Ok(res, { 32 | token: user.generateAuthToken(), 33 | user, 34 | }); 35 | } 36 | 37 | async function sendVerificationEmail( 38 | verificationToken: string, 39 | recieverEmail: string, 40 | host: string, 41 | ): Promise { 42 | const sender: {email: string; password: string} = { 43 | email: process.env.EMAIL || '', 44 | password: process.env.EMAIL_PASSWORD || '', 45 | }; 46 | 47 | if (!sender.email || !sender.password) { 48 | console.log(colors.yellow('Undefined Email | password')); 49 | return; 50 | } 51 | 52 | const transporter = nodemailer.createTransport({ 53 | service: 'Gmail', 54 | auth: { 55 | user: sender.email, 56 | pass: sender.password, 57 | }, 58 | }); 59 | 60 | const verfificationLink = 61 | 'http://' + host + '/verify/' + verificationToken + ''; 62 | 63 | await transporter.sendMail({ 64 | from: `"JudgeX" <${sender.email}>`, // sender address 65 | to: recieverEmail, 66 | subject: 'Verify Your Email', // Subject 67 | html: 68 | "Please use the following link to verify your Email: here.", 71 | }); 72 | } 73 | -------------------------------------------------------------------------------- /src/models/contest.ts: -------------------------------------------------------------------------------- 1 | import mongoose, {PaginateModel} from 'mongoose'; 2 | import Joi from '@hapi/joi'; 3 | import mongoosePaginate from 'mongoose-paginate-v2'; 4 | import {Problem} from './problem'; 5 | 6 | export interface IContest extends mongoose.Document { 7 | name: string; 8 | setter: string; 9 | problems: [string]; 10 | registeredUsers: [string]; 11 | startDate: Date; 12 | duration: number; 13 | password?: string; 14 | } 15 | 16 | const contestSchema = new mongoose.Schema({ 17 | name: { 18 | type: String, 19 | required: true, 20 | minlength: 1, 21 | maxlength: 50, 22 | }, 23 | setter: { 24 | type: mongoose.Schema.Types.ObjectId, 25 | required: true, 26 | ref: 'User', 27 | }, 28 | problems: [ 29 | { 30 | type: mongoose.Schema.Types.ObjectId, 31 | ref: 'Problem', 32 | }, 33 | ], 34 | registeredUsers: [ 35 | { 36 | type: mongoose.Schema.Types.ObjectId, 37 | ref: 'User', 38 | }, 39 | ], 40 | startDate: { 41 | type: Date, 42 | required: true, 43 | }, 44 | duration: { 45 | type: Number, 46 | required: true, // number of minutes the contest will last 47 | }, 48 | password: { 49 | type: String, 50 | // no password by default (the contest is general i.e: available for all the users) 51 | }, 52 | }); 53 | 54 | contestSchema.plugin(mongoosePaginate); 55 | 56 | export const Contest = mongoose.model( 57 | 'Contest', 58 | contestSchema, 59 | ) as PaginateModel; 60 | 61 | export async function validProblemIDs(problems: string[]): Promise { 62 | try { 63 | return await Problem.exists({ 64 | // TODO WARNING remove never when $all problem is fixed 65 | _id: {$all: problems as never}, 66 | }); 67 | } catch (err) { 68 | console.log(err); 69 | return false; 70 | } 71 | } 72 | 73 | // prettier-ignore 74 | export function validateContest(contest: {}): Joi.ValidationResult { 75 | const schema = Joi.object({ 76 | name: Joi.string().required().min(1).max(50), 77 | problems: Joi.array().required().min(1).items(Joi.string()), 78 | startDate: Joi.date().required().min(Date.now()), 79 | duration: Joi.number().required().min(1), 80 | password: Joi.string().min(1) 81 | }) 82 | return schema.validate(contest); 83 | } 84 | -------------------------------------------------------------------------------- /src/models/user.ts: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose'; 2 | import Joi from '@hapi/joi'; 3 | import jwt from 'jsonwebtoken'; 4 | import crypto from 'crypto'; 5 | import {enumToArray} from '../utils/enumToArray'; 6 | import {IDecodedToken} from '../middlewares'; 7 | import bcrypt from 'bcryptjs'; 8 | 9 | export enum Roles { 10 | ADMIN, 11 | PROBLEM_SETTER, 12 | USER, 13 | } 14 | 15 | export interface IUser extends mongoose.Document { 16 | name: string; 17 | email: string; 18 | password: string; 19 | role: string; 20 | isVerified: boolean; 21 | verificationToken: string; 22 | generateEmailVerificationToken(): void; 23 | generateAuthToken(): string; 24 | } 25 | 26 | const userSchema = new mongoose.Schema({ 27 | name: { 28 | type: String, 29 | required: true, 30 | minlength: 3, 31 | maxlength: 50, 32 | }, 33 | email: { 34 | type: String, 35 | required: true, 36 | minlength: 3, 37 | maxlength: 50, 38 | unique: true, 39 | }, 40 | password: { 41 | type: String, 42 | required: true, 43 | }, 44 | role: { 45 | type: String, 46 | default: Roles[Roles.USER], 47 | enum: enumToArray(Roles), 48 | }, 49 | isVerified: { 50 | required: true, 51 | type: Boolean, 52 | default: false, 53 | }, 54 | verificationToken: { 55 | // required: true, 56 | type: String, 57 | }, 58 | fromInit: { 59 | // only for users created on server init 60 | type: Boolean, 61 | }, 62 | }); 63 | 64 | userSchema.methods.generateEmailVerificationToken = function (): string { 65 | this.verificationToken = crypto.randomBytes(16).toString('hex'); 66 | return this.verificationToken; 67 | }; 68 | 69 | userSchema.methods.generateAuthToken = function (): string { 70 | const token: IDecodedToken = { 71 | role: this.role, 72 | _id: this._id, 73 | }; 74 | return jwt.sign(token, process.env.JWT_SECRET_KEY || ''); 75 | }; 76 | 77 | userSchema.methods.toJSON = function (): IUser { 78 | const obj = this.toObject(); 79 | delete obj.password; 80 | return obj; 81 | }; 82 | 83 | userSchema.pre('save', async function (this: IUser, next) { 84 | const salt = await bcrypt.genSalt(); 85 | this.password = await bcrypt.hash(this.password, salt); 86 | next(); 87 | }); 88 | 89 | export const User = mongoose.model('User', userSchema); 90 | 91 | // prettier-ignore 92 | export function validateUser(user: {}): Joi.ValidationResult { 93 | const schema = Joi.object({ 94 | name: Joi.string().min(3).max(50).required(), 95 | email: Joi.string().min(3).max(50).required().email(), 96 | password: Joi.string().min(6).max(50).required() 97 | }); 98 | 99 | return schema.validate(user); 100 | } 101 | -------------------------------------------------------------------------------- /src/models/problem.ts: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose'; 2 | import Joi from '@hapi/joi'; 3 | import {enumToArray} from '../utils/enumToArray'; 4 | import mongoosePaginate from 'mongoose-paginate-v2'; 5 | 6 | export enum JudgeType { 7 | LOCAL, 8 | JUDGE0, 9 | CODEFORCES, 10 | } 11 | 12 | type JudgeName = 'LOCAL' | 'JUDGE0' | 'CODEFORCES'; 13 | export interface IProblem extends mongoose.Document { 14 | description: { 15 | title: string; 16 | statement: string; 17 | inputSpecification: string; 18 | outputSpecification: string; 19 | samples: [{input: string; output: string}]; 20 | timeLimit: number; 21 | memoryLimit: number; 22 | note: string; 23 | }; 24 | judge: { 25 | type: JudgeName; 26 | tests?: [{input: string; output: string}]; 27 | cfID?: string; 28 | }; 29 | } 30 | 31 | const testCaseSchema = new mongoose.Schema( 32 | { 33 | input: String, 34 | output: String, 35 | }, 36 | {_id: false}, 37 | ); 38 | 39 | const judgeSchema = new mongoose.Schema( 40 | { 41 | type: { 42 | type: String, 43 | enum: enumToArray(JudgeType), 44 | required: true, 45 | }, 46 | tests: testCaseSchema, 47 | cfID: String, 48 | }, 49 | {_id: false}, 50 | ); 51 | 52 | const problemSchema = new mongoose.Schema({ 53 | description: { 54 | title: {required: true, type: String}, 55 | statement: {required: true, type: String}, 56 | inputSpecification: {required: true, type: String}, 57 | outputSpecification: {required: true, type: String}, 58 | samples: {required: true, type: [testCaseSchema]}, 59 | timeLimit: {required: true, type: Number}, 60 | memoryLimit: {required: true, type: Number}, 61 | note: {required: true, type: String}, 62 | }, 63 | judge: judgeSchema, 64 | }); 65 | 66 | problemSchema.plugin(mongoosePaginate); 67 | 68 | export const Problem = mongoose.model('Problem', problemSchema); 69 | 70 | // prettier-ignore 71 | export function validateProblem(problem: {}): Joi.ValidationResult { 72 | const schema = Joi.object({ 73 | description: Joi.object({ 74 | title: Joi.string().required(), 75 | statement: Joi.string().required(), 76 | inputSpecification: Joi.string().required(), 77 | outputSpecification: Joi.string().required(), 78 | samples: Joi.string().required(), 79 | timeLimit: Joi.string().required(), 80 | memoryLimit: Joi.string().required(), 81 | note: Joi.string().required(), 82 | }), judge: Joi.object({ 83 | type: Joi.string().allow(...enumToArray(JudgeType)).required(), 84 | tests: Joi.array().items(Joi.object({ 85 | input: Joi.string().required(), 86 | output: Joi.string().required() 87 | })), 88 | cfID: Joi.string() 89 | }) 90 | }) 91 | return schema.validate(problem); 92 | } 93 | -------------------------------------------------------------------------------- /src/models/submission.ts: -------------------------------------------------------------------------------- 1 | import mongoose, {PaginateModel} from 'mongoose'; 2 | import Joi from '@hapi/joi'; 3 | import mongoosePaginate from 'mongoose-paginate-v2'; 4 | import {IProblem} from './problem'; 5 | import {IUser} from './user'; 6 | import {IContest} from './contest'; 7 | 8 | export enum Verdict { 9 | PENDING, 10 | ACCEPTED = 3, 11 | WRONG_ANSWER, 12 | TIME_LIMIT_EXCEEDED, 13 | COMPILATION_ERROR, 14 | RUNTIME_ERROR, 15 | MEMORY_LIMIT_EXCEEDED, 16 | JUDGE_ERROR = 13, 17 | } 18 | 19 | export type judgeSubmissionID = string; 20 | 21 | export interface ISubmission extends mongoose.Document { 22 | createdAt: string; 23 | updatedAt: string; 24 | contest: IContest; 25 | problem: IProblem; 26 | user: IUser; 27 | isDuringContest: boolean; 28 | isJudged: boolean; 29 | judgeSubmissionID: judgeSubmissionID; 30 | sourceCode: string; 31 | verdict: string; 32 | time: number; 33 | memory: number; 34 | languageID: number; 35 | } 36 | 37 | const submissionSchema = new mongoose.Schema( 38 | { 39 | contest: { 40 | type: mongoose.Types.ObjectId, 41 | ref: 'Contest', 42 | required: true, 43 | }, 44 | problem: { 45 | type: mongoose.Types.ObjectId, 46 | ref: 'Problem', 47 | required: true, 48 | }, 49 | user: { 50 | type: mongoose.Types.ObjectId, 51 | ref: 'User', 52 | required: true, 53 | }, 54 | isDuringContest: { 55 | type: Boolean, 56 | default: false, 57 | }, 58 | isJudged: { 59 | type: Boolean, 60 | required: true, 61 | default: false, 62 | }, 63 | judgeSubmissionID: { 64 | type: String, 65 | }, 66 | sourceCode: { 67 | type: String, 68 | required: true, 69 | }, 70 | verdict: { 71 | type: String, 72 | default: Verdict[Verdict.PENDING], 73 | // enum: enumToArray(Verdict) 74 | }, 75 | time: { 76 | type: Number, 77 | default: 0, 78 | }, 79 | languageID: { 80 | type: Number, 81 | required: true, 82 | }, 83 | memory: { 84 | type: Number, 85 | default: 0, 86 | }, 87 | }, 88 | { 89 | timestamps: true, 90 | }, 91 | ); 92 | 93 | submissionSchema.plugin(mongoosePaginate); 94 | 95 | export const Submission = mongoose.model( 96 | 'Submission', 97 | submissionSchema, 98 | ) as PaginateModel; 99 | 100 | // prettier-ignore 101 | export function validateSubmission(submission: {}): Joi.ValidationResult { 102 | const schema = Joi.object({ 103 | user: Joi.any(), 104 | problem: Joi.string().required().min(1), 105 | contest: Joi.string().min(1), 106 | languageID: Joi.number().required().min(1), 107 | sourceCode: Joi.string().required().min(1) 108 | }); 109 | return schema.validate(submission); 110 | } 111 | -------------------------------------------------------------------------------- /src/lib/judge/BaseJudge.ts: -------------------------------------------------------------------------------- 1 | import {IContest} from '../../models/contest'; 2 | import {IUser} from '../../models/user'; 3 | import {IProblem} from '../../models/problem'; 4 | import {ISubmission, Submission} from '../../models/submission'; 5 | import {Standing, IStanding} from '../../models/standing'; 6 | 7 | export class BaseJudge { 8 | readonly WRONG_ANSWER_PENALITY = 20; 9 | protected contest: IContest; 10 | protected user: IUser; 11 | protected problem: IProblem; 12 | 13 | constructor(protected submission: ISubmission) { 14 | ({ 15 | contest: this.contest, 16 | user: this.user, 17 | problem: this.problem, 18 | } = submission); 19 | this.init(); 20 | } 21 | 22 | private async init(): Promise { 23 | // problem: un-finished submissions don't get updated 24 | // push the submissions to the queue if isStillJudging 25 | // the queue should update the problem verdict every 5 seconds 26 | // the queue should remove the finished and judged submissions 27 | if (this.isDuringContest()) { 28 | const standing = await this.getUserStanding(); 29 | const problem = standing.problems.find(({problem}) => 30 | problem._id.equals(this.problem._id), 31 | ); // find current submitted problem 32 | 33 | if (!problem) { 34 | throw new Error('problem id not found '); 35 | } 36 | // add submission to the standing 37 | problem.submissions.push(this.submission); 38 | await standing.save(); 39 | } 40 | } 41 | 42 | /** 43 | * Returns standing if found for user, creates one otherwise 44 | */ 45 | async getUserStanding(): Promise { 46 | return ( 47 | (await Standing.findOne({ 48 | user: this.user, 49 | contest: this.contest, 50 | })) || 51 | (await new Standing({ 52 | user: this.user, 53 | contest: this.contest, 54 | problems: this.contest.problems.map((problem) => { 55 | return {problem}; 56 | }), 57 | }).save()) 58 | ); 59 | } 60 | 61 | static contestStarted(contest: IContest): boolean { 62 | const start = new Date(contest.startDate); 63 | return new Date() > start; 64 | } 65 | 66 | isDuringContest(): boolean { 67 | const start = new Date(this.contest.startDate); 68 | const end = new Date(); 69 | end.setTime(start.getTime() + this.contest.duration * 60 * 1000); 70 | return new Date() < end && BaseJudge.contestStarted(this.contest); 71 | } 72 | 73 | async isFirstAccepted(): Promise { 74 | // get first submission in the contest for this problem 75 | // bring the first accepted submission if any 76 | const previousAcceptedSubmission = await Submission.exists({ 77 | contest: this.submission.contest, 78 | problem: this.submission.problem, 79 | verdict: 'Accepted', 80 | createdAt: {$lt: this.submission.createdAt}, 81 | }); 82 | return !previousAcceptedSubmission; 83 | } 84 | 85 | calculateAcceptedPenality(): number { 86 | return new Date().getTime() - new Date(this.contest.startDate).getTime(); 87 | } 88 | } 89 | --------------------------------------------------------------------------------