users.js 35 KB

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