users.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. hasTag(tag) {
  42. const {tags = []} = this.profile;
  43. return _.contains(tags, tag);
  44. },
  45. hasNotification(activityId) {
  46. const {notifications = []} = this.profile;
  47. return _.contains(notifications, activityId);
  48. },
  49. getEmailBuffer() {
  50. const {emailBuffer = []} = this.profile;
  51. return emailBuffer;
  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. addTag(tag) {
  98. return {
  99. $addToSet: {
  100. 'profile.tags': tag,
  101. },
  102. };
  103. },
  104. removeTag(tag) {
  105. return {
  106. $pull: {
  107. 'profile.tags': tag,
  108. },
  109. };
  110. },
  111. toggleTag(tag) {
  112. if (this.hasTag(tag))
  113. this.removeTag(tag);
  114. else
  115. this.addTag(tag);
  116. },
  117. addNotification(activityId) {
  118. return {
  119. $addToSet: {
  120. 'profile.notifications': activityId,
  121. },
  122. };
  123. },
  124. removeNotification(activityId) {
  125. return {
  126. $pull: {
  127. 'profile.notifications': activityId,
  128. },
  129. };
  130. },
  131. addEmailBuffer(text) {
  132. return {
  133. $addToSet: {
  134. 'profile.emailBuffer': text,
  135. },
  136. };
  137. },
  138. clearEmailBuffer() {
  139. return {
  140. $set: {
  141. 'profile.emailBuffer': [],
  142. },
  143. };
  144. },
  145. setAvatarUrl(avatarUrl) {
  146. return { $set: { 'profile.avatarUrl': avatarUrl }};
  147. },
  148. });
  149. Meteor.methods({
  150. setUsername(username) {
  151. check(username, String);
  152. const nUsersWithUsername = Users.find({ username }).count();
  153. if (nUsersWithUsername > 0) {
  154. throw new Meteor.Error('username-already-taken');
  155. } else {
  156. Users.update(this.userId, {$set: { username }});
  157. }
  158. },
  159. });
  160. if (Meteor.isServer) {
  161. Meteor.methods({
  162. // we accept userId, username, email
  163. inviteUserToBoard(username, boardId) {
  164. check(username, String);
  165. check(boardId, String);
  166. const inviter = Meteor.user();
  167. const board = Boards.findOne(boardId);
  168. const allowInvite = inviter &&
  169. board &&
  170. board.members &&
  171. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  172. _.where(board.members, {userId: inviter._id})[0].isActive &&
  173. _.where(board.members, {userId: inviter._id})[0].isAdmin;
  174. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  175. this.unblock();
  176. const posAt = username.indexOf('@');
  177. let user = null;
  178. if (posAt>=0) {
  179. user = Users.findOne({emails: {$elemMatch: {address: username}}});
  180. } else {
  181. user = Users.findOne(username) || Users.findOne({ username });
  182. }
  183. if (user) {
  184. if (user._id === inviter._id) throw new Meteor.Error('error-user-notAllowSelf');
  185. } else {
  186. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  187. const email = username;
  188. username = email.substring(0, posAt);
  189. const newUserId = Accounts.createUser({ username, email });
  190. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  191. // assume new user speak same language with inviter
  192. if (inviter.profile && inviter.profile.language) {
  193. Users.update(newUserId, {
  194. $set: {
  195. 'profile.language': inviter.profile.language,
  196. },
  197. });
  198. }
  199. Accounts.sendEnrollmentEmail(newUserId);
  200. user = Users.findOne(newUserId);
  201. }
  202. board.addMember(user._id);
  203. user.addInvite(boardId);
  204. try {
  205. const params = {
  206. user: user.username,
  207. inviter: inviter.username,
  208. board: board.title,
  209. url: board.absoluteUrl(),
  210. };
  211. const lang = user.getLanguage();
  212. Email.send({
  213. to: user.emails[0].address,
  214. from: Accounts.emailTemplates.from,
  215. subject: TAPi18n.__('email-invite-subject', params, lang),
  216. text: TAPi18n.__('email-invite-text', params, lang),
  217. });
  218. } catch (e) {
  219. throw new Meteor.Error('email-fail', e.message);
  220. }
  221. return { username: user.username, email: user.emails[0].address };
  222. },
  223. });
  224. }
  225. Users.before.insert((userId, doc) => {
  226. doc.profile = doc.profile || {};
  227. if (!doc.username && doc.profile.name) {
  228. doc.username = doc.profile.name.toLowerCase().replace(/\s/g, '');
  229. }
  230. });
  231. if (Meteor.isServer) {
  232. // Let mongoDB ensure username unicity
  233. Meteor.startup(() => {
  234. Users._collection._ensureIndex({
  235. username: 1,
  236. }, { unique: true });
  237. });
  238. // Each board document contains the de-normalized number of users that have
  239. // starred it. If the user star or unstar a board, we need to update this
  240. // counter.
  241. // We need to run this code on the server only, otherwise the incrementation
  242. // will be done twice.
  243. Users.after.update(function(userId, user, fieldNames) {
  244. // The `starredBoards` list is hosted on the `profile` field. If this
  245. // field hasn't been modificated we don't need to run this hook.
  246. if (!_.contains(fieldNames, 'profile'))
  247. return;
  248. // To calculate a diff of board starred ids, we get both the previous
  249. // and the newly board ids list
  250. function getStarredBoardsIds(doc) {
  251. return doc.profile && doc.profile.starredBoards;
  252. }
  253. const oldIds = getStarredBoardsIds(this.previous);
  254. const newIds = getStarredBoardsIds(user);
  255. // The _.difference(a, b) method returns the values from a that are not in
  256. // b. We use it to find deleted and newly inserted ids by using it in one
  257. // direction and then in the other.
  258. function incrementBoards(boardsIds, inc) {
  259. boardsIds.forEach((boardId) => {
  260. Boards.update(boardId, {$inc: {stars: inc}});
  261. });
  262. }
  263. incrementBoards(_.difference(oldIds, newIds), -1);
  264. incrementBoards(_.difference(newIds, oldIds), +1);
  265. });
  266. // XXX i18n
  267. Users.after.insert((userId, doc) => {
  268. const ExampleBoard = {
  269. title: 'Welcome Board',
  270. userId: doc._id,
  271. permission: 'private',
  272. };
  273. // Insert the Welcome Board
  274. Boards.insert(ExampleBoard, (err, boardId) => {
  275. ['Basics', 'Advanced'].forEach((title) => {
  276. const list = {
  277. title,
  278. boardId,
  279. userId: ExampleBoard.userId,
  280. // XXX Not certain this is a bug, but we except these fields get
  281. // inserted by the Lists.before.insert collection-hook. Since this
  282. // hook is not called in this case, we have to dublicate the logic and
  283. // set them here.
  284. archived: false,
  285. createdAt: new Date(),
  286. };
  287. Lists.insert(list);
  288. });
  289. });
  290. });
  291. }