Example #1
0
Meteor.startup(() => {

  const usernames = [
    'Saitama', 'Genos', 'Fubuki', 'King', 'Bang', 'ChildEmperor', 'AtomicSamurai', 'DriveKnight', 'Sneck', 'Lily',
    'SonGoKu', 'Vegeta', 'Cell', 'Frieza', 'Buu', 'Bulma', 'SonGoHan', 'Trunks', 'SonGoTen', 'Yamcha',
    'Aventador', 'Centenario', 'Huracan', 'Zagato', 'Gallardo', 'Vorsteiner', 'Kahn', 'Egoista', 'Veneno', 'Murcielago'
  ];

  const groupNames = ['OnePunchMan', 'DragonBall', 'Lamborghini', 'Doraemon', 'SuicideSquad'];

  if (Meteor.users.find().count() == 0) {
    for (const i of Array(usernames.length).keys()) {
      Accounts.createUser({ username: usernames[i], password: 'password' });
    }
  }
  if (Groups.find().count() == 0) {
    let c = 0;
    let players = [];
    for (const i of Array(usernames.length).keys()) {
      const user = Meteor.users.findOne({ username: usernames[i] });
      const groupsCount = Groups.find().count();
      if (i + 1 < (groupsCount + 1) * (groupsCount + 2)) {
        players.push({ id: user._id, role: 'Undecided' });
      } else {
        Groups.update(Groups.insert({ ownerId: user._id, name: groupNames[c++] }), { $push: { players: { $each: players.reverse() } } });
        players = [];
      }
    }
  }
});
Meteor.publish('allUsers', function () {
  if (Roles.userIsInRole(this.userId, 'admin'))
    return Meteor.users.find({
      $or: [
        {roles: 'projectManager'},
        {roles: 'employee'}
      ]
    }, {
      fields: {
        _id: 1,
        username: 1,
        roles: 1
      }
    });
  else
    return Meteor.users.find({
      $or: [
        {roles: 'employee'}
      ]
    }, {
      fields: {
        _id: 1,
        username: 1,
        roles: 1
      }
    });
});
Example #3
0
export default function () {
  Meteor.methods({

    '_users.add'(data) {

      check(data, {
        email: String,
        profile: {
          firstName: String,
          lastName: String
        }
      });

      data.password = 'test1234';

      // console.log('_users.add data', data);

      // XXX: Do some user authorization
      const _idNew = Accounts.createUser({email: data.email, password: 'test1234', profile: data.profile});
      // // console.log('new user created with _id_new', _id_new);

      return { _idNew };

    },

    '_users.update'(data, _id) {
      check(data, {
        firstName: String,
        lastName: String,
        email: String
      });
      check(_id, String);

      //  console.log('_users.update _id', _id);
      //  console.log('_users.update data', data);

      // XXX: Do some user authorization

      let record = Meteor.users.findOne(_id);
      // const allowedFields = ['profile.firstName'];
      // data.forEach(key => record.set(key,data[key]) );

      record.profile.set('firstName', data.firstName);
      record.profile.set('lastName', data.lastName);
      record.emails[0].set('address', data.email);
      record.save();

    },

    '_users.delete'(_id) {
      check(_id, String);
      //  console.log('_users.delete _id', _id);
      if (Meteor.userId() !== _id) {
        let record = Meteor.users.findOne(_id);
        record.remove();
      }
    }
  });
}
Example #4
0
    Meteor.users.find(query).forEach(function (identity) {
      if (identity.services.resume && identity.services.resume.loginTokens &&
          identity.services.resume.loginTokens.length > 0) {
        Meteor.users.update({ _id: identity._id }, { $set: { "services.resume.loginTokens": [] } });
      }

      Meteor.users.update({ "loginIdentities.id": identity._id },
                          { $set: { "services.resume.loginTokens": [] } });
    });
Example #5
0
 Meteor.publish("commonareas.details", function(commonareaId) {
   if (!this.userId) return null;
   let user = Meteor.users.findOne(this.userId);
   return [
     CommonAreas.find(commonareaId),
     CommonAreasSchedules.find({commonareaId: commonareaId, status: "open"}),
     Meteor.users.find({buildingId: user.buildingId}),
   ];
 });
Example #6
0
 channels.forEach(function(stream) {
     var find = Meteor.users.findOne({_id: uID, 'follows.name': stream.name});
     if (typeof find === 'undefined') {
         // Not found, insert
         Meteor.users.update(uID, {$push: {follows: stream}});
     } else {
         // Update
         Meteor.users.update({
             _id: uID,
             'follows.name': stream.name
         }, {$set: {'follows.$': stream}});
     }
 });
