users.js 13 KB

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