users.js 8.3 KB

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