InstitutionsAPI.js 8.1 KB

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