提交 6ff2b3b7 编写于 作者: J Jingwen Owen Ou

Implement two factor authentication

上级 ebc91a30
...@@ -9,6 +9,7 @@ import ( ...@@ -9,6 +9,7 @@ import (
"github.com/jingweno/gh/utils" "github.com/jingweno/gh/utils"
"os" "os"
"path/filepath" "path/filepath"
"regexp"
) )
type Config struct { type Config struct {
...@@ -40,6 +41,14 @@ func (c *Config) FetchPassword() string { ...@@ -40,6 +41,14 @@ func (c *Config) FetchPassword() string {
return string(pass) return string(pass)
} }
func (c *Config) FetchTwoFactorCode() string {
var code string
fmt.Print("two-factor authentication code: ")
fmt.Scanln(&code)
return code
}
func (c *Config) FetchCredentials() { func (c *Config) FetchCredentials() {
var changed bool var changed bool
if c.User == "" { if c.User == "" {
...@@ -49,7 +58,16 @@ func (c *Config) FetchCredentials() { ...@@ -49,7 +58,16 @@ func (c *Config) FetchCredentials() {
if c.Token == "" { if c.Token == "" {
password := c.FetchPassword() password := c.FetchPassword()
token, err := findOrCreateToken(c.User, password) token, err := findOrCreateToken(c.User, password, "")
// TODO: return an two factor auth failure error
if err != nil {
re := regexp.MustCompile("two-factor authentication OTP code")
if re.MatchString(fmt.Sprintf("%s", err)) {
code := c.FetchTwoFactorCode()
token, err = findOrCreateToken(c.User, password, code)
}
}
utils.Check(err) utils.Check(err)
c.Token = token c.Token = token
......
...@@ -127,9 +127,15 @@ func (gh *GitHub) repo() octokat.Repo { ...@@ -127,9 +127,15 @@ func (gh *GitHub) repo() octokat.Repo {
return octokat.Repo{Name: project.Name, UserName: project.Owner} return octokat.Repo{Name: project.Name, UserName: project.Owner}
} }
func findOrCreateToken(user, password string) (string, error) { func findOrCreateToken(user, password, twoFactorCode string) (string, error) {
client := octokat.NewClient().WithLogin(user, password) client := octokat.NewClient().WithLogin(user, password)
auths, err := client.Authorizations(nil) options := &octokat.Options{}
if twoFactorCode != "" {
headers := octokat.Headers{"X-GitHub-OTP": twoFactorCode}
options.Headers = headers
}
auths, err := client.Authorizations(options)
if err != nil { if err != nil {
return "", err return "", err
} }
...@@ -147,9 +153,9 @@ func findOrCreateToken(user, password string) (string, error) { ...@@ -147,9 +153,9 @@ func findOrCreateToken(user, password string) (string, error) {
authParam.Scopes = append(authParam.Scopes, "repo") authParam.Scopes = append(authParam.Scopes, "repo")
authParam.Note = "gh" authParam.Note = "gh"
authParam.NoteURL = OAuthAppURL authParam.NoteURL = OAuthAppURL
options := octokat.Options{Params: authParam} options.Params = authParam
auth, err := client.CreateAuthorization(&options) auth, err := client.CreateAuthorization(options)
if err != nil { if err != nil {
return "", err return "", err
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册