aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authornanalelfe <nargiza.nosirova@mail.utoronto.ca>2016-07-22 02:45:27 +0000
committernanalelfe <nargiza.nosirova@mail.utoronto.ca>2016-07-22 02:45:27 +0000
commit12659ff5704a04d2447f5dbf036541676c59f139 (patch)
tree68a36260059bb05bb9d589011bf9d8ca22f72b2f
parentdc3888553bdda4ee30e6440992459916cec8d911 (diff)
parent797b4fe83ed4ebbed47930c7d0d0a34cd37703c6 (diff)
Added passport for signup
-rw-r--r--config/passport.js89
-rw-r--r--node_simple.js645
-rw-r--r--routes/index.js141
-rw-r--r--testImports.js58
-rw-r--r--views/admin.hbs69
-rw-r--r--views/exams.hbs2
-rw-r--r--views/index.hbs20
-rw-r--r--views/partials/header.hbs1
-rw-r--r--views/questions.hbs68
-rw-r--r--views/signup.hbs29
10 files changed, 734 insertions, 388 deletions
diff --git a/config/passport.js b/config/passport.js
index 9131abe..576f088 100644
--- a/config/passport.js
+++ b/config/passport.js
@@ -2,7 +2,17 @@
* Created by nanalelfe on 2016-07-20.
*/
var passport = require('passport');
+var dbFile = require("../node_simple.js");
var LocalStrategy = require('passport-local').Strategy;
+var bcrypt = require('bcrypt-nodejs');
+
+var encryptPassword = function (password) {
+ return bcrypt.hashSync(password, bcrypt.genSaltSync(5), null);
+}
+
+var comparePassword = function (password) {
+ return bcrypt.compareSync(password1, password2);
+}
passport.serializeUser(function (user, done) {
done(null, user.id);
@@ -12,13 +22,82 @@ passport.deserializeUser(function(id, done) {
done(err, user);
});
-passport.use('local.signup', new LocalStrategy({
- usernameField: 'username',
+
+// fields - [email, user_name, f_name, l_name, uni, department, password, phone_num]
+
+passport.use('local_signup', new LocalStrategy({
+ usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
-}, function(req, username, password, done){
+}, function(req, email, password, done){
+ req.check('email', 'Invalid email address').notEmpty().isEmail();
+ req.check('password', "Password is invalid").notEmpty().isLength({min: 6}).equals(req.body.confirmPassword);
+ // password has to be at least 4 characters long
+
+ var errors = req.validationErrors();
+ console.log("IN PASSPORT");
+ if (errors) {
+ var messages = [];
+ errors.forEach(function (error) {
+ messages.push(error.msg);
+ });
+ return done(null, false, req.flash('error', messages));
+ }
+ var hash_pass = encryptPassword(password);
+
+ var fields = [email, req.body.usrname, req.body.fname, req.body.lname, req.body.univ, req.body.dept, hash_pass,
+ req.body.phone_num];
+
+ dbFile.add_user(fields, function (success, error, message) {
+
+ if (!success && error) {
+ console.log("!success && error");
+ return done(message);
+ }
+
+ else if (!success && !error) {
+ console.log("!success && !error");
+ console.log(message);
+ return done(null, false, {message: message});
+ }
+
+ else {
+ console.log("ELSE");
+ return done(null, fields);
+ }
+ });
+
// Check if username already in use
// If not, create new user with given info
// Encrypt the passport using bcrypt
- return done(null, false, {message: "username already in use"});
-})); \ No newline at end of file
+}));
+
+/*router.post('/signup', function(req, res, next) {
+ req.check('email', 'Invalid email address').isEmail();
+ req.check('password', "Password is invalid").isLength({min: 4}).equals(req.body.confirmPassword);
+ // password has to be at least 4 characters long
+
+ var errors = req.validationErrors();
+ if (errors) {
+ req.session.errors = errors;
+ req.session.success = false;
+ console.log("got here");
+ res.redirect('/signup');
+ } else {
+ req.session.success = true;
+ console.log("GOT SUCCESS");
+ passport.authenticate('local_signup', {
+ successRedirect: '/user_profile',
+ failureRedirect: '/signup',
+ failureFlash: true
+ });
+ }
+ //res.redirect('/signup');
+
+ });*/
+
+/*router.post('/signup', passport.authenticate('local.signup', {
+ sucessRedirect: '/profile',
+ failureRedirect: '/signup',
+ failureFlash: true
+ }));*/
diff --git a/node_simple.js b/node_simple.js
index 5f91c0e..1c34590 100644
--- a/node_simple.js
+++ b/node_simple.js
@@ -1,27 +1,30 @@
// a simple node driver to interact with mongo database
/* TO DO:
-* 1. get all exams given course code -- order by year desc ? DONE
-* 1B. get the title of the course ? DONE
-* 2. add upload date and user name ? DONE
-* 3. remove exam ? DONE
-* 4a. get all questions for a given exam_id ? PENDING
-* 4b. add exam id to each question returned. ? PENDING
-* 6. get all solutions provided question_id and exam_id ? PENDING
-* 5. answers ? CURRENTLY WORKING ON -- need to add field for solutions provider, and updating.
-* 7. ....TBD
-* */
+ * 1. get all exams given course code -- order by year desc ? DONE
+ * 1B. get the title of the course ? DONE
+ * 2. add upload date and user name ? DONE
+ * 3. remove exam ? DONE
+ * 4a. get all questions for a given exam_id ? DONE
+ * 4b. add exam id to each question returned. ? PENDING
+ * 6. get all solutions provided question_id and exam_id ? DONE
+ * 5. solutions ? CURRENTLY WORKING ON -- need to add field for solutions provider, and updating.
+ * 7. add university field to courses, exams ? PENDING
+ * 8. make a user ? DONE
+ * 9.
+ * */
/* I pass in exam id and you give me the number of questions and the comments and solutions associated with each question?*/
/* Tables SO FAR:
-* 1. exams
-* 2. courses
-* 3. solutions
-* 4.
-*
-* */
+ * 1. exams
+ * 2. courses
+ * 3. solutions
+ * 4. users
+ * 5. logins
+ *
+ * */
/*Tables schema SO FAR:*/
// |======================================================exams==================================================================================|
@@ -44,6 +47,18 @@
// |"354ff71ed078933079d6467e"|"578a44ff71ed097fc3079d6e" |1 |"answer"| 1 |[{},{}] |
// |..........|
+// |========================================users===============================================================================|
+// |_______ _id_________|email_________|user_name__|f_name__|l_name__|uni___|departm.|answered|messeges|comments|phone|followers|
+// |====================|==============|===========|========|========|======|========|========|========|========|=====|=========|
+// |"3.....efsdfsdf...."|blah@blah.com |"some_user"|"f.name"|"l.name"|"uofT"|CS |40 |30 |15 |() - |[{},{}] |
+// |..........|
+
+// |====================================login===================================|
+// |_________ _id_____________|email____________|user_name|pass_________________|
+// |==========================|=================|=========|=====================|
+// |"askjdfklajsdf..........."|"asdf@asdf.com |"asdfasd"|(some hasehd thing) |
+// |..........|
+
var exports = module.exports = {};
const debug_mode = false;
@@ -55,8 +70,10 @@ var ObjectId = require('mongodb').ObjectID;
var assert = require('assert');
// Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname
-//var uri = 'mongodb://general:assignment4@ds057862.mlab.com:57862/solutions_repo';
-var uri = 'mongodb://localhost:27017/db';
+var uri = 'mongodb://general:assignment4@ds057862.mlab.com:57862/solutions_repo';
+
+// Keep this for testing on local machine, do not remove. - Humair
+//var uri = 'mongodb://localhost:27017/db';
//***********************PRELIMINARY TESTING******************************************|
@@ -67,6 +84,137 @@ var uri = 'mongodb://localhost:27017/db';
+/*
+ * This function creates and adds a user to users table.
+ * IFF both the email and the user_name are not in the database already.
+ * If either of them exist, the user is NOT added.
+ * Params: fields - [email, user_name, f_name, l_name, uni, department, password, phone_num]
+ * */
+exports.add_user = function (fields, callbackUser) {
+ console.log("inside add_user");
+ // create a user object
+ var user_data = {
+ email: fields[0],
+ user_name: fields[1],
+ f_name: fields[2],
+ l_name: fields[3],
+ university: fields[4],
+ department: fields[5],
+ answered: 0,
+ messages: 0,
+ comments: 0,
+ phone_num: fields[7],
+ followers: []
+ };
+
+ var login_data = {
+ email: fields[0],
+ user_name: fields[1],
+ password: fields[6]
+ };
+
+ // find out if this user already exists by checking their email
+ exports.find_user( fields[0] ,callbackUser, function (result) {
+ console.log("inside find_user");
+ if (result == false) {
+ console.log("no such user found");
+
+ // find out if the user_name is taken
+ exports.find_user_name( fields[1], callbackUser, function (docs) {
+ if (docs == false) { // if not ...
+ // continue
+ console.log("user name is valid");
+
+ // when both are valid add the user to the users and logins table
+ mongoFactory.getConnection(uri)
+ .then(function (db) {
+
+ var users = db.collection('users');
+ var logins = db.collection('logins');
+
+ users.insertOne( user_data, function (err) {
+ if (err) callbackUser(false, true, "Unable to add user.");
+ else {
+ console.log("user has been added to users");
+ callbackUser(true, false, "User has been added.");
+ }
+ });
+
+ logins.insertOne( login_data, function (err) {
+ if (err) callbackUser(false, true, "Login has not been added.");
+ else{
+ callbackUser(true, false, "Login added.");
+ }
+ });
+
+ db.close();
+ })
+ .catch(function (err) {
+ callbackUser(false, true, "Unable to connect.");
+ })
+ }
+ else {
+ callbackUser(false, false, "Username is taken.");
+ }
+ });
+ }
+ else {
+ callbackUser(false, false, "User with this email already exists.");
+ }
+ });
+};
+
+/*
+ * This (helper) function returns true IFF user_name already exists in the database
+ * Params: user_name - the user name
+ * */
+exports.find_user_name = function (user_name, callbackUser, callback) {
+ // make a connection
+ mongoFactory.getConnection(uri)
+ .then(function (db) {
+
+ var logins = db.collection('logins');
+ logins.find( { user_name: user_name } ).toArray(function (err, result) {
+ if (err) throw err;
+ else if (result.length == 0) { // nothing was found so this user is new
+ callback(false);
+ }
+ else {
+ callback(true);
+ }
+ });
+ // db.close();
+ })
+ .catch(function (err) {
+ console.err(err);
+ })
+};
+
+/*
+ * This (helper) function returns true IFF email already exists in the database
+ * */
+exports.find_user = function (email, callbackUser, callback) {
+ // make a connection
+ mongoFactory.getConnection(uri)
+ .then(function (db) {
+
+ var logins = db.collection('logins');
+ logins.find( { email: email } ).toArray(function (err, result) {
+ if (err) throw err;
+ else if (result.length == 0) { // nothing was found so this user is new
+ callback(false, callbackUser);
+ }
+ else {
+ callback(true, callbackUser);
+ }
+ });
+ // db.close();
+ })
+ .catch(function (err) {
+ console.err(err);
+ })
+};
+
// this function returns an array where is element contains info for a particular question
// such as the question number (_id), number of solutions (count), and number of comments
@@ -102,7 +250,7 @@ exports.get_exam_info_by_ID = function (exam_id, callback) {
}
- ]).toArray(function (err, result) {
+ ]).toArray(function (err, result) {
// console.log(result);
callback(result);
@@ -112,15 +260,19 @@ exports.get_exam_info_by_ID = function (exam_id, callback) {
console.err(err);
})
-}
-
+};
+/*
+ * This function will add a comment to the solutions table
+ * Params: sol_id - id of the solution to which to add the comment
+ * fields - [text, by]
+ * */
exports.add_comment = function (sol_id, fields) {
var Data = {
text: fields[0],
- date: fields[1],
- by: fields[2]
+ date: new Date(),
+ by: fields[1]
};
mongoFactory.getConnection(uri)
@@ -140,7 +292,9 @@ exports.add_comment = function (sol_id, fields) {
.catch(function (err) {
console.error(err);
})
-}
+};
+
+
// get all solutions given an exam_id and the question number
exports.get_all_solutions = function (exam_id, q_num, callback) {
@@ -166,11 +320,11 @@ exports.get_all_solutions = function (exam_id, q_num, callback) {
})
.catch(function () {
- console.error(err);
+ console.error(err);
})
-}
+};
/*
* This function will add a solution to the solutions table in the database .
@@ -209,7 +363,7 @@ exports.add_solution = function (fields) {
console.error(err);
});
-}
+};
@@ -220,174 +374,180 @@ exports.add_solution = function (fields) {
* */
exports.get_all_exams = function (course_code, callback) {
- // get a connection
- mongoFactory.getConnection(uri)
- .then(function(db) {
+ // get a connection
+ mongoFactory.getConnection(uri)
+ .then(function(db) {
- // get the exams table
- var exam_collection = db.collection('exams');
+ // get the exams table
+ var exam_collection = db.collection('exams');
- // search exams table with given course code
- exam_collection.find(
- { course_code: course_code }
- ).sort({ year: -1}).toArray( function (err, docs) { // order by year
- if (err) throw err;
+ // search exams table with given course code
+ exam_collection.find(
+ { course_code: course_code }
+ ).sort({ year: -1}).toArray( function (err, docs) { // order by year
+ if (err) throw err;
- else { // get the title
- exports.find_course(course_code, function (result, data) {
+ else { // get the title
+ exports.find_course(course_code, function (result, data) {
- if (result == true) {
- // append the title from data to each exam object from docs
- docs.forEach(function (doc) {
- doc.title = data[0].title;
- });
+ if (result == true) {
+ // append the title from data to each exam object from docs
+ docs.forEach(function (doc) {
+ doc.title = data[0].title;
+ });
- if (debug_mode == true){
- console.log(docs);
- console.log(data);
- }
- /*callback(docs); // send back the data*/
- }
- else if (result == false) { // no such course was found
- console.log("This course has not been added to the database.");
- }
- callback(docs); // send back the data
+ if (debug_mode == true){
+ console.log(docs);
+ console.log(data);
+ }
+ /*callback(docs); // send back the data*/
+ }
+ else if (result == false) { // no such course was found
+ console.log("This course has not been added to the database.");
+ }
+ callback(docs); // send back the data
+ });
+ }
});
- }
+ })
+ .catch(function(err) {
+ console.error(err);
});
- })
- .catch(function(err) {
- console.error(err);
- });
-
-}
-
+};
/*
-* This function will add an exam to the database UNLESS the exams already exists.
-* If the exams table is empty, this will create one and then add the data.
-* Note: this assumes that (course_code + year + term + type) together form a unique exam.
-* i.e there can't be two exams occurring for the same course in the same year in the same term with the same type.
-* Params: fields - an array of format ["course_code", year, "term",
-* ["instructor1",...,"instructor n"], page_count, question_count
-* "upload_date", "user_name"]
-* questions_array - a array by format ["q_1", "q_2", ... , "q_question_count"]
-* */
-exports.add_exam = function (fields, questions_array) {
-
- // construct an exam object
- var Data =
- {
- course_code: fields[0],
- year: fields[1],
- term: fields[2],
- type: fields[3],
- instructors: fields[4],
- page_count: fields[5],
- questions_count: fields[6],
- questions_list: [],
- upload_date: fields[7],
- uploaded_by: fields[8]
- };
-
- // create the questions objects
- for (var i = 1; i <= Data.questions_count; i++) {
- Data.questions_list.push(
- {
- q_id: i,
- question: questions_array[i - 1]
- }
- );
- }
-
- // first see if the exam already exists
- // pass in course_code, year, term and type...
- exports.find_exam([fields[0], fields[1], fields[2], fields[3]], function(result) {
+ * This function will add an exam to the database UNLESS the exams already exists.
+ * If the exams table is empty, this will create one and then add the data.
+ * Note: this assumes that (course_code + year + term + type) together form a unique exam.
+ * i.e there can't be two exams occurring for the same course in the same year in the same term with the same type.
+ * Params: fields - an array of format ["course_code", year, "term",
+ * ["instructor1",...,"instructor n"], page_count, question_count
+ * "upload_date", "user_name"]
+ * questions_array - a array by format ["q_1", "q_2", ... , "q_question_count"]
+ *
+ * callback parameter takes a boolean to indicate whether insert was successful
+ * and an output status message.*/
+exports.add_exam = function (fields, questions_array, serverCallback) {
+
+ // construct an exam object
+ var Data =
+ {
+ course_code: fields[0],
+ year: fields[1],
+ term: fields[2],
+ type: fields[3],
+ instructors: fields[4],
+ page_count: fields[5],
+ questions_count: fields[6],
+ questions_list: [],
+ upload_date: fields[7],
+ uploaded_by: fields[8]
+ };
- if (result == true) { // meaning that the exam was found
- console.log("This exam already exists in the database");
+ // create the questions objects
+ for (var i = 1; i <= Data.questions_count; i++) {
+ Data.questions_list.push(
+ {
+ q_id: i,
+ question: questions_array[i - 1]
+ }
+ );
}
- else { // add Data to the database
- // make a connection
- mongoFactory.getConnection(uri)
- .then(function(db) {
+ // first see if the exam already exists
+ // pass in course_code, year, term and type...
+ exports.find_exam([fields[0], fields[1], fields[2], fields[3]], serverCallback, function(result, serverCallback) {
- // find the exams table
- var exam_collection = db.collection('exams');
- // insert data into table
- exam_collection.insert(Data, function(err) {
- if (err) throw err;
- else {
- console.log("exam added");
- db.close(function (err) { // close the connection when done
- if (err) throw err;
+ if (result == true) { // meaning that the exam was found
+ serverCallback(false, "This exam already exists in the database.");
+ console.log("This exam already exists in the database");
+ }
+
+ else { // add Data to the database
+ // make a connection
+ mongoFactory.getConnection(uri)
+ .then(function(db) {
+
+ // find the exams table
+ var exam_collection = db.collection('exams');
+ // insert data into table
+ exam_collection.insert(Data, function(err) {
+ if (err) {
+ serverCallback(false, "Error: Could not add exam into database.");
+ throw err;
+ }
+ else {
+ console.log("exam added");
+ serverCallback(true, "Exam Successfully added.");
+ db.close(function (err) { // close the connection when done
+ if (err) throw err;
+ });
+ }
+ });
+ })
+ .catch(function(err) {
+ serverCallback(false, "Error: Could not establish connection with database.");
+ console.error(err);
});
- }
- });
- })
- .catch(function(err) {
- console.error(err);
- });
- }
- });
-}
+ }
+ });
+};
/*
-* This function will return TRUE if the provided exam info already exists in the database
-* OR FALSE if it does not exist in the database.
-* Params: fields - an array of format ["course_code", year, "term", "type"]
-*
-* */
-exports.find_exam = function (fields, callback) {
-
- var course_code = fields[0];
- var year = fields[1];
- var term = fields[2];
- var type = fields[3];
-
- // console.log(Data);
-
- // check the data to see if this exam exists...
-
- // first make a connection
- mongoFactory.getConnection(uri)
- .then(function(db) {
-
- // fetch the exams table
- var exams = db.collection('exams');
-
- // look for the exam
- exams.find(
- {
- course_code: course_code,
- year: year,
- term: term,
- type: type
- }
- ).toArray(function (err, docs) {
- if (err) throw err;
-
- if (docs.length == 0) { // if this exam doesnt exist.... add it
- callback(false);
- }
- else { // exam was found
- callback(true);
- }
- });
+ * This function will return TRUE if the provided exam info already exists in the database
+ * OR FALSE if it does not exist in the database.
+ * Params: fields - an array of format ["course_code", year, "term", "type"]
+ *
+ * */
+exports.find_exam = function (fields, serverCallback, callback) {
+
+ var course_code = fields[0];
+ var year = fields[1];
+ var term = fields[2];
+ var type = fields[3];
-/* db.close(function (err) {
- if (err) throw err;
- });*/
+ // console.log(Data);
- })
- .catch(function(err) {
- console.error(err);
- });
-}
+ // check the data to see if this exam exists...
+
+ // first make a connection
+ mongoFactory.getConnection(uri)
+ .then(function(db) {
+
+ // fetch the exams table
+ var exams = db.collection('exams');
+
+ // look for the exam
+ exams.find(
+ {
+ course_code: course_code,
+ year: year,
+ term: term,
+ type: type
+ }
+ ).toArray(function (err, docs) {
+ if (err) throw err;
+
+ if (docs.length == 0) { // if this exam doesnt exist.... add it
+ callback(false, serverCallback);
+ }
+ else { // exam was found
+ callback(true, serverCallback);
+ }
+ });
+
+ /* db.close(function (err) {
+ if (err) throw err;
+ });*/
+
+ })
+ .catch(function(err) {
+ console.error(err);
+ });
+};
/*
@@ -399,39 +559,39 @@ exports.find_exam = function (fields, callback) {
* */
exports.add_course = function (course_code, title) {
- var courseData = {
- course_code: course_code,
- title: title
- };
-
- exports.find_course(course_code, function (result) {
+ var courseData = {
+ course_code: course_code,
+ title: title
+ };
- if (result == true){
- console.log("course already exists");
- }
- else if (result == false) { // add it
- mongoFactory.getConnection(uri)
- .then(function(db) {
+ exports.find_course(course_code, function (result) {
- // find the exams table
- var courses = db.collection('courses');
- // insert data into table
- courses.insert(courseData, function(err) {
- if (err) throw err;
- else {
- console.log("couse added");
- db.close(function (err) { // close the connection when done
- if (err) throw err;
+ if (result == true){
+ console.log("course already exists");
+ }
+ else if (result == false) { // add it
+ mongoFactory.getConnection(uri)
+ .then(function(db) {
+
+ // find the exams table
+ var courses = db.collection('courses');
+ // insert data into table
+ courses.insert(courseData, function(err) {
+ if (err) throw err;
+ else {
+ console.log("couse added");
+ db.close(function (err) { // close the connection when done
+ if (err) throw err;
+ });
+ }
+ });
+ })
+ .catch(function(err) {
+ console.error(err);
});
- }
- });
- })
- .catch(function(err) {
- console.error(err);
- });
- }
- });
-}
+ }
+ });
+};
/*
@@ -441,38 +601,38 @@ exports.add_course = function (course_code, title) {
*
* */
exports.find_course = function (course_code, callback) {
- // check the data to see if this exam exists...
-
- // first make a connection
- mongoFactory.getConnection(uri)
- .then(function(db) {
-
- // fetch the courses table
- var courses = db.collection('courses');
-
- // look for the courses
- courses.find(
- { course_code: course_code }
- ).toArray(function (err, docs) {
- if (err) throw err;
-
- if (docs.length == 0) { // if this course doesnt exist.... add it
- callback(false);
- }
- else { // course was found
- callback(true, docs);
- }
- });
+ // check the data to see if this exam exists...
+
+ // first make a connection
+ mongoFactory.getConnection(uri)
+ .then(function(db) {
-/* db.close(function (err) {
- if (err) throw err;
- });*/
+ // fetch the courses table
+ var courses = db.collection('courses');
+
+ // look for the courses
+ courses.find(
+ { course_code: course_code }
+ ).toArray(function (err, docs) {
+ if (err) throw err;
+
+ if (docs.length == 0) { // if this course doesnt exist.... add it
+ callback(false);
+ }
+ else { // course was found
+ callback(true, docs);
+ }
+ });
+
+ /* db.close(function (err) {
+ if (err) throw err;
+ });*/
- })
- .catch(function(err) {
- console.error(err);
- });
-}
+ })
+ .catch(function(err) {
+ console.error(err);
+ });
+};
/*
@@ -517,7 +677,7 @@ exports.remove_exam = function (fields) {
.catch(function(err) {
console.error(err);
});
-}
+};
//get_exam_byID("578a44ff71ed097fc3079d6e");
@@ -542,15 +702,13 @@ exports.get_exam_byID = function (id) {
.catch(function(err) {
console.error(err);
});
-}
+};
-/* IGNORE BELOW *********************************************************************************
-
- /*
+/*
* userObj = {fs: fs, ls: ls, email: email, username: username, pass_hash: pass_hash, univ: univ, dept: dept}
*
- * */
+ *
exports.addUser = function (userObj) {
mongoFactory.getConnection(uri)
.then(function(db) {
@@ -561,12 +719,13 @@ exports.addUser = function (userObj) {
});
});
-}
+} */
+
-exports.findUser = function ()
+/* IGNORE BELOW *********************************************************************************
+
-ONLY FOR SYNTAX REFERENCE
/!*
* Then we need to give Boyz II Men credit for their contribution
diff --git a/routes/index.js b/routes/index.js
index c96af41..b998f11 100644
--- a/routes/index.js
+++ b/routes/index.js
@@ -34,23 +34,62 @@ router.get('/questions', function(req, res, next) {
res.render('questions');
});
-/* Render/GET exam page */
-/* Render/GET exam page */
+router.get('/admin', function(req,res){
+ res.render('admin', {csrfToken: req.csrfToken()});
+});
+
+
+router.post('/admin/update', function(req,res){
+ var course_code = req.body.course_code,
+ year = req.body.year,
+ type = req.body.type,
+ term = req.body.term,
+ instructors = parseStringArray(req.body.instructors),
+ page_count = req.body.page_count,
+ questions_count = req.body.questions_count,
+ questions_list = parseStringArray(req.body.questions_list),
+ upload_date = req.body.upload_date,
+ uploaded_by = req.body.uploaded_by;
+
+ var fields = [
+ course_code, // String
+ year, // Int
+ type, // String; Needs to be added to database code
+ term, // String
+ instructors, // Array of strings
+ page_count, // Int
+ questions_count, // Int
+ upload_date, // String
+ uploaded_by]; // String
+
+ dbFile.add_exam(fields, questions_list, function(examAdded, statusMessage){
+ if(examAdded){
+ console.log("Success!");
+ }else{
+ console.log("Failed!");
+ }
+ console.log(statusMessage);
+ });
+ res.redirect('/admin');
+});
+
+
//EXAMPLE EXPECTED DATA GIVEN BELOW:
-/*[ { courseCode: 'CSC240',
- year: 2016,
- term: 'Fall',
- instructors: [ 'Faith Ellen', 'Tom F.' ],
- type: 'Midterm Examination',
- title: 'Thry of Computation' },
- { courseCode: 'CSC240',
- year: 2014,
- term: 'Fall',
- instructors: [ 'Faith Ellen', 'Tom F.' ],
- type: 'Midterm Examination',
- title: 'Thry of Computation' } ]
- */
+/*[ {courseCode: 'CSC240',
+ year: 2016,
+ term: 'Fall',
+ instructors: ['Faith Ellen', 'Tom F.'],
+ type: 'Midterm Examination',
+ title: 'Thry of Computation' },
+
+ {courseCode: 'CSC240',
+ year: 2014,
+ term: 'Fall',
+ instructors: ['Faith Ellen', 'Tom F.'],
+ type: 'Midterm Examination',
+ title: 'Thry of Computation' } ]
+ */
router.get('/exams/:id', function(req, res, next) {
var minExamInfoArray = [];
dbFile.get_all_exams(req.params.id, function (exams) {
@@ -61,6 +100,7 @@ router.get('/exams/:id', function(req, res, next) {
//console.log(exams);
//only pass over the information that is necessary for the exams page
for (var i = 0; i<exams.length;i++){
+
var getInstructors = exams[i].instructors.join(", ");
var minExamInfo = { courseCode:exams[i].course_code,
year:exams[i].year,
@@ -86,14 +126,6 @@ router.get('/search', function(req, res, next) {
res.redirect('/exams/' + courseName);
});
-
-/* REDIRECT - exam -> questions page*/
-router.get('/exam_click',function (req,res) {
- //TODO:get needs to have exam_id attached
- var examId = req.query.exam_id;
- res.redirect('/questions/'+examId);
-});
-
/*EXAMPLE DATA GIVEN BELOW:
* questions = [{id,count,comments},{id,count,comments}] --> array of "question" objects
*
@@ -101,9 +133,10 @@ router.get('/exam_click',function (req,res) {
* count= number of solutions
* comments = number of comments*/
router.get('/questions/:exam_id', function (req,res) {
+ console.log(req.params.exam_id);
dbFile.get_exam_info_by_ID(req.params.exam_id, function (questions) {
-
res.render('questions', {query: questions});
+ console.log(questions);
});
});
@@ -111,22 +144,36 @@ router.get('/signup', function(req, res, next) {
res.render('signup', {csrfToken: req.csrfToken(), success: req.session.success, errors: req.session.errors});
});
-router.post('/signup', function(req, res, next) {
+
+router.post('/signup', passport.authenticate('local_signup', {
+ successRedirect: '/user_profile',
+ failureRedirect: '/signup',
+ failureFlash: true
+}));
+
+/*router.post('/signup', function(req, res, next) {
req.check('email', 'Invalid email address').isEmail();
req.check('password', "Password is invalid").isLength({min: 4}).equals(req.body.confirmPassword);
// password has to be at least 4 characters long
var errors = req.validationErrors();
if (errors) {
- console.log(req);
req.session.errors = errors;
req.session.success = false;
+ console.log("got here");
+ res.redirect('/signup');
} else {
req.session.success = true;
+ console.log("GOT SUCCESS");
+ passport.authenticate('local_signup', {
+ successRedirect: '/user_profile',
+ failureRedirect: '/signup',
+ failureFlash: true
+ });
}
- res.redirect('/signup');
+ //res.redirect('/signup');
-});
+});*/
/*router.post('/signup', passport.authenticate('local.signup', {
sucessRedirect: '/profile',
@@ -134,21 +181,7 @@ router.post('/signup', function(req, res, next) {
failureFlash: true
}));*/
-
-/*
-app.get('/exams',function (req,res) {
- console.log(req.query.search);
- var courseName = req.query.search;
- res.redirect("http://localhost:3000/exams.html/?course_name="+courseName);
-});
-
-
-app.get('/exams.html', function (req,res) {
- /!*LOADS ALL THE STATIC FILES REALTIVE TO THE REDIRECTED URL*!/
- app.use('/exams.html', express.static(__dirname));
- res.sendFile(__dirname+'/exams.html');
-});*/
-
+/**** Helpers ****/
function getExamsForCourseCode(courseCode) {
dbFile.get_all_exams(courseCode, function (exams) {
@@ -161,9 +194,23 @@ function getExamsForCourseCode(courseCode) {
});
}
-
-module.exports = router;
-
function toProperCase(string) {
return string.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
-} \ No newline at end of file
+}
+
+
+/* Takes an input string delimited by commas, will split by comma and trim white
+ * spaces. Consider callback.
+ */
+function parseStringArray(input){
+ var list = input.split(',');
+ var parsedList = [];
+ list.forEach(function(word){
+ if (word != ""){
+ parsedList.push(word.trim());
+ }
+ });
+ return parsedList;
+}
+
+module.exports = router; \ No newline at end of file
diff --git a/testImports.js b/testImports.js
index c9f0bb2..7ce9e1c 100644
--- a/testImports.js
+++ b/testImports.js
@@ -18,13 +18,13 @@ var questions_array = ["this is q1", "this is q2"];
//test getting all exams database functionality -- USE FOR THE EXAMS PAGES maybe?
/*dbFile.get_all_exams("CSC240", function (exams) {
- if (exams.length == 0){
- console.log("Nothing was found");
- }
- else {
- console.log(exams);
- }
-});*/
+ if (exams.length == 0){
+ console.log("Nothing was found");
+ }
+ else {
+ console.log(exams);
+ }
+ });*/
//test adding course
// dbFile.add_course("CSC148", "Intro to Programming");
@@ -41,14 +41,38 @@ var questions_array = ["this is q1", "this is q2"];
//test adding of comments given a solution_id, and the comment information as an array
-// dbFile.add_comment("578f08e43bba452ee98da444", ["this is asdfasdf", "this is the date", "this is the author"]);
+//dbFile.add_comment("578f08e43bba452ee98da444", ["this is asdfasdf", "this is the author"]);
+
+
+/*
+ dbFile.get_exam_info_by_ID("578a44ff71ed097fc3079d6e", function (result) {
+ if (result.length == 0) {
+ console.log("some error occured");
+ }
+ else {
+ console.log(result);
+ }
+ });*/
+
+// dbFile.add_user(["some as email", "some_user names", "kumar", "damani", "uofT", "cs", "some hashed passwd"]);
+
+
+/*
+ dbFile.find_user("some Email", function (result) {
+ if (result == false) {
+ console.log("no such user found");
+ }
+ else {
+ console.log("user already exists");
+ }
+ });*/
+
+/* dbFile.find_user_name("some_user name", function (result) {
+ if (result == false) {
+ console.log("no such user_name found");
+ }
+ else {
+ console.log("user_name taken");
+ }
+ });*/
-
-dbFile.get_exam_info_by_ID("578a44ff71ed097fc3079d6e", function (result) {
- if (result.length == 0) {
- console.log("some error occured");
- }
- else {
- console.log(result);
- }
-}); \ No newline at end of file
diff --git a/views/admin.hbs b/views/admin.hbs
new file mode 100644
index 0000000..ecbd46e
--- /dev/null
+++ b/views/admin.hbs
@@ -0,0 +1,69 @@
+<main id="solutions-main">
+<div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3">
+<h4>Add Exam</h4>
+<form action="/admin/update" method="post">
+ <div class="form-group">
+ <input type="text"
+ class="form-control"
+ placeholder="course code"
+ name="course_code">
+ </div>
+ <div class="form-group">
+ <input type="text"
+ class="form-control"
+ placeholder="year"
+ name="year">
+ </div>
+ <div class="form-group">
+ <input type="text"
+ class="form-control"
+ placeholder="term"
+ name="term">
+ </div>
+ <div class="form-group">
+ <input type="text"
+ class="form-control"
+ placeholder="type"
+ name="type">
+ </div>
+ <div class="form-group">
+ <input type="text"
+ class="form-control"
+ placeholder="instructor1,instructor2,.."
+ name="instructors">
+ </div>
+ <div class="form-group">
+ <input type="text"
+ class="form-control"
+ placeholder="page count"
+ name="page_count">
+ </div>
+ <div class="form-group">
+ <input type="text"
+ class="form-control"
+ placeholder="questions count"
+ name="questions_count">
+ </div>
+ <div class="form-group">
+ <input type="text"
+ class="form-control"
+ placeholder="q1,q2,q3,.."
+ name="questions_list">
+ </div>
+ <div class="form-group">
+ <input type="text"
+ class="form-control"
+ placeholder="upload date"
+ name="upload_date">
+ </div>
+ <div class="form-group">
+ <input type="text"
+ class="form-control"
+ placeholder="uploader"
+ name="uploaded_by">
+ </div>
+ <input type="hidden" name="_csrf" value="{{ csrfToken }}">
+ <button type="submit" class="btn btn-primary">Submit</button>
+</form>
+</div>
+</main> \ No newline at end of file
diff --git a/views/exams.hbs b/views/exams.hbs
index 5a5955c..d7697c3 100644
--- a/views/exams.hbs
+++ b/views/exams.hbs
@@ -2,7 +2,7 @@
<div class = 'search container' id = 'solutions-div'>
<h4 class='search-head'>Search results for "{{query}}"</h4>
{{# each result}}
- <a href="/questions">
+ <a href="/questions/{{this.id}}">
<section class = 'solutions-card'>
<h3 class = 'solutions-title'>{{this.title}}</h3>
<p class = 'solutions-time' ><em>Term: </em>{{this.term}} {{this.year}}</p>
diff --git a/views/index.hbs b/views/index.hbs
index 9826209..59c589f 100644
--- a/views/index.hbs
+++ b/views/index.hbs
@@ -10,7 +10,14 @@
<div class="input-group">
<!-- Search Category Drop-Down -->
<div class="input-group-btn">
- <button type="button" class="btn btn-default dropdown-toggle search-button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Courses <span class="caret"></span></button>
+ <button type="button"
+ class="btn btn-default dropdown-toggle search-button"
+ data-toggle="dropdown"
+ aria-haspopup="true"
+ aria-expanded="false">
+ Courses
+ <span class="caret"></span>
+ </button>
<ul class="dropdown-menu">
<li><a href="#">Courses</a></li>
<li><a href="#">Users</a> </li>
@@ -18,10 +25,17 @@
</div>
<!-- Search bar -->
- <input type="text" id = "user-input" class="form-control" aria-label="..." name="search" placeholder="Enter course name">
+ <input type="text"
+ id = "user-input"
+ class="form-control"
+ aria-label="..."
+ name="search"
+ placeholder="Enter course name">
<!-- Prompt Search -->
<span class="input-group-btn">
- <button id = 'go-button' class="btn btn-default search-button go-button" type="submit">Go!</button>
+ <button id = 'go-button'
+ class="btn btn-default search-button go-button"
+ type="submit">Go!</button>
</span>
</div>
</div>
diff --git a/views/partials/header.hbs b/views/partials/header.hbs
index 98ccffb..8298ce2 100644
--- a/views/partials/header.hbs
+++ b/views/partials/header.hbs
@@ -37,6 +37,7 @@
</ul>
</li>
<li><a href="#" data-toggle="modal" data-target=".login-window">Log In</a></li>
+ <li><a href="/admin">Admin Panel</a></li>
<!--<li><a href="#" data-toggle="modal" data-target=".registration-window">Sign up</a></li>-->
<li><a href="/signup" >Sign up</a></li>
<li class="dropdown">
diff --git a/views/questions.hbs b/views/questions.hbs
index 8b69f8f..ff9b3b2 100644
--- a/views/questions.hbs
+++ b/views/questions.hbs
@@ -17,65 +17,23 @@
<!-- QUESTION LISTINGS -->
- <a href="/user_solutions">
- <section class = 'solutions-card row'>
- <div class='pull-left col-sm-8 col-md-8'>
- <h3 class = 'questions-number'>Question 1</h3>
- <p><span class='questions-sol-num'>2 solutions, </span> <span class = 'questions-comment'>6 comments</span></p>
- </div>
- <div class='pull-right right-arrow'>
- <img class='rounded' src="assets/images/right-arrow.png">
- </div>
- </section>
- </a>
+ {{#each query}}
- <a href="/user_solutions">
- <section class = 'solutions-card row'>
- <div class='pull-left col-sm-8 col-md-8'>
- <h3 class = 'questions-number'>Question 2</h3>
- <p><span class='questions-sol-num'>1 solution, </span> <span class = 'questions-comment'>2 comments</span></p>
- </div>
- <div class='pull-right right-arrow'>
- <img class='rounded' src="assets/images/right-arrow.png">
- </div>
- </section>
- </a>
+ <a href="/user_solutions">
+ <section class = 'solutions-card row'>
+ <div class='pull-left col-sm-8 col-md-8'>
+ <h3 class = 'questions-number'>Question {{this.id}}</h3>
+ <p><span class='questions-sol-num'>{{this.count}} solutions, </span> <span class = 'questions-comment'>{{this.comments}} comments</span></p>
+ </div>
+ <div class='pull-right right-arrow'>
+ <img class='rounded' src="/assets/images/right-arrow.png">
+ </div>
+ </section>
+ </a>
- <a href="/user_solutions">
- <section class = 'solutions-card row'>
- <div class='pull-left col-sm-8 col-md-8'>
- <h3 class = 'questions-number'>Question 3</h3>
- <p><span class='questions-sol-num'>1 solution, </span> <span class = 'questions-comment'>2 comments</span></p>
- </div>
- <div class='pull-right right-arrow'>
- <img class='rounded' src="assets/images/right-arrow.png">
- </div>
+ {{/each}}
- </section>
- </a>
- <a href="/user_solutions">
- <section class = 'solutions-card row'>
- <div class='pull-left col-sm-8 col-md-8'>
- <h3 class = 'questions-number'>Question 4</h3>
- <p><span class='questions-sol-num'>3 solutions, </span> <span class = 'questions-comment'>2 comments</span></p>
- </div>
- <div class='pull-right right-arrow'>
- <img class='rounded' src="assets/images/right-arrow.png">
- </div>
- </section>
- </a>
- <a href="/user_solutions">
- <section class = 'solutions-card row'>
- <div class='pull-left col-sm-8 col-md-8'>
- <h3 class = 'questions-number'>Question 5</h3>
- <p><span class='questions-sol-num'>0 solutions </span> <span class = 'questions-comment'></span></p>
- </div>
- <div class='pull-right right-arrow'>
- <img class='rounded' src="assets/images/right-arrow.png">
- </div>
- </section>
- </a>
</div>
</main>
diff --git a/views/signup.hbs b/views/signup.hbs
index 252a5bb..b5fd363 100644
--- a/views/signup.hbs
+++ b/views/signup.hbs
@@ -3,21 +3,13 @@
<div class="row" id="solutions-main">
<div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3">
- {{# if success }}
- <section class="success-msgs">
- <!-- Change those to banners later -->
- <h2>Signup Successful!</h2>
- </section>
- {{ else }}
- {{# if errors }}
- <section class="error-msgs">
- <ul>
- {{# each errors }}
- <li>{{ this.msg }}</li>
- {{/each}}
- </ul>
- </section>
- {{/if}}
+
+ {{# if hasErrors}}
+ <div class="alert alert-danger">
+ {{# each messages}}
+ <p>{{this}}</p>
+ {{/each}}
+ </div>
{{/if}}
<h2><i class="fa fa-user-plus" aria-hidden="true"></i> Sign Up</h2>
<form action="/signup" method="post">
@@ -44,11 +36,14 @@
<input type="password" class="form-control" placeholder="New Password" name="confirmPassword">
</div>
<div class="form-group">
- <input type="text" class="form-control" placeholder="University (optional)">
+ <input type="number" class="form-control" placeholder="Phone Number (optional)" name="phone_num">
+ </div>
+ <div class="form-group">
+ <input type="text" class="form-control" placeholder="University (optional)" name="univ">
</div>
<div class="form-group">
- <input type="text" class="form-control" placeholder="Department (optional)">
+ <input type="text" class="form-control" placeholder="Department (optional)" name="dept">
</div>
<input type="hidden" name="_csrf" value="{{ csrfToken }}">
<button type="signup" class="btn btn-primary">Sign Up</button>