users.js 13 KB

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