login-passport.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. module.exports = function(crowi, app) {
  2. 'use strict';
  3. var debug = require('debug')('crowi:routes:login-passport')
  4. , passport = require('passport')
  5. , config = crowi.getConfig()
  6. , Config = crowi.model('Config')
  7. , ExternalAccount = crowi.model('ExternalAccount')
  8. , passportService = crowi.passportService
  9. ;
  10. /**
  11. * success handler
  12. * @param {*} req
  13. * @param {*} res
  14. */
  15. const loginSuccess = (req, res, user) => {
  16. // update lastLoginAt
  17. user.updateLastLoginAt(new Date(), (err, userData) => {
  18. if (err) {
  19. console.log(`updateLastLoginAt dumps error: ${err}`);
  20. debug(`updateLastLoginAt dumps error: ${err}`);
  21. }
  22. });
  23. var jumpTo = req.session.jumpTo;
  24. if (jumpTo) {
  25. req.session.jumpTo = null;
  26. return res.redirect(jumpTo);
  27. } else {
  28. return res.redirect('/');
  29. }
  30. };
  31. /**
  32. * failure handler
  33. * @param {*} req
  34. * @param {*} res
  35. */
  36. const loginFailure = (req, res, next) => {
  37. req.flash('errorMessage', 'Sign in failure.');
  38. return res.redirect('/login');
  39. };
  40. /**
  41. * return true(valid) or false(invalid)
  42. *
  43. * true ... group filter is not defined or the user has one or more groups
  44. * false ... group filter is defined and the user has any group
  45. *
  46. */
  47. function isValidLdapUserByGroupFilter(user) {
  48. let bool = true;
  49. if (user._groups != null) {
  50. if (user._groups.length == 0) {
  51. bool = false;
  52. }
  53. }
  54. return bool;
  55. }
  56. /**
  57. * middleware that login with LdapStrategy
  58. * @param {*} req
  59. * @param {*} res
  60. * @param {*} next
  61. */
  62. const loginWithLdap = (req, res, next) => {
  63. if (!passportService.isLdapStrategySetup) {
  64. debug('LdapStrategy has not been set up');
  65. return next();
  66. }
  67. const loginForm = req.body.loginForm;
  68. if (!req.form.isValid) {
  69. debug("invalid form");
  70. return res.render('login', {
  71. });
  72. }
  73. passport.authenticate('ldapauth', (err, ldapAccountInfo, info) => {
  74. if (res.headersSent) { // dirty hack -- 2017.09.25
  75. return; // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
  76. }
  77. debug('--- authenticate with LdapStrategy ---');
  78. debug('ldapAccountInfo', ldapAccountInfo);
  79. debug('info', info);
  80. if (err) { // DB Error
  81. console.log('LDAP Server Error: ', err);
  82. req.flash('warningMessage', 'LDAP Server Error occured.');
  83. return next(); // pass and the flash message is displayed when all of authentications are failed.
  84. }
  85. // authentication failure
  86. if (!ldapAccountInfo) { return next(); }
  87. // check groups
  88. if (!isValidLdapUserByGroupFilter(ldapAccountInfo)) {
  89. return loginFailure(req, res, next);
  90. }
  91. /*
  92. * authentication success
  93. */
  94. // it is guaranteed that username that is input from form can be acquired
  95. // because this processes after authentication
  96. const ldapAccountId = passportService.getLdapAccountIdFromReq(req);
  97. const attrMapUsername = passportService.getLdapAttrNameMappedToUsername();
  98. const usernameToBeRegistered = ldapAccountInfo[attrMapUsername];
  99. // find or register(create) user
  100. ExternalAccount.findOrRegister('ldap', ldapAccountId, usernameToBeRegistered)
  101. .then((externalAccount) => {
  102. return externalAccount.getPopulatedUser();
  103. })
  104. .then((user) => {
  105. // login
  106. req.logIn(user, (err) => {
  107. if (err) { return next(); }
  108. else {
  109. return loginSuccess(req, res, user);
  110. }
  111. });
  112. })
  113. .catch((err) => {
  114. if (err.name != null && err.name === 'DuplicatedUsernameException') {
  115. req.flash('isDuplicatedUsernameExceptionOccured', true);
  116. return next();
  117. }
  118. else {
  119. return next(err);
  120. }
  121. });
  122. })(req, res, next);
  123. }
  124. /**
  125. * middleware that test credentials with LdapStrategy
  126. *
  127. * @param {*} req
  128. * @param {*} res
  129. */
  130. const testLdapCredentials = (req, res) => {
  131. if (!passportService.isLdapStrategySetup) {
  132. debug('LdapStrategy has not been set up');
  133. return res.json({
  134. status: 'warning',
  135. message: 'LdapStrategy has not been set up',
  136. });
  137. }
  138. const loginForm = req.body.loginForm;
  139. passport.authenticate('ldapauth', (err, user, info) => {
  140. if (res.headersSent) { // dirty hack -- 2017.09.25
  141. return; // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
  142. }
  143. if (err) { // DB Error
  144. console.log('LDAP Server Error: ', err);
  145. return res.json({
  146. status: 'warning',
  147. message: 'LDAP Server Error occured.',
  148. });
  149. }
  150. if (info && info.message) {
  151. return res.json({
  152. status: 'warning',
  153. message: info.message,
  154. });
  155. }
  156. if (user) {
  157. // check groups
  158. if (!isValidLdapUserByGroupFilter(user)) {
  159. return res.json({
  160. status: 'warning',
  161. message: 'The user is found, but that has no groups.',
  162. });
  163. }
  164. return res.json({
  165. status: 'success',
  166. message: 'Successfully authenticated.',
  167. });
  168. }
  169. })(req, res, () => {});
  170. }
  171. /**
  172. * middleware that login with LocalStrategy
  173. * @param {*} req
  174. * @param {*} res
  175. * @param {*} next
  176. */
  177. const loginWithLocal = (req, res, next) => {
  178. const loginForm = req.body.loginForm;
  179. if (!req.form.isValid) {
  180. return res.render('login', {
  181. });
  182. }
  183. passport.authenticate('local', (err, user, info) => {
  184. debug('--- authenticate with LocalStrategy ---');
  185. debug('user', user);
  186. debug('info', info);
  187. if (err) { // DB Error
  188. console.log('Database Server Error: ', err);
  189. req.flash('warningMessage', 'Database Server Error occured.');
  190. return next(); // pass and the flash message is displayed when all of authentications are failed.
  191. }
  192. if (!user) { return next(); }
  193. req.logIn(user, (err) => {
  194. if (err) { return next(); }
  195. else {
  196. return loginSuccess(req, res, user);
  197. }
  198. });
  199. })(req, res, next);
  200. }
  201. return {
  202. loginFailure,
  203. loginWithLdap,
  204. testLdapCredentials,
  205. loginWithLocal,
  206. };
  207. };