users.js 34 KB

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