users.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. Users = Meteor.users; // eslint-disable-line meteor/collections
  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. if (!process.env.MAIL_URL || (!Email)) return { username: user.username };
  145. try {
  146. let rootUrl = Meteor.absoluteUrl.defaultOptions.rootUrl || '';
  147. if (!rootUrl.endsWith('/')) rootUrl = `${rootUrl}/`;
  148. const boardUrl = `${rootUrl}b/${board._id}/${board.slug}`;
  149. const vars = {
  150. user: user.username,
  151. inviter: inviter.username,
  152. board: board.title,
  153. url: boardUrl,
  154. };
  155. const lang = user.getLanguage();
  156. Email.send({
  157. to: user.emails[0].address,
  158. from: Accounts.emailTemplates.from,
  159. subject: TAPi18n.__('email-invite-subject', vars, lang),
  160. text: TAPi18n.__('email-invite-text', vars, lang),
  161. });
  162. } catch (e) {
  163. throw new Meteor.Error('email-fail', e.message);
  164. }
  165. return { username: user.username, email: user.emails[0].address };
  166. },
  167. });
  168. }
  169. Users.before.insert((userId, doc) => {
  170. doc.profile = doc.profile || {};
  171. if (!doc.username && doc.profile.name) {
  172. doc.username = doc.profile.name.toLowerCase().replace(/\s/g, '');
  173. }
  174. });
  175. if (Meteor.isServer) {
  176. // Let mongoDB ensure username unicity
  177. Meteor.startup(() => {
  178. Users._collection._ensureIndex({
  179. username: 1,
  180. }, { unique: true });
  181. });
  182. // Each board document contains the de-normalized number of users that have
  183. // starred it. If the user star or unstar a board, we need to update this
  184. // counter.
  185. // We need to run this code on the server only, otherwise the incrementation
  186. // will be done twice.
  187. Users.after.update(function(userId, user, fieldNames) {
  188. // The `starredBoards` list is hosted on the `profile` field. If this
  189. // field hasn't been modificated we don't need to run this hook.
  190. if (!_.contains(fieldNames, 'profile'))
  191. return;
  192. // To calculate a diff of board starred ids, we get both the previous
  193. // and the newly board ids list
  194. function getStarredBoardsIds(doc) {
  195. return doc.profile && doc.profile.starredBoards;
  196. }
  197. const oldIds = getStarredBoardsIds(this.previous);
  198. const newIds = getStarredBoardsIds(user);
  199. // The _.difference(a, b) method returns the values from a that are not in
  200. // b. We use it to find deleted and newly inserted ids by using it in one
  201. // direction and then in the other.
  202. function incrementBoards(boardsIds, inc) {
  203. boardsIds.forEach((boardId) => {
  204. Boards.update(boardId, {$inc: {stars: inc}});
  205. });
  206. }
  207. incrementBoards(_.difference(oldIds, newIds), -1);
  208. incrementBoards(_.difference(newIds, oldIds), +1);
  209. });
  210. // XXX i18n
  211. Users.after.insert((userId, doc) => {
  212. const ExampleBoard = {
  213. title: 'Welcome Board',
  214. userId: doc._id,
  215. permission: 'private',
  216. };
  217. // Insert the Welcome Board
  218. Boards.insert(ExampleBoard, (err, boardId) => {
  219. ['Basics', 'Advanced'].forEach((title) => {
  220. const list = {
  221. title,
  222. boardId,
  223. userId: ExampleBoard.userId,
  224. // XXX Not certain this is a bug, but we except these fields get
  225. // inserted by the Lists.before.insert collection-hook. Since this
  226. // hook is not called in this case, we have to dublicate the logic and
  227. // set them here.
  228. archived: false,
  229. createdAt: new Date(),
  230. };
  231. Lists.insert(list);
  232. });
  233. });
  234. });
  235. }