users.js 9.9 KB

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