LaunchpadController.mjs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import OError from '@overleaf/o-error'
  2. import { expressify } from '@overleaf/promise-utils'
  3. import Settings from '@overleaf/settings'
  4. import Path from 'node:path'
  5. import crypto from 'node:crypto'
  6. import logger from '@overleaf/logger'
  7. import UserRegistrationHandler from '../../../../app/src/Features/User/UserRegistrationHandler.mjs'
  8. import EmailHandler from '../../../../app/src/Features/Email/EmailHandler.mjs'
  9. import UserGetter from '../../../../app/src/Features/User/UserGetter.mjs'
  10. import { User } from '../../../../app/src/models/User.mjs'
  11. import AuthenticationManager from '../../../../app/src/Features/Authentication/AuthenticationManager.mjs'
  12. import AuthenticationController from '../../../../app/src/Features/Authentication/AuthenticationController.mjs'
  13. import SessionManager from '../../../../app/src/Features/Authentication/SessionManager.mjs'
  14. import AdminAuthorizationHelper from '../../../../app/src/Features/Helpers/AdminAuthorizationHelper.mjs'
  15. const { hasAdminAccess } = AdminAuthorizationHelper
  16. /**
  17. * Container for functions that need to be mocked in tests
  18. *
  19. * TODO: Rewrite tests in terms of exported functions only
  20. */
  21. const _mocks = {}
  22. _mocks._atLeastOneAdminExists = async () => {
  23. const user = await UserGetter.promises.getUser(
  24. { isAdmin: true },
  25. { _id: 1, isAdmin: 1 }
  26. )
  27. return Boolean(user)
  28. }
  29. async function _atLeastOneAdminExists() {
  30. return await _mocks._atLeastOneAdminExists()
  31. }
  32. function getAuthMethod() {
  33. if (Settings.ldap) {
  34. return 'ldap'
  35. } else if (Settings.saml) {
  36. return 'saml'
  37. } else {
  38. return 'local'
  39. }
  40. }
  41. async function launchpadPage(req, res) {
  42. // TODO: check if we're using external auth?
  43. // * how does all this work with ldap and saml?
  44. const sessionUser = SessionManager.getSessionUser(req.session)
  45. const authMethod = getAuthMethod()
  46. const adminUserExists = await _atLeastOneAdminExists()
  47. if (!sessionUser) {
  48. if (!adminUserExists) {
  49. res.render(Path.resolve(import.meta.dirname, '../views/launchpad'), {
  50. adminUserExists,
  51. authMethod,
  52. })
  53. } else {
  54. AuthenticationController.setRedirectInSession(req)
  55. res.redirect('/login')
  56. }
  57. } else {
  58. const user = await UserGetter.promises.getUser(sessionUser._id, {
  59. isAdmin: 1,
  60. })
  61. if (hasAdminAccess(user)) {
  62. res.render(Path.resolve(import.meta.dirname, '../views/launchpad'), {
  63. wsUrl: Settings.wsUrl,
  64. adminUserExists,
  65. authMethod,
  66. })
  67. } else {
  68. res.redirect('/restricted')
  69. }
  70. }
  71. }
  72. async function sendTestEmail(req, res) {
  73. const { email } = req.body
  74. if (!email) {
  75. logger.debug({}, 'no email address supplied')
  76. return res.status(400).json({
  77. message: 'no email address supplied',
  78. })
  79. }
  80. logger.debug({ email }, 'sending test email')
  81. const emailOptions = { to: email }
  82. try {
  83. await EmailHandler.promises.sendEmail('testEmail', emailOptions)
  84. logger.debug({ email }, 'sent test email')
  85. res.json({ message: res.locals.translate('email_sent') })
  86. } catch (err) {
  87. OError.tag(err, 'error sending test email', {
  88. email,
  89. })
  90. throw err
  91. }
  92. }
  93. function registerExternalAuthAdmin(authMethod) {
  94. return expressify(async function (req, res) {
  95. if (getAuthMethod() !== authMethod) {
  96. logger.debug(
  97. { authMethod },
  98. 'trying to register external admin, but that auth service is not enabled, disallow'
  99. )
  100. return res.sendStatus(403)
  101. }
  102. const { email } = req.body
  103. if (!email) {
  104. logger.debug({ authMethod }, 'no email supplied, disallow')
  105. return res.sendStatus(400)
  106. }
  107. logger.debug({ email }, 'attempted register first admin user')
  108. const exists = await _atLeastOneAdminExists()
  109. if (exists) {
  110. logger.debug({ email }, 'already have at least one admin user, disallow')
  111. return res.sendStatus(403)
  112. }
  113. const body = {
  114. email,
  115. password: crypto.randomBytes(32).toString('hex'),
  116. first_name: email,
  117. last_name: '',
  118. analyticsId: crypto.randomUUID(),
  119. }
  120. logger.debug(
  121. { email, authMethod },
  122. 'creating admin account for specified external-auth user'
  123. )
  124. let user
  125. try {
  126. user = await UserRegistrationHandler.promises.registerNewUser(body)
  127. } catch (err) {
  128. OError.tag(err, 'error with registerNewUser', {
  129. email,
  130. authMethod,
  131. })
  132. throw err
  133. }
  134. try {
  135. const reversedHostname = user.email
  136. .split('@')[1]
  137. .split('')
  138. .reverse()
  139. .join('')
  140. await User.updateOne(
  141. { _id: user._id },
  142. {
  143. $set: { isAdmin: true, emails: [{ email, reversedHostname }] },
  144. }
  145. ).exec()
  146. } catch (err) {
  147. OError.tag(err, 'error setting user to admin', {
  148. user_id: user._id,
  149. })
  150. throw err
  151. }
  152. AuthenticationController.setRedirectInSession(req, '/launchpad')
  153. logger.debug(
  154. { email, userId: user._id, authMethod },
  155. 'created first admin account'
  156. )
  157. res.json({ redir: '/launchpad', email })
  158. })
  159. }
  160. async function registerAdmin(req, res) {
  161. const { email } = req.body
  162. const { password } = req.body
  163. if (!email || !password) {
  164. logger.debug({}, 'must supply both email and password, disallow')
  165. return res.sendStatus(400)
  166. }
  167. logger.debug({ email }, 'attempted register first admin user')
  168. const exists = await _atLeastOneAdminExists()
  169. if (exists) {
  170. logger.debug(
  171. { email: req.body.email },
  172. 'already have at least one admin user, disallow'
  173. )
  174. return res.status(403).json({
  175. message: { type: 'error', text: 'admin user already exists' },
  176. })
  177. }
  178. const invalidEmail = AuthenticationManager.validateEmail(email)
  179. if (invalidEmail) {
  180. return res
  181. .status(400)
  182. .json({ message: { type: 'error', text: invalidEmail.message } })
  183. }
  184. const invalidPassword = AuthenticationManager.validatePassword(
  185. password,
  186. email
  187. )
  188. if (invalidPassword) {
  189. return res
  190. .status(400)
  191. .json({ message: { type: 'error', text: invalidPassword.message } })
  192. }
  193. const body = { email, password, analyticsId: crypto.randomUUID() }
  194. const user = await UserRegistrationHandler.promises.registerNewUser(body)
  195. logger.debug({ userId: user._id }, 'making user an admin')
  196. try {
  197. const reversedHostname = user.email
  198. .split('@')[1]
  199. .split('')
  200. .reverse()
  201. .join('')
  202. await User.updateOne(
  203. { _id: user._id },
  204. {
  205. $set: {
  206. isAdmin: true,
  207. emails: [{ email, reversedHostname }],
  208. },
  209. }
  210. ).exec()
  211. } catch (err) {
  212. OError.tag(err, 'error setting user to admin', {
  213. user_id: user._id,
  214. })
  215. throw err
  216. }
  217. logger.debug({ email, userId: user._id }, 'created first admin account')
  218. res.json({ redir: '/launchpad' })
  219. }
  220. const LaunchpadController = {
  221. launchpadPage: expressify(launchpadPage),
  222. registerAdmin: expressify(registerAdmin),
  223. registerExternalAuthAdmin,
  224. sendTestEmail: expressify(sendTestEmail),
  225. _atLeastOneAdminExists,
  226. _mocks,
  227. }
  228. export default LaunchpadController