본문 바로가기

개발자의 logs

Node.js Google passport Code(구글 패스포트) 본문

개발 공부지식/*개발 공부*

Node.js Google passport Code(구글 패스포트)

주인장v 2022. 6. 26. 18:16
// config/passport.js

const dotenv = require('dotenv'); // 설정파일
dotenv.config();

const GUser = require('../schemas/googleUser');

var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth2').Strategy;

passport.serializeUser(function (user, done) {
  done(null, user);
});
passport.deserializeUser(function (user, done) {
  done(null, user);
});

passport.use(
  new GoogleStrategy(
    {
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_SECRET,
      callbackURL: 'http://hayeon-sum.shop/auth/google/callback',
      passReqToCallback: true,
    },
    async (request, accessToken, refreshToken, profile, done) => {
      let user = profile;
      const userid = 'abc' + user.id.slice(0, 7);
      const username = user.given_name;
      const profileimage = user.picture;
      const iscompany = false;

      const exUser = await GUser.findOne({ userid });

      if (exUser) {
        done(null, exUser);
      } else {
        const user_save = new GUser({
          userid,
          username,
          profileimage,
          iscompany,
        });
        user_save.save();
      }
    }
  )
);

module.exports = passport;

 

 

//routes/google_auth.js

const express = require('express');

const router = express.Router();
const passport = require('../config/passport.js');

// 로그인 API

router.get('/login', (req, res) => {
  res.render('auth/login');
});

// 로그아웃 API
router.get('/logout', (req, res) => {
  req.logout();
  res.redirect('/');
});

// 구글로 로그인하기 Router
router.get('/google', passport.authenticate('google', { scope: ['profile'] }));

// 그리고 passport 로그인 전략에 의해 googleStrategy로 가서 구글계정 정보와 DB를 비교해서 회원가입시키거나 로그인 처리하게 한다.
router.get('/google/callback', passport.authenticate('google'), authSuccess);

function authSuccess(req, res) {
  res.redirect('/main');
}

module.exports = router;

 

 

 

// schemas/ user.js

const mongoose = require('mongoose');
const GuserSchema = new mongoose.Schema({
  username: {
    type: String,
  },

  userid: {
    type: String,
    unique: true,
  },

  profileimage: {
    type: String,
  },

  iscompany: {
    type: String,
  },
});

module.exports = mongoose.model('GUser', GuserSchema);
© 2022 GitHub, Inc.
Terms
Privacy
Security
Status
Comments