users.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. Users = Meteor.users;
  2. // Search a user in the complete server database by its name or username. This
  3. // is used for instance to add a new user to a board.
  4. const searchInFields = ['username', 'profile.fullname'];
  5. Users.initEasySearch(searchInFields, {
  6. use: 'mongo-db',
  7. returnFields: [...searchInFields, 'profile.avatarUrl'],
  8. });
  9. if (Meteor.isClient) {
  10. Users.helpers({
  11. isBoardMember() {
  12. const board = Boards.findOne(Session.get('currentBoard'));
  13. return board && board.hasMember(this._id);
  14. },
  15. isBoardAdmin() {
  16. const board = Boards.findOne(Session.get('currentBoard'));
  17. return board && board.hasAdmin(this._id);
  18. },
  19. });
  20. }
  21. Users.helpers({
  22. boards() {
  23. return Boards.find({ userId: this._id });
  24. },
  25. starredBoards() {
  26. const {starredBoards = []} = this.profile;
  27. return Boards.find({archived: false, _id: {$in: starredBoards}});
  28. },
  29. hasStarred(boardId) {
  30. const {starredBoards = []} = this.profile;
  31. return _.contains(starredBoards, boardId);
  32. },
  33. invitedBoards() {
  34. const {invitedBoards = []} = this.profile;
  35. return Boards.find({archived: false, _id: {$in: invitedBoards}});
  36. },
  37. isInvitedTo(boardId) {
  38. const {invitedBoards = []} = this.profile;
  39. return _.contains(invitedBoards, boardId);
  40. },
  41. getInitials() {
  42. const profile = this.profile || {};
  43. if (profile.initials)
  44. return profile.initials;
  45. else if (profile.fullname) {
  46. return profile.fullname.split(/\s+/).reduce((memo = '', word) => {
  47. return memo + word[0];
  48. }).toUpperCase();
  49. } else {
  50. return this.username[0].toUpperCase();
  51. }
  52. },
  53. getName() {
  54. const profile = this.profile || {};
  55. return profile.fullname || this.username;
  56. },
  57. getLanguage() {
  58. const profile = this.profile || {};
  59. return profile.language || 'en';
  60. },
  61. });
  62. Users.mutations({
  63. toggleBoardStar(boardId) {
  64. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  65. return {
  66. [queryKind]: {
  67. 'profile.starredBoards': boardId,
  68. },
  69. };
  70. },
  71. addInvite(boardId) {
  72. return {
  73. $addToSet: {
  74. 'profile.invitedBoards': boardId,
  75. },
  76. };
  77. },
  78. removeInvite(boardId) {
  79. return {
  80. $pull: {
  81. 'profile.invitedBoards': boardId,
  82. },
  83. };
  84. },
  85. setAvatarUrl(avatarUrl) {
  86. return { $set: { 'profile.avatarUrl': avatarUrl }};
  87. },
  88. });
  89. Meteor.methods({
  90. setUsername(username) {
  91. check(username, String);
  92. const nUsersWithUsername = Users.find({ username }).count();
  93. if (nUsersWithUsername > 0) {
  94. throw new Meteor.Error('username-already-taken');
  95. } else {
  96. Users.update(this.userId, {$set: { username }});
  97. }
  98. },
  99. });
  100. if (Meteor.isServer) {
  101. Meteor.methods({
  102. // we accept userId, username, email
  103. inviteUserToBoard(username, boardId) {
  104. check(username, String);
  105. check(boardId, String);
  106. const inviter = Meteor.user();
  107. const board = Boards.findOne(boardId);
  108. const allowInvite = inviter &&
  109. board &&
  110. board.members &&
  111. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  112. _.where(board.members, {userId: inviter._id})[0].isActive &&
  113. _.where(board.members, {userId: inviter._id})[0].isAdmin;
  114. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  115. this.unblock();
  116. const posAt = username.indexOf('@');
  117. let user = null;
  118. if (posAt>=0) {
  119. user = Users.findOne({emails: {$elemMatch: {address: username}}});
  120. } else {
  121. user = Users.findOne(username) || Users.findOne({ username });
  122. }
  123. if (user) {
  124. if (user._id === inviter._id) throw new Meteor.Error('error-user-notAllowSelf');
  125. } else {
  126. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  127. const email = username;
  128. username = email.substring(0, posAt);
  129. const newUserId = Accounts.createUser({ username, email });
  130. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  131. // assume new user speak same language with inviter
  132. if (inviter.profile && inviter.profile.language) {
  133. Users.update(newUserId, {
  134. $set: {
  135. 'profile.language': inviter.profile.language,
  136. },
  137. });
  138. }
  139. Accounts.sendEnrollmentEmail(newUserId);
  140. user = Users.findOne(newUserId);
  141. }
  142. board.addMember(user._id);
  143. user.addInvite(boardId);
  144. try {
  145. const { _id, slug } = board;
  146. const boardUrl = FlowRouter.url('board', { id: _id, slug });
  147. const vars = {
  148. user: user.username,
  149. inviter: inviter.username,
  150. board: board.title,
  151. url: boardUrl,
  152. };
  153. const lang = user.getLanguage();
  154. Email.send({
  155. to: user.emails[0].address,
  156. from: Accounts.emailTemplates.from,
  157. subject: TAPi18n.__('email-invite-subject', vars, lang),
  158. text: TAPi18n.__('email-invite-text', vars, lang),
  159. });
  160. } catch (e) {
  161. throw new Meteor.Error('email-fail', e.message);
  162. }
  163. return { username: user.username, email: user.emails[0].address };
  164. },
  165. });
  166. }
  167. Users.before.insert((userId, doc) => {
  168. doc.profile = doc.profile || {};
  169. if (!doc.username && doc.profile.name) {
  170. doc.username = doc.profile.name.toLowerCase().replace(/\s/g, '');
  171. }
  172. });
  173. if (Meteor.isServer) {
  174. // Let mongoDB ensure username unicity
  175. Meteor.startup(() => {
  176. Users._collection._ensureIndex({
  177. username: 1,
  178. }, { unique: true });
  179. });
  180. // Each board document contains the de-normalized number of users that have
  181. // starred it. If the user star or unstar a board, we need to update this
  182. // counter.
  183. // We need to run this code on the server only, otherwise the incrementation
  184. // will be done twice.
  185. Users.after.update(function(userId, user, fieldNames) {
  186. // The `starredBoards` list is hosted on the `profile` field. If this
  187. // field hasn't been modificated we don't need to run this hook.
  188. if (!_.contains(fieldNames, 'profile'))
  189. return;
  190. // To calculate a diff of board starred ids, we get both the previous
  191. // and the newly board ids list
  192. function getStarredBoardsIds(doc) {
  193. return doc.profile && doc.profile.starredBoards;
  194. }
  195. const oldIds = getStarredBoardsIds(this.previous);
  196. const newIds = getStarredBoardsIds(user);
  197. // The _.difference(a, b) method returns the values from a that are not in
  198. // b. We use it to find deleted and newly inserted ids by using it in one
  199. // direction and then in the other.
  200. function incrementBoards(boardsIds, inc) {
  201. boardsIds.forEach((boardId) => {
  202. Boards.update(boardId, {$inc: {stars: inc}});
  203. });
  204. }
  205. incrementBoards(_.difference(oldIds, newIds), -1);
  206. incrementBoards(_.difference(newIds, oldIds), +1);
  207. });
  208. // XXX i18n
  209. Users.after.insert((userId, doc) => {
  210. const ExampleBoard = {
  211. title: 'Welcome Board',
  212. userId: doc._id,
  213. permission: 'private',
  214. };
  215. // Insert the Welcome Board
  216. Boards.insert(ExampleBoard, (err, boardId) => {
  217. ['Basics', 'Advanced'].forEach((title) => {
  218. const list = {
  219. title,
  220. boardId,
  221. userId: ExampleBoard.userId,
  222. // XXX Not certain this is a bug, but we except these fields get
  223. // inserted by the Lists.before.insert collection-hook. Since this
  224. // hook is not called in this case, we have to dublicate the logic and
  225. // set them here.
  226. archived: false,
  227. createdAt: new Date(),
  228. };
  229. Lists.insert(list);
  230. });
  231. });
  232. });
  233. }