LaunchpadController.mjs 6.8 KB

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