1
1
'use strict'
2
2
3
3
const Router = require ( 'express' ) . Router
4
+ const request = require ( 'request' )
4
5
const passport = require ( 'passport' )
5
6
const GithubStrategy = require ( 'passport-github' ) . Strategy
7
+ const { InternalOAuthError } = require ( 'passport-oauth2' )
6
8
const config = require ( '../../config' )
7
9
const response = require ( '../../response' )
8
10
const { setReturnToFromReferer, passportGeneralCallback } = require ( '../utils' )
9
11
const { URL } = require ( 'url' )
12
+ const { promisify } = require ( 'util' )
13
+
14
+ const rp = promisify ( request )
10
15
11
16
const githubAuth = module . exports = Router ( )
12
17
@@ -15,20 +20,48 @@ function githubUrl (path) {
15
20
}
16
21
17
22
passport . use ( new GithubStrategy ( {
23
+ scope : ( config . github . organizations ? config . github . scopes . concat ( [ 'read:org' ] ) : config . github . scope ) ,
18
24
clientID : config . github . clientID ,
19
25
clientSecret : config . github . clientSecret ,
20
26
callbackURL : config . serverURL + '/auth/github/callback' ,
21
27
authorizationURL : githubUrl ( 'login/oauth/authorize' ) ,
22
28
tokenURL : githubUrl ( 'login/oauth/access_token' ) ,
23
29
userProfileURL : githubUrl ( 'api/v3/user' )
24
- } , passportGeneralCallback ) )
30
+ } , async ( accessToken , refreshToken , profile , done ) => {
31
+ if ( ! config . github . organizations ) {
32
+ return passportGeneralCallback ( accessToken , refreshToken , profile , done )
33
+ }
34
+ const { statusCode, body : data } = await rp ( {
35
+ url : `https://api.github.com/user/orgs` ,
36
+ method : 'GET' ,
37
+ json : true ,
38
+ timeout : 2000 ,
39
+ headers : {
40
+ Authorization : `token ${ accessToken } ` ,
41
+ 'User-Agent' : 'nodejs-http'
42
+ }
43
+ } )
44
+ if ( statusCode !== 200 ) {
45
+ return done ( InternalOAuthError (
46
+ `Failed to query organizations for user: ${ profile . username } `
47
+ ) )
48
+ }
49
+ const orgs = data . map ( ( { login } ) => login )
50
+ for ( const org of orgs ) {
51
+ if ( config . github . organizations . includes ( org ) ) {
52
+ return passportGeneralCallback ( accessToken , refreshToken , profile , done )
53
+ }
54
+ }
55
+ return done ( InternalOAuthError (
56
+ `User orgs not whitelisted: ${ profile . username } (${ orgs . join ( ',' ) } )`
57
+ ) )
58
+ } ) )
25
59
26
60
githubAuth . get ( '/auth/github' , function ( req , res , next ) {
27
61
setReturnToFromReferer ( req )
28
62
passport . authenticate ( 'github' ) ( req , res , next )
29
63
} )
30
64
31
- // github auth callback
32
65
githubAuth . get ( '/auth/github/callback' ,
33
66
passport . authenticate ( 'github' , {
34
67
successReturnToOrRedirect : config . serverURL + '/' ,
0 commit comments