users.js 13 KB

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