login-passport.js 7.1 KB

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