users.js 30 KB

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