# passport を用いたログイン

## loginRequired について

- loginRequiredStrictly との違いは...?
    - code を見てみよう

## req.user になぜユーザーデータが入っているのか

- passport を使っている
    - https://knimon-software.github.io/www.passportjs.org/
- 3つの項目の設定が必要
    - https://knimon-software.github.io/www.passportjs.org/guide/configure/
    - 認証用ストラテジーの選択
    - アプリケーションミドルウェア
    - セッション管理(省略可)


```js:passport.js

  /**
   * setup LocalStrategy
   *
   * @memberof PassportService
   */
  setupLocalStrategy() {

    this.resetLocalStrategy();

    const { configManager } = this.crowi;

    const isEnabled = configManager.getConfig('crowi', 'security:passport-local:isEnabled');

    // when disabled
    if (!isEnabled) {
      return;
    }

    logger.debug('LocalStrategy: setting up..');

    const User = this.crowi.model('User');

    passport.use(new LocalStrategy(
      {
        usernameField: PassportService.USERNAME_FIELD,
        passwordField: PassportService.PASSWORD_FIELD,
      },
      (username, password, done) => {
        // find user
        User.findUserByUsernameOrEmail(username, password, (err, user) => {
          if (err) { return done(err) }
          // check existence and password
          if (!user || !user.isPasswordValid(password)) {
            return done(null, false, { message: 'Incorrect credentials.' });
          }
          return done(null, user);
        });
      },
    ));

    this.isLocalStrategySetup = true;
    logger.debug('LocalStrategy: setup is done');
  }
  ```
  
## ログイン時

### route
`app.post('/login'                  , form.login                           , csrf, loginPassport.loginWithLocal, loginPassport.loginWithLdap, loginPassport.loginFailure);`

```js:login-passport.js
  const loginWithLocal = (req, res, next) => {
    if (!passportService.isLocalStrategySetup) {
      debug('LocalStrategy has not been set up');
      req.flash('warningMessage', req.t('message.strategy_has_not_been_set_up', { strategy: 'LocalStrategy' }));
      return next();
    }

    if (!req.form.isValid) {
      return res.render('login', {
      });
    }

    passport.authenticate('local', (err, user, info) => {
      debug('--- authenticate with LocalStrategy ---');
      debug('user', user);
      debug('info', info);

      if (err) { // DB Error
        logger.error('Database Server Error: ', err);
        req.flash('warningMessage', req.t('message.database_error'));
        return next(); // pass and the flash message is displayed when all of authentications are failed.
      }
      if (!user) { return next() }
      req.logIn(user, (err) => {
        if (err) { debug(err.message); return next() }

        return loginSuccessHandler(req, res, user);
      });
    })(req, res, next);
  };
```

```
    passport.deserializeUser(async(id, done) => {
      try {
        const user = await User.findById(id);
        console.log(user);
        if (user == null) {
          throw new Error('user not found');
        }
        if (user.imageUrlCached == null) {
          await user.updateImageUrlCached();
          await user.save();
        }
        done(null, user);
      }
      catch (err) {
        done(err);
      }
    });
```


---

## Page Navigation

- Canonical URL: https://dev.growi.org/GROWI勉強会/20200911/GROWIにおけるpassport
- Permalink: https://dev.growi.org/5f561afc3492a1004820cf65
- Parent: [20200911](/5f5619083492a1004820cf56.md)
- Children: 0 total
- Total descendants: 0
- Siblings: 1 total
  - [Slack button 新調 BS4 効かない問題](/5f9af4cebac0ae004887c652.md)
- Last updated: 2020-10-28T16:21:40.765Z by itizawa
- Full page listing (all children regardless of count): https://dev.growi.org/_api/v3/page-listing/children?id=5f561afc3492a1004820cf65