Accounts.LinkUserFromExternalService = function(serviceName, serviceData, options) {
  // TODO Do we need this?
  options = { ...options };

  //We probably throw an error instead of call update or create here.
  if (!Meteor.userId()) return new Meteor.Error('You must be logged in to use LinkUserFromExternalService');

  if (serviceName === 'password' || serviceName === 'resume')
    throw new Meteor.Error("Can't use LinkUserFromExternalService with internal service: " + serviceName);
  if (!(serviceData.hasOwnProperty('id') || serviceData.hasOwnProperty('userId')))
    throw new Meteor.Error("'id' missing from service data for: " + serviceName);

  const user = Meteor.user();

  if (!user) {
    return new Meteor.Error('User not found for LinkUserFromExternalService');
  }
  const checkExistingSelector = {};
  if (!!serviceData.userId) {
    serviceData.id = serviceData.userId;
    delete serviceData.userId;
  }
  checkExistingSelector['services.' + serviceName + '.id'] = serviceData.id;

  const existingUsers = Meteor.users.find(checkExistingSelector).fetch();
  if (existingUsers.length) {
    existingUsers.forEach(function(existingUser) {
      if (existingUser._id !== Meteor.userId())
        throw new Meteor.Error('This social account is already in use by other user');
    });
  }

  //we do not allow link another account from existing service.
  //XXX maybe we can override this?
  if (user.services && user.services[serviceName] && user.services[serviceName].id !== serviceData.id) {
    return new Meteor.Error('User can link only one account to service: ' + serviceName);
  } else {
    const setAttrs = {};
    Object.keys(serviceData).forEach(key => {
      setAttrs['services.' + serviceName + '.' + key] = serviceData[key];
    });

    Meteor.users.update(user._id, { $set: setAttrs });
    return {
      type: serviceName,
      userId: user._id
    };
  }
};
Example #8
0
  cfAssetsAddAccount: function(obj) {
    if (!this.userId) return {
      err: "no userid"
    };
    // print("in add account", obj);
    check(obj, Match.ObjectIncluding({
      isPublic: Boolean,
      name: String
    }));

    var user = Meteor.users.findOne({
      _id: this.userId
    });
    if (!user) return;
    if (!accountNameIsValid(obj.name, this.userId)) return {
      err: "invalid acc name"
    };

    var key = Acounts.insert({
      name: obj.name,
      addresses: {},
      isPrivate: !obj.isPublic,
      refId: user._id
    });

    if (obj.address) Meteor.call("cfAssetsAddAddress", key, obj.address);

    return {
      newAccountKey: key
    };
  },
Example #9
0
      pointsToAdd.forEach((user) => {
        // add points for user and notify
        
        Meteor.users.update(user._id, {
          $inc: { pointsGames: user.pointsToAdd, }, $set: { pointsLastGame: user.pointsToAdd }
        });

        // notify user about that
        let notification = {};
        if (user.pointsToAdd >= 0) {
          notification = {
            userId: user._id,
            name: 'Získal si nové body',
            text: `Za odohranú hru si získal ${user.pointsToAdd} bodov. Gratulujeme.`,
            read: false
          }
        } else {
          notification = {
            userId: user._id,
            name: 'Prišiel si o body',
            text: `Za odohranú hru si bohužial prišiel o ${user.pointsToAdd} bodov.`,
            read: false
          }
        }
        
        Notifications.insert(notification);
      })
Example #10
0
  const refIdentity = (identityId) => {
    if (identitySubs[identityId]) {
      // should never happen, but if somehow an account wound up with a duplicate identity ID,
      // avoid leaking a subscription
      console.error("duplicate identity id:", identityId);
      return;
    }

    const cursor = Meteor.users.find({ _id: identityId });
    const observeHandle = cursor.observe({
      added: (doc) => {
        this.added("users", doc._id, doc);
      },

      changed: (newDoc, oldDoc) => {
        this.changed("users", newDoc._id, newDoc);
      },

      removed: (oldDoc) => {
        this.removed("users", oldDoc._id);
      },
    });

    identitySubs[identityId] = observeHandle;
  };
