Skip to content

Commit

Permalink
feat: two-factor authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
gr2m committed Jan 17, 2019
1 parent 81df303 commit fb38885
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
3 changes: 3 additions & 0 deletions plugins/authentication/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ module.exports = authenticationPlugin

const authenticate = require('./authenticate')
const beforeRequest = require('./before-request')
const requestError = require('./request-error')

function authenticationPlugin (octokit) {
const state = {
octokit,
auth: false
}
octokit.authenticate = authenticate.bind(null, state)
octokit.hook.before('request', beforeRequest.bind(null, state))
octokit.hook.error('request', requestError.bind(null, state))
}
25 changes: 25 additions & 0 deletions plugins/authentication/request-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
module.exports = authenticationRequestError

const HttpError = require('@octokit/request/lib/http-error')

function authenticationRequestError (state, error, options) {
// handle "2FA required" error only
if (error.status !== 401 || !/required/.test(error.headers['x-github-otp'] || '')) {
throw error
}

if (typeof state.auth.on2fa !== 'function') {
throw new HttpError('2FA required, but options.on2fa is not a function. See https://github.com/octokit/rest.js#authentication', 401, error.headers, options)
}

return Promise.resolve()
.then(() => {
return state.auth.on2fa()
})
.then((oneTimePassword) => {
const newOptions = Object.assign(options, {
headers: Object.assign({ 'x-github-otp': oneTimePassword }, options.headers)
})
return state.octokit.request(newOptions)
})
}

0 comments on commit fb38885

Please sign in to comment.