UserMembershipController.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. import SessionManager from '../Authentication/SessionManager.mjs'
  2. import UserMembershipHandler from './UserMembershipHandler.mjs'
  3. import Errors from '../Errors/Errors.js'
  4. import EmailHelper from '../Helpers/EmailHelper.mjs'
  5. import { csvAttachment } from '../../infrastructure/Response.mjs'
  6. import UserMembershipErrors from './UserMembershipErrors.mjs'
  7. import { SSOConfig } from '../../models/SSOConfig.mjs'
  8. import { Parser as CSVParser } from 'json2csv'
  9. import { expressify } from '@overleaf/promise-utils'
  10. import logger from '@overleaf/logger'
  11. import PlansLocator from '../Subscription/PlansLocator.mjs'
  12. import RecurlyClient from '../Subscription/RecurlyClient.mjs'
  13. import Modules from '../../infrastructure/Modules.mjs'
  14. import UserMembershipAuthorization from './UserMembershipAuthorization.mjs'
  15. import SplitTestHandler from '../SplitTests/SplitTestHandler.mjs'
  16. import _ from 'lodash'
  17. async function manageGroupMembers(req, res, next) {
  18. const { entity: subscription, entityConfig } = req
  19. const entityPrimaryKey =
  20. subscription[entityConfig.fields.primaryKey].toString()
  21. let entityName
  22. if (entityConfig.fields.name) {
  23. entityName = subscription[entityConfig.fields.name]
  24. }
  25. const users = await UserMembershipHandler.promises.getUsers(
  26. subscription,
  27. entityConfig
  28. )
  29. const ssoConfig = await SSOConfig.findById(subscription.ssoConfig).exec()
  30. const plan = PlansLocator.findLocalPlanInSettings(subscription.planCode)
  31. const userId = SessionManager.getLoggedInUserId(req.session)?.toString()
  32. const isAdmin = subscription.admin_id.toString() === userId
  33. const isUserGroupManager =
  34. Boolean(subscription.manager_ids?.some(id => id.toString() === userId)) &&
  35. !isAdmin
  36. let recurlySubscription
  37. try {
  38. if (subscription.recurlySubscription_id) {
  39. recurlySubscription = await RecurlyClient.promises.getSubscription(
  40. subscription.recurlySubscription_id
  41. )
  42. }
  43. } catch (err) {
  44. // do not block page rendering
  45. logger.error(
  46. {
  47. err,
  48. subscription: {
  49. _id: subscription._id,
  50. recurlySubscription_id: subscription.recurlySubscription_id,
  51. },
  52. },
  53. 'Error fetching Recurly subscription'
  54. )
  55. }
  56. const canUseAddSeatsFeature = Boolean(
  57. plan?.canUseFlexibleLicensing && isAdmin && recurlySubscription
  58. )
  59. res.render('user_membership/group-members-react', {
  60. name: entityName,
  61. groupId: entityPrimaryKey,
  62. users,
  63. groupSize: subscription.membersLimit,
  64. managedUsersActive: subscription.managedUsersEnabled,
  65. isUserGroupManager,
  66. groupSSOActive: ssoConfig?.enabled,
  67. canUseFlexibleLicensing: plan?.canUseFlexibleLicensing,
  68. canUseAddSeatsFeature,
  69. entityAccess: UserMembershipAuthorization.hasEntityAccess()(req),
  70. })
  71. }
  72. async function manageGroupManagers(req, res, next) {
  73. await _renderManagersPage(
  74. req,
  75. res,
  76. next,
  77. 'user_membership/group-managers-react'
  78. )
  79. }
  80. async function manageInstitutionManagers(req, res, next) {
  81. await _renderManagersPage(
  82. req,
  83. res,
  84. next,
  85. 'user_membership/institution-managers-react'
  86. )
  87. }
  88. async function managePublisherManagers(req, res, next) {
  89. await _renderManagersPage(
  90. req,
  91. res,
  92. next,
  93. 'user_membership/publisher-managers-react'
  94. )
  95. }
  96. async function _renderManagersPage(req, res, next, template) {
  97. const { entity, entityConfig } = req
  98. const fetchV1Data = new Promise((resolve, reject) => {
  99. entity.fetchV1Data((error, entity) => {
  100. if (error) {
  101. reject(error)
  102. } else {
  103. resolve(entity)
  104. }
  105. })
  106. })
  107. const entityWithV1Data = await fetchV1Data
  108. const entityPrimaryKey =
  109. entityWithV1Data[entityConfig.fields.primaryKey].toString()
  110. let entityName
  111. if (entityConfig.fields.name) {
  112. entityName = entityWithV1Data[entityConfig.fields.name]
  113. }
  114. const users = await UserMembershipHandler.promises.getUsers(
  115. entityWithV1Data,
  116. entityConfig
  117. )
  118. res.render(template, {
  119. name: entityName,
  120. users,
  121. groupId: entityPrimaryKey,
  122. entityAccess: UserMembershipAuthorization.hasEntityAccess()(req),
  123. })
  124. }
  125. async function manageGroupUsers(req, res) {
  126. const combinedUserManagement = await SplitTestHandler.promises.getAssignment(
  127. req,
  128. res,
  129. 'combined-user-management'
  130. )
  131. const { entity: subscription, entityConfig } = req
  132. const entityPrimaryKey =
  133. subscription[entityConfig.fields.primaryKey].toString()
  134. if (combinedUserManagement.variant !== 'enabled') {
  135. return res.redirect(`/manage/groups/${entityPrimaryKey}/members`)
  136. }
  137. let entityName
  138. if (entityConfig.fields.name) {
  139. entityName = subscription[entityConfig.fields.name]
  140. }
  141. const userId = SessionManager.getLoggedInUserId(req.session)?.toString()
  142. const plan = PlansLocator.findLocalPlanInSettings(subscription.planCode)
  143. const isAdmin = subscription.admin_id.toString() === userId
  144. const recurlySubscription = subscription.recurlySubscription_id
  145. ? await RecurlyClient.promises.getSubscription(
  146. subscription.recurlySubscription_id
  147. )
  148. : undefined
  149. const canUseAddSeatsFeature =
  150. plan?.canUseFlexibleLicensing &&
  151. isAdmin &&
  152. recurlySubscription &&
  153. !recurlySubscription.pendingChange
  154. const ssoConfig = await SSOConfig.findById(subscription.ssoConfig).exec()
  155. const users = await UserMembershipHandler.promises.getUsers(
  156. subscription,
  157. entityConfig
  158. )
  159. const { usersNoInvites, invites } = Object.groupBy(users, user =>
  160. user.invite ? 'invites' : 'usersNoInvites'
  161. )
  162. const deduplicatedUsers = _.uniqBy(usersNoInvites, 'email')
  163. for (const invite of invites) {
  164. const alreadyAdded = deduplicatedUsers.find(
  165. user => user.email === invite.email
  166. )
  167. if (alreadyAdded) {
  168. alreadyAdded.invite = true
  169. } else {
  170. deduplicatedUsers.unshift(invite)
  171. }
  172. }
  173. res.render('user_membership/group-users-react', {
  174. name: entityName,
  175. groupId: entityPrimaryKey,
  176. users: deduplicatedUsers,
  177. groupSize: subscription.membersLimit,
  178. managedUsersActive: subscription.managedUsersEnabled,
  179. entityAccess: UserMembershipAuthorization.hasEntityAccess()(req),
  180. canUseAddSeatsFeature,
  181. groupSSOActive: ssoConfig?.enabled,
  182. })
  183. }
  184. async function exportCsv(req, res) {
  185. let ssoEnabled
  186. const { entity, entityConfig } = req
  187. const fields = ['email', 'last_logged_in_at', 'last_active_at']
  188. const { managedUsersEnabled } = entity
  189. let users = await UserMembershipHandler.promises.getUsers(
  190. entity,
  191. entityConfig
  192. )
  193. if (entity.ssoConfig) {
  194. const ssoEnabledResult = await Modules.promises.hooks.fire(
  195. 'hasGroupSSOEnabled',
  196. entity
  197. )
  198. ssoEnabled = ssoEnabledResult?.[0]
  199. }
  200. if (managedUsersEnabled) {
  201. fields.push('managed')
  202. }
  203. if (ssoEnabled) {
  204. fields.push('sso')
  205. }
  206. if (managedUsersEnabled || ssoEnabled) {
  207. users = users.map(user => {
  208. if (managedUsersEnabled) {
  209. user.managed =
  210. user.enrollment?.managedBy?.toString() === entity._id.toString()
  211. }
  212. if (ssoEnabled) {
  213. user.sso = !!user.enrollment?.sso?.some(
  214. groupLinked =>
  215. groupLinked.groupId.toString() === entity._id.toString()
  216. )
  217. }
  218. return user
  219. })
  220. }
  221. const csvParser = new CSVParser({ fields })
  222. csvAttachment(res, csvParser.parse(users), 'Group.csv')
  223. }
  224. async function add(req, res) {
  225. const { entity, entityConfig } = req
  226. const email = EmailHelper.parseEmail(req.body.email)
  227. if (email == null) {
  228. return res.status(400).json({
  229. error: {
  230. code: 'invalid_email',
  231. message: req.i18n.translate('invalid_email'),
  232. },
  233. })
  234. }
  235. if (entityConfig.readOnly) {
  236. throw new Errors.NotFoundError('Cannot add users to entity')
  237. }
  238. let user
  239. try {
  240. const auditInfo = {
  241. ipAddress: req.ip,
  242. initiatorId: SessionManager.getLoggedInUserId(req.session),
  243. }
  244. user = await UserMembershipHandler.promises.addUser(
  245. entity,
  246. entityConfig,
  247. email,
  248. auditInfo
  249. )
  250. } catch (err) {
  251. if (err instanceof UserMembershipErrors.UserAlreadyAddedError) {
  252. return res.status(400).json({
  253. error: {
  254. code: 'user_already_added',
  255. message: req.i18n.translate('user_already_added'),
  256. },
  257. })
  258. }
  259. if (err instanceof UserMembershipErrors.UserNotFoundError) {
  260. return res.status(404).json({
  261. error: {
  262. code: 'user_not_found',
  263. message: req.i18n.translate('add_manager_user_not_found'),
  264. },
  265. })
  266. }
  267. throw err
  268. }
  269. res.json({ user })
  270. }
  271. async function remove(req, res) {
  272. const { entity, entityConfig } = req
  273. const { userId } = req.params
  274. if (entityConfig.readOnly) {
  275. throw new Errors.NotFoundError('Cannot remove users from entity')
  276. }
  277. const loggedInUserId = SessionManager.getLoggedInUserId(req.session)
  278. if (loggedInUserId === userId) {
  279. return res.status(400).json({
  280. error: {
  281. code: 'managers_cannot_remove_self',
  282. message: req.i18n.translate('managers_cannot_remove_self'),
  283. },
  284. })
  285. }
  286. try {
  287. const auditInfo = {
  288. ipAddress: req.ip,
  289. initiatorId: loggedInUserId,
  290. }
  291. await UserMembershipHandler.promises.removeUser(
  292. entity,
  293. entityConfig,
  294. userId,
  295. auditInfo
  296. )
  297. } catch (err) {
  298. if (err instanceof UserMembershipErrors.UserIsManagerError) {
  299. return res.status(400).json({
  300. error: {
  301. code: 'managers_cannot_remove_admin',
  302. message: req.i18n.translate('managers_cannot_remove_admin'),
  303. },
  304. })
  305. }
  306. throw err
  307. }
  308. res.sendStatus(200)
  309. }
  310. async function create(req, res) {
  311. const entityId = req.params.id
  312. const entityConfig = req.entityConfig
  313. await UserMembershipHandler.promises.createEntity(entityId, entityConfig)
  314. res.redirect(entityConfig.pathsFor(entityId).index)
  315. }
  316. export default {
  317. manageGroupMembers: expressify(manageGroupMembers),
  318. manageGroupManagers: expressify(manageGroupManagers),
  319. manageGroupUsers: expressify(manageGroupUsers),
  320. manageInstitutionManagers: expressify(manageInstitutionManagers),
  321. managePublisherManagers: expressify(managePublisherManagers),
  322. add: expressify(add),
  323. remove: expressify(remove),
  324. exportCsv: expressify(exportCsv),
  325. new(req, res, next) {
  326. res.render('user_membership/new', {
  327. entityName: req.params.name,
  328. entityId: req.params.id,
  329. })
  330. },
  331. create: expressify(create),
  332. }