users.js 33 KB

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