2
0

users.js 16 KB

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