LaunchpadController.mjs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. }
  119. logger.debug(
  120. { email, authMethod },
  121. 'creating admin account for specified external-auth user'
  122. )
  123. let user
  124. try {
  125. user = await UserRegistrationHandler.promises.registerNewUser(body)
  126. } catch (err) {
  127. OError.tag(err, 'error with registerNewUser', {
  128. email,
  129. authMethod,
  130. })
  131. throw err
  132. }
  133. try {
  134. const reversedHostname = user.email
  135. .split('@')[1]
  136. .split('')
  137. .reverse()
  138. .join('')
  139. await User.updateOne(
  140. { _id: user._id },
  141. {
  142. $set: { isAdmin: true, emails: [{ email, reversedHostname }] },
  143. }
  144. ).exec()
  145. } catch (err) {
  146. OError.tag(err, 'error setting user to admin', {
  147. user_id: user._id,
  148. })
  149. throw err
  150. }
  151. AuthenticationController.setRedirectInSession(req, '/launchpad')
  152. logger.debug(
  153. { email, userId: user._id, authMethod },
  154. 'created first admin account'
  155. )
  156. res.json({ redir: '/launchpad', email })
  157. })
  158. }
  159. async function registerAdmin(req, res) {
  160. const { email } = req.body
  161. const { password } = req.body
  162. if (!email || !password) {
  163. logger.debug({}, 'must supply both email and password, disallow')
  164. return res.sendStatus(400)
  165. }
  166. logger.debug({ email }, 'attempted register first admin user')
  167. const exists = await _atLeastOneAdminExists()
  168. if (exists) {
  169. logger.debug(
  170. { email: req.body.email },
  171. 'already have at least one admin user, disallow'
  172. )
  173. return res.status(403).json({
  174. message: { type: 'error', text: 'admin user already exists' },
  175. })
  176. }
  177. const invalidEmail = AuthenticationManager.validateEmail(email)
  178. if (invalidEmail) {
  179. return res
  180. .status(400)
  181. .json({ message: { type: 'error', text: invalidEmail.message } })
  182. }
  183. const invalidPassword = AuthenticationManager.validatePassword(
  184. password,
  185. email
  186. )
  187. if (invalidPassword) {
  188. return res
  189. .status(400)
  190. .json({ message: { type: 'error', text: invalidPassword.message } })
  191. }
  192. const body = { email, password }
  193. const user = await UserRegistrationHandler.promises.registerNewUser(body)
  194. logger.debug({ userId: user._id }, 'making user an admin')
  195. try {
  196. const reversedHostname = user.email
  197. .split('@')[1]
  198. .split('')
  199. .reverse()
  200. .join('')
  201. await User.updateOne(
  202. { _id: user._id },
  203. {
  204. $set: {
  205. isAdmin: true,
  206. emails: [{ email, reversedHostname }],
  207. },
  208. }
  209. ).exec()
  210. } catch (err) {
  211. OError.tag(err, 'error setting user to admin', {
  212. user_id: user._id,
  213. })
  214. throw err
  215. }
  216. logger.debug({ email, userId: user._id }, 'created first admin account')
  217. res.json({ redir: '/launchpad' })
  218. }
  219. const LaunchpadController = {
  220. launchpadPage: expressify(launchpadPage),
  221. registerAdmin: expressify(registerAdmin),
  222. registerExternalAuthAdmin,
  223. sendTestEmail: expressify(sendTestEmail),
  224. _atLeastOneAdminExists,
  225. _mocks,
  226. }
  227. export default LaunchpadController