diff options
Diffstat (limited to 'app/models/room.js')
-rw-r--r-- | app/models/room.js | 80 |
1 files changed, 79 insertions, 1 deletions
diff --git a/app/models/room.js b/app/models/room.js index 86ad322..bb597ce 100644 --- a/app/models/room.js +++ b/app/models/room.js @@ -7,6 +7,7 @@ var mongoose = require('mongoose'), ObjectId = mongoose.Schema.Types.ObjectId, uniqueValidator = require('mongoose-unique-validator'), + bcrypt = require('bcryptjs'), settings = require('./../config'); var RoomSchema = new mongoose.Schema({ @@ -36,6 +37,10 @@ var RoomSchema = new mongoose.Schema({ ref: 'User', required: true }, + participants: [{ // We can have an array per role + type: ObjectId, + ref: 'User' + }], messages: [{ type: ObjectId, ref: 'Message' @@ -47,6 +52,10 @@ var RoomSchema = new mongoose.Schema({ lastActive: { type: Date, default: Date.now + }, + password: { + type: String, + required: false//only for password-protected room } }); @@ -54,10 +63,78 @@ RoomSchema.virtual('handle').get(function() { return this.slug || this.name.replace(/\W/i, ''); }); +RoomSchema.virtual('hasPassword').get(function() { + return !!this.password; +}); + +RoomSchema.pre('save', function(next) { + var room = this; + if (!room.password || !room.isModified('password')) { + return next(); + } + + bcrypt.hash(room.password, 10, function(err, hash) { + if (err) { + return next(err); + } + room.password = hash; + next(); + }); +}); + RoomSchema.plugin(uniqueValidator, { message: 'Expected {PATH} to be unique' }); +RoomSchema.method('isAuthorized', function(userId) { + if(!this.password) { + return true; + } + + if (this.owner.equals(userId)) { + return true; + } + + return this.participants.some(function(participant) { + return participant.equals(userId); + }); +}); + +RoomSchema.method('canJoin', function(options, cb) { + var userId = options.userId, + password = options.password, + saveMembership = options.saveMembership; + + if (this.isAuthorized(userId)) { + return cb(null, true); + } + + bcrypt.compare(password || '', this.password, function(err, isMatch) { + if(err) { + return cb(err); + } + + if (!isMatch) { + return cb(null, false); + } + + if (!saveMembership) { + return cb(null, true); + } + + this.participants.push(userId); + + this.save(function(err) { + if(err) { + return cb(err); + } + + cb(null, true); + }); + + }.bind(this)); +}); + RoomSchema.method('toJSON', function() { var room = this.toObject(); return { @@ -67,7 +144,8 @@ RoomSchema.method('toJSON', function() { description: room.description, lastActive: room.lastActive, created: room.created, - owner: room.owner + owner: room.owner, + hasPassword: this.hasPassword }; }); |