Fix Client.AuthRefresh

This commit is contained in:
emersion 2017-08-22 12:07:31 +02:00
parent 8baa4a62f6
commit a6f6f5f8e2
No known key found for this signature in database
GPG Key ID: 0FDE7BE0E88F5E48
2 changed files with 76 additions and 26 deletions

View File

@ -2,6 +2,7 @@ package main
import (
"bufio"
"encoding/json"
"fmt"
"log"
"os"
@ -9,6 +10,30 @@ import (
"github.com/emersion/hydroxide/protonmail"
)
const authFile = "auth.json"
func readCachedAuth() (*protonmail.Auth, error) {
f, err := os.Open(authFile)
if err != nil {
return nil, err
}
defer f.Close()
auth := new(protonmail.Auth)
err = json.NewDecoder(f).Decode(auth)
return auth, err
}
func saveAuth(auth *protonmail.Auth) error {
f, err := os.Create(authFile)
if err != nil {
return err
}
defer f.Close()
return json.NewEncoder(f).Encode(auth)
}
func main() {
c := &protonmail.Client{
RootURL: "https://dev.protonmail.com/api",
@ -19,13 +44,26 @@ func main() {
scanner := bufio.NewScanner(os.Stdin)
var password string
auth, err := readCachedAuth()
if err == nil {
passwordMode := auth.PasswordMode
var err error
auth, err = c.AuthRefresh(auth.UID, auth.RefreshToken)
if err != nil {
log.Fatal(err)
}
auth.PasswordMode = passwordMode
} else if os.IsNotExist(err) {
fmt.Printf("Username: ")
scanner.Scan()
username := scanner.Text()
fmt.Printf("Password: ")
scanner.Scan()
password := scanner.Text()
password = scanner.Text()
authInfo, err := c.AuthInfo(username)
if err != nil {
@ -39,21 +77,29 @@ func main() {
twoFactorCode = scanner.Text()
}
auth, err := c.Auth(username, password, twoFactorCode, authInfo)
auth, err = c.Auth(username, password, twoFactorCode, authInfo)
if err != nil {
log.Fatal(err)
}
log.Println(auth)
var mailboxPassword string
if auth.PasswordMode == protonmail.PasswordTwo {
fmt.Printf("Mailbox password: ")
scanner.Scan()
mailboxPassword = scanner.Text()
} else {
log.Fatal(err)
}
_, err = c.Unlock(auth, mailboxPassword)
if err := saveAuth(auth); err != nil {
log.Fatal(err)
}
if auth.PasswordMode == protonmail.PasswordTwo || password == "" {
if auth.PasswordMode == protonmail.PasswordTwo {
fmt.Printf("Mailbox password: ")
} else {
fmt.Printf("Password: ")
}
scanner.Scan()
password = scanner.Text()
}
_, err = c.Unlock(auth, password)
if err != nil {
log.Fatal(err)
}

View File

@ -154,15 +154,19 @@ func (c *Client) Auth(username, password, twoFactorCode string, info *AuthInfo)
type authRefreshReq struct {
ClientID string
ClientSecret string
UID string `json:"Uid"`
RefreshToken string
// Unused but required
ResponseType string
GrantType string
RedirectURI string
State string
}
func (c *Client) AuthRefresh(uid, refreshToken string) (*Auth, error) {
reqData := &authRefreshReq{
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
UID: uid,
RefreshToken: refreshToken,
}