users.js 34 KB

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