Example #11
0
  updateQuotas: function (token, list, quota) {
    checkAuth(token);
    check(list, String);
    check(quota, Match.OneOf(undefined, null, Number));

    if (!list.trim()) {
      throw new Meteor.Error(400, "Must enter addresses.");
    }

    const items = list.split("\n");
    const invalid = [];
    for (const i in items) {
      const modifier = (typeof quota === "number") ? { $set: { quota: quota } }
                                                 : { $unset: { quota: "" } };
      let n = SignupKeys.update({ email: items[i] }, modifier, { multi: true });
      n += Meteor.users.update({ signupEmail: items[i] }, modifier, { multi: true });

      if (n < 1) invalid.push(items[i]);
    }

    if (invalid.length > 0) {
      throw new Meteor.Error(404, "These addresses did not map to any user nor invite: " +
          invalid.join(", "));
    }
  },
Example #12
0
export default function handleOnCreateUser(newUser) {
	if (!newUser) {
		return this.log('Invalid handleOnCreateUser call');
	}
	if (!newUser.username) {
		return this.log('Invalid handleOnCreateUser call (Missing username)');
	}
	if (this.loggedInUsers.indexOf(newUser._id) !== -1) {
		return this.log('Duplicate handleOnCreateUser call');
	}

	this.loggedInUsers.push(newUser._id);

	Meteor.users.update({ _id: newUser._id }, {
		$set: {
			'profile.irc.fromIRC': false,
			'profile.irc.username': `${ newUser.username }-rkt`,
			'profile.irc.nick': `${ newUser.username }-rkt`,
			'profile.irc.hostname': 'rocket.chat',
		},
	});

	const user = RocketChat.models.Users.findOne({
		_id: newUser._id,
	});

	this.sendCommand('registerUser', user);

	const rooms = RocketChat.models.Rooms.findBySubscriptionUserId(user._id).fetch();

	rooms.forEach((room) => this.sendCommand('joinedChannel', { room, user }));
}
Example #13
0
Meteor.publish("users.getUsers", function() {
	if (!Roles.userIsInRole(this.userId, ['admin'])) {
		throw new Meteor.Error('not-authorized');
	}

	return Meteor.users.find({}, {sort: {roles: 1}});
});
      shops.forEach((shop) => {
        const shopManager = Groups.findOne({ slug: "shop manager", shopId: shop._id });
        if (shopManager) {
          const shopManagerRoles = shopManager.permissions;
          // add back admin role
          const newShopManagerRoles = shopManagerRoles.concat(["admin"]);
          Groups.update({
            slug: "shop manager",
            shopId: shop._id
          }, {
            $set: { permissions: newShopManagerRoles }
          });
          Logger.debug(`group "shop manager" with id "${shopManager._id}" updated(admin role added)`);

          // update users in group to new roles
          const userIds = Accounts.find({ groups: shopManager._id }).fetch().map((acc) => acc._id);
          Meteor.users.update({
            _id: { $in: userIds }
          }, {
            $set: { [`roles.${shop._id}`]: newShopManagerRoles }
          }, {
            multi: true
          });
          Logger.debug(`users with "shop manager" in shop "${shop._id}" updated(admin role added)`);
        }
      });
Example #15
0
 Meteor.publish('users', function () {
   return Meteor.users.find({}, {fields: {
     'profile': true,
     'services.google.picture': true,
     'points': true
   }});
 });
function onPropsChange (props, onData) {
  let handle = Meteor.subscribe('userList')
  if (handle.ready()) {
    const users = Meteor.users.find({}).fetch()
    onData(null, { users })
  }
}
  'createChannel': function (userId) {
    const user = Meteor.user();

    if (!user) {
      return;
    }

    Channels.insert({
      subscriber: userId,
      publisher: user._id,
      creationDate: new Date()
    });

    Meteor.users.update({_id: user._id}, {$set: {state: 'subscriber'}});
    Meteor.users.update({_id: userId}, {$set: {state: 'publisher'}});

  },
