2017-11-12 1 views
2

나는 passport-github 전략을 사용하고 있습니다. API를 통해 요령을 게시하는 방법 (익명으로 아님)

passport.use(new Strategy({ 
    clientID: "...", 
    clientSecret: "...", 
    callbackURL: 'http://localhost:3000/login/github/return', 
    scope: 'gist' 
    }, 
    function(accessToken, refreshToken, profile, cb) { 
    return cb(null, profile); 
    })); 

는 다음 나는 POST 요청

app.get('/profile/post', 
    require('connect-ensure-login').ensureLoggedIn(), 
    function(req, res){ 
var url = 'https://api.github.com/gists'; 

axios.post(url, { 
    method: "POST", 
    "description": "POSTING FROM EXPRESS", 
    "public": true, 
    "files": { 
    "file1.txt": { 
     "content": "EXPRESS " 
    } 

} 
}) 
    .then(function (response) {...}) 
    .catch(function (error) { ... }); 
요지가 생성됩니다

그러나 익명을합니다.

요청 인수의 일부로 "owner""user"을 전달했지만 사용하지 못했습니다. 나는 또한 사용자 이름을 URL에 전달하려고 시도했다.

까지 나는 the docs에 대해 아무 말도하지 않는다.

답변

1

여권 인증 콜백에서 가져온 액세스 토큰을 저장해야합니다. 그런 다음

passport.use(new GitHubStrategy({ 
     clientID: "...", 
     clientSecret: "...", 
     callbackURL: 'http://localhost:3000/login/github/return' 
    }, 
    function(accessToken, refreshToken, profile, done) { 

     process.nextTick(function() { 

      User.findOne({ id: profile.id }, function(err, res) { 
       if (err) 
        return done(err); 
       if (res) { 
        console.log("user exists"); 
        return done(null, res); 
       } else { 
        console.log("insert user"); 
        var user = new User({ 
         id: profile.id, 
         access_token: accessToken, 
         refresh_token: refreshToken 
        }); 
        user.save(function(err) { 
         if (err) 
          return done(err); 
         return done(null, user); 
        }); 
       } 
      }) 
     }); 
    } 
)); 

당신이 사용자를 역 직렬화 할 때, 당신은 다시 액세스 토큰을 사용자에게 얻을 : 예를 들어, 몽구스와 몽고를 사용하는 사용자를 저장하기 위해 엔드 포인트에서 지금

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

passport.deserializeUser(function(id, done) { 
    User.findOne({ "id": id }, function(err, user) { 
     done(err, user); 
    }); 
}); 

하고, 넣어 GitHub의 API를 요청 Authorization 헤더 req.user.access_token :

app.get('/profile/post', 
    require('connect-ensure-login').ensureLoggedIn(), 
    function(req, res) { 

    axios.post('https://api.github.com/gists', { 
     "method": "POST", 
     "description": "POSTING FROM EXPRESS", 
     "headers": { 
     "Authorization" : "token " + req.user.access_token 
     }, 
     "public": true, 
     "files": { 
     "file1.txt": { 
      "content": "EXPRESS " 
     } 
     } 
    }) 
    .then(function (response) {...}) 
    .catch(function (error) { ... }); 
    } 
); 

하지만 그 대신 수동으로 요청을 구축, 당신은 octonode 라이브러리 그쪽을 사용할 수 있습니다 너를 위해서해라. octonode와 mongodb가있는 여권 github의 전체 예제 here을 찾을 수 있습니다

관련 문제