github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+incompatible/api/uaa/user.go (about)

     1  package uaa
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"net/http"
     7  
     8  	"code.cloudfoundry.org/cli/api/uaa/internal"
     9  )
    10  
    11  // User represents an UAA user account.
    12  type User struct {
    13  	ID string
    14  }
    15  
    16  // newUserRequestBody represents the body of the request.
    17  type newUserRequestBody struct {
    18  	Username string   `json:"userName"`
    19  	Password string   `json:"password"`
    20  	Origin   string   `json:"origin"`
    21  	Name     userName `json:"name"`
    22  	Emails   []email  `json:"emails"`
    23  }
    24  
    25  type userName struct {
    26  	FamilyName string `json:"familyName"`
    27  	GivenName  string `json:"givenName"`
    28  }
    29  
    30  type email struct {
    31  	Value   string `json:"value"`
    32  	Primary bool   `json:"primary"`
    33  }
    34  
    35  // newUserResponse represents the HTTP JSON response.
    36  type newUserResponse struct {
    37  	ID string `json:"id"`
    38  }
    39  
    40  // CreateUser creates a new UAA user account with the provided password.
    41  func (client *Client) CreateUser(user string, password string, origin string) (User, error) {
    42  	userRequest := newUserRequestBody{
    43  		Username: user,
    44  		Password: password,
    45  		Origin:   origin,
    46  		Name: userName{
    47  			FamilyName: user,
    48  			GivenName:  user,
    49  		},
    50  		Emails: []email{
    51  			{
    52  				Value:   user,
    53  				Primary: true,
    54  			},
    55  		},
    56  	}
    57  
    58  	bodyBytes, err := json.Marshal(userRequest)
    59  	if err != nil {
    60  		return User{}, err
    61  	}
    62  
    63  	request, err := client.newRequest(requestOptions{
    64  		RequestName: internal.PostUserRequest,
    65  		Header: http.Header{
    66  			"Content-Type": {"application/json"},
    67  		},
    68  		Body: bytes.NewBuffer(bodyBytes),
    69  	})
    70  	if err != nil {
    71  		return User{}, err
    72  	}
    73  
    74  	var userResponse newUserResponse
    75  	response := Response{
    76  		Result: &userResponse,
    77  	}
    78  
    79  	err = client.connection.Make(request, &response)
    80  	if err != nil {
    81  		return User{}, err
    82  	}
    83  
    84  	return User{ID: userResponse.ID}, nil
    85  }