2020-01-28 13:08:03 +08:00
module . exports = authenticationPlugin ;
2020-03-02 21:16:42 +08:00
const { createTokenAuth } = require ( "@octokit/auth-token" ) ;
const { Deprecation } = require ( "deprecation" ) ;
const once = require ( "once" ) ;
2020-01-28 13:08:03 +08:00
const beforeRequest = require ( "./before-request" ) ;
const requestError = require ( "./request-error" ) ;
const validate = require ( "./validate" ) ;
2020-03-02 21:16:42 +08:00
const withAuthorizationPrefix = require ( "./with-authorization-prefix" ) ;
const deprecateAuthBasic = once ( ( log , deprecation ) => log . warn ( deprecation ) ) ;
const deprecateAuthObject = once ( ( log , deprecation ) => log . warn ( deprecation ) ) ;
2020-01-28 13:08:03 +08:00
function authenticationPlugin ( octokit , options ) {
2020-03-02 21:16:42 +08:00
// If `options.authStrategy` is set then use it and pass in `options.auth`
if ( options . authStrategy ) {
const auth = options . authStrategy ( options . auth ) ;
octokit . hook . wrap ( "request" , auth . hook ) ;
octokit . auth = auth ;
return ;
}
// If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance
// is unauthenticated. The `octokit.auth()` method is a no-op and no request hook is registred.
2020-01-28 13:08:03 +08:00
if ( ! options . auth ) {
2020-03-02 21:16:42 +08:00
octokit . auth = ( ) =>
Promise . resolve ( {
type : "unauthenticated"
} ) ;
2020-01-28 13:08:03 +08:00
return ;
}
2020-03-02 21:16:42 +08:00
const isBasicAuthString =
typeof options . auth === "string" &&
/^basic/ . test ( withAuthorizationPrefix ( options . auth ) ) ;
// If only `options.auth` is set to a string, use the default token authentication strategy.
if ( typeof options . auth === "string" && ! isBasicAuthString ) {
const auth = createTokenAuth ( options . auth ) ;
octokit . hook . wrap ( "request" , auth . hook ) ;
octokit . auth = auth ;
return ;
}
// Otherwise log a deprecation message
const [ deprecationMethod , deprecationMessapge ] = isBasicAuthString
? [
deprecateAuthBasic ,
'Setting the "new Octokit({ auth })" option to a Basic Auth string is deprecated. Use https://github.com/octokit/auth-basic.js instead. See (https://octokit.github.io/rest.js/#authentication)'
]
: [
deprecateAuthObject ,
'Setting the "new Octokit({ auth })" option to an object without also setting the "authStrategy" option is deprecated and will be removed in v17. See (https://octokit.github.io/rest.js/#authentication)'
] ;
deprecationMethod (
octokit . log ,
new Deprecation ( "[@octokit/rest] " + deprecationMessapge )
) ;
octokit . auth = ( ) =>
Promise . resolve ( {
type : "deprecated" ,
message : deprecationMessapge
} ) ;
2020-01-28 13:08:03 +08:00
validate ( options . auth ) ;
const state = {
octokit ,
auth : options . auth
} ;
octokit . hook . before ( "request" , beforeRequest . bind ( null , state ) ) ;
octokit . hook . error ( "request" , requestError . bind ( null , state ) ) ;
}