Node.js 模块之【passport】第三方【Github】鉴权(二)

1. 安装模块

npm i connect-mongo --save-dev
npm i passport --save-dev
npm i passport-github --save

2. 引入模块及其他依赖模块

var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var passport = require('passport');
var GithubStrategy = require('passport-github').Strategy;

3. 添加序列化与反序列化回调


passport.serializeUser(function(user, done) {
     
    done(null, user.id);
});
passport.deserializeUser(function(id, done) {
     
    UserModel.findById(id, function(err, user) {
     
        done(err, user);
    })
});

4. 添加Github鉴权策略

passport.use(new GithubStrategy({
  clientID:'【Your ClientID】',
  clientSecret:'【Your Secret】',
  callbackURL:'【Your CallBack】'
},function(accessToken,refreshToken,profile,done) {
     
  UserModel.findOne({
      githubId: profile.id
  }, function(err, user) {
     
      if (err) {
          return done(err);
      } else {
          if (!user) {
              user = new UserModel({
                githubId:profile.id,
                username:profile.username
              });
              user.save();
              return done(null, user);
          }else{
              return done(null, user);
          }
      }
  });
}));

5. 使用connect-mongo保存

app.use(session({
    resave: false,
    saveUninitialized: true,
    cookie: {
        maxAge: 36000000 /*单位:毫秒*/
    },
    secret: "robin shop",
    store: new MongoStore({
        url:'mongodb://localhost/【Your MongoDB】'
    })
}));

6. 封装权限检查中间件

var isAuthenticated = function(req, res, next) {
     
        if (req.isAuthenticated() || (req.user && req.user.provider)) {
            return next();
        }
        res.redirect('/login');
    }

7. 设置Github登陆路由及其回调

    app.get('/auth/github', passport.authenticate('github'));

    app.get('/auth/github/callback', passport.authenticate('github', {
        failureRedirect: '/login'
    }), function(req, res) {
     
        res.redirect('/users');
    });

8. 登出销毁session

    app.get('/logout', function(req, res) {
     
        req.logout();
        res.redirect('/login');
    });

9. 权限限定

    app.use('/users', isAuthenticated, users);
    app.use('/products', isAuthenticated, products);
    app.use('/upload', isAuthenticated, upload);

你可能感兴趣的:(nodejs,node.js,session,github,鉴权)