schema.statics.getByIdChallenges = function (id) { var Arena = this.db.model(Model); var Challenge = this.db.model('Challenge'); return Promise.fulfilled().then(function () { return Challenge.find({arena:id}).sort('order').exec(); }); };
handle: function handle(record) { var promises = []; if (this.filter(record)) { var i = this._handlers.length; while (i--) { if (record.level >= this._handlers[i].level) { promises.push(this._handlers[i].handle(record)); } } // if this.propagate, tell our parent if (this.propagate) { var par = getEffectiveParent(this._name); if (par) { promises.push(par.handle(record)); } } } if (promises.length > 2) { return Promise.all(promises); } else if (promises[0]) { return promises[0]; } else { return Promise.fulfilled(); } },
function createIfNewUser(req, user) { if (user) { throw { http_code: 400, message: 'User already exists' }; } var role = getRoleByEmail(req.body.email); return Promise.fulfilled().then(function() { return User.find({}).count({}).exec(); }).then(function(count) { var flags = getFlags({ user: req.body, count: count }); return User.create({ username: req.body.username, email: req.body.email, uniId: req.body.uniId, lectureGroup: req.body.lectureGroup, labGroup: req.body.labGroup, password: req.body.password, role: role, flags: flags, activated: false }); }); }
.then(function(dexists) { if(!dexists) { return fs.mkdirAsync(pth); } return Promise.fulfilled(); });
app.put('/api/users/:id', access.requireRole(['$self', 'teacher', 'admin']), function(req, res, next) { var user = req.body.user; Promise.fulfilled().then(function() { if (user.password && user.password !== user.passwordConfirmation) { throw { http_code: 403, message: "passwords didn't match" }; } return User.findOne({ _id: req.params.id }).exec(); }).then(function(model) { if (!model) throw { http_code: 404, message: "Not Found" }; model.set(user); model.save(function(err, model) { if (err) return next(err); res.json({ user: model, access_token: user.passwordConfirmation ? model.token : undefined }); }); }).catch(function(err) { if (err.http_code) { return res.send(err.http_code, err.message); } next(err); }); });
log: function log(level, msg /*, messageArs..., [callback] */) { level = LEVELS.getLevel(level); var args; if (arguments.length < 3) { args = [msg]; } else { args = SLICE.call(arguments, 1); } var fn; if (typeof args[args.length - 1] === 'function') { fn = args.pop(); } // if level >= this.getEffectiveLevel(), tell our handlers var promise; var record; if (this.isEnabledFor(level)) { record = this.makeRecord(this._name, level, msg, args); promise = this.handle(record); } else { promise = Promise.fulfilled(); } if (fn) { promise = promise.done(fn); } return promise; },
observer.on('userArena.complete', function(userArena) { Promise.fulfilled().then(function() { return Requirement.find({ model1: 'Arena', $or: [{ id1: { $exists: false } }, { id1: userArena.arena }], complete: false, user: userArena.user }).exec(); }).then(function (reqs) { return _.map(reqs, function (req) { req.completed+=1; if(req.completed===req.times) { req.complete = true; } return new Promise(function(resolve, reject) { req.save(function(err, model) { if (err) return reject(err); if (model.complete) observer.emit('requirement.complete', req); resolve(model); }); }); }); }); });
schema.statics.getMembers = function(id) { return Promise.fulfilled().then(function() { return Member.find({ group: id }).exec(); }); };
ExpiringToken.getToken(req.body.token).then(function(token) { if (token) { return Promise.fulfilled().then(function() { return User.findOne({ _id: token.user }).exec(); }).then(function(user) { if (req.body.password !== req.body.passwordConfirmation) { throw { http_code: 400, message: 'Passwords do not match.' }; } user.password = req.body.password; user.save(function(err, user) { if (err) throw err; res.render('confirm.html', { user: user, }); ExpiringToken.useToken(token.id); }); }); } else { res.render("expiredToken.html"); } }).catch(function(err) {
schema.methods.getMembers = function() { return Promise.fulfilled().then(function() { return Member.find({ group: this.id }).exec(); }); };
app.get('/api/trials', access.requireRole(), function(req, res, next) { var promise; if(req.query.ids) { req.query._id = {$in:req.query.ids}; delete req.query.ids; promise = Trial.getByQuery(req.query).then(function(model) { res.json({ trial: model }); }); } else if(req.query.arena || req.query.userArena) { var userId; if(req.user.isStudent) { userId = req.user.id; } else { userId = req.query.user || req.user.id; } promise = Promise.fulfilled().then(function () { if(!req.query.arena) { return Arena.getByQuery({users: {$in:[req.query.userArena]}}); } else { return {id:req.query.arena}; } }).then(function (arena) { var userarena = {}; if(req.query.userArena) { userarena.id = req.query.userArena; } else { var obj = {arena:arena.id, user:userId}; userarena = UserArena.getOneByQueryOrCreate(obj, obj); } return [Challenge.getByQuery({arena:arena.id}), userarena, arena]; }).spread(function (challenges, ua, arena) { challenges = _.filter(challenges, 'isPublished'); return [ challenges, Promise.map(challenges, function (ch) { var obj = {arena:arena.id, userArena:ua.id, challenge:ch.id, user:userId}; var update = _.clone(obj); update.order = ch.order; update.group = ch.group; return Trial.getOneByQueryOrCreateOrUpdate(obj, update); }) ]; }).spread(function (challenges, trials) { res.json({ challenge:challenges, trial: _.filter(trials, null) }); }); } else { promise = Trial.getByQuery(req.query).then(function(model) { res.json({ trial: model }); }); } promise.catch(next); });
schema.methods.getUserArenaByUserId = function (userId) { var arena = this; var UserArena = this.db.model('UserArena'); return Promise.fulfilled().then(function () { var obj = {arena:arena.id, user:userId}; return UserArena.getOneByQueryOrCreate(obj, obj); }); };
schema.methods.getOwners = function() { var group = this; return Promise.fulfilled().then(function() { return Member.find({ group: group.id, role: 'owner' }).exec(); }); };
schema.methods.addMember = function(uid) { var group = this; return Promise.fulfilled().then(function() { return User.findOne({_id:uid}).exec(); }).then(function(user) { if(!user) throw {http_code: 404, message:"user not found"}; return group.join(user); }); };
schema.methods.getUsers = function(id) { return Promise.fulfilled().then(function() { Member.find({ group: id }).populate('user').exec(); }).then(function(members) { return _.map(members, 'user'); }); };
schema.statics.getGroups = function(uid) { return Promise.fulfilled().then(function() { return Member.find({ user: uid }).populate('group').exec(); }).then(function (memeberships) { return _.map(memeberships, 'group'); }); };
handle: function(record) { if (!this.filter(record)) { return Promise.fulfilled(); } if (this.emit.length < 2) { throw new Error('Handler.emit requires a callback argument'); } return this._emit(record); },
schema.methods.addMembers = function(uids) { var group = this; return Promise.fulfilled().then(function() { return User.find({_id:{$in:uids}}).exec(); }).then(function(users) { return Promise.map(users, function (user) { return group.join(user); }); }); };
schema.statics.getArenaWithUserArenaByUserId = function (id, userId) { var Arena = this.db.model(Model); var UserArena = this.db.model('UserArena'); return Promise.fulfilled().then(function (arena) { var obj = {arena:id, user:userId}; return UserArena.getOneByQueryOrCreate(obj, obj); }).then(function (ua) { return [Arena.getById_404(id), ua]; }); };
function addHtml(fullpath, basepath) { if (fastfs.isPage(fullpath, basepath)) { return parse(fullpath, basepath).then(function(content) { var target = fastfs.targetPath(fullpath, basepath); return fs.writeFileAsync(target, content); }); } // Dummy promise return Promise.fulfilled(); }
schema.statics.findOrCreateByName = function(name) { var Group = this.db.model('Group'); return Promise.fulfilled().then(function() { return Group.findOne({ name: name }).exec(); }).then(function (group) { if (group) {return group;} return Group.create({name:name}); }); };
app.get('/profile', access.requireRole(), function(req, res) { Promise.fulfilled().then(function() { return [UserQuest.find({ user: req.user.id }).exec()]; }).spread(function(uqs) { res.send({ user: req.user, userQuests: uqs }); }); });
beforeEach(function(done) { student = { username: 'student', email: 'student@place.com', password: 'student123', role: 'student', activated: true }; student2 = { username: 'student2', email: 'student2@place.com', password: 'student123', role: 'student', activated: true }; teacher = { username: 'teacher', email: 'teach@place.com', password: 'teacher123', role: 'teacher', activated: true }; Promise.fulfilled().then(function() { return [ User.create(teacher), User.create(student), User.create(student2) ]; }).spread(function(t, st, st2) { student = st; student2 = st2; var at = Achievement.create({ name:"start of a journey", description: "you got 10 exp points", requirements: [{property:'exp', condition:'>=', activation:10}], author: teacher.id }); return [at]; }).spread(function(g) { achievement = g; expect(achievement).to.exist; // console.log(achievement); return [User.findOne({ _id: teacher.id }).exec(), User.findOne({ _id: student.id }).exec()]; }).spread(function(t, st) { student = st; teacher = t; }).finally(done); });
app.post('/signup', function(req, res, next) { Promise.fulfilled() .then(validateRequestBody(req)) .then(processFields) .then(findUser) .spread(createIfNewUser) .then(emitAndRespond(res)) .catch(function(err) { if (err.http_code) { return res.send(err.http_code, err.message); } res.send(500, err.message); }); });
schema.statics.getSubscribersFor = function(gid) { var Group = this.db.model('Group'); if(_.isArray(gid)) { return Promise.fulfilled().then(function () { return Member.find({ group: {$in:gid}, role: 'subscriber' }).exec(); }); } else { return Group.getById_404(gid).then(function(group) { return group.getSubscribers(); }); } };
schema.methods.getIfMember = function(options) { var uid; if (_.isString(options)) { uid = options; } else { uid = options.isUser ? options.id : options.user.id; } var group = this; return Promise.fulfilled().then(function() { return Member.findOne({ group: group.id, user: uid, }).exec(); }); };
schema.statics.KCreate = function(challenge) { var Challenge = this.db.model('Challenge'); var promise = Promise.fulfilled(); if (!challenge.order && challenge.arena) { promise = promise.then(function() { return Arena.getById(challenge.arena).then(function(arena) { challenge.order = arena.challenges.length + 1; }); }); } return promise.then(function() { return Challenge.create(challenge); }); };
beforeEach(function(done) { Promise.fulfilled().then(function() { var at = UserArena.create({}); var ch = Challenge.create({}); var ch2 = Challenge.create({}); var usr = User.create({ username: 'testuser', password: 'testuser12' }); return [at, ch, ch2, usr]; }).spread(function(at, ch, ch2, usr) { challenge = ch; userArena = at; user = usr; var arr = Array(num); var chs = Promise.each(arr, function() { return Trial.create({ challenge: ch._id, userArena: at._id, user: usr }); }); var chs2 = Promise.each(arr, function() { return Trial.create({ challenge: ch2._id, userArena: at._id, user: usr }); }); return [chs, chs2]; }).spread(function(chs, chs2) { trials = chs.concat(chs2); return [ UserArena.findOne({ _id: userArena._id }).exec(), Challenge.findOne({ _id: challenge._id }).exec() ]; }).spread(function(at, ch) { userArena = at; challenge = ch; }).finally(done); });
/** * Purges entries in database for EC2 instances not seen for a week */ function purgeDbEntries(){ var weekAgo = new Date(); //Date.now(); // create an variable with the date a week ago weekAgo.setDate(weekAgo.getDate() - 0); var queryParams = { TableName: tableName, IndexName: "timestamp", KeyConditionExpression: "#vid = :hkey AND #ls < :rkey", ExpressionAttributeNames:{ "#vid": "vpc-id", "#ls": "last_seen" }, ExpressionAttributeValues: { ":hkey": vpcId, ":rkey": weekAgo.getTime() } }; var docClient = new AWS.DynamoDB.DocumentClient(); docClient.query(queryParams).promise() .then(function(results){ for (let i = 0; i < results.Items.length; i++){ let deleteParams = { TableName: tableName, Key: { 'ec2-id': results.Items[i]['ec2-id'] } } docClient.delete(deleteParams); } }) .catch( function(error){ console.log('Error purging old entries from database.\n'+error); } ); return Promise.fulfilled(); // return promise to top level }
app.post('/api/users/forgotpass', function(req, res, next) { var user; var token; Promise.fulfilled().then(function() { return User.findByIdentity(req.body.identification); }).then(function(usr) { if (!usr) { throw { http_code: 403, message: "Identity does not exist" }; } user = usr; return ExpiringToken.toForgotPassword(usr); }).then(function(eToken) { token = eToken; var confirmURL = req.headers.host + '/forgotpass/' + eToken._id; // template in views/mail return mail.renderAndSend('forgotpass.html', { confirmURL: confirmURL }, { to: user.email, subject: 'Forgot Password Request', stub: process.env.NODE_ENV === 'test', }); }).then(function(info) { if (process.env.NODE_ENV === 'test') { return res.send({ token: token._id, info: info }); } else { res.send({ message: "Email was sent to reset your password" }); } }).catch(function(err) { console.log(err.stack); if (err.http_code) { return res.send(err.http_code, err.message); } res.send(500, err.message); }); });