users.js 17 KB

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