users.js 34 KB

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