Skip to content

Commit

Permalink
Enable github two-factor authentication; fixes #5252
Browse files Browse the repository at this point in the history
  • Loading branch information
kmsquire committed Sep 3, 2014
1 parent d69c193 commit a5b1f30
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions base/pkg/github.jl
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,14 @@ function curl(url::String, opts::Cmd=``)
out, proc = open(`curl -i -s -S $opts $url`,"r")
head = readline(out)
status = int(split(head,r"\s+";limit=3)[2])
header = (String=>String)[]
for line in eachline(out)
ismatch(r"^\s*$",line) || continue
wait(proc); return status, readall(out)
if !ismatch(r"^\s*$",line)
(k,v) = split(line, r":\s*", 2)
header[k] = v
continue
end
wait(proc); return status, header, readall(out)
end
error("strangely formatted HTTP response")
end
Expand All @@ -55,20 +60,30 @@ end
function token(user::String=user())
tokfile = Dir.path(".github","token")
isfile(tokfile) && return strip(readchomp(tokfile))
status, content = curl("https://api.github.com/authorizations",AUTH_DATA,`-u $user`)
status, header, content = curl("https://api.github.com/authorizations",AUTH_DATA,`-u $user`)

# Check for two-factor authentication
if status == 401 && get(header, "X-GitHub-OTP", "") |> x->beginswith(x, "required") && isinteractive()
info("Two-factor authentication in use. Enter auth code. (You may have to re-enter your password.)")
print(STDERR, "Authentication code: ")
code = readline(STDIN) |> chomp
status, header, content = curl("https://api.github.com/authorizations",AUTH_DATA,`-H "X-GitHub-OTP: $code" -u $user`)
end

if status == 422
error_code = json().parse(content)["errors"][1]["code"]
if error_code == "already_exists"
info("Retrieving existing GitHub token (you may have to enter you password again)")
status,content = curl("https://api.github.com/authorizations",`-u $user`)
info("Retrieving existing GitHub token. (You may have to re-enter your password.)")
status, header, content = curl("https://api.github.com/authorizations",`-u $user`)
(status >= 400) && error("$status: $(json().parse(content)["message"])")
for entry in json().parse(content)
if entry["note"] == AUTH_NOTE
tok = entry["token"]
break
end
end
else
error("GitHub returned validation error (422): $error_code")
error("GitHub returned validation error (422): $error_code: $(json().parse(content)["message"])")
end
else
(status != 401 && status != 403) || error("$status: $(json().parse(content)["message"])")
Expand All @@ -81,7 +96,7 @@ end

function req(resource::String, data, opts::Cmd=``)
url = "https://api.github.com/$resource"
status, content = curl(url,data,`-u $(token()):x-oauth-basic $opts`)
status, header, content = curl(url,data,`-u $(token()):x-oauth-basic $opts`)
response = json().parse(content)
status, response
end
Expand Down

0 comments on commit a5b1f30

Please sign in to comment.