users.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  1. import { SyncedCron } from 'meteor/percolate:synced-cron';
  2. // Sandstorm context is detected using the METEOR_SETTINGS environment variable
  3. // in the package definition.
  4. const isSandstorm =
  5. Meteor.settings && Meteor.settings.public && Meteor.settings.public.sandstorm;
  6. Users = Meteor.users;
  7. const allowedSortValues = [
  8. '-modifiedAt',
  9. 'modifiedAt',
  10. '-title',
  11. 'title',
  12. '-sort',
  13. 'sort',
  14. ];
  15. const defaultSortBy = allowedSortValues[0];
  16. /**
  17. * A User in wekan
  18. */
  19. Users.attachSchema(
  20. new SimpleSchema({
  21. username: {
  22. /**
  23. * the username of the user
  24. */
  25. type: String,
  26. optional: true,
  27. // eslint-disable-next-line consistent-return
  28. autoValue() {
  29. if (this.isInsert && !this.isSet) {
  30. const name = this.field('profile.fullname');
  31. if (name.isSet) {
  32. return name.value.toLowerCase().replace(/\s/g, '');
  33. }
  34. }
  35. },
  36. },
  37. emails: {
  38. /**
  39. * the list of emails attached to a user
  40. */
  41. type: [Object],
  42. optional: true,
  43. },
  44. 'emails.$.address': {
  45. /**
  46. * The email address
  47. */
  48. type: String,
  49. regEx: SimpleSchema.RegEx.Email,
  50. },
  51. 'emails.$.verified': {
  52. /**
  53. * Has the email been verified
  54. */
  55. type: Boolean,
  56. },
  57. createdAt: {
  58. /**
  59. * creation date of the user
  60. */
  61. type: Date,
  62. // eslint-disable-next-line consistent-return
  63. autoValue() {
  64. if (this.isInsert) {
  65. return new Date();
  66. } else if (this.isUpsert) {
  67. return { $setOnInsert: new Date() };
  68. } else {
  69. this.unset();
  70. }
  71. },
  72. },
  73. modifiedAt: {
  74. type: Date,
  75. denyUpdate: false,
  76. // eslint-disable-next-line consistent-return
  77. autoValue() {
  78. if (this.isInsert || this.isUpsert || this.isUpdate) {
  79. return new Date();
  80. } else {
  81. this.unset();
  82. }
  83. },
  84. },
  85. profile: {
  86. /**
  87. * profile settings
  88. */
  89. type: Object,
  90. optional: true,
  91. // eslint-disable-next-line consistent-return
  92. autoValue() {
  93. if (this.isInsert && !this.isSet) {
  94. return {
  95. boardView: 'board-view-lists',
  96. };
  97. }
  98. },
  99. },
  100. 'profile.avatarUrl': {
  101. /**
  102. * URL of the avatar of the user
  103. */
  104. type: String,
  105. optional: true,
  106. },
  107. 'profile.emailBuffer': {
  108. /**
  109. * list of email buffers of the user
  110. */
  111. type: [String],
  112. optional: true,
  113. },
  114. 'profile.fullname': {
  115. /**
  116. * full name of the user
  117. */
  118. type: String,
  119. optional: true,
  120. },
  121. 'profile.showDesktopDragHandles': {
  122. /**
  123. * does the user want to hide system messages?
  124. */
  125. type: Boolean,
  126. optional: true,
  127. },
  128. 'profile.hiddenSystemMessages': {
  129. /**
  130. * does the user want to hide system messages?
  131. */
  132. type: Boolean,
  133. optional: true,
  134. },
  135. 'profile.hiddenMinicardLabelText': {
  136. /**
  137. * does the user want to hide minicard label texts?
  138. */
  139. type: Boolean,
  140. optional: true,
  141. },
  142. 'profile.initials': {
  143. /**
  144. * initials of the user
  145. */
  146. type: String,
  147. optional: true,
  148. },
  149. 'profile.invitedBoards': {
  150. /**
  151. * board IDs the user has been invited to
  152. */
  153. type: [String],
  154. optional: true,
  155. },
  156. 'profile.language': {
  157. /**
  158. * language of the user
  159. */
  160. type: String,
  161. optional: true,
  162. },
  163. 'profile.notifications': {
  164. /**
  165. * enabled notifications for the user
  166. */
  167. type: [Object],
  168. optional: true,
  169. },
  170. 'profile.notifications.$.activity': {
  171. /**
  172. * The id of the activity this notification references
  173. */
  174. type: String,
  175. },
  176. 'profile.notifications.$.read': {
  177. /**
  178. * the date on which this notification was read
  179. */
  180. type: Date,
  181. optional: true,
  182. },
  183. 'profile.showCardsCountAt': {
  184. /**
  185. * showCardCountAt field of the user
  186. */
  187. type: Number,
  188. optional: true,
  189. },
  190. 'profile.starredBoards': {
  191. /**
  192. * list of starred board IDs
  193. */
  194. type: [String],
  195. optional: true,
  196. },
  197. 'profile.icode': {
  198. /**
  199. * icode
  200. */
  201. type: String,
  202. optional: true,
  203. },
  204. 'profile.boardView': {
  205. /**
  206. * boardView field of the user
  207. */
  208. type: String,
  209. optional: true,
  210. allowedValues: [
  211. 'board-view-lists',
  212. 'board-view-swimlanes',
  213. 'board-view-cal',
  214. ],
  215. },
  216. 'profile.listSortBy': {
  217. /**
  218. * default sort list for user
  219. */
  220. type: String,
  221. optional: true,
  222. defaultValue: defaultSortBy,
  223. allowedValues: allowedSortValues,
  224. },
  225. 'profile.templatesBoardId': {
  226. /**
  227. * Reference to the templates board
  228. */
  229. type: String,
  230. defaultValue: '',
  231. },
  232. 'profile.cardTemplatesSwimlaneId': {
  233. /**
  234. * Reference to the card templates swimlane Id
  235. */
  236. type: String,
  237. defaultValue: '',
  238. },
  239. 'profile.listTemplatesSwimlaneId': {
  240. /**
  241. * Reference to the list templates swimlane Id
  242. */
  243. type: String,
  244. defaultValue: '',
  245. },
  246. 'profile.boardTemplatesSwimlaneId': {
  247. /**
  248. * Reference to the board templates swimlane Id
  249. */
  250. type: String,
  251. defaultValue: '',
  252. },
  253. services: {
  254. /**
  255. * services field of the user
  256. */
  257. type: Object,
  258. optional: true,
  259. blackbox: true,
  260. },
  261. heartbeat: {
  262. /**
  263. * last time the user has been seen
  264. */
  265. type: Date,
  266. optional: true,
  267. },
  268. isAdmin: {
  269. /**
  270. * is the user an admin of the board?
  271. */
  272. type: Boolean,
  273. optional: true,
  274. },
  275. createdThroughApi: {
  276. /**
  277. * was the user created through the API?
  278. */
  279. type: Boolean,
  280. optional: true,
  281. },
  282. loginDisabled: {
  283. /**
  284. * loginDisabled field of the user
  285. */
  286. type: Boolean,
  287. optional: true,
  288. },
  289. authenticationMethod: {
  290. /**
  291. * authentication method of the user
  292. */
  293. type: String,
  294. optional: false,
  295. defaultValue: 'password',
  296. },
  297. }),
  298. );
  299. Users.allow({
  300. update(userId, doc) {
  301. const user = Users.findOne({ _id: userId });
  302. if ((user && user.isAdmin) || (Meteor.user() && Meteor.user().isAdmin))
  303. return true;
  304. if (!user) {
  305. return false;
  306. }
  307. return doc._id === userId;
  308. },
  309. remove(userId, doc) {
  310. const adminsNumber = Users.find({ isAdmin: true }).count();
  311. const { isAdmin } = Users.findOne(
  312. { _id: userId },
  313. { fields: { isAdmin: 1 } },
  314. );
  315. // Prevents remove of the only one administrator
  316. if (adminsNumber === 1 && isAdmin && userId === doc._id) {
  317. return false;
  318. }
  319. // If it's the user or an admin
  320. return userId === doc._id || isAdmin;
  321. },
  322. fetch: [],
  323. });
  324. // Search a user in the complete server database by its name or username. This
  325. // is used for instance to add a new user to a board.
  326. const searchInFields = ['username', 'profile.fullname'];
  327. Users.initEasySearch(searchInFields, {
  328. use: 'mongo-db',
  329. returnFields: [...searchInFields, 'profile.avatarUrl'],
  330. });
  331. if (Meteor.isClient) {
  332. Users.helpers({
  333. isBoardMember() {
  334. const board = Boards.findOne(Session.get('currentBoard'));
  335. return board && board.hasMember(this._id);
  336. },
  337. isNotNoComments() {
  338. const board = Boards.findOne(Session.get('currentBoard'));
  339. return (
  340. board && board.hasMember(this._id) && !board.hasNoComments(this._id)
  341. );
  342. },
  343. isNoComments() {
  344. const board = Boards.findOne(Session.get('currentBoard'));
  345. return board && board.hasNoComments(this._id);
  346. },
  347. isNotCommentOnly() {
  348. const board = Boards.findOne(Session.get('currentBoard'));
  349. return (
  350. board && board.hasMember(this._id) && !board.hasCommentOnly(this._id)
  351. );
  352. },
  353. isCommentOnly() {
  354. const board = Boards.findOne(Session.get('currentBoard'));
  355. return board && board.hasCommentOnly(this._id);
  356. },
  357. isNotWorker() {
  358. const board = Boards.findOne(Session.get('currentBoard'));
  359. return board && board.hasMember(this._id) && !board.hasWorker(this._id);
  360. },
  361. isWorker() {
  362. const board = Boards.findOne(Session.get('currentBoard'));
  363. return board && board.hasWorker(this._id);
  364. },
  365. isBoardAdmin() {
  366. const board = Boards.findOne(Session.get('currentBoard'));
  367. return board && board.hasAdmin(this._id);
  368. },
  369. });
  370. }
  371. Users.helpers({
  372. boards() {
  373. return Boards.find({ 'members.userId': this._id });
  374. },
  375. starredBoards() {
  376. const { starredBoards = [] } = this.profile || {};
  377. return Boards.find({ archived: false, _id: { $in: starredBoards } });
  378. },
  379. hasStarred(boardId) {
  380. const { starredBoards = [] } = this.profile || {};
  381. return _.contains(starredBoards, boardId);
  382. },
  383. invitedBoards() {
  384. const { invitedBoards = [] } = this.profile || {};
  385. return Boards.find({ archived: false, _id: { $in: invitedBoards } });
  386. },
  387. isInvitedTo(boardId) {
  388. const { invitedBoards = [] } = this.profile || {};
  389. return _.contains(invitedBoards, boardId);
  390. },
  391. _getListSortBy() {
  392. const profile = this.profile || {};
  393. const sortBy = profile.listSortBy || defaultSortBy;
  394. const keyPattern = /^(-{0,1})(.*$)/;
  395. const ret = [];
  396. if (keyPattern.exec(sortBy)) {
  397. ret[0] = RegExp.$2;
  398. ret[1] = RegExp.$1 ? -1 : 1;
  399. }
  400. return ret;
  401. },
  402. hasSortBy() {
  403. // if use doesn't have dragHandle, then we can let user to choose sort list by different order
  404. return !this.hasShowDesktopDragHandles();
  405. },
  406. getListSortBy() {
  407. return this._getListSortBy()[0];
  408. },
  409. getListSortTypes() {
  410. return allowedSortValues;
  411. },
  412. getListSortByDirection() {
  413. return this._getListSortBy()[1];
  414. },
  415. hasTag(tag) {
  416. const { tags = [] } = this.profile || {};
  417. return _.contains(tags, tag);
  418. },
  419. hasNotification(activityId) {
  420. const { notifications = [] } = this.profile || {};
  421. return _.contains(notifications, activityId);
  422. },
  423. notifications() {
  424. const { notifications = [] } = this.profile || {};
  425. for (const index in notifications) {
  426. if (!notifications.hasOwnProperty(index)) continue;
  427. const notification = notifications[index];
  428. // this preserves their db sort order for editing
  429. notification.dbIndex = index;
  430. notification.activity = Activities.findOne(notification.activity);
  431. }
  432. // this sorts them newest to oldest to match Trello's behavior
  433. notifications.reverse();
  434. return notifications;
  435. },
  436. hasShowDesktopDragHandles() {
  437. const profile = this.profile || {};
  438. return profile.showDesktopDragHandles || false;
  439. },
  440. hasHiddenSystemMessages() {
  441. const profile = this.profile || {};
  442. return profile.hiddenSystemMessages || false;
  443. },
  444. hasHiddenMinicardLabelText() {
  445. const profile = this.profile || {};
  446. return profile.hiddenMinicardLabelText || false;
  447. },
  448. getEmailBuffer() {
  449. const { emailBuffer = [] } = this.profile || {};
  450. return emailBuffer;
  451. },
  452. getInitials() {
  453. const profile = this.profile || {};
  454. if (profile.initials) return profile.initials;
  455. else if (profile.fullname) {
  456. return profile.fullname
  457. .split(/\s+/)
  458. .reduce((memo, word) => {
  459. return memo + word[0];
  460. }, '')
  461. .toUpperCase();
  462. } else {
  463. return this.username[0].toUpperCase();
  464. }
  465. },
  466. getLimitToShowCardsCount() {
  467. const profile = this.profile || {};
  468. return profile.showCardsCountAt;
  469. },
  470. getName() {
  471. const profile = this.profile || {};
  472. return profile.fullname || this.username;
  473. },
  474. getLanguage() {
  475. const profile = this.profile || {};
  476. return profile.language || 'en';
  477. },
  478. getTemplatesBoardId() {
  479. return (this.profile || {}).templatesBoardId;
  480. },
  481. getTemplatesBoardSlug() {
  482. return (Boards.findOne((this.profile || {}).templatesBoardId) || {}).slug;
  483. },
  484. remove() {
  485. User.remove({ _id: this._id });
  486. },
  487. });
  488. Users.mutations({
  489. toggleBoardStar(boardId) {
  490. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  491. return {
  492. [queryKind]: {
  493. 'profile.starredBoards': boardId,
  494. },
  495. };
  496. },
  497. addInvite(boardId) {
  498. return {
  499. $addToSet: {
  500. 'profile.invitedBoards': boardId,
  501. },
  502. };
  503. },
  504. removeInvite(boardId) {
  505. return {
  506. $pull: {
  507. 'profile.invitedBoards': boardId,
  508. },
  509. };
  510. },
  511. addTag(tag) {
  512. return {
  513. $addToSet: {
  514. 'profile.tags': tag,
  515. },
  516. };
  517. },
  518. removeTag(tag) {
  519. return {
  520. $pull: {
  521. 'profile.tags': tag,
  522. },
  523. };
  524. },
  525. toggleTag(tag) {
  526. if (this.hasTag(tag)) this.removeTag(tag);
  527. else this.addTag(tag);
  528. },
  529. setListSortBy(value) {
  530. return {
  531. $set: {
  532. 'profile.listSortBy': value,
  533. },
  534. };
  535. },
  536. toggleDesktopHandles(value = false) {
  537. return {
  538. $set: {
  539. 'profile.showDesktopDragHandles': !value,
  540. },
  541. };
  542. },
  543. toggleSystem(value = false) {
  544. return {
  545. $set: {
  546. 'profile.hiddenSystemMessages': !value,
  547. },
  548. };
  549. },
  550. toggleLabelText(value = false) {
  551. return {
  552. $set: {
  553. 'profile.hiddenMinicardLabelText': !value,
  554. },
  555. };
  556. },
  557. addNotification(activityId) {
  558. return {
  559. $addToSet: {
  560. 'profile.notifications': { activity: activityId },
  561. },
  562. };
  563. },
  564. removeNotification(activityId) {
  565. return {
  566. $pull: {
  567. 'profile.notifications': { activity: activityId },
  568. },
  569. };
  570. },
  571. addEmailBuffer(text) {
  572. return {
  573. $addToSet: {
  574. 'profile.emailBuffer': text,
  575. },
  576. };
  577. },
  578. clearEmailBuffer() {
  579. return {
  580. $set: {
  581. 'profile.emailBuffer': [],
  582. },
  583. };
  584. },
  585. setAvatarUrl(avatarUrl) {
  586. return { $set: { 'profile.avatarUrl': avatarUrl } };
  587. },
  588. setShowCardsCountAt(limit) {
  589. return { $set: { 'profile.showCardsCountAt': limit } };
  590. },
  591. setBoardView(view) {
  592. return {
  593. $set: {
  594. 'profile.boardView': view,
  595. },
  596. };
  597. },
  598. });
  599. Meteor.methods({
  600. setListSortBy(value) {
  601. check(value, String);
  602. Meteor.user().setListSortBy(value);
  603. },
  604. toggleDesktopDragHandles() {
  605. const user = Meteor.user();
  606. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  607. },
  608. toggleSystemMessages() {
  609. const user = Meteor.user();
  610. user.toggleSystem(user.hasHiddenSystemMessages());
  611. },
  612. toggleMinicardLabelText() {
  613. const user = Meteor.user();
  614. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  615. },
  616. changeLimitToShowCardsCount(limit) {
  617. check(limit, Number);
  618. Meteor.user().setShowCardsCountAt(limit);
  619. },
  620. });
  621. if (Meteor.isServer) {
  622. Meteor.methods({
  623. setCreateUser(fullname, username, password, isAdmin, isActive, email) {
  624. if (Meteor.user() && Meteor.user().isAdmin) {
  625. check(fullname, String);
  626. check(username, String);
  627. check(password, String);
  628. check(isAdmin, String);
  629. check(isActive, String);
  630. check(email, String);
  631. const nUsersWithUsername = Users.find({ username }).count();
  632. const nUsersWithEmail = Users.find({ email }).count();
  633. if (nUsersWithUsername > 0) {
  634. throw new Meteor.Error('username-already-taken');
  635. } else if (nUsersWithEmail > 0) {
  636. throw new Meteor.Error('email-already-taken');
  637. } else {
  638. Accounts.createUser({
  639. fullname,
  640. username,
  641. password,
  642. isAdmin,
  643. isActive,
  644. email: email.toLowerCase(),
  645. from: 'admin',
  646. });
  647. }
  648. }
  649. },
  650. setUsername(username, userId) {
  651. if (Meteor.user() && Meteor.user().isAdmin) {
  652. check(username, String);
  653. check(userId, String);
  654. const nUsersWithUsername = Users.find({ username }).count();
  655. if (nUsersWithUsername > 0) {
  656. throw new Meteor.Error('username-already-taken');
  657. } else {
  658. Users.update(userId, { $set: { username } });
  659. }
  660. }
  661. },
  662. setEmail(email, userId) {
  663. if (Meteor.user() && Meteor.user().isAdmin) {
  664. if (Array.isArray(email)) {
  665. email = email.shift();
  666. }
  667. check(email, String);
  668. const existingUser = Users.findOne(
  669. { 'emails.address': email },
  670. { fields: { _id: 1 } },
  671. );
  672. if (existingUser) {
  673. throw new Meteor.Error('email-already-taken');
  674. } else {
  675. Users.update(userId, {
  676. $set: {
  677. emails: [
  678. {
  679. address: email,
  680. verified: false,
  681. },
  682. ],
  683. },
  684. });
  685. }
  686. }
  687. },
  688. setUsernameAndEmail(username, email, userId) {
  689. if (Meteor.user() && Meteor.user().isAdmin) {
  690. check(username, String);
  691. if (Array.isArray(email)) {
  692. email = email.shift();
  693. }
  694. check(email, String);
  695. check(userId, String);
  696. Meteor.call('setUsername', username, userId);
  697. Meteor.call('setEmail', email, userId);
  698. }
  699. },
  700. setPassword(newPassword, userId) {
  701. if (Meteor.user() && Meteor.user().isAdmin) {
  702. check(userId, String);
  703. check(newPassword, String);
  704. if (Meteor.user().isAdmin) {
  705. Accounts.setPassword(userId, newPassword);
  706. }
  707. }
  708. },
  709. // we accept userId, username, email
  710. inviteUserToBoard(username, boardId) {
  711. check(username, String);
  712. check(boardId, String);
  713. const inviter = Meteor.user();
  714. const board = Boards.findOne(boardId);
  715. const allowInvite =
  716. inviter &&
  717. board &&
  718. board.members &&
  719. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  720. _.where(board.members, { userId: inviter._id })[0].isActive;
  721. // GitHub issue 2060
  722. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  723. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  724. this.unblock();
  725. const posAt = username.indexOf('@');
  726. let user = null;
  727. if (posAt >= 0) {
  728. user = Users.findOne({ emails: { $elemMatch: { address: username } } });
  729. } else {
  730. user = Users.findOne(username) || Users.findOne({ username });
  731. }
  732. if (user) {
  733. if (user._id === inviter._id)
  734. throw new Meteor.Error('error-user-notAllowSelf');
  735. } else {
  736. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  737. if (Settings.findOne({ disableRegistration: true })) {
  738. throw new Meteor.Error('error-user-notCreated');
  739. }
  740. // Set in lowercase email before creating account
  741. const email = username.toLowerCase();
  742. username = email.substring(0, posAt);
  743. const newUserId = Accounts.createUser({ username, email });
  744. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  745. // assume new user speak same language with inviter
  746. if (inviter.profile && inviter.profile.language) {
  747. Users.update(newUserId, {
  748. $set: {
  749. 'profile.language': inviter.profile.language,
  750. },
  751. });
  752. }
  753. Accounts.sendEnrollmentEmail(newUserId);
  754. user = Users.findOne(newUserId);
  755. }
  756. board.addMember(user._id);
  757. user.addInvite(boardId);
  758. try {
  759. const params = {
  760. user: user.username,
  761. inviter: inviter.username,
  762. board: board.title,
  763. url: board.absoluteUrl(),
  764. };
  765. const lang = user.getLanguage();
  766. Email.send({
  767. to: user.emails[0].address.toLowerCase(),
  768. from: Accounts.emailTemplates.from,
  769. subject: TAPi18n.__('email-invite-subject', params, lang),
  770. text: TAPi18n.__('email-invite-text', params, lang),
  771. });
  772. } catch (e) {
  773. throw new Meteor.Error('email-fail', e.message);
  774. }
  775. return { username: user.username, email: user.emails[0].address };
  776. },
  777. });
  778. Accounts.onCreateUser((options, user) => {
  779. const userCount = Users.find().count();
  780. if (userCount === 0) {
  781. user.isAdmin = true;
  782. return user;
  783. }
  784. if (user.services.oidc) {
  785. let email = user.services.oidc.email;
  786. if (Array.isArray(email)) {
  787. email = email.shift();
  788. }
  789. email = email.toLowerCase();
  790. user.username = user.services.oidc.username;
  791. user.emails = [{ address: email, verified: true }];
  792. const initials = user.services.oidc.fullname
  793. .match(/\b[a-zA-Z]/g)
  794. .join('')
  795. .toUpperCase();
  796. user.profile = {
  797. initials,
  798. fullname: user.services.oidc.fullname,
  799. boardView: 'board-view-lists',
  800. };
  801. user.authenticationMethod = 'oauth2';
  802. // see if any existing user has this email address or username, otherwise create new
  803. const existingUser = Meteor.users.findOne({
  804. $or: [{ 'emails.address': email }, { username: user.username }],
  805. });
  806. if (!existingUser) return user;
  807. // copy across new service info
  808. const service = _.keys(user.services)[0];
  809. existingUser.services[service] = user.services[service];
  810. existingUser.emails = user.emails;
  811. existingUser.username = user.username;
  812. existingUser.profile = user.profile;
  813. existingUser.authenticationMethod = user.authenticationMethod;
  814. Meteor.users.remove({ _id: existingUser._id }); // remove existing record
  815. return existingUser;
  816. }
  817. if (options.from === 'admin') {
  818. user.createdThroughApi = true;
  819. return user;
  820. }
  821. const disableRegistration = Settings.findOne().disableRegistration;
  822. // If this is the first Authentication by the ldap and self registration disabled
  823. if (disableRegistration && options && options.ldap) {
  824. user.authenticationMethod = 'ldap';
  825. return user;
  826. }
  827. // If self registration enabled
  828. if (!disableRegistration) {
  829. return user;
  830. }
  831. if (!options || !options.profile) {
  832. throw new Meteor.Error(
  833. 'error-invitation-code-blank',
  834. 'The invitation code is required',
  835. );
  836. }
  837. const invitationCode = InvitationCodes.findOne({
  838. code: options.profile.invitationcode,
  839. email: options.email,
  840. valid: true,
  841. });
  842. if (!invitationCode) {
  843. throw new Meteor.Error(
  844. 'error-invitation-code-not-exist',
  845. // eslint-disable-next-line quotes
  846. "The invitation code doesn't exist",
  847. );
  848. } else {
  849. user.profile = { icode: options.profile.invitationcode };
  850. user.profile.boardView = 'board-view-lists';
  851. // Deletes the invitation code after the user was created successfully.
  852. setTimeout(
  853. Meteor.bindEnvironment(() => {
  854. InvitationCodes.remove({ _id: invitationCode._id });
  855. }),
  856. 200,
  857. );
  858. return user;
  859. }
  860. });
  861. }
  862. const addCronJob = _.debounce(
  863. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  864. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  865. const envRemoveAge = process.env.NOTIFICATION_REMOVAL_AGE;
  866. // default notifications will be removed 2 days after they are read
  867. const defaultRemoveAge = 2;
  868. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  869. SyncedCron.add({
  870. name: 'notification_cleanup',
  871. schedule: parser => parser.text('every 1 days'),
  872. job: () => {
  873. for (const user of Users.find()) {
  874. for (const notification of user.profile.notifications) {
  875. if (notification.read) {
  876. const removeDate = new Date(notification.read);
  877. removeDate.setDate(removeDate.getDate() + removeAge);
  878. if (removeDate <= new Date()) {
  879. user.removeNotification(notification.activity);
  880. }
  881. }
  882. }
  883. }
  884. },
  885. });
  886. SyncedCron.start();
  887. }),
  888. 500,
  889. );
  890. if (Meteor.isServer) {
  891. // Let mongoDB ensure username unicity
  892. Meteor.startup(() => {
  893. allowedSortValues.forEach(value => {
  894. Lists._collection._ensureIndex(value);
  895. });
  896. Users._collection._ensureIndex({ modifiedAt: -1 });
  897. Users._collection._ensureIndex(
  898. {
  899. username: 1,
  900. },
  901. { unique: true },
  902. );
  903. Meteor.defer(() => {
  904. addCronJob();
  905. });
  906. });
  907. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  908. // if admin is removed, board is removed.
  909. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  910. // to use that board, and not have board deleted.
  911. // Someone can be later changed to be admin of board, by making change to database.
  912. // TODO: Add UI for changing someone as board admin.
  913. //Users.before.remove((userId, doc) => {
  914. // Boards
  915. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  916. // .forEach((board) => {
  917. // // If only one admin for the board
  918. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  919. // Boards.remove(board._id);
  920. // }
  921. // });
  922. //});
  923. // Each board document contains the de-normalized number of users that have
  924. // starred it. If the user star or unstar a board, we need to update this
  925. // counter.
  926. // We need to run this code on the server only, otherwise the incrementation
  927. // will be done twice.
  928. Users.after.update(function(userId, user, fieldNames) {
  929. // The `starredBoards` list is hosted on the `profile` field. If this
  930. // field hasn't been modificated we don't need to run this hook.
  931. if (!_.contains(fieldNames, 'profile')) return;
  932. // To calculate a diff of board starred ids, we get both the previous
  933. // and the newly board ids list
  934. function getStarredBoardsIds(doc) {
  935. return doc.profile && doc.profile.starredBoards;
  936. }
  937. const oldIds = getStarredBoardsIds(this.previous);
  938. const newIds = getStarredBoardsIds(user);
  939. // The _.difference(a, b) method returns the values from a that are not in
  940. // b. We use it to find deleted and newly inserted ids by using it in one
  941. // direction and then in the other.
  942. function incrementBoards(boardsIds, inc) {
  943. boardsIds.forEach(boardId => {
  944. Boards.update(boardId, { $inc: { stars: inc } });
  945. });
  946. }
  947. incrementBoards(_.difference(oldIds, newIds), -1);
  948. incrementBoards(_.difference(newIds, oldIds), +1);
  949. });
  950. const fakeUserId = new Meteor.EnvironmentVariable();
  951. const getUserId = CollectionHooks.getUserId;
  952. CollectionHooks.getUserId = () => {
  953. return fakeUserId.get() || getUserId();
  954. };
  955. if (!isSandstorm) {
  956. Users.after.insert((userId, doc) => {
  957. const fakeUser = {
  958. extendAutoValueContext: {
  959. userId: doc._id,
  960. },
  961. };
  962. fakeUserId.withValue(doc._id, () => {
  963. /*
  964. // Insert the Welcome Board
  965. Boards.insert({
  966. title: TAPi18n.__('welcome-board'),
  967. permission: 'private',
  968. }, fakeUser, (err, boardId) => {
  969. Swimlanes.insert({
  970. title: TAPi18n.__('welcome-swimlane'),
  971. boardId,
  972. sort: 1,
  973. }, fakeUser);
  974. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  975. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  976. });
  977. });
  978. */
  979. Boards.insert(
  980. {
  981. title: TAPi18n.__('templates'),
  982. permission: 'private',
  983. type: 'template-container',
  984. },
  985. fakeUser,
  986. (err, boardId) => {
  987. // Insert the reference to our templates board
  988. Users.update(fakeUserId.get(), {
  989. $set: { 'profile.templatesBoardId': boardId },
  990. });
  991. // Insert the card templates swimlane
  992. Swimlanes.insert(
  993. {
  994. title: TAPi18n.__('card-templates-swimlane'),
  995. boardId,
  996. sort: 1,
  997. type: 'template-container',
  998. },
  999. fakeUser,
  1000. (err, swimlaneId) => {
  1001. // Insert the reference to out card templates swimlane
  1002. Users.update(fakeUserId.get(), {
  1003. $set: { 'profile.cardTemplatesSwimlaneId': swimlaneId },
  1004. });
  1005. },
  1006. );
  1007. // Insert the list templates swimlane
  1008. Swimlanes.insert(
  1009. {
  1010. title: TAPi18n.__('list-templates-swimlane'),
  1011. boardId,
  1012. sort: 2,
  1013. type: 'template-container',
  1014. },
  1015. fakeUser,
  1016. (err, swimlaneId) => {
  1017. // Insert the reference to out list templates swimlane
  1018. Users.update(fakeUserId.get(), {
  1019. $set: { 'profile.listTemplatesSwimlaneId': swimlaneId },
  1020. });
  1021. },
  1022. );
  1023. // Insert the board templates swimlane
  1024. Swimlanes.insert(
  1025. {
  1026. title: TAPi18n.__('board-templates-swimlane'),
  1027. boardId,
  1028. sort: 3,
  1029. type: 'template-container',
  1030. },
  1031. fakeUser,
  1032. (err, swimlaneId) => {
  1033. // Insert the reference to out board templates swimlane
  1034. Users.update(fakeUserId.get(), {
  1035. $set: { 'profile.boardTemplatesSwimlaneId': swimlaneId },
  1036. });
  1037. },
  1038. );
  1039. },
  1040. );
  1041. });
  1042. });
  1043. }
  1044. Users.after.insert((userId, doc) => {
  1045. if (doc.createdThroughApi) {
  1046. // The admin user should be able to create a user despite disabling registration because
  1047. // it is two different things (registration and creation).
  1048. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1049. // the disableRegistration check.
  1050. // Issue : https://github.com/wekan/wekan/issues/1232
  1051. // PR : https://github.com/wekan/wekan/pull/1251
  1052. Users.update(doc._id, { $set: { createdThroughApi: '' } });
  1053. return;
  1054. }
  1055. //invite user to corresponding boards
  1056. const disableRegistration = Settings.findOne().disableRegistration;
  1057. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1058. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1059. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1060. const invitationCode = InvitationCodes.findOne({
  1061. code: doc.profile.icode,
  1062. valid: true,
  1063. });
  1064. if (!invitationCode) {
  1065. throw new Meteor.Error('error-invitation-code-not-exist');
  1066. } else {
  1067. invitationCode.boardsToBeInvited.forEach(boardId => {
  1068. const board = Boards.findOne(boardId);
  1069. board.addMember(doc._id);
  1070. });
  1071. if (!doc.profile) {
  1072. doc.profile = {};
  1073. }
  1074. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1075. Users.update(doc._id, { $set: { profile: doc.profile } });
  1076. InvitationCodes.update(invitationCode._id, { $set: { valid: false } });
  1077. }
  1078. }
  1079. });
  1080. }
  1081. // USERS REST API
  1082. if (Meteor.isServer) {
  1083. // Middleware which checks that API is enabled.
  1084. JsonRoutes.Middleware.use(function(req, res, next) {
  1085. const api = req.url.startsWith('/api');
  1086. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1087. return next();
  1088. } else {
  1089. res.writeHead(301, { Location: '/' });
  1090. return res.end();
  1091. }
  1092. });
  1093. /**
  1094. * @operation get_current_user
  1095. *
  1096. * @summary returns the current user
  1097. * @return_type Users
  1098. */
  1099. JsonRoutes.add('GET', '/api/user', function(req, res) {
  1100. try {
  1101. Authentication.checkLoggedIn(req.userId);
  1102. const data = Meteor.users.findOne({ _id: req.userId });
  1103. delete data.services;
  1104. JsonRoutes.sendResult(res, {
  1105. code: 200,
  1106. data,
  1107. });
  1108. } catch (error) {
  1109. JsonRoutes.sendResult(res, {
  1110. code: 200,
  1111. data: error,
  1112. });
  1113. }
  1114. });
  1115. /**
  1116. * @operation get_all_users
  1117. *
  1118. * @summary return all the users
  1119. *
  1120. * @description Only the admin user (the first user) can call the REST API.
  1121. * @return_type [{ _id: string,
  1122. * username: string}]
  1123. */
  1124. JsonRoutes.add('GET', '/api/users', function(req, res) {
  1125. try {
  1126. Authentication.checkUserId(req.userId);
  1127. JsonRoutes.sendResult(res, {
  1128. code: 200,
  1129. data: Meteor.users.find({}).map(function(doc) {
  1130. return { _id: doc._id, username: doc.username };
  1131. }),
  1132. });
  1133. } catch (error) {
  1134. JsonRoutes.sendResult(res, {
  1135. code: 200,
  1136. data: error,
  1137. });
  1138. }
  1139. });
  1140. /**
  1141. * @operation get_user
  1142. *
  1143. * @summary get a given user
  1144. *
  1145. * @description Only the admin user (the first user) can call the REST API.
  1146. *
  1147. * @param {string} userId the user ID
  1148. * @return_type Users
  1149. */
  1150. JsonRoutes.add('GET', '/api/users/:userId', function(req, res) {
  1151. try {
  1152. Authentication.checkUserId(req.userId);
  1153. const id = req.params.userId;
  1154. JsonRoutes.sendResult(res, {
  1155. code: 200,
  1156. data: Meteor.users.findOne({ _id: id }),
  1157. });
  1158. } catch (error) {
  1159. JsonRoutes.sendResult(res, {
  1160. code: 200,
  1161. data: error,
  1162. });
  1163. }
  1164. });
  1165. /**
  1166. * @operation edit_user
  1167. *
  1168. * @summary edit a given user
  1169. *
  1170. * @description Only the admin user (the first user) can call the REST API.
  1171. *
  1172. * Possible values for *action*:
  1173. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1174. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1175. * - `enableLogin`: Enable a user
  1176. *
  1177. * @param {string} userId the user ID
  1178. * @param {string} action the action
  1179. * @return_type {_id: string,
  1180. * title: string}
  1181. */
  1182. JsonRoutes.add('PUT', '/api/users/:userId', function(req, res) {
  1183. try {
  1184. Authentication.checkUserId(req.userId);
  1185. const id = req.params.userId;
  1186. const action = req.body.action;
  1187. let data = Meteor.users.findOne({ _id: id });
  1188. if (data !== undefined) {
  1189. if (action === 'takeOwnership') {
  1190. data = Boards.find({
  1191. 'members.userId': id,
  1192. 'members.isAdmin': true,
  1193. }).map(function(board) {
  1194. if (board.hasMember(req.userId)) {
  1195. board.removeMember(req.userId);
  1196. }
  1197. board.changeOwnership(id, req.userId);
  1198. return {
  1199. _id: board._id,
  1200. title: board.title,
  1201. };
  1202. });
  1203. } else {
  1204. if (action === 'disableLogin' && id !== req.userId) {
  1205. Users.update(
  1206. { _id: id },
  1207. {
  1208. $set: {
  1209. loginDisabled: true,
  1210. 'services.resume.loginTokens': '',
  1211. },
  1212. },
  1213. );
  1214. } else if (action === 'enableLogin') {
  1215. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  1216. }
  1217. data = Meteor.users.findOne({ _id: id });
  1218. }
  1219. }
  1220. JsonRoutes.sendResult(res, {
  1221. code: 200,
  1222. data,
  1223. });
  1224. } catch (error) {
  1225. JsonRoutes.sendResult(res, {
  1226. code: 200,
  1227. data: error,
  1228. });
  1229. }
  1230. });
  1231. /**
  1232. * @operation add_board_member
  1233. * @tag Boards
  1234. *
  1235. * @summary Add New Board Member with Role
  1236. *
  1237. * @description Only the admin user (the first user) can call the REST API.
  1238. *
  1239. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1240. * to later change the permissions.
  1241. *
  1242. * @param {string} boardId the board ID
  1243. * @param {string} userId the user ID
  1244. * @param {boolean} isAdmin is the user an admin of the board
  1245. * @param {boolean} isNoComments disable comments
  1246. * @param {boolean} isCommentOnly only enable comments
  1247. * @return_type {_id: string,
  1248. * title: string}
  1249. */
  1250. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function(
  1251. req,
  1252. res,
  1253. ) {
  1254. try {
  1255. Authentication.checkUserId(req.userId);
  1256. const userId = req.params.userId;
  1257. const boardId = req.params.boardId;
  1258. const action = req.body.action;
  1259. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1260. let data = Meteor.users.findOne({ _id: userId });
  1261. if (data !== undefined) {
  1262. if (action === 'add') {
  1263. data = Boards.find({
  1264. _id: boardId,
  1265. }).map(function(board) {
  1266. if (!board.hasMember(userId)) {
  1267. board.addMember(userId);
  1268. function isTrue(data) {
  1269. return data.toLowerCase() === 'true';
  1270. }
  1271. board.setMemberPermission(
  1272. userId,
  1273. isTrue(isAdmin),
  1274. isTrue(isNoComments),
  1275. isTrue(isCommentOnly),
  1276. userId,
  1277. );
  1278. }
  1279. return {
  1280. _id: board._id,
  1281. title: board.title,
  1282. };
  1283. });
  1284. }
  1285. }
  1286. JsonRoutes.sendResult(res, {
  1287. code: 200,
  1288. data: query,
  1289. });
  1290. } catch (error) {
  1291. JsonRoutes.sendResult(res, {
  1292. code: 200,
  1293. data: error,
  1294. });
  1295. }
  1296. });
  1297. /**
  1298. * @operation remove_board_member
  1299. * @tag Boards
  1300. *
  1301. * @summary Remove Member from Board
  1302. *
  1303. * @description Only the admin user (the first user) can call the REST API.
  1304. *
  1305. * @param {string} boardId the board ID
  1306. * @param {string} userId the user ID
  1307. * @param {string} action the action (needs to be `remove`)
  1308. * @return_type {_id: string,
  1309. * title: string}
  1310. */
  1311. JsonRoutes.add(
  1312. 'POST',
  1313. '/api/boards/:boardId/members/:userId/remove',
  1314. function(req, res) {
  1315. try {
  1316. Authentication.checkUserId(req.userId);
  1317. const userId = req.params.userId;
  1318. const boardId = req.params.boardId;
  1319. const action = req.body.action;
  1320. let data = Meteor.users.findOne({ _id: userId });
  1321. if (data !== undefined) {
  1322. if (action === 'remove') {
  1323. data = Boards.find({
  1324. _id: boardId,
  1325. }).map(function(board) {
  1326. if (board.hasMember(userId)) {
  1327. board.removeMember(userId);
  1328. }
  1329. return {
  1330. _id: board._id,
  1331. title: board.title,
  1332. };
  1333. });
  1334. }
  1335. }
  1336. JsonRoutes.sendResult(res, {
  1337. code: 200,
  1338. data: query,
  1339. });
  1340. } catch (error) {
  1341. JsonRoutes.sendResult(res, {
  1342. code: 200,
  1343. data: error,
  1344. });
  1345. }
  1346. },
  1347. );
  1348. /**
  1349. * @operation new_user
  1350. *
  1351. * @summary Create a new user
  1352. *
  1353. * @description Only the admin user (the first user) can call the REST API.
  1354. *
  1355. * @param {string} username the new username
  1356. * @param {string} email the email of the new user
  1357. * @param {string} password the password of the new user
  1358. * @return_type {_id: string}
  1359. */
  1360. JsonRoutes.add('POST', '/api/users/', function(req, res) {
  1361. try {
  1362. Authentication.checkUserId(req.userId);
  1363. const id = Accounts.createUser({
  1364. username: req.body.username,
  1365. email: req.body.email,
  1366. password: req.body.password,
  1367. from: 'admin',
  1368. });
  1369. JsonRoutes.sendResult(res, {
  1370. code: 200,
  1371. data: {
  1372. _id: id,
  1373. },
  1374. });
  1375. } catch (error) {
  1376. JsonRoutes.sendResult(res, {
  1377. code: 200,
  1378. data: error,
  1379. });
  1380. }
  1381. });
  1382. /**
  1383. * @operation delete_user
  1384. *
  1385. * @summary Delete a user
  1386. *
  1387. * @description Only the admin user (the first user) can call the REST API.
  1388. *
  1389. * @param {string} userId the ID of the user to delete
  1390. * @return_type {_id: string}
  1391. */
  1392. JsonRoutes.add('DELETE', '/api/users/:userId', function(req, res) {
  1393. try {
  1394. Authentication.checkUserId(req.userId);
  1395. const id = req.params.userId;
  1396. Meteor.users.remove({ _id: id });
  1397. JsonRoutes.sendResult(res, {
  1398. code: 200,
  1399. data: {
  1400. _id: id,
  1401. },
  1402. });
  1403. } catch (error) {
  1404. JsonRoutes.sendResult(res, {
  1405. code: 200,
  1406. data: error,
  1407. });
  1408. }
  1409. });
  1410. }
  1411. export default Users;