UserInfoController.js 2.2 KB

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