users.js 17 KB

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