users.js 10 KB

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