SAMLIdentityManager.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. const EmailHandler = require('../Email/EmailHandler')
  2. const Errors = require('../Errors/Errors')
  3. const InstitutionsAPI = require('../Institutions/InstitutionsAPI')
  4. const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
  5. const OError = require('@overleaf/o-error')
  6. const SubscriptionLocator = require('../Subscription/SubscriptionLocator')
  7. const UserAuditLogHandler = require('../User/UserAuditLogHandler')
  8. const UserGetter = require('../User/UserGetter')
  9. const UserUpdater = require('../User/UserUpdater')
  10. const logger = require('logger-sharelatex')
  11. const { User } = require('../../models/User')
  12. async function _addAuditLogEntry(
  13. link,
  14. userId,
  15. auditLog,
  16. institutionEmail,
  17. providerId,
  18. providerName
  19. ) {
  20. const operation = link ? 'link-institution-sso' : 'unlink-institution-sso'
  21. await UserAuditLogHandler.promises.addEntry(
  22. userId,
  23. operation,
  24. auditLog.initiatorId,
  25. auditLog.ipAddress,
  26. {
  27. institutionEmail,
  28. providerId,
  29. providerName
  30. }
  31. )
  32. }
  33. async function _addIdentifier(
  34. userId,
  35. externalUserId,
  36. providerId,
  37. hasEntitlement,
  38. institutionEmail,
  39. providerName,
  40. auditLog
  41. ) {
  42. // first check if institutionEmail linked to another account
  43. // before adding the identifier for the email
  44. const user = await UserGetter.promises.getUserByAnyEmail(institutionEmail)
  45. if (user && user._id.toString() !== userId.toString()) {
  46. const existingEmailData = user.emails.find(
  47. emailData => emailData.email === institutionEmail
  48. )
  49. if (existingEmailData && existingEmailData.samlProviderId) {
  50. // email exists and institution link.
  51. // Return back to requesting page with error
  52. throw new Errors.SAMLIdentityExistsError()
  53. } else {
  54. // Only email exists but not linked, so redirect to linking page
  55. // which will tell this user to log out to link
  56. throw new Errors.EmailExistsError()
  57. }
  58. }
  59. providerId = providerId.toString()
  60. await _addAuditLogEntry(
  61. true,
  62. userId,
  63. auditLog,
  64. institutionEmail,
  65. providerId,
  66. providerName
  67. )
  68. hasEntitlement = !!hasEntitlement
  69. const query = {
  70. _id: userId,
  71. 'samlIdentifiers.providerId': {
  72. $ne: providerId
  73. }
  74. }
  75. const update = {
  76. $push: {
  77. samlIdentifiers: {
  78. hasEntitlement,
  79. externalUserId,
  80. providerId
  81. }
  82. }
  83. }
  84. try {
  85. // update v2 user record
  86. const updatedUser = User.findOneAndUpdate(query, update, {
  87. new: true
  88. }).exec()
  89. return updatedUser
  90. } catch (err) {
  91. if (err.code === 11000) {
  92. throw new Errors.SAMLIdentityExistsError()
  93. } else {
  94. throw OError.tag(err)
  95. }
  96. }
  97. }
  98. async function _addInstitutionEmail(userId, email, providerId, auditLog) {
  99. const user = await UserGetter.promises.getUser(userId)
  100. const query = {
  101. _id: userId,
  102. 'emails.email': email
  103. }
  104. const update = {
  105. $set: {
  106. 'emails.$.samlProviderId': providerId.toString()
  107. }
  108. }
  109. if (user == null) {
  110. throw new Errors.NotFoundError('user not found')
  111. }
  112. const emailAlreadyAssociated = user.emails.find(e => e.email === email)
  113. if (emailAlreadyAssociated && emailAlreadyAssociated.confirmedAt) {
  114. await UserUpdater.promises.updateUser(query, update)
  115. } else if (emailAlreadyAssociated) {
  116. await UserUpdater.promises.confirmEmail(user._id, email)
  117. await UserUpdater.promises.updateUser(query, update)
  118. } else {
  119. await UserUpdater.promises.addEmailAddress(user._id, email, {}, auditLog)
  120. await UserUpdater.promises.confirmEmail(user._id, email)
  121. await UserUpdater.promises.updateUser(query, update)
  122. }
  123. }
  124. async function _sendLinkedEmail(userId, providerName, institutionEmail) {
  125. const user = await UserGetter.promises.getUser(userId, { email: 1 })
  126. const emailOptions = {
  127. to: user.email,
  128. actionDescribed: `an Institutional SSO account at ${providerName} was linked to your account ${
  129. user.email
  130. }`,
  131. action: 'institutional SSO account linked',
  132. message: [
  133. `<span style="display:inline-block;padding: 0 20px;width:100%;">Linked: <br/><b>${institutionEmail}</b></span>`
  134. ]
  135. }
  136. EmailHandler.sendEmail('securityAlert', emailOptions, error => {
  137. if (error) {
  138. logger.warn({ err: error })
  139. }
  140. })
  141. }
  142. function _sendUnlinkedEmail(primaryEmail, providerName, institutionEmail) {
  143. const emailOptions = {
  144. to: primaryEmail,
  145. actionDescribed: `an Institutional SSO account at ${providerName} was unlinked from your account ${primaryEmail}`,
  146. action: 'institutional SSO account no longer linked',
  147. message: [
  148. `<span style="display:inline-block;padding: 0 20px;width:100%;">No longer linked: <br/><b>${institutionEmail}</b></span>`
  149. ]
  150. }
  151. EmailHandler.sendEmail('securityAlert', emailOptions, error => {
  152. if (error) {
  153. logger.warn({ err: error })
  154. }
  155. })
  156. }
  157. async function getUser(providerId, externalUserId) {
  158. if (!providerId || !externalUserId) {
  159. throw new Error(
  160. `invalid arguments: providerId: ${providerId}, externalUserId: ${externalUserId}`
  161. )
  162. }
  163. const user = await User.findOne({
  164. 'samlIdentifiers.externalUserId': externalUserId.toString(),
  165. 'samlIdentifiers.providerId': providerId.toString()
  166. }).exec()
  167. return user
  168. }
  169. async function redundantSubscription(userId, providerId, providerName) {
  170. const subscription = await SubscriptionLocator.promises.getUserIndividualSubscription(
  171. userId
  172. )
  173. if (subscription) {
  174. await NotificationsBuilder.promises
  175. .redundantPersonalSubscription(
  176. {
  177. institutionId: providerId,
  178. institutionName: providerName
  179. },
  180. { _id: userId }
  181. )
  182. .create()
  183. }
  184. }
  185. async function linkAccounts(
  186. userId,
  187. externalUserId,
  188. institutionEmail,
  189. providerId,
  190. providerName,
  191. hasEntitlement,
  192. auditLog
  193. ) {
  194. await _addIdentifier(
  195. userId,
  196. externalUserId,
  197. providerId,
  198. hasEntitlement,
  199. institutionEmail,
  200. providerName,
  201. auditLog
  202. )
  203. await _addInstitutionEmail(userId, institutionEmail, providerId, auditLog)
  204. await _sendLinkedEmail(userId, providerName, institutionEmail)
  205. // update v1 affiliations record
  206. if (hasEntitlement) {
  207. await InstitutionsAPI.promises.addEntitlement(userId, institutionEmail)
  208. try {
  209. await redundantSubscription(userId, providerId, providerName)
  210. } catch (error) {
  211. logger.err({ err: error }, 'error checking redundant subscription')
  212. }
  213. } else {
  214. await InstitutionsAPI.promises.removeEntitlement(userId, institutionEmail)
  215. }
  216. }
  217. async function unlinkAccounts(
  218. userId,
  219. institutionEmail,
  220. primaryEmail,
  221. providerId,
  222. providerName,
  223. auditLog
  224. ) {
  225. providerId = providerId.toString()
  226. const query = {
  227. _id: userId
  228. }
  229. await _addAuditLogEntry(
  230. false,
  231. userId,
  232. auditLog,
  233. institutionEmail,
  234. providerId,
  235. providerName
  236. )
  237. const update = {
  238. $pull: {
  239. samlIdentifiers: {
  240. providerId
  241. }
  242. }
  243. }
  244. // update v2 user
  245. await User.update(query, update).exec()
  246. // update v1 affiliations record
  247. await InstitutionsAPI.promises.removeEntitlement(userId, institutionEmail)
  248. // send email
  249. _sendUnlinkedEmail(primaryEmail, providerName, institutionEmail)
  250. }
  251. async function updateEntitlement(
  252. userId,
  253. institutionEmail,
  254. providerId,
  255. hasEntitlement
  256. ) {
  257. providerId = providerId.toString()
  258. hasEntitlement = !!hasEntitlement
  259. const query = {
  260. _id: userId,
  261. 'samlIdentifiers.providerId': providerId.toString()
  262. }
  263. const update = {
  264. $set: {
  265. 'samlIdentifiers.$.hasEntitlement': hasEntitlement
  266. }
  267. }
  268. // update v2 user
  269. await User.update(query, update).exec()
  270. // update v1 affiliations record
  271. if (hasEntitlement) {
  272. await InstitutionsAPI.promises.addEntitlement(userId, institutionEmail)
  273. } else {
  274. await InstitutionsAPI.promises.removeEntitlement(userId, institutionEmail)
  275. }
  276. }
  277. function entitlementAttributeMatches(entitlementAttribute, entitlementMatcher) {
  278. if (Array.isArray(entitlementAttribute)) {
  279. entitlementAttribute = entitlementAttribute.join(' ')
  280. }
  281. if (
  282. typeof entitlementAttribute !== 'string' ||
  283. typeof entitlementMatcher !== 'string'
  284. ) {
  285. return false
  286. }
  287. try {
  288. const entitlementRegExp = new RegExp(entitlementMatcher)
  289. return !!entitlementAttribute.match(entitlementRegExp)
  290. } catch (err) {
  291. logger.error({ err }, 'Invalid SAML entitlement matcher')
  292. // this is likely caused by an invalid regex in the matcher string
  293. // log the error but do not bubble so that user can still sign in
  294. // even if they don't have the entitlement
  295. return false
  296. }
  297. }
  298. function userHasEntitlement(user, providerId) {
  299. providerId = providerId.toString()
  300. if (!user || !Array.isArray(user.samlIdentifiers)) {
  301. return false
  302. }
  303. for (const samlIdentifier of user.samlIdentifiers) {
  304. if (providerId && samlIdentifier.providerId !== providerId) {
  305. continue
  306. }
  307. if (samlIdentifier.hasEntitlement) {
  308. return true
  309. }
  310. }
  311. return false
  312. }
  313. const SAMLIdentityManager = {
  314. entitlementAttributeMatches,
  315. getUser,
  316. linkAccounts,
  317. redundantSubscription,
  318. unlinkAccounts,
  319. updateEntitlement,
  320. userHasEntitlement
  321. }
  322. module.exports = SAMLIdentityManager