github.com/coincircle/mattermost-server@v4.8.1-0.20180321182714-9d701c704416+incompatible/api4/user_test.go (about)

     1  // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package api4
     5  
     6  import (
     7  	"fmt"
     8  	"net/http"
     9  	"strconv"
    10  	"testing"
    11  	"time"
    12  
    13  	"github.com/mattermost/mattermost-server/model"
    14  	"github.com/mattermost/mattermost-server/store"
    15  	"github.com/mattermost/mattermost-server/utils"
    16  	"github.com/stretchr/testify/assert"
    17  	"github.com/stretchr/testify/require"
    18  )
    19  
    20  func TestCreateUser(t *testing.T) {
    21  	th := Setup().InitBasic().InitSystemAdmin()
    22  	defer th.TearDown()
    23  	Client := th.Client
    24  	AdminClient := th.SystemAdminClient
    25  
    26  	user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
    27  
    28  	ruser, resp := Client.CreateUser(&user)
    29  	CheckNoError(t, resp)
    30  	CheckCreatedStatus(t, resp)
    31  
    32  	Client.Login(user.Email, user.Password)
    33  
    34  	if ruser.Nickname != user.Nickname {
    35  		t.Fatal("nickname didn't match")
    36  	}
    37  
    38  	if ruser.Roles != model.SYSTEM_USER_ROLE_ID {
    39  		t.Log(ruser.Roles)
    40  		t.Fatal("did not clear roles")
    41  	}
    42  
    43  	CheckUserSanitization(t, ruser)
    44  
    45  	_, resp = Client.CreateUser(ruser)
    46  	CheckBadRequestStatus(t, resp)
    47  
    48  	ruser.Id = ""
    49  	ruser.Username = GenerateTestUsername()
    50  	ruser.Password = "passwd1"
    51  	_, resp = Client.CreateUser(ruser)
    52  	CheckErrorMessage(t, resp, "store.sql_user.save.email_exists.app_error")
    53  	CheckBadRequestStatus(t, resp)
    54  
    55  	ruser.Email = th.GenerateTestEmail()
    56  	ruser.Username = user.Username
    57  	_, resp = Client.CreateUser(ruser)
    58  	CheckErrorMessage(t, resp, "store.sql_user.save.username_exists.app_error")
    59  	CheckBadRequestStatus(t, resp)
    60  
    61  	ruser.Email = ""
    62  	_, resp = Client.CreateUser(ruser)
    63  	CheckErrorMessage(t, resp, "model.user.is_valid.email.app_error")
    64  	CheckBadRequestStatus(t, resp)
    65  
    66  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = false })
    67  	th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = false })
    68  
    69  	user2 := &model.User{Email: th.GenerateTestEmail(), Password: "Password1", Username: GenerateTestUsername()}
    70  	_, resp = AdminClient.CreateUser(user2)
    71  	CheckNoError(t, resp)
    72  
    73  	if r, err := Client.DoApiPost("/users", "garbage"); err == nil {
    74  		t.Fatal("should have errored")
    75  	} else {
    76  		if r.StatusCode != http.StatusBadRequest {
    77  			t.Log("actual: " + strconv.Itoa(r.StatusCode))
    78  			t.Log("expected: " + strconv.Itoa(http.StatusBadRequest))
    79  			t.Fatal("wrong status code")
    80  		}
    81  	}
    82  }
    83  
    84  func TestCreateUserWithHash(t *testing.T) {
    85  	th := Setup().InitBasic().InitSystemAdmin()
    86  	defer th.TearDown()
    87  	Client := th.Client
    88  
    89  	t.Run("CreateWithHashHappyPath", func(t *testing.T) {
    90  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
    91  		props := make(map[string]string)
    92  		props["email"] = user.Email
    93  		props["id"] = th.BasicTeam.Id
    94  		props["display_name"] = th.BasicTeam.DisplayName
    95  		props["name"] = th.BasicTeam.Name
    96  		props["time"] = fmt.Sprintf("%v", model.GetMillis())
    97  		data := model.MapToJson(props)
    98  		hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt))
    99  
   100  		ruser, resp := Client.CreateUserWithHash(&user, hash, data)
   101  		CheckNoError(t, resp)
   102  		CheckCreatedStatus(t, resp)
   103  
   104  		Client.Login(user.Email, user.Password)
   105  		if ruser.Nickname != user.Nickname {
   106  			t.Fatal("nickname didn't match")
   107  		}
   108  		if ruser.Roles != model.SYSTEM_USER_ROLE_ID {
   109  			t.Log(ruser.Roles)
   110  			t.Fatal("did not clear roles")
   111  		}
   112  		CheckUserSanitization(t, ruser)
   113  	})
   114  
   115  	t.Run("NoHashAndNoData", func(t *testing.T) {
   116  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   117  		props := make(map[string]string)
   118  		props["email"] = user.Email
   119  		props["id"] = th.BasicTeam.Id
   120  		props["display_name"] = th.BasicTeam.DisplayName
   121  		props["name"] = th.BasicTeam.Name
   122  		props["time"] = fmt.Sprintf("%v", model.GetMillis())
   123  		data := model.MapToJson(props)
   124  		hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt))
   125  
   126  		_, resp := Client.CreateUserWithHash(&user, "", data)
   127  		CheckBadRequestStatus(t, resp)
   128  		CheckErrorMessage(t, resp, "api.user.create_user.missing_hash_or_data.app_error")
   129  
   130  		_, resp = Client.CreateUserWithHash(&user, hash, "")
   131  		CheckBadRequestStatus(t, resp)
   132  		CheckErrorMessage(t, resp, "api.user.create_user.missing_hash_or_data.app_error")
   133  	})
   134  
   135  	t.Run("HashExpired", func(t *testing.T) {
   136  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   137  		timeNow := time.Now()
   138  		past49Hours := timeNow.Add(-49*time.Hour).UnixNano() / int64(time.Millisecond)
   139  
   140  		props := make(map[string]string)
   141  		props["email"] = user.Email
   142  		props["id"] = th.BasicTeam.Id
   143  		props["display_name"] = th.BasicTeam.DisplayName
   144  		props["name"] = th.BasicTeam.Name
   145  		props["time"] = fmt.Sprintf("%v", past49Hours)
   146  		data := model.MapToJson(props)
   147  		hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt))
   148  
   149  		_, resp := Client.CreateUserWithHash(&user, hash, data)
   150  		CheckInternalErrorStatus(t, resp)
   151  		CheckErrorMessage(t, resp, "api.user.create_user.signup_link_expired.app_error")
   152  	})
   153  
   154  	t.Run("WrongHash", func(t *testing.T) {
   155  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   156  		props := make(map[string]string)
   157  		props["email"] = user.Email
   158  		props["id"] = th.BasicTeam.Id
   159  		props["display_name"] = th.BasicTeam.DisplayName
   160  		props["name"] = th.BasicTeam.Name
   161  		props["time"] = fmt.Sprintf("%v", model.GetMillis())
   162  		data := model.MapToJson(props)
   163  		hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, "WrongHash"))
   164  
   165  		_, resp := Client.CreateUserWithHash(&user, hash, data)
   166  		CheckInternalErrorStatus(t, resp)
   167  		CheckErrorMessage(t, resp, "api.user.create_user.signup_link_invalid.app_error")
   168  	})
   169  
   170  	t.Run("EnableUserCreationDisable", func(t *testing.T) {
   171  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   172  
   173  		props := make(map[string]string)
   174  		props["email"] = user.Email
   175  		props["id"] = th.BasicTeam.Id
   176  		props["display_name"] = th.BasicTeam.DisplayName
   177  		props["name"] = th.BasicTeam.Name
   178  		props["time"] = fmt.Sprintf("%v", model.GetMillis())
   179  		data := model.MapToJson(props)
   180  		hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt))
   181  
   182  		th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = false })
   183  
   184  		_, resp := Client.CreateUserWithHash(&user, hash, data)
   185  		CheckNotImplementedStatus(t, resp)
   186  		CheckErrorMessage(t, resp, "api.user.create_user.signup_email_disabled.app_error")
   187  
   188  		th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = true })
   189  	})
   190  
   191  	t.Run("EnableOpenServerDisable", func(t *testing.T) {
   192  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   193  
   194  		props := make(map[string]string)
   195  		props["email"] = user.Email
   196  		props["id"] = th.BasicTeam.Id
   197  		props["display_name"] = th.BasicTeam.DisplayName
   198  		props["name"] = th.BasicTeam.Name
   199  		props["time"] = fmt.Sprintf("%v", model.GetMillis())
   200  		data := model.MapToJson(props)
   201  		hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt))
   202  
   203  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = false })
   204  
   205  		ruser, resp := Client.CreateUserWithHash(&user, hash, data)
   206  		CheckNoError(t, resp)
   207  		CheckCreatedStatus(t, resp)
   208  
   209  		Client.Login(user.Email, user.Password)
   210  		if ruser.Nickname != user.Nickname {
   211  			t.Fatal("nickname didn't match")
   212  		}
   213  		if ruser.Roles != model.SYSTEM_USER_ROLE_ID {
   214  			t.Log(ruser.Roles)
   215  			t.Fatal("did not clear roles")
   216  		}
   217  		CheckUserSanitization(t, ruser)
   218  	})
   219  }
   220  
   221  func TestCreateUserWithInviteId(t *testing.T) {
   222  	th := Setup().InitBasic().InitSystemAdmin()
   223  	defer th.TearDown()
   224  	Client := th.Client
   225  	AdminClient := th.SystemAdminClient
   226  
   227  	t.Run("CreateWithInviteIdHappyPath", func(t *testing.T) {
   228  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   229  
   230  		inviteId := th.BasicTeam.InviteId
   231  
   232  		ruser, resp := Client.CreateUserWithInviteId(&user, inviteId)
   233  		CheckNoError(t, resp)
   234  		CheckCreatedStatus(t, resp)
   235  
   236  		Client.Login(user.Email, user.Password)
   237  		if ruser.Nickname != user.Nickname {
   238  			t.Fatal("nickname didn't match")
   239  		}
   240  		if ruser.Roles != model.SYSTEM_USER_ROLE_ID {
   241  			t.Log(ruser.Roles)
   242  			t.Fatal("did not clear roles")
   243  		}
   244  		CheckUserSanitization(t, ruser)
   245  	})
   246  
   247  	t.Run("WrongInviteId", func(t *testing.T) {
   248  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   249  
   250  		inviteId := model.NewId()
   251  
   252  		_, resp := Client.CreateUserWithInviteId(&user, inviteId)
   253  		CheckNotFoundStatus(t, resp)
   254  		CheckErrorMessage(t, resp, "store.sql_team.get_by_invite_id.find.app_error")
   255  	})
   256  
   257  	t.Run("NoInviteId", func(t *testing.T) {
   258  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   259  
   260  		_, resp := Client.CreateUserWithInviteId(&user, "")
   261  		CheckBadRequestStatus(t, resp)
   262  		CheckErrorMessage(t, resp, "api.user.create_user.missing_invite_id.app_error")
   263  	})
   264  
   265  	t.Run("ExpiredInviteId", func(t *testing.T) {
   266  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   267  
   268  		inviteId := th.BasicTeam.InviteId
   269  
   270  		th.BasicTeam.InviteId = model.NewId()
   271  		_, resp := AdminClient.UpdateTeam(th.BasicTeam)
   272  		CheckNoError(t, resp)
   273  
   274  		_, resp = Client.CreateUserWithInviteId(&user, inviteId)
   275  		CheckNotFoundStatus(t, resp)
   276  		CheckErrorMessage(t, resp, "store.sql_team.get_by_invite_id.find.app_error")
   277  	})
   278  
   279  	t.Run("EnableUserCreationDisable", func(t *testing.T) {
   280  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   281  
   282  		th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = false })
   283  
   284  		inviteId := th.BasicTeam.InviteId
   285  
   286  		_, resp := Client.CreateUserWithInviteId(&user, inviteId)
   287  		CheckNotImplementedStatus(t, resp)
   288  		CheckErrorMessage(t, resp, "api.user.create_user.signup_email_disabled.app_error")
   289  
   290  		th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = true })
   291  	})
   292  
   293  	t.Run("EnableOpenServerDisable", func(t *testing.T) {
   294  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   295  
   296  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = false })
   297  
   298  		inviteId := th.BasicTeam.InviteId
   299  
   300  		ruser, resp := Client.CreateUserWithInviteId(&user, inviteId)
   301  		CheckNoError(t, resp)
   302  		CheckCreatedStatus(t, resp)
   303  
   304  		Client.Login(user.Email, user.Password)
   305  		if ruser.Nickname != user.Nickname {
   306  			t.Fatal("nickname didn't match")
   307  		}
   308  		if ruser.Roles != model.SYSTEM_USER_ROLE_ID {
   309  			t.Log(ruser.Roles)
   310  			t.Fatal("did not clear roles")
   311  		}
   312  		CheckUserSanitization(t, ruser)
   313  	})
   314  
   315  }
   316  
   317  func TestGetMe(t *testing.T) {
   318  	th := Setup().InitBasic()
   319  	defer th.TearDown()
   320  	Client := th.Client
   321  
   322  	ruser, resp := Client.GetMe("")
   323  	CheckNoError(t, resp)
   324  
   325  	if ruser.Id != th.BasicUser.Id {
   326  		t.Fatal("wrong user")
   327  	}
   328  
   329  	Client.Logout()
   330  	_, resp = Client.GetMe("")
   331  	CheckUnauthorizedStatus(t, resp)
   332  }
   333  
   334  func TestGetUser(t *testing.T) {
   335  	th := Setup().InitBasic().InitSystemAdmin()
   336  	defer th.TearDown()
   337  	Client := th.Client
   338  
   339  	user := th.CreateUser()
   340  	user.Props = map[string]string{"testpropkey": "testpropvalue"}
   341  
   342  	th.App.UpdateUser(user, false)
   343  
   344  	ruser, resp := Client.GetUser(user.Id, "")
   345  	CheckNoError(t, resp)
   346  	CheckUserSanitization(t, ruser)
   347  
   348  	if ruser.Email != user.Email {
   349  		t.Fatal("emails did not match")
   350  	}
   351  
   352  	assert.NotNil(t, ruser.Props)
   353  	assert.Equal(t, ruser.Props["testpropkey"], "testpropvalue")
   354  
   355  	ruser, resp = Client.GetUser(user.Id, resp.Etag)
   356  	CheckEtag(t, ruser, resp)
   357  
   358  	_, resp = Client.GetUser("junk", "")
   359  	CheckBadRequestStatus(t, resp)
   360  
   361  	_, resp = Client.GetUser(model.NewId(), "")
   362  	CheckNotFoundStatus(t, resp)
   363  
   364  	// Check against privacy config settings
   365  	th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false })
   366  	th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false })
   367  
   368  	ruser, resp = Client.GetUser(user.Id, "")
   369  	CheckNoError(t, resp)
   370  
   371  	if ruser.Email != "" {
   372  		t.Fatal("email should be blank")
   373  	}
   374  	if ruser.FirstName != "" {
   375  		t.Fatal("first name should be blank")
   376  	}
   377  	if ruser.LastName != "" {
   378  		t.Fatal("last name should be blank")
   379  	}
   380  
   381  	Client.Logout()
   382  	_, resp = Client.GetUser(user.Id, "")
   383  	CheckUnauthorizedStatus(t, resp)
   384  
   385  	// System admins should ignore privacy settings
   386  	ruser, resp = th.SystemAdminClient.GetUser(user.Id, resp.Etag)
   387  	if ruser.Email == "" {
   388  		t.Fatal("email should not be blank")
   389  	}
   390  	if ruser.FirstName == "" {
   391  		t.Fatal("first name should not be blank")
   392  	}
   393  	if ruser.LastName == "" {
   394  		t.Fatal("last name should not be blank")
   395  	}
   396  }
   397  
   398  func TestGetUserByUsername(t *testing.T) {
   399  	th := Setup().InitBasic().InitSystemAdmin()
   400  	defer th.TearDown()
   401  	Client := th.Client
   402  
   403  	user := th.BasicUser
   404  
   405  	ruser, resp := Client.GetUserByUsername(user.Username, "")
   406  	CheckNoError(t, resp)
   407  	CheckUserSanitization(t, ruser)
   408  
   409  	if ruser.Email != user.Email {
   410  		t.Fatal("emails did not match")
   411  	}
   412  
   413  	ruser, resp = Client.GetUserByUsername(user.Username, resp.Etag)
   414  	CheckEtag(t, ruser, resp)
   415  
   416  	_, resp = Client.GetUserByUsername(GenerateTestUsername(), "")
   417  	CheckNotFoundStatus(t, resp)
   418  
   419  	// Check against privacy config settings
   420  	th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false })
   421  	th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false })
   422  
   423  	ruser, resp = Client.GetUserByUsername(user.Username, "")
   424  	CheckNoError(t, resp)
   425  
   426  	if ruser.Email != "" {
   427  		t.Fatal("email should be blank")
   428  	}
   429  	if ruser.FirstName != "" {
   430  		t.Fatal("first name should be blank")
   431  	}
   432  	if ruser.LastName != "" {
   433  		t.Fatal("last name should be blank")
   434  	}
   435  
   436  	Client.Logout()
   437  	_, resp = Client.GetUserByUsername(user.Username, "")
   438  	CheckUnauthorizedStatus(t, resp)
   439  
   440  	// System admins should ignore privacy settings
   441  	ruser, resp = th.SystemAdminClient.GetUserByUsername(user.Username, resp.Etag)
   442  	if ruser.Email == "" {
   443  		t.Fatal("email should not be blank")
   444  	}
   445  	if ruser.FirstName == "" {
   446  		t.Fatal("first name should not be blank")
   447  	}
   448  	if ruser.LastName == "" {
   449  		t.Fatal("last name should not be blank")
   450  	}
   451  }
   452  
   453  func TestGetUserByEmail(t *testing.T) {
   454  	th := Setup().InitBasic().InitSystemAdmin()
   455  	defer th.TearDown()
   456  	Client := th.Client
   457  
   458  	user := th.CreateUser()
   459  
   460  	ruser, resp := Client.GetUserByEmail(user.Email, "")
   461  	CheckNoError(t, resp)
   462  	CheckUserSanitization(t, ruser)
   463  
   464  	if ruser.Email != user.Email {
   465  		t.Fatal("emails did not match")
   466  	}
   467  
   468  	ruser, resp = Client.GetUserByEmail(user.Email, resp.Etag)
   469  	CheckEtag(t, ruser, resp)
   470  
   471  	_, resp = Client.GetUserByEmail(GenerateTestUsername(), "")
   472  	CheckBadRequestStatus(t, resp)
   473  
   474  	_, resp = Client.GetUserByEmail(th.GenerateTestEmail(), "")
   475  	CheckNotFoundStatus(t, resp)
   476  
   477  	// Check against privacy config settings
   478  	th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false })
   479  	th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false })
   480  
   481  	ruser, resp = Client.GetUserByEmail(user.Email, "")
   482  	CheckNoError(t, resp)
   483  
   484  	if ruser.Email != "" {
   485  		t.Fatal("email should be blank")
   486  	}
   487  	if ruser.FirstName != "" {
   488  		t.Fatal("first name should be blank")
   489  	}
   490  	if ruser.LastName != "" {
   491  		t.Fatal("last name should be blank")
   492  	}
   493  
   494  	Client.Logout()
   495  	_, resp = Client.GetUserByEmail(user.Email, "")
   496  	CheckUnauthorizedStatus(t, resp)
   497  
   498  	// System admins should ignore privacy settings
   499  	ruser, resp = th.SystemAdminClient.GetUserByEmail(user.Email, resp.Etag)
   500  	if ruser.Email == "" {
   501  		t.Fatal("email should not be blank")
   502  	}
   503  	if ruser.FirstName == "" {
   504  		t.Fatal("first name should not be blank")
   505  	}
   506  	if ruser.LastName == "" {
   507  		t.Fatal("last name should not be blank")
   508  	}
   509  }
   510  
   511  func TestSearchUsers(t *testing.T) {
   512  	th := Setup().InitBasic().InitSystemAdmin()
   513  	defer th.TearDown()
   514  	Client := th.Client
   515  
   516  	search := &model.UserSearch{Term: th.BasicUser.Username}
   517  
   518  	users, resp := Client.SearchUsers(search)
   519  	CheckNoError(t, resp)
   520  
   521  	if !findUserInList(th.BasicUser.Id, users) {
   522  		t.Fatal("should have found user")
   523  	}
   524  
   525  	_, err := th.App.UpdateNonSSOUserActive(th.BasicUser2.Id, false)
   526  	if err != nil {
   527  		t.Fatal(err)
   528  	}
   529  
   530  	search.Term = th.BasicUser2.Username
   531  	search.AllowInactive = false
   532  
   533  	users, resp = Client.SearchUsers(search)
   534  	CheckNoError(t, resp)
   535  
   536  	if findUserInList(th.BasicUser2.Id, users) {
   537  		t.Fatal("should not have found user")
   538  	}
   539  
   540  	search.AllowInactive = true
   541  
   542  	users, resp = Client.SearchUsers(search)
   543  	CheckNoError(t, resp)
   544  
   545  	if !findUserInList(th.BasicUser2.Id, users) {
   546  		t.Fatal("should have found user")
   547  	}
   548  
   549  	search.Term = th.BasicUser.Username
   550  	search.AllowInactive = false
   551  	search.TeamId = th.BasicTeam.Id
   552  
   553  	users, resp = Client.SearchUsers(search)
   554  	CheckNoError(t, resp)
   555  
   556  	if !findUserInList(th.BasicUser.Id, users) {
   557  		t.Fatal("should have found user")
   558  	}
   559  
   560  	search.NotInChannelId = th.BasicChannel.Id
   561  
   562  	users, resp = Client.SearchUsers(search)
   563  	CheckNoError(t, resp)
   564  
   565  	if findUserInList(th.BasicUser.Id, users) {
   566  		t.Fatal("should not have found user")
   567  	}
   568  
   569  	search.TeamId = ""
   570  	search.NotInChannelId = ""
   571  	search.InChannelId = th.BasicChannel.Id
   572  
   573  	users, resp = Client.SearchUsers(search)
   574  	CheckNoError(t, resp)
   575  
   576  	if !findUserInList(th.BasicUser.Id, users) {
   577  		t.Fatal("should have found user")
   578  	}
   579  
   580  	search.InChannelId = ""
   581  	search.NotInChannelId = th.BasicChannel.Id
   582  	_, resp = Client.SearchUsers(search)
   583  	CheckBadRequestStatus(t, resp)
   584  
   585  	search.NotInChannelId = model.NewId()
   586  	search.TeamId = model.NewId()
   587  	_, resp = Client.SearchUsers(search)
   588  	CheckForbiddenStatus(t, resp)
   589  
   590  	search.NotInChannelId = ""
   591  	search.TeamId = model.NewId()
   592  	_, resp = Client.SearchUsers(search)
   593  	CheckForbiddenStatus(t, resp)
   594  
   595  	search.InChannelId = model.NewId()
   596  	search.TeamId = ""
   597  	_, resp = Client.SearchUsers(search)
   598  	CheckForbiddenStatus(t, resp)
   599  
   600  	// Test search for users not in any team
   601  	search.TeamId = ""
   602  	search.NotInChannelId = ""
   603  	search.InChannelId = ""
   604  	search.NotInTeamId = th.BasicTeam.Id
   605  
   606  	users, resp = Client.SearchUsers(search)
   607  	CheckNoError(t, resp)
   608  
   609  	if findUserInList(th.BasicUser.Id, users) {
   610  		t.Fatal("should not have found user")
   611  	}
   612  
   613  	oddUser := th.CreateUser()
   614  	search.Term = oddUser.Username
   615  
   616  	users, resp = Client.SearchUsers(search)
   617  	CheckNoError(t, resp)
   618  
   619  	if !findUserInList(oddUser.Id, users) {
   620  		t.Fatal("should have found user")
   621  	}
   622  
   623  	_, resp = th.SystemAdminClient.AddTeamMember(th.BasicTeam.Id, oddUser.Id)
   624  	CheckNoError(t, resp)
   625  
   626  	users, resp = Client.SearchUsers(search)
   627  	CheckNoError(t, resp)
   628  
   629  	if findUserInList(oddUser.Id, users) {
   630  		t.Fatal("should not have found user")
   631  	}
   632  
   633  	search.NotInTeamId = model.NewId()
   634  	_, resp = Client.SearchUsers(search)
   635  	CheckForbiddenStatus(t, resp)
   636  
   637  	search.Term = th.BasicUser.Username
   638  
   639  	th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false })
   640  	th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false })
   641  
   642  	_, err = th.App.UpdateNonSSOUserActive(th.BasicUser2.Id, true)
   643  	if err != nil {
   644  		t.Fatal(err)
   645  	}
   646  
   647  	search.InChannelId = ""
   648  	search.NotInTeamId = ""
   649  	search.Term = th.BasicUser2.Email
   650  	users, resp = Client.SearchUsers(search)
   651  	CheckNoError(t, resp)
   652  
   653  	if findUserInList(th.BasicUser2.Id, users) {
   654  		t.Fatal("should not have found user")
   655  	}
   656  
   657  	search.Term = th.BasicUser2.FirstName
   658  	users, resp = Client.SearchUsers(search)
   659  	CheckNoError(t, resp)
   660  
   661  	if findUserInList(th.BasicUser2.Id, users) {
   662  		t.Fatal("should not have found user")
   663  	}
   664  
   665  	search.Term = th.BasicUser2.LastName
   666  	users, resp = Client.SearchUsers(search)
   667  	CheckNoError(t, resp)
   668  
   669  	if findUserInList(th.BasicUser2.Id, users) {
   670  		t.Fatal("should not have found user")
   671  	}
   672  
   673  	search.Term = th.BasicUser.FirstName
   674  	search.InChannelId = th.BasicChannel.Id
   675  	search.NotInChannelId = th.BasicChannel.Id
   676  	search.TeamId = th.BasicTeam.Id
   677  	users, resp = th.SystemAdminClient.SearchUsers(search)
   678  	CheckNoError(t, resp)
   679  
   680  	if !findUserInList(th.BasicUser.Id, users) {
   681  		t.Fatal("should have found user")
   682  	}
   683  }
   684  
   685  func findUserInList(id string, users []*model.User) bool {
   686  	for _, user := range users {
   687  		if user.Id == id {
   688  			return true
   689  		}
   690  	}
   691  	return false
   692  }
   693  
   694  func TestAutocompleteUsers(t *testing.T) {
   695  	th := Setup().InitBasic().InitSystemAdmin()
   696  	defer th.TearDown()
   697  	Client := th.Client
   698  	teamId := th.BasicTeam.Id
   699  	channelId := th.BasicChannel.Id
   700  	username := th.BasicUser.Username
   701  
   702  	rusers, resp := Client.AutocompleteUsersInChannel(teamId, channelId, username, "")
   703  	CheckNoError(t, resp)
   704  
   705  	if len(rusers.Users) != 1 {
   706  		t.Fatal("should have returned 1 user")
   707  	}
   708  
   709  	rusers, resp = Client.AutocompleteUsersInChannel(teamId, channelId, "amazonses", "")
   710  	CheckNoError(t, resp)
   711  	if len(rusers.Users) != 0 {
   712  		t.Fatal("should have returned 0 users")
   713  	}
   714  
   715  	rusers, resp = Client.AutocompleteUsersInChannel(teamId, channelId, "", "")
   716  	CheckNoError(t, resp)
   717  	if len(rusers.Users) < 2 {
   718  		t.Fatal("should have many users")
   719  	}
   720  
   721  	rusers, resp = Client.AutocompleteUsersInChannel("", channelId, "", "")
   722  	CheckNoError(t, resp)
   723  	if len(rusers.Users) < 2 {
   724  		t.Fatal("should have many users")
   725  	}
   726  
   727  	rusers, resp = Client.AutocompleteUsersInTeam(teamId, username, "")
   728  	CheckNoError(t, resp)
   729  
   730  	if len(rusers.Users) != 1 {
   731  		t.Fatal("should have returned 1 user")
   732  	}
   733  
   734  	rusers, resp = Client.AutocompleteUsers(username, "")
   735  	CheckNoError(t, resp)
   736  
   737  	if len(rusers.Users) != 1 {
   738  		t.Fatal("should have returned 1 users")
   739  	}
   740  
   741  	rusers, resp = Client.AutocompleteUsers("", "")
   742  	CheckNoError(t, resp)
   743  
   744  	if len(rusers.Users) < 2 {
   745  		t.Fatal("should have returned many users")
   746  	}
   747  
   748  	rusers, resp = Client.AutocompleteUsersInTeam(teamId, "amazonses", "")
   749  	CheckNoError(t, resp)
   750  	if len(rusers.Users) != 0 {
   751  		t.Fatal("should have returned 0 users")
   752  	}
   753  
   754  	rusers, resp = Client.AutocompleteUsersInTeam(teamId, "", "")
   755  	CheckNoError(t, resp)
   756  	if len(rusers.Users) < 2 {
   757  		t.Fatal("should have many users")
   758  	}
   759  
   760  	Client.Logout()
   761  	_, resp = Client.AutocompleteUsersInChannel(teamId, channelId, username, "")
   762  	CheckUnauthorizedStatus(t, resp)
   763  
   764  	_, resp = Client.AutocompleteUsersInTeam(teamId, username, "")
   765  	CheckUnauthorizedStatus(t, resp)
   766  
   767  	_, resp = Client.AutocompleteUsers(username, "")
   768  	CheckUnauthorizedStatus(t, resp)
   769  
   770  	user := th.CreateUser()
   771  	Client.Login(user.Email, user.Password)
   772  	_, resp = Client.AutocompleteUsersInChannel(teamId, channelId, username, "")
   773  	CheckForbiddenStatus(t, resp)
   774  
   775  	_, resp = Client.AutocompleteUsersInTeam(teamId, username, "")
   776  	CheckForbiddenStatus(t, resp)
   777  
   778  	_, resp = Client.AutocompleteUsers(username, "")
   779  	CheckNoError(t, resp)
   780  
   781  	_, resp = th.SystemAdminClient.AutocompleteUsersInChannel(teamId, channelId, username, "")
   782  	CheckNoError(t, resp)
   783  
   784  	_, resp = th.SystemAdminClient.AutocompleteUsersInTeam(teamId, username, "")
   785  	CheckNoError(t, resp)
   786  
   787  	_, resp = th.SystemAdminClient.AutocompleteUsers(username, "")
   788  	CheckNoError(t, resp)
   789  
   790  	// Check against privacy config settings
   791  	th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false })
   792  
   793  	th.LoginBasic()
   794  
   795  	rusers, resp = Client.AutocompleteUsers(username, "")
   796  	CheckNoError(t, resp)
   797  
   798  	if rusers.Users[0].FirstName != "" || rusers.Users[0].LastName != "" {
   799  		t.Fatal("should not show first/last name")
   800  	}
   801  
   802  	rusers, resp = Client.AutocompleteUsersInChannel(teamId, channelId, username, "")
   803  	CheckNoError(t, resp)
   804  
   805  	if rusers.Users[0].FirstName != "" || rusers.Users[0].LastName != "" {
   806  		t.Fatal("should not show first/last name")
   807  	}
   808  
   809  	rusers, resp = Client.AutocompleteUsersInTeam(teamId, username, "")
   810  	CheckNoError(t, resp)
   811  
   812  	if rusers.Users[0].FirstName != "" || rusers.Users[0].LastName != "" {
   813  		t.Fatal("should not show first/last name")
   814  	}
   815  }
   816  
   817  func TestGetProfileImage(t *testing.T) {
   818  	th := Setup().InitBasic().InitSystemAdmin()
   819  	defer th.TearDown()
   820  	Client := th.Client
   821  	user := th.BasicUser
   822  
   823  	data, resp := Client.GetProfileImage(user.Id, "")
   824  	CheckNoError(t, resp)
   825  	if len(data) == 0 {
   826  		t.Fatal("Should not be empty")
   827  	}
   828  
   829  	_, resp = Client.GetProfileImage(user.Id, resp.Etag)
   830  	if resp.StatusCode == http.StatusNotModified {
   831  		t.Fatal("Shouldn't have hit etag")
   832  	}
   833  
   834  	_, resp = Client.GetProfileImage("junk", "")
   835  	CheckBadRequestStatus(t, resp)
   836  
   837  	Client.Logout()
   838  	_, resp = Client.GetProfileImage(user.Id, "")
   839  	CheckUnauthorizedStatus(t, resp)
   840  
   841  	_, resp = th.SystemAdminClient.GetProfileImage(user.Id, "")
   842  	CheckNoError(t, resp)
   843  
   844  	info := &model.FileInfo{Path: "/users/" + user.Id + "/profile.png"}
   845  	if err := th.cleanupTestFile(info); err != nil {
   846  		t.Fatal(err)
   847  	}
   848  }
   849  
   850  func TestGetUsersByIds(t *testing.T) {
   851  	th := Setup().InitBasic()
   852  	defer th.TearDown()
   853  
   854  	Client := th.Client
   855  
   856  	users, resp := Client.GetUsersByIds([]string{th.BasicUser.Id})
   857  	CheckNoError(t, resp)
   858  
   859  	if users[0].Id != th.BasicUser.Id {
   860  		t.Fatal("returned wrong user")
   861  	}
   862  	CheckUserSanitization(t, users[0])
   863  
   864  	_, resp = Client.GetUsersByIds([]string{})
   865  	CheckBadRequestStatus(t, resp)
   866  
   867  	users, resp = Client.GetUsersByIds([]string{"junk"})
   868  	CheckNoError(t, resp)
   869  	if len(users) > 0 {
   870  		t.Fatal("no users should be returned")
   871  	}
   872  
   873  	users, resp = Client.GetUsersByIds([]string{"junk", th.BasicUser.Id})
   874  	CheckNoError(t, resp)
   875  	if len(users) != 1 {
   876  		t.Fatal("1 user should be returned")
   877  	}
   878  
   879  	Client.Logout()
   880  	_, resp = Client.GetUsersByIds([]string{th.BasicUser.Id})
   881  	CheckUnauthorizedStatus(t, resp)
   882  }
   883  
   884  func TestGetUsersByUsernames(t *testing.T) {
   885  	th := Setup().InitBasic()
   886  	defer th.TearDown()
   887  
   888  	Client := th.Client
   889  
   890  	users, resp := Client.GetUsersByUsernames([]string{th.BasicUser.Username})
   891  	CheckNoError(t, resp)
   892  
   893  	if users[0].Id != th.BasicUser.Id {
   894  		t.Fatal("returned wrong user")
   895  	}
   896  	CheckUserSanitization(t, users[0])
   897  
   898  	_, resp = Client.GetUsersByIds([]string{})
   899  	CheckBadRequestStatus(t, resp)
   900  
   901  	users, resp = Client.GetUsersByUsernames([]string{"junk"})
   902  	CheckNoError(t, resp)
   903  	if len(users) > 0 {
   904  		t.Fatal("no users should be returned")
   905  	}
   906  
   907  	users, resp = Client.GetUsersByUsernames([]string{"junk", th.BasicUser.Username})
   908  	CheckNoError(t, resp)
   909  	if len(users) != 1 {
   910  		t.Fatal("1 user should be returned")
   911  	}
   912  
   913  	Client.Logout()
   914  	_, resp = Client.GetUsersByUsernames([]string{th.BasicUser.Username})
   915  	CheckUnauthorizedStatus(t, resp)
   916  }
   917  
   918  func TestUpdateUser(t *testing.T) {
   919  	th := Setup().InitBasic().InitSystemAdmin()
   920  	defer th.TearDown()
   921  	Client := th.Client
   922  
   923  	user := th.CreateUser()
   924  	Client.Login(user.Email, user.Password)
   925  
   926  	user.Nickname = "Joram Wilander"
   927  	user.Roles = model.SYSTEM_ADMIN_ROLE_ID
   928  	user.LastPasswordUpdate = 123
   929  
   930  	ruser, resp := Client.UpdateUser(user)
   931  	CheckNoError(t, resp)
   932  	CheckUserSanitization(t, ruser)
   933  
   934  	if ruser.Nickname != "Joram Wilander" {
   935  		t.Fatal("Nickname did not update properly")
   936  	}
   937  	if ruser.Roles != model.SYSTEM_USER_ROLE_ID {
   938  		t.Fatal("Roles should not have updated")
   939  	}
   940  	if ruser.LastPasswordUpdate == 123 {
   941  		t.Fatal("LastPasswordUpdate should not have updated")
   942  	}
   943  
   944  	ruser.Id = "junk"
   945  	_, resp = Client.UpdateUser(ruser)
   946  	CheckBadRequestStatus(t, resp)
   947  
   948  	ruser.Id = model.NewId()
   949  	_, resp = Client.UpdateUser(ruser)
   950  	CheckForbiddenStatus(t, resp)
   951  
   952  	if r, err := Client.DoApiPut("/users/"+ruser.Id, "garbage"); err == nil {
   953  		t.Fatal("should have errored")
   954  	} else {
   955  		if r.StatusCode != http.StatusBadRequest {
   956  			t.Log("actual: " + strconv.Itoa(r.StatusCode))
   957  			t.Log("expected: " + strconv.Itoa(http.StatusBadRequest))
   958  			t.Fatal("wrong status code")
   959  		}
   960  	}
   961  
   962  	session, _ := th.App.GetSession(Client.AuthToken)
   963  	session.IsOAuth = true
   964  	th.App.AddSessionToCache(session)
   965  
   966  	ruser.Id = user.Id
   967  	ruser.Email = th.GenerateTestEmail()
   968  	_, resp = Client.UpdateUser(ruser)
   969  	CheckForbiddenStatus(t, resp)
   970  
   971  	Client.Logout()
   972  	_, resp = Client.UpdateUser(user)
   973  	CheckUnauthorizedStatus(t, resp)
   974  
   975  	th.LoginBasic()
   976  	_, resp = Client.UpdateUser(user)
   977  	CheckForbiddenStatus(t, resp)
   978  
   979  	_, resp = th.SystemAdminClient.UpdateUser(user)
   980  	CheckNoError(t, resp)
   981  }
   982  
   983  func TestPatchUser(t *testing.T) {
   984  	th := Setup().InitBasic().InitSystemAdmin()
   985  	defer th.TearDown()
   986  	Client := th.Client
   987  
   988  	user := th.CreateUser()
   989  	Client.Login(user.Email, user.Password)
   990  
   991  	patch := &model.UserPatch{}
   992  
   993  	patch.Nickname = model.NewString("Joram Wilander")
   994  	patch.FirstName = model.NewString("Joram")
   995  	patch.LastName = model.NewString("Wilander")
   996  	patch.Position = new(string)
   997  	patch.NotifyProps = model.StringMap{}
   998  	patch.NotifyProps["comment"] = "somethingrandom"
   999  
  1000  	ruser, resp := Client.PatchUser(user.Id, patch)
  1001  	CheckNoError(t, resp)
  1002  	CheckUserSanitization(t, ruser)
  1003  
  1004  	if ruser.Nickname != "Joram Wilander" {
  1005  		t.Fatal("Nickname did not update properly")
  1006  	}
  1007  	if ruser.FirstName != "Joram" {
  1008  		t.Fatal("FirstName did not update properly")
  1009  	}
  1010  	if ruser.LastName != "Wilander" {
  1011  		t.Fatal("LastName did not update properly")
  1012  	}
  1013  	if ruser.Position != "" {
  1014  		t.Fatal("Position did not update properly")
  1015  	}
  1016  	if ruser.Username != user.Username {
  1017  		t.Fatal("Username should not have updated")
  1018  	}
  1019  	if ruser.NotifyProps["comment"] != "somethingrandom" {
  1020  		t.Fatal("NotifyProps did not update properly")
  1021  	}
  1022  
  1023  	patch.Username = model.NewString(th.BasicUser2.Username)
  1024  	_, resp = Client.PatchUser(user.Id, patch)
  1025  	CheckBadRequestStatus(t, resp)
  1026  
  1027  	patch.Username = nil
  1028  
  1029  	_, resp = Client.PatchUser("junk", patch)
  1030  	CheckBadRequestStatus(t, resp)
  1031  
  1032  	ruser.Id = model.NewId()
  1033  	_, resp = Client.PatchUser(model.NewId(), patch)
  1034  	CheckForbiddenStatus(t, resp)
  1035  
  1036  	if r, err := Client.DoApiPut("/users/"+user.Id+"/patch", "garbage"); err == nil {
  1037  		t.Fatal("should have errored")
  1038  	} else {
  1039  		if r.StatusCode != http.StatusBadRequest {
  1040  			t.Log("actual: " + strconv.Itoa(r.StatusCode))
  1041  			t.Log("expected: " + strconv.Itoa(http.StatusBadRequest))
  1042  			t.Fatal("wrong status code")
  1043  		}
  1044  	}
  1045  
  1046  	session, _ := th.App.GetSession(Client.AuthToken)
  1047  	session.IsOAuth = true
  1048  	th.App.AddSessionToCache(session)
  1049  
  1050  	patch.Email = model.NewString(th.GenerateTestEmail())
  1051  	_, resp = Client.PatchUser(user.Id, patch)
  1052  	CheckForbiddenStatus(t, resp)
  1053  
  1054  	Client.Logout()
  1055  	_, resp = Client.PatchUser(user.Id, patch)
  1056  	CheckUnauthorizedStatus(t, resp)
  1057  
  1058  	th.LoginBasic()
  1059  	_, resp = Client.PatchUser(user.Id, patch)
  1060  	CheckForbiddenStatus(t, resp)
  1061  
  1062  	_, resp = th.SystemAdminClient.PatchUser(user.Id, patch)
  1063  	CheckNoError(t, resp)
  1064  }
  1065  
  1066  func TestUpdateUserAuth(t *testing.T) {
  1067  	th := Setup().InitSystemAdmin().InitBasic()
  1068  	defer th.TearDown()
  1069  
  1070  	Client := th.SystemAdminClient
  1071  	team := th.CreateTeamWithClient(Client)
  1072  
  1073  	user := th.CreateUser()
  1074  
  1075  	th.LinkUserToTeam(user, team)
  1076  	store.Must(th.App.Srv.Store.User().VerifyEmail(user.Id))
  1077  
  1078  	userAuth := &model.UserAuth{}
  1079  	userAuth.AuthData = user.AuthData
  1080  	userAuth.AuthService = user.AuthService
  1081  	userAuth.Password = user.Password
  1082  
  1083  	// Regular user can not use endpoint
  1084  	if _, err := th.Client.UpdateUserAuth(user.Id, userAuth); err == nil {
  1085  		t.Fatal("Shouldn't have permissions. Only Admins")
  1086  	}
  1087  
  1088  	userAuth.AuthData = model.NewString("test@test.com")
  1089  	userAuth.AuthService = model.USER_AUTH_SERVICE_SAML
  1090  	userAuth.Password = "newpassword"
  1091  	ruser, resp := Client.UpdateUserAuth(user.Id, userAuth)
  1092  	CheckNoError(t, resp)
  1093  
  1094  	// AuthData and AuthService are set, password is set to empty
  1095  	if *ruser.AuthData != *userAuth.AuthData {
  1096  		t.Fatal("Should have set the correct AuthData")
  1097  	}
  1098  	if ruser.AuthService != model.USER_AUTH_SERVICE_SAML {
  1099  		t.Fatal("Should have set the correct AuthService")
  1100  	}
  1101  	if ruser.Password != "" {
  1102  		t.Fatal("Password should be empty")
  1103  	}
  1104  
  1105  	// When AuthData or AuthService are empty, password must be valid
  1106  	userAuth.AuthData = user.AuthData
  1107  	userAuth.AuthService = ""
  1108  	userAuth.Password = "1"
  1109  	if _, err := Client.UpdateUserAuth(user.Id, userAuth); err == nil {
  1110  		t.Fatal("Should have errored - user password not valid")
  1111  	}
  1112  
  1113  	// Regular user can not use endpoint
  1114  	user2 := th.CreateUser()
  1115  	th.LinkUserToTeam(user2, team)
  1116  	store.Must(th.App.Srv.Store.User().VerifyEmail(user2.Id))
  1117  
  1118  	Client.Login(user2.Email, "passwd1")
  1119  
  1120  	userAuth.AuthData = user.AuthData
  1121  	userAuth.AuthService = user.AuthService
  1122  	userAuth.Password = user.Password
  1123  	if _, err := Client.UpdateUserAuth(user.Id, userAuth); err == nil {
  1124  		t.Fatal("Should have errored")
  1125  	}
  1126  }
  1127  
  1128  func TestDeleteUser(t *testing.T) {
  1129  	th := Setup().InitBasic().InitSystemAdmin()
  1130  	defer th.TearDown()
  1131  
  1132  	Client := th.Client
  1133  
  1134  	user := th.BasicUser
  1135  	th.LoginBasic()
  1136  
  1137  	testUser := th.SystemAdminUser
  1138  	_, resp := Client.DeleteUser(testUser.Id)
  1139  	CheckForbiddenStatus(t, resp)
  1140  
  1141  	Client.Logout()
  1142  
  1143  	_, resp = Client.DeleteUser(user.Id)
  1144  	CheckUnauthorizedStatus(t, resp)
  1145  
  1146  	Client.Login(testUser.Email, testUser.Password)
  1147  
  1148  	user.Id = model.NewId()
  1149  	_, resp = Client.DeleteUser(user.Id)
  1150  	CheckNotFoundStatus(t, resp)
  1151  
  1152  	user.Id = "junk"
  1153  	_, resp = Client.DeleteUser(user.Id)
  1154  	CheckBadRequestStatus(t, resp)
  1155  
  1156  	_, resp = Client.DeleteUser(testUser.Id)
  1157  	CheckNoError(t, resp)
  1158  }
  1159  
  1160  func TestUpdateUserRoles(t *testing.T) {
  1161  	th := Setup().InitBasic().InitSystemAdmin()
  1162  	defer th.TearDown()
  1163  
  1164  	Client := th.Client
  1165  	SystemAdminClient := th.SystemAdminClient
  1166  
  1167  	_, resp := Client.UpdateUserRoles(th.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID)
  1168  	CheckForbiddenStatus(t, resp)
  1169  
  1170  	_, resp = SystemAdminClient.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID)
  1171  	CheckNoError(t, resp)
  1172  
  1173  	_, resp = SystemAdminClient.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID)
  1174  	CheckNoError(t, resp)
  1175  
  1176  	_, resp = SystemAdminClient.UpdateUserRoles(th.BasicUser.Id, "junk")
  1177  	CheckBadRequestStatus(t, resp)
  1178  
  1179  	_, resp = SystemAdminClient.UpdateUserRoles("junk", model.SYSTEM_USER_ROLE_ID)
  1180  	CheckBadRequestStatus(t, resp)
  1181  
  1182  	_, resp = SystemAdminClient.UpdateUserRoles(model.NewId(), model.SYSTEM_USER_ROLE_ID)
  1183  	CheckBadRequestStatus(t, resp)
  1184  }
  1185  
  1186  func TestUpdateUserActive(t *testing.T) {
  1187  	th := Setup().InitBasic().InitSystemAdmin()
  1188  	defer th.TearDown()
  1189  
  1190  	Client := th.Client
  1191  	SystemAdminClient := th.SystemAdminClient
  1192  	user := th.BasicUser
  1193  
  1194  	pass, resp := Client.UpdateUserActive(user.Id, false)
  1195  	CheckNoError(t, resp)
  1196  
  1197  	if !pass {
  1198  		t.Fatal("should have returned true")
  1199  	}
  1200  
  1201  	pass, resp = Client.UpdateUserActive(user.Id, false)
  1202  	CheckUnauthorizedStatus(t, resp)
  1203  
  1204  	if pass {
  1205  		t.Fatal("should have returned false")
  1206  	}
  1207  
  1208  	th.LoginBasic2()
  1209  
  1210  	_, resp = Client.UpdateUserActive(user.Id, true)
  1211  	CheckForbiddenStatus(t, resp)
  1212  
  1213  	_, resp = Client.UpdateUserActive(GenerateTestId(), true)
  1214  	CheckForbiddenStatus(t, resp)
  1215  
  1216  	_, resp = Client.UpdateUserActive("junk", true)
  1217  	CheckBadRequestStatus(t, resp)
  1218  
  1219  	Client.Logout()
  1220  
  1221  	_, resp = Client.UpdateUserActive(user.Id, true)
  1222  	CheckUnauthorizedStatus(t, resp)
  1223  
  1224  	_, resp = SystemAdminClient.UpdateUserActive(user.Id, true)
  1225  	CheckNoError(t, resp)
  1226  
  1227  	_, resp = SystemAdminClient.UpdateUserActive(user.Id, false)
  1228  	CheckNoError(t, resp)
  1229  
  1230  	authData := model.NewId()
  1231  	result := <-th.App.Srv.Store.User().UpdateAuthData(user.Id, "random", &authData, "", true)
  1232  	require.Nil(t, result.Err)
  1233  
  1234  	_, resp = SystemAdminClient.UpdateUserActive(user.Id, false)
  1235  	CheckNoError(t, resp)
  1236  }
  1237  
  1238  func TestGetUsers(t *testing.T) {
  1239  	th := Setup().InitBasic()
  1240  	defer th.TearDown()
  1241  	Client := th.Client
  1242  
  1243  	rusers, resp := Client.GetUsers(0, 60, "")
  1244  	CheckNoError(t, resp)
  1245  	for _, u := range rusers {
  1246  		CheckUserSanitization(t, u)
  1247  	}
  1248  
  1249  	rusers, resp = Client.GetUsers(0, 60, resp.Etag)
  1250  	CheckEtag(t, rusers, resp)
  1251  
  1252  	rusers, resp = Client.GetUsers(0, 1, "")
  1253  	CheckNoError(t, resp)
  1254  	if len(rusers) != 1 {
  1255  		t.Fatal("should be 1 per page")
  1256  	}
  1257  
  1258  	rusers, resp = Client.GetUsers(1, 1, "")
  1259  	CheckNoError(t, resp)
  1260  	if len(rusers) != 1 {
  1261  		t.Fatal("should be 1 per page")
  1262  	}
  1263  
  1264  	rusers, resp = Client.GetUsers(10000, 100, "")
  1265  	CheckNoError(t, resp)
  1266  	if len(rusers) != 0 {
  1267  		t.Fatal("should be no users")
  1268  	}
  1269  
  1270  	// Check default params for page and per_page
  1271  	if _, err := Client.DoApiGet("/users", ""); err != nil {
  1272  		t.Fatal("should not have errored")
  1273  	}
  1274  
  1275  	Client.Logout()
  1276  	_, resp = Client.GetUsers(0, 60, "")
  1277  	CheckUnauthorizedStatus(t, resp)
  1278  }
  1279  
  1280  func TestGetNewUsersInTeam(t *testing.T) {
  1281  	th := Setup().InitBasic()
  1282  	defer th.TearDown()
  1283  	Client := th.Client
  1284  	teamId := th.BasicTeam.Id
  1285  
  1286  	rusers, resp := Client.GetNewUsersInTeam(teamId, 0, 60, "")
  1287  	CheckNoError(t, resp)
  1288  
  1289  	lastCreateAt := model.GetMillis()
  1290  	for _, u := range rusers {
  1291  		if u.CreateAt > lastCreateAt {
  1292  			t.Fatal("bad sorting")
  1293  		}
  1294  		lastCreateAt = u.CreateAt
  1295  		CheckUserSanitization(t, u)
  1296  	}
  1297  
  1298  	rusers, resp = Client.GetNewUsersInTeam(teamId, 1, 1, "")
  1299  	CheckNoError(t, resp)
  1300  	if len(rusers) != 1 {
  1301  		t.Fatal("should be 1 per page")
  1302  	}
  1303  
  1304  	Client.Logout()
  1305  	_, resp = Client.GetNewUsersInTeam(teamId, 1, 1, "")
  1306  	CheckUnauthorizedStatus(t, resp)
  1307  }
  1308  
  1309  func TestGetRecentlyActiveUsersInTeam(t *testing.T) {
  1310  	th := Setup().InitBasic()
  1311  	defer th.TearDown()
  1312  	Client := th.Client
  1313  	teamId := th.BasicTeam.Id
  1314  
  1315  	th.App.SetStatusOnline(th.BasicUser.Id, "", true)
  1316  
  1317  	rusers, resp := Client.GetRecentlyActiveUsersInTeam(teamId, 0, 60, "")
  1318  	CheckNoError(t, resp)
  1319  
  1320  	for _, u := range rusers {
  1321  		if u.LastActivityAt == 0 {
  1322  			t.Fatal("did not return last activity at")
  1323  		}
  1324  		CheckUserSanitization(t, u)
  1325  	}
  1326  
  1327  	rusers, resp = Client.GetRecentlyActiveUsersInTeam(teamId, 0, 1, "")
  1328  	CheckNoError(t, resp)
  1329  	if len(rusers) != 1 {
  1330  		t.Fatal("should be 1 per page")
  1331  	}
  1332  
  1333  	Client.Logout()
  1334  	_, resp = Client.GetRecentlyActiveUsersInTeam(teamId, 0, 1, "")
  1335  	CheckUnauthorizedStatus(t, resp)
  1336  }
  1337  
  1338  func TestGetUsersWithoutTeam(t *testing.T) {
  1339  	th := Setup().InitBasic().InitSystemAdmin()
  1340  	defer th.TearDown()
  1341  	Client := th.Client
  1342  	SystemAdminClient := th.SystemAdminClient
  1343  
  1344  	if _, resp := Client.GetUsersWithoutTeam(0, 100, ""); resp.Error == nil {
  1345  		t.Fatal("should prevent non-admin user from getting users without a team")
  1346  	}
  1347  
  1348  	// These usernames need to appear in the first 100 users for this to work
  1349  
  1350  	user, resp := Client.CreateUser(&model.User{
  1351  		Username: "a000000000" + model.NewId(),
  1352  		Email:    "success+" + model.NewId() + "@simulator.amazonses.com",
  1353  		Password: "Password1",
  1354  	})
  1355  	CheckNoError(t, resp)
  1356  	th.LinkUserToTeam(user, th.BasicTeam)
  1357  	defer th.App.Srv.Store.User().PermanentDelete(user.Id)
  1358  
  1359  	user2, resp := Client.CreateUser(&model.User{
  1360  		Username: "a000000001" + model.NewId(),
  1361  		Email:    "success+" + model.NewId() + "@simulator.amazonses.com",
  1362  		Password: "Password1",
  1363  	})
  1364  	CheckNoError(t, resp)
  1365  	defer th.App.Srv.Store.User().PermanentDelete(user2.Id)
  1366  
  1367  	rusers, resp := SystemAdminClient.GetUsersWithoutTeam(0, 100, "")
  1368  	CheckNoError(t, resp)
  1369  
  1370  	found1 := false
  1371  	found2 := false
  1372  
  1373  	for _, u := range rusers {
  1374  		if u.Id == user.Id {
  1375  			found1 = true
  1376  		} else if u.Id == user2.Id {
  1377  			found2 = true
  1378  		}
  1379  	}
  1380  
  1381  	if found1 {
  1382  		t.Fatal("shouldn't have returned user that has a team")
  1383  	} else if !found2 {
  1384  		t.Fatal("should've returned user that has no teams")
  1385  	}
  1386  }
  1387  
  1388  func TestGetUsersInTeam(t *testing.T) {
  1389  	th := Setup().InitBasic().InitSystemAdmin()
  1390  	defer th.TearDown()
  1391  	Client := th.Client
  1392  	teamId := th.BasicTeam.Id
  1393  
  1394  	rusers, resp := Client.GetUsersInTeam(teamId, 0, 60, "")
  1395  	CheckNoError(t, resp)
  1396  	for _, u := range rusers {
  1397  		CheckUserSanitization(t, u)
  1398  	}
  1399  
  1400  	rusers, resp = Client.GetUsersInTeam(teamId, 0, 60, resp.Etag)
  1401  	CheckEtag(t, rusers, resp)
  1402  
  1403  	rusers, resp = Client.GetUsersInTeam(teamId, 0, 1, "")
  1404  	CheckNoError(t, resp)
  1405  	if len(rusers) != 1 {
  1406  		t.Fatal("should be 1 per page")
  1407  	}
  1408  
  1409  	rusers, resp = Client.GetUsersInTeam(teamId, 1, 1, "")
  1410  	CheckNoError(t, resp)
  1411  	if len(rusers) != 1 {
  1412  		t.Fatal("should be 1 per page")
  1413  	}
  1414  
  1415  	rusers, resp = Client.GetUsersInTeam(teamId, 10000, 100, "")
  1416  	CheckNoError(t, resp)
  1417  	if len(rusers) != 0 {
  1418  		t.Fatal("should be no users")
  1419  	}
  1420  
  1421  	Client.Logout()
  1422  	_, resp = Client.GetUsersInTeam(teamId, 0, 60, "")
  1423  	CheckUnauthorizedStatus(t, resp)
  1424  
  1425  	user := th.CreateUser()
  1426  	Client.Login(user.Email, user.Password)
  1427  	_, resp = Client.GetUsersInTeam(teamId, 0, 60, "")
  1428  	CheckForbiddenStatus(t, resp)
  1429  
  1430  	_, resp = th.SystemAdminClient.GetUsersInTeam(teamId, 0, 60, "")
  1431  	CheckNoError(t, resp)
  1432  }
  1433  
  1434  func TestGetUsersNotInTeam(t *testing.T) {
  1435  	th := Setup().InitBasic().InitSystemAdmin()
  1436  	defer th.TearDown()
  1437  	Client := th.Client
  1438  	teamId := th.BasicTeam.Id
  1439  
  1440  	rusers, resp := Client.GetUsersNotInTeam(teamId, 0, 60, "")
  1441  	CheckNoError(t, resp)
  1442  	for _, u := range rusers {
  1443  		CheckUserSanitization(t, u)
  1444  	}
  1445  
  1446  	rusers, resp = Client.GetUsersNotInTeam(teamId, 0, 60, resp.Etag)
  1447  	CheckEtag(t, rusers, resp)
  1448  
  1449  	rusers, resp = Client.GetUsersNotInTeam(teamId, 0, 1, "")
  1450  	CheckNoError(t, resp)
  1451  	if len(rusers) != 1 {
  1452  		t.Fatal("should be 1 per page")
  1453  	}
  1454  
  1455  	rusers, resp = Client.GetUsersNotInTeam(teamId, 1, 1, "")
  1456  	CheckNoError(t, resp)
  1457  	if len(rusers) != 1 {
  1458  		t.Fatal("should be 1 per page")
  1459  	}
  1460  
  1461  	rusers, resp = Client.GetUsersNotInTeam(teamId, 10000, 100, "")
  1462  	CheckNoError(t, resp)
  1463  	if len(rusers) != 0 {
  1464  		t.Fatal("should be no users")
  1465  	}
  1466  
  1467  	Client.Logout()
  1468  	_, resp = Client.GetUsersNotInTeam(teamId, 0, 60, "")
  1469  	CheckUnauthorizedStatus(t, resp)
  1470  
  1471  	user := th.CreateUser()
  1472  	Client.Login(user.Email, user.Password)
  1473  	_, resp = Client.GetUsersNotInTeam(teamId, 0, 60, "")
  1474  	CheckForbiddenStatus(t, resp)
  1475  
  1476  	_, resp = th.SystemAdminClient.GetUsersNotInTeam(teamId, 0, 60, "")
  1477  	CheckNoError(t, resp)
  1478  }
  1479  
  1480  func TestGetUsersInChannel(t *testing.T) {
  1481  	th := Setup().InitBasic().InitSystemAdmin()
  1482  	defer th.TearDown()
  1483  	Client := th.Client
  1484  	channelId := th.BasicChannel.Id
  1485  
  1486  	rusers, resp := Client.GetUsersInChannel(channelId, 0, 60, "")
  1487  	CheckNoError(t, resp)
  1488  	for _, u := range rusers {
  1489  		CheckUserSanitization(t, u)
  1490  	}
  1491  
  1492  	rusers, resp = Client.GetUsersInChannel(channelId, 0, 1, "")
  1493  	CheckNoError(t, resp)
  1494  	if len(rusers) != 1 {
  1495  		t.Fatal("should be 1 per page")
  1496  	}
  1497  
  1498  	rusers, resp = Client.GetUsersInChannel(channelId, 1, 1, "")
  1499  	CheckNoError(t, resp)
  1500  	if len(rusers) != 1 {
  1501  		t.Fatal("should be 1 per page")
  1502  	}
  1503  
  1504  	rusers, resp = Client.GetUsersInChannel(channelId, 10000, 100, "")
  1505  	CheckNoError(t, resp)
  1506  	if len(rusers) != 0 {
  1507  		t.Fatal("should be no users")
  1508  	}
  1509  
  1510  	Client.Logout()
  1511  	_, resp = Client.GetUsersInChannel(channelId, 0, 60, "")
  1512  	CheckUnauthorizedStatus(t, resp)
  1513  
  1514  	user := th.CreateUser()
  1515  	Client.Login(user.Email, user.Password)
  1516  	_, resp = Client.GetUsersInChannel(channelId, 0, 60, "")
  1517  	CheckForbiddenStatus(t, resp)
  1518  
  1519  	_, resp = th.SystemAdminClient.GetUsersInChannel(channelId, 0, 60, "")
  1520  	CheckNoError(t, resp)
  1521  }
  1522  
  1523  func TestGetUsersNotInChannel(t *testing.T) {
  1524  	th := Setup().InitBasic().InitSystemAdmin()
  1525  	defer th.TearDown()
  1526  	Client := th.Client
  1527  	teamId := th.BasicTeam.Id
  1528  	channelId := th.BasicChannel.Id
  1529  
  1530  	user := th.CreateUser()
  1531  	th.LinkUserToTeam(user, th.BasicTeam)
  1532  
  1533  	rusers, resp := Client.GetUsersNotInChannel(teamId, channelId, 0, 60, "")
  1534  	CheckNoError(t, resp)
  1535  	for _, u := range rusers {
  1536  		CheckUserSanitization(t, u)
  1537  	}
  1538  
  1539  	rusers, resp = Client.GetUsersNotInChannel(teamId, channelId, 0, 1, "")
  1540  	CheckNoError(t, resp)
  1541  	if len(rusers) != 1 {
  1542  		t.Log(len(rusers))
  1543  		t.Fatal("should be 1 per page")
  1544  	}
  1545  
  1546  	rusers, resp = Client.GetUsersNotInChannel(teamId, channelId, 10000, 100, "")
  1547  	CheckNoError(t, resp)
  1548  	if len(rusers) != 0 {
  1549  		t.Fatal("should be no users")
  1550  	}
  1551  
  1552  	Client.Logout()
  1553  	_, resp = Client.GetUsersNotInChannel(teamId, channelId, 0, 60, "")
  1554  	CheckUnauthorizedStatus(t, resp)
  1555  
  1556  	Client.Login(user.Email, user.Password)
  1557  	_, resp = Client.GetUsersNotInChannel(teamId, channelId, 0, 60, "")
  1558  	CheckForbiddenStatus(t, resp)
  1559  
  1560  	_, resp = th.SystemAdminClient.GetUsersNotInChannel(teamId, channelId, 0, 60, "")
  1561  	CheckNoError(t, resp)
  1562  }
  1563  
  1564  func TestUpdateUserMfa(t *testing.T) {
  1565  	th := Setup().InitBasic().InitSystemAdmin()
  1566  	defer th.TearDown()
  1567  	Client := th.Client
  1568  
  1569  	th.App.SetLicense(model.NewTestLicense("mfa"))
  1570  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true })
  1571  
  1572  	session, _ := th.App.GetSession(Client.AuthToken)
  1573  	session.IsOAuth = true
  1574  	th.App.AddSessionToCache(session)
  1575  
  1576  	_, resp := Client.UpdateUserMfa(th.BasicUser.Id, "12345", false)
  1577  	CheckForbiddenStatus(t, resp)
  1578  }
  1579  
  1580  func TestCheckUserMfa(t *testing.T) {
  1581  	th := Setup().InitBasic().InitSystemAdmin()
  1582  	defer th.TearDown()
  1583  	Client := th.Client
  1584  
  1585  	required, resp := Client.CheckUserMfa(th.BasicUser.Email)
  1586  	CheckNoError(t, resp)
  1587  
  1588  	if required {
  1589  		t.Fatal("should be false - mfa not active")
  1590  	}
  1591  
  1592  	_, resp = Client.CheckUserMfa("")
  1593  	CheckBadRequestStatus(t, resp)
  1594  
  1595  	Client.Logout()
  1596  
  1597  	required, resp = Client.CheckUserMfa(th.BasicUser.Email)
  1598  	CheckNoError(t, resp)
  1599  
  1600  	if required {
  1601  		t.Fatal("should be false - mfa not active")
  1602  	}
  1603  
  1604  	th.App.SetLicense(model.NewTestLicense("mfa"))
  1605  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true })
  1606  
  1607  	th.LoginBasic()
  1608  
  1609  	required, resp = Client.CheckUserMfa(th.BasicUser.Email)
  1610  	CheckNoError(t, resp)
  1611  
  1612  	if required {
  1613  		t.Fatal("should be false - mfa not active")
  1614  	}
  1615  
  1616  	Client.Logout()
  1617  
  1618  	required, resp = Client.CheckUserMfa(th.BasicUser.Email)
  1619  	CheckNoError(t, resp)
  1620  
  1621  	if required {
  1622  		t.Fatal("should be false - mfa not active")
  1623  	}
  1624  }
  1625  
  1626  func TestGenerateMfaSecret(t *testing.T) {
  1627  	th := Setup().InitBasic().InitSystemAdmin()
  1628  	defer th.TearDown()
  1629  	Client := th.Client
  1630  
  1631  	_, resp := Client.GenerateMfaSecret(th.BasicUser.Id)
  1632  	CheckNotImplementedStatus(t, resp)
  1633  
  1634  	_, resp = th.SystemAdminClient.GenerateMfaSecret(th.BasicUser.Id)
  1635  	CheckNotImplementedStatus(t, resp)
  1636  
  1637  	_, resp = Client.GenerateMfaSecret("junk")
  1638  	CheckBadRequestStatus(t, resp)
  1639  
  1640  	th.App.SetLicense(model.NewTestLicense("mfa"))
  1641  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true })
  1642  
  1643  	_, resp = Client.GenerateMfaSecret(model.NewId())
  1644  	CheckForbiddenStatus(t, resp)
  1645  
  1646  	session, _ := th.App.GetSession(Client.AuthToken)
  1647  	session.IsOAuth = true
  1648  	th.App.AddSessionToCache(session)
  1649  
  1650  	_, resp = Client.GenerateMfaSecret(th.BasicUser.Id)
  1651  	CheckForbiddenStatus(t, resp)
  1652  
  1653  	Client.Logout()
  1654  
  1655  	_, resp = Client.GenerateMfaSecret(th.BasicUser.Id)
  1656  	CheckUnauthorizedStatus(t, resp)
  1657  }
  1658  
  1659  func TestUpdateUserPassword(t *testing.T) {
  1660  	th := Setup().InitBasic().InitSystemAdmin()
  1661  	defer th.TearDown()
  1662  	Client := th.Client
  1663  
  1664  	password := "newpassword1"
  1665  	pass, resp := Client.UpdateUserPassword(th.BasicUser.Id, th.BasicUser.Password, password)
  1666  	CheckNoError(t, resp)
  1667  
  1668  	if !pass {
  1669  		t.Fatal("should have returned true")
  1670  	}
  1671  
  1672  	_, resp = Client.UpdateUserPassword(th.BasicUser.Id, password, "")
  1673  	CheckBadRequestStatus(t, resp)
  1674  
  1675  	_, resp = Client.UpdateUserPassword(th.BasicUser.Id, password, "junk")
  1676  	CheckBadRequestStatus(t, resp)
  1677  
  1678  	_, resp = Client.UpdateUserPassword("junk", password, password)
  1679  	CheckBadRequestStatus(t, resp)
  1680  
  1681  	_, resp = Client.UpdateUserPassword(th.BasicUser.Id, "", password)
  1682  	CheckBadRequestStatus(t, resp)
  1683  
  1684  	_, resp = Client.UpdateUserPassword(th.BasicUser.Id, "junk", password)
  1685  	CheckBadRequestStatus(t, resp)
  1686  
  1687  	_, resp = Client.UpdateUserPassword(th.BasicUser.Id, password, th.BasicUser.Password)
  1688  	CheckNoError(t, resp)
  1689  
  1690  	Client.Logout()
  1691  	_, resp = Client.UpdateUserPassword(th.BasicUser.Id, password, password)
  1692  	CheckUnauthorizedStatus(t, resp)
  1693  
  1694  	th.LoginBasic2()
  1695  	_, resp = Client.UpdateUserPassword(th.BasicUser.Id, password, password)
  1696  	CheckForbiddenStatus(t, resp)
  1697  
  1698  	th.LoginBasic()
  1699  
  1700  	// Test lockout
  1701  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.MaximumLoginAttempts = 2 })
  1702  
  1703  	// Fail twice
  1704  	_, resp = Client.UpdateUserPassword(th.BasicUser.Id, "badpwd", "newpwd")
  1705  	CheckBadRequestStatus(t, resp)
  1706  	_, resp = Client.UpdateUserPassword(th.BasicUser.Id, "badpwd", "newpwd")
  1707  	CheckBadRequestStatus(t, resp)
  1708  
  1709  	// Should fail because account is locked out
  1710  	_, resp = Client.UpdateUserPassword(th.BasicUser.Id, th.BasicUser.Password, "newpwd")
  1711  	CheckErrorMessage(t, resp, "api.user.check_user_login_attempts.too_many.app_error")
  1712  	CheckUnauthorizedStatus(t, resp)
  1713  
  1714  	// System admin can update another user's password
  1715  	adminSetPassword := "pwdsetbyadmin"
  1716  	pass, resp = th.SystemAdminClient.UpdateUserPassword(th.BasicUser.Id, "", adminSetPassword)
  1717  	CheckNoError(t, resp)
  1718  
  1719  	if !pass {
  1720  		t.Fatal("should have returned true")
  1721  	}
  1722  
  1723  	_, resp = Client.Login(th.BasicUser.Email, adminSetPassword)
  1724  	CheckNoError(t, resp)
  1725  }
  1726  
  1727  /*func TestResetPassword(t *testing.T) {
  1728  	th := Setup().InitBasic()
  1729  	Client := th.Client
  1730  
  1731  	Client.Logout()
  1732  
  1733  	user := th.BasicUser
  1734  
  1735  	// Delete all the messages before check the reset password
  1736  	utils.DeleteMailBox(user.Email)
  1737  
  1738  	success, resp := Client.SendPasswordResetEmail(user.Email)
  1739  	CheckNoError(t, resp)
  1740  	if !success {
  1741  		t.Fatal("should have succeeded")
  1742  	}
  1743  
  1744  	_, resp = Client.SendPasswordResetEmail("")
  1745  	CheckBadRequestStatus(t, resp)
  1746  
  1747  	// Should not leak whether the email is attached to an account or not
  1748  	success, resp = Client.SendPasswordResetEmail("notreal@example.com")
  1749  	CheckNoError(t, resp)
  1750  	if !success {
  1751  		t.Fatal("should have succeeded")
  1752  	}
  1753  
  1754  	// Check if the email was send to the right email address and the recovery key match
  1755  	var resultsMailbox utils.JSONMessageHeaderInbucket
  1756  	err := utils.RetryInbucket(5, func() error {
  1757  		var err error
  1758  		resultsMailbox, err = utils.GetMailBox(user.Email)
  1759  		return err
  1760  	})
  1761  	if err != nil {
  1762  		t.Log(err)
  1763  		t.Log("No email was received, maybe due load on the server. Disabling this verification")
  1764  	}
  1765  
  1766  	var recoveryTokenString string
  1767  	if err == nil && len(resultsMailbox) > 0 {
  1768  		if !strings.ContainsAny(resultsMailbox[0].To[0], user.Email) {
  1769  			t.Fatal("Wrong To recipient")
  1770  		} else {
  1771  			if resultsEmail, err := utils.GetMessageFromMailbox(user.Email, resultsMailbox[0].ID); err == nil {
  1772  				loc := strings.Index(resultsEmail.Body.Text, "token=")
  1773  				if loc == -1 {
  1774  					t.Log(resultsEmail.Body.Text)
  1775  					t.Fatal("Code not found in email")
  1776  				}
  1777  				loc += 6
  1778  				recoveryTokenString = resultsEmail.Body.Text[loc : loc+model.TOKEN_SIZE]
  1779  			}
  1780  		}
  1781  	}
  1782  
  1783  	var recoveryToken *model.Token
  1784  	if result := <-th.App.Srv.Store.Token().GetByToken(recoveryTokenString); result.Err != nil {
  1785  		t.Log(recoveryTokenString)
  1786  		t.Fatal(result.Err)
  1787  	} else {
  1788  		recoveryToken = result.Data.(*model.Token)
  1789  	}
  1790  
  1791  	_, resp = Client.ResetPassword(recoveryToken.Token, "")
  1792  	CheckBadRequestStatus(t, resp)
  1793  
  1794  	_, resp = Client.ResetPassword(recoveryToken.Token, "newp")
  1795  	CheckBadRequestStatus(t, resp)
  1796  
  1797  	_, resp = Client.ResetPassword("", "newpwd")
  1798  	CheckBadRequestStatus(t, resp)
  1799  
  1800  	_, resp = Client.ResetPassword("junk", "newpwd")
  1801  	CheckBadRequestStatus(t, resp)
  1802  
  1803  	code := ""
  1804  	for i := 0; i < model.TOKEN_SIZE; i++ {
  1805  		code += "a"
  1806  	}
  1807  
  1808  	_, resp = Client.ResetPassword(code, "newpwd")
  1809  	CheckBadRequestStatus(t, resp)
  1810  
  1811  	success, resp = Client.ResetPassword(recoveryToken.Token, "newpwd")
  1812  	CheckNoError(t, resp)
  1813  	if !success {
  1814  		t.Fatal("should have succeeded")
  1815  	}
  1816  
  1817  	Client.Login(user.Email, "newpwd")
  1818  	Client.Logout()
  1819  
  1820  	_, resp = Client.ResetPassword(recoveryToken.Token, "newpwd")
  1821  	CheckBadRequestStatus(t, resp)
  1822  
  1823  	authData := model.NewId()
  1824  	if result := <-app.Srv.Store.User().UpdateAuthData(user.Id, "random", &authData, "", true); result.Err != nil {
  1825  		t.Fatal(result.Err)
  1826  	}
  1827  
  1828  	_, resp = Client.SendPasswordResetEmail(user.Email)
  1829  	CheckBadRequestStatus(t, resp)
  1830  }*/
  1831  
  1832  func TestGetSessions(t *testing.T) {
  1833  	th := Setup().InitBasic().InitSystemAdmin()
  1834  	defer th.TearDown()
  1835  	Client := th.Client
  1836  
  1837  	user := th.BasicUser
  1838  
  1839  	Client.Login(user.Email, user.Password)
  1840  
  1841  	sessions, resp := Client.GetSessions(user.Id, "")
  1842  	for _, session := range sessions {
  1843  		if session.UserId != user.Id {
  1844  			t.Fatal("user id does not match session user id")
  1845  		}
  1846  	}
  1847  	CheckNoError(t, resp)
  1848  
  1849  	_, resp = Client.RevokeSession("junk", model.NewId())
  1850  	CheckBadRequestStatus(t, resp)
  1851  
  1852  	_, resp = Client.GetSessions(th.BasicUser2.Id, "")
  1853  	CheckForbiddenStatus(t, resp)
  1854  
  1855  	_, resp = Client.GetSessions(model.NewId(), "")
  1856  	CheckForbiddenStatus(t, resp)
  1857  
  1858  	Client.Logout()
  1859  	_, resp = Client.GetSessions(th.BasicUser2.Id, "")
  1860  	CheckUnauthorizedStatus(t, resp)
  1861  
  1862  	_, resp = th.SystemAdminClient.GetSessions(user.Id, "")
  1863  	CheckNoError(t, resp)
  1864  
  1865  	_, resp = th.SystemAdminClient.GetSessions(th.BasicUser2.Id, "")
  1866  	CheckNoError(t, resp)
  1867  
  1868  	_, resp = th.SystemAdminClient.GetSessions(model.NewId(), "")
  1869  	CheckNoError(t, resp)
  1870  }
  1871  
  1872  func TestRevokeSessions(t *testing.T) {
  1873  	th := Setup().InitBasic().InitSystemAdmin()
  1874  	defer th.TearDown()
  1875  	Client := th.Client
  1876  
  1877  	user := th.BasicUser
  1878  	Client.Login(user.Email, user.Password)
  1879  	sessions, _ := Client.GetSessions(user.Id, "")
  1880  	if len(sessions) == 0 {
  1881  		t.Fatal("sessions should exist")
  1882  	}
  1883  	for _, session := range sessions {
  1884  		if session.UserId != user.Id {
  1885  			t.Fatal("user id does not match session user id")
  1886  		}
  1887  	}
  1888  	session := sessions[0]
  1889  
  1890  	_, resp := Client.RevokeSession(user.Id, model.NewId())
  1891  	CheckBadRequestStatus(t, resp)
  1892  
  1893  	_, resp = Client.RevokeSession(th.BasicUser2.Id, model.NewId())
  1894  	CheckForbiddenStatus(t, resp)
  1895  
  1896  	_, resp = Client.RevokeSession("junk", model.NewId())
  1897  	CheckBadRequestStatus(t, resp)
  1898  
  1899  	status, resp := Client.RevokeSession(user.Id, session.Id)
  1900  	if !status {
  1901  		t.Fatal("user session revoke unsuccessful")
  1902  	}
  1903  	CheckNoError(t, resp)
  1904  
  1905  	th.LoginBasic()
  1906  
  1907  	sessions, _ = th.App.GetSessions(th.SystemAdminUser.Id)
  1908  	session = sessions[0]
  1909  
  1910  	_, resp = Client.RevokeSession(user.Id, session.Id)
  1911  	CheckBadRequestStatus(t, resp)
  1912  
  1913  	Client.Logout()
  1914  	_, resp = Client.RevokeSession(user.Id, model.NewId())
  1915  	CheckUnauthorizedStatus(t, resp)
  1916  
  1917  	_, resp = th.SystemAdminClient.RevokeSession(user.Id, model.NewId())
  1918  	CheckBadRequestStatus(t, resp)
  1919  
  1920  	sessions, _ = th.SystemAdminClient.GetSessions(th.SystemAdminUser.Id, "")
  1921  	if len(sessions) == 0 {
  1922  		t.Fatal("sessions should exist")
  1923  	}
  1924  	for _, session := range sessions {
  1925  		if session.UserId != th.SystemAdminUser.Id {
  1926  			t.Fatal("user id does not match session user id")
  1927  		}
  1928  	}
  1929  	session = sessions[0]
  1930  
  1931  	_, resp = th.SystemAdminClient.RevokeSession(th.SystemAdminUser.Id, session.Id)
  1932  	CheckNoError(t, resp)
  1933  }
  1934  
  1935  func TestRevokeAllSessions(t *testing.T) {
  1936  	th := Setup().InitBasic()
  1937  	defer th.TearDown()
  1938  	Client := th.Client
  1939  
  1940  	user := th.BasicUser
  1941  	Client.Login(user.Email, user.Password)
  1942  
  1943  	_, resp := Client.RevokeAllSessions(th.BasicUser2.Id)
  1944  	CheckForbiddenStatus(t, resp)
  1945  
  1946  	th.InitSystemAdmin()
  1947  
  1948  	_, resp = Client.RevokeAllSessions("junk" + user.Id)
  1949  	CheckBadRequestStatus(t, resp)
  1950  
  1951  	status, resp := Client.RevokeAllSessions(user.Id)
  1952  	if !status {
  1953  		t.Fatal("user all sessions revoke unsuccessful")
  1954  	}
  1955  	CheckNoError(t, resp)
  1956  
  1957  	Client.Logout()
  1958  	_, resp = Client.RevokeAllSessions(user.Id)
  1959  	CheckUnauthorizedStatus(t, resp)
  1960  
  1961  	Client.Login(user.Email, user.Password)
  1962  
  1963  	sessions, _ := Client.GetSessions(user.Id, "")
  1964  	if len(sessions) < 1 {
  1965  		t.Fatal("session should exist")
  1966  	}
  1967  
  1968  	_, resp = Client.RevokeAllSessions(user.Id)
  1969  	CheckNoError(t, resp)
  1970  
  1971  	sessions, _ = th.SystemAdminClient.GetSessions(user.Id, "")
  1972  	if len(sessions) != 0 {
  1973  		t.Fatal("no sessions should exist for user")
  1974  	}
  1975  
  1976  	_, resp = Client.RevokeAllSessions(user.Id)
  1977  	CheckUnauthorizedStatus(t, resp)
  1978  }
  1979  
  1980  func TestAttachDeviceId(t *testing.T) {
  1981  	th := Setup().InitBasic()
  1982  	defer th.TearDown()
  1983  	Client := th.Client
  1984  
  1985  	deviceId := model.PUSH_NOTIFY_APPLE + ":1234567890"
  1986  	pass, resp := Client.AttachDeviceId(deviceId)
  1987  	CheckNoError(t, resp)
  1988  
  1989  	if !pass {
  1990  		t.Fatal("should have passed")
  1991  	}
  1992  
  1993  	if sessions, err := th.App.GetSessions(th.BasicUser.Id); err != nil {
  1994  		t.Fatal(err)
  1995  	} else {
  1996  		if sessions[0].DeviceId != deviceId {
  1997  			t.Fatal("Missing device Id")
  1998  		}
  1999  	}
  2000  
  2001  	_, resp = Client.AttachDeviceId("")
  2002  	CheckBadRequestStatus(t, resp)
  2003  
  2004  	Client.Logout()
  2005  
  2006  	_, resp = Client.AttachDeviceId("")
  2007  	CheckUnauthorizedStatus(t, resp)
  2008  }
  2009  
  2010  func TestGetUserAudits(t *testing.T) {
  2011  	th := Setup().InitBasic().InitSystemAdmin()
  2012  	defer th.TearDown()
  2013  	Client := th.Client
  2014  	user := th.BasicUser
  2015  
  2016  	audits, resp := Client.GetUserAudits(user.Id, 0, 100, "")
  2017  	for _, audit := range audits {
  2018  		if audit.UserId != user.Id {
  2019  			t.Fatal("user id does not match audit user id")
  2020  		}
  2021  	}
  2022  	CheckNoError(t, resp)
  2023  
  2024  	_, resp = Client.GetUserAudits(th.BasicUser2.Id, 0, 100, "")
  2025  	CheckForbiddenStatus(t, resp)
  2026  
  2027  	Client.Logout()
  2028  	_, resp = Client.GetUserAudits(user.Id, 0, 100, "")
  2029  	CheckUnauthorizedStatus(t, resp)
  2030  
  2031  	_, resp = th.SystemAdminClient.GetUserAudits(user.Id, 0, 100, "")
  2032  	CheckNoError(t, resp)
  2033  }
  2034  
  2035  func TestVerifyUserEmail(t *testing.T) {
  2036  	th := Setup().InitBasic()
  2037  	defer th.TearDown()
  2038  	Client := th.Client
  2039  
  2040  	user := model.User{Email: th.GenerateTestEmail(), Nickname: "Darth Vader", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
  2041  
  2042  	ruser, resp := Client.CreateUser(&user)
  2043  
  2044  	token, err := th.App.CreateVerifyEmailToken(ruser.Id)
  2045  	if err != nil {
  2046  		t.Fatal("Unable to create email verify token")
  2047  	}
  2048  
  2049  	_, resp = Client.VerifyUserEmail(token.Token)
  2050  	CheckNoError(t, resp)
  2051  
  2052  	_, resp = Client.VerifyUserEmail(GenerateTestId())
  2053  	CheckBadRequestStatus(t, resp)
  2054  
  2055  	_, resp = Client.VerifyUserEmail("")
  2056  	CheckBadRequestStatus(t, resp)
  2057  }
  2058  
  2059  func TestSendVerificationEmail(t *testing.T) {
  2060  	th := Setup().InitBasic()
  2061  	defer th.TearDown()
  2062  	Client := th.Client
  2063  
  2064  	pass, resp := Client.SendVerificationEmail(th.BasicUser.Email)
  2065  	CheckNoError(t, resp)
  2066  
  2067  	if !pass {
  2068  		t.Fatal("should have passed")
  2069  	}
  2070  
  2071  	_, resp = Client.SendVerificationEmail("")
  2072  	CheckBadRequestStatus(t, resp)
  2073  
  2074  	// Even non-existent emails should return 200 OK
  2075  	_, resp = Client.SendVerificationEmail(th.GenerateTestEmail())
  2076  	CheckNoError(t, resp)
  2077  
  2078  	Client.Logout()
  2079  	_, resp = Client.SendVerificationEmail(th.BasicUser.Email)
  2080  	CheckNoError(t, resp)
  2081  }
  2082  
  2083  func TestSetProfileImage(t *testing.T) {
  2084  	th := Setup().InitBasic().InitSystemAdmin()
  2085  	defer th.TearDown()
  2086  	Client := th.Client
  2087  	user := th.BasicUser
  2088  
  2089  	data, err := readTestFile("test.png")
  2090  	if err != nil {
  2091  		t.Fatal(err)
  2092  	}
  2093  
  2094  	ok, resp := Client.SetProfileImage(user.Id, data)
  2095  	if !ok {
  2096  		t.Fatal(resp.Error)
  2097  	}
  2098  	CheckNoError(t, resp)
  2099  
  2100  	ok, resp = Client.SetProfileImage(model.NewId(), data)
  2101  	if ok {
  2102  		t.Fatal("Should return false, set profile image not allowed")
  2103  	}
  2104  	CheckForbiddenStatus(t, resp)
  2105  
  2106  	// status code returns either forbidden or unauthorized
  2107  	// note: forbidden is set as default at Client4.SetProfileImage when request is terminated early by server
  2108  	Client.Logout()
  2109  	_, resp = Client.SetProfileImage(user.Id, data)
  2110  	if resp.StatusCode == http.StatusForbidden {
  2111  		CheckForbiddenStatus(t, resp)
  2112  	} else if resp.StatusCode == http.StatusUnauthorized {
  2113  		CheckUnauthorizedStatus(t, resp)
  2114  	} else {
  2115  		t.Fatal("Should have failed either forbidden or unauthorized")
  2116  	}
  2117  
  2118  	buser, err := th.App.GetUser(user.Id)
  2119  	require.Nil(t, err)
  2120  
  2121  	_, resp = th.SystemAdminClient.SetProfileImage(user.Id, data)
  2122  	CheckNoError(t, resp)
  2123  
  2124  	ruser, err := th.App.GetUser(user.Id)
  2125  	require.Nil(t, err)
  2126  	assert.True(t, buser.LastPictureUpdate < ruser.LastPictureUpdate, "Picture should have updated for user")
  2127  
  2128  	info := &model.FileInfo{Path: "users/" + user.Id + "/profile.png"}
  2129  	if err := th.cleanupTestFile(info); err != nil {
  2130  		t.Fatal(err)
  2131  	}
  2132  }
  2133  
  2134  func TestSwitchAccount(t *testing.T) {
  2135  	th := Setup().InitBasic().InitSystemAdmin()
  2136  	defer th.TearDown()
  2137  	Client := th.Client
  2138  
  2139  	th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Enable = true })
  2140  
  2141  	Client.Logout()
  2142  
  2143  	sr := &model.SwitchRequest{
  2144  		CurrentService: model.USER_AUTH_SERVICE_EMAIL,
  2145  		NewService:     model.USER_AUTH_SERVICE_GITLAB,
  2146  		Email:          th.BasicUser.Email,
  2147  		Password:       th.BasicUser.Password,
  2148  	}
  2149  
  2150  	link, resp := Client.SwitchAccountType(sr)
  2151  	CheckNoError(t, resp)
  2152  
  2153  	if link == "" {
  2154  		t.Fatal("bad link")
  2155  	}
  2156  
  2157  	th.App.SetLicense(model.NewTestLicense())
  2158  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExperimentalEnableAuthenticationTransfer = false })
  2159  
  2160  	sr = &model.SwitchRequest{
  2161  		CurrentService: model.USER_AUTH_SERVICE_EMAIL,
  2162  		NewService:     model.USER_AUTH_SERVICE_GITLAB,
  2163  	}
  2164  
  2165  	_, resp = Client.SwitchAccountType(sr)
  2166  	CheckForbiddenStatus(t, resp)
  2167  
  2168  	th.LoginBasic()
  2169  
  2170  	sr = &model.SwitchRequest{
  2171  		CurrentService: model.USER_AUTH_SERVICE_SAML,
  2172  		NewService:     model.USER_AUTH_SERVICE_EMAIL,
  2173  		Email:          th.BasicUser.Email,
  2174  		NewPassword:    th.BasicUser.Password,
  2175  	}
  2176  
  2177  	_, resp = Client.SwitchAccountType(sr)
  2178  	CheckForbiddenStatus(t, resp)
  2179  
  2180  	sr = &model.SwitchRequest{
  2181  		CurrentService: model.USER_AUTH_SERVICE_EMAIL,
  2182  		NewService:     model.USER_AUTH_SERVICE_LDAP,
  2183  	}
  2184  
  2185  	_, resp = Client.SwitchAccountType(sr)
  2186  	CheckForbiddenStatus(t, resp)
  2187  
  2188  	sr = &model.SwitchRequest{
  2189  		CurrentService: model.USER_AUTH_SERVICE_LDAP,
  2190  		NewService:     model.USER_AUTH_SERVICE_EMAIL,
  2191  	}
  2192  
  2193  	_, resp = Client.SwitchAccountType(sr)
  2194  	CheckForbiddenStatus(t, resp)
  2195  
  2196  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExperimentalEnableAuthenticationTransfer = true })
  2197  
  2198  	th.LoginBasic()
  2199  
  2200  	fakeAuthData := model.NewId()
  2201  	if result := <-th.App.Srv.Store.User().UpdateAuthData(th.BasicUser.Id, model.USER_AUTH_SERVICE_GITLAB, &fakeAuthData, th.BasicUser.Email, true); result.Err != nil {
  2202  		t.Fatal(result.Err)
  2203  	}
  2204  
  2205  	sr = &model.SwitchRequest{
  2206  		CurrentService: model.USER_AUTH_SERVICE_GITLAB,
  2207  		NewService:     model.USER_AUTH_SERVICE_EMAIL,
  2208  		Email:          th.BasicUser.Email,
  2209  		NewPassword:    th.BasicUser.Password,
  2210  	}
  2211  
  2212  	link, resp = Client.SwitchAccountType(sr)
  2213  	CheckNoError(t, resp)
  2214  
  2215  	if link != "/login?extra=signin_change" {
  2216  		t.Log(link)
  2217  		t.Fatal("bad link")
  2218  	}
  2219  
  2220  	Client.Logout()
  2221  	_, resp = Client.Login(th.BasicUser.Email, th.BasicUser.Password)
  2222  	CheckNoError(t, resp)
  2223  	Client.Logout()
  2224  
  2225  	sr = &model.SwitchRequest{
  2226  		CurrentService: model.USER_AUTH_SERVICE_GITLAB,
  2227  		NewService:     model.SERVICE_GOOGLE,
  2228  	}
  2229  
  2230  	_, resp = Client.SwitchAccountType(sr)
  2231  	CheckBadRequestStatus(t, resp)
  2232  
  2233  	sr = &model.SwitchRequest{
  2234  		CurrentService: model.USER_AUTH_SERVICE_EMAIL,
  2235  		NewService:     model.USER_AUTH_SERVICE_GITLAB,
  2236  		Password:       th.BasicUser.Password,
  2237  	}
  2238  
  2239  	_, resp = Client.SwitchAccountType(sr)
  2240  	CheckNotFoundStatus(t, resp)
  2241  
  2242  	sr = &model.SwitchRequest{
  2243  		CurrentService: model.USER_AUTH_SERVICE_EMAIL,
  2244  		NewService:     model.USER_AUTH_SERVICE_GITLAB,
  2245  		Email:          th.BasicUser.Email,
  2246  	}
  2247  
  2248  	_, resp = Client.SwitchAccountType(sr)
  2249  	CheckUnauthorizedStatus(t, resp)
  2250  
  2251  	sr = &model.SwitchRequest{
  2252  		CurrentService: model.USER_AUTH_SERVICE_GITLAB,
  2253  		NewService:     model.USER_AUTH_SERVICE_EMAIL,
  2254  		Email:          th.BasicUser.Email,
  2255  		NewPassword:    th.BasicUser.Password,
  2256  	}
  2257  
  2258  	_, resp = Client.SwitchAccountType(sr)
  2259  	CheckUnauthorizedStatus(t, resp)
  2260  }
  2261  
  2262  func TestCreateUserAccessToken(t *testing.T) {
  2263  	th := Setup().InitBasic().InitSystemAdmin()
  2264  	defer th.TearDown()
  2265  	Client := th.Client
  2266  	AdminClient := th.SystemAdminClient
  2267  
  2268  	testDescription := "test token"
  2269  
  2270  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  2271  
  2272  	_, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  2273  	CheckForbiddenStatus(t, resp)
  2274  
  2275  	_, resp = Client.CreateUserAccessToken("notarealuserid", testDescription)
  2276  	CheckBadRequestStatus(t, resp)
  2277  
  2278  	_, resp = Client.CreateUserAccessToken(th.BasicUser.Id, "")
  2279  	CheckBadRequestStatus(t, resp)
  2280  
  2281  	th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  2282  
  2283  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = false })
  2284  	_, resp = Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  2285  	CheckNotImplementedStatus(t, resp)
  2286  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  2287  
  2288  	rtoken, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  2289  	CheckNoError(t, resp)
  2290  
  2291  	if rtoken.UserId != th.BasicUser.Id {
  2292  		t.Fatal("wrong user id")
  2293  	} else if rtoken.Token == "" {
  2294  		t.Fatal("token should not be empty")
  2295  	} else if rtoken.Id == "" {
  2296  		t.Fatal("id should not be empty")
  2297  	} else if rtoken.Description != testDescription {
  2298  		t.Fatal("description did not match")
  2299  	} else if !rtoken.IsActive {
  2300  		t.Fatal("token should be active")
  2301  	}
  2302  
  2303  	oldSessionToken := Client.AuthToken
  2304  	Client.AuthToken = rtoken.Token
  2305  	ruser, resp := Client.GetMe("")
  2306  	CheckNoError(t, resp)
  2307  
  2308  	if ruser.Id != th.BasicUser.Id {
  2309  		t.Fatal("returned wrong user")
  2310  	}
  2311  
  2312  	Client.AuthToken = oldSessionToken
  2313  
  2314  	_, resp = Client.CreateUserAccessToken(th.BasicUser2.Id, testDescription)
  2315  	CheckForbiddenStatus(t, resp)
  2316  
  2317  	rtoken, resp = AdminClient.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  2318  	CheckNoError(t, resp)
  2319  
  2320  	if rtoken.UserId != th.BasicUser.Id {
  2321  		t.Fatal("wrong user id")
  2322  	}
  2323  
  2324  	oldSessionToken = Client.AuthToken
  2325  	Client.AuthToken = rtoken.Token
  2326  	ruser, resp = Client.GetMe("")
  2327  	CheckNoError(t, resp)
  2328  
  2329  	if ruser.Id != th.BasicUser.Id {
  2330  		t.Fatal("returned wrong user")
  2331  	}
  2332  
  2333  	Client.AuthToken = oldSessionToken
  2334  
  2335  	session, _ := th.App.GetSession(Client.AuthToken)
  2336  	session.IsOAuth = true
  2337  	th.App.AddSessionToCache(session)
  2338  
  2339  	_, resp = Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  2340  	CheckForbiddenStatus(t, resp)
  2341  }
  2342  
  2343  func TestGetUserAccessToken(t *testing.T) {
  2344  	th := Setup().InitBasic().InitSystemAdmin()
  2345  	defer th.TearDown()
  2346  	Client := th.Client
  2347  	AdminClient := th.SystemAdminClient
  2348  
  2349  	testDescription := "test token"
  2350  
  2351  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  2352  
  2353  	_, resp := Client.GetUserAccessToken("123")
  2354  	CheckBadRequestStatus(t, resp)
  2355  
  2356  	_, resp = Client.GetUserAccessToken(model.NewId())
  2357  	CheckForbiddenStatus(t, resp)
  2358  
  2359  	th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  2360  	token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  2361  	CheckNoError(t, resp)
  2362  
  2363  	rtoken, resp := Client.GetUserAccessToken(token.Id)
  2364  	CheckNoError(t, resp)
  2365  
  2366  	if rtoken.UserId != th.BasicUser.Id {
  2367  		t.Fatal("wrong user id")
  2368  	} else if rtoken.Token != "" {
  2369  		t.Fatal("token should be blank")
  2370  	} else if rtoken.Id == "" {
  2371  		t.Fatal("id should not be empty")
  2372  	} else if rtoken.Description != testDescription {
  2373  		t.Fatal("description did not match")
  2374  	}
  2375  
  2376  	_, resp = AdminClient.GetUserAccessToken(token.Id)
  2377  	CheckNoError(t, resp)
  2378  
  2379  	token, resp = Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  2380  	CheckNoError(t, resp)
  2381  
  2382  	rtokens, resp := Client.GetUserAccessTokensForUser(th.BasicUser.Id, 0, 100)
  2383  	CheckNoError(t, resp)
  2384  
  2385  	if len(rtokens) != 2 {
  2386  		t.Fatal("should have 2 tokens")
  2387  	}
  2388  
  2389  	for _, uat := range rtokens {
  2390  		if uat.UserId != th.BasicUser.Id {
  2391  			t.Fatal("wrong user id")
  2392  		}
  2393  	}
  2394  
  2395  	rtokens, resp = Client.GetUserAccessTokensForUser(th.BasicUser.Id, 1, 1)
  2396  	CheckNoError(t, resp)
  2397  
  2398  	if len(rtokens) != 1 {
  2399  		t.Fatal("should have 1 token")
  2400  	}
  2401  
  2402  	rtokens, resp = AdminClient.GetUserAccessTokensForUser(th.BasicUser.Id, 0, 100)
  2403  	CheckNoError(t, resp)
  2404  
  2405  	if len(rtokens) != 2 {
  2406  		t.Fatal("should have 2 tokens")
  2407  	}
  2408  
  2409  	_, resp = Client.GetUserAccessTokens(0, 100)
  2410  	CheckForbiddenStatus(t, resp)
  2411  
  2412  	rtokens, resp = AdminClient.GetUserAccessTokens(1, 1)
  2413  	CheckNoError(t, resp)
  2414  
  2415  	if len(rtokens) != 1 {
  2416  		t.Fatal("should have 1 token")
  2417  	}
  2418  
  2419  	rtokens, resp = AdminClient.GetUserAccessTokens(0, 2)
  2420  	CheckNoError(t, resp)
  2421  
  2422  	if len(rtokens) != 2 {
  2423  		t.Fatal("should have 2 tokens")
  2424  	}
  2425  }
  2426  
  2427  func TestSearchUserAccessToken(t *testing.T) {
  2428  	th := Setup().InitBasic().InitSystemAdmin()
  2429  	defer th.TearDown()
  2430  	Client := th.Client
  2431  	AdminClient := th.SystemAdminClient
  2432  
  2433  	testDescription := "test token"
  2434  
  2435  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  2436  
  2437  	th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  2438  	token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  2439  	CheckNoError(t, resp)
  2440  
  2441  	_, resp = Client.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: token.Id})
  2442  	CheckForbiddenStatus(t, resp)
  2443  
  2444  	rtokens, resp := AdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: th.BasicUser.Id})
  2445  	CheckNoError(t, resp)
  2446  
  2447  	if len(rtokens) != 1 {
  2448  		t.Fatal("should have 1 tokens")
  2449  	}
  2450  
  2451  	rtokens, resp = AdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: token.Id})
  2452  	CheckNoError(t, resp)
  2453  
  2454  	if len(rtokens) != 1 {
  2455  		t.Fatal("should have 1 tokens")
  2456  	}
  2457  
  2458  	rtokens, resp = AdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: th.BasicUser.Username})
  2459  	CheckNoError(t, resp)
  2460  
  2461  	if len(rtokens) != 1 {
  2462  		t.Fatal("should have 1 tokens")
  2463  	}
  2464  
  2465  	rtokens, resp = AdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: "not found"})
  2466  	CheckNoError(t, resp)
  2467  
  2468  	if len(rtokens) != 0 {
  2469  		t.Fatal("should have 0 tokens")
  2470  	}
  2471  }
  2472  
  2473  func TestRevokeUserAccessToken(t *testing.T) {
  2474  	th := Setup().InitBasic().InitSystemAdmin()
  2475  	defer th.TearDown()
  2476  	Client := th.Client
  2477  	AdminClient := th.SystemAdminClient
  2478  
  2479  	testDescription := "test token"
  2480  
  2481  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  2482  
  2483  	th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  2484  	token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  2485  	CheckNoError(t, resp)
  2486  
  2487  	oldSessionToken := Client.AuthToken
  2488  	Client.AuthToken = token.Token
  2489  	_, resp = Client.GetMe("")
  2490  	CheckNoError(t, resp)
  2491  	Client.AuthToken = oldSessionToken
  2492  
  2493  	ok, resp := Client.RevokeUserAccessToken(token.Id)
  2494  	CheckNoError(t, resp)
  2495  
  2496  	if !ok {
  2497  		t.Fatal("should have passed")
  2498  	}
  2499  
  2500  	oldSessionToken = Client.AuthToken
  2501  	Client.AuthToken = token.Token
  2502  	_, resp = Client.GetMe("")
  2503  	CheckUnauthorizedStatus(t, resp)
  2504  	Client.AuthToken = oldSessionToken
  2505  
  2506  	token, resp = AdminClient.CreateUserAccessToken(th.BasicUser2.Id, testDescription)
  2507  	CheckNoError(t, resp)
  2508  
  2509  	ok, resp = Client.RevokeUserAccessToken(token.Id)
  2510  	CheckForbiddenStatus(t, resp)
  2511  
  2512  	if ok {
  2513  		t.Fatal("should have failed")
  2514  	}
  2515  }
  2516  
  2517  func TestDisableUserAccessToken(t *testing.T) {
  2518  	th := Setup().InitBasic().InitSystemAdmin()
  2519  	defer th.TearDown()
  2520  	Client := th.Client
  2521  	AdminClient := th.SystemAdminClient
  2522  
  2523  	testDescription := "test token"
  2524  
  2525  	*th.App.Config().ServiceSettings.EnableUserAccessTokens = true
  2526  
  2527  	th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  2528  	token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  2529  	CheckNoError(t, resp)
  2530  
  2531  	oldSessionToken := Client.AuthToken
  2532  	Client.AuthToken = token.Token
  2533  	_, resp = Client.GetMe("")
  2534  	CheckNoError(t, resp)
  2535  	Client.AuthToken = oldSessionToken
  2536  
  2537  	ok, resp := Client.DisableUserAccessToken(token.Id)
  2538  	CheckNoError(t, resp)
  2539  
  2540  	if !ok {
  2541  		t.Fatal("should have passed")
  2542  	}
  2543  
  2544  	oldSessionToken = Client.AuthToken
  2545  	Client.AuthToken = token.Token
  2546  	_, resp = Client.GetMe("")
  2547  	CheckUnauthorizedStatus(t, resp)
  2548  	Client.AuthToken = oldSessionToken
  2549  
  2550  	token, resp = AdminClient.CreateUserAccessToken(th.BasicUser2.Id, testDescription)
  2551  	CheckNoError(t, resp)
  2552  
  2553  	ok, resp = Client.DisableUserAccessToken(token.Id)
  2554  	CheckForbiddenStatus(t, resp)
  2555  
  2556  	if ok {
  2557  		t.Fatal("should have failed")
  2558  	}
  2559  }
  2560  
  2561  func TestEnableUserAccessToken(t *testing.T) {
  2562  	th := Setup().InitBasic().InitSystemAdmin()
  2563  	defer th.TearDown()
  2564  	Client := th.Client
  2565  
  2566  	testDescription := "test token"
  2567  
  2568  	*th.App.Config().ServiceSettings.EnableUserAccessTokens = true
  2569  
  2570  	th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  2571  	token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  2572  	CheckNoError(t, resp)
  2573  
  2574  	oldSessionToken := Client.AuthToken
  2575  	Client.AuthToken = token.Token
  2576  	_, resp = Client.GetMe("")
  2577  	CheckNoError(t, resp)
  2578  	Client.AuthToken = oldSessionToken
  2579  
  2580  	_, resp = Client.DisableUserAccessToken(token.Id)
  2581  	CheckNoError(t, resp)
  2582  
  2583  	oldSessionToken = Client.AuthToken
  2584  	Client.AuthToken = token.Token
  2585  	_, resp = Client.GetMe("")
  2586  	CheckUnauthorizedStatus(t, resp)
  2587  	Client.AuthToken = oldSessionToken
  2588  
  2589  	ok, resp := Client.EnableUserAccessToken(token.Id)
  2590  	CheckNoError(t, resp)
  2591  
  2592  	if !ok {
  2593  		t.Fatal("should have passed")
  2594  	}
  2595  
  2596  	oldSessionToken = Client.AuthToken
  2597  	Client.AuthToken = token.Token
  2598  	_, resp = Client.GetMe("")
  2599  	CheckNoError(t, resp)
  2600  	Client.AuthToken = oldSessionToken
  2601  }
  2602  
  2603  func TestUserAccessTokenInactiveUser(t *testing.T) {
  2604  	th := Setup().InitBasic().InitSystemAdmin()
  2605  	defer th.TearDown()
  2606  	Client := th.Client
  2607  
  2608  	testDescription := "test token"
  2609  
  2610  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  2611  
  2612  	th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  2613  	token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  2614  	CheckNoError(t, resp)
  2615  
  2616  	Client.AuthToken = token.Token
  2617  	_, resp = Client.GetMe("")
  2618  	CheckNoError(t, resp)
  2619  
  2620  	th.App.UpdateActive(th.BasicUser, false)
  2621  
  2622  	_, resp = Client.GetMe("")
  2623  	CheckUnauthorizedStatus(t, resp)
  2624  }
  2625  
  2626  func TestUserAccessTokenDisableConfig(t *testing.T) {
  2627  	th := Setup().InitBasic().InitSystemAdmin()
  2628  	defer th.TearDown()
  2629  	Client := th.Client
  2630  
  2631  	testDescription := "test token"
  2632  
  2633  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  2634  
  2635  	th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  2636  	token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  2637  	CheckNoError(t, resp)
  2638  
  2639  	oldSessionToken := Client.AuthToken
  2640  	Client.AuthToken = token.Token
  2641  	_, resp = Client.GetMe("")
  2642  	CheckNoError(t, resp)
  2643  
  2644  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = false })
  2645  
  2646  	_, resp = Client.GetMe("")
  2647  	CheckUnauthorizedStatus(t, resp)
  2648  
  2649  	Client.AuthToken = oldSessionToken
  2650  	_, resp = Client.GetMe("")
  2651  	CheckNoError(t, resp)
  2652  }
  2653  
  2654  func TestGetUsersByStatus(t *testing.T) {
  2655  	th := Setup()
  2656  	defer th.TearDown()
  2657  
  2658  	team, err := th.App.CreateTeam(&model.Team{
  2659  		DisplayName: "dn_" + model.NewId(),
  2660  		Name:        GenerateTestTeamName(),
  2661  		Email:       th.GenerateTestEmail(),
  2662  		Type:        model.TEAM_OPEN,
  2663  	})
  2664  	if err != nil {
  2665  		t.Fatalf("failed to create team: %v", err)
  2666  	}
  2667  
  2668  	channel, err := th.App.CreateChannel(&model.Channel{
  2669  		DisplayName: "dn_" + model.NewId(),
  2670  		Name:        "name_" + model.NewId(),
  2671  		Type:        model.CHANNEL_OPEN,
  2672  		TeamId:      team.Id,
  2673  		CreatorId:   model.NewId(),
  2674  	}, false)
  2675  	if err != nil {
  2676  		t.Fatalf("failed to create channel: %v", err)
  2677  	}
  2678  
  2679  	createUserWithStatus := func(username string, status string) *model.User {
  2680  		id := model.NewId()
  2681  
  2682  		user, err := th.App.CreateUser(&model.User{
  2683  			Email:    "success+" + id + "@simulator.amazonses.com",
  2684  			Username: "un_" + username + "_" + id,
  2685  			Nickname: "nn_" + id,
  2686  			Password: "Password1",
  2687  		})
  2688  		if err != nil {
  2689  			t.Fatalf("failed to create user: %v", err)
  2690  		}
  2691  
  2692  		th.LinkUserToTeam(user, team)
  2693  		th.AddUserToChannel(user, channel)
  2694  
  2695  		th.App.SaveAndBroadcastStatus(&model.Status{
  2696  			UserId: user.Id,
  2697  			Status: status,
  2698  			Manual: true,
  2699  		})
  2700  
  2701  		return user
  2702  	}
  2703  
  2704  	// Creating these out of order in case that affects results
  2705  	offlineUser1 := createUserWithStatus("offline1", model.STATUS_OFFLINE)
  2706  	offlineUser2 := createUserWithStatus("offline2", model.STATUS_OFFLINE)
  2707  	awayUser1 := createUserWithStatus("away1", model.STATUS_AWAY)
  2708  	awayUser2 := createUserWithStatus("away2", model.STATUS_AWAY)
  2709  	onlineUser1 := createUserWithStatus("online1", model.STATUS_ONLINE)
  2710  	onlineUser2 := createUserWithStatus("online2", model.STATUS_ONLINE)
  2711  	dndUser1 := createUserWithStatus("dnd1", model.STATUS_DND)
  2712  	dndUser2 := createUserWithStatus("dnd2", model.STATUS_DND)
  2713  
  2714  	client := th.CreateClient()
  2715  	if _, resp := client.Login(onlineUser2.Username, "Password1"); resp.Error != nil {
  2716  		t.Fatal(resp.Error)
  2717  	}
  2718  
  2719  	t.Run("sorting by status then alphabetical", func(t *testing.T) {
  2720  		usersByStatus, resp := client.GetUsersInChannelByStatus(channel.Id, 0, 8, "")
  2721  		if resp.Error != nil {
  2722  			t.Fatal(resp.Error)
  2723  		}
  2724  
  2725  		expectedUsersByStatus := []*model.User{
  2726  			onlineUser1,
  2727  			onlineUser2,
  2728  			awayUser1,
  2729  			awayUser2,
  2730  			dndUser1,
  2731  			dndUser2,
  2732  			offlineUser1,
  2733  			offlineUser2,
  2734  		}
  2735  
  2736  		if len(usersByStatus) != len(expectedUsersByStatus) {
  2737  			t.Fatalf("received only %v users, expected %v", len(usersByStatus), len(expectedUsersByStatus))
  2738  		}
  2739  
  2740  		for i := range usersByStatus {
  2741  			if usersByStatus[i].Id != expectedUsersByStatus[i].Id {
  2742  				t.Fatalf("received user %v at index %v, expected %v", usersByStatus[i].Username, i, expectedUsersByStatus[i].Username)
  2743  			}
  2744  		}
  2745  	})
  2746  
  2747  	t.Run("paging", func(t *testing.T) {
  2748  		usersByStatus, resp := client.GetUsersInChannelByStatus(channel.Id, 0, 3, "")
  2749  		if resp.Error != nil {
  2750  			t.Fatal(resp.Error)
  2751  		}
  2752  
  2753  		if len(usersByStatus) != 3 {
  2754  			t.Fatal("received too many users")
  2755  		}
  2756  
  2757  		if usersByStatus[0].Id != onlineUser1.Id && usersByStatus[1].Id != onlineUser2.Id {
  2758  			t.Fatal("expected to receive online users first")
  2759  		}
  2760  
  2761  		if usersByStatus[2].Id != awayUser1.Id {
  2762  			t.Fatal("expected to receive away users second")
  2763  		}
  2764  
  2765  		usersByStatus, resp = client.GetUsersInChannelByStatus(channel.Id, 1, 3, "")
  2766  		if resp.Error != nil {
  2767  			t.Fatal(resp.Error)
  2768  		}
  2769  
  2770  		if usersByStatus[0].Id != awayUser2.Id {
  2771  			t.Fatal("expected to receive away users second")
  2772  		}
  2773  
  2774  		if usersByStatus[1].Id != dndUser1.Id && usersByStatus[2].Id != dndUser2.Id {
  2775  			t.Fatal("expected to receive dnd users third")
  2776  		}
  2777  
  2778  		usersByStatus, resp = client.GetUsersInChannelByStatus(channel.Id, 1, 4, "")
  2779  		if resp.Error != nil {
  2780  			t.Fatal(resp.Error)
  2781  		}
  2782  
  2783  		if len(usersByStatus) != 4 {
  2784  			t.Fatal("received too many users")
  2785  		}
  2786  
  2787  		if usersByStatus[0].Id != dndUser1.Id && usersByStatus[1].Id != dndUser2.Id {
  2788  			t.Fatal("expected to receive dnd users third")
  2789  		}
  2790  
  2791  		if usersByStatus[2].Id != offlineUser1.Id && usersByStatus[3].Id != offlineUser2.Id {
  2792  			t.Fatal("expected to receive offline users last")
  2793  		}
  2794  	})
  2795  }