users.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. // Sandstorm context is detected using the METEOR_SETTINGS environment variable
  2. // in the package definition.
  3. const isSandstorm = Meteor.settings && Meteor.settings.public &&
  4. Meteor.settings.public.sandstorm;
  5. Users = Meteor.users;
  6. Users.attachSchema(new SimpleSchema({
  7. username: {
  8. type: String,
  9. optional: true,
  10. autoValue() { // eslint-disable-line consistent-return
  11. if (this.isInsert && !this.isSet) {
  12. const name = this.field('profile.fullname');
  13. if (name.isSet) {
  14. return name.value.toLowerCase().replace(/\s/g, '');
  15. }
  16. }
  17. },
  18. },
  19. emails: {
  20. type: [Object],
  21. optional: true,
  22. },
  23. 'emails.$.address': {
  24. type: String,
  25. regEx: SimpleSchema.RegEx.Email,
  26. },
  27. 'emails.$.verified': {
  28. type: Boolean,
  29. },
  30. createdAt: {
  31. type: Date,
  32. autoValue() { // eslint-disable-line consistent-return
  33. if (this.isInsert) {
  34. return new Date();
  35. } else {
  36. this.unset();
  37. }
  38. },
  39. },
  40. profile: {
  41. type: Object,
  42. optional: true,
  43. autoValue() { // eslint-disable-line consistent-return
  44. if (this.isInsert && !this.isSet) {
  45. return {};
  46. }
  47. },
  48. },
  49. 'profile.avatarUrl': {
  50. type: String,
  51. optional: true,
  52. },
  53. 'profile.emailBuffer': {
  54. type: [String],
  55. optional: true,
  56. },
  57. 'profile.fullname': {
  58. type: String,
  59. optional: true,
  60. },
  61. 'profile.hiddenSystemMessages': {
  62. type: Boolean,
  63. optional: true,
  64. },
  65. 'profile.initials': {
  66. type: String,
  67. optional: true,
  68. },
  69. 'profile.invitedBoards': {
  70. type: [String],
  71. optional: true,
  72. },
  73. 'profile.language': {
  74. type: String,
  75. optional: true,
  76. },
  77. 'profile.notifications': {
  78. type: [String],
  79. optional: true,
  80. },
  81. 'profile.showCardsCountAt': {
  82. type: Number,
  83. optional: true,
  84. },
  85. 'profile.starredBoards': {
  86. type: [String],
  87. optional: true,
  88. },
  89. 'profile.tags': {
  90. type: [String],
  91. optional: true,
  92. },
  93. 'profile.icode': {
  94. type: String,
  95. optional: true,
  96. },
  97. services: {
  98. type: Object,
  99. optional: true,
  100. blackbox: true,
  101. },
  102. heartbeat: {
  103. type: Date,
  104. optional: true,
  105. },
  106. }));
  107. // Search a user in the complete server database by its name or username. This
  108. // is used for instance to add a new user to a board.
  109. const searchInFields = ['username', 'profile.fullname'];
  110. Users.initEasySearch(searchInFields, {
  111. use: 'mongo-db',
  112. returnFields: [...searchInFields, 'profile.avatarUrl'],
  113. });
  114. if (Meteor.isClient) {
  115. Users.helpers({
  116. isBoardMember() {
  117. const board = Boards.findOne(Session.get('currentBoard'));
  118. return board && board.hasMember(this._id);
  119. },
  120. isNotCommentOnly() {
  121. const board = Boards.findOne(Session.get('currentBoard'));
  122. return board && board.hasMember(this._id) && !board.hasCommentOnly(this._id);
  123. },
  124. isCommentOnly() {
  125. const board = Boards.findOne(Session.get('currentBoard'));
  126. return board && board.hasCommentOnly(this._id);
  127. },
  128. isBoardAdmin() {
  129. const board = Boards.findOne(Session.get('currentBoard'));
  130. return board && board.hasAdmin(this._id);
  131. },
  132. });
  133. }
  134. Users.helpers({
  135. boards() {
  136. return Boards.find({ userId: this._id });
  137. },
  138. starredBoards() {
  139. const {starredBoards = []} = this.profile;
  140. return Boards.find({archived: false, _id: {$in: starredBoards}});
  141. },
  142. hasStarred(boardId) {
  143. const {starredBoards = []} = this.profile;
  144. return _.contains(starredBoards, boardId);
  145. },
  146. invitedBoards() {
  147. const {invitedBoards = []} = this.profile;
  148. return Boards.find({archived: false, _id: {$in: invitedBoards}});
  149. },
  150. isInvitedTo(boardId) {
  151. const {invitedBoards = []} = this.profile;
  152. return _.contains(invitedBoards, boardId);
  153. },
  154. hasTag(tag) {
  155. const {tags = []} = this.profile;
  156. return _.contains(tags, tag);
  157. },
  158. hasNotification(activityId) {
  159. const {notifications = []} = this.profile;
  160. return _.contains(notifications, activityId);
  161. },
  162. hasHiddenSystemMessages() {
  163. const profile = this.profile || {};
  164. return profile.hiddenSystemMessages || false;
  165. },
  166. getEmailBuffer() {
  167. const {emailBuffer = []} = this.profile;
  168. return emailBuffer;
  169. },
  170. getInitials() {
  171. const profile = this.profile || {};
  172. if (profile.initials)
  173. return profile.initials;
  174. else if (profile.fullname) {
  175. return profile.fullname.split(/\s+/).reduce((memo, word) => {
  176. return memo + word[0];
  177. }, '').toUpperCase();
  178. } else {
  179. return this.username[0].toUpperCase();
  180. }
  181. },
  182. getLimitToShowCardsCount() {
  183. const profile = this.profile || {};
  184. return profile.showCardsCountAt;
  185. },
  186. getName() {
  187. const profile = this.profile || {};
  188. return profile.fullname || this.username;
  189. },
  190. getLanguage() {
  191. const profile = this.profile || {};
  192. return profile.language || 'en';
  193. },
  194. });
  195. Users.mutations({
  196. toggleBoardStar(boardId) {
  197. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  198. return {
  199. [queryKind]: {
  200. 'profile.starredBoards': boardId,
  201. },
  202. };
  203. },
  204. addInvite(boardId) {
  205. return {
  206. $addToSet: {
  207. 'profile.invitedBoards': boardId,
  208. },
  209. };
  210. },
  211. removeInvite(boardId) {
  212. return {
  213. $pull: {
  214. 'profile.invitedBoards': boardId,
  215. },
  216. };
  217. },
  218. addTag(tag) {
  219. return {
  220. $addToSet: {
  221. 'profile.tags': tag,
  222. },
  223. };
  224. },
  225. removeTag(tag) {
  226. return {
  227. $pull: {
  228. 'profile.tags': tag,
  229. },
  230. };
  231. },
  232. toggleTag(tag) {
  233. if (this.hasTag(tag))
  234. this.removeTag(tag);
  235. else
  236. this.addTag(tag);
  237. },
  238. toggleSystem(value = false) {
  239. return {
  240. $set: {
  241. 'profile.hiddenSystemMessages': !value,
  242. },
  243. };
  244. },
  245. addNotification(activityId) {
  246. return {
  247. $addToSet: {
  248. 'profile.notifications': activityId,
  249. },
  250. };
  251. },
  252. removeNotification(activityId) {
  253. return {
  254. $pull: {
  255. 'profile.notifications': activityId,
  256. },
  257. };
  258. },
  259. addEmailBuffer(text) {
  260. return {
  261. $addToSet: {
  262. 'profile.emailBuffer': text,
  263. },
  264. };
  265. },
  266. clearEmailBuffer() {
  267. return {
  268. $set: {
  269. 'profile.emailBuffer': [],
  270. },
  271. };
  272. },
  273. setAvatarUrl(avatarUrl) {
  274. return { $set: { 'profile.avatarUrl': avatarUrl }};
  275. },
  276. setShowCardsCountAt(limit) {
  277. return { $set: { 'profile.showCardsCountAt': limit } };
  278. },
  279. });
  280. Meteor.methods({
  281. setUsername(username) {
  282. check(username, String);
  283. const nUsersWithUsername = Users.find({ username }).count();
  284. if (nUsersWithUsername > 0) {
  285. throw new Meteor.Error('username-already-taken');
  286. } else {
  287. Users.update(this.userId, {$set: { username }});
  288. }
  289. },
  290. toggleSystemMessages() {
  291. const user = Meteor.user();
  292. user.toggleSystem(user.hasHiddenSystemMessages());
  293. },
  294. changeLimitToShowCardsCount(limit) {
  295. check(limit, Number);
  296. Meteor.user().setShowCardsCountAt(limit);
  297. },
  298. });
  299. if (Meteor.isServer) {
  300. Meteor.methods({
  301. // we accept userId, username, email
  302. inviteUserToBoard(username, boardId) {
  303. check(username, String);
  304. check(boardId, String);
  305. const inviter = Meteor.user();
  306. const board = Boards.findOne(boardId);
  307. const allowInvite = inviter &&
  308. board &&
  309. board.members &&
  310. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  311. _.where(board.members, {userId: inviter._id})[0].isActive &&
  312. _.where(board.members, {userId: inviter._id})[0].isAdmin;
  313. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  314. this.unblock();
  315. const posAt = username.indexOf('@');
  316. let user = null;
  317. if (posAt>=0) {
  318. user = Users.findOne({emails: {$elemMatch: {address: username}}});
  319. } else {
  320. user = Users.findOne(username) || Users.findOne({ username });
  321. }
  322. if (user) {
  323. if (user._id === inviter._id) throw new Meteor.Error('error-user-notAllowSelf');
  324. } else {
  325. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  326. if (Settings.findOne().disableRegistration) throw new Meteor.Error('error-user-notCreated');
  327. // Set in lowercase email before creating account
  328. const email = username.toLowerCase();
  329. username = email.substring(0, posAt);
  330. const newUserId = Accounts.createUser({ username, email });
  331. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  332. // assume new user speak same language with inviter
  333. if (inviter.profile && inviter.profile.language) {
  334. Users.update(newUserId, {
  335. $set: {
  336. 'profile.language': inviter.profile.language,
  337. },
  338. });
  339. }
  340. Accounts.sendEnrollmentEmail(newUserId);
  341. user = Users.findOne(newUserId);
  342. }
  343. board.addMember(user._id);
  344. user.addInvite(boardId);
  345. try {
  346. const params = {
  347. user: user.username,
  348. inviter: inviter.username,
  349. board: board.title,
  350. url: board.absoluteUrl(),
  351. };
  352. const lang = user.getLanguage();
  353. Email.send({
  354. to: user.emails[0].address.toLowerCase(),
  355. from: Accounts.emailTemplates.from,
  356. subject: TAPi18n.__('email-invite-subject', params, lang),
  357. text: TAPi18n.__('email-invite-text', params, lang),
  358. });
  359. } catch (e) {
  360. throw new Meteor.Error('email-fail', e.message);
  361. }
  362. return { username: user.username, email: user.emails[0].address };
  363. },
  364. });
  365. Accounts.onCreateUser((options, user) => {
  366. const userCount = Users.find().count();
  367. if (userCount === 0){
  368. user.isAdmin = true;
  369. return user;
  370. }
  371. const disableRegistration = Settings.findOne().disableRegistration;
  372. if (!disableRegistration) {
  373. return user;
  374. }
  375. if (!options || !options.profile) {
  376. throw new Meteor.Error('error-invitation-code-blank', 'The invitation code is required');
  377. }
  378. const invitationCode = InvitationCodes.findOne({code: options.profile.invitationcode, email: options.email, valid: true});
  379. if (!invitationCode) {
  380. throw new Meteor.Error('error-invitation-code-not-exist', 'The invitation code doesn\'t exist');
  381. }else{
  382. user.profile = {icode: options.profile.invitationcode};
  383. }
  384. return user;
  385. });
  386. }
  387. if (Meteor.isServer) {
  388. // Let mongoDB ensure username unicity
  389. Meteor.startup(() => {
  390. Users._collection._ensureIndex({
  391. username: 1,
  392. }, { unique: true });
  393. });
  394. // Each board document contains the de-normalized number of users that have
  395. // starred it. If the user star or unstar a board, we need to update this
  396. // counter.
  397. // We need to run this code on the server only, otherwise the incrementation
  398. // will be done twice.
  399. Users.after.update(function(userId, user, fieldNames) {
  400. // The `starredBoards` list is hosted on the `profile` field. If this
  401. // field hasn't been modificated we don't need to run this hook.
  402. if (!_.contains(fieldNames, 'profile'))
  403. return;
  404. // To calculate a diff of board starred ids, we get both the previous
  405. // and the newly board ids list
  406. function getStarredBoardsIds(doc) {
  407. return doc.profile && doc.profile.starredBoards;
  408. }
  409. const oldIds = getStarredBoardsIds(this.previous);
  410. const newIds = getStarredBoardsIds(user);
  411. // The _.difference(a, b) method returns the values from a that are not in
  412. // b. We use it to find deleted and newly inserted ids by using it in one
  413. // direction and then in the other.
  414. function incrementBoards(boardsIds, inc) {
  415. boardsIds.forEach((boardId) => {
  416. Boards.update(boardId, {$inc: {stars: inc}});
  417. });
  418. }
  419. incrementBoards(_.difference(oldIds, newIds), -1);
  420. incrementBoards(_.difference(newIds, oldIds), +1);
  421. });
  422. const fakeUserId = new Meteor.EnvironmentVariable();
  423. const getUserId = CollectionHooks.getUserId;
  424. CollectionHooks.getUserId = () => {
  425. return fakeUserId.get() || getUserId();
  426. };
  427. if (!isSandstorm) {
  428. Users.after.insert((userId, doc) => {
  429. const fakeUser = {
  430. extendAutoValueContext: {
  431. userId: doc._id,
  432. },
  433. };
  434. fakeUserId.withValue(doc._id, () => {
  435. // Insert the Welcome Board
  436. Boards.insert({
  437. title: TAPi18n.__('welcome-board'),
  438. permission: 'private',
  439. }, fakeUser, (err, boardId) => {
  440. ['welcome-list1', 'welcome-list2'].forEach((title) => {
  441. Lists.insert({ title: TAPi18n.__(title), boardId }, fakeUser);
  442. });
  443. });
  444. });
  445. });
  446. }
  447. Users.after.insert((userId, doc) => {
  448. //invite user to corresponding boards
  449. const disableRegistration = Settings.findOne().disableRegistration;
  450. if (disableRegistration) {
  451. const invitationCode = InvitationCodes.findOne({code: doc.profile.icode, valid:true});
  452. if (!invitationCode) {
  453. throw new Meteor.Error('error-invitation-code-not-exist');
  454. }else{
  455. invitationCode.boardsToBeInvited.forEach((boardId) => {
  456. const board = Boards.findOne(boardId);
  457. board.addMember(doc._id);
  458. });
  459. if (!doc.profile) {
  460. doc.profile = {};
  461. }
  462. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  463. Users.update(doc._id, {$set:{profile: doc.profile}});
  464. InvitationCodes.update(invitationCode._id, {$set: {valid:false}});
  465. }
  466. }
  467. });
  468. }