본문으로 바로가기
 

passport-github

GitHub authentication strategy for Passport.

www.passportjs.org

해당 문서를 읽어보면 사용 방법이 나와있다.

 

kakao social login과 크게 다르지 않다.

 

1. github 로그인 버튼을 누르면 /auth/github로 이동하여 로그인 요청

2. github 로그인 (콜백 함수 실행 안 됨)

3. 지정한 콜백 경로로 프로필 반환 (/auth/github/callback으로 지정해놓았습니다)

4. 콜백 함수 실행 됨

 


 

설치

 

npm i passport-github

 

등록

 

kakao에서 그랬듯, github developers에서 어플리케이션 등록 과정을 거친 후에 사용할 수 있습니다.

위 passport.js 문서에 나와있는 링크를 통해 등록하도록 합시다.

(https://github.com/settings/applications/new)

 

 

🔑 사용

 

그냥 공식 문서를 보고 따라하는 게 훨씬 빠르다. 문서를 긁어왔다. 순서만 잘 이해하면 하나도 어렵지 않다. 

 

1. github 로그인 버튼을 누르면 /auth/github로 이동하여 로그인 요청 (GET)

2. 카카오 로그인 (콜백 함수 실행 안 됨)

3. 지정한 콜백 경로로 프로필 반환 (GET /auth/github/callback)

4. 콜백 함수 실행 됨

 

./passport.js

import { Strategy as GitHubStrategy } from "passport-github";

2. 깃허브 로그인 (콜백 함수 실행 안 됨)
4. 콜백 함수 실행 됨
passport.use(
  new GitHubStrategy(
    {
      clientID: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
      callbackURL: "http://localhost:4000/auth/github/callback",
    },
    
    
    // 이하 함수는 콜백 함수입니다.
    async (accessToken, refreshToken, profile, cb) => {
      // profile에서 정보를 가져옵니다.
      const {
        _json: { id, avatar_url, name, email },
      } = profile;
      
      // 이미 존재하는 id라면 cb에 기존 유저 정보를 넣어서 return합니다.
      try {
        const user = await User.findOne({ email });
        if (user) {
          user.githubId = id;
          user.save();
          return cb(null, user);
        }
        
        // 없는 id라면 생성한 후 return합니다.
        const newUser = await User.create({
          email,
          name,
          githubId: id,
          avatarURL: avatar_url,
        });
        return cb(null, newUser);
        
      } catch (error) {
      
        // 에러면 error로 cb return
        return cb(error);
      }
    }
  )
);
1. github 로그인 버튼을 누르면 /auth/github로 이동하여 로그인 요청함
passport.authenticate는 자동으로 지정한 전략을 수행하려고 함(2로 이동)

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



3. github 측에서 지정한 콜백 경로로 프로필 반환함. (/auth/github/callback으로 지정해놓음)
app.get('/auth/github/callback', 
  passport.authenticate('github', { failureRedirect: '/login' }),
  (req, res) => res.redirect('/');
  });

 

 

주의할 점이 있다.

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

이 부분에서 아래와 같이 함수로 작성하면 안된다. (아 내 2시간 ㅜㅜ)

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

 

인증을 성공하고 실행하는 콜백함수는 accessToken, refreshToken, profile, cb를 인자로 받습니다.

profile에 우리가 사용하고자 하는 유저의 정보가 들었으므로 살펴봅시다.

 

 

🔑 github profile 객체

 

kakao에서도 뜯어 봤는데 github도 뜯어보기로 했다.  kakao에서 반환한 profile과 딱히 다르지 않다.

{
  id: '아이디(숫자)',
  displayName: null,
  username: 'MartinGwon',
  profileUrl: 'https://github.com/MartinGwon',
  photos: [
    { value: 'https://avatars0.githubusercontent.com/u/54386980?v=4' }
  ],
  provider: 'github',
  _raw: '{"login":"MartinGwon","id":아이디(숫자),"node_id":"난수화된 문자열",
  "avatar_url":"https://avatars0.githubusercontent.com/u/54386980?v=4",
  "gravatar_id":"","url":"https://api.github.com/users/MartinGwon",
  "html_url":"https://github.com/MartinGwon",
  "followers_url":"주소",
  "following_url":"주소",
  "gists_url":"주소",
  "starred_url":"주소",
  "subscriptions_url":"주소",
  "organizations_url":"주소",
  "repos_url":"주소",
  "events_url":"주소",
  "received_events_url":"주소",
  "type":"User","site_admin":false,"name":null,"company":"(주) 에듀팝콘",
  "blog":"https://darrengwon.tistory.com/",
  "location":"Seoul","email":null,"hireable":null,"bio":null,
  "public_repos": 공개 repos 숫자,"public_gists":공개 gists 숫자,
  "followers":팔로워 숫자,"following":팔로잉 숫자,"
  created_at":"2019-08-22T03:37:54Z","updated_at":"2020-04-04T12:58:48Z"}',
  _json: {
    login: 'MartinGwon',
    id: 아이디(숫자),
    node_id: '난수화된 문자열',
    avatar_url: 'https://avatars0.githubusercontent.com/u/54386980?v=4',
    gravatar_id: '',
    url: '해당 유저의 api url',
    html_url: 'https://github.com/MartinGwon',
    followers_url: '해당 유저를 팔로워하는 사람들을 볼 수 있는 주소',
    following_url: '해당 유저가 팔로잉하는 사람들을 볼 수 있는 주소',
    gists_url: '주소',
    starred_url: '주소',
    subscriptions_url: '주소',
    organizations_url: '주소',
    repos_url: '주소',
    events_url: '주소',
    received_events_url: '주소',
    type: 'User',
    site_admin: false,
    name: null,
    company: '개인 프로필에 등록한 회사',
    blog: 'https://darrengwon.tistory.com/',
    location: 'Seoul',
    email: null,
    hireable: null,
    bio: null,
    public_repos: 공개 repos 숫자,
    public_gists: 공개 gists 숫자,
    followers: 팔로워 숫자,
    following: 팔로잉 숫자,
    created_at: '2019-08-22T03:37:54Z',
    updated_at: '2020-04-04T12:58:48Z'
  }
}​

 


darren, dev blog
블로그 이미지 DarrenKwonDev 님의 블로그
VISITOR 오늘 / 전체