InstitutionsAPI.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. const OError = require('@overleaf/o-error')
  2. const logger = require('logger-sharelatex')
  3. const metrics = require('@overleaf/metrics')
  4. const settings = require('@overleaf/settings')
  5. const request = require('request')
  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(requestOptions, callback) {
  193. if (!settings.apis.v1.url) {
  194. return callback(null)
  195. } // service is not configured
  196. if (!requestOptions.extraSuccessStatusCodes) {
  197. requestOptions.extraSuccessStatusCodes = []
  198. }
  199. request(
  200. {
  201. method: requestOptions.method,
  202. url: `${settings.apis.v1.url}${requestOptions.path}`,
  203. body: requestOptions.body,
  204. auth: { user: settings.apis.v1.user, pass: settings.apis.v1.pass },
  205. json: true,
  206. timeout: 20 * 1000,
  207. },
  208. function (error, response, body) {
  209. if (error) {
  210. return callback(
  211. new V1ConnectionError('error getting affiliations from v1').withCause(
  212. error
  213. )
  214. )
  215. }
  216. if (response && response.statusCode >= 500) {
  217. return callback(
  218. new V1ConnectionError({
  219. message: 'error getting affiliations from v1',
  220. info: {
  221. status: response.statusCode,
  222. body: body,
  223. },
  224. })
  225. )
  226. }
  227. let isSuccess = response.statusCode >= 200 && response.statusCode < 300
  228. if (!isSuccess) {
  229. isSuccess = requestOptions.extraSuccessStatusCodes.includes(
  230. response.statusCode
  231. )
  232. }
  233. if (!isSuccess) {
  234. let errorMessage
  235. if (body && body.errors) {
  236. errorMessage = `${response.statusCode}: ${body.errors}`
  237. } else {
  238. errorMessage = `${requestOptions.defaultErrorMessage}: ${response.statusCode}`
  239. }
  240. logger.warn(
  241. { path: requestOptions.path, body: requestOptions.body },
  242. errorMessage
  243. )
  244. return callback(
  245. new OError(errorMessage, { statusCode: response.statusCode })
  246. )
  247. }
  248. callback(null, body)
  249. }
  250. )
  251. }
  252. ;[
  253. 'getInstitutionAffiliations',
  254. 'getUserAffiliations',
  255. 'addAffiliation',
  256. 'removeAffiliation',
  257. ].map(method =>
  258. metrics.timeAsyncMethod(
  259. InstitutionsAPI,
  260. method,
  261. 'mongo.InstitutionsAPI',
  262. logger
  263. )
  264. )
  265. InstitutionsAPI.promises = promisifyAll(InstitutionsAPI)
  266. module.exports = InstitutionsAPI