users.js 28 KB

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