UserInfoController.mjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import UserGetter from './UserGetter.js'
  2. import SessionManager from '../Authentication/SessionManager.js'
  3. import mongodb from 'mongodb-legacy'
  4. import { expressify } from '@overleaf/promise-utils'
  5. const { ObjectId } = mongodb
  6. function getLoggedInUsersPersonalInfo(req, res, next) {
  7. const userId = SessionManager.getLoggedInUserId(req.session)
  8. if (!userId) {
  9. return next(new Error('User is not logged in'))
  10. }
  11. UserGetter.getUser(
  12. userId,
  13. {
  14. first_name: true,
  15. last_name: true,
  16. role: true,
  17. institution: true,
  18. email: true,
  19. signUpDate: true,
  20. },
  21. function (error, user) {
  22. if (error) {
  23. return next(error)
  24. }
  25. sendFormattedPersonalInfo(user, res, next)
  26. }
  27. )
  28. }
  29. function getPersonalInfo(req, res, next) {
  30. let query
  31. const userId = req.params.user_id
  32. if (/^\d+$/.test(userId)) {
  33. query = { 'overleaf.id': parseInt(userId, 10) }
  34. } else if (/^[a-f0-9]{24}$/.test(userId)) {
  35. query = { _id: new ObjectId(userId) }
  36. } else {
  37. return res.sendStatus(400)
  38. }
  39. UserGetter.getUser(
  40. query,
  41. { _id: true, first_name: true, last_name: true, email: true },
  42. function (error, user) {
  43. if (error) {
  44. return next(error)
  45. }
  46. if (!user) {
  47. return res.sendStatus(404)
  48. }
  49. sendFormattedPersonalInfo(user, res, next)
  50. }
  51. )
  52. }
  53. function sendFormattedPersonalInfo(user, res, next) {
  54. const info = formatPersonalInfo(user)
  55. res.json(info)
  56. }
  57. function formatPersonalInfo(user) {
  58. if (!user) {
  59. return {}
  60. }
  61. const formattedUser = { id: user._id.toString() }
  62. for (const key of [
  63. 'first_name',
  64. 'last_name',
  65. 'email',
  66. 'signUpDate',
  67. 'role',
  68. 'institution',
  69. ]) {
  70. if (user[key]) {
  71. formattedUser[key] = user[key]
  72. }
  73. }
  74. return formattedUser
  75. }
  76. async function getUserFeatures(req, res, next) {
  77. const userId = SessionManager.getLoggedInUserId(req.session)
  78. if (!userId) {
  79. throw new Error('User is not logged in')
  80. }
  81. const features = await UserGetter.promises.getUserFeatures(userId)
  82. return res.json(features)
  83. }
  84. export default {
  85. getLoggedInUsersPersonalInfo,
  86. getPersonalInfo,
  87. sendFormattedPersonalInfo,
  88. formatPersonalInfo,
  89. getUserFeatures: expressify(getUserFeatures),
  90. }