e07e2432eb5ab901d0428069270a7d3c14012fcc
[qomet.git] / courses.js
1 let router = require("express").Router();
2 const access = require("../utils/access.js");
3 const validator = require("../public/javascripts/utils/validation");
4 const sanitizeHtml = require('sanitize-html');
5 const ObjectId = require("bson-objectid");
6 const CourseEntity = require("../entities/course");
7 const CourseModel = require("../models/course");
8
9 router.get('/add/course', access.ajax, access.logged, (req,res) => {
10 let code = req.query["code"];
11 let description = sanitizeHtml(req.query["description"]);
12 let error = validator({code:code}, "Course");
13 if (error.length > 0)
14 return res.json({errmsg:error});
15 CourseEntity.insert(req.user._id, code, description, (err,course) => {
16 access.checkRequest(res, err, course, "Course addition failed", () => {
17 res.json(course);
18 });
19 });
20 });
21
22 router.get("/set/password", access.ajax, access.logged, (req,res) => {
23 let cid = req.query["cid"];
24 let pwd = req.query["pwd"];
25 let error = validator({password:pwd, _id:cid}, "Course");
26 if (error.length > 0)
27 return res.json({errmsg:error});
28 CourseModel.setPassword(req.user._id, ObjectId(cid), pwd, (err,ret) => {
29 access.checkRequest(res, err, ret, "password update failed", () => {
30 res.json({});
31 });
32 });
33 });
34
35 router.post('/import/students', access.ajax, access.logged, (req,res) => {
36 let cid = req.body["cid"];
37 let students = JSON.parse(req.body["students"]);
38 let error = validator({_id:cid, students: students}, "Course");
39 if (error.length > 0)
40 return res.json({errmsg:error});
41 access.getUser(req, res, (err,user) => {
42 if (!!err)
43 return res.json(err);
44 CourseModel.importStudents(req.user._id, ObjectId(cid), students, (err,ret) => {
45 access.checkRequest(res, err, ret, "Students addition failed", () => {
46 res.json({});
47 });
48 });
49 });
50 });
51
52 router.get('/get/student', access.ajax, (req,res) => {
53 let number = req.query["number"];
54 let cid = req.query["cid"];
55 let error = validator({ _id: cid, students: [{number:number}] }, "Course");
56 if (error.length > 0)
57 return res.json({errmsg:error});
58 CourseEntity.getStudent(ObjectId(cid), number, (err,ret) => {
59 access.checkRequest(res, err, ret, "Failed retrieving student", () => {
60 res.json({student: ret.students[0]});
61 });
62 });
63 });
64
65 router.get('/remove/course', access.ajax, access.logged, (req,res) => {
66 let cid = req.query["cid"];
67 let error = validator({_id:cid}, "Course");
68 if (error.length > 0)
69 return res.json({errmsg:error});
70 CourseModel.remove(req.user._id, ObjectId(cid), (err,ret) => {
71 access.checkRequest(res, err, ret, "Course removal failed", () => {
72 res.json({});
73 });
74 });
75 });
76
77 // TODO: grading page (for at least partially open-questions exams)
78
79 module.exports = router;