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