InstitutionsAPI.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. const OError = require('@overleaf/o-error')
  2. const logger = require('@overleaf/logger')
  3. const metrics = require('@overleaf/metrics')
  4. const settings = require('@overleaf/settings')
  5. const request = require('requestretry')
  6. const { promisifyAll } = require('../../util/promises')
  7. const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
  8. const {
  9. V1ConnectionError,
  10. InvalidInstitutionalEmailError,
  11. } = require('../Errors/Errors')
  12. const InstitutionsAPI = {
  13. getInstitutionAffiliations(institutionId, callback) {
  14. makeAffiliationRequest(
  15. {
  16. method: 'GET',
  17. path: `/api/v2/institutions/${institutionId.toString()}/affiliations`,
  18. defaultErrorMessage: "Couldn't get institution affiliations",
  19. },
  20. (error, body) => callback(error, body || [])
  21. )
  22. },
  23. getInstitutionAffiliationsCounts(institutionId, callback) {
  24. makeAffiliationRequest(
  25. {
  26. method: 'GET',
  27. path: `/api/v2/institutions/${institutionId.toString()}/affiliations_counts`,
  28. defaultErrorMessage: "Couldn't get institution counts",
  29. },
  30. (error, body) => callback(error, body || [])
  31. )
  32. },
  33. getLicencesForAnalytics(lag, queryDate, callback) {
  34. makeAffiliationRequest(
  35. {
  36. method: 'GET',
  37. path: `/api/v2/institutions/institutions_licences`,
  38. body: { query_date: queryDate, lag },
  39. defaultErrorMessage: 'Could not get institutions licences',
  40. },
  41. callback
  42. )
  43. },
  44. getUserAffiliations(userId, callback) {
  45. makeAffiliationRequest(
  46. {
  47. method: 'GET',
  48. path: `/api/v2/users/${userId.toString()}/affiliations`,
  49. defaultErrorMessage: "Couldn't get user affiliations",
  50. },
  51. (error, body) => callback(error, body || [])
  52. )
  53. },
  54. getUsersNeedingReconfirmationsLapsedProcessed(callback) {
  55. makeAffiliationRequest(
  56. {
  57. method: 'GET',
  58. path: '/api/v2/institutions/need_reconfirmation_lapsed_processed',
  59. defaultErrorMessage:
  60. 'Could not get users that need reconfirmations lapsed processed',
  61. },
  62. (error, body) => callback(error, body || [])
  63. )
  64. },
  65. addAffiliation(userId, email, affiliationOptions, callback) {
  66. if (!callback) {
  67. // affiliationOptions is optional
  68. callback = affiliationOptions
  69. affiliationOptions = {}
  70. }
  71. const {
  72. university,
  73. department,
  74. role,
  75. confirmedAt,
  76. entitlement,
  77. rejectIfBlocklisted,
  78. } = affiliationOptions
  79. makeAffiliationRequest(
  80. {
  81. method: 'POST',
  82. path: `/api/v2/users/${userId.toString()}/affiliations`,
  83. body: {
  84. email,
  85. university,
  86. department,
  87. role,
  88. confirmedAt,
  89. entitlement,
  90. rejectIfBlocklisted,
  91. },
  92. defaultErrorMessage: "Couldn't create affiliation",
  93. },
  94. function (error, body) {
  95. if (error) {
  96. if (error.info && error.info.statusCode === 422) {
  97. return callback(
  98. new InvalidInstitutionalEmailError(error.message).withCause(error)
  99. )
  100. }
  101. return callback(error)
  102. }
  103. if (!university) {
  104. return callback(null, body)
  105. }
  106. // have notifications delete any ip matcher notifications for this university
  107. NotificationsBuilder.ipMatcherAffiliation(userId).read(
  108. university.id,
  109. function (err) {
  110. if (err) {
  111. // log and ignore error
  112. logger.err(
  113. { err },
  114. 'Something went wrong marking ip notifications read'
  115. )
  116. }
  117. callback(null, body)
  118. }
  119. )
  120. }
  121. )
  122. },
  123. removeAffiliation(userId, email, callback) {
  124. makeAffiliationRequest(
  125. {
  126. method: 'POST',
  127. path: `/api/v2/users/${userId.toString()}/affiliations/remove`,
  128. body: { email },
  129. extraSuccessStatusCodes: [404], // `Not Found` responses are considered successful
  130. defaultErrorMessage: "Couldn't remove affiliation",
  131. },
  132. callback
  133. )
  134. },
  135. endorseAffiliation(userId, email, role, department, callback) {
  136. makeAffiliationRequest(
  137. {
  138. method: 'POST',
  139. path: `/api/v2/users/${userId.toString()}/affiliations/endorse`,
  140. body: { email, role, department },
  141. defaultErrorMessage: "Couldn't endorse affiliation",
  142. },
  143. callback
  144. )
  145. },
  146. deleteAffiliations(userId, callback) {
  147. makeAffiliationRequest(
  148. {
  149. method: 'DELETE',
  150. path: `/api/v2/users/${userId.toString()}/affiliations`,
  151. defaultErrorMessage: "Couldn't delete affiliations",
  152. },
  153. callback
  154. )
  155. },
  156. addEntitlement(userId, email, callback) {
  157. makeAffiliationRequest(
  158. {
  159. method: 'POST',
  160. path: `/api/v2/users/${userId}/affiliations/add_entitlement`,
  161. body: { email },
  162. defaultErrorMessage: "Couldn't add entitlement",
  163. },
  164. callback
  165. )
  166. },
  167. removeEntitlement(userId, email, callback) {
  168. makeAffiliationRequest(
  169. {
  170. method: 'POST',
  171. path: `/api/v2/users/${userId}/affiliations/remove_entitlement`,
  172. body: { email },
  173. defaultErrorMessage: "Couldn't remove entitlement",
  174. extraSuccessStatusCodes: [404],
  175. },
  176. callback
  177. )
  178. },
  179. sendUsersWithReconfirmationsLapsedProcessed(users, callback) {
  180. makeAffiliationRequest(
  181. {
  182. method: 'POST',
  183. path: '/api/v2/institutions/reconfirmation_lapsed_processed',
  184. body: { users },
  185. defaultErrorMessage:
  186. 'Could not update reconfirmation_lapsed_processed_at',
  187. },
  188. (error, body) => callback(error, body || [])
  189. )
  190. },
  191. }
  192. function makeAffiliationRequest(options, callback) {
  193. if (!settings.apis.v1.url) {
  194. return callback(null)
  195. } // service is not configured
  196. if (!options.extraSuccessStatusCodes) {
  197. options.extraSuccessStatusCodes = []
  198. }
  199. const requestOptions = {
  200. method: options.method,
  201. url: `${settings.apis.v1.url}${options.path}`,
  202. body: options.body,
  203. auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass },
  204. json: true,
  205. timeout: settings.apis.v1.timeout,
  206. }
  207. if (options.method === 'GET') {
  208. requestOptions.maxAttempts = 3
  209. requestOptions.retryDelay = 500
  210. } else {
  211. requestOptions.maxAttempts = 0
  212. }
  213. request(requestOptions, function (error, response, body) {
  214. if (error) {
  215. return callback(
  216. new V1ConnectionError('error getting affiliations from v1').withCause(
  217. error
  218. )
  219. )
  220. }
  221. if (response && response.statusCode >= 500) {
  222. return callback(
  223. new V1ConnectionError({
  224. message: 'error getting affiliations from v1',
  225. info: {
  226. status: response.statusCode,
  227. body,
  228. },
  229. })
  230. )
  231. }
  232. let isSuccess = response.statusCode >= 200 && response.statusCode < 300
  233. if (!isSuccess) {
  234. isSuccess = options.extraSuccessStatusCodes.includes(response.statusCode)
  235. }
  236. if (!isSuccess) {
  237. let errorMessage
  238. if (body && body.errors) {
  239. errorMessage = `${response.statusCode}: ${body.errors}`
  240. } else {
  241. errorMessage = `${options.defaultErrorMessage}: ${response.statusCode}`
  242. }
  243. logger.warn({ path: options.path, body: options.body }, errorMessage)
  244. return callback(
  245. new OError(errorMessage, { statusCode: response.statusCode })
  246. )
  247. }
  248. callback(null, body)
  249. })
  250. }
  251. ;[
  252. 'getInstitutionAffiliations',
  253. 'getUserAffiliations',
  254. 'addAffiliation',
  255. 'removeAffiliation',
  256. ].map(method =>
  257. metrics.timeAsyncMethod(
  258. InstitutionsAPI,
  259. method,
  260. 'mongo.InstitutionsAPI',
  261. logger
  262. )
  263. )
  264. InstitutionsAPI.promises = promisifyAll(InstitutionsAPI)
  265. module.exports = InstitutionsAPI