users.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  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. setCreateUser(fullname, username, password, isAdmin, isActive, email) {
  574. if (Meteor.user().isAdmin) {
  575. check(fullname, String);
  576. check(username, String);
  577. check(password, String);
  578. check(isAdmin, String);
  579. check(isActive, String);
  580. check(email, String);
  581. const nUsersWithUsername = Users.find({ username }).count();
  582. const nUsersWithEmail = Users.find({ email }).count();
  583. if (nUsersWithUsername > 0) {
  584. throw new Meteor.Error('username-already-taken');
  585. } else if (nUsersWithEmail > 0) {
  586. throw new Meteor.Error('email-already-taken');
  587. } else {
  588. Accounts.createUser({
  589. fullname,
  590. username,
  591. password,
  592. isAdmin,
  593. isActive,
  594. email: email.toLowerCase(),
  595. from: 'admin',
  596. });
  597. }
  598. }
  599. },
  600. setUsername(username, userId) {
  601. check(username, String);
  602. check(userId, String);
  603. const nUsersWithUsername = Users.find({ username }).count();
  604. if (nUsersWithUsername > 0) {
  605. throw new Meteor.Error('username-already-taken');
  606. } else {
  607. Users.update(userId, { $set: { username } });
  608. }
  609. },
  610. setListSortBy(value) {
  611. check(value, String);
  612. Meteor.user().setListSortBy(value);
  613. },
  614. toggleDesktopDragHandles() {
  615. const user = Meteor.user();
  616. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  617. },
  618. toggleSystemMessages() {
  619. const user = Meteor.user();
  620. user.toggleSystem(user.hasHiddenSystemMessages());
  621. },
  622. toggleMinicardLabelText() {
  623. const user = Meteor.user();
  624. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  625. },
  626. changeLimitToShowCardsCount(limit) {
  627. check(limit, Number);
  628. Meteor.user().setShowCardsCountAt(limit);
  629. },
  630. setEmail(email, userId) {
  631. if (Array.isArray(email)) {
  632. email = email.shift();
  633. }
  634. check(email, String);
  635. const existingUser = Users.findOne(
  636. { 'emails.address': email },
  637. { fields: { _id: 1 } },
  638. );
  639. if (existingUser) {
  640. throw new Meteor.Error('email-already-taken');
  641. } else {
  642. Users.update(userId, {
  643. $set: {
  644. emails: [
  645. {
  646. address: email,
  647. verified: false,
  648. },
  649. ],
  650. },
  651. });
  652. }
  653. },
  654. setUsernameAndEmail(username, email, userId) {
  655. check(username, String);
  656. if (Array.isArray(email)) {
  657. email = email.shift();
  658. }
  659. check(email, String);
  660. check(userId, String);
  661. Meteor.call('setUsername', username, userId);
  662. Meteor.call('setEmail', email, userId);
  663. },
  664. setPassword(newPassword, userId) {
  665. check(userId, String);
  666. check(newPassword, String);
  667. if (Meteor.user().isAdmin) {
  668. Accounts.setPassword(userId, newPassword);
  669. }
  670. },
  671. });
  672. if (Meteor.isServer) {
  673. Meteor.methods({
  674. // we accept userId, username, email
  675. inviteUserToBoard(username, boardId) {
  676. check(username, String);
  677. check(boardId, String);
  678. const inviter = Meteor.user();
  679. const board = Boards.findOne(boardId);
  680. const allowInvite =
  681. inviter &&
  682. board &&
  683. board.members &&
  684. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  685. _.where(board.members, { userId: inviter._id })[0].isActive;
  686. // GitHub issue 2060
  687. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  688. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  689. this.unblock();
  690. const posAt = username.indexOf('@');
  691. let user = null;
  692. if (posAt >= 0) {
  693. user = Users.findOne({ emails: { $elemMatch: { address: username } } });
  694. } else {
  695. user = Users.findOne(username) || Users.findOne({ username });
  696. }
  697. if (user) {
  698. if (user._id === inviter._id)
  699. throw new Meteor.Error('error-user-notAllowSelf');
  700. } else {
  701. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  702. if (Settings.findOne().disableRegistration)
  703. throw new Meteor.Error('error-user-notCreated');
  704. // Set in lowercase email before creating account
  705. const email = username.toLowerCase();
  706. username = email.substring(0, posAt);
  707. const newUserId = Accounts.createUser({ username, email });
  708. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  709. // assume new user speak same language with inviter
  710. if (inviter.profile && inviter.profile.language) {
  711. Users.update(newUserId, {
  712. $set: {
  713. 'profile.language': inviter.profile.language,
  714. },
  715. });
  716. }
  717. Accounts.sendEnrollmentEmail(newUserId);
  718. user = Users.findOne(newUserId);
  719. }
  720. board.addMember(user._id);
  721. user.addInvite(boardId);
  722. try {
  723. const params = {
  724. user: user.username,
  725. inviter: inviter.username,
  726. board: board.title,
  727. url: board.absoluteUrl(),
  728. };
  729. const lang = user.getLanguage();
  730. Email.send({
  731. to: user.emails[0].address.toLowerCase(),
  732. from: Accounts.emailTemplates.from,
  733. subject: TAPi18n.__('email-invite-subject', params, lang),
  734. text: TAPi18n.__('email-invite-text', params, lang),
  735. });
  736. } catch (e) {
  737. throw new Meteor.Error('email-fail', e.message);
  738. }
  739. return { username: user.username, email: user.emails[0].address };
  740. },
  741. });
  742. Accounts.onCreateUser((options, user) => {
  743. const userCount = Users.find().count();
  744. if (userCount === 0) {
  745. user.isAdmin = true;
  746. return user;
  747. }
  748. if (user.services.oidc) {
  749. let email = user.services.oidc.email;
  750. if (Array.isArray(email)) {
  751. email = email.shift();
  752. }
  753. email = email.toLowerCase();
  754. user.username = user.services.oidc.username;
  755. user.emails = [{ address: email, verified: true }];
  756. const initials = user.services.oidc.fullname
  757. .match(/\b[a-zA-Z]/g)
  758. .join('')
  759. .toUpperCase();
  760. user.profile = {
  761. initials,
  762. fullname: user.services.oidc.fullname,
  763. boardView: 'board-view-lists',
  764. };
  765. user.authenticationMethod = 'oauth2';
  766. // see if any existing user has this email address or username, otherwise create new
  767. const existingUser = Meteor.users.findOne({
  768. $or: [{ 'emails.address': email }, { username: user.username }],
  769. });
  770. if (!existingUser) return user;
  771. // copy across new service info
  772. const service = _.keys(user.services)[0];
  773. existingUser.services[service] = user.services[service];
  774. existingUser.emails = user.emails;
  775. existingUser.username = user.username;
  776. existingUser.profile = user.profile;
  777. existingUser.authenticationMethod = user.authenticationMethod;
  778. Meteor.users.remove({ _id: existingUser._id }); // remove existing record
  779. return existingUser;
  780. }
  781. if (options.from === 'admin') {
  782. user.createdThroughApi = true;
  783. return user;
  784. }
  785. const disableRegistration = Settings.findOne().disableRegistration;
  786. // If this is the first Authentication by the ldap and self registration disabled
  787. if (disableRegistration && options && options.ldap) {
  788. user.authenticationMethod = 'ldap';
  789. return user;
  790. }
  791. // If self registration enabled
  792. if (!disableRegistration) {
  793. return user;
  794. }
  795. if (!options || !options.profile) {
  796. throw new Meteor.Error(
  797. 'error-invitation-code-blank',
  798. 'The invitation code is required',
  799. );
  800. }
  801. const invitationCode = InvitationCodes.findOne({
  802. code: options.profile.invitationcode,
  803. email: options.email,
  804. valid: true,
  805. });
  806. if (!invitationCode) {
  807. throw new Meteor.Error(
  808. 'error-invitation-code-not-exist',
  809. // eslint-disable-next-line quotes
  810. "The invitation code doesn't exist",
  811. );
  812. } else {
  813. user.profile = { icode: options.profile.invitationcode };
  814. user.profile.boardView = 'board-view-lists';
  815. // Deletes the invitation code after the user was created successfully.
  816. setTimeout(
  817. Meteor.bindEnvironment(() => {
  818. InvitationCodes.remove({ _id: invitationCode._id });
  819. }),
  820. 200,
  821. );
  822. return user;
  823. }
  824. });
  825. }
  826. if (Meteor.isServer) {
  827. // Let mongoDB ensure username unicity
  828. Meteor.startup(() => {
  829. allowedSortValues.forEach(value => {
  830. Lists._collection._ensureIndex(value);
  831. });
  832. Users._collection._ensureIndex({ modifiedAt: -1 });
  833. Users._collection._ensureIndex(
  834. {
  835. username: 1,
  836. },
  837. { unique: true },
  838. );
  839. });
  840. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  841. // if admin is removed, board is removed.
  842. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  843. // to use that board, and not have board deleted.
  844. // Someone can be later changed to be admin of board, by making change to database.
  845. // TODO: Add UI for changing someone as board admin.
  846. //Users.before.remove((userId, doc) => {
  847. // Boards
  848. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  849. // .forEach((board) => {
  850. // // If only one admin for the board
  851. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  852. // Boards.remove(board._id);
  853. // }
  854. // });
  855. //});
  856. // Each board document contains the de-normalized number of users that have
  857. // starred it. If the user star or unstar a board, we need to update this
  858. // counter.
  859. // We need to run this code on the server only, otherwise the incrementation
  860. // will be done twice.
  861. Users.after.update(function(userId, user, fieldNames) {
  862. // The `starredBoards` list is hosted on the `profile` field. If this
  863. // field hasn't been modificated we don't need to run this hook.
  864. if (!_.contains(fieldNames, 'profile')) return;
  865. // To calculate a diff of board starred ids, we get both the previous
  866. // and the newly board ids list
  867. function getStarredBoardsIds(doc) {
  868. return doc.profile && doc.profile.starredBoards;
  869. }
  870. const oldIds = getStarredBoardsIds(this.previous);
  871. const newIds = getStarredBoardsIds(user);
  872. // The _.difference(a, b) method returns the values from a that are not in
  873. // b. We use it to find deleted and newly inserted ids by using it in one
  874. // direction and then in the other.
  875. function incrementBoards(boardsIds, inc) {
  876. boardsIds.forEach(boardId => {
  877. Boards.update(boardId, { $inc: { stars: inc } });
  878. });
  879. }
  880. incrementBoards(_.difference(oldIds, newIds), -1);
  881. incrementBoards(_.difference(newIds, oldIds), +1);
  882. });
  883. const fakeUserId = new Meteor.EnvironmentVariable();
  884. const getUserId = CollectionHooks.getUserId;
  885. CollectionHooks.getUserId = () => {
  886. return fakeUserId.get() || getUserId();
  887. };
  888. if (!isSandstorm) {
  889. Users.after.insert((userId, doc) => {
  890. const fakeUser = {
  891. extendAutoValueContext: {
  892. userId: doc._id,
  893. },
  894. };
  895. fakeUserId.withValue(doc._id, () => {
  896. /*
  897. // Insert the Welcome Board
  898. Boards.insert({
  899. title: TAPi18n.__('welcome-board'),
  900. permission: 'private',
  901. }, fakeUser, (err, boardId) => {
  902. Swimlanes.insert({
  903. title: TAPi18n.__('welcome-swimlane'),
  904. boardId,
  905. sort: 1,
  906. }, fakeUser);
  907. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  908. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  909. });
  910. });
  911. */
  912. Boards.insert(
  913. {
  914. title: TAPi18n.__('templates'),
  915. permission: 'private',
  916. type: 'template-container',
  917. },
  918. fakeUser,
  919. (err, boardId) => {
  920. // Insert the reference to our templates board
  921. Users.update(fakeUserId.get(), {
  922. $set: { 'profile.templatesBoardId': boardId },
  923. });
  924. // Insert the card templates swimlane
  925. Swimlanes.insert(
  926. {
  927. title: TAPi18n.__('card-templates-swimlane'),
  928. boardId,
  929. sort: 1,
  930. type: 'template-container',
  931. },
  932. fakeUser,
  933. (err, swimlaneId) => {
  934. // Insert the reference to out card templates swimlane
  935. Users.update(fakeUserId.get(), {
  936. $set: { 'profile.cardTemplatesSwimlaneId': swimlaneId },
  937. });
  938. },
  939. );
  940. // Insert the list templates swimlane
  941. Swimlanes.insert(
  942. {
  943. title: TAPi18n.__('list-templates-swimlane'),
  944. boardId,
  945. sort: 2,
  946. type: 'template-container',
  947. },
  948. fakeUser,
  949. (err, swimlaneId) => {
  950. // Insert the reference to out list templates swimlane
  951. Users.update(fakeUserId.get(), {
  952. $set: { 'profile.listTemplatesSwimlaneId': swimlaneId },
  953. });
  954. },
  955. );
  956. // Insert the board templates swimlane
  957. Swimlanes.insert(
  958. {
  959. title: TAPi18n.__('board-templates-swimlane'),
  960. boardId,
  961. sort: 3,
  962. type: 'template-container',
  963. },
  964. fakeUser,
  965. (err, swimlaneId) => {
  966. // Insert the reference to out board templates swimlane
  967. Users.update(fakeUserId.get(), {
  968. $set: { 'profile.boardTemplatesSwimlaneId': swimlaneId },
  969. });
  970. },
  971. );
  972. },
  973. );
  974. });
  975. });
  976. }
  977. Users.after.insert((userId, doc) => {
  978. if (doc.createdThroughApi) {
  979. // The admin user should be able to create a user despite disabling registration because
  980. // it is two different things (registration and creation).
  981. // So, when a new user is created via the api (only admin user can do that) one must avoid
  982. // the disableRegistration check.
  983. // Issue : https://github.com/wekan/wekan/issues/1232
  984. // PR : https://github.com/wekan/wekan/pull/1251
  985. Users.update(doc._id, { $set: { createdThroughApi: '' } });
  986. return;
  987. }
  988. //invite user to corresponding boards
  989. const disableRegistration = Settings.findOne().disableRegistration;
  990. // If ldap, bypass the inviation code if the self registration isn't allowed.
  991. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  992. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  993. const invitationCode = InvitationCodes.findOne({
  994. code: doc.profile.icode,
  995. valid: true,
  996. });
  997. if (!invitationCode) {
  998. throw new Meteor.Error('error-invitation-code-not-exist');
  999. } else {
  1000. invitationCode.boardsToBeInvited.forEach(boardId => {
  1001. const board = Boards.findOne(boardId);
  1002. board.addMember(doc._id);
  1003. });
  1004. if (!doc.profile) {
  1005. doc.profile = {};
  1006. }
  1007. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1008. Users.update(doc._id, { $set: { profile: doc.profile } });
  1009. InvitationCodes.update(invitationCode._id, { $set: { valid: false } });
  1010. }
  1011. }
  1012. });
  1013. }
  1014. // USERS REST API
  1015. if (Meteor.isServer) {
  1016. // Middleware which checks that API is enabled.
  1017. JsonRoutes.Middleware.use(function(req, res, next) {
  1018. const api = req.url.startsWith('/api');
  1019. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1020. return next();
  1021. } else {
  1022. res.writeHead(301, { Location: '/' });
  1023. return res.end();
  1024. }
  1025. });
  1026. /**
  1027. * @operation get_current_user
  1028. *
  1029. * @summary returns the current user
  1030. * @return_type Users
  1031. */
  1032. JsonRoutes.add('GET', '/api/user', function(req, res) {
  1033. try {
  1034. Authentication.checkLoggedIn(req.userId);
  1035. const data = Meteor.users.findOne({ _id: req.userId });
  1036. delete data.services;
  1037. JsonRoutes.sendResult(res, {
  1038. code: 200,
  1039. data,
  1040. });
  1041. } catch (error) {
  1042. JsonRoutes.sendResult(res, {
  1043. code: 200,
  1044. data: error,
  1045. });
  1046. }
  1047. });
  1048. /**
  1049. * @operation get_all_users
  1050. *
  1051. * @summary return all the users
  1052. *
  1053. * @description Only the admin user (the first user) can call the REST API.
  1054. * @return_type [{ _id: string,
  1055. * username: string}]
  1056. */
  1057. JsonRoutes.add('GET', '/api/users', function(req, res) {
  1058. try {
  1059. Authentication.checkUserId(req.userId);
  1060. JsonRoutes.sendResult(res, {
  1061. code: 200,
  1062. data: Meteor.users.find({}).map(function(doc) {
  1063. return { _id: doc._id, username: doc.username };
  1064. }),
  1065. });
  1066. } catch (error) {
  1067. JsonRoutes.sendResult(res, {
  1068. code: 200,
  1069. data: error,
  1070. });
  1071. }
  1072. });
  1073. /**
  1074. * @operation get_user
  1075. *
  1076. * @summary get a given user
  1077. *
  1078. * @description Only the admin user (the first user) can call the REST API.
  1079. *
  1080. * @param {string} userId the user ID
  1081. * @return_type Users
  1082. */
  1083. JsonRoutes.add('GET', '/api/users/:userId', function(req, res) {
  1084. try {
  1085. Authentication.checkUserId(req.userId);
  1086. const id = req.params.userId;
  1087. JsonRoutes.sendResult(res, {
  1088. code: 200,
  1089. data: Meteor.users.findOne({ _id: id }),
  1090. });
  1091. } catch (error) {
  1092. JsonRoutes.sendResult(res, {
  1093. code: 200,
  1094. data: error,
  1095. });
  1096. }
  1097. });
  1098. /**
  1099. * @operation edit_user
  1100. *
  1101. * @summary edit a given user
  1102. *
  1103. * @description Only the admin user (the first user) can call the REST API.
  1104. *
  1105. * Possible values for *action*:
  1106. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1107. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1108. * - `enableLogin`: Enable a user
  1109. *
  1110. * @param {string} userId the user ID
  1111. * @param {string} action the action
  1112. * @return_type {_id: string,
  1113. * title: string}
  1114. */
  1115. JsonRoutes.add('PUT', '/api/users/:userId', function(req, res) {
  1116. try {
  1117. Authentication.checkUserId(req.userId);
  1118. const id = req.params.userId;
  1119. const action = req.body.action;
  1120. let data = Meteor.users.findOne({ _id: id });
  1121. if (data !== undefined) {
  1122. if (action === 'takeOwnership') {
  1123. data = Boards.find({
  1124. 'members.userId': id,
  1125. 'members.isAdmin': true,
  1126. }).map(function(board) {
  1127. if (board.hasMember(req.userId)) {
  1128. board.removeMember(req.userId);
  1129. }
  1130. board.changeOwnership(id, req.userId);
  1131. return {
  1132. _id: board._id,
  1133. title: board.title,
  1134. };
  1135. });
  1136. } else {
  1137. if (action === 'disableLogin' && id !== req.userId) {
  1138. Users.update(
  1139. { _id: id },
  1140. {
  1141. $set: {
  1142. loginDisabled: true,
  1143. 'services.resume.loginTokens': '',
  1144. },
  1145. },
  1146. );
  1147. } else if (action === 'enableLogin') {
  1148. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  1149. }
  1150. data = Meteor.users.findOne({ _id: id });
  1151. }
  1152. }
  1153. JsonRoutes.sendResult(res, {
  1154. code: 200,
  1155. data,
  1156. });
  1157. } catch (error) {
  1158. JsonRoutes.sendResult(res, {
  1159. code: 200,
  1160. data: error,
  1161. });
  1162. }
  1163. });
  1164. /**
  1165. * @operation add_board_member
  1166. * @tag Boards
  1167. *
  1168. * @summary Add New Board Member with Role
  1169. *
  1170. * @description Only the admin user (the first user) can call the REST API.
  1171. *
  1172. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1173. * to later change the permissions.
  1174. *
  1175. * @param {string} boardId the board ID
  1176. * @param {string} userId the user ID
  1177. * @param {boolean} isAdmin is the user an admin of the board
  1178. * @param {boolean} isNoComments disable comments
  1179. * @param {boolean} isCommentOnly only enable comments
  1180. * @return_type {_id: string,
  1181. * title: string}
  1182. */
  1183. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function(
  1184. req,
  1185. res,
  1186. ) {
  1187. try {
  1188. Authentication.checkUserId(req.userId);
  1189. const userId = req.params.userId;
  1190. const boardId = req.params.boardId;
  1191. const action = req.body.action;
  1192. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1193. let data = Meteor.users.findOne({ _id: userId });
  1194. if (data !== undefined) {
  1195. if (action === 'add') {
  1196. data = Boards.find({
  1197. _id: boardId,
  1198. }).map(function(board) {
  1199. if (!board.hasMember(userId)) {
  1200. board.addMember(userId);
  1201. function isTrue(data) {
  1202. return data.toLowerCase() === 'true';
  1203. }
  1204. board.setMemberPermission(
  1205. userId,
  1206. isTrue(isAdmin),
  1207. isTrue(isNoComments),
  1208. isTrue(isCommentOnly),
  1209. userId,
  1210. );
  1211. }
  1212. return {
  1213. _id: board._id,
  1214. title: board.title,
  1215. };
  1216. });
  1217. }
  1218. }
  1219. JsonRoutes.sendResult(res, {
  1220. code: 200,
  1221. data: query,
  1222. });
  1223. } catch (error) {
  1224. JsonRoutes.sendResult(res, {
  1225. code: 200,
  1226. data: error,
  1227. });
  1228. }
  1229. });
  1230. /**
  1231. * @operation remove_board_member
  1232. * @tag Boards
  1233. *
  1234. * @summary Remove Member from Board
  1235. *
  1236. * @description Only the admin user (the first user) can call the REST API.
  1237. *
  1238. * @param {string} boardId the board ID
  1239. * @param {string} userId the user ID
  1240. * @param {string} action the action (needs to be `remove`)
  1241. * @return_type {_id: string,
  1242. * title: string}
  1243. */
  1244. JsonRoutes.add(
  1245. 'POST',
  1246. '/api/boards/:boardId/members/:userId/remove',
  1247. function(req, res) {
  1248. try {
  1249. Authentication.checkUserId(req.userId);
  1250. const userId = req.params.userId;
  1251. const boardId = req.params.boardId;
  1252. const action = req.body.action;
  1253. let data = Meteor.users.findOne({ _id: userId });
  1254. if (data !== undefined) {
  1255. if (action === 'remove') {
  1256. data = Boards.find({
  1257. _id: boardId,
  1258. }).map(function(board) {
  1259. if (board.hasMember(userId)) {
  1260. board.removeMember(userId);
  1261. }
  1262. return {
  1263. _id: board._id,
  1264. title: board.title,
  1265. };
  1266. });
  1267. }
  1268. }
  1269. JsonRoutes.sendResult(res, {
  1270. code: 200,
  1271. data: query,
  1272. });
  1273. } catch (error) {
  1274. JsonRoutes.sendResult(res, {
  1275. code: 200,
  1276. data: error,
  1277. });
  1278. }
  1279. },
  1280. );
  1281. /**
  1282. * @operation new_user
  1283. *
  1284. * @summary Create a new user
  1285. *
  1286. * @description Only the admin user (the first user) can call the REST API.
  1287. *
  1288. * @param {string} username the new username
  1289. * @param {string} email the email of the new user
  1290. * @param {string} password the password of the new user
  1291. * @return_type {_id: string}
  1292. */
  1293. JsonRoutes.add('POST', '/api/users/', function(req, res) {
  1294. try {
  1295. Authentication.checkUserId(req.userId);
  1296. const id = Accounts.createUser({
  1297. username: req.body.username,
  1298. email: req.body.email,
  1299. password: req.body.password,
  1300. from: 'admin',
  1301. });
  1302. JsonRoutes.sendResult(res, {
  1303. code: 200,
  1304. data: {
  1305. _id: id,
  1306. },
  1307. });
  1308. } catch (error) {
  1309. JsonRoutes.sendResult(res, {
  1310. code: 200,
  1311. data: error,
  1312. });
  1313. }
  1314. });
  1315. /**
  1316. * @operation delete_user
  1317. *
  1318. * @summary Delete a user
  1319. *
  1320. * @description Only the admin user (the first user) can call the REST API.
  1321. *
  1322. * @param {string} userId the ID of the user to delete
  1323. * @return_type {_id: string}
  1324. */
  1325. JsonRoutes.add('DELETE', '/api/users/:userId', function(req, res) {
  1326. try {
  1327. Authentication.checkUserId(req.userId);
  1328. const id = req.params.userId;
  1329. Meteor.users.remove({ _id: id });
  1330. JsonRoutes.sendResult(res, {
  1331. code: 200,
  1332. data: {
  1333. _id: id,
  1334. },
  1335. });
  1336. } catch (error) {
  1337. JsonRoutes.sendResult(res, {
  1338. code: 200,
  1339. data: error,
  1340. });
  1341. }
  1342. });
  1343. }
  1344. export default Users;