users.js 33 KB

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