Example #18
0
export function invite(partyId, userId) {
  check(partyId, String);
  check(userId, String);

  if (!this.userId) {
    throw new Meteor.Error(400, 'You have to be logged in!');
  }

  const party = Festas.findOne(partyId);

  if (!party) {
    throw new Meteor.Error(404, 'No such party!');
  }

  if (party.owner !== this.userId) {
    throw new Meteor.Error(404, 'No permissions!');
  }

  if (party.public) {
    throw new Meteor.Error(400, 'That party is public. No need to invite people.');
  }

  if (userId !== party.owner && ! _.contains(party.invited, userId)) {
    Festas.update(partyId, {
      $addToSet: {
        invited: userId
      }
    });

    const replyTo = getContactEmail(Meteor.users.findOne(this.userId));
    const to = getContactEmail(Meteor.users.findOne(userId));

    if (Meteor.isServer && to) {
      Email.send({
        to,
        replyTo,
        from: 'noreply@socially.com',
        subject: `PARTY: ${party.title}`,
        text: `
          Olá, Eu gostaria de convidar você para a ${party.title} do grupo.
          Confira o convite no link: ${Meteor.absoluteUrl()}
        `
      });
    }
  }
}
Example #19
0
 event.attendees.map(function(attendee) {
   let user = Meteor.users.find({_id: attendee._id}).fetch()[0];
   if(user.profile.notif_email == true) {
     let email = user.emails[0].address;
     let username = user.username;
     sendMailReminder(email, username, event.title, event.venue, event.address.formattedAddress, event.hour);
   }
 });
 'setUserAsRequested': function (userId) {
   return Meteor.users.update({_id: userId}, {
     $set: {
       state: 'requested',
       requestingUserId: (Meteor.user() || {})._id
     }
   });
 },
 this.getRoomHolder = () => {
   var holder = Meteor.users.findOne({ "status.online": true });
   if(holder){
     return holder.username;
   }else{
     return '';
   };
 };
Example #22
0
users.forEach(({ email, password, profile, roles }) => {
  const userExists = Meteor.users.findOne({ 'emails.address': email });

  if (!userExists) {
    const userId = Accounts.createUser({ email, password, profile });
    Roles.addUsersToRoles(userId, roles);
  }
});
Example #23
0
function composer(props, onData) {
  const currUserId = Meteor.userId();
  const handle = Meteor.subscribe('organizations.portfolioOwnerSelection', currUserId);
  if (handle.ready()) {
    const currUser = Meteor.users.findOne({ _id: Meteor.userId() });
    onData(null, { create, currUser, getOwnerOptions });
  }
}
Example #24
0
function setGravatars() {
    let users = Meteor.users.find( { md5hash: { $exists: false } } );
    users.forEach( ( user ) => {
        if(user.emails && user.emails.length)
        Meteor.users.update( { _id: user._id }, {
            $set: { "profile.md5hash": Gravatar.hash( user.emails[0].address ) }
        });
    });
}
Example #25
0
 Meteor.publish('userData', function () {
   if (this.userId) {
     return Meteor.users.find({ _id: this.userId }, {
       fields: { other: 1, things: 1 }
     });
   } else {
     this.ready();
   }
 });
Example #26
0
export function getUsers(limit = 2) {
  const users = [];
  const existingUsers = Meteor.users.find({}, { limit }).fetch();
  for (let i = 0; i < limit; i += 1) {
    const user = existingUsers[i] || Factory.create("user");
    users.push(user);
  }
  return users;
}
 distributeWeeklyEmails: function () {
   console.log('Distributing weekly meal plans to users...');
   Meteor.users.find().map(function(user) {
     var week = moment().weeks();
     var year = moment().weekYear();
     var mealPlan = Plans.findOne({user: user._id, week: week, year: year});
     Meteor.call('sendWeeklyEmail', user._id, user.services.facebook.email, week, year);
   });
 }
Example #28
0
  constructor($scope) {
    'ngInject';

    $scope.viewModel(this);

    this.helpers({
      users() {
        return Meteor.users.find({});
      }
    });
  }
Example #29
0
  Meteor.publish('sharedBins', function() {
    const user = Meteor.users.findOne(this.userId);

    if (!user) { return; }

    const email = user.emails[0].address;

    return Bins.find({
      sharedWith: { $elemMatch: { $eq: email }}
    });
  });
Example #30
0
Picker.route('/users/search', function (params, req, res) {
  // Required headers
  const userId = req.headers['x-user-id'];
  const loginToken = req.headers['x-login-token'];

  if (!userId || !loginToken) {
    fail(res);
    return false;
  }

  // Connected user
  const user = findUserByLoginToken(userId, loginToken, {
    fields: {
      'profile.contacts': 1
    }
  });

  if (!user) {
    fail(res);
    return false;
  }

  // Exclude bot, connected user and his contacts
  const excludeIds = user.profile && user.profile.contacts
    ? user.profile.contacts
    : [];

  excludeIds.push(Meteor.settings.public.bot.id);
  excludeIds.push(userId);

  // Find users
  const users = Meteor.users.find({
    _id: {
      $nin: excludeIds
    },
    username: {
      $regex: escapeStringRegExp(params.query.username)
    }
  }, {
    fields: {
      username: 1
    },
    limit: 20
  }).fetch();

  // Return results
  res.end(JSON.stringify({
    success: true,
    results: users.map(user => ({
      name: user.username,
      value: user.username
    }))
  }));
});