This PR starts to implement the refactoring described at https://github.com/ooni/probe/issues/1951. I originally wrote more patches than the ones in this PR, but overall they were not readable. Since I want to squash and merge, here's a reasonable subset of the original patches that will still be readable and understandable in the future.
38 lines
840 B
Go
38 lines
840 B
Go
package probeservices
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
)
|
|
|
|
// LoginCredentials contains the login credentials
|
|
type LoginCredentials struct {
|
|
ClientID string `json:"username"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
// LoginAuth contains authentication info
|
|
type LoginAuth struct {
|
|
Expire time.Time `json:"expire"`
|
|
Token string `json:"token"`
|
|
}
|
|
|
|
// MaybeLogin performs login if necessary
|
|
func (c Client) MaybeLogin(ctx context.Context) error {
|
|
state := c.StateFile.Get()
|
|
if state.Auth() != nil {
|
|
return nil // we're already good
|
|
}
|
|
creds := state.Credentials()
|
|
if creds == nil {
|
|
return ErrNotRegistered
|
|
}
|
|
c.LoginCalls.Add(1)
|
|
var auth LoginAuth
|
|
if err := c.APIClient.PostJSON(ctx, "/api/v1/login", *creds, &auth); err != nil {
|
|
return err
|
|
}
|
|
state.Expire = auth.Expire
|
|
state.Token = auth.Token
|
|
return c.StateFile.Set(state)
|
|
}
|