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