...

Source file src/github.com/okta/okta-sdk-golang/v2/tests/integration/user_test.go

Documentation: github.com/okta/okta-sdk-golang/v2/tests/integration

     1  /*
     2   * Copyright 2018 - Present Okta, Inc.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *      http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package integration
    18  
    19  import (
    20  	"context"
    21  	"net/http"
    22  	"testing"
    23  	"time"
    24  
    25  	"github.com/okta/okta-sdk-golang/v2/okta"
    26  	"github.com/okta/okta-sdk-golang/v2/okta/query"
    27  	"github.com/okta/okta-sdk-golang/v2/tests"
    28  	"github.com/stretchr/testify/assert"
    29  	"github.com/stretchr/testify/require"
    30  )
    31  
    32  func TestCanGetAUser(t *testing.T) {
    33  	ctx, client, err := tests.NewClient(context.TODO())
    34  	require.NoError(t, err)
    35  	// Create user with credentials → POST /api/v1/users?activate=false
    36  	p := &okta.PasswordCredential{
    37  		Value: "Abcd1234",
    38  	}
    39  	uc := &okta.UserCredentials{
    40  		Password: p,
    41  	}
    42  	profile := okta.UserProfile{}
    43  	profile["firstName"] = "John"
    44  	profile["lastName"] = "Get-User"
    45  	profile["email"] = randomEmail()
    46  	profile["login"] = profile["email"]
    47  	u := &okta.CreateUserRequest{
    48  		Credentials: uc,
    49  		Profile:     &profile,
    50  	}
    51  	qp := query.NewQueryParams(query.WithActivate(false))
    52  
    53  	user, _, err := client.User.CreateUser(ctx, *u, qp)
    54  	require.NoError(t, err, "Creating a new user should not error")
    55  
    56  	// Get the user by ID → GET /api/v1/users/{{userId}}
    57  	ubid, _, err := client.User.GetUser(ctx, user.Id)
    58  	require.NoError(t, err, "Getting a user by id should not error")
    59  	assert.Equal(t, user.Id, ubid.Id, "Could not find user by Id")
    60  
    61  	// Get the user by login name → GET /api/v1/users/{{login}}
    62  	ubln, _, err := client.User.GetUser(ctx, profile["login"].(string))
    63  	require.NoError(t, err, "Getting a user by login should not error")
    64  	assert.Equal(t, user.Id, ubln.Id, "Could not find user by Login")
    65  
    66  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
    67  	_, err = client.User.DeactivateUser(ctx, user.Id, nil)
    68  	require.NoError(t, err, "Should not error when deactivating")
    69  
    70  	// Delete the user → DELETE /api/v1/users/{{userId}}
    71  	_, err = client.User.DeactivateOrDeleteUser(ctx, user.Id, nil)
    72  	require.NoError(t, err, "Should not error when deleting")
    73  
    74  	// Verify that the user is deleted by calling get on user (Exception thrown with 404 error message) → GET /api/v1/users/{{userId}}
    75  	_, _, err = client.User.GetUser(ctx, user.Id)
    76  	require.Error(t, err, "User should not exist, but does")
    77  }
    78  
    79  func TestCanActivateAUser(t *testing.T) {
    80  	ctx, client, err := tests.NewClient(context.TODO())
    81  	require.NoError(t, err)
    82  	// Create user with credentials → POST /api/v1/users?activate=false
    83  	uc := &okta.UserCredentials{
    84  		Password: &okta.PasswordCredential{
    85  			Value: "Abcd1234",
    86  		},
    87  	}
    88  	profile := okta.UserProfile{}
    89  	profile["firstName"] = "John"
    90  	profile["lastName"] = "Activate"
    91  	profile["email"] = randomEmail()
    92  	profile["login"] = profile["email"]
    93  	u := &okta.CreateUserRequest{
    94  		Credentials: uc,
    95  		Profile:     &profile,
    96  	}
    97  	qp := query.NewQueryParams(query.WithActivate(false))
    98  
    99  	user, _, err := client.User.CreateUser(ctx, *u, qp)
   100  	require.NoError(t, err, "Creating a new user should not error")
   101  
   102  	// Activate the user → POST /api/v1/users/{{userId}}/lifecycle/activate?sendEmail=false
   103  	token, _, err := client.User.ActivateUser(ctx, user.Id, query.NewQueryParams(query.WithSendEmail(false)))
   104  	require.NoError(t, err, "Could not activate the user")
   105  	assert.NotEmpty(t, token, "Token was not provided")
   106  	assert.IsType(t, &okta.UserActivationToken{}, token, "Activation did not return correct type")
   107  
   108  	crUser, _, err := client.User.GetUser(ctx, user.Id)
   109  	require.NoError(t, err, "Could not get user by ID")
   110  	assert.NotNil(t, crUser.Activated, "users activation time is missing")
   111  
   112  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   113  	_, err = client.User.DeactivateUser(ctx, user.Id, nil)
   114  	require.NoError(t, err, "Should not error when deactivating")
   115  
   116  	// Delete the user → DELETE /api/v1/users/{{userId}}
   117  	_, err = client.User.DeactivateOrDeleteUser(ctx, user.Id, nil)
   118  	require.NoError(t, err, "Should not error when deleting")
   119  }
   120  
   121  func TestCanUpdateUserProfile(t *testing.T) {
   122  	ctx, client, err := tests.NewClient(context.TODO())
   123  	require.NoError(t, err)
   124  	// Create user with credentials → POST /api/v1/users?activate=false
   125  	p := &okta.PasswordCredential{
   126  		Value: "Abcd1234",
   127  	}
   128  	uc := &okta.UserCredentials{
   129  		Password: p,
   130  	}
   131  	profile := okta.UserProfile{}
   132  	profile["firstName"] = "John"
   133  	profile["lastName"] = "Profile-Update"
   134  	profile["email"] = randomEmail()
   135  	profile["login"] = profile["email"]
   136  	u := &okta.CreateUserRequest{
   137  		Credentials: uc,
   138  		Profile:     &profile,
   139  	}
   140  	qp := query.NewQueryParams(query.WithActivate(false))
   141  
   142  	user, _, err := client.User.CreateUser(ctx, *u, qp)
   143  	require.NoError(t, err, "Creating a new user should not error")
   144  
   145  	// Update the user's profile by adding a nickname → PUT /api/v1/users/{{userId}}
   146  	newProfile := *user.Profile
   147  	newProfile["nickName"] = "Batman"
   148  	updatedUser := &okta.User{
   149  		Profile: &newProfile,
   150  	}
   151  	_, _, err = client.User.UpdateUser(ctx, user.Id, *updatedUser, nil)
   152  	require.NoError(t, err, "Could not update the user")
   153  
   154  	// Verify that user profile is updated by calling get on the user → GET /api/v1/users/{{userId}}
   155  	tmpUser, _, err := client.User.GetUser(ctx, user.Id)
   156  	require.NoError(t, err, "User was not available to get")
   157  	tmpProfile := *tmpUser.Profile
   158  	assert.Equal(t, "Batman", tmpProfile["nickName"])
   159  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   160  	_, err = client.User.DeactivateUser(ctx, user.Id, nil)
   161  	require.NoError(t, err, "Should not error when deactivating")
   162  
   163  	// Delete the user → DELETE /api/v1/users/{{userId}}
   164  	_, err = client.User.DeactivateOrDeleteUser(ctx, user.Id, nil)
   165  	require.NoError(t, err, "Should not error when deleting")
   166  }
   167  
   168  func TestCanSuspendAUser(t *testing.T) {
   169  	ctx, client, err := tests.NewClient(context.TODO())
   170  	require.NoError(t, err)
   171  	// Create user with credentials → POST /api/v1/users?activate=true
   172  	p := &okta.PasswordCredential{
   173  		Value: "Abcd1234",
   174  	}
   175  	uc := &okta.UserCredentials{
   176  		Password: p,
   177  	}
   178  	profile := okta.UserProfile{}
   179  	profile["firstName"] = "John"
   180  	profile["lastName"] = "Suspend"
   181  	profile["email"] = randomEmail()
   182  	profile["login"] = profile["email"]
   183  	u := &okta.CreateUserRequest{
   184  		Credentials: uc,
   185  		Profile:     &profile,
   186  	}
   187  	qp := query.NewQueryParams(query.WithActivate(true))
   188  
   189  	user, _, err := client.User.CreateUser(ctx, *u, qp)
   190  	require.NoError(t, err, "Creating a new user should not error")
   191  
   192  	// Suspend the user → POST /api/v1/users/{{userId}}/lifecycle/suspend
   193  	_, err = client.User.SuspendUser(ctx, user.Id)
   194  	require.NoError(t, err, "Could not suspend the user")
   195  
   196  	// Verify that user is in the list of suspended users → GET /api/v1/users?filter=status eq "SUSPENDED"
   197  	filter := query.NewQueryParams(query.WithFilter("status eq \"SUSPENDED\""))
   198  	users, _, err := client.User.ListUsers(ctx, filter)
   199  	require.NoError(t, err, "Could not get suspended users")
   200  	found := false
   201  	for _, u := range users {
   202  		if user.Id == u.Id {
   203  			found = true
   204  		}
   205  	}
   206  	assert.True(t, found, "The user was not found")
   207  
   208  	// Unsuspend the user →  POST /api/v1/users/{{userId}}/lifecycle/unsuspend
   209  	_, err = client.User.UnsuspendUser(ctx, user.Id)
   210  	require.NoError(t, err, "Could not unsuspend the user")
   211  
   212  	// Verify that user is in the list of active users → GET /api/v1/users?filter=status eq "ACTIVE"
   213  	filter = query.NewQueryParams(query.WithFilter("status eq \"ACTIVE\""))
   214  	users, _, err = client.User.ListUsers(ctx, filter)
   215  	require.NoError(t, err, "Could not get active users")
   216  	found = false
   217  	for _, u := range users {
   218  		if user.Id == u.Id {
   219  			found = true
   220  		}
   221  	}
   222  	assert.True(t, found, "The user was not found")
   223  
   224  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   225  	_, err = client.User.DeactivateUser(ctx, user.Id, nil)
   226  	require.NoError(t, err, "Should not error when deactivating")
   227  
   228  	// Delete the user → DELETE /api/v1/users/{{userId}}
   229  	_, err = client.User.DeactivateOrDeleteUser(ctx, user.Id, nil)
   230  	require.NoError(t, err, "Should not error when deleting")
   231  }
   232  
   233  func TestCanChangeUsersPassword(t *testing.T) {
   234  	ctx, client, err := tests.NewClient(context.TODO())
   235  	require.NoError(t, err)
   236  	// Create user with credentials → POST /api/v1/users?activate=true
   237  	p := &okta.PasswordCredential{
   238  		Value: "Abcd1234",
   239  	}
   240  	uc := &okta.UserCredentials{
   241  		Password: p,
   242  	}
   243  	profile := okta.UserProfile{}
   244  	profile["firstName"] = "John"
   245  	profile["lastName"] = "Change-Password"
   246  	profile["email"] = randomEmail()
   247  	profile["login"] = profile["email"]
   248  	u := &okta.CreateUserRequest{
   249  		Credentials: uc,
   250  		Profile:     &profile,
   251  	}
   252  	qp := query.NewQueryParams(query.WithActivate(true))
   253  
   254  	user, _, err := client.User.CreateUser(ctx, *u, qp)
   255  	require.NoError(t, err, "Creating a new user should not error")
   256  
   257  	// Sleep 1 second to make sure time has passed for password chagned timestamps
   258  	time.Sleep(1 * time.Second)
   259  
   260  	// Change the password to '1234Abcd' → POST /api/v1/users/{{userId}}/credentials/change_password
   261  	op := &okta.PasswordCredential{
   262  		Value: "Abcd1234",
   263  	}
   264  	np := &okta.PasswordCredential{
   265  		Value: "1234Abcd",
   266  	}
   267  	npr := &okta.ChangePasswordRequest{
   268  		OldPassword: op,
   269  		NewPassword: np,
   270  	}
   271  	_, _, err = client.User.ChangePassword(ctx, user.Id, *npr, nil)
   272  	require.NoError(t, err, "Could not change password")
   273  
   274  	// Get the user and verify that 'passwordChanged' field has increased → GET /api/v1/users/{{userId}}/
   275  	ubid, _, err := client.User.GetUser(ctx, user.Id)
   276  	require.NoError(t, err, "Getting a user by login should not error")
   277  	assert.Equal(t, user.Id, ubid.Id, "Could not find user by Login")
   278  	assert.True(t, ubid.PasswordChanged.After(*user.PasswordChanged), "Appears that password change did not happen")
   279  
   280  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   281  	_, err = client.User.DeactivateUser(ctx, user.Id, nil)
   282  	require.NoError(t, err, "Should not error when deactivating")
   283  
   284  	// Delete the user → DELETE /api/v1/users/{{userId}}
   285  	_, err = client.User.DeactivateOrDeleteUser(ctx, user.Id, nil)
   286  	require.NoError(t, err, "Should not error when deleting")
   287  
   288  	// Verify that the user is deleted by calling get on user (Exception thrown with 404 error message) → GET /api/v1/users/{{userId}}
   289  	_, _, err = client.User.GetUser(ctx, user.Id)
   290  	require.Error(t, err, "User should not exist, but does")
   291  }
   292  
   293  func TestCanGetResetPasswordLinkForUser(t *testing.T) {
   294  	ctx, client, err := tests.NewClient(context.TODO())
   295  	require.NoError(t, err)
   296  	// Create user with credentials → POST /api/v1/users?activate=true
   297  	p := &okta.PasswordCredential{
   298  		Value: "Abcd1234",
   299  	}
   300  	uc := &okta.UserCredentials{
   301  		Password: p,
   302  	}
   303  	profile := okta.UserProfile{}
   304  	profile["firstName"] = "John"
   305  	profile["lastName"] = "Get-Reset-Password-Url"
   306  	profile["email"] = randomEmail()
   307  	profile["login"] = profile["email"]
   308  	u := &okta.CreateUserRequest{
   309  		Credentials: uc,
   310  		Profile:     &profile,
   311  	}
   312  	qp := query.NewQueryParams(query.WithActivate(true))
   313  
   314  	user, _, err := client.User.CreateUser(ctx, *u, qp)
   315  	require.NoError(t, err, "Creating a new user should not error")
   316  
   317  	// Reset the user password → POST /api/v1/users/{{userId}}/lifecycle/reset_password?sendEmail=false
   318  	rpt, _, err := client.User.ResetPassword(ctx, user.Id, query.NewQueryParams(query.WithSendEmail(false)))
   319  	require.NoError(t, err, "Could not reset password")
   320  
   321  	// Verify that the response returned contains the reset password link
   322  	assert.IsType(t, &okta.ResetPasswordToken{}, rpt)
   323  	assert.NotEmpty(t, rpt.ResetPasswordUrl, "Reset Password is not set")
   324  
   325  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   326  	_, err = client.User.DeactivateUser(ctx, user.Id, nil)
   327  	require.NoError(t, err, "Should not error when deactivating")
   328  
   329  	// Delete the user → DELETE /api/v1/users/{{userId}}
   330  	_, err = client.User.DeactivateOrDeleteUser(ctx, user.Id, nil)
   331  	require.NoError(t, err, "Should not error when deleting")
   332  
   333  	// Verify that the user is deleted by calling get on user (Exception thrown with 404 error message) → GET /api/v1/users/{{userId}}
   334  	_, _, err = client.User.GetUser(ctx, user.Id)
   335  	require.Error(t, err, "User should not exist, but does")
   336  }
   337  
   338  func TestCanExpireAUsersPasswordAndGetATempOne(t *testing.T) {
   339  	ctx, client, err := tests.NewClient(context.TODO())
   340  	require.NoError(t, err)
   341  	// Create a user with credentials, activated by default → POST /api/v1/users?activate=true
   342  	p := &okta.PasswordCredential{
   343  		Value: "Abcd1234",
   344  	}
   345  	uc := &okta.UserCredentials{
   346  		Password: p,
   347  	}
   348  	profile := okta.UserProfile{}
   349  	profile["firstName"] = "John"
   350  	profile["lastName"] = "Expire-Password"
   351  	profile["email"] = randomEmail()
   352  	profile["login"] = profile["email"]
   353  	u := &okta.CreateUserRequest{
   354  		Credentials: uc,
   355  		Profile:     &profile,
   356  	}
   357  	qp := query.NewQueryParams(query.WithActivate(true))
   358  
   359  	user, _, err := client.User.CreateUser(ctx, *u, qp)
   360  	require.NoError(t, err, "Creating a new user should not error")
   361  
   362  	// Expire the user password → POST /api/v1/users/{{userId}}/lifecycle/expire_password?tempPassword=true
   363  	ep, _, err := client.User.ExpirePasswordAndGetTemporaryPassword(ctx, user.Id)
   364  	require.NoError(t, err, "Could not reset password")
   365  
   366  	// Verify that the returned response contains a temporary password
   367  	assert.IsType(t, &okta.TempPassword{}, ep)
   368  	assert.NotEmpty(t, ep.TempPassword, "Temp Password not provided")
   369  
   370  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   371  	_, err = client.User.DeactivateUser(ctx, user.Id, nil)
   372  	require.NoError(t, err, "Should not error when deactivating")
   373  
   374  	// Delete the user → DELETE /api/v1/users/{{userId}}
   375  	_, err = client.User.DeactivateOrDeleteUser(ctx, user.Id, nil)
   376  	require.NoError(t, err, "Should not error when deleting")
   377  
   378  	// Verify that the user is deleted by calling get on user (Exception thrown with 404 error message) → GET /api/v1/users/{{userId}}
   379  	_, _, err = client.User.GetUser(ctx, user.Id)
   380  	require.Error(t, err, "User should not exist, but does")
   381  }
   382  
   383  func TestCanChangeUserRecoveryQuestion(t *testing.T) {
   384  	ctx, client, err := tests.NewClient(context.TODO())
   385  	require.NoError(t, err)
   386  	// Create a user with credentials, activated by default → POST /api/v1/users?activate=true
   387  	p := &okta.PasswordCredential{
   388  		Value: "Abcd1234",
   389  	}
   390  	uc := &okta.UserCredentials{
   391  		Password: p,
   392  	}
   393  	profile := okta.UserProfile{}
   394  	profile["firstName"] = "John"
   395  	profile["lastName"] = "Change-Recovery-Question"
   396  	profile["email"] = randomEmail()
   397  	profile["login"] = profile["email"]
   398  	u := &okta.CreateUserRequest{
   399  		Credentials: uc,
   400  		Profile:     &profile,
   401  	}
   402  	qp := query.NewQueryParams(query.WithActivate(true))
   403  
   404  	user, _, err := client.User.CreateUser(ctx, *u, qp)
   405  	require.NoError(t, err, "Creating a new user should not error")
   406  
   407  	// Update the user's recovery question → POST /api/v1/users/{{userId}}/credentials/change_recovery_question
   408  	nucp := &okta.PasswordCredential{
   409  		Value: "Abcd1234",
   410  	}
   411  	nucrq := &okta.RecoveryQuestionCredential{
   412  		Question: "How many roads must a man walk down?",
   413  		Answer:   "forty two",
   414  	}
   415  	nuc := &okta.UserCredentials{
   416  		Password:         nucp,
   417  		RecoveryQuestion: nucrq,
   418  	}
   419  	tmpuc, _, err := client.User.ChangeRecoveryQuestion(ctx, user.Id, *nuc)
   420  	require.NoError(t, err, "Could not change recovery question")
   421  	assert.IsType(t, &okta.UserCredentials{}, tmpuc)
   422  
   423  	// Update the user's password using updated recovery question credentials passing the body below → POST /api/v1/users/{{userId}}/credentials/forgot_password
   424  	np := &okta.PasswordCredential{
   425  		Value: "1234Abcd",
   426  	}
   427  	rq := &okta.RecoveryQuestionCredential{
   428  		Answer: "forty two",
   429  	}
   430  	ucfp := &okta.UserCredentials{
   431  		Password:         np,
   432  		RecoveryQuestion: rq,
   433  	}
   434  	_, _, err = client.User.ForgotPasswordSetNewPassword(ctx, user.Id, *ucfp, nil)
   435  	require.NoError(t, err, "Could not change password with recovery question")
   436  
   437  	// Get the user and verify that 'passwordChanged' field has increased → GET /api/v1/users/{{userId}}
   438  	ubid, _, err := client.User.GetUser(ctx, user.Id)
   439  	require.NoError(t, err, "Getting a user by login should not error")
   440  	assert.Equal(t, user.Id, ubid.Id, "Could not find user by Login")
   441  	assert.True(t, ubid.PasswordChanged.After(*user.PasswordChanged), "Appears that password change did not happen")
   442  
   443  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   444  	_, err = client.User.DeactivateUser(ctx, user.Id, nil)
   445  	require.NoError(t, err, "Should not error when deactivating")
   446  
   447  	// Delete the user → DELETE /api/v1/users/{{userId}}
   448  	_, err = client.User.DeactivateOrDeleteUser(ctx, user.Id, nil)
   449  	require.NoError(t, err, "Should not error when deleting")
   450  
   451  	// Verify that the user is deleted by calling get on user (Exception thrown with 404 error message) → GET /api/v1/users/{{userId}}
   452  	_, _, err = client.User.GetUser(ctx, user.Id)
   453  	require.Error(t, err, "User should not exist, but does")
   454  }
   455  
   456  func TestCanAssignAUserToARole(t *testing.T) {
   457  	ctx, client, err := tests.NewClient(context.TODO(), okta.WithCache(false))
   458  	require.NoError(t, err)
   459  	// Create a user with credentials, activated by default → POST /api/v1/users?activate=true
   460  	p := &okta.PasswordCredential{
   461  		Value: "Abcd1234",
   462  	}
   463  	uc := &okta.UserCredentials{
   464  		Password: p,
   465  	}
   466  	profile := okta.UserProfile{}
   467  	profile["firstName"] = "John"
   468  	profile["lastName"] = "Role"
   469  	profile["email"] = randomEmail()
   470  	profile["login"] = profile["email"]
   471  	u := &okta.CreateUserRequest{
   472  		Credentials: uc,
   473  		Profile:     &profile,
   474  	}
   475  	qp := query.NewQueryParams(query.WithActivate(true))
   476  
   477  	user, _, err := client.User.CreateUser(ctx, *u, qp)
   478  	require.NoError(t, err, "Creating a new user should not error")
   479  
   480  	// Add 'USER_ADMIN' role to the user → POST /api/v1/users/{{userId}}/roles (Body → { type: 'USER_ADMIN'  })
   481  	arr := &okta.AssignRoleRequest{
   482  		Type: "USER_ADMIN",
   483  	}
   484  	_, _, err = client.User.AssignRoleToUser(ctx, user.Id, *arr, nil)
   485  	require.NoError(t, err, "Should not have had an error when adding role to user")
   486  
   487  	// List roles for the user and verify added role → GET /api/v1/users/{{userId}}/roles
   488  	roles, _, err := client.User.ListAssignedRolesForUser(ctx, user.Id, nil)
   489  	require.NoError(t, err)
   490  	found := false
   491  	roleId := ""
   492  	for _, role := range roles {
   493  		if role.Type == "USER_ADMIN" {
   494  			found = true
   495  			roleId = role.Id
   496  		}
   497  	}
   498  	assert.True(t, found, "Could not verify USER_ADMIN was added to the user")
   499  
   500  	// Remove role for the user → DELETE /api/v1/users/{{userId}}//roles/{{roleId}}/
   501  	_, err = client.User.RemoveRoleFromUser(ctx, user.Id, roleId)
   502  	require.NoError(t, err, "Should not have had an error when removing role to user")
   503  
   504  	// List roles for user and verify role was removed → GET /api/v1/users/{{userId}}/roles
   505  	roles, _, err = client.User.ListAssignedRolesForUser(ctx, user.Id, nil)
   506  	require.NoError(t, err)
   507  	found = false
   508  	for _, role := range roles {
   509  		if role.Type == "USER_ADMIN" {
   510  			found = true
   511  		}
   512  	}
   513  	assert.False(t, found, "Could not verify USER_ADMIN was removed to the user")
   514  
   515  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   516  	_, err = client.User.DeactivateUser(ctx, user.Id, nil)
   517  	require.NoError(t, err, "Should not error when deactivating")
   518  
   519  	// Delete the user → DELETE /api/v1/users/{{userId}}
   520  	_, err = client.User.DeactivateOrDeleteUser(ctx, user.Id, nil)
   521  	require.NoError(t, err, "Should not error when deleting")
   522  
   523  	// Verify that the user is deleted by calling get on user (Exception thrown with 404 error message) → GET /api/v1/users/{{userId}}
   524  	_, resp, err := client.User.GetUser(ctx, user.Id)
   525  	require.Error(t, err, "User should not exist, but does")
   526  	assert.Equal(t, http.StatusNotFound, resp.StatusCode, "Should not have been able to find user")
   527  }
   528  
   529  func TestUserGroupTargetRole(t *testing.T) {
   530  	ctx, client, err := tests.NewClient(context.TODO())
   531  	require.NoError(t, err)
   532  	// Create a user with credentials, activated by default → POST /api/v1/users?activate=true
   533  	p := &okta.PasswordCredential{
   534  		Value: "Abcd1234",
   535  	}
   536  	uc := &okta.UserCredentials{
   537  		Password: p,
   538  	}
   539  	profile := okta.UserProfile{}
   540  	profile["firstName"] = "John"
   541  	profile["lastName"] = "Group-Target"
   542  	profile["email"] = randomEmail()
   543  	profile["login"] = profile["email"]
   544  	u := &okta.CreateUserRequest{
   545  		Credentials: uc,
   546  		Profile:     &profile,
   547  	}
   548  	qp := query.NewQueryParams(query.WithActivate(true))
   549  
   550  	user, _, err := client.User.CreateUser(ctx, *u, qp)
   551  	require.NoError(t, err, "Creating a new user should not error")
   552  
   553  	// Create a new group → POST /api/v1/groups
   554  	gp := &okta.GroupProfile{
   555  		Name: "SDK_TEST Group-Target Test Group",
   556  	}
   557  	g := &okta.Group{
   558  		Profile: gp,
   559  	}
   560  	group, _, err := client.Group.CreateGroup(ctx, *g)
   561  	require.NoError(t, err, "Creating an group should not error")
   562  
   563  	// Add 'USER_ADMIN' role to the user → POST /api/v1/users/{{userId}}/roles (Body → { type: 'USER_ADMIN'  })
   564  	arr := &okta.AssignRoleRequest{
   565  		Type: "USER_ADMIN",
   566  	}
   567  	r, _, err := client.User.AssignRoleToUser(ctx, user.Id, *arr, nil)
   568  	require.NoError(t, err, "Should not have had an error when adding role to user")
   569  
   570  	// Add Group Target to 'USER_ADMIN' role → PUT /api/v1/users/{{userId}}/roles/{{roleId}}/targets/groups/{{groupId}}
   571  	_, err = client.User.AddGroupTargetToRole(ctx, user.Id, r.Id, group.Id)
   572  	require.NoError(t, err, "Should not have had an error when adding group target to role")
   573  
   574  	// List Group Targets for role → GET  /api/v1/users/{{userId}}/roles/{{roleId}}/targets/groups
   575  	groups, _, err := client.User.ListGroupTargetsForRole(ctx, user.Id, r.Id, nil)
   576  	require.NoError(t, err)
   577  	found := false
   578  	for _, tmpgroup := range groups {
   579  		if tmpgroup.Id == group.Id {
   580  			found = true
   581  		}
   582  	}
   583  	assert.True(t, found, "Could not verify group target")
   584  
   585  	// Remove Group Target from Admin User Role and verify removed → DELETE /api/v1/users/{{userId}}/roles/{{roleId}}/targets/groups/{{groupId}}
   586  	gp = &okta.GroupProfile{
   587  		Name: "SDK_TEST TMP - Group-Target Test Group",
   588  	}
   589  	g = &okta.Group{
   590  		Profile: gp,
   591  	}
   592  	newgroup, _, err := client.Group.CreateGroup(ctx, *g)
   593  	require.NoError(t, err)
   594  	_, err = client.User.AddGroupTargetToRole(ctx, user.Id, r.Id, newgroup.Id)
   595  	require.NoError(t, err)
   596  	_, err = client.User.RemoveGroupTargetFromRole(ctx, user.Id, r.Id, group.Id)
   597  	require.NoError(t, err, "Should not have had an error when removing group target to role")
   598  
   599  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   600  	_, err = client.User.DeactivateUser(ctx, user.Id, nil)
   601  	require.NoError(t, err, "Should not error when deactivating")
   602  
   603  	// Delete the user → DELETE /api/v1/users/{{userId}}
   604  	_, err = client.User.DeactivateOrDeleteUser(ctx, user.Id, nil)
   605  	require.NoError(t, err, "Should not error when deleting")
   606  
   607  	// Verify that the user is deleted by calling get on user (Exception thrown with 404 error message) → GET /api/v1/users/{{userId}}
   608  	_, resp, err := client.User.GetUser(ctx, user.Id)
   609  	require.Error(t, err, "User should not exist, but does")
   610  	assert.Equal(t, http.StatusNotFound, resp.StatusCode, "Should not have been able to find user")
   611  
   612  	// Delete the group → DELETE /api/v1/groups/{{groupId}}
   613  	client.Group.DeleteGroup(ctx, group.Id)
   614  	client.Group.DeleteGroup(ctx, newgroup.Id)
   615  }
   616  
   617  func TestCanGetUserWithCacheEnabled(t *testing.T) {
   618  	ctx, client, err := tests.NewClient(context.TODO())
   619  	require.NoError(t, err)
   620  
   621  	p := &okta.PasswordCredential{
   622  		Value: "Abcd1234",
   623  	}
   624  	uc := &okta.UserCredentials{
   625  		Password: p,
   626  	}
   627  	profile := okta.UserProfile{}
   628  	profile["firstName"] = "John"
   629  	profile["lastName"] = "Test-Cache"
   630  	profile["email"] = randomEmail()
   631  	profile["login"] = profile["email"]
   632  	u := &okta.CreateUserRequest{
   633  		Credentials: uc,
   634  		Profile:     &profile,
   635  	}
   636  	qp := query.NewQueryParams(query.WithActivate(true))
   637  
   638  	createdUser, _, err := client.User.CreateUser(ctx, *u, qp)
   639  	require.NoError(t, err, "Creating a new user should not error")
   640  
   641  	for i := 0; i < 50; i++ {
   642  		user, resp, err := client.User.GetUser(ctx, profile["email"].(string))
   643  		assert.NoError(t, err, "Should not error when getting user")
   644  		assert.NotNil(t, user, "user should not be nil")
   645  		assert.NotNil(t, resp, "resp should not be nil")
   646  	}
   647  
   648  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   649  	_, err = client.User.DeactivateUser(ctx, createdUser.Id, nil)
   650  	require.NoError(t, err, "Should not error when deactivating")
   651  
   652  	// Delete the user → DELETE /api/v1/users/{{userId}}
   653  	_, err = client.User.DeactivateOrDeleteUser(ctx, createdUser.Id, nil)
   654  	require.NoError(t, err, "Should not error when deleting")
   655  }
   656  
   657  func TestCanPaginateAcrossUsers(t *testing.T) {
   658  	ctx, client, err := tests.NewClient(context.TODO(), okta.WithCache(false))
   659  	require.NoError(t, err)
   660  
   661  	p := &okta.PasswordCredential{
   662  		Value: "Abcd1234",
   663  	}
   664  	uc := &okta.UserCredentials{
   665  		Password: p,
   666  	}
   667  	profile1 := okta.UserProfile{}
   668  	profile1["firstName"] = "John"
   669  	profile1["lastName"] = "page-test"
   670  	profile1["email"] = "john-page-1@example.com"
   671  	profile1["login"] = "SDK_TESTjohn-page-1@example.com"
   672  	u1 := &okta.CreateUserRequest{
   673  		Credentials: uc,
   674  		Profile:     &profile1,
   675  	}
   676  	profile2 := okta.UserProfile{}
   677  	profile2["firstName"] = "John"
   678  	profile2["lastName"] = "page-test"
   679  	profile2["email"] = "john-page-2@example.com"
   680  	profile2["login"] = "SDK_TESTjohn-page-2@example.com"
   681  	u2 := &okta.CreateUserRequest{
   682  		Credentials: uc,
   683  		Profile:     &profile2,
   684  	}
   685  	qp := query.NewQueryParams(query.WithActivate(true))
   686  
   687  	createdUser1, _, err := client.User.CreateUser(ctx, *u1, qp)
   688  	require.NoError(t, err, "Creating a new user should not error")
   689  	createdUser2, _, err := client.User.CreateUser(ctx, *u2, qp)
   690  	require.NoError(t, err, "Creating a new user should not error")
   691  
   692  	query := query.NewQueryParams(query.WithLimit(1))
   693  	user1, resp, err := client.User.ListUsers(ctx, query)
   694  	require.NoError(t, err)
   695  	assert.Equal(t, 1, len(user1), "User1 did not reutrn 1 user")
   696  	user1Profile := *user1[0].Profile
   697  
   698  	hasNext := resp.HasNextPage()
   699  	assert.True(t, hasNext, "Should return true for HasNextPage")
   700  
   701  	var user2 []*okta.User
   702  	_, err = resp.Next(ctx, &user2)
   703  	require.NoError(t, err)
   704  
   705  	assert.Equal(t, 1, len(user2), "User2 did not reutrn 1 user")
   706  	user2Profile := *user2[0].Profile
   707  
   708  	assert.NotEqual(t, user2Profile["email"], user1Profile["email"], "Emails should not be the same")
   709  
   710  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   711  	_, err = client.User.DeactivateUser(ctx, createdUser1.Id, nil)
   712  	require.NoError(t, err, "Should not error when deactivating")
   713  
   714  	// Delete the user → DELETE /api/v1/users/{{userId}}
   715  	_, err = client.User.DeactivateOrDeleteUser(ctx, createdUser1.Id, nil)
   716  	require.NoError(t, err, "Should not error when deleting")
   717  
   718  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   719  	_, err = client.User.DeactivateUser(ctx, createdUser2.Id, nil)
   720  	require.NoError(t, err, "Should not error when deactivating")
   721  
   722  	// Delete the user → DELETE /api/v1/users/{{userId}}
   723  	_, err = client.User.DeactivateOrDeleteUser(ctx, createdUser2.Id, nil)
   724  	require.NoError(t, err, "Should not error when deleting")
   725  }
   726  
   727  func TestListUserSubscriptions(t *testing.T) {
   728  	// FIXME list users is getting an API error due to this documentated limitation:
   729  	//
   730  	// List subscriptions of a User. Only lists subscriptions for current user.
   731  	// An AccessDeniedException message is sent if requests are made from other
   732  	// users.
   733  	//
   734  	// Have tried creating a user and getting the current user: GET /api/v1/users/me
   735  	t.Skip("Need to determine how to set up environment for ListUserSubscriptions")
   736  
   737  	ctx, client, err := tests.NewClient(context.TODO(), okta.WithCache(false))
   738  	require.NoError(t, err)
   739  
   740  	user, _, err := client.User.GetUser(ctx, "me")
   741  	require.NoError(t, err, "Getting the current user should not error")
   742  
   743  	subscriptions, _, err := client.User.ListUserSubscriptions(ctx, user.Id)
   744  	require.NoError(t, err, "Should not error listing user subscriptions")
   745  
   746  	assert.True(t, len(subscriptions) > 0, "User should have subscriptions")
   747  
   748  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   749  	_, err = client.User.DeactivateUser(ctx, user.Id, nil)
   750  	require.NoError(t, err, "Should not error when deactivating")
   751  
   752  	// Delete the user → DELETE /api/v1/users/{{userId}}
   753  	_, err = client.User.DeactivateOrDeleteUser(ctx, user.Id, nil)
   754  	require.NoError(t, err, "Should not error when deleting")
   755  
   756  	// Verify that the user is deleted by calling get on user (Exception thrown with 404 error message) → GET /api/v1/users/{{userId}}
   757  	_, resp, err := client.User.GetUser(ctx, user.Id)
   758  	require.Error(t, err, "User should not exist, but does")
   759  	assert.Equal(t, http.StatusNotFound, resp.StatusCode, "Should not have been able to find user")
   760  }
   761  
   762  func TestGetUserSubscriptionByNotificationType(t *testing.T) {
   763  	// FIXME get user subscriptions by notification type is getting an API error
   764  	// due to this documentated limitation:
   765  	//
   766  	// Get the subscriptions of a User with a specific notification type. Only
   767  	// gets subscriptions for current user. An AccessDeniedException message is
   768  	// sent if requests are made from other users.
   769  	//
   770  	// Have tried creating a user and getting the current user: GET /api/v1/users/me
   771  	t.Skip("Need to determine how to set up environment for GetUserSubscriptionByNotificationType")
   772  
   773  	ctx, client, err := tests.NewClient(context.TODO(), okta.WithCache(false))
   774  	require.NoError(t, err)
   775  
   776  	user, _, err := client.User.GetUser(ctx, "me")
   777  	require.NoError(t, err, "Getting the current user should not error")
   778  
   779  	expectedNotificationType := "OKTA_ANNOUNCEMENT"
   780  	subscription, _, err := client.User.GetUserSubscriptionByNotificationType(ctx, user.Id, expectedNotificationType)
   781  	require.NoError(t, err, "Should not error getting user subscription by notification types")
   782  
   783  	assert.True(t, subscription.NotificationType == "OKTA_ANNOUNCEMENT", "User should have subscription notification type %q, got %q", expectedNotificationType, subscription.NotificationType)
   784  
   785  	// Deactivate the user → POST /api/v1/users/{{userId}}/lifecycle/deactivate
   786  	_, err = client.User.DeactivateUser(ctx, user.Id, nil)
   787  	require.NoError(t, err, "Should not error when deactivating")
   788  
   789  	// Delete the user → DELETE /api/v1/users/{{userId}}
   790  	_, err = client.User.DeactivateOrDeleteUser(ctx, user.Id, nil)
   791  	require.NoError(t, err, "Should not error when deleting")
   792  
   793  	// Verify that the user is deleted by calling get on user (Exception thrown with 404 error message) → GET /api/v1/users/{{userId}}
   794  	_, resp, err := client.User.GetUser(ctx, user.Id)
   795  	require.Error(t, err, "User should not exist, but does")
   796  	assert.Equal(t, http.StatusNotFound, resp.StatusCode, "Should not have been able to find user")
   797  }
   798  

View as plain text