maildownloader/authentication.go

62 lines
1.5 KiB
Go

package main
import (
"context"
"fmt"
"log"
"os"
"encoding/json"
"net/http"
"path/filepath"
"golang.org/x/oauth2"
)
func getClient(config *oauth2.Config) *http.Client {
token_file := filepath.Join(CREDENTIALS_DIR, TOKEN_FILE)
token, err := tokenFromFile(token_file)
if err != nil {
token = getTokenFromWeb(config)
saveToken(token_file, token)
}
return config.Client(context.Background(), token)
}
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
auth_url := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf("Go to the following link in your browser, then type the " +
"authorization code: \n%v\n", auth_url)
var auth_code string
if _, err := fmt.Scan(&auth_code) ; err != nil {
log.Fatalf("Unable to read authorization code: %v", err)
}
token, err := config.Exchange(context.TODO(), auth_code)
if err != nil {
log.Fatalf("Unable to retrieve token from web: %v", err)
}
return token
}
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
token := &oauth2.Token{}
err = json.NewDecoder(f).Decode(token)
return token, err
}
func saveToken(path string, token *oauth2.Token) {
fmt.Printf("Saving credential file to: %s\n", path)
file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer file.Close()
json.NewEncoder(file).Encode(token)
}