InstitutionsAPI.js 8.1 KB

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