2
0

passport.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. const debug = require('debug')('growi:service:PassportService');
  2. const passport = require('passport');
  3. const LocalStrategy = require('passport-local').Strategy;
  4. const LdapStrategy = require('passport-ldapauth');
  5. const GoogleStrategy = require('passport-google-auth').Strategy;
  6. const GitHubStrategy = require('passport-github').Strategy;
  7. /**
  8. * the service class of Passport
  9. */
  10. class PassportService {
  11. // see '/lib/form/login.js'
  12. static get USERNAME_FIELD() { return 'loginForm[username]' }
  13. static get PASSWORD_FIELD() { return 'loginForm[password]' }
  14. constructor(crowi) {
  15. this.crowi = crowi;
  16. /**
  17. * the flag whether LocalStrategy is set up successfully
  18. */
  19. this.isLocalStrategySetup = false;
  20. /**
  21. * the flag whether LdapStrategy is set up successfully
  22. */
  23. this.isLdapStrategySetup = false;
  24. /**
  25. * the flag whether LdapStrategy is set up successfully
  26. */
  27. this.isGoogleStrategySetup = false;
  28. /**
  29. * the flag whether serializer/deserializer are set up successfully
  30. */
  31. this.isSerializerSetup = false;
  32. }
  33. /**
  34. * reset LocalStrategy
  35. *
  36. * @memberof PassportService
  37. */
  38. resetLocalStrategy() {
  39. debug('LocalStrategy: reset');
  40. passport.unuse('local');
  41. this.isLocalStrategySetup = false;
  42. }
  43. /**
  44. * setup LocalStrategy
  45. *
  46. * @memberof PassportService
  47. */
  48. setupLocalStrategy() {
  49. // check whether the strategy has already been set up
  50. if (this.isLocalStrategySetup) {
  51. throw new Error('LocalStrategy has already been set up');
  52. }
  53. debug('LocalStrategy: setting up..');
  54. const User = this.crowi.model('User');
  55. passport.use(new LocalStrategy(
  56. {
  57. usernameField: PassportService.USERNAME_FIELD,
  58. passwordField: PassportService.PASSWORD_FIELD,
  59. },
  60. (username, password, done) => {
  61. // find user
  62. User.findUserByUsernameOrEmail(username, password, (err, user) => {
  63. if (err) { return done(err) }
  64. // check existence and password
  65. if (!user || !user.isPasswordValid(password)) {
  66. return done(null, false, { message: 'Incorrect credentials.' });
  67. }
  68. return done(null, user);
  69. });
  70. }
  71. ));
  72. this.isLocalStrategySetup = true;
  73. debug('LocalStrategy: setup is done');
  74. }
  75. /**
  76. * reset LdapStrategy
  77. *
  78. * @memberof PassportService
  79. */
  80. resetLdapStrategy() {
  81. debug('LdapStrategy: reset');
  82. passport.unuse('ldapauth');
  83. this.isLdapStrategySetup = false;
  84. }
  85. /**
  86. * Asynchronous configuration retrieval
  87. *
  88. * @memberof PassportService
  89. */
  90. setupLdapStrategy() {
  91. // check whether the strategy has already been set up
  92. if (this.isLdapStrategySetup) {
  93. throw new Error('LdapStrategy has already been set up');
  94. }
  95. const config = this.crowi.config;
  96. const Config = this.crowi.model('Config');
  97. const isLdapEnabled = Config.isEnabledPassportLdap(config);
  98. // when disabled
  99. if (!isLdapEnabled) {
  100. return;
  101. }
  102. debug('LdapStrategy: setting up..');
  103. passport.use(new LdapStrategy(this.getLdapConfigurationFunc(config, {passReqToCallback: true}),
  104. (req, ldapAccountInfo, done) => {
  105. debug('LDAP authentication has succeeded', ldapAccountInfo);
  106. // store ldapAccountInfo to req
  107. req.ldapAccountInfo = ldapAccountInfo;
  108. done(null, ldapAccountInfo);
  109. }
  110. ));
  111. this.isLdapStrategySetup = true;
  112. debug('LdapStrategy: setup is done');
  113. }
  114. /**
  115. * return attribute name for mapping to username of Crowi DB
  116. *
  117. * @returns
  118. * @memberof PassportService
  119. */
  120. getLdapAttrNameMappedToUsername() {
  121. const config = this.crowi.config;
  122. return config.crowi['security:passport-ldap:attrMapUsername'] || 'uid';
  123. }
  124. /**
  125. * return attribute name for mapping to name of Crowi DB
  126. *
  127. * @returns
  128. * @memberof PassportService
  129. */
  130. getLdapAttrNameMappedToName() {
  131. const config = this.crowi.config;
  132. return config.crowi['security:passport-ldap:attrMapName'] || '';
  133. }
  134. /**
  135. * CAUTION: this method is capable to use only when `req.body.loginForm` is not null
  136. *
  137. * @param {any} req
  138. * @returns
  139. * @memberof PassportService
  140. */
  141. getLdapAccountIdFromReq(req) {
  142. return req.body.loginForm.username;
  143. }
  144. /**
  145. * Asynchronous configuration retrieval
  146. * @see https://github.com/vesse/passport-ldapauth#asynchronous-configuration-retrieval
  147. *
  148. * @param {object} config
  149. * @param {object} opts
  150. * @returns
  151. * @memberof PassportService
  152. */
  153. getLdapConfigurationFunc(config, opts) {
  154. // get configurations
  155. const isUserBind = config.crowi['security:passport-ldap:isUserBind'];
  156. const serverUrl = config.crowi['security:passport-ldap:serverUrl'];
  157. const bindDN = config.crowi['security:passport-ldap:bindDN'];
  158. const bindCredentials = config.crowi['security:passport-ldap:bindDNPassword'];
  159. const searchFilter = config.crowi['security:passport-ldap:searchFilter'] || '(uid={{username}})';
  160. const groupSearchBase = config.crowi['security:passport-ldap:groupSearchBase'];
  161. const groupSearchFilter = config.crowi['security:passport-ldap:groupSearchFilter'];
  162. const groupDnProperty = config.crowi['security:passport-ldap:groupDnProperty'] || 'uid';
  163. // parse serverUrl
  164. // see: https://regex101.com/r/0tuYBB/1
  165. const match = serverUrl.match(/(ldaps?:\/\/[^/]+)\/(.*)?/);
  166. if (match == null || match.length < 1) {
  167. debug('LdapStrategy: serverUrl is invalid');
  168. return (req, callback) => { callback({ message: 'serverUrl is invalid'}) };
  169. }
  170. const url = match[1];
  171. const searchBase = match[2] || '';
  172. debug(`LdapStrategy: url=${url}`);
  173. debug(`LdapStrategy: searchBase=${searchBase}`);
  174. debug(`LdapStrategy: isUserBind=${isUserBind}`);
  175. if (!isUserBind) {
  176. debug(`LdapStrategy: bindDN=${bindDN}`);
  177. debug(`LdapStrategy: bindCredentials=${bindCredentials}`);
  178. }
  179. debug(`LdapStrategy: searchFilter=${searchFilter}`);
  180. debug(`LdapStrategy: groupSearchBase=${groupSearchBase}`);
  181. debug(`LdapStrategy: groupSearchFilter=${groupSearchFilter}`);
  182. debug(`LdapStrategy: groupDnProperty=${groupDnProperty}`);
  183. return (req, callback) => {
  184. // get credentials from form data
  185. const loginForm = req.body.loginForm;
  186. if (!req.form.isValid) {
  187. return callback({ message: 'Incorrect credentials.' });
  188. }
  189. // user bind
  190. const fixedBindDN = (isUserBind) ?
  191. bindDN.replace(/{{username}}/, loginForm.username):
  192. bindDN;
  193. const fixedBindCredentials = (isUserBind) ? loginForm.password : bindCredentials;
  194. let serverOpt = { url, bindDN: fixedBindDN, bindCredentials: fixedBindCredentials, searchBase, searchFilter };
  195. if (groupSearchBase && groupSearchFilter) {
  196. serverOpt = Object.assign(serverOpt, { groupSearchBase, groupSearchFilter, groupDnProperty });
  197. }
  198. process.nextTick(() => {
  199. const mergedOpts = Object.assign({
  200. usernameField: PassportService.USERNAME_FIELD,
  201. passwordField: PassportService.PASSWORD_FIELD,
  202. server: serverOpt,
  203. }, opts);
  204. debug('ldap configuration: ', mergedOpts);
  205. // store configuration to req
  206. req.ldapConfiguration = mergedOpts;
  207. callback(null, mergedOpts);
  208. });
  209. };
  210. }
  211. /**
  212. * Asynchronous configuration retrieval
  213. *
  214. * @memberof PassportService
  215. */
  216. setupGoogleStrategy() {
  217. // check whether the strategy has already been set up
  218. if (this.isGoogleStrategySetup) {
  219. throw new Error('GoogleStrategy has already been set up');
  220. }
  221. const config = this.crowi.config;
  222. const Config = this.crowi.model('Config');
  223. //this
  224. const isGoogleEnabled = Config.isEnabledPassportGoogle(config);
  225. // when disabled
  226. if (!isGoogleEnabled) {
  227. return;
  228. }
  229. debug('GoogleStrategy: setting up..');
  230. passport.use(new GoogleStrategy({
  231. clientId: config.crowi['security:passport-google:clientId'] || process.env.OAUTH_GOOGLE_CLIENT_SECRET,
  232. clientSecret: config.crowi['security:passport-google:clientSecret'] || process.env.OAUTH_GOOGLE_CLIENT_SECRET,
  233. callbackURL: 'http://localhost:3000/passport/google/callback', //change this
  234. skipUserProfile: false,
  235. }, function(accessToken, refreshToken, profile, done) {
  236. if (profile) {
  237. return done(null, profile);
  238. }
  239. else {
  240. return done(null, false);
  241. }
  242. }));
  243. this.isGoogleStrategySetup = true;
  244. debug('GoogleStrategy: setup is done');
  245. }
  246. /**
  247. * reset GoogleStrategy
  248. *
  249. * @memberof PassportService
  250. */
  251. resetGoogleStrategy() {
  252. debug('GoogleStrategy: reset');
  253. passport.unuse('google');
  254. this.isGoogleStrategySetup = false;
  255. }
  256. setupGitHubStrategy() {
  257. // check whether the strategy has already been set up
  258. if (this.isGitHubStrategySetup) {
  259. throw new Error('GitHubStrategy has already been set up');
  260. }
  261. const config = this.crowi.config;
  262. const Config = this.crowi.model('Config');
  263. //this
  264. const isGitHubEnabled = Config.isEnabledPassportGitHub(config);
  265. // when disabled
  266. if (!isGitHubEnabled) {
  267. return;
  268. }
  269. debug('GitHubStrategy: setting up..');
  270. passport.use(new GitHubStrategy({
  271. clientID: config.crowi['security:passport-github:clientId'] || process.env.OAUTH_GITHUB_CLIENT_ID,
  272. clientSecret: config.crowi['security:passport-github:clientSecret'] || process.env.OAUTH_GITHUB_CLIENT_SECRET,
  273. callbackURL: 'http://localhost:3000/passport/github/callback', //change this
  274. skipUserProfile: false,
  275. }, function(accessToken, refreshToken, profile, done) {
  276. if (profile) {
  277. return done(null, profile);
  278. }
  279. else {
  280. return done(null, false);
  281. }
  282. }));
  283. this.isGitHubStrategySetup = true;
  284. debug('GitHubStrategy: setup is done');
  285. }
  286. /**
  287. * reset GoogleStrategy
  288. *
  289. * @memberof PassportService
  290. */
  291. resetGitHubStrategy() {
  292. debug('GitHubStrategy: reset');
  293. passport.unuse('github');
  294. this.isGitHubStrategySetup = false;
  295. }
  296. /**
  297. * setup serializer and deserializer
  298. *
  299. * @memberof PassportService
  300. */
  301. setupSerializer() {
  302. // check whether the serializer/deserializer have already been set up
  303. if (this.isSerializerSetup) {
  304. throw new Error('serializer/deserializer have already been set up');
  305. }
  306. debug('setting up serializer and deserializer');
  307. const User = this.crowi.model('User');
  308. passport.serializeUser(function(user, done) {
  309. done(null, user.id);
  310. });
  311. passport.deserializeUser(function(id, done) {
  312. User.findById(id, function(err, user) {
  313. done(err, user);
  314. });
  315. });
  316. this.isSerializerSetup = true;
  317. }
  318. }
  319. module.exports = PassportService;