users.js 38 KB

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