users.js 8.1 KB

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