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.
		
			
				
	
	
		
			43 lines
		
	
	
		
			964 B
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			43 lines
		
	
	
		
			964 B
		
	
	
	
		
			Go
		
	
	
	
	
	
| package probeservices
 | |
| 
 | |
| import (
 | |
| 	"context"
 | |
| 
 | |
| 	"github.com/ooni/probe-cli/v3/internal/randx"
 | |
| )
 | |
| 
 | |
| type registerRequest struct {
 | |
| 	Metadata
 | |
| 	Password string `json:"password"`
 | |
| }
 | |
| 
 | |
| type registerResult struct {
 | |
| 	ClientID string `json:"client_id"`
 | |
| }
 | |
| 
 | |
| // MaybeRegister registers this client if not already registered
 | |
| func (c Client) MaybeRegister(ctx context.Context, metadata Metadata) error {
 | |
| 	if !metadata.Valid() {
 | |
| 		return ErrInvalidMetadata
 | |
| 	}
 | |
| 	state := c.StateFile.Get()
 | |
| 	if state.Credentials() != nil {
 | |
| 		return nil // we're already good
 | |
| 	}
 | |
| 	c.RegisterCalls.Add(1)
 | |
| 	// TODO(bassosimone): here we should use a CSRNG
 | |
| 	// (https://github.com/ooni/probe/issues/1502)
 | |
| 	pwd := randx.Letters(64)
 | |
| 	req := ®isterRequest{
 | |
| 		Metadata: metadata,
 | |
| 		Password: pwd,
 | |
| 	}
 | |
| 	var resp registerResult
 | |
| 	if err := c.APIClient.PostJSON(ctx, "/api/v1/register", req, &resp); err != nil {
 | |
| 		return err
 | |
| 	}
 | |
| 	state.ClientID = resp.ClientID
 | |
| 	state.Password = pwd
 | |
| 	return c.StateFile.Set(state)
 | |
| }
 |