login-passport.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. module.exports = function(crowi, app) {
  2. 'use strict';
  3. const 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. const 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 = async(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. const providerId = 'ldap';
  75. const strategyName = 'ldapauth';
  76. const ldapAccountInfo = await promisifiedPassportAuthentication(req, res, next, strategyName);
  77. // check groups for LDAP
  78. if (!isValidLdapUserByGroupFilter(ldapAccountInfo)) {
  79. return loginFailure(req, res, next);
  80. }
  81. /*
  82. * authentication success
  83. */
  84. // it is guaranteed that username that is input from form can be acquired
  85. // because this processes after authentication
  86. const ldapAccountId = passportService.getLdapAccountIdFromReq(req);
  87. const attrMapUsername = passportService.getLdapAttrNameMappedToUsername();
  88. const attrMapName = passportService.getLdapAttrNameMappedToName();
  89. const usernameToBeRegistered = ldapAccountInfo[attrMapUsername];
  90. const nameToBeRegistered = ldapAccountInfo[attrMapName];
  91. const userInfo = {
  92. 'id': ldapAccountId,
  93. 'username': usernameToBeRegistered,
  94. 'name': nameToBeRegistered
  95. };
  96. const externalAccount = await getOrCreateUser(req, res, next, userInfo, providerId);
  97. if (!externalAccount) {
  98. return loginFailure(req, res, next);
  99. }
  100. const user = await externalAccount.getPopulatedUser();
  101. // login
  102. await req.logIn(user, err => {
  103. if (err) { return next(err) }
  104. return loginSuccess(req, res, user);
  105. });
  106. };
  107. /**
  108. * middleware that test credentials with LdapStrategy
  109. *
  110. * @param {*} req
  111. * @param {*} res
  112. */
  113. const testLdapCredentials = (req, res) => {
  114. if (!passportService.isLdapStrategySetup) {
  115. debug('LdapStrategy has not been set up');
  116. return res.json({
  117. status: 'warning',
  118. message: 'LdapStrategy has not been set up',
  119. });
  120. }
  121. passport.authenticate('ldapauth', (err, user, info) => {
  122. if (res.headersSent) { // dirty hack -- 2017.09.25
  123. return; // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
  124. }
  125. if (err) { // DB Error
  126. logger.error('LDAP Server Error: ', err);
  127. return res.json({
  128. status: 'warning',
  129. message: 'LDAP Server Error occured.',
  130. err
  131. });
  132. }
  133. if (info && info.message) {
  134. return res.json({
  135. status: 'warning',
  136. message: info.message,
  137. ldapConfiguration: req.ldapConfiguration,
  138. ldapAccountInfo: req.ldapAccountInfo,
  139. });
  140. }
  141. if (user) {
  142. // check groups
  143. if (!isValidLdapUserByGroupFilter(user)) {
  144. return res.json({
  145. status: 'warning',
  146. message: 'The user is found, but that has no groups.',
  147. ldapConfiguration: req.ldapConfiguration,
  148. ldapAccountInfo: req.ldapAccountInfo,
  149. });
  150. }
  151. return res.json({
  152. status: 'success',
  153. message: 'Successfully authenticated.',
  154. ldapConfiguration: req.ldapConfiguration,
  155. ldapAccountInfo: req.ldapAccountInfo,
  156. });
  157. }
  158. })(req, res, () => {});
  159. };
  160. /**
  161. * middleware that login with LocalStrategy
  162. * @param {*} req
  163. * @param {*} res
  164. * @param {*} next
  165. */
  166. const loginWithLocal = (req, res, next) => {
  167. if (!req.form.isValid) {
  168. return res.render('login', {
  169. });
  170. }
  171. passport.authenticate('local', (err, user, info) => {
  172. debug('--- authenticate with LocalStrategy ---');
  173. debug('user', user);
  174. debug('info', info);
  175. if (err) { // DB Error
  176. logger.error('Database Server Error: ', err);
  177. req.flash('warningMessage', 'Database Server Error occured.');
  178. return next(); // pass and the flash message is displayed when all of authentications are failed.
  179. }
  180. if (!user) { return next() }
  181. req.logIn(user, (err) => {
  182. if (err) { return next() }
  183. else {
  184. return loginSuccess(req, res, user);
  185. }
  186. });
  187. })(req, res, next);
  188. };
  189. const loginWithGoogle = function(req, res, next) {
  190. if (!passportService.isGoogleStrategySetup) {
  191. debug('GoogleStrategy has not been set up');
  192. req.flash('warningMessage', 'GoogleStrategy has not been set up');
  193. return next();
  194. }
  195. passport.authenticate('google', {
  196. scope: ['profile', 'email'],
  197. })(req, res);
  198. };
  199. const loginPassportGoogleCallback = async(req, res, next) => {
  200. const providerId = 'google';
  201. const strategyName = 'google';
  202. const response = await promisifiedPassportAuthentication(req, res, next, strategyName);
  203. const userInfo = {
  204. 'id': response.id,
  205. 'username': response.displayName,
  206. 'name': `${response.name.givenName} ${response.name.familyName}`
  207. };
  208. const externalAccount = await getOrCreateUser(req, res, next, userInfo, providerId);
  209. if (!externalAccount) {
  210. return loginFailure(req, res, next);
  211. }
  212. const user = await externalAccount.getPopulatedUser();
  213. // login
  214. req.logIn(user, err => {
  215. if (err) { return next(err) }
  216. return loginSuccess(req, res, user);
  217. });
  218. };
  219. const loginWithGitHub = function(req, res, next) {
  220. if (!passportService.isGitHubStrategySetup) {
  221. debug('GitHubStrategy has not been set up');
  222. req.flash('warningMessage', 'GitHubStrategy has not been set up');
  223. return next();
  224. }
  225. passport.authenticate('github')(req, res);
  226. };
  227. const loginPassportGitHubCallback = async(req, res, next) => {
  228. const providerId = 'github';
  229. const strategyName = 'github';
  230. const response = await promisifiedPassportAuthentication(req, res, next, strategyName);
  231. const userInfo = {
  232. 'id': response.id,
  233. 'username': response.username,
  234. 'name': response.displayName
  235. };
  236. const externalAccount = await getOrCreateUser(req, res, next, userInfo, providerId);
  237. if (!externalAccount) {
  238. return loginFailure(req, res, next);
  239. }
  240. const user = await externalAccount.getPopulatedUser();
  241. // login
  242. req.logIn(user, err => {
  243. if (err) { return next(err) }
  244. return loginSuccess(req, res, user);
  245. });
  246. };
  247. const promisifiedPassportAuthentication = (req, res, next, strategyName) => {
  248. return new Promise((resolve, reject) => {
  249. passport.authenticate(strategyName, (err, response, info) => {
  250. if (res.headersSent) { // dirty hack -- 2017.09.25
  251. return; // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
  252. }
  253. if (err) {
  254. logger.error(`'${strategyName}' passport authentication error: `, err);
  255. req.flash('warningMessage', `Error occured in '${strategyName}' passport authentication`);
  256. return next(); // pass and the flash message is displayed when all of authentications are failed.
  257. }
  258. // authentication failure
  259. if (!response) {
  260. return next();
  261. }
  262. resolve(response);
  263. })(req, res, next);
  264. });
  265. };
  266. const getOrCreateUser = async(req, res, next, userInfo, providerId) => {
  267. try {
  268. // find or register(create) user
  269. const externalAccount = await ExternalAccount.findOrRegister(
  270. providerId,
  271. userInfo.id,
  272. userInfo.username,
  273. userInfo.name
  274. );
  275. return externalAccount;
  276. }
  277. catch (err) {
  278. if (err.name === 'DuplicatedUsernameException') {
  279. // get option
  280. const isSameUsernameTreatedAsIdenticalUser = Config.isSameUsernameTreatedAsIdenticalUser(config, providerId);
  281. if (isSameUsernameTreatedAsIdenticalUser) {
  282. // associate to existing user
  283. debug(`ExternalAccount '${userInfo.username}' will be created and bound to the exisiting User account`);
  284. return ExternalAccount.associate(providerId, userInfo.id, err.user);
  285. }
  286. else {
  287. req.flash('provider-DuplicatedUsernameException', providerId);
  288. return;
  289. }
  290. }
  291. }
  292. };
  293. return {
  294. loginFailure,
  295. loginWithLdap,
  296. testLdapCredentials,
  297. loginWithLocal,
  298. loginWithGoogle,
  299. loginWithGitHub,
  300. loginPassportGoogleCallback,
  301. loginPassportGitHubCallback,
  302. };
  303. };