users.js 11 KB

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