login.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. // disable all of linting
  2. // because this file is a deprecated legacy of Crowi
  3. /* eslint-disable */
  4. module.exports = function(crowi, app) {
  5. const debug = require('debug')('growi:routes:login');
  6. const logger = require('@alias/logger')('growi:routes:login');
  7. const path = require('path');
  8. const async = require('async');
  9. const mailer = crowi.getMailer();
  10. const User = crowi.model('User');
  11. const { configManager, appService, aclService } = crowi;
  12. const actions = {};
  13. const loginSuccess = function(req, res, userData) {
  14. req.user = req.session.user = userData;
  15. // update lastLoginAt
  16. userData.updateLastLoginAt(new Date(), (err, uData) => {
  17. if (err) {
  18. logger.error(`updateLastLoginAt dumps error: ${err}`);
  19. }
  20. });
  21. if (!userData.password) {
  22. return res.redirect('/me/password');
  23. }
  24. const jumpTo = req.session.jumpTo;
  25. if (jumpTo) {
  26. req.session.jumpTo = null;
  27. // prevention from open redirect
  28. try {
  29. const redirectUrl = new URL(jumpTo, `${req.protocol}://${req.get('host')}`);
  30. if (redirectUrl.hostname === req.hostname) {
  31. return res.redirect(redirectUrl);
  32. }
  33. logger.warn('Requested redirect URL is invalid, redirect to root page');
  34. }
  35. catch (err) {
  36. logger.warn('Requested redirect URL is invalid, redirect to root page', err);
  37. return res.redirect('/');
  38. }
  39. }
  40. return res.redirect('/');
  41. };
  42. const loginFailure = function(req, res) {
  43. req.flash('warningMessage', 'Sign in failure.');
  44. return res.redirect('/login');
  45. };
  46. actions.error = function(req, res) {
  47. const reason = req.params.reason;
  48. let reasonMessage = '';
  49. if (reason === 'suspended') {
  50. reasonMessage = 'This account is suspended.';
  51. }
  52. else if (reason === 'registered') {
  53. reasonMessage = 'Wait for approved by administrators.';
  54. }
  55. return res.render('login/error', {
  56. reason,
  57. reasonMessage,
  58. });
  59. };
  60. actions.login = function(req, res) {
  61. const loginForm = req.body.loginForm;
  62. if (req.method == 'POST' && req.form.isValid) {
  63. const username = loginForm.username;
  64. const password = loginForm.password;
  65. // find user
  66. User.findUserByUsernameOrEmail(username, password, (err, user) => {
  67. if (err) { return loginFailure(req, res) }
  68. // check existence and password
  69. if (!user || !user.isPasswordValid(password)) {
  70. return loginFailure(req, res);
  71. }
  72. return loginSuccess(req, res, user);
  73. });
  74. }
  75. else { // method GET
  76. if (req.form) {
  77. debug(req.form.errors);
  78. }
  79. return res.render('login', {
  80. });
  81. }
  82. };
  83. actions.register = function(req, res) {
  84. // redirect to '/' if both of these are true:
  85. // 1. user has logged in
  86. // 2. req.user is not username/email string (which is set by basic-auth-connect)
  87. if (req.user != null && req.user instanceof Object) {
  88. return res.redirect('/');
  89. }
  90. // config で closed ならさよなら
  91. if (configManager.getConfig('crowi', 'security:registrationMode') == aclService.labels.SECURITY_REGISTRATION_MODE_CLOSED) {
  92. return res.redirect('/');
  93. }
  94. if (req.method == 'POST' && req.form.isValid) {
  95. const registerForm = req.form.registerForm || {};
  96. const name = registerForm.name;
  97. const username = registerForm.username;
  98. const email = registerForm.email;
  99. const password = registerForm.password;
  100. // email と username の unique チェックする
  101. User.isRegisterable(email, username, (isRegisterable, errOn) => {
  102. let isError = false;
  103. if (!User.isEmailValid(email)) {
  104. isError = true;
  105. req.flash('registerWarningMessage', 'This email address could not be used. (Make sure the allowed email address)');
  106. }
  107. if (!isRegisterable) {
  108. if (!errOn.username) {
  109. isError = true;
  110. req.flash('registerWarningMessage', 'This User ID is not available.');
  111. }
  112. if (!errOn.email) {
  113. isError = true;
  114. req.flash('registerWarningMessage', 'This email address is already registered.');
  115. }
  116. }
  117. if (isError) {
  118. debug('isError user register error', errOn);
  119. return res.redirect('/register');
  120. }
  121. User.createUserByEmailAndPassword(name, username, email, password, undefined, (err, userData) => {
  122. if (err) {
  123. if (err.name === 'UserUpperLimitException') {
  124. req.flash('registerWarningMessage', 'Can not register more than the maximum number of users.');
  125. }
  126. else {
  127. req.flash('registerWarningMessage', 'Failed to register.');
  128. }
  129. return res.redirect('/register');
  130. }
  131. // 作成後、承認が必要なモードなら、管理者に通知する
  132. const appTitle = appService.getAppTitle();
  133. if (configManager.getConfig('crowi', 'security:registrationMode') === aclService.labels.SECURITY_REGISTRATION_MODE_RESTRICTED) {
  134. // TODO send mail
  135. User.findAdmins((err, admins) => {
  136. async.each(
  137. admins,
  138. (adminUser, next) => {
  139. mailer.send({
  140. to: adminUser.email,
  141. subject: `[${appTitle}:admin] A New User Created and Waiting for Activation`,
  142. template: path.join(crowi.localeDir, 'en-US/admin/userWaitingActivation.txt'),
  143. vars: {
  144. createdUser: userData,
  145. adminUser,
  146. url: appService.getSiteUrl(),
  147. appTitle,
  148. },
  149. },
  150. (err, s) => {
  151. debug('completed to send email: ', err, s);
  152. next();
  153. });
  154. },
  155. (err) => {
  156. debug('Sending invitation email completed.', err);
  157. },
  158. );
  159. });
  160. }
  161. // add a flash message to inform the user that processing was successful -- 2017.09.23 Yuki Takei
  162. // cz. loginSuccess method doesn't work on it's own when using passport
  163. // because `req.login()` prepared by passport is not called.
  164. req.flash('successMessage', `The user '${userData.username}' is successfully created.`);
  165. return loginSuccess(req, res, userData);
  166. });
  167. });
  168. }
  169. else { // method GET of form is not valid
  170. debug('session is', req.session);
  171. const isRegistering = true;
  172. return res.render('login', { isRegistering });
  173. }
  174. };
  175. actions.invited = async function(req, res) {
  176. if (!req.user) {
  177. return res.redirect('/login');
  178. }
  179. if (req.method == 'POST' && req.form.isValid) {
  180. const user = req.user;
  181. const invitedForm = req.form.invitedForm || {};
  182. const username = invitedForm.username;
  183. const name = invitedForm.name;
  184. const password = invitedForm.password;
  185. // check user upper limit
  186. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  187. if (isUserCountExceedsUpperLimit) {
  188. req.flash('warningMessage', 'ユーザーが上限に達したためアクティベートできません。');
  189. return res.redirect('/invited');
  190. }
  191. const creatable = await User.isRegisterableUsername(username);
  192. if (creatable) {
  193. try {
  194. await user.activateInvitedUser(username, name, password);
  195. return res.redirect('/');
  196. }
  197. catch (err) {
  198. req.flash('warningMessage', 'アクティベートに失敗しました。');
  199. return res.render('invited');
  200. }
  201. }
  202. else {
  203. req.flash('warningMessage', '利用できないユーザーIDです。');
  204. debug('username', username);
  205. return res.render('invited');
  206. }
  207. }
  208. else {
  209. return res.render('invited', {
  210. });
  211. }
  212. };
  213. actions.updateInvitedUser = function(req, res) {
  214. return res.redirect('/');
  215. };
  216. return actions;
  217. };