user-activation.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import path from 'path';
  2. import { ErrorV3 } from '@growi/core/dist/models';
  3. import { format, subSeconds } from 'date-fns';
  4. import { body, validationResult } from 'express-validator';
  5. import { SupportedAction } from '~/interfaces/activity';
  6. import { RegistrationMode } from '~/interfaces/registration-mode';
  7. import UserRegistrationOrder from '~/server/models/user-registration-order';
  8. import { configManager } from '~/server/service/config-manager';
  9. import { getTranslation } from '~/server/service/i18next';
  10. import loggerFactory from '~/utils/logger';
  11. const logger = loggerFactory('growi:routes:apiv3:user-activation');
  12. const PASSOWRD_MINIMUM_NUMBER = 8;
  13. // validation rules for complete registration form
  14. export const completeRegistrationRules = () => {
  15. return [
  16. body('username')
  17. .matches(/^[\da-zA-Z\-_.]+$/)
  18. .withMessage('Username has invalid characters')
  19. .not()
  20. .isEmpty()
  21. .withMessage('Username field is required'),
  22. body('name').not().isEmpty().withMessage('Name field is required'),
  23. body('token').not().isEmpty().withMessage('Token value is required'),
  24. body('password')
  25. .matches(/^[\x20-\x7F]*$/)
  26. .withMessage('Password has invalid character')
  27. .isLength({ min: PASSOWRD_MINIMUM_NUMBER })
  28. .withMessage('Password minimum character should be more than 8 characters')
  29. .not()
  30. .isEmpty()
  31. .withMessage('Password field is required'),
  32. ];
  33. };
  34. // middleware to validate complete registration form
  35. export const validateCompleteRegistration = (req, res, next) => {
  36. const errors = validationResult(req);
  37. if (errors.isEmpty()) {
  38. return next();
  39. }
  40. const extractedErrors: string[] = [];
  41. errors.array().map(err => extractedErrors.push(err.msg));
  42. return res.apiv3Err(extractedErrors);
  43. };
  44. async function sendEmailToAllAdmins(userData, admins, appTitle, mailService, template, url) {
  45. admins.map((admin) => {
  46. return mailService.send({
  47. to: admin.email,
  48. subject: `[${appTitle}:admin] A New User Created and Waiting for Activation`,
  49. template,
  50. vars: {
  51. createdUser: userData,
  52. admin,
  53. url,
  54. appTitle,
  55. },
  56. });
  57. });
  58. }
  59. export const completeRegistrationAction = (crowi) => {
  60. const User = crowi.model('User');
  61. const activityEvent = crowi.event('activity');
  62. const {
  63. aclService,
  64. appService,
  65. mailService,
  66. } = crowi;
  67. return async function(req, res) {
  68. const { t } = await getTranslation();
  69. if (req.user != null) {
  70. return res.apiv3Err(new ErrorV3('You have been logged in', 'registration-failed'), 403);
  71. }
  72. // error when registration is not allowed
  73. if (configManager.getConfig('crowi', 'security:registrationMode') === aclService.labels.SECURITY_REGISTRATION_MODE_CLOSED) {
  74. return res.apiv3Err(new ErrorV3('Registration closed', 'registration-failed'), 403);
  75. }
  76. // error when email authentication is disabled
  77. if (configManager.getConfig('crowi', 'security:passport-local:isEmailAuthenticationEnabled') !== true) {
  78. return res.apiv3Err(new ErrorV3('Email authentication configuration is disabled', 'registration-failed'), 403);
  79. }
  80. const { userRegistrationOrder } = req;
  81. const registerForm = req.body;
  82. const email = userRegistrationOrder.email;
  83. const name = registerForm.name;
  84. const username = registerForm.username;
  85. const password = registerForm.password;
  86. // email と username の unique チェックする
  87. User.isRegisterable(email, username, (isRegisterable, errOn) => {
  88. let isError = false;
  89. let errorMessage = '';
  90. if (!User.isEmailValid(email)) {
  91. isError = true;
  92. errorMessage += t('message.email_address_could_not_be_used');
  93. }
  94. if (!isRegisterable) {
  95. if (!errOn.username) {
  96. isError = true;
  97. errorMessage += t('message.user_id_is_not_available');
  98. }
  99. if (!errOn.email) {
  100. isError = true;
  101. errorMessage += t('message.email_address_is_already_registered');
  102. }
  103. }
  104. if (isError) {
  105. return res.apiv3Err(new ErrorV3(errorMessage, 'registration-failed'), 403);
  106. }
  107. User.createUserByEmailAndPassword(name, username, email, password, undefined, async(err, userData) => {
  108. if (err) {
  109. if (err.name === 'UserUpperLimitException') {
  110. errorMessage = t('message.can_not_register_maximum_number_of_users');
  111. }
  112. else {
  113. errorMessage = t('message.failed_to_register');
  114. }
  115. return res.apiv3Err(new ErrorV3(errorMessage, 'registration-failed'), 403);
  116. }
  117. const parameters = { action: SupportedAction.ACTION_USER_REGISTRATION_SUCCESS };
  118. activityEvent.emit('update', res.locals.activity._id, parameters);
  119. userRegistrationOrder.revokeOneTimeToken();
  120. if (configManager.getConfig('crowi', 'security:registrationMode') === aclService.labels.SECURITY_REGISTRATION_MODE_RESTRICTED) {
  121. const isMailerSetup = mailService.isMailerSetup ?? false;
  122. if (isMailerSetup) {
  123. const admins = await User.findAdmins();
  124. const appTitle = appService.getAppTitle();
  125. const locale = configManager.getConfig('crowi', 'app:globalLang');
  126. const template = path.join(crowi.localeDir, `${locale}/admin/userWaitingActivation.ejs`);
  127. const url = appService.getSiteUrl();
  128. sendEmailToAllAdmins(userData, admins, appTitle, mailService, template, url);
  129. }
  130. // This 'completeRegistrationAction' should not be able to be called if the email settings is not set up in the first place.
  131. // So this method dows not stop processing as an error, but only displays a warning. -- 2022.11.01 Yuki Takei
  132. else {
  133. logger.warn('E-mail Settings must be set up.');
  134. }
  135. return res.apiv3({});
  136. }
  137. req.login(userData, (err) => {
  138. if (err) {
  139. logger.debug(err);
  140. }
  141. else {
  142. // update lastLoginAt
  143. userData.updateLastLoginAt(new Date(), (err) => {
  144. if (err) {
  145. logger.error(`updateLastLoginAt dumps error: ${err}`);
  146. }
  147. });
  148. }
  149. // userData.password can't be empty but, prepare redirect because password property in User Model is optional
  150. // https://github.com/weseek/growi/pull/6670
  151. const redirectTo = userData.password != null ? '/' : '/me#password_settings';
  152. return res.apiv3({ redirectTo });
  153. });
  154. });
  155. });
  156. };
  157. };
  158. // validation rules for registration form when email authentication enabled
  159. export const registerRules = () => {
  160. return [
  161. body('registerForm.email')
  162. .isEmail()
  163. .withMessage('Email format is invalid.')
  164. .exists()
  165. .withMessage('Email field is required.'),
  166. ];
  167. };
  168. // middleware to validate register form if email authentication enabled
  169. export const validateRegisterForm = (req, res, next) => {
  170. const errors = validationResult(req);
  171. if (errors.isEmpty()) {
  172. return next();
  173. }
  174. const extractedErrors: string[] = [];
  175. errors.array().map(err => extractedErrors.push(err.msg));
  176. return res.apiv3Err(extractedErrors, 400);
  177. };
  178. async function makeRegistrationEmailToken(email, crowi) {
  179. const {
  180. mailService,
  181. localeDir,
  182. appService,
  183. } = crowi;
  184. const isMailerSetup = mailService.isMailerSetup ?? false;
  185. if (!isMailerSetup) {
  186. throw Error('mailService is not setup');
  187. }
  188. const locale = configManager.getConfig('crowi', 'app:globalLang');
  189. const appUrl = appService.getSiteUrl();
  190. const userRegistrationOrder = await UserRegistrationOrder.createUserRegistrationOrder(email);
  191. const grwTzoffsetSec = crowi.appService.getTzoffset() * 60;
  192. const expiredAt = subSeconds(userRegistrationOrder.expiredAt, grwTzoffsetSec);
  193. const formattedExpiredAt = format(expiredAt, 'yyyy/MM/dd HH:mm');
  194. const url = new URL(`/user-activation/${userRegistrationOrder.token}`, appUrl);
  195. const oneTimeUrl = url.href;
  196. return mailService.send({
  197. to: email,
  198. subject: '[GROWI] User Activation',
  199. template: path.join(localeDir, `${locale}/notifications/userActivation.ejs`),
  200. vars: {
  201. appTitle: appService.getAppTitle(),
  202. email,
  203. expiredAt: formattedExpiredAt,
  204. url: oneTimeUrl,
  205. },
  206. });
  207. }
  208. export const registerAction = (crowi) => {
  209. const User = crowi.model('User');
  210. return async function(req, res) {
  211. const registerForm = req.body.registerForm || {};
  212. const email = registerForm.email;
  213. const isRegisterableEmail = await User.isRegisterableEmail(email);
  214. const registrationMode = configManager.getConfig('crowi', 'security:registrationMode') as RegistrationMode;
  215. const isEmailValid = await User.isEmailValid(email);
  216. if (registrationMode === RegistrationMode.CLOSED) {
  217. return res.apiv3Err(['message.registration_closed'], 400);
  218. }
  219. if (!isRegisterableEmail) {
  220. req.body.registerForm.email = email;
  221. return res.apiv3Err(['message.email_address_is_already_registered'], 400);
  222. }
  223. if (!isEmailValid) {
  224. return res.apiv3Err(['message.email_address_could_not_be_used'], 400);
  225. }
  226. try {
  227. await makeRegistrationEmailToken(email, crowi);
  228. }
  229. catch (err) {
  230. return res.apiv3Err(err);
  231. }
  232. return res.apiv3({ redirectTo: '/login#register' });
  233. };
  234. };