users.js 12 KB

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