forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Support new Tesla login including MFA devices (evcc-io#626)
- Loading branch information
Showing
8 changed files
with
594 additions
and
35 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
package cmd | ||
|
||
import ( | ||
"bufio" | ||
"context" | ||
"errors" | ||
"fmt" | ||
"os" | ||
"strings" | ||
|
||
"github.com/andig/evcc/server" | ||
"github.com/andig/evcc/util" | ||
auth "github.com/andig/evcc/vehicle/tesla" | ||
"github.com/spf13/cobra" | ||
"github.com/spf13/viper" | ||
"github.com/thoas/go-funk" | ||
"github.com/uhthomas/tesla" | ||
) | ||
|
||
// teslaCmd represents the vehicle command | ||
var teslaCmd = &cobra.Command{ | ||
Use: "tesla-token [name]", | ||
Short: "Generate Tesla access token for configured vehicle", | ||
Run: runTeslaToken, | ||
} | ||
|
||
func init() { | ||
rootCmd.AddCommand(teslaCmd) | ||
} | ||
|
||
func codePrompt(ctx context.Context, devices []tesla.Device) (tesla.Device, string, error) { | ||
fmt.Println("Authentication devices:", funk.Map(devices, func(d tesla.Device) string { | ||
return fmt.Sprintf("%s (%s)", d.Name, d.FactorType) | ||
})) | ||
if len(devices) > 1 { | ||
return tesla.Device{}, "", errors.New("multiple devices found, only single device supported") | ||
} | ||
|
||
fmt.Print("Please enter passcode: ") | ||
reader := bufio.NewReader(os.Stdin) | ||
code, err := reader.ReadString('\n') | ||
|
||
return devices[0], strings.TrimSpace(code), err | ||
} | ||
|
||
func generateToken(user, pass string) { | ||
client, err := auth.NewClient(log) | ||
if err != nil { | ||
log.FATAL.Fatalln(err) | ||
} | ||
|
||
client.DeviceHandler(codePrompt) | ||
|
||
ts, err := client.Login(user, pass) | ||
if err != nil { | ||
log.FATAL.Fatalln(err) | ||
} | ||
|
||
token, err := ts.Token() | ||
if err != nil { | ||
log.FATAL.Fatalln(err) | ||
} | ||
|
||
fmt.Println() | ||
fmt.Println("Add the following tokens to the tesla vehicle config:") | ||
fmt.Println() | ||
fmt.Println(" tokens:") | ||
fmt.Println(" access:", token.AccessToken) | ||
fmt.Println(" refresh:", token.RefreshToken) | ||
} | ||
|
||
func runTeslaToken(cmd *cobra.Command, args []string) { | ||
util.LogLevel(viper.GetString("log"), viper.GetStringMapString("levels")) | ||
log.INFO.Printf("evcc %s (%s)", server.Version, server.Commit) | ||
|
||
// load config | ||
conf, err := loadConfigFile(cfgFile) | ||
if err != nil { | ||
log.FATAL.Fatal(err) | ||
} | ||
|
||
var vehicleConf qualifiedConfig | ||
if len(conf.Vehicles) == 1 { | ||
vehicleConf = conf.Vehicles[0] | ||
} else if len(args) == 1 { | ||
vehicleConf = funk.Find(conf.Vehicles, func(v qualifiedConfig) bool { | ||
return strings.ToLower(v.Name) == strings.ToLower(args[0]) | ||
}).(qualifiedConfig) | ||
} | ||
|
||
if vehicleConf.Name == "" { | ||
log.FATAL.Fatal("vehicle not found") | ||
} | ||
|
||
var credentials struct { | ||
User, Password string | ||
Other map[string]interface{} `mapstructure:",remain"` | ||
} | ||
|
||
if err := util.DecodeOther(vehicleConf.Other, &credentials); err != nil { | ||
log.FATAL.Fatal(err) | ||
} | ||
|
||
generateToken(credentials.User, credentials.Password) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
package tesla | ||
|
||
import ( | ||
"context" | ||
"crypto/rand" | ||
"crypto/sha256" | ||
"encoding/base64" | ||
"errors" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
|
||
"github.com/andig/evcc/util" | ||
"github.com/uhthomas/tesla" | ||
"golang.org/x/oauth2" | ||
) | ||
|
||
// Client is the tesla authentication client | ||
type Client struct { | ||
config *oauth2.Config | ||
auth *tesla.Auth | ||
verifier string | ||
} | ||
|
||
// github.com/uhthomas/tesla | ||
func state() string { | ||
var b [9]byte | ||
if _, err := io.ReadFull(rand.Reader, b[:]); err != nil { | ||
panic(err) | ||
} | ||
return base64.RawURLEncoding.EncodeToString(b[:]) | ||
} | ||
|
||
// https://www.oauth.com/oauth2-servers/pkce/ | ||
func pkce() (verifier, challenge string, err error) { | ||
var p [87]byte | ||
if _, err := io.ReadFull(rand.Reader, p[:]); err != nil { | ||
return "", "", fmt.Errorf("rand read full: %w", err) | ||
} | ||
verifier = base64.RawURLEncoding.EncodeToString(p[:]) | ||
b := sha256.Sum256([]byte(challenge)) | ||
challenge = base64.RawURLEncoding.EncodeToString(b[:]) | ||
return verifier, challenge, nil | ||
} | ||
|
||
// NewClient creates a tesla authentication client | ||
func NewClient(log *util.Logger) (*Client, error) { | ||
httpClient := &http.Client{Transport: &roundTripper{ | ||
log: log, | ||
transport: http.DefaultTransport, | ||
}} | ||
|
||
config := &oauth2.Config{ | ||
ClientID: "ownerapi", | ||
ClientSecret: "", | ||
RedirectURL: "https://auth.tesla.com/void/callback", | ||
Scopes: []string{"openid email offline_access"}, | ||
Endpoint: oauth2.Endpoint{ | ||
AuthURL: "https://auth.tesla.com/oauth2/v3/authorize", | ||
TokenURL: "https://auth.tesla.com/oauth2/v3/token", | ||
}, | ||
} | ||
|
||
verifier, challenge, err := pkce() | ||
if err != nil { | ||
return nil, fmt.Errorf("pkce: %w", err) | ||
} | ||
|
||
auth := &tesla.Auth{ | ||
Client: httpClient, | ||
AuthURL: config.AuthCodeURL(state(), oauth2.AccessTypeOffline, | ||
oauth2.SetAuthURLParam("code_challenge", challenge), | ||
oauth2.SetAuthURLParam("code_challenge_method", "S256"), | ||
), | ||
} | ||
|
||
client := &Client{ | ||
config: config, | ||
auth: auth, | ||
verifier: verifier, | ||
} | ||
client.DeviceHandler(client.mfaUnsupported) | ||
|
||
return client, nil | ||
} | ||
|
||
// Login executes the MFA or non-MFA login | ||
func (c *Client) Login(username, password string) (oauth2.TokenSource, error) { | ||
ctx := context.Background() | ||
code, err := c.auth.Do(ctx, username, password) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
token, err := c.config.Exchange(ctx, code, | ||
oauth2.SetAuthURLParam("code_verifier", c.verifier), | ||
) | ||
if err != nil { | ||
return nil, fmt.Errorf("exchange: %w", err) | ||
} | ||
|
||
return c.TokenSource(token), nil | ||
} | ||
|
||
// TokenSource creates an oauth tokensource from given token | ||
func (c *Client) TokenSource(token *oauth2.Token) oauth2.TokenSource { | ||
ctx := context.Background() | ||
return c.config.TokenSource(ctx, token) | ||
} | ||
|
||
// DeviceHandler sets an alternative authentication device handler | ||
func (c *Client) DeviceHandler(handler func(context.Context, []tesla.Device) (tesla.Device, string, error)) { | ||
c.auth.SelectDevice = handler | ||
} | ||
|
||
func (c *Client) mfaUnsupported(_ context.Context, _ []tesla.Device) (tesla.Device, string, error) { | ||
return tesla.Device{}, "", errors.New("multi factor authentication is not supported") | ||
} |
Oops, something went wrong.