users.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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. Users.attachSchema(new SimpleSchema({
  7. username: {
  8. type: String,
  9. optional: true,
  10. autoValue() { // eslint-disable-line consistent-return
  11. if (this.isInsert && !this.isSet) {
  12. const name = this.field('profile.fullname');
  13. if (name.isSet) {
  14. return name.value.toLowerCase().replace(/\s/g, '');
  15. }
  16. }
  17. },
  18. },
  19. emails: {
  20. type: [Object],
  21. optional: true,
  22. },
  23. 'emails.$.address': {
  24. type: String,
  25. regEx: SimpleSchema.RegEx.Email,
  26. },
  27. 'emails.$.verified': {
  28. type: Boolean,
  29. },
  30. createdAt: {
  31. type: Date,
  32. autoValue() { // eslint-disable-line consistent-return
  33. if (this.isInsert) {
  34. return new Date();
  35. } else {
  36. this.unset();
  37. }
  38. },
  39. },
  40. profile: {
  41. type: Object,
  42. optional: true,
  43. autoValue() { // eslint-disable-line consistent-return
  44. if (this.isInsert && !this.isSet) {
  45. return {
  46. boardView: 'board-view-lists',
  47. };
  48. }
  49. },
  50. },
  51. 'profile.avatarUrl': {
  52. type: String,
  53. optional: true,
  54. },
  55. 'profile.emailBuffer': {
  56. type: [String],
  57. optional: true,
  58. },
  59. 'profile.fullname': {
  60. type: String,
  61. optional: true,
  62. },
  63. 'profile.hiddenSystemMessages': {
  64. type: Boolean,
  65. optional: true,
  66. },
  67. 'profile.initials': {
  68. type: String,
  69. optional: true,
  70. },
  71. 'profile.invitedBoards': {
  72. type: [String],
  73. optional: true,
  74. },
  75. 'profile.language': {
  76. type: String,
  77. optional: true,
  78. },
  79. 'profile.notifications': {
  80. type: [String],
  81. optional: true,
  82. },
  83. 'profile.showCardsCountAt': {
  84. type: Number,
  85. optional: true,
  86. },
  87. 'profile.starredBoards': {
  88. type: [String],
  89. optional: true,
  90. },
  91. 'profile.tags': {
  92. type: [String],
  93. optional: true,
  94. },
  95. 'profile.icode': {
  96. type: String,
  97. optional: true,
  98. },
  99. 'profile.boardView': {
  100. type: String,
  101. optional: true,
  102. allowedValues: [
  103. 'board-view-lists',
  104. 'board-view-swimlanes',
  105. 'board-view-cal',
  106. ],
  107. },
  108. services: {
  109. type: Object,
  110. optional: true,
  111. blackbox: true,
  112. },
  113. heartbeat: {
  114. type: Date,
  115. optional: true,
  116. },
  117. isAdmin: {
  118. type: Boolean,
  119. optional: true,
  120. },
  121. createdThroughApi: {
  122. type: Boolean,
  123. optional: true,
  124. },
  125. loginDisabled: {
  126. type: Boolean,
  127. optional: true,
  128. },
  129. }));
  130. Users.allow({
  131. update(userId) {
  132. const user = Users.findOne(userId);
  133. return user && Meteor.user().isAdmin;
  134. },
  135. });
  136. // Search a user in the complete server database by its name or username. This
  137. // is used for instance to add a new user to a board.
  138. const searchInFields = ['username', 'profile.fullname'];
  139. Users.initEasySearch(searchInFields, {
  140. use: 'mongo-db',
  141. returnFields: [...searchInFields, 'profile.avatarUrl'],
  142. });
  143. if (Meteor.isClient) {
  144. Users.helpers({
  145. isBoardMember() {
  146. const board = Boards.findOne(Session.get('currentBoard'));
  147. return board && board.hasMember(this._id);
  148. },
  149. isNotCommentOnly() {
  150. const board = Boards.findOne(Session.get('currentBoard'));
  151. return board && board.hasMember(this._id) && !board.hasCommentOnly(this._id);
  152. },
  153. isCommentOnly() {
  154. const board = Boards.findOne(Session.get('currentBoard'));
  155. return board && board.hasCommentOnly(this._id);
  156. },
  157. isBoardAdmin() {
  158. const board = Boards.findOne(Session.get('currentBoard'));
  159. return board && board.hasAdmin(this._id);
  160. },
  161. });
  162. }
  163. Users.helpers({
  164. boards() {
  165. return Boards.find({ 'members.userId': this._id });
  166. },
  167. starredBoards() {
  168. const {starredBoards = []} = this.profile;
  169. return Boards.find({archived: false, _id: {$in: starredBoards}});
  170. },
  171. hasStarred(boardId) {
  172. const {starredBoards = []} = this.profile;
  173. return _.contains(starredBoards, boardId);
  174. },
  175. invitedBoards() {
  176. const {invitedBoards = []} = this.profile;
  177. return Boards.find({archived: false, _id: {$in: invitedBoards}});
  178. },
  179. isInvitedTo(boardId) {
  180. const {invitedBoards = []} = this.profile;
  181. return _.contains(invitedBoards, boardId);
  182. },
  183. hasTag(tag) {
  184. const {tags = []} = this.profile;
  185. return _.contains(tags, tag);
  186. },
  187. hasNotification(activityId) {
  188. const {notifications = []} = this.profile;
  189. return _.contains(notifications, activityId);
  190. },
  191. hasHiddenSystemMessages() {
  192. const profile = this.profile || {};
  193. return profile.hiddenSystemMessages || false;
  194. },
  195. getEmailBuffer() {
  196. const {emailBuffer = []} = this.profile;
  197. return emailBuffer;
  198. },
  199. getInitials() {
  200. const profile = this.profile || {};
  201. if (profile.initials)
  202. return profile.initials;
  203. else if (profile.fullname) {
  204. return profile.fullname.split(/\s+/).reduce((memo, word) => {
  205. return memo + word[0];
  206. }, '').toUpperCase();
  207. } else {
  208. return this.username[0].toUpperCase();
  209. }
  210. },
  211. getLimitToShowCardsCount() {
  212. const profile = this.profile || {};
  213. return profile.showCardsCountAt;
  214. },
  215. getName() {
  216. const profile = this.profile || {};
  217. return profile.fullname || this.username;
  218. },
  219. getLanguage() {
  220. const profile = this.profile || {};
  221. return profile.language || 'en';
  222. },
  223. });
  224. Users.mutations({
  225. toggleBoardStar(boardId) {
  226. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  227. return {
  228. [queryKind]: {
  229. 'profile.starredBoards': boardId,
  230. },
  231. };
  232. },
  233. addInvite(boardId) {
  234. return {
  235. $addToSet: {
  236. 'profile.invitedBoards': boardId,
  237. },
  238. };
  239. },
  240. removeInvite(boardId) {
  241. return {
  242. $pull: {
  243. 'profile.invitedBoards': boardId,
  244. },
  245. };
  246. },
  247. addTag(tag) {
  248. return {
  249. $addToSet: {
  250. 'profile.tags': tag,
  251. },
  252. };
  253. },
  254. removeTag(tag) {
  255. return {
  256. $pull: {
  257. 'profile.tags': tag,
  258. },
  259. };
  260. },
  261. toggleTag(tag) {
  262. if (this.hasTag(tag))
  263. this.removeTag(tag);
  264. else
  265. this.addTag(tag);
  266. },
  267. toggleSystem(value = false) {
  268. return {
  269. $set: {
  270. 'profile.hiddenSystemMessages': !value,
  271. },
  272. };
  273. },
  274. addNotification(activityId) {
  275. return {
  276. $addToSet: {
  277. 'profile.notifications': activityId,
  278. },
  279. };
  280. },
  281. removeNotification(activityId) {
  282. return {
  283. $pull: {
  284. 'profile.notifications': activityId,
  285. },
  286. };
  287. },
  288. addEmailBuffer(text) {
  289. return {
  290. $addToSet: {
  291. 'profile.emailBuffer': text,
  292. },
  293. };
  294. },
  295. clearEmailBuffer() {
  296. return {
  297. $set: {
  298. 'profile.emailBuffer': [],
  299. },
  300. };
  301. },
  302. setAvatarUrl(avatarUrl) {
  303. return {$set: {'profile.avatarUrl': avatarUrl}};
  304. },
  305. setShowCardsCountAt(limit) {
  306. return {$set: {'profile.showCardsCountAt': limit}};
  307. },
  308. setBoardView(view) {
  309. return {
  310. $set : {
  311. 'profile.boardView': view,
  312. },
  313. };
  314. },
  315. });
  316. Meteor.methods({
  317. setUsername(username, userId) {
  318. check(username, String);
  319. const nUsersWithUsername = Users.find({username}).count();
  320. if (nUsersWithUsername > 0) {
  321. throw new Meteor.Error('username-already-taken');
  322. } else {
  323. Users.update(userId, {$set: {username}});
  324. }
  325. },
  326. toggleSystemMessages() {
  327. const user = Meteor.user();
  328. user.toggleSystem(user.hasHiddenSystemMessages());
  329. },
  330. changeLimitToShowCardsCount(limit) {
  331. check(limit, Number);
  332. Meteor.user().setShowCardsCountAt(limit);
  333. },
  334. setEmail(email, userId) {
  335. check(email, String);
  336. const existingUser = Users.findOne({'emails.address': email}, {fields: {_id: 1}});
  337. if (existingUser) {
  338. throw new Meteor.Error('email-already-taken');
  339. } else {
  340. Users.update(userId, {
  341. $set: {
  342. emails: [{
  343. address: email,
  344. verified: false,
  345. }],
  346. },
  347. });
  348. }
  349. },
  350. setUsernameAndEmail(username, email, userId) {
  351. check(username, String);
  352. check(email, String);
  353. check(userId, String);
  354. Meteor.call('setUsername', username, userId);
  355. Meteor.call('setEmail', email, userId);
  356. },
  357. setPassword(newPassword, userId) {
  358. check(userId, String);
  359. check(newPassword, String);
  360. if(Meteor.user().isAdmin){
  361. Accounts.setPassword(userId, newPassword);
  362. }
  363. },
  364. });
  365. if (Meteor.isServer) {
  366. Meteor.methods({
  367. // we accept userId, username, email
  368. inviteUserToBoard(username, boardId) {
  369. check(username, String);
  370. check(boardId, String);
  371. const inviter = Meteor.user();
  372. const board = Boards.findOne(boardId);
  373. const allowInvite = inviter &&
  374. board &&
  375. board.members &&
  376. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  377. _.where(board.members, {userId: inviter._id})[0].isActive &&
  378. _.where(board.members, {userId: inviter._id})[0].isAdmin;
  379. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  380. this.unblock();
  381. const posAt = username.indexOf('@');
  382. let user = null;
  383. if (posAt >= 0) {
  384. user = Users.findOne({emails: {$elemMatch: {address: username}}});
  385. } else {
  386. user = Users.findOne(username) || Users.findOne({username});
  387. }
  388. if (user) {
  389. if (user._id === inviter._id) throw new Meteor.Error('error-user-notAllowSelf');
  390. } else {
  391. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  392. if (Settings.findOne().disableRegistration) throw new Meteor.Error('error-user-notCreated');
  393. // Set in lowercase email before creating account
  394. const email = username.toLowerCase();
  395. username = email.substring(0, posAt);
  396. const newUserId = Accounts.createUser({username, email});
  397. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  398. // assume new user speak same language with inviter
  399. if (inviter.profile && inviter.profile.language) {
  400. Users.update(newUserId, {
  401. $set: {
  402. 'profile.language': inviter.profile.language,
  403. },
  404. });
  405. }
  406. Accounts.sendEnrollmentEmail(newUserId);
  407. user = Users.findOne(newUserId);
  408. }
  409. board.addMember(user._id);
  410. user.addInvite(boardId);
  411. try {
  412. const params = {
  413. user: user.username,
  414. inviter: inviter.username,
  415. board: board.title,
  416. url: board.absoluteUrl(),
  417. };
  418. const lang = user.getLanguage();
  419. Email.send({
  420. to: user.emails[0].address.toLowerCase(),
  421. from: Accounts.emailTemplates.from,
  422. subject: TAPi18n.__('email-invite-subject', params, lang),
  423. text: TAPi18n.__('email-invite-text', params, lang),
  424. });
  425. } catch (e) {
  426. throw new Meteor.Error('email-fail', e.message);
  427. }
  428. return {username: user.username, email: user.emails[0].address};
  429. },
  430. });
  431. Accounts.onCreateUser((options, user) => {
  432. const userCount = Users.find().count();
  433. if (!isSandstorm && userCount === 0) {
  434. user.isAdmin = true;
  435. return user;
  436. }
  437. if (options.from === 'admin') {
  438. user.createdThroughApi = true;
  439. return user;
  440. }
  441. const disableRegistration = Settings.findOne().disableRegistration;
  442. if (!disableRegistration) {
  443. return user;
  444. }
  445. if (!options || !options.profile) {
  446. throw new Meteor.Error('error-invitation-code-blank', 'The invitation code is required');
  447. }
  448. const invitationCode = InvitationCodes.findOne({
  449. code: options.profile.invitationcode,
  450. email: options.email,
  451. valid: true,
  452. });
  453. if (!invitationCode) {
  454. throw new Meteor.Error('error-invitation-code-not-exist', 'The invitation code doesn\'t exist');
  455. } else {
  456. user.profile = {icode: options.profile.invitationcode};
  457. user.profile.boardView = 'board-view-lists';
  458. // Deletes the invitation code after the user was created successfully.
  459. setTimeout(Meteor.bindEnvironment(() => {
  460. InvitationCodes.remove({'_id': invitationCode._id});
  461. }), 200);
  462. return user;
  463. }
  464. });
  465. }
  466. if (Meteor.isServer) {
  467. // Let mongoDB ensure username unicity
  468. Meteor.startup(() => {
  469. Users._collection._ensureIndex({
  470. username: 1,
  471. }, {unique: true});
  472. });
  473. // Each board document contains the de-normalized number of users that have
  474. // starred it. If the user star or unstar a board, we need to update this
  475. // counter.
  476. // We need to run this code on the server only, otherwise the incrementation
  477. // will be done twice.
  478. Users.after.update(function (userId, user, fieldNames) {
  479. // The `starredBoards` list is hosted on the `profile` field. If this
  480. // field hasn't been modificated we don't need to run this hook.
  481. if (!_.contains(fieldNames, 'profile'))
  482. return;
  483. // To calculate a diff of board starred ids, we get both the previous
  484. // and the newly board ids list
  485. function getStarredBoardsIds(doc) {
  486. return doc.profile && doc.profile.starredBoards;
  487. }
  488. const oldIds = getStarredBoardsIds(this.previous);
  489. const newIds = getStarredBoardsIds(user);
  490. // The _.difference(a, b) method returns the values from a that are not in
  491. // b. We use it to find deleted and newly inserted ids by using it in one
  492. // direction and then in the other.
  493. function incrementBoards(boardsIds, inc) {
  494. boardsIds.forEach((boardId) => {
  495. Boards.update(boardId, {$inc: {stars: inc}});
  496. });
  497. }
  498. incrementBoards(_.difference(oldIds, newIds), -1);
  499. incrementBoards(_.difference(newIds, oldIds), +1);
  500. });
  501. const fakeUserId = new Meteor.EnvironmentVariable();
  502. const getUserId = CollectionHooks.getUserId;
  503. CollectionHooks.getUserId = () => {
  504. return fakeUserId.get() || getUserId();
  505. };
  506. if (!isSandstorm) {
  507. Users.after.insert((userId, doc) => {
  508. const fakeUser = {
  509. extendAutoValueContext: {
  510. userId: doc._id,
  511. },
  512. };
  513. fakeUserId.withValue(doc._id, () => {
  514. // Insert the Welcome Board
  515. Boards.insert({
  516. title: TAPi18n.__('welcome-board'),
  517. permission: 'private',
  518. }, fakeUser, (err, boardId) => {
  519. Swimlanes.insert({
  520. title: TAPi18n.__('welcome-swimlane'),
  521. boardId,
  522. sort: 1,
  523. }, fakeUser);
  524. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  525. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  526. });
  527. });
  528. });
  529. });
  530. }
  531. Users.after.insert((userId, doc) => {
  532. if (doc.createdThroughApi) {
  533. // The admin user should be able to create a user despite disabling registration because
  534. // it is two different things (registration and creation).
  535. // So, when a new user is created via the api (only admin user can do that) one must avoid
  536. // the disableRegistration check.
  537. // Issue : https://github.com/wekan/wekan/issues/1232
  538. // PR : https://github.com/wekan/wekan/pull/1251
  539. Users.update(doc._id, {$set: {createdThroughApi: ''}});
  540. return;
  541. }
  542. //invite user to corresponding boards
  543. const disableRegistration = Settings.findOne().disableRegistration;
  544. if (disableRegistration) {
  545. const invitationCode = InvitationCodes.findOne({code: doc.profile.icode, valid: true});
  546. if (!invitationCode) {
  547. throw new Meteor.Error('error-invitation-code-not-exist');
  548. } else {
  549. invitationCode.boardsToBeInvited.forEach((boardId) => {
  550. const board = Boards.findOne(boardId);
  551. board.addMember(doc._id);
  552. });
  553. if (!doc.profile) {
  554. doc.profile = {};
  555. }
  556. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  557. Users.update(doc._id, {$set: {profile: doc.profile}});
  558. InvitationCodes.update(invitationCode._id, {$set: {valid: false}});
  559. }
  560. }
  561. });
  562. }
  563. // USERS REST API
  564. if (Meteor.isServer) {
  565. // Middleware which checks that API is enabled.
  566. JsonRoutes.Middleware.use(function (req, res, next) {
  567. const api = req.url.search('api');
  568. if (api === 1 && process.env.WITH_API === 'true' || api === -1){
  569. return next();
  570. }
  571. else {
  572. res.writeHead(301, {Location: '/'});
  573. return res.end();
  574. }
  575. });
  576. JsonRoutes.add('GET', '/api/user', function(req, res) {
  577. try {
  578. Authentication.checkLoggedIn(req.userId);
  579. const data = Meteor.users.findOne({ _id: req.userId});
  580. delete data.services;
  581. JsonRoutes.sendResult(res, {
  582. code: 200,
  583. data,
  584. });
  585. }
  586. catch (error) {
  587. JsonRoutes.sendResult(res, {
  588. code: 200,
  589. data: error,
  590. });
  591. }
  592. });
  593. JsonRoutes.add('GET', '/api/users', function (req, res) {
  594. try {
  595. Authentication.checkUserId(req.userId);
  596. JsonRoutes.sendResult(res, {
  597. code: 200,
  598. data: Meteor.users.find({}).map(function (doc) {
  599. return { _id: doc._id, username: doc.username };
  600. }),
  601. });
  602. }
  603. catch (error) {
  604. JsonRoutes.sendResult(res, {
  605. code: 200,
  606. data: error,
  607. });
  608. }
  609. });
  610. JsonRoutes.add('GET', '/api/users/:id', function (req, res) {
  611. try {
  612. Authentication.checkUserId(req.userId);
  613. const id = req.params.id;
  614. JsonRoutes.sendResult(res, {
  615. code: 200,
  616. data: Meteor.users.findOne({ _id: id }),
  617. });
  618. }
  619. catch (error) {
  620. JsonRoutes.sendResult(res, {
  621. code: 200,
  622. data: error,
  623. });
  624. }
  625. });
  626. JsonRoutes.add('PUT', '/api/users/:id', function (req, res) {
  627. try {
  628. Authentication.checkUserId(req.userId);
  629. const id = req.params.id;
  630. const action = req.body.action;
  631. let data = Meteor.users.findOne({ _id: id });
  632. if (data !== undefined) {
  633. if (action === 'takeOwnership') {
  634. data = Boards.find({
  635. 'members.userId': id,
  636. 'members.isAdmin': true,
  637. }).map(function(board) {
  638. if (board.hasMember(req.userId)) {
  639. board.removeMember(req.userId);
  640. }
  641. board.changeOwnership(id, req.userId);
  642. return {
  643. _id: board._id,
  644. title: board.title,
  645. };
  646. });
  647. } else {
  648. if ((action === 'disableLogin') && (id !== req.userId)) {
  649. Users.update({ _id: id }, { $set: { loginDisabled: true, 'services.resume.loginTokens': '' } });
  650. } else if (action === 'enableLogin') {
  651. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  652. }
  653. data = Meteor.users.findOne({ _id: id });
  654. }
  655. }
  656. JsonRoutes.sendResult(res, {
  657. code: 200,
  658. data,
  659. });
  660. }
  661. catch (error) {
  662. JsonRoutes.sendResult(res, {
  663. code: 200,
  664. data: error,
  665. });
  666. }
  667. });
  668. JsonRoutes.add('POST', '/api/users/', function (req, res) {
  669. try {
  670. Authentication.checkUserId(req.userId);
  671. const id = Accounts.createUser({
  672. username: req.body.username,
  673. email: req.body.email,
  674. password: req.body.password,
  675. from: 'admin',
  676. });
  677. JsonRoutes.sendResult(res, {
  678. code: 200,
  679. data: {
  680. _id: id,
  681. },
  682. });
  683. }
  684. catch (error) {
  685. JsonRoutes.sendResult(res, {
  686. code: 200,
  687. data: error,
  688. });
  689. }
  690. });
  691. JsonRoutes.add('DELETE', '/api/users/:id', function (req, res) {
  692. try {
  693. Authentication.checkUserId(req.userId);
  694. const id = req.params.id;
  695. Meteor.users.remove({ _id: id });
  696. JsonRoutes.sendResult(res, {
  697. code: 200,
  698. data: {
  699. _id: id,
  700. },
  701. });
  702. }
  703. catch (error) {
  704. JsonRoutes.sendResult(res, {
  705. code: 200,
  706. data: error,
  707. });
  708. }
  709. });
  710. }