2
0

users.js 31 KB

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