github.com/RajatVaryani/mattermost-server@v5.11.1+incompatible/api4/user_test.go (about)

     1  // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package api4
     5  
     6  import (
     7  	"fmt"
     8  	"net/http"
     9  	"regexp"
    10  	"strconv"
    11  	"strings"
    12  	"testing"
    13  	"time"
    14  
    15  	"github.com/dgryski/dgoogauth"
    16  
    17  	"github.com/mattermost/mattermost-server/app"
    18  	"github.com/mattermost/mattermost-server/model"
    19  	"github.com/mattermost/mattermost-server/services/mailservice"
    20  	"github.com/mattermost/mattermost-server/store"
    21  	"github.com/mattermost/mattermost-server/utils/testutils"
    22  	"github.com/stretchr/testify/assert"
    23  	"github.com/stretchr/testify/require"
    24  )
    25  
    26  func TestCreateUser(t *testing.T) {
    27  	th := Setup().InitBasic()
    28  	defer th.TearDown()
    29  
    30  	user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
    31  
    32  	ruser, resp := th.Client.CreateUser(&user)
    33  	CheckNoError(t, resp)
    34  	CheckCreatedStatus(t, resp)
    35  
    36  	_, _ = th.Client.Login(user.Email, user.Password)
    37  
    38  	if ruser.Nickname != user.Nickname {
    39  		t.Fatal("nickname didn't match")
    40  	}
    41  
    42  	if ruser.Roles != model.SYSTEM_USER_ROLE_ID {
    43  		t.Log(ruser.Roles)
    44  		t.Fatal("did not clear roles")
    45  	}
    46  
    47  	CheckUserSanitization(t, ruser)
    48  
    49  	_, resp = th.Client.CreateUser(ruser)
    50  	CheckBadRequestStatus(t, resp)
    51  
    52  	ruser.Id = ""
    53  	ruser.Username = GenerateTestUsername()
    54  	ruser.Password = "passwd1"
    55  	_, resp = th.Client.CreateUser(ruser)
    56  	CheckErrorMessage(t, resp, "store.sql_user.save.email_exists.app_error")
    57  	CheckBadRequestStatus(t, resp)
    58  
    59  	ruser.Email = th.GenerateTestEmail()
    60  	ruser.Username = user.Username
    61  	_, resp = th.Client.CreateUser(ruser)
    62  	CheckErrorMessage(t, resp, "store.sql_user.save.username_exists.app_error")
    63  	CheckBadRequestStatus(t, resp)
    64  
    65  	ruser.Email = ""
    66  	_, resp = th.Client.CreateUser(ruser)
    67  	CheckErrorMessage(t, resp, "model.user.is_valid.email.app_error")
    68  	CheckBadRequestStatus(t, resp)
    69  
    70  	ruser.Username = "testinvalid+++"
    71  	_, resp = th.Client.CreateUser(ruser)
    72  	CheckErrorMessage(t, resp, "model.user.is_valid.username.app_error")
    73  	CheckBadRequestStatus(t, resp)
    74  
    75  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = false })
    76  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableUserCreation = false })
    77  
    78  	user2 := &model.User{Email: th.GenerateTestEmail(), Password: "Password1", Username: GenerateTestUsername()}
    79  	_, resp = th.SystemAdminClient.CreateUser(user2)
    80  	CheckNoError(t, resp)
    81  
    82  	r, err := th.Client.DoApiPost("/users", "garbage")
    83  	require.NotNil(t, err, "should have errored")
    84  	assert.Equal(t, http.StatusBadRequest, r.StatusCode)
    85  }
    86  
    87  func TestCreateUserWithToken(t *testing.T) {
    88  	th := Setup().InitBasic()
    89  	defer th.TearDown()
    90  
    91  	t.Run("CreateWithTokenHappyPath", func(t *testing.T) {
    92  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
    93  		token := model.NewToken(
    94  			app.TOKEN_TYPE_TEAM_INVITATION,
    95  			model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
    96  		)
    97  		<-th.App.Srv.Store.Token().Save(token)
    98  
    99  		ruser, resp := th.Client.CreateUserWithToken(&user, token.Token)
   100  		CheckNoError(t, resp)
   101  		CheckCreatedStatus(t, resp)
   102  
   103  		th.Client.Login(user.Email, user.Password)
   104  		if ruser.Nickname != user.Nickname {
   105  			t.Fatal("nickname didn't match")
   106  		}
   107  		if ruser.Roles != model.SYSTEM_USER_ROLE_ID {
   108  			t.Log(ruser.Roles)
   109  			t.Fatal("did not clear roles")
   110  		}
   111  		CheckUserSanitization(t, ruser)
   112  		if result := <-th.App.Srv.Store.Token().GetByToken(token.Token); result.Err == nil {
   113  			t.Fatal("The token must be deleted after be used")
   114  		}
   115  
   116  		if result := <-th.App.Srv.Store.Token().GetByToken(token.Token); result.Err == nil {
   117  			t.Fatal("The token must be deleted after be used")
   118  		}
   119  
   120  		if teams, err := th.App.GetTeamsForUser(ruser.Id); err != nil || len(teams) == 0 {
   121  			t.Fatal("The user must have teams")
   122  		} else if teams[0].Id != th.BasicTeam.Id {
   123  			t.Fatal("The user joined team must be the team provided.")
   124  		}
   125  	})
   126  
   127  	t.Run("NoToken", func(t *testing.T) {
   128  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   129  		token := model.NewToken(
   130  			app.TOKEN_TYPE_TEAM_INVITATION,
   131  			model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
   132  		)
   133  		<-th.App.Srv.Store.Token().Save(token)
   134  		defer th.App.DeleteToken(token)
   135  
   136  		_, resp := th.Client.CreateUserWithToken(&user, "")
   137  		CheckBadRequestStatus(t, resp)
   138  		CheckErrorMessage(t, resp, "api.user.create_user.missing_token.app_error")
   139  	})
   140  
   141  	t.Run("TokenExpired", func(t *testing.T) {
   142  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   143  		timeNow := time.Now()
   144  		past49Hours := timeNow.Add(-49*time.Hour).UnixNano() / int64(time.Millisecond)
   145  		token := model.NewToken(
   146  			app.TOKEN_TYPE_TEAM_INVITATION,
   147  			model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
   148  		)
   149  		token.CreateAt = past49Hours
   150  		<-th.App.Srv.Store.Token().Save(token)
   151  		defer th.App.DeleteToken(token)
   152  
   153  		_, resp := th.Client.CreateUserWithToken(&user, token.Token)
   154  		CheckBadRequestStatus(t, resp)
   155  		CheckErrorMessage(t, resp, "api.user.create_user.signup_link_expired.app_error")
   156  	})
   157  
   158  	t.Run("WrongToken", func(t *testing.T) {
   159  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   160  
   161  		_, resp := th.Client.CreateUserWithToken(&user, "wrong")
   162  		CheckBadRequestStatus(t, resp)
   163  		CheckErrorMessage(t, resp, "api.user.create_user.signup_link_invalid.app_error")
   164  	})
   165  
   166  	t.Run("EnableUserCreationDisable", func(t *testing.T) {
   167  
   168  		enableUserCreation := th.App.Config().TeamSettings.EnableUserCreation
   169  		defer func() {
   170  			th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = enableUserCreation })
   171  		}()
   172  
   173  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   174  
   175  		token := model.NewToken(
   176  			app.TOKEN_TYPE_TEAM_INVITATION,
   177  			model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
   178  		)
   179  		<-th.App.Srv.Store.Token().Save(token)
   180  		defer th.App.DeleteToken(token)
   181  
   182  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableUserCreation = false })
   183  
   184  		_, resp := th.Client.CreateUserWithToken(&user, token.Token)
   185  		CheckNotImplementedStatus(t, resp)
   186  		CheckErrorMessage(t, resp, "api.user.create_user.signup_email_disabled.app_error")
   187  
   188  	})
   189  
   190  	t.Run("EnableOpenServerDisable", func(t *testing.T) {
   191  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   192  
   193  		token := model.NewToken(
   194  			app.TOKEN_TYPE_TEAM_INVITATION,
   195  			model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}),
   196  		)
   197  		<-th.App.Srv.Store.Token().Save(token)
   198  
   199  		enableOpenServer := th.App.Config().TeamSettings.EnableOpenServer
   200  		defer func() {
   201  			th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableOpenServer = enableOpenServer })
   202  		}()
   203  
   204  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = false })
   205  
   206  		ruser, resp := th.Client.CreateUserWithToken(&user, token.Token)
   207  		CheckNoError(t, resp)
   208  		CheckCreatedStatus(t, resp)
   209  
   210  		th.Client.Login(user.Email, user.Password)
   211  		if ruser.Nickname != user.Nickname {
   212  			t.Fatal("nickname didn't match")
   213  		}
   214  		if ruser.Roles != model.SYSTEM_USER_ROLE_ID {
   215  			t.Log(ruser.Roles)
   216  			t.Fatal("did not clear roles")
   217  		}
   218  		CheckUserSanitization(t, ruser)
   219  		if result := <-th.App.Srv.Store.Token().GetByToken(token.Token); result.Err == nil {
   220  			t.Fatal("The token must be deleted after be used")
   221  		}
   222  	})
   223  }
   224  
   225  func TestCreateUserWithInviteId(t *testing.T) {
   226  	th := Setup().InitBasic()
   227  	defer th.TearDown()
   228  
   229  	t.Run("CreateWithInviteIdHappyPath", func(t *testing.T) {
   230  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   231  
   232  		inviteId := th.BasicTeam.InviteId
   233  
   234  		ruser, resp := th.Client.CreateUserWithInviteId(&user, inviteId)
   235  		CheckNoError(t, resp)
   236  		CheckCreatedStatus(t, resp)
   237  
   238  		th.Client.Login(user.Email, user.Password)
   239  		if ruser.Nickname != user.Nickname {
   240  			t.Fatal("nickname didn't match")
   241  		}
   242  		if ruser.Roles != model.SYSTEM_USER_ROLE_ID {
   243  			t.Log(ruser.Roles)
   244  			t.Fatal("did not clear roles")
   245  		}
   246  		CheckUserSanitization(t, ruser)
   247  	})
   248  
   249  	t.Run("WrongInviteId", func(t *testing.T) {
   250  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   251  
   252  		inviteId := model.NewId()
   253  
   254  		_, resp := th.Client.CreateUserWithInviteId(&user, inviteId)
   255  		CheckNotFoundStatus(t, resp)
   256  		CheckErrorMessage(t, resp, "store.sql_team.get_by_invite_id.finding.app_error")
   257  	})
   258  
   259  	t.Run("NoInviteId", func(t *testing.T) {
   260  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   261  
   262  		_, resp := th.Client.CreateUserWithInviteId(&user, "")
   263  		CheckBadRequestStatus(t, resp)
   264  		CheckErrorMessage(t, resp, "api.user.create_user.missing_invite_id.app_error")
   265  	})
   266  
   267  	t.Run("ExpiredInviteId", func(t *testing.T) {
   268  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   269  
   270  		inviteId := th.BasicTeam.InviteId
   271  
   272  		_, resp := th.SystemAdminClient.RegenerateTeamInviteId(th.BasicTeam.Id)
   273  		CheckNoError(t, resp)
   274  
   275  		_, resp = th.Client.CreateUserWithInviteId(&user, inviteId)
   276  		CheckNotFoundStatus(t, resp)
   277  		CheckErrorMessage(t, resp, "store.sql_team.get_by_invite_id.finding.app_error")
   278  	})
   279  
   280  	t.Run("EnableUserCreationDisable", func(t *testing.T) {
   281  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   282  
   283  		enableUserCreation := th.App.Config().TeamSettings.EnableUserCreation
   284  		defer func() {
   285  			th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = enableUserCreation })
   286  		}()
   287  
   288  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableUserCreation = false })
   289  
   290  		inviteId := th.BasicTeam.InviteId
   291  
   292  		_, resp := th.Client.CreateUserWithInviteId(&user, inviteId)
   293  		CheckNotImplementedStatus(t, resp)
   294  		CheckErrorMessage(t, resp, "api.user.create_user.signup_email_disabled.app_error")
   295  	})
   296  
   297  	t.Run("EnableOpenServerDisable", func(t *testing.T) {
   298  		user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
   299  
   300  		enableOpenServer := th.App.Config().TeamSettings.EnableOpenServer
   301  		defer func() {
   302  			th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableOpenServer = enableOpenServer })
   303  		}()
   304  
   305  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = false })
   306  
   307  		team, res := th.SystemAdminClient.RegenerateTeamInviteId(th.BasicTeam.Id)
   308  		assert.Nil(t, res.Error)
   309  		inviteId := team.InviteId
   310  
   311  		ruser, resp := th.Client.CreateUserWithInviteId(&user, inviteId)
   312  		CheckNoError(t, resp)
   313  		CheckCreatedStatus(t, resp)
   314  
   315  		th.Client.Login(user.Email, user.Password)
   316  		if ruser.Nickname != user.Nickname {
   317  			t.Fatal("nickname didn't match")
   318  		}
   319  		if ruser.Roles != model.SYSTEM_USER_ROLE_ID {
   320  			t.Log(ruser.Roles)
   321  			t.Fatal("did not clear roles")
   322  		}
   323  		CheckUserSanitization(t, ruser)
   324  	})
   325  
   326  }
   327  
   328  func TestGetMe(t *testing.T) {
   329  	th := Setup().InitBasic()
   330  	defer th.TearDown()
   331  
   332  	ruser, resp := th.Client.GetMe("")
   333  	CheckNoError(t, resp)
   334  
   335  	if ruser.Id != th.BasicUser.Id {
   336  		t.Fatal("wrong user")
   337  	}
   338  
   339  	th.Client.Logout()
   340  	_, resp = th.Client.GetMe("")
   341  	CheckUnauthorizedStatus(t, resp)
   342  }
   343  
   344  func TestGetUser(t *testing.T) {
   345  	th := Setup().InitBasic()
   346  	defer th.TearDown()
   347  
   348  	user := th.CreateUser()
   349  	user.Props = map[string]string{"testpropkey": "testpropvalue"}
   350  
   351  	th.App.UpdateUser(user, false)
   352  
   353  	ruser, resp := th.Client.GetUser(user.Id, "")
   354  	CheckNoError(t, resp)
   355  	CheckUserSanitization(t, ruser)
   356  
   357  	if ruser.Email != user.Email {
   358  		t.Fatal("emails did not match")
   359  	}
   360  
   361  	assert.NotNil(t, ruser.Props)
   362  	assert.Equal(t, ruser.Props["testpropkey"], "testpropvalue")
   363  	require.False(t, ruser.IsBot)
   364  
   365  	ruser, resp = th.Client.GetUser(user.Id, resp.Etag)
   366  	CheckEtag(t, ruser, resp)
   367  
   368  	_, resp = th.Client.GetUser("junk", "")
   369  	CheckBadRequestStatus(t, resp)
   370  
   371  	_, resp = th.Client.GetUser(model.NewId(), "")
   372  	CheckNotFoundStatus(t, resp)
   373  
   374  	// Check against privacy config settings
   375  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowEmailAddress = false })
   376  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowFullName = false })
   377  
   378  	ruser, resp = th.Client.GetUser(user.Id, "")
   379  	CheckNoError(t, resp)
   380  
   381  	if ruser.Email != "" {
   382  		t.Fatal("email should be blank")
   383  	}
   384  	if ruser.FirstName != "" {
   385  		t.Fatal("first name should be blank")
   386  	}
   387  	if ruser.LastName != "" {
   388  		t.Fatal("last name should be blank")
   389  	}
   390  
   391  	th.Client.Logout()
   392  	_, resp = th.Client.GetUser(user.Id, "")
   393  	CheckUnauthorizedStatus(t, resp)
   394  
   395  	// System admins should ignore privacy settings
   396  	ruser, _ = th.SystemAdminClient.GetUser(user.Id, resp.Etag)
   397  	if ruser.Email == "" {
   398  		t.Fatal("email should not be blank")
   399  	}
   400  	if ruser.FirstName == "" {
   401  		t.Fatal("first name should not be blank")
   402  	}
   403  	if ruser.LastName == "" {
   404  		t.Fatal("last name should not be blank")
   405  	}
   406  }
   407  
   408  func TestGetUserWithAcceptedTermsOfServiceForOtherUser(t *testing.T) {
   409  	th := Setup().InitBasic()
   410  	defer th.TearDown()
   411  
   412  	user := th.CreateUser()
   413  
   414  	tos, _ := th.App.CreateTermsOfService("Dummy TOS", user.Id)
   415  
   416  	th.App.UpdateUser(user, false)
   417  
   418  	ruser, resp := th.Client.GetUser(user.Id, "")
   419  	CheckNoError(t, resp)
   420  	CheckUserSanitization(t, ruser)
   421  
   422  	if ruser.Email != user.Email {
   423  		t.Fatal("emails did not match")
   424  	}
   425  
   426  	assert.Empty(t, ruser.TermsOfServiceId)
   427  
   428  	th.App.SaveUserTermsOfService(user.Id, tos.Id, true)
   429  
   430  	ruser, resp = th.Client.GetUser(user.Id, "")
   431  	CheckNoError(t, resp)
   432  	CheckUserSanitization(t, ruser)
   433  
   434  	if ruser.Email != user.Email {
   435  		t.Fatal("emails did not match")
   436  	}
   437  
   438  	// user TOS data cannot be fetched for other users by non-admin users
   439  	assert.Empty(t, ruser.TermsOfServiceId)
   440  }
   441  
   442  func TestGetUserWithAcceptedTermsOfService(t *testing.T) {
   443  	th := Setup().InitBasic()
   444  	defer th.TearDown()
   445  
   446  	user := th.BasicUser
   447  
   448  	tos, _ := th.App.CreateTermsOfService("Dummy TOS", user.Id)
   449  
   450  	ruser, resp := th.Client.GetUser(user.Id, "")
   451  	CheckNoError(t, resp)
   452  	CheckUserSanitization(t, ruser)
   453  
   454  	if ruser.Email != user.Email {
   455  		t.Fatal("emails did not match")
   456  	}
   457  
   458  	assert.Empty(t, ruser.TermsOfServiceId)
   459  
   460  	th.App.SaveUserTermsOfService(user.Id, tos.Id, true)
   461  
   462  	ruser, resp = th.Client.GetUser(user.Id, "")
   463  	CheckNoError(t, resp)
   464  	CheckUserSanitization(t, ruser)
   465  
   466  	if ruser.Email != user.Email {
   467  		t.Fatal("emails did not match")
   468  	}
   469  
   470  	// a user can view their own TOS details
   471  	assert.Equal(t, tos.Id, ruser.TermsOfServiceId)
   472  }
   473  
   474  func TestGetUserWithAcceptedTermsOfServiceWithAdminUser(t *testing.T) {
   475  	th := Setup().InitBasic()
   476  	th.LoginSystemAdmin()
   477  	defer th.TearDown()
   478  
   479  	user := th.BasicUser
   480  
   481  	tos, _ := th.App.CreateTermsOfService("Dummy TOS", user.Id)
   482  
   483  	ruser, resp := th.SystemAdminClient.GetUser(user.Id, "")
   484  	CheckNoError(t, resp)
   485  	CheckUserSanitization(t, ruser)
   486  
   487  	if ruser.Email != user.Email {
   488  		t.Fatal("emails did not match")
   489  	}
   490  
   491  	assert.Empty(t, ruser.TermsOfServiceId)
   492  
   493  	th.App.SaveUserTermsOfService(user.Id, tos.Id, true)
   494  
   495  	ruser, resp = th.SystemAdminClient.GetUser(user.Id, "")
   496  	CheckNoError(t, resp)
   497  	CheckUserSanitization(t, ruser)
   498  
   499  	if ruser.Email != user.Email {
   500  		t.Fatal("emails did not match")
   501  	}
   502  
   503  	// admin can view anyone's TOS details
   504  	assert.Equal(t, tos.Id, ruser.TermsOfServiceId)
   505  }
   506  
   507  func TestGetBotUser(t *testing.T) {
   508  	th := Setup().InitBasic()
   509  	defer th.TearDown()
   510  
   511  	defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
   512  
   513  	th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID)
   514  	th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false)
   515  
   516  	bot := &model.Bot{
   517  		Username:    GenerateTestUsername(),
   518  		DisplayName: "a bot",
   519  		Description: "bot",
   520  	}
   521  
   522  	createdBot, resp := th.Client.CreateBot(bot)
   523  	CheckCreatedStatus(t, resp)
   524  	defer th.App.PermanentDeleteBot(createdBot.UserId)
   525  
   526  	botUser, resp := th.Client.GetUser(createdBot.UserId, "")
   527  	require.Equal(t, bot.Username, botUser.Username)
   528  	require.True(t, botUser.IsBot)
   529  }
   530  
   531  func TestGetUserByUsername(t *testing.T) {
   532  	th := Setup().InitBasic()
   533  	defer th.TearDown()
   534  
   535  	user := th.BasicUser
   536  
   537  	ruser, resp := th.Client.GetUserByUsername(user.Username, "")
   538  	CheckNoError(t, resp)
   539  	CheckUserSanitization(t, ruser)
   540  
   541  	if ruser.Email != user.Email {
   542  		t.Fatal("emails did not match")
   543  	}
   544  
   545  	ruser, resp = th.Client.GetUserByUsername(user.Username, resp.Etag)
   546  	CheckEtag(t, ruser, resp)
   547  
   548  	_, resp = th.Client.GetUserByUsername(GenerateTestUsername(), "")
   549  	CheckNotFoundStatus(t, resp)
   550  
   551  	// Check against privacy config settings
   552  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowEmailAddress = false })
   553  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowFullName = false })
   554  
   555  	ruser, resp = th.Client.GetUserByUsername(th.BasicUser2.Username, "")
   556  	CheckNoError(t, resp)
   557  
   558  	if ruser.Email != "" {
   559  		t.Fatal("email should be blank")
   560  	}
   561  	if ruser.FirstName != "" {
   562  		t.Fatal("first name should be blank")
   563  	}
   564  	if ruser.LastName != "" {
   565  		t.Fatal("last name should be blank")
   566  	}
   567  
   568  	ruser, resp = th.Client.GetUserByUsername(th.BasicUser.Username, "")
   569  	CheckNoError(t, resp)
   570  	if len(ruser.NotifyProps) == 0 {
   571  		t.Fatal("notify props should be sent")
   572  	}
   573  
   574  	th.Client.Logout()
   575  	_, resp = th.Client.GetUserByUsername(user.Username, "")
   576  	CheckUnauthorizedStatus(t, resp)
   577  
   578  	// System admins should ignore privacy settings
   579  	ruser, _ = th.SystemAdminClient.GetUserByUsername(user.Username, resp.Etag)
   580  	if ruser.Email == "" {
   581  		t.Fatal("email should not be blank")
   582  	}
   583  	if ruser.FirstName == "" {
   584  		t.Fatal("first name should not be blank")
   585  	}
   586  	if ruser.LastName == "" {
   587  		t.Fatal("last name should not be blank")
   588  	}
   589  }
   590  
   591  func TestGetUserByUsernameWithAcceptedTermsOfService(t *testing.T) {
   592  	th := Setup().InitBasic()
   593  	defer th.TearDown()
   594  
   595  	user := th.BasicUser
   596  
   597  	ruser, resp := th.Client.GetUserByUsername(user.Username, "")
   598  	CheckNoError(t, resp)
   599  	CheckUserSanitization(t, ruser)
   600  
   601  	if ruser.Email != user.Email {
   602  		t.Fatal("emails did not match")
   603  	}
   604  
   605  	tos, _ := th.App.CreateTermsOfService("Dummy TOS", user.Id)
   606  	th.App.SaveUserTermsOfService(ruser.Id, tos.Id, true)
   607  
   608  	ruser, resp = th.Client.GetUserByUsername(user.Username, "")
   609  	CheckNoError(t, resp)
   610  	CheckUserSanitization(t, ruser)
   611  
   612  	if ruser.Email != user.Email {
   613  		t.Fatal("emails did not match")
   614  	}
   615  
   616  	if ruser.TermsOfServiceId != tos.Id {
   617  		t.Fatal("Terms of service ID didn't match")
   618  	}
   619  }
   620  
   621  func TestGetUserByEmail(t *testing.T) {
   622  	th := Setup().InitBasic()
   623  	defer th.TearDown()
   624  
   625  	user := th.CreateUser()
   626  
   627  	th.App.UpdateConfig(func(cfg *model.Config) {
   628  		*cfg.PrivacySettings.ShowEmailAddress = true
   629  		*cfg.PrivacySettings.ShowFullName = true
   630  	})
   631  
   632  	t.Run("should be able to get another user by email", func(t *testing.T) {
   633  		ruser, resp := th.Client.GetUserByEmail(user.Email, "")
   634  		CheckNoError(t, resp)
   635  		CheckUserSanitization(t, ruser)
   636  
   637  		if ruser.Email != user.Email {
   638  			t.Fatal("emails did not match")
   639  		}
   640  	})
   641  
   642  	t.Run("should return not modified when provided with a matching etag", func(t *testing.T) {
   643  		_, resp := th.Client.GetUserByEmail(user.Email, "")
   644  		CheckNoError(t, resp)
   645  
   646  		ruser, resp := th.Client.GetUserByEmail(user.Email, resp.Etag)
   647  		CheckEtag(t, ruser, resp)
   648  	})
   649  
   650  	t.Run("should return bad request when given an invalid email", func(t *testing.T) {
   651  		_, resp := th.Client.GetUserByEmail(GenerateTestUsername(), "")
   652  		CheckBadRequestStatus(t, resp)
   653  	})
   654  
   655  	t.Run("should return 404 when given a non-existent email", func(t *testing.T) {
   656  		_, resp := th.Client.GetUserByEmail(th.GenerateTestEmail(), "")
   657  		CheckNotFoundStatus(t, resp)
   658  	})
   659  
   660  	t.Run("should sanitize full name for non-admin based on privacy settings", func(t *testing.T) {
   661  		th.App.UpdateConfig(func(cfg *model.Config) {
   662  			*cfg.PrivacySettings.ShowEmailAddress = true
   663  			*cfg.PrivacySettings.ShowFullName = false
   664  		})
   665  
   666  		ruser, resp := th.Client.GetUserByEmail(user.Email, "")
   667  		CheckNoError(t, resp)
   668  		assert.Equal(t, "", ruser.FirstName, "first name should be blank")
   669  		assert.Equal(t, "", ruser.LastName, "last name should be blank")
   670  
   671  		th.App.UpdateConfig(func(cfg *model.Config) {
   672  			*cfg.PrivacySettings.ShowFullName = true
   673  		})
   674  
   675  		ruser, resp = th.Client.GetUserByEmail(user.Email, "")
   676  		CheckNoError(t, resp)
   677  		assert.NotEqual(t, "", ruser.FirstName, "first name should be set")
   678  		assert.NotEqual(t, "", ruser.LastName, "last name should be set")
   679  	})
   680  
   681  	t.Run("should not sanitize full name for admin, regardless of privacy settings", func(t *testing.T) {
   682  		th.App.UpdateConfig(func(cfg *model.Config) {
   683  			*cfg.PrivacySettings.ShowEmailAddress = true
   684  			*cfg.PrivacySettings.ShowFullName = false
   685  		})
   686  
   687  		ruser, resp := th.SystemAdminClient.GetUserByEmail(user.Email, "")
   688  		CheckNoError(t, resp)
   689  		assert.NotEqual(t, "", ruser.FirstName, "first name should be set")
   690  		assert.NotEqual(t, "", ruser.LastName, "last name should be set")
   691  
   692  		th.App.UpdateConfig(func(cfg *model.Config) {
   693  			*cfg.PrivacySettings.ShowFullName = true
   694  		})
   695  
   696  		ruser, resp = th.SystemAdminClient.GetUserByEmail(user.Email, "")
   697  		CheckNoError(t, resp)
   698  		assert.NotEqual(t, "", ruser.FirstName, "first name should be set")
   699  		assert.NotEqual(t, "", ruser.LastName, "last name should be set")
   700  	})
   701  
   702  	t.Run("should return forbidden for non-admin when privacy settings hide email", func(t *testing.T) {
   703  		th.App.UpdateConfig(func(cfg *model.Config) {
   704  			*cfg.PrivacySettings.ShowEmailAddress = false
   705  		})
   706  
   707  		_, resp := th.Client.GetUserByEmail(user.Email, "")
   708  		CheckForbiddenStatus(t, resp)
   709  
   710  		th.App.UpdateConfig(func(cfg *model.Config) {
   711  			*cfg.PrivacySettings.ShowEmailAddress = true
   712  		})
   713  
   714  		ruser, resp := th.Client.GetUserByEmail(user.Email, "")
   715  		CheckNoError(t, resp)
   716  		assert.Equal(t, user.Email, ruser.Email, "email should be set")
   717  	})
   718  
   719  	t.Run("should always return email for admin, regardless of privacy settings", func(t *testing.T) {
   720  		th.App.UpdateConfig(func(cfg *model.Config) {
   721  			*cfg.PrivacySettings.ShowEmailAddress = false
   722  		})
   723  
   724  		ruser, resp := th.SystemAdminClient.GetUserByEmail(user.Email, "")
   725  		CheckNoError(t, resp)
   726  		assert.Equal(t, user.Email, ruser.Email, "email should be set")
   727  
   728  		th.App.UpdateConfig(func(cfg *model.Config) {
   729  			*cfg.PrivacySettings.ShowEmailAddress = true
   730  		})
   731  
   732  		ruser, resp = th.SystemAdminClient.GetUserByEmail(user.Email, "")
   733  		CheckNoError(t, resp)
   734  		assert.Equal(t, user.Email, ruser.Email, "email should be set")
   735  	})
   736  }
   737  
   738  func TestSearchUsers(t *testing.T) {
   739  	th := Setup().InitBasic()
   740  	defer th.TearDown()
   741  
   742  	search := &model.UserSearch{Term: th.BasicUser.Username}
   743  
   744  	users, resp := th.Client.SearchUsers(search)
   745  	CheckNoError(t, resp)
   746  
   747  	if !findUserInList(th.BasicUser.Id, users) {
   748  		t.Fatal("should have found user")
   749  	}
   750  
   751  	_, err := th.App.UpdateActive(th.BasicUser2, false)
   752  	if err != nil {
   753  		t.Fatal(err)
   754  	}
   755  
   756  	search.Term = th.BasicUser2.Username
   757  	search.AllowInactive = false
   758  
   759  	users, resp = th.Client.SearchUsers(search)
   760  	CheckNoError(t, resp)
   761  
   762  	if findUserInList(th.BasicUser2.Id, users) {
   763  		t.Fatal("should not have found user")
   764  	}
   765  
   766  	search.AllowInactive = true
   767  
   768  	users, resp = th.Client.SearchUsers(search)
   769  	CheckNoError(t, resp)
   770  
   771  	if !findUserInList(th.BasicUser2.Id, users) {
   772  		t.Fatal("should have found user")
   773  	}
   774  
   775  	search.Term = th.BasicUser.Username
   776  	search.AllowInactive = false
   777  	search.TeamId = th.BasicTeam.Id
   778  
   779  	users, resp = th.Client.SearchUsers(search)
   780  	CheckNoError(t, resp)
   781  
   782  	if !findUserInList(th.BasicUser.Id, users) {
   783  		t.Fatal("should have found user")
   784  	}
   785  
   786  	search.NotInChannelId = th.BasicChannel.Id
   787  
   788  	users, resp = th.Client.SearchUsers(search)
   789  	CheckNoError(t, resp)
   790  
   791  	if findUserInList(th.BasicUser.Id, users) {
   792  		t.Fatal("should not have found user")
   793  	}
   794  
   795  	search.TeamId = ""
   796  	search.NotInChannelId = ""
   797  	search.InChannelId = th.BasicChannel.Id
   798  
   799  	users, resp = th.Client.SearchUsers(search)
   800  	CheckNoError(t, resp)
   801  
   802  	if !findUserInList(th.BasicUser.Id, users) {
   803  		t.Fatal("should have found user")
   804  	}
   805  
   806  	search.InChannelId = ""
   807  	search.NotInChannelId = th.BasicChannel.Id
   808  	_, resp = th.Client.SearchUsers(search)
   809  	CheckBadRequestStatus(t, resp)
   810  
   811  	search.NotInChannelId = model.NewId()
   812  	search.TeamId = model.NewId()
   813  	_, resp = th.Client.SearchUsers(search)
   814  	CheckForbiddenStatus(t, resp)
   815  
   816  	search.NotInChannelId = ""
   817  	search.TeamId = model.NewId()
   818  	_, resp = th.Client.SearchUsers(search)
   819  	CheckForbiddenStatus(t, resp)
   820  
   821  	search.InChannelId = model.NewId()
   822  	search.TeamId = ""
   823  	_, resp = th.Client.SearchUsers(search)
   824  	CheckForbiddenStatus(t, resp)
   825  
   826  	// Test search for users not in any team
   827  	search.TeamId = ""
   828  	search.NotInChannelId = ""
   829  	search.InChannelId = ""
   830  	search.NotInTeamId = th.BasicTeam.Id
   831  
   832  	users, resp = th.Client.SearchUsers(search)
   833  	CheckNoError(t, resp)
   834  
   835  	if findUserInList(th.BasicUser.Id, users) {
   836  		t.Fatal("should not have found user")
   837  	}
   838  
   839  	oddUser := th.CreateUser()
   840  	search.Term = oddUser.Username
   841  
   842  	users, resp = th.Client.SearchUsers(search)
   843  	CheckNoError(t, resp)
   844  
   845  	if !findUserInList(oddUser.Id, users) {
   846  		t.Fatal("should have found user")
   847  	}
   848  
   849  	_, resp = th.SystemAdminClient.AddTeamMember(th.BasicTeam.Id, oddUser.Id)
   850  	CheckNoError(t, resp)
   851  
   852  	users, resp = th.Client.SearchUsers(search)
   853  	CheckNoError(t, resp)
   854  
   855  	if findUserInList(oddUser.Id, users) {
   856  		t.Fatal("should not have found user")
   857  	}
   858  
   859  	search.NotInTeamId = model.NewId()
   860  	_, resp = th.Client.SearchUsers(search)
   861  	CheckForbiddenStatus(t, resp)
   862  
   863  	search.Term = th.BasicUser.Username
   864  
   865  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowEmailAddress = false })
   866  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowFullName = false })
   867  
   868  	_, err = th.App.UpdateActive(th.BasicUser2, true)
   869  	if err != nil {
   870  		t.Fatal(err)
   871  	}
   872  
   873  	search.InChannelId = ""
   874  	search.NotInTeamId = ""
   875  	search.Term = th.BasicUser2.Email
   876  	users, resp = th.Client.SearchUsers(search)
   877  	CheckNoError(t, resp)
   878  
   879  	if findUserInList(th.BasicUser2.Id, users) {
   880  		t.Fatal("should not have found user")
   881  	}
   882  
   883  	search.Term = th.BasicUser2.FirstName
   884  	users, resp = th.Client.SearchUsers(search)
   885  	CheckNoError(t, resp)
   886  
   887  	if findUserInList(th.BasicUser2.Id, users) {
   888  		t.Fatal("should not have found user")
   889  	}
   890  
   891  	search.Term = th.BasicUser2.LastName
   892  	users, resp = th.Client.SearchUsers(search)
   893  	CheckNoError(t, resp)
   894  
   895  	if findUserInList(th.BasicUser2.Id, users) {
   896  		t.Fatal("should not have found user")
   897  	}
   898  
   899  	search.Term = th.BasicUser.FirstName
   900  	search.InChannelId = th.BasicChannel.Id
   901  	search.NotInChannelId = th.BasicChannel.Id
   902  	search.TeamId = th.BasicTeam.Id
   903  	users, resp = th.SystemAdminClient.SearchUsers(search)
   904  	CheckNoError(t, resp)
   905  
   906  	if !findUserInList(th.BasicUser.Id, users) {
   907  		t.Fatal("should have found user")
   908  	}
   909  }
   910  
   911  func findUserInList(id string, users []*model.User) bool {
   912  	for _, user := range users {
   913  		if user.Id == id {
   914  			return true
   915  		}
   916  	}
   917  	return false
   918  }
   919  
   920  func TestAutocompleteUsers(t *testing.T) {
   921  	th := Setup().InitBasic()
   922  	defer th.TearDown()
   923  	teamId := th.BasicTeam.Id
   924  	channelId := th.BasicChannel.Id
   925  	username := th.BasicUser.Username
   926  
   927  	rusers, resp := th.Client.AutocompleteUsersInChannel(teamId, channelId, username, model.USER_SEARCH_DEFAULT_LIMIT, "")
   928  	CheckNoError(t, resp)
   929  
   930  	if len(rusers.Users) != 1 {
   931  		t.Fatal("should have returned 1 user")
   932  	}
   933  
   934  	rusers, resp = th.Client.AutocompleteUsersInChannel(teamId, channelId, "amazonses", model.USER_SEARCH_DEFAULT_LIMIT, "")
   935  	CheckNoError(t, resp)
   936  	if len(rusers.Users) != 0 {
   937  		t.Fatal("should have returned 0 users")
   938  	}
   939  
   940  	rusers, resp = th.Client.AutocompleteUsersInChannel(teamId, channelId, "", model.USER_SEARCH_DEFAULT_LIMIT, "")
   941  	CheckNoError(t, resp)
   942  	if len(rusers.Users) < 2 {
   943  		t.Fatal("should have many users")
   944  	}
   945  
   946  	rusers, resp = th.Client.AutocompleteUsersInChannel("", channelId, "", model.USER_SEARCH_DEFAULT_LIMIT, "")
   947  	CheckNoError(t, resp)
   948  	if len(rusers.Users) < 2 {
   949  		t.Fatal("should have many users")
   950  	}
   951  
   952  	rusers, resp = th.Client.AutocompleteUsersInTeam(teamId, username, model.USER_SEARCH_DEFAULT_LIMIT, "")
   953  	CheckNoError(t, resp)
   954  
   955  	if len(rusers.Users) != 1 {
   956  		t.Fatal("should have returned 1 user")
   957  	}
   958  
   959  	rusers, resp = th.Client.AutocompleteUsers(username, model.USER_SEARCH_DEFAULT_LIMIT, "")
   960  	CheckNoError(t, resp)
   961  
   962  	if len(rusers.Users) != 1 {
   963  		t.Fatal("should have returned 1 users")
   964  	}
   965  
   966  	rusers, resp = th.Client.AutocompleteUsers("", model.USER_SEARCH_DEFAULT_LIMIT, "")
   967  	CheckNoError(t, resp)
   968  
   969  	if len(rusers.Users) < 2 {
   970  		t.Fatal("should have returned many users")
   971  	}
   972  
   973  	rusers, resp = th.Client.AutocompleteUsersInTeam(teamId, "amazonses", model.USER_SEARCH_DEFAULT_LIMIT, "")
   974  	CheckNoError(t, resp)
   975  	if len(rusers.Users) != 0 {
   976  		t.Fatal("should have returned 0 users")
   977  	}
   978  
   979  	rusers, resp = th.Client.AutocompleteUsersInTeam(teamId, "", model.USER_SEARCH_DEFAULT_LIMIT, "")
   980  	CheckNoError(t, resp)
   981  	if len(rusers.Users) < 2 {
   982  		t.Fatal("should have many users")
   983  	}
   984  
   985  	th.Client.Logout()
   986  	_, resp = th.Client.AutocompleteUsersInChannel(teamId, channelId, username, model.USER_SEARCH_DEFAULT_LIMIT, "")
   987  	CheckUnauthorizedStatus(t, resp)
   988  
   989  	_, resp = th.Client.AutocompleteUsersInTeam(teamId, username, model.USER_SEARCH_DEFAULT_LIMIT, "")
   990  	CheckUnauthorizedStatus(t, resp)
   991  
   992  	_, resp = th.Client.AutocompleteUsers(username, model.USER_SEARCH_DEFAULT_LIMIT, "")
   993  	CheckUnauthorizedStatus(t, resp)
   994  
   995  	user := th.CreateUser()
   996  	th.Client.Login(user.Email, user.Password)
   997  	_, resp = th.Client.AutocompleteUsersInChannel(teamId, channelId, username, model.USER_SEARCH_DEFAULT_LIMIT, "")
   998  	CheckForbiddenStatus(t, resp)
   999  
  1000  	_, resp = th.Client.AutocompleteUsersInTeam(teamId, username, model.USER_SEARCH_DEFAULT_LIMIT, "")
  1001  	CheckForbiddenStatus(t, resp)
  1002  
  1003  	_, resp = th.Client.AutocompleteUsers(username, model.USER_SEARCH_DEFAULT_LIMIT, "")
  1004  	CheckNoError(t, resp)
  1005  
  1006  	_, resp = th.SystemAdminClient.AutocompleteUsersInChannel(teamId, channelId, username, model.USER_SEARCH_DEFAULT_LIMIT, "")
  1007  	CheckNoError(t, resp)
  1008  
  1009  	_, resp = th.SystemAdminClient.AutocompleteUsersInTeam(teamId, username, model.USER_SEARCH_DEFAULT_LIMIT, "")
  1010  	CheckNoError(t, resp)
  1011  
  1012  	_, resp = th.SystemAdminClient.AutocompleteUsers(username, model.USER_SEARCH_DEFAULT_LIMIT, "")
  1013  	CheckNoError(t, resp)
  1014  
  1015  	// Check against privacy config settings
  1016  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowFullName = false })
  1017  
  1018  	th.LoginBasic()
  1019  
  1020  	rusers, resp = th.Client.AutocompleteUsers(username, model.USER_SEARCH_DEFAULT_LIMIT, "")
  1021  	CheckNoError(t, resp)
  1022  
  1023  	if rusers.Users[0].FirstName != "" || rusers.Users[0].LastName != "" {
  1024  		t.Fatal("should not show first/last name")
  1025  	}
  1026  
  1027  	rusers, resp = th.Client.AutocompleteUsersInChannel(teamId, channelId, username, model.USER_SEARCH_DEFAULT_LIMIT, "")
  1028  	CheckNoError(t, resp)
  1029  
  1030  	if rusers.Users[0].FirstName != "" || rusers.Users[0].LastName != "" {
  1031  		t.Fatal("should not show first/last name")
  1032  	}
  1033  
  1034  	rusers, resp = th.Client.AutocompleteUsersInTeam(teamId, username, model.USER_SEARCH_DEFAULT_LIMIT, "")
  1035  	CheckNoError(t, resp)
  1036  
  1037  	if rusers.Users[0].FirstName != "" || rusers.Users[0].LastName != "" {
  1038  		t.Fatal("should not show first/last name")
  1039  	}
  1040  
  1041  	t.Run("user must have access to team id, especially when it does not match channel's team id", func(t *testing.T) {
  1042  		rusers, resp = th.Client.AutocompleteUsersInChannel("otherTeamId", channelId, username, model.USER_SEARCH_DEFAULT_LIMIT, "")
  1043  		CheckErrorMessage(t, resp, "api.context.permissions.app_error")
  1044  	})
  1045  }
  1046  
  1047  func TestGetProfileImage(t *testing.T) {
  1048  	th := Setup().InitBasic()
  1049  	defer th.TearDown()
  1050  	user := th.BasicUser
  1051  
  1052  	data, resp := th.Client.GetProfileImage(user.Id, "")
  1053  	CheckNoError(t, resp)
  1054  	if len(data) == 0 {
  1055  		t.Fatal("Should not be empty")
  1056  	}
  1057  
  1058  	_, resp = th.Client.GetProfileImage(user.Id, resp.Etag)
  1059  	if resp.StatusCode == http.StatusNotModified {
  1060  		t.Fatal("Shouldn't have hit etag")
  1061  	}
  1062  
  1063  	_, resp = th.Client.GetProfileImage("junk", "")
  1064  	CheckBadRequestStatus(t, resp)
  1065  
  1066  	_, resp = th.Client.GetProfileImage(model.NewId(), "")
  1067  	CheckNotFoundStatus(t, resp)
  1068  
  1069  	th.Client.Logout()
  1070  	_, resp = th.Client.GetProfileImage(user.Id, "")
  1071  	CheckUnauthorizedStatus(t, resp)
  1072  
  1073  	_, resp = th.SystemAdminClient.GetProfileImage(user.Id, "")
  1074  	CheckNoError(t, resp)
  1075  
  1076  	info := &model.FileInfo{Path: "/users/" + user.Id + "/profile.png"}
  1077  	if err := th.cleanupTestFile(info); err != nil {
  1078  		t.Fatal(err)
  1079  	}
  1080  }
  1081  
  1082  func TestGetUsersByIds(t *testing.T) {
  1083  	th := Setup().InitBasic()
  1084  	defer th.TearDown()
  1085  
  1086  	users, resp := th.Client.GetUsersByIds([]string{th.BasicUser.Id})
  1087  	CheckNoError(t, resp)
  1088  
  1089  	if users[0].Id != th.BasicUser.Id {
  1090  		t.Fatal("returned wrong user")
  1091  	}
  1092  	CheckUserSanitization(t, users[0])
  1093  
  1094  	_, resp = th.Client.GetUsersByIds([]string{})
  1095  	CheckBadRequestStatus(t, resp)
  1096  
  1097  	users, resp = th.Client.GetUsersByIds([]string{"junk"})
  1098  	CheckNoError(t, resp)
  1099  	if len(users) > 0 {
  1100  		t.Fatal("no users should be returned")
  1101  	}
  1102  
  1103  	users, resp = th.Client.GetUsersByIds([]string{"junk", th.BasicUser.Id})
  1104  	CheckNoError(t, resp)
  1105  	if len(users) != 1 {
  1106  		t.Fatal("1 user should be returned")
  1107  	}
  1108  
  1109  	th.Client.Logout()
  1110  	_, resp = th.Client.GetUsersByIds([]string{th.BasicUser.Id})
  1111  	CheckUnauthorizedStatus(t, resp)
  1112  }
  1113  
  1114  func TestGetUsersByUsernames(t *testing.T) {
  1115  	th := Setup().InitBasic()
  1116  	defer th.TearDown()
  1117  
  1118  	users, resp := th.Client.GetUsersByUsernames([]string{th.BasicUser.Username})
  1119  	CheckNoError(t, resp)
  1120  
  1121  	if users[0].Id != th.BasicUser.Id {
  1122  		t.Fatal("returned wrong user")
  1123  	}
  1124  	CheckUserSanitization(t, users[0])
  1125  
  1126  	_, resp = th.Client.GetUsersByIds([]string{})
  1127  	CheckBadRequestStatus(t, resp)
  1128  
  1129  	users, resp = th.Client.GetUsersByUsernames([]string{"junk"})
  1130  	CheckNoError(t, resp)
  1131  	if len(users) > 0 {
  1132  		t.Fatal("no users should be returned")
  1133  	}
  1134  
  1135  	users, resp = th.Client.GetUsersByUsernames([]string{"junk", th.BasicUser.Username})
  1136  	CheckNoError(t, resp)
  1137  	if len(users) != 1 {
  1138  		t.Fatal("1 user should be returned")
  1139  	}
  1140  
  1141  	th.Client.Logout()
  1142  	_, resp = th.Client.GetUsersByUsernames([]string{th.BasicUser.Username})
  1143  	CheckUnauthorizedStatus(t, resp)
  1144  }
  1145  
  1146  func TestGetTotalUsersStat(t *testing.T) {
  1147  	th := Setup().InitBasic()
  1148  	defer th.TearDown()
  1149  
  1150  	total := <-th.Server.Store.User().Count(model.UserCountOptions{
  1151  		IncludeDeleted:     false,
  1152  		IncludeBotAccounts: true,
  1153  	})
  1154  
  1155  	rstats, resp := th.Client.GetTotalUsersStats("")
  1156  	CheckNoError(t, resp)
  1157  
  1158  	if rstats.TotalUsersCount != total.Data.(int64) {
  1159  		t.Fatal("wrong count")
  1160  	}
  1161  }
  1162  
  1163  func TestUpdateUser(t *testing.T) {
  1164  	th := Setup().InitBasic()
  1165  	defer th.TearDown()
  1166  
  1167  	user := th.CreateUser()
  1168  	th.Client.Login(user.Email, user.Password)
  1169  
  1170  	user.Nickname = "Joram Wilander"
  1171  	user.Roles = model.SYSTEM_ADMIN_ROLE_ID
  1172  	user.LastPasswordUpdate = 123
  1173  
  1174  	ruser, resp := th.Client.UpdateUser(user)
  1175  	CheckNoError(t, resp)
  1176  	CheckUserSanitization(t, ruser)
  1177  
  1178  	if ruser.Nickname != "Joram Wilander" {
  1179  		t.Fatal("Nickname did not update properly")
  1180  	}
  1181  	if ruser.Roles != model.SYSTEM_USER_ROLE_ID {
  1182  		t.Fatal("Roles should not have updated")
  1183  	}
  1184  	if ruser.LastPasswordUpdate == 123 {
  1185  		t.Fatal("LastPasswordUpdate should not have updated")
  1186  	}
  1187  
  1188  	ruser.Email = th.GenerateTestEmail()
  1189  	_, resp = th.Client.UpdateUser(ruser)
  1190  	CheckBadRequestStatus(t, resp)
  1191  
  1192  	ruser.Password = user.Password
  1193  	ruser, resp = th.Client.UpdateUser(ruser)
  1194  	CheckNoError(t, resp)
  1195  	CheckUserSanitization(t, ruser)
  1196  
  1197  	ruser.Id = "junk"
  1198  	_, resp = th.Client.UpdateUser(ruser)
  1199  	CheckBadRequestStatus(t, resp)
  1200  
  1201  	ruser.Id = model.NewId()
  1202  	_, resp = th.Client.UpdateUser(ruser)
  1203  	CheckForbiddenStatus(t, resp)
  1204  
  1205  	if r, err := th.Client.DoApiPut("/users/"+ruser.Id, "garbage"); err == nil {
  1206  		t.Fatal("should have errored")
  1207  	} else {
  1208  		if r.StatusCode != http.StatusBadRequest {
  1209  			t.Log("actual: " + strconv.Itoa(r.StatusCode))
  1210  			t.Log("expected: " + strconv.Itoa(http.StatusBadRequest))
  1211  			t.Fatal("wrong status code")
  1212  		}
  1213  	}
  1214  
  1215  	session, _ := th.App.GetSession(th.Client.AuthToken)
  1216  	session.IsOAuth = true
  1217  	th.App.AddSessionToCache(session)
  1218  
  1219  	ruser.Id = user.Id
  1220  	ruser.Email = th.GenerateTestEmail()
  1221  	_, resp = th.Client.UpdateUser(ruser)
  1222  	CheckForbiddenStatus(t, resp)
  1223  
  1224  	th.Client.Logout()
  1225  	_, resp = th.Client.UpdateUser(user)
  1226  	CheckUnauthorizedStatus(t, resp)
  1227  
  1228  	th.LoginBasic()
  1229  	_, resp = th.Client.UpdateUser(user)
  1230  	CheckForbiddenStatus(t, resp)
  1231  
  1232  	_, resp = th.SystemAdminClient.UpdateUser(user)
  1233  	CheckNoError(t, resp)
  1234  }
  1235  
  1236  func TestPatchUser(t *testing.T) {
  1237  	th := Setup().InitBasic()
  1238  	defer th.TearDown()
  1239  
  1240  	user := th.CreateUser()
  1241  	th.Client.Login(user.Email, user.Password)
  1242  
  1243  	patch := &model.UserPatch{}
  1244  	patch.Password = model.NewString("testpassword")
  1245  	patch.Nickname = model.NewString("Joram Wilander")
  1246  	patch.FirstName = model.NewString("Joram")
  1247  	patch.LastName = model.NewString("Wilander")
  1248  	patch.Position = new(string)
  1249  	patch.NotifyProps = model.StringMap{}
  1250  	patch.NotifyProps["comment"] = "somethingrandom"
  1251  	patch.Timezone = model.StringMap{}
  1252  	patch.Timezone["useAutomaticTimezone"] = "true"
  1253  	patch.Timezone["automaticTimezone"] = "America/New_York"
  1254  	patch.Timezone["manualTimezone"] = ""
  1255  
  1256  	ruser, resp := th.Client.PatchUser(user.Id, patch)
  1257  	CheckNoError(t, resp)
  1258  	CheckUserSanitization(t, ruser)
  1259  
  1260  	if ruser.Nickname != "Joram Wilander" {
  1261  		t.Fatal("Nickname did not update properly")
  1262  	}
  1263  	if ruser.FirstName != "Joram" {
  1264  		t.Fatal("FirstName did not update properly")
  1265  	}
  1266  	if ruser.LastName != "Wilander" {
  1267  		t.Fatal("LastName did not update properly")
  1268  	}
  1269  	if ruser.Position != "" {
  1270  		t.Fatal("Position did not update properly")
  1271  	}
  1272  	if ruser.Username != user.Username {
  1273  		t.Fatal("Username should not have updated")
  1274  	}
  1275  	if ruser.Password != "" {
  1276  		t.Fatal("Password should not be returned")
  1277  	}
  1278  	if ruser.NotifyProps["comment"] != "somethingrandom" {
  1279  		t.Fatal("NotifyProps did not update properly")
  1280  	}
  1281  	if ruser.Timezone["useAutomaticTimezone"] != "true" {
  1282  		t.Fatal("useAutomaticTimezone did not update properly")
  1283  	}
  1284  	if ruser.Timezone["automaticTimezone"] != "America/New_York" {
  1285  		t.Fatal("automaticTimezone did not update properly")
  1286  	}
  1287  	if ruser.Timezone["manualTimezone"] != "" {
  1288  		t.Fatal("manualTimezone did not update properly")
  1289  	}
  1290  
  1291  	err := th.App.CheckPasswordAndAllCriteria(ruser, *patch.Password, "")
  1292  	assert.Error(t, err, "Password should not match")
  1293  
  1294  	currentPassword := user.Password
  1295  	user, err = th.App.GetUser(ruser.Id)
  1296  	if err != nil {
  1297  		t.Fatal("User Get shouldn't error")
  1298  	}
  1299  
  1300  	err = th.App.CheckPasswordAndAllCriteria(user, currentPassword, "")
  1301  	if err != nil {
  1302  		t.Fatal("Password should still match")
  1303  	}
  1304  
  1305  	patch = &model.UserPatch{}
  1306  	patch.Email = model.NewString(th.GenerateTestEmail())
  1307  
  1308  	_, resp = th.Client.PatchUser(user.Id, patch)
  1309  	CheckBadRequestStatus(t, resp)
  1310  
  1311  	patch.Password = model.NewString(currentPassword)
  1312  	ruser, resp = th.Client.PatchUser(user.Id, patch)
  1313  	CheckNoError(t, resp)
  1314  
  1315  	if ruser.Email != *patch.Email {
  1316  		t.Fatal("Email did not update properly")
  1317  	}
  1318  
  1319  	patch.Username = model.NewString(th.BasicUser2.Username)
  1320  	_, resp = th.Client.PatchUser(user.Id, patch)
  1321  	CheckBadRequestStatus(t, resp)
  1322  
  1323  	patch.Username = nil
  1324  
  1325  	_, resp = th.Client.PatchUser("junk", patch)
  1326  	CheckBadRequestStatus(t, resp)
  1327  
  1328  	ruser.Id = model.NewId()
  1329  	_, resp = th.Client.PatchUser(model.NewId(), patch)
  1330  	CheckForbiddenStatus(t, resp)
  1331  
  1332  	if r, err := th.Client.DoApiPut("/users/"+user.Id+"/patch", "garbage"); err == nil {
  1333  		t.Fatal("should have errored")
  1334  	} else {
  1335  		if r.StatusCode != http.StatusBadRequest {
  1336  			t.Log("actual: " + strconv.Itoa(r.StatusCode))
  1337  			t.Log("expected: " + strconv.Itoa(http.StatusBadRequest))
  1338  			t.Fatal("wrong status code")
  1339  		}
  1340  	}
  1341  
  1342  	session, _ := th.App.GetSession(th.Client.AuthToken)
  1343  	session.IsOAuth = true
  1344  	th.App.AddSessionToCache(session)
  1345  
  1346  	patch.Email = model.NewString(th.GenerateTestEmail())
  1347  	_, resp = th.Client.PatchUser(user.Id, patch)
  1348  	CheckForbiddenStatus(t, resp)
  1349  
  1350  	th.Client.Logout()
  1351  	_, resp = th.Client.PatchUser(user.Id, patch)
  1352  	CheckUnauthorizedStatus(t, resp)
  1353  
  1354  	th.LoginBasic()
  1355  	_, resp = th.Client.PatchUser(user.Id, patch)
  1356  	CheckForbiddenStatus(t, resp)
  1357  
  1358  	_, resp = th.SystemAdminClient.PatchUser(user.Id, patch)
  1359  	CheckNoError(t, resp)
  1360  }
  1361  
  1362  func TestUpdateUserAuth(t *testing.T) {
  1363  	th := Setup().InitBasic()
  1364  	defer th.TearDown()
  1365  
  1366  	team := th.CreateTeamWithClient(th.SystemAdminClient)
  1367  
  1368  	user := th.CreateUser()
  1369  
  1370  	th.LinkUserToTeam(user, team)
  1371  	store.Must(th.App.Srv.Store.User().VerifyEmail(user.Id, user.Email))
  1372  
  1373  	userAuth := &model.UserAuth{}
  1374  	userAuth.AuthData = user.AuthData
  1375  	userAuth.AuthService = user.AuthService
  1376  	userAuth.Password = user.Password
  1377  
  1378  	// Regular user can not use endpoint
  1379  	if _, err := th.SystemAdminClient.UpdateUserAuth(user.Id, userAuth); err == nil {
  1380  		t.Fatal("Shouldn't have permissions. Only Admins")
  1381  	}
  1382  
  1383  	userAuth.AuthData = model.NewString("test@test.com")
  1384  	userAuth.AuthService = model.USER_AUTH_SERVICE_SAML
  1385  	userAuth.Password = "newpassword"
  1386  	ruser, resp := th.SystemAdminClient.UpdateUserAuth(user.Id, userAuth)
  1387  	CheckNoError(t, resp)
  1388  
  1389  	// AuthData and AuthService are set, password is set to empty
  1390  	if *ruser.AuthData != *userAuth.AuthData {
  1391  		t.Fatal("Should have set the correct AuthData")
  1392  	}
  1393  	if ruser.AuthService != model.USER_AUTH_SERVICE_SAML {
  1394  		t.Fatal("Should have set the correct AuthService")
  1395  	}
  1396  	if ruser.Password != "" {
  1397  		t.Fatal("Password should be empty")
  1398  	}
  1399  
  1400  	// When AuthData or AuthService are empty, password must be valid
  1401  	userAuth.AuthData = user.AuthData
  1402  	userAuth.AuthService = ""
  1403  	userAuth.Password = "1"
  1404  	if _, err := th.SystemAdminClient.UpdateUserAuth(user.Id, userAuth); err == nil {
  1405  		t.Fatal("Should have errored - user password not valid")
  1406  	}
  1407  
  1408  	// Regular user can not use endpoint
  1409  	user2 := th.CreateUser()
  1410  	th.LinkUserToTeam(user2, team)
  1411  	store.Must(th.App.Srv.Store.User().VerifyEmail(user2.Id, user2.Email))
  1412  
  1413  	th.SystemAdminClient.Login(user2.Email, "passwd1")
  1414  
  1415  	userAuth.AuthData = user.AuthData
  1416  	userAuth.AuthService = user.AuthService
  1417  	userAuth.Password = user.Password
  1418  	if _, err := th.SystemAdminClient.UpdateUserAuth(user.Id, userAuth); err == nil {
  1419  		t.Fatal("Should have errored")
  1420  	}
  1421  }
  1422  
  1423  func TestDeleteUser(t *testing.T) {
  1424  	th := Setup().InitBasic()
  1425  	defer th.TearDown()
  1426  
  1427  	user := th.BasicUser
  1428  	th.LoginBasic()
  1429  
  1430  	testUser := th.SystemAdminUser
  1431  	_, resp := th.Client.DeleteUser(testUser.Id)
  1432  	CheckForbiddenStatus(t, resp)
  1433  
  1434  	th.Client.Logout()
  1435  
  1436  	_, resp = th.Client.DeleteUser(user.Id)
  1437  	CheckUnauthorizedStatus(t, resp)
  1438  
  1439  	th.Client.Login(testUser.Email, testUser.Password)
  1440  
  1441  	user.Id = model.NewId()
  1442  	_, resp = th.Client.DeleteUser(user.Id)
  1443  	CheckNotFoundStatus(t, resp)
  1444  
  1445  	user.Id = "junk"
  1446  	_, resp = th.Client.DeleteUser(user.Id)
  1447  	CheckBadRequestStatus(t, resp)
  1448  
  1449  	_, resp = th.Client.DeleteUser(testUser.Id)
  1450  	CheckNoError(t, resp)
  1451  
  1452  	selfDeleteUser := th.CreateUser()
  1453  	th.Client.Login(selfDeleteUser.Email, selfDeleteUser.Password)
  1454  
  1455  	th.App.UpdateConfig(func(c *model.Config) {
  1456  		*c.TeamSettings.EnableUserDeactivation = false
  1457  	})
  1458  	_, resp = th.Client.DeleteUser(selfDeleteUser.Id)
  1459  	CheckUnauthorizedStatus(t, resp)
  1460  
  1461  	th.App.UpdateConfig(func(c *model.Config) {
  1462  		*c.TeamSettings.EnableUserDeactivation = true
  1463  	})
  1464  	_, resp = th.Client.DeleteUser(selfDeleteUser.Id)
  1465  	CheckNoError(t, resp)
  1466  }
  1467  
  1468  func TestUpdateUserRoles(t *testing.T) {
  1469  	th := Setup().InitBasic()
  1470  	defer th.TearDown()
  1471  
  1472  	_, resp := th.Client.UpdateUserRoles(th.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID)
  1473  	CheckForbiddenStatus(t, resp)
  1474  
  1475  	_, resp = th.SystemAdminClient.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID)
  1476  	CheckNoError(t, resp)
  1477  
  1478  	_, resp = th.SystemAdminClient.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID)
  1479  	CheckNoError(t, resp)
  1480  
  1481  	_, resp = th.SystemAdminClient.UpdateUserRoles(th.BasicUser.Id, "junk")
  1482  	CheckBadRequestStatus(t, resp)
  1483  
  1484  	_, resp = th.SystemAdminClient.UpdateUserRoles("junk", model.SYSTEM_USER_ROLE_ID)
  1485  	CheckBadRequestStatus(t, resp)
  1486  
  1487  	_, resp = th.SystemAdminClient.UpdateUserRoles(model.NewId(), model.SYSTEM_USER_ROLE_ID)
  1488  	CheckBadRequestStatus(t, resp)
  1489  }
  1490  
  1491  func assertExpectedWebsocketEvent(t *testing.T, client *model.WebSocketClient, event string, test func(*model.WebSocketEvent)) {
  1492  	for {
  1493  		select {
  1494  		case resp, ok := <-client.EventChannel:
  1495  			if !ok {
  1496  				t.Fatalf("channel closed before receiving expected event %s", model.WEBSOCKET_EVENT_USER_UPDATED)
  1497  			} else if resp.Event == model.WEBSOCKET_EVENT_USER_UPDATED {
  1498  				test(resp)
  1499  				return
  1500  			}
  1501  		case <-time.After(5 * time.Second):
  1502  			t.Fatalf("failed to receive expected event %s", model.WEBSOCKET_EVENT_USER_UPDATED)
  1503  		}
  1504  	}
  1505  }
  1506  
  1507  func assertWebsocketEventUserUpdatedWithEmail(t *testing.T, client *model.WebSocketClient, email string) {
  1508  	assertExpectedWebsocketEvent(t, client, model.WEBSOCKET_EVENT_USER_UPDATED, func(event *model.WebSocketEvent) {
  1509  		if eventUser, ok := event.Data["user"].(map[string]interface{}); !ok {
  1510  			t.Fatalf("expected user")
  1511  		} else if userEmail, ok := eventUser["email"].(string); !ok {
  1512  			t.Fatalf("expected email %s, but got nil", email)
  1513  		} else {
  1514  			assert.Equal(t, email, userEmail)
  1515  		}
  1516  	})
  1517  }
  1518  
  1519  func TestUpdateUserActive(t *testing.T) {
  1520  	t.Run("basic tests", func(t *testing.T) {
  1521  		th := Setup().InitBasic()
  1522  		defer th.TearDown()
  1523  
  1524  		user := th.BasicUser
  1525  
  1526  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableUserDeactivation = true })
  1527  		pass, resp := th.Client.UpdateUserActive(user.Id, false)
  1528  		CheckNoError(t, resp)
  1529  
  1530  		if !pass {
  1531  			t.Fatal("should have returned true")
  1532  		}
  1533  
  1534  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableUserDeactivation = false })
  1535  		pass, resp = th.Client.UpdateUserActive(user.Id, false)
  1536  		CheckUnauthorizedStatus(t, resp)
  1537  
  1538  		if pass {
  1539  			t.Fatal("should have returned false")
  1540  		}
  1541  
  1542  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableUserDeactivation = true })
  1543  		pass, resp = th.Client.UpdateUserActive(user.Id, false)
  1544  		CheckUnauthorizedStatus(t, resp)
  1545  
  1546  		if pass {
  1547  			t.Fatal("should have returned false")
  1548  		}
  1549  
  1550  		th.LoginBasic2()
  1551  
  1552  		_, resp = th.Client.UpdateUserActive(user.Id, true)
  1553  		CheckForbiddenStatus(t, resp)
  1554  
  1555  		_, resp = th.Client.UpdateUserActive(GenerateTestId(), true)
  1556  		CheckForbiddenStatus(t, resp)
  1557  
  1558  		_, resp = th.Client.UpdateUserActive("junk", true)
  1559  		CheckBadRequestStatus(t, resp)
  1560  
  1561  		th.Client.Logout()
  1562  
  1563  		_, resp = th.Client.UpdateUserActive(user.Id, true)
  1564  		CheckUnauthorizedStatus(t, resp)
  1565  
  1566  		_, resp = th.SystemAdminClient.UpdateUserActive(user.Id, true)
  1567  		CheckNoError(t, resp)
  1568  
  1569  		_, resp = th.SystemAdminClient.UpdateUserActive(user.Id, false)
  1570  		CheckNoError(t, resp)
  1571  
  1572  		authData := model.NewId()
  1573  		result := <-th.App.Srv.Store.User().UpdateAuthData(user.Id, "random", &authData, "", true)
  1574  		require.Nil(t, result.Err)
  1575  
  1576  		_, resp = th.SystemAdminClient.UpdateUserActive(user.Id, false)
  1577  		CheckNoError(t, resp)
  1578  	})
  1579  
  1580  	t.Run("websocket events", func(t *testing.T) {
  1581  		th := Setup().InitBasic()
  1582  		defer th.TearDown()
  1583  
  1584  		user := th.BasicUser2
  1585  
  1586  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableUserDeactivation = true })
  1587  
  1588  		webSocketClient, err := th.CreateWebSocketClient()
  1589  		assert.Nil(t, err)
  1590  		defer webSocketClient.Close()
  1591  
  1592  		webSocketClient.Listen()
  1593  
  1594  		time.Sleep(300 * time.Millisecond)
  1595  		if resp := <-webSocketClient.ResponseChannel; resp.Status != model.STATUS_OK {
  1596  			t.Fatal("should have responded OK to authentication challenge")
  1597  		}
  1598  
  1599  		adminWebSocketClient, err := th.CreateWebSocketSystemAdminClient()
  1600  		assert.Nil(t, err)
  1601  		defer adminWebSocketClient.Close()
  1602  
  1603  		adminWebSocketClient.Listen()
  1604  
  1605  		time.Sleep(300 * time.Millisecond)
  1606  		if resp := <-adminWebSocketClient.ResponseChannel; resp.Status != model.STATUS_OK {
  1607  			t.Fatal("should have responded OK to authentication challenge")
  1608  		}
  1609  
  1610  		// Verify that both admins and regular users see the email when privacy settings allow same.
  1611  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowEmailAddress = true })
  1612  		_, resp := th.SystemAdminClient.UpdateUserActive(user.Id, false)
  1613  		CheckNoError(t, resp)
  1614  
  1615  		assertWebsocketEventUserUpdatedWithEmail(t, webSocketClient, user.Email)
  1616  		assertWebsocketEventUserUpdatedWithEmail(t, adminWebSocketClient, user.Email)
  1617  
  1618  		// Verify that only admins see the email when privacy settings hide emails.
  1619  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowEmailAddress = false })
  1620  		_, resp = th.SystemAdminClient.UpdateUserActive(user.Id, true)
  1621  		CheckNoError(t, resp)
  1622  
  1623  		assertWebsocketEventUserUpdatedWithEmail(t, webSocketClient, "")
  1624  		assertWebsocketEventUserUpdatedWithEmail(t, adminWebSocketClient, user.Email)
  1625  	})
  1626  }
  1627  
  1628  func TestGetUsers(t *testing.T) {
  1629  	th := Setup().InitBasic()
  1630  	defer th.TearDown()
  1631  
  1632  	rusers, resp := th.Client.GetUsers(0, 60, "")
  1633  	CheckNoError(t, resp)
  1634  	for _, u := range rusers {
  1635  		CheckUserSanitization(t, u)
  1636  	}
  1637  
  1638  	rusers, resp = th.Client.GetUsers(0, 60, resp.Etag)
  1639  	CheckEtag(t, rusers, resp)
  1640  
  1641  	rusers, resp = th.Client.GetUsers(0, 1, "")
  1642  	CheckNoError(t, resp)
  1643  	if len(rusers) != 1 {
  1644  		t.Fatal("should be 1 per page")
  1645  	}
  1646  
  1647  	rusers, resp = th.Client.GetUsers(1, 1, "")
  1648  	CheckNoError(t, resp)
  1649  	if len(rusers) != 1 {
  1650  		t.Fatal("should be 1 per page")
  1651  	}
  1652  
  1653  	rusers, resp = th.Client.GetUsers(10000, 100, "")
  1654  	CheckNoError(t, resp)
  1655  	if len(rusers) != 0 {
  1656  		t.Fatal("should be no users")
  1657  	}
  1658  
  1659  	// Check default params for page and per_page
  1660  	if _, err := th.Client.DoApiGet("/users", ""); err != nil {
  1661  		t.Fatal("should not have errored")
  1662  	}
  1663  
  1664  	th.Client.Logout()
  1665  	_, resp = th.Client.GetUsers(0, 60, "")
  1666  	CheckUnauthorizedStatus(t, resp)
  1667  }
  1668  
  1669  func TestGetNewUsersInTeam(t *testing.T) {
  1670  	th := Setup().InitBasic()
  1671  	defer th.TearDown()
  1672  	teamId := th.BasicTeam.Id
  1673  
  1674  	rusers, resp := th.Client.GetNewUsersInTeam(teamId, 0, 60, "")
  1675  	CheckNoError(t, resp)
  1676  
  1677  	lastCreateAt := model.GetMillis()
  1678  	for _, u := range rusers {
  1679  		if u.CreateAt > lastCreateAt {
  1680  			t.Fatal("bad sorting")
  1681  		}
  1682  		lastCreateAt = u.CreateAt
  1683  		CheckUserSanitization(t, u)
  1684  	}
  1685  
  1686  	rusers, resp = th.Client.GetNewUsersInTeam(teamId, 1, 1, "")
  1687  	CheckNoError(t, resp)
  1688  	if len(rusers) != 1 {
  1689  		t.Fatal("should be 1 per page")
  1690  	}
  1691  
  1692  	th.Client.Logout()
  1693  	_, resp = th.Client.GetNewUsersInTeam(teamId, 1, 1, "")
  1694  	CheckUnauthorizedStatus(t, resp)
  1695  }
  1696  
  1697  func TestGetRecentlyActiveUsersInTeam(t *testing.T) {
  1698  	th := Setup().InitBasic()
  1699  	defer th.TearDown()
  1700  	teamId := th.BasicTeam.Id
  1701  
  1702  	th.App.SetStatusOnline(th.BasicUser.Id, true)
  1703  
  1704  	rusers, resp := th.Client.GetRecentlyActiveUsersInTeam(teamId, 0, 60, "")
  1705  	CheckNoError(t, resp)
  1706  
  1707  	for _, u := range rusers {
  1708  		if u.LastActivityAt == 0 {
  1709  			t.Fatal("did not return last activity at")
  1710  		}
  1711  		CheckUserSanitization(t, u)
  1712  	}
  1713  
  1714  	rusers, resp = th.Client.GetRecentlyActiveUsersInTeam(teamId, 0, 1, "")
  1715  	CheckNoError(t, resp)
  1716  	if len(rusers) != 1 {
  1717  		t.Fatal("should be 1 per page")
  1718  	}
  1719  
  1720  	th.Client.Logout()
  1721  	_, resp = th.Client.GetRecentlyActiveUsersInTeam(teamId, 0, 1, "")
  1722  	CheckUnauthorizedStatus(t, resp)
  1723  }
  1724  
  1725  func TestGetUsersWithoutTeam(t *testing.T) {
  1726  	th := Setup().InitBasic()
  1727  	defer th.TearDown()
  1728  
  1729  	if _, resp := th.Client.GetUsersWithoutTeam(0, 100, ""); resp.Error == nil {
  1730  		t.Fatal("should prevent non-admin user from getting users without a team")
  1731  	}
  1732  
  1733  	// These usernames need to appear in the first 100 users for this to work
  1734  
  1735  	user, resp := th.Client.CreateUser(&model.User{
  1736  		Username: "a000000000" + model.NewId(),
  1737  		Email:    "success+" + model.NewId() + "@simulator.amazonses.com",
  1738  		Password: "Password1",
  1739  	})
  1740  	CheckNoError(t, resp)
  1741  	th.LinkUserToTeam(user, th.BasicTeam)
  1742  	defer th.App.Srv.Store.User().PermanentDelete(user.Id)
  1743  
  1744  	user2, resp := th.Client.CreateUser(&model.User{
  1745  		Username: "a000000001" + model.NewId(),
  1746  		Email:    "success+" + model.NewId() + "@simulator.amazonses.com",
  1747  		Password: "Password1",
  1748  	})
  1749  	CheckNoError(t, resp)
  1750  	defer th.App.Srv.Store.User().PermanentDelete(user2.Id)
  1751  
  1752  	rusers, resp := th.SystemAdminClient.GetUsersWithoutTeam(0, 100, "")
  1753  	CheckNoError(t, resp)
  1754  
  1755  	found1 := false
  1756  	found2 := false
  1757  
  1758  	for _, u := range rusers {
  1759  		if u.Id == user.Id {
  1760  			found1 = true
  1761  		} else if u.Id == user2.Id {
  1762  			found2 = true
  1763  		}
  1764  	}
  1765  
  1766  	if found1 {
  1767  		t.Fatal("shouldn't have returned user that has a team")
  1768  	} else if !found2 {
  1769  		t.Fatal("should've returned user that has no teams")
  1770  	}
  1771  }
  1772  
  1773  func TestGetUsersInTeam(t *testing.T) {
  1774  	th := Setup().InitBasic()
  1775  	defer th.TearDown()
  1776  	teamId := th.BasicTeam.Id
  1777  
  1778  	rusers, resp := th.Client.GetUsersInTeam(teamId, 0, 60, "")
  1779  	CheckNoError(t, resp)
  1780  	for _, u := range rusers {
  1781  		CheckUserSanitization(t, u)
  1782  	}
  1783  
  1784  	rusers, resp = th.Client.GetUsersInTeam(teamId, 0, 60, resp.Etag)
  1785  	CheckEtag(t, rusers, resp)
  1786  
  1787  	rusers, resp = th.Client.GetUsersInTeam(teamId, 0, 1, "")
  1788  	CheckNoError(t, resp)
  1789  	if len(rusers) != 1 {
  1790  		t.Fatal("should be 1 per page")
  1791  	}
  1792  
  1793  	rusers, resp = th.Client.GetUsersInTeam(teamId, 1, 1, "")
  1794  	CheckNoError(t, resp)
  1795  	if len(rusers) != 1 {
  1796  		t.Fatal("should be 1 per page")
  1797  	}
  1798  
  1799  	rusers, resp = th.Client.GetUsersInTeam(teamId, 10000, 100, "")
  1800  	CheckNoError(t, resp)
  1801  	if len(rusers) != 0 {
  1802  		t.Fatal("should be no users")
  1803  	}
  1804  
  1805  	th.Client.Logout()
  1806  	_, resp = th.Client.GetUsersInTeam(teamId, 0, 60, "")
  1807  	CheckUnauthorizedStatus(t, resp)
  1808  
  1809  	user := th.CreateUser()
  1810  	th.Client.Login(user.Email, user.Password)
  1811  	_, resp = th.Client.GetUsersInTeam(teamId, 0, 60, "")
  1812  	CheckForbiddenStatus(t, resp)
  1813  
  1814  	_, resp = th.SystemAdminClient.GetUsersInTeam(teamId, 0, 60, "")
  1815  	CheckNoError(t, resp)
  1816  }
  1817  
  1818  func TestGetUsersNotInTeam(t *testing.T) {
  1819  	th := Setup().InitBasic()
  1820  	defer th.TearDown()
  1821  	teamId := th.BasicTeam.Id
  1822  
  1823  	rusers, resp := th.Client.GetUsersNotInTeam(teamId, 0, 60, "")
  1824  	CheckNoError(t, resp)
  1825  	for _, u := range rusers {
  1826  		CheckUserSanitization(t, u)
  1827  	}
  1828  	require.Len(t, rusers, 1, "should be 1 user in total")
  1829  
  1830  	rusers, resp = th.Client.GetUsersNotInTeam(teamId, 0, 60, resp.Etag)
  1831  	CheckEtag(t, rusers, resp)
  1832  
  1833  	rusers, resp = th.Client.GetUsersNotInTeam(teamId, 0, 1, "")
  1834  	CheckNoError(t, resp)
  1835  	require.Len(t, rusers, 1, "should be 1 per page")
  1836  
  1837  	rusers, resp = th.Client.GetUsersNotInTeam(teamId, 1, 1, "")
  1838  	CheckNoError(t, resp)
  1839  	require.Len(t, rusers, 0, "should be no users")
  1840  
  1841  	rusers, resp = th.Client.GetUsersNotInTeam(teamId, 10000, 100, "")
  1842  	CheckNoError(t, resp)
  1843  	require.Len(t, rusers, 0, "should be no users")
  1844  
  1845  	th.Client.Logout()
  1846  	_, resp = th.Client.GetUsersNotInTeam(teamId, 0, 60, "")
  1847  	CheckUnauthorizedStatus(t, resp)
  1848  
  1849  	user := th.CreateUser()
  1850  	th.Client.Login(user.Email, user.Password)
  1851  	_, resp = th.Client.GetUsersNotInTeam(teamId, 0, 60, "")
  1852  	CheckForbiddenStatus(t, resp)
  1853  
  1854  	_, resp = th.SystemAdminClient.GetUsersNotInTeam(teamId, 0, 60, "")
  1855  	CheckNoError(t, resp)
  1856  }
  1857  
  1858  func TestGetUsersInChannel(t *testing.T) {
  1859  	th := Setup().InitBasic()
  1860  	defer th.TearDown()
  1861  	channelId := th.BasicChannel.Id
  1862  
  1863  	rusers, resp := th.Client.GetUsersInChannel(channelId, 0, 60, "")
  1864  	CheckNoError(t, resp)
  1865  	for _, u := range rusers {
  1866  		CheckUserSanitization(t, u)
  1867  	}
  1868  
  1869  	rusers, resp = th.Client.GetUsersInChannel(channelId, 0, 1, "")
  1870  	CheckNoError(t, resp)
  1871  	if len(rusers) != 1 {
  1872  		t.Fatal("should be 1 per page")
  1873  	}
  1874  
  1875  	rusers, resp = th.Client.GetUsersInChannel(channelId, 1, 1, "")
  1876  	CheckNoError(t, resp)
  1877  	if len(rusers) != 1 {
  1878  		t.Fatal("should be 1 per page")
  1879  	}
  1880  
  1881  	rusers, resp = th.Client.GetUsersInChannel(channelId, 10000, 100, "")
  1882  	CheckNoError(t, resp)
  1883  	if len(rusers) != 0 {
  1884  		t.Fatal("should be no users")
  1885  	}
  1886  
  1887  	th.Client.Logout()
  1888  	_, resp = th.Client.GetUsersInChannel(channelId, 0, 60, "")
  1889  	CheckUnauthorizedStatus(t, resp)
  1890  
  1891  	user := th.CreateUser()
  1892  	th.Client.Login(user.Email, user.Password)
  1893  	_, resp = th.Client.GetUsersInChannel(channelId, 0, 60, "")
  1894  	CheckForbiddenStatus(t, resp)
  1895  
  1896  	_, resp = th.SystemAdminClient.GetUsersInChannel(channelId, 0, 60, "")
  1897  	CheckNoError(t, resp)
  1898  }
  1899  
  1900  func TestGetUsersNotInChannel(t *testing.T) {
  1901  	th := Setup().InitBasic()
  1902  	defer th.TearDown()
  1903  	teamId := th.BasicTeam.Id
  1904  	channelId := th.BasicChannel.Id
  1905  
  1906  	user := th.CreateUser()
  1907  	th.LinkUserToTeam(user, th.BasicTeam)
  1908  
  1909  	rusers, resp := th.Client.GetUsersNotInChannel(teamId, channelId, 0, 60, "")
  1910  	CheckNoError(t, resp)
  1911  	for _, u := range rusers {
  1912  		CheckUserSanitization(t, u)
  1913  	}
  1914  
  1915  	rusers, resp = th.Client.GetUsersNotInChannel(teamId, channelId, 0, 1, "")
  1916  	CheckNoError(t, resp)
  1917  	if len(rusers) != 1 {
  1918  		t.Log(len(rusers))
  1919  		t.Fatal("should be 1 per page")
  1920  	}
  1921  
  1922  	rusers, resp = th.Client.GetUsersNotInChannel(teamId, channelId, 10000, 100, "")
  1923  	CheckNoError(t, resp)
  1924  	if len(rusers) != 0 {
  1925  		t.Fatal("should be no users")
  1926  	}
  1927  
  1928  	th.Client.Logout()
  1929  	_, resp = th.Client.GetUsersNotInChannel(teamId, channelId, 0, 60, "")
  1930  	CheckUnauthorizedStatus(t, resp)
  1931  
  1932  	th.Client.Login(user.Email, user.Password)
  1933  	_, resp = th.Client.GetUsersNotInChannel(teamId, channelId, 0, 60, "")
  1934  	CheckForbiddenStatus(t, resp)
  1935  
  1936  	_, resp = th.SystemAdminClient.GetUsersNotInChannel(teamId, channelId, 0, 60, "")
  1937  	CheckNoError(t, resp)
  1938  }
  1939  
  1940  func TestUpdateUserMfa(t *testing.T) {
  1941  	th := Setup().InitBasic()
  1942  	defer th.TearDown()
  1943  
  1944  	th.App.SetLicense(model.NewTestLicense("mfa"))
  1945  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true })
  1946  
  1947  	session, _ := th.App.GetSession(th.Client.AuthToken)
  1948  	session.IsOAuth = true
  1949  	th.App.AddSessionToCache(session)
  1950  
  1951  	_, resp := th.Client.UpdateUserMfa(th.BasicUser.Id, "12345", false)
  1952  	CheckForbiddenStatus(t, resp)
  1953  }
  1954  
  1955  // CheckUserMfa is deprecated and should not be used anymore, it will be disabled by default in version 6.0
  1956  func TestCheckUserMfa(t *testing.T) {
  1957  	th := Setup().InitBasic()
  1958  	defer th.TearDown()
  1959  
  1960  	th.App.UpdateConfig(func(c *model.Config) {
  1961  		*c.ServiceSettings.DisableLegacyMFA = false
  1962  	})
  1963  
  1964  	required, resp := th.Client.CheckUserMfa(th.BasicUser.Email)
  1965  	CheckNoError(t, resp)
  1966  
  1967  	if required {
  1968  		t.Fatal("should be false - mfa not active")
  1969  	}
  1970  
  1971  	_, resp = th.Client.CheckUserMfa("")
  1972  	CheckBadRequestStatus(t, resp)
  1973  
  1974  	th.Client.Logout()
  1975  
  1976  	required, resp = th.Client.CheckUserMfa(th.BasicUser.Email)
  1977  	CheckNoError(t, resp)
  1978  
  1979  	if required {
  1980  		t.Fatal("should be false - mfa not active")
  1981  	}
  1982  
  1983  	th.App.SetLicense(model.NewTestLicense("mfa"))
  1984  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true })
  1985  
  1986  	th.LoginBasic()
  1987  
  1988  	required, resp = th.Client.CheckUserMfa(th.BasicUser.Email)
  1989  	CheckNoError(t, resp)
  1990  
  1991  	if required {
  1992  		t.Fatal("should be false - mfa not active")
  1993  	}
  1994  
  1995  	th.Client.Logout()
  1996  
  1997  	required, resp = th.Client.CheckUserMfa(th.BasicUser.Email)
  1998  	CheckNoError(t, resp)
  1999  
  2000  	if required {
  2001  		t.Fatal("should be false - mfa not active")
  2002  	}
  2003  
  2004  	th.App.UpdateConfig(func(c *model.Config) {
  2005  		*c.ServiceSettings.DisableLegacyMFA = true
  2006  	})
  2007  
  2008  	_, resp = th.Client.CheckUserMfa(th.BasicUser.Email)
  2009  	CheckNotFoundStatus(t, resp)
  2010  }
  2011  
  2012  func TestUserLoginMFAFlow(t *testing.T) {
  2013  	th := Setup().InitBasic()
  2014  	defer th.TearDown()
  2015  
  2016  	th.App.UpdateConfig(func(c *model.Config) {
  2017  		*c.ServiceSettings.DisableLegacyMFA = true
  2018  		*c.ServiceSettings.EnableMultifactorAuthentication = true
  2019  	})
  2020  
  2021  	t.Run("WithoutMFA", func(t *testing.T) {
  2022  		_, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password)
  2023  		CheckNoError(t, resp)
  2024  	})
  2025  
  2026  	t.Run("WithInvalidMFA", func(t *testing.T) {
  2027  		secret, err := th.App.GenerateMfaSecret(th.BasicUser.Id)
  2028  		assert.Nil(t, err)
  2029  
  2030  		// Fake user has MFA enabled
  2031  		if result := <-th.Server.Store.User().UpdateMfaActive(th.BasicUser.Id, true); result.Err != nil {
  2032  			t.Fatal(result.Err)
  2033  		}
  2034  
  2035  		if result := <-th.Server.Store.User().UpdateMfaSecret(th.BasicUser.Id, secret.Secret); result.Err != nil {
  2036  			t.Fatal(result.Err)
  2037  		}
  2038  
  2039  		user, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password)
  2040  		CheckErrorMessage(t, resp, "mfa.validate_token.authenticate.app_error")
  2041  		assert.Nil(t, user)
  2042  
  2043  		user, resp = th.Client.LoginWithMFA(th.BasicUser.Email, th.BasicUser.Password, "")
  2044  		CheckErrorMessage(t, resp, "mfa.validate_token.authenticate.app_error")
  2045  		assert.Nil(t, user)
  2046  
  2047  		user, resp = th.Client.LoginWithMFA(th.BasicUser.Email, th.BasicUser.Password, "abcdefgh")
  2048  		CheckErrorMessage(t, resp, "mfa.validate_token.authenticate.app_error")
  2049  		assert.Nil(t, user)
  2050  
  2051  		secret2, err := th.App.GenerateMfaSecret(th.BasicUser2.Id)
  2052  		assert.Nil(t, err)
  2053  		user, resp = th.Client.LoginWithMFA(th.BasicUser.Email, th.BasicUser.Password, secret2.Secret)
  2054  		CheckErrorMessage(t, resp, "mfa.validate_token.authenticate.app_error")
  2055  		assert.Nil(t, user)
  2056  	})
  2057  
  2058  	t.Run("WithCorrectMFA", func(t *testing.T) {
  2059  		secret, err := th.App.GenerateMfaSecret(th.BasicUser.Id)
  2060  		assert.Nil(t, err)
  2061  
  2062  		// Fake user has MFA enabled
  2063  		if result := <-th.Server.Store.User().UpdateMfaActive(th.BasicUser.Id, true); result.Err != nil {
  2064  			t.Fatal(result.Err)
  2065  		}
  2066  
  2067  		if result := <-th.Server.Store.User().UpdateMfaSecret(th.BasicUser.Id, secret.Secret); result.Err != nil {
  2068  			t.Fatal(result.Err)
  2069  		}
  2070  
  2071  		code := dgoogauth.ComputeCode(secret.Secret, time.Now().UTC().Unix()/30)
  2072  
  2073  		user, resp := th.Client.LoginWithMFA(th.BasicUser.Email, th.BasicUser.Password, fmt.Sprintf("%06d", code))
  2074  		CheckNoError(t, resp)
  2075  		assert.NotNil(t, user)
  2076  	})
  2077  }
  2078  
  2079  func TestGenerateMfaSecret(t *testing.T) {
  2080  	th := Setup().InitBasic()
  2081  	defer th.TearDown()
  2082  
  2083  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = false })
  2084  
  2085  	_, resp := th.Client.GenerateMfaSecret(th.BasicUser.Id)
  2086  	CheckNotImplementedStatus(t, resp)
  2087  
  2088  	_, resp = th.SystemAdminClient.GenerateMfaSecret(th.BasicUser.Id)
  2089  	CheckNotImplementedStatus(t, resp)
  2090  
  2091  	_, resp = th.Client.GenerateMfaSecret("junk")
  2092  	CheckBadRequestStatus(t, resp)
  2093  
  2094  	th.App.SetLicense(model.NewTestLicense("mfa"))
  2095  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true })
  2096  
  2097  	_, resp = th.Client.GenerateMfaSecret(model.NewId())
  2098  	CheckForbiddenStatus(t, resp)
  2099  
  2100  	session, _ := th.App.GetSession(th.Client.AuthToken)
  2101  	session.IsOAuth = true
  2102  	th.App.AddSessionToCache(session)
  2103  
  2104  	_, resp = th.Client.GenerateMfaSecret(th.BasicUser.Id)
  2105  	CheckForbiddenStatus(t, resp)
  2106  
  2107  	th.Client.Logout()
  2108  
  2109  	_, resp = th.Client.GenerateMfaSecret(th.BasicUser.Id)
  2110  	CheckUnauthorizedStatus(t, resp)
  2111  }
  2112  
  2113  func TestUpdateUserPassword(t *testing.T) {
  2114  	th := Setup().InitBasic()
  2115  	defer th.TearDown()
  2116  
  2117  	password := "newpassword1"
  2118  	pass, resp := th.Client.UpdateUserPassword(th.BasicUser.Id, th.BasicUser.Password, password)
  2119  	CheckNoError(t, resp)
  2120  
  2121  	if !pass {
  2122  		t.Fatal("should have returned true")
  2123  	}
  2124  
  2125  	_, resp = th.Client.UpdateUserPassword(th.BasicUser.Id, password, "")
  2126  	CheckBadRequestStatus(t, resp)
  2127  
  2128  	_, resp = th.Client.UpdateUserPassword(th.BasicUser.Id, password, "junk")
  2129  	CheckBadRequestStatus(t, resp)
  2130  
  2131  	_, resp = th.Client.UpdateUserPassword("junk", password, password)
  2132  	CheckBadRequestStatus(t, resp)
  2133  
  2134  	_, resp = th.Client.UpdateUserPassword(th.BasicUser.Id, "", password)
  2135  	CheckBadRequestStatus(t, resp)
  2136  
  2137  	_, resp = th.Client.UpdateUserPassword(th.BasicUser.Id, "junk", password)
  2138  	CheckBadRequestStatus(t, resp)
  2139  
  2140  	_, resp = th.Client.UpdateUserPassword(th.BasicUser.Id, password, th.BasicUser.Password)
  2141  	CheckNoError(t, resp)
  2142  
  2143  	th.Client.Logout()
  2144  	_, resp = th.Client.UpdateUserPassword(th.BasicUser.Id, password, password)
  2145  	CheckUnauthorizedStatus(t, resp)
  2146  
  2147  	th.LoginBasic2()
  2148  	_, resp = th.Client.UpdateUserPassword(th.BasicUser.Id, password, password)
  2149  	CheckForbiddenStatus(t, resp)
  2150  
  2151  	th.LoginBasic()
  2152  
  2153  	// Test lockout
  2154  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.MaximumLoginAttempts = 2 })
  2155  
  2156  	// Fail twice
  2157  	_, resp = th.Client.UpdateUserPassword(th.BasicUser.Id, "badpwd", "newpwd")
  2158  	CheckBadRequestStatus(t, resp)
  2159  	_, resp = th.Client.UpdateUserPassword(th.BasicUser.Id, "badpwd", "newpwd")
  2160  	CheckBadRequestStatus(t, resp)
  2161  
  2162  	// Should fail because account is locked out
  2163  	_, resp = th.Client.UpdateUserPassword(th.BasicUser.Id, th.BasicUser.Password, "newpwd")
  2164  	CheckErrorMessage(t, resp, "api.user.check_user_login_attempts.too_many.app_error")
  2165  	CheckUnauthorizedStatus(t, resp)
  2166  
  2167  	// System admin can update another user's password
  2168  	adminSetPassword := "pwdsetbyadmin"
  2169  	pass, resp = th.SystemAdminClient.UpdateUserPassword(th.BasicUser.Id, "", adminSetPassword)
  2170  	CheckNoError(t, resp)
  2171  
  2172  	if !pass {
  2173  		t.Fatal("should have returned true")
  2174  	}
  2175  
  2176  	_, resp = th.Client.Login(th.BasicUser.Email, adminSetPassword)
  2177  	CheckNoError(t, resp)
  2178  }
  2179  
  2180  func TestResetPassword(t *testing.T) {
  2181  	t.Skip("test disabled during old build server changes, should be investigated")
  2182  
  2183  	th := Setup().InitBasic()
  2184  	defer th.TearDown()
  2185  	th.Client.Logout()
  2186  	user := th.BasicUser
  2187  	// Delete all the messages before check the reset password
  2188  	mailservice.DeleteMailBox(user.Email)
  2189  	success, resp := th.Client.SendPasswordResetEmail(user.Email)
  2190  	CheckNoError(t, resp)
  2191  	if !success {
  2192  		t.Fatal("should have succeeded")
  2193  	}
  2194  	_, resp = th.Client.SendPasswordResetEmail("")
  2195  	CheckBadRequestStatus(t, resp)
  2196  	// Should not leak whether the email is attached to an account or not
  2197  	success, resp = th.Client.SendPasswordResetEmail("notreal@example.com")
  2198  	CheckNoError(t, resp)
  2199  	if !success {
  2200  		t.Fatal("should have succeeded")
  2201  	}
  2202  	// Check if the email was send to the right email address and the recovery key match
  2203  	var resultsMailbox mailservice.JSONMessageHeaderInbucket
  2204  	err := mailservice.RetryInbucket(5, func() error {
  2205  		var err error
  2206  		resultsMailbox, err = mailservice.GetMailBox(user.Email)
  2207  		return err
  2208  	})
  2209  	if err != nil {
  2210  		t.Log(err)
  2211  		t.Log("No email was received, maybe due load on the server. Disabling this verification")
  2212  	}
  2213  	var recoveryTokenString string
  2214  	if err == nil && len(resultsMailbox) > 0 {
  2215  		if !strings.ContainsAny(resultsMailbox[0].To[0], user.Email) {
  2216  			t.Fatal("Wrong To recipient")
  2217  		} else {
  2218  			if resultsEmail, err := mailservice.GetMessageFromMailbox(user.Email, resultsMailbox[0].ID); err == nil {
  2219  				loc := strings.Index(resultsEmail.Body.Text, "token=")
  2220  				if loc == -1 {
  2221  					t.Log(resultsEmail.Body.Text)
  2222  					t.Fatal("Code not found in email")
  2223  				}
  2224  				loc += 6
  2225  				recoveryTokenString = resultsEmail.Body.Text[loc : loc+model.TOKEN_SIZE]
  2226  			}
  2227  		}
  2228  	}
  2229  	var recoveryToken *model.Token
  2230  	if result := <-th.App.Srv.Store.Token().GetByToken(recoveryTokenString); result.Err != nil {
  2231  		t.Log(recoveryTokenString)
  2232  		t.Fatal(result.Err)
  2233  	} else {
  2234  		recoveryToken = result.Data.(*model.Token)
  2235  	}
  2236  	_, resp = th.Client.ResetPassword(recoveryToken.Token, "")
  2237  	CheckBadRequestStatus(t, resp)
  2238  	_, resp = th.Client.ResetPassword(recoveryToken.Token, "newp")
  2239  	CheckBadRequestStatus(t, resp)
  2240  	_, resp = th.Client.ResetPassword("", "newpwd")
  2241  	CheckBadRequestStatus(t, resp)
  2242  	_, resp = th.Client.ResetPassword("junk", "newpwd")
  2243  	CheckBadRequestStatus(t, resp)
  2244  	code := ""
  2245  	for i := 0; i < model.TOKEN_SIZE; i++ {
  2246  		code += "a"
  2247  	}
  2248  	_, resp = th.Client.ResetPassword(code, "newpwd")
  2249  	CheckBadRequestStatus(t, resp)
  2250  	success, resp = th.Client.ResetPassword(recoveryToken.Token, "newpwd")
  2251  	CheckNoError(t, resp)
  2252  	if !success {
  2253  		t.Fatal("should have succeeded")
  2254  	}
  2255  	th.Client.Login(user.Email, "newpwd")
  2256  	th.Client.Logout()
  2257  	_, resp = th.Client.ResetPassword(recoveryToken.Token, "newpwd")
  2258  	CheckBadRequestStatus(t, resp)
  2259  	authData := model.NewId()
  2260  	if result := <-th.App.Srv.Store.User().UpdateAuthData(user.Id, "random", &authData, "", true); result.Err != nil {
  2261  		t.Fatal(result.Err)
  2262  	}
  2263  	_, resp = th.Client.SendPasswordResetEmail(user.Email)
  2264  	CheckBadRequestStatus(t, resp)
  2265  }
  2266  
  2267  func TestGetSessions(t *testing.T) {
  2268  	th := Setup().InitBasic()
  2269  	defer th.TearDown()
  2270  
  2271  	user := th.BasicUser
  2272  
  2273  	th.Client.Login(user.Email, user.Password)
  2274  
  2275  	sessions, resp := th.Client.GetSessions(user.Id, "")
  2276  	for _, session := range sessions {
  2277  		if session.UserId != user.Id {
  2278  			t.Fatal("user id does not match session user id")
  2279  		}
  2280  	}
  2281  	CheckNoError(t, resp)
  2282  
  2283  	_, resp = th.Client.RevokeSession("junk", model.NewId())
  2284  	CheckBadRequestStatus(t, resp)
  2285  
  2286  	_, resp = th.Client.GetSessions(th.BasicUser2.Id, "")
  2287  	CheckForbiddenStatus(t, resp)
  2288  
  2289  	_, resp = th.Client.GetSessions(model.NewId(), "")
  2290  	CheckForbiddenStatus(t, resp)
  2291  
  2292  	th.Client.Logout()
  2293  	_, resp = th.Client.GetSessions(th.BasicUser2.Id, "")
  2294  	CheckUnauthorizedStatus(t, resp)
  2295  
  2296  	_, resp = th.SystemAdminClient.GetSessions(user.Id, "")
  2297  	CheckNoError(t, resp)
  2298  
  2299  	_, resp = th.SystemAdminClient.GetSessions(th.BasicUser2.Id, "")
  2300  	CheckNoError(t, resp)
  2301  
  2302  	_, resp = th.SystemAdminClient.GetSessions(model.NewId(), "")
  2303  	CheckNoError(t, resp)
  2304  }
  2305  
  2306  func TestRevokeSessions(t *testing.T) {
  2307  	th := Setup().InitBasic()
  2308  	defer th.TearDown()
  2309  
  2310  	user := th.BasicUser
  2311  	th.Client.Login(user.Email, user.Password)
  2312  	sessions, _ := th.Client.GetSessions(user.Id, "")
  2313  	if len(sessions) == 0 {
  2314  		t.Fatal("sessions should exist")
  2315  	}
  2316  	for _, session := range sessions {
  2317  		if session.UserId != user.Id {
  2318  			t.Fatal("user id does not match session user id")
  2319  		}
  2320  	}
  2321  	session := sessions[0]
  2322  
  2323  	_, resp := th.Client.RevokeSession(user.Id, model.NewId())
  2324  	CheckBadRequestStatus(t, resp)
  2325  
  2326  	_, resp = th.Client.RevokeSession(th.BasicUser2.Id, model.NewId())
  2327  	CheckForbiddenStatus(t, resp)
  2328  
  2329  	_, resp = th.Client.RevokeSession("junk", model.NewId())
  2330  	CheckBadRequestStatus(t, resp)
  2331  
  2332  	status, resp := th.Client.RevokeSession(user.Id, session.Id)
  2333  	if !status {
  2334  		t.Fatal("user session revoke unsuccessful")
  2335  	}
  2336  	CheckNoError(t, resp)
  2337  
  2338  	th.LoginBasic()
  2339  
  2340  	sessions, _ = th.App.GetSessions(th.SystemAdminUser.Id)
  2341  	session = sessions[0]
  2342  
  2343  	_, resp = th.Client.RevokeSession(user.Id, session.Id)
  2344  	CheckBadRequestStatus(t, resp)
  2345  
  2346  	th.Client.Logout()
  2347  	_, resp = th.Client.RevokeSession(user.Id, model.NewId())
  2348  	CheckUnauthorizedStatus(t, resp)
  2349  
  2350  	_, resp = th.SystemAdminClient.RevokeSession(user.Id, model.NewId())
  2351  	CheckBadRequestStatus(t, resp)
  2352  
  2353  	sessions, _ = th.SystemAdminClient.GetSessions(th.SystemAdminUser.Id, "")
  2354  	if len(sessions) == 0 {
  2355  		t.Fatal("sessions should exist")
  2356  	}
  2357  	for _, session := range sessions {
  2358  		if session.UserId != th.SystemAdminUser.Id {
  2359  			t.Fatal("user id does not match session user id")
  2360  		}
  2361  	}
  2362  	session = sessions[0]
  2363  
  2364  	_, resp = th.SystemAdminClient.RevokeSession(th.SystemAdminUser.Id, session.Id)
  2365  	CheckNoError(t, resp)
  2366  }
  2367  
  2368  func TestRevokeAllSessions(t *testing.T) {
  2369  	th := Setup().InitBasic()
  2370  	defer th.TearDown()
  2371  
  2372  	user := th.BasicUser
  2373  	th.Client.Login(user.Email, user.Password)
  2374  
  2375  	_, resp := th.Client.RevokeAllSessions(th.BasicUser2.Id)
  2376  	CheckForbiddenStatus(t, resp)
  2377  
  2378  	_, resp = th.Client.RevokeAllSessions("junk" + user.Id)
  2379  	CheckBadRequestStatus(t, resp)
  2380  
  2381  	status, resp := th.Client.RevokeAllSessions(user.Id)
  2382  	if !status {
  2383  		t.Fatal("user all sessions revoke unsuccessful")
  2384  	}
  2385  	CheckNoError(t, resp)
  2386  
  2387  	th.Client.Logout()
  2388  	_, resp = th.Client.RevokeAllSessions(user.Id)
  2389  	CheckUnauthorizedStatus(t, resp)
  2390  
  2391  	th.Client.Login(user.Email, user.Password)
  2392  
  2393  	sessions, _ := th.Client.GetSessions(user.Id, "")
  2394  	if len(sessions) < 1 {
  2395  		t.Fatal("session should exist")
  2396  	}
  2397  
  2398  	_, resp = th.Client.RevokeAllSessions(user.Id)
  2399  	CheckNoError(t, resp)
  2400  
  2401  	sessions, _ = th.SystemAdminClient.GetSessions(user.Id, "")
  2402  	if len(sessions) != 0 {
  2403  		t.Fatal("no sessions should exist for user")
  2404  	}
  2405  
  2406  	_, resp = th.Client.RevokeAllSessions(user.Id)
  2407  	CheckUnauthorizedStatus(t, resp)
  2408  }
  2409  
  2410  func TestAttachDeviceId(t *testing.T) {
  2411  	th := Setup().InitBasic()
  2412  	defer th.TearDown()
  2413  
  2414  	deviceId := model.PUSH_NOTIFY_APPLE + ":1234567890"
  2415  	pass, resp := th.Client.AttachDeviceId(deviceId)
  2416  	CheckNoError(t, resp)
  2417  
  2418  	if !pass {
  2419  		t.Fatal("should have passed")
  2420  	}
  2421  
  2422  	if sessions, err := th.App.GetSessions(th.BasicUser.Id); err != nil {
  2423  		t.Fatal(err)
  2424  	} else {
  2425  		if sessions[0].DeviceId != deviceId {
  2426  			t.Fatal("Missing device Id")
  2427  		}
  2428  	}
  2429  
  2430  	_, resp = th.Client.AttachDeviceId("")
  2431  	CheckBadRequestStatus(t, resp)
  2432  
  2433  	th.Client.Logout()
  2434  
  2435  	_, resp = th.Client.AttachDeviceId("")
  2436  	CheckUnauthorizedStatus(t, resp)
  2437  }
  2438  
  2439  func TestGetUserAudits(t *testing.T) {
  2440  	th := Setup().InitBasic()
  2441  	defer th.TearDown()
  2442  	user := th.BasicUser
  2443  
  2444  	audits, resp := th.Client.GetUserAudits(user.Id, 0, 100, "")
  2445  	for _, audit := range audits {
  2446  		if audit.UserId != user.Id {
  2447  			t.Fatal("user id does not match audit user id")
  2448  		}
  2449  	}
  2450  	CheckNoError(t, resp)
  2451  
  2452  	_, resp = th.Client.GetUserAudits(th.BasicUser2.Id, 0, 100, "")
  2453  	CheckForbiddenStatus(t, resp)
  2454  
  2455  	th.Client.Logout()
  2456  	_, resp = th.Client.GetUserAudits(user.Id, 0, 100, "")
  2457  	CheckUnauthorizedStatus(t, resp)
  2458  
  2459  	_, resp = th.SystemAdminClient.GetUserAudits(user.Id, 0, 100, "")
  2460  	CheckNoError(t, resp)
  2461  }
  2462  
  2463  func TestVerifyUserEmail(t *testing.T) {
  2464  	th := Setup().InitBasic()
  2465  	defer th.TearDown()
  2466  
  2467  	email := th.GenerateTestEmail()
  2468  	user := model.User{Email: email, Nickname: "Darth Vader", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
  2469  
  2470  	ruser, _ := th.Client.CreateUser(&user)
  2471  
  2472  	token, err := th.App.CreateVerifyEmailToken(ruser.Id, email)
  2473  	if err != nil {
  2474  		t.Fatal("Unable to create email verify token")
  2475  	}
  2476  
  2477  	_, resp := th.Client.VerifyUserEmail(token.Token)
  2478  	CheckNoError(t, resp)
  2479  
  2480  	_, resp = th.Client.VerifyUserEmail(GenerateTestId())
  2481  	CheckBadRequestStatus(t, resp)
  2482  
  2483  	_, resp = th.Client.VerifyUserEmail("")
  2484  	CheckBadRequestStatus(t, resp)
  2485  }
  2486  
  2487  func TestSendVerificationEmail(t *testing.T) {
  2488  	th := Setup().InitBasic()
  2489  	defer th.TearDown()
  2490  
  2491  	pass, resp := th.Client.SendVerificationEmail(th.BasicUser.Email)
  2492  	CheckNoError(t, resp)
  2493  
  2494  	if !pass {
  2495  		t.Fatal("should have passed")
  2496  	}
  2497  
  2498  	_, resp = th.Client.SendVerificationEmail("")
  2499  	CheckBadRequestStatus(t, resp)
  2500  
  2501  	// Even non-existent emails should return 200 OK
  2502  	_, resp = th.Client.SendVerificationEmail(th.GenerateTestEmail())
  2503  	CheckNoError(t, resp)
  2504  
  2505  	th.Client.Logout()
  2506  	_, resp = th.Client.SendVerificationEmail(th.BasicUser.Email)
  2507  	CheckNoError(t, resp)
  2508  }
  2509  
  2510  func TestSetProfileImage(t *testing.T) {
  2511  	th := Setup().InitBasic()
  2512  	defer th.TearDown()
  2513  	user := th.BasicUser
  2514  
  2515  	data, err := testutils.ReadTestFile("test.png")
  2516  	if err != nil {
  2517  		t.Fatal(err)
  2518  	}
  2519  
  2520  	ok, resp := th.Client.SetProfileImage(user.Id, data)
  2521  	if !ok {
  2522  		t.Fatal(resp.Error)
  2523  	}
  2524  	CheckNoError(t, resp)
  2525  
  2526  	ok, resp = th.Client.SetProfileImage(model.NewId(), data)
  2527  	if ok {
  2528  		t.Fatal("Should return false, set profile image not allowed")
  2529  	}
  2530  	CheckForbiddenStatus(t, resp)
  2531  
  2532  	// status code returns either forbidden or unauthorized
  2533  	// note: forbidden is set as default at Client4.SetProfileImage when request is terminated early by server
  2534  	th.Client.Logout()
  2535  	_, resp = th.Client.SetProfileImage(user.Id, data)
  2536  	if resp.StatusCode == http.StatusForbidden {
  2537  		CheckForbiddenStatus(t, resp)
  2538  	} else if resp.StatusCode == http.StatusUnauthorized {
  2539  		CheckUnauthorizedStatus(t, resp)
  2540  	} else {
  2541  		t.Fatal("Should have failed either forbidden or unauthorized")
  2542  	}
  2543  
  2544  	buser, err := th.App.GetUser(user.Id)
  2545  	require.Nil(t, err)
  2546  
  2547  	_, resp = th.SystemAdminClient.SetProfileImage(user.Id, data)
  2548  	CheckNoError(t, resp)
  2549  
  2550  	ruser, err := th.App.GetUser(user.Id)
  2551  	require.Nil(t, err)
  2552  	assert.True(t, buser.LastPictureUpdate < ruser.LastPictureUpdate, "Picture should have updated for user")
  2553  
  2554  	info := &model.FileInfo{Path: "users/" + user.Id + "/profile.png"}
  2555  	if err := th.cleanupTestFile(info); err != nil {
  2556  		t.Fatal(err)
  2557  	}
  2558  }
  2559  
  2560  func TestSetDefaultProfileImage(t *testing.T) {
  2561  	th := Setup().InitBasic()
  2562  	defer th.TearDown()
  2563  	user := th.BasicUser
  2564  
  2565  	ok, resp := th.Client.SetDefaultProfileImage(user.Id)
  2566  	if !ok {
  2567  		t.Fatal(resp.Error)
  2568  	}
  2569  	CheckNoError(t, resp)
  2570  
  2571  	ok, resp = th.Client.SetDefaultProfileImage(model.NewId())
  2572  	if ok {
  2573  		t.Fatal("Should return false, set profile image not allowed")
  2574  	}
  2575  	CheckForbiddenStatus(t, resp)
  2576  
  2577  	// status code returns either forbidden or unauthorized
  2578  	// note: forbidden is set as default at Client4.SetDefaultProfileImage when request is terminated early by server
  2579  	th.Client.Logout()
  2580  	_, resp = th.Client.SetDefaultProfileImage(user.Id)
  2581  	if resp.StatusCode == http.StatusForbidden {
  2582  		CheckForbiddenStatus(t, resp)
  2583  	} else if resp.StatusCode == http.StatusUnauthorized {
  2584  		CheckUnauthorizedStatus(t, resp)
  2585  	} else {
  2586  		t.Fatal("Should have failed either forbidden or unauthorized")
  2587  	}
  2588  
  2589  	_, resp = th.SystemAdminClient.SetDefaultProfileImage(user.Id)
  2590  	CheckNoError(t, resp)
  2591  
  2592  	ruser, err := th.App.GetUser(user.Id)
  2593  	require.Nil(t, err)
  2594  	assert.Equal(t, int64(0), ruser.LastPictureUpdate, "Picture should have resetted to default")
  2595  
  2596  	info := &model.FileInfo{Path: "users/" + user.Id + "/profile.png"}
  2597  	if err := th.cleanupTestFile(info); err != nil {
  2598  		t.Fatal(err)
  2599  	}
  2600  }
  2601  
  2602  func TestLogin(t *testing.T) {
  2603  	th := Setup().InitBasic()
  2604  	defer th.TearDown()
  2605  	th.Client.Logout()
  2606  
  2607  	t.Run("missing password", func(t *testing.T) {
  2608  		_, resp := th.Client.Login(th.BasicUser.Email, "")
  2609  		CheckErrorMessage(t, resp, "api.user.login.blank_pwd.app_error")
  2610  	})
  2611  
  2612  	t.Run("unknown user", func(t *testing.T) {
  2613  		_, resp := th.Client.Login("unknown", th.BasicUser.Password)
  2614  		CheckErrorMessage(t, resp, "store.sql_user.get_for_login.app_error")
  2615  	})
  2616  
  2617  	t.Run("valid login", func(t *testing.T) {
  2618  		user, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password)
  2619  		CheckNoError(t, resp)
  2620  		assert.Equal(t, user.Id, th.BasicUser.Id)
  2621  	})
  2622  
  2623  	t.Run("bot login rejected", func(t *testing.T) {
  2624  		bot, resp := th.SystemAdminClient.CreateBot(&model.Bot{
  2625  			Username: "bot",
  2626  		})
  2627  		CheckNoError(t, resp)
  2628  
  2629  		botUser, resp := th.SystemAdminClient.GetUser(bot.UserId, "")
  2630  		CheckNoError(t, resp)
  2631  
  2632  		changed, resp := th.SystemAdminClient.UpdateUserPassword(bot.UserId, "", "password")
  2633  		CheckNoError(t, resp)
  2634  		require.True(t, changed)
  2635  
  2636  		_, resp = th.Client.Login(botUser.Email, "password")
  2637  		CheckErrorMessage(t, resp, "api.user.login.bot_login_forbidden.app_error")
  2638  	})
  2639  
  2640  	t.Run("login with terms_of_service set", func(t *testing.T) {
  2641  		termsOfService, err := th.App.CreateTermsOfService("terms of service", th.BasicUser.Id)
  2642  		if err != nil {
  2643  			t.Fatal(err)
  2644  		}
  2645  
  2646  		success, resp := th.Client.RegisterTermsOfServiceAction(th.BasicUser.Id, termsOfService.Id, true)
  2647  		CheckNoError(t, resp)
  2648  		assert.True(t, *success)
  2649  
  2650  		userTermsOfService, resp := th.Client.GetUserTermsOfService(th.BasicUser.Id, "")
  2651  		CheckNoError(t, resp)
  2652  
  2653  		user, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password)
  2654  		CheckNoError(t, resp)
  2655  		assert.Equal(t, user.Id, th.BasicUser.Id)
  2656  		assert.Equal(t, user.TermsOfServiceId, userTermsOfService.TermsOfServiceId)
  2657  		assert.Equal(t, user.TermsOfServiceCreateAt, userTermsOfService.CreateAt)
  2658  	})
  2659  }
  2660  
  2661  func TestLoginCookies(t *testing.T) {
  2662  	t.Run("should return cookies with X-Requested-With header", func(t *testing.T) {
  2663  		th := Setup().InitBasic()
  2664  		defer th.TearDown()
  2665  
  2666  		th.Client.HttpHeader[model.HEADER_REQUESTED_WITH] = model.HEADER_REQUESTED_WITH_XML
  2667  
  2668  		user, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password)
  2669  
  2670  		sessionCookie := ""
  2671  		userCookie := ""
  2672  		csrfCookie := ""
  2673  
  2674  		for _, cookie := range resp.Header["Set-Cookie"] {
  2675  			if match := regexp.MustCompile("^" + model.SESSION_COOKIE_TOKEN + "=([a-z0-9]+)").FindStringSubmatch(cookie); match != nil {
  2676  				sessionCookie = match[1]
  2677  			} else if match := regexp.MustCompile("^" + model.SESSION_COOKIE_USER + "=([a-z0-9]+)").FindStringSubmatch(cookie); match != nil {
  2678  				userCookie = match[1]
  2679  			} else if match := regexp.MustCompile("^" + model.SESSION_COOKIE_CSRF + "=([a-z0-9]+)").FindStringSubmatch(cookie); match != nil {
  2680  				csrfCookie = match[1]
  2681  			}
  2682  		}
  2683  
  2684  		session, _ := th.App.GetSession(th.Client.AuthToken)
  2685  
  2686  		assert.Equal(t, th.Client.AuthToken, sessionCookie)
  2687  		assert.Equal(t, user.Id, userCookie)
  2688  		assert.Equal(t, session.GetCSRF(), csrfCookie)
  2689  	})
  2690  
  2691  	t.Run("should not return cookies without X-Requested-With header", func(t *testing.T) {
  2692  		th := Setup().InitBasic()
  2693  		defer th.TearDown()
  2694  
  2695  		_, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password)
  2696  
  2697  		assert.Empty(t, resp.Header.Get("Set-Cookie"))
  2698  	})
  2699  }
  2700  
  2701  func TestCBALogin(t *testing.T) {
  2702  	t.Run("primary", func(t *testing.T) {
  2703  		th := Setup().InitBasic()
  2704  		defer th.TearDown()
  2705  		th.App.SetLicense(model.NewTestLicense("saml"))
  2706  
  2707  		th.App.UpdateConfig(func(cfg *model.Config) {
  2708  			*cfg.ExperimentalSettings.ClientSideCertEnable = true
  2709  			*cfg.ExperimentalSettings.ClientSideCertCheck = model.CLIENT_SIDE_CERT_CHECK_PRIMARY_AUTH
  2710  		})
  2711  
  2712  		t.Run("missing cert header", func(t *testing.T) {
  2713  			th.Client.Logout()
  2714  			_, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password)
  2715  			CheckBadRequestStatus(t, resp)
  2716  		})
  2717  
  2718  		t.Run("missing cert subject", func(t *testing.T) {
  2719  			th.Client.Logout()
  2720  			th.Client.HttpHeader["X-SSL-Client-Cert"] = "valid_cert_fake"
  2721  			_, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password)
  2722  			CheckBadRequestStatus(t, resp)
  2723  		})
  2724  
  2725  		t.Run("emails mismatch", func(t *testing.T) {
  2726  			th.Client.Logout()
  2727  			th.Client.HttpHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=mis_match" + th.BasicUser.Email
  2728  			_, resp := th.Client.Login(th.BasicUser.Email, "")
  2729  			CheckBadRequestStatus(t, resp)
  2730  		})
  2731  
  2732  		t.Run("successful cba login", func(t *testing.T) {
  2733  			th.Client.HttpHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + th.BasicUser.Email
  2734  			user, resp := th.Client.Login(th.BasicUser.Email, "")
  2735  			CheckNoError(t, resp)
  2736  			require.NotNil(t, user)
  2737  			require.Equal(t, th.BasicUser.Id, user.Id)
  2738  		})
  2739  
  2740  		t.Run("bot login rejected", func(t *testing.T) {
  2741  			bot, resp := th.SystemAdminClient.CreateBot(&model.Bot{
  2742  				Username: "bot",
  2743  			})
  2744  			CheckNoError(t, resp)
  2745  
  2746  			botUser, resp := th.SystemAdminClient.GetUser(bot.UserId, "")
  2747  			CheckNoError(t, resp)
  2748  
  2749  			th.Client.HttpHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + botUser.Email
  2750  
  2751  			_, resp = th.Client.Login(botUser.Email, "")
  2752  			CheckErrorMessage(t, resp, "api.user.login.bot_login_forbidden.app_error")
  2753  		})
  2754  	})
  2755  
  2756  	t.Run("secondary", func(t *testing.T) {
  2757  		th := Setup().InitBasic()
  2758  		defer th.TearDown()
  2759  		th.App.SetLicense(model.NewTestLicense("saml"))
  2760  
  2761  		th.Client.HttpHeader["X-SSL-Client-Cert"] = "valid_cert_fake"
  2762  
  2763  		th.App.UpdateConfig(func(cfg *model.Config) {
  2764  			*cfg.ExperimentalSettings.ClientSideCertEnable = true
  2765  			*cfg.ExperimentalSettings.ClientSideCertCheck = model.CLIENT_SIDE_CERT_CHECK_SECONDARY_AUTH
  2766  		})
  2767  
  2768  		t.Run("password required", func(t *testing.T) {
  2769  			th.Client.HttpHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + th.BasicUser.Email
  2770  			_, resp := th.Client.Login(th.BasicUser.Email, "")
  2771  			CheckBadRequestStatus(t, resp)
  2772  		})
  2773  
  2774  		t.Run("successful cba login with password", func(t *testing.T) {
  2775  			th.Client.HttpHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + th.BasicUser.Email
  2776  			user, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password)
  2777  			CheckNoError(t, resp)
  2778  			require.NotNil(t, user)
  2779  			require.Equal(t, th.BasicUser.Id, user.Id)
  2780  		})
  2781  
  2782  		t.Run("bot login rejected", func(t *testing.T) {
  2783  			bot, resp := th.SystemAdminClient.CreateBot(&model.Bot{
  2784  				Username: "bot",
  2785  			})
  2786  			CheckNoError(t, resp)
  2787  
  2788  			botUser, resp := th.SystemAdminClient.GetUser(bot.UserId, "")
  2789  			CheckNoError(t, resp)
  2790  
  2791  			changed, resp := th.SystemAdminClient.UpdateUserPassword(bot.UserId, "", "password")
  2792  			CheckNoError(t, resp)
  2793  			require.True(t, changed)
  2794  
  2795  			th.Client.HttpHeader["X-SSL-Client-Cert-Subject-DN"] = "C=US, ST=Maryland, L=Pasadena, O=Brent Baccala, OU=FreeSoft, CN=www.freesoft.org/emailAddress=" + botUser.Email
  2796  
  2797  			_, resp = th.Client.Login(botUser.Email, "password")
  2798  			CheckErrorMessage(t, resp, "api.user.login.bot_login_forbidden.app_error")
  2799  		})
  2800  	})
  2801  }
  2802  
  2803  func TestSwitchAccount(t *testing.T) {
  2804  	th := Setup().InitBasic()
  2805  	defer th.TearDown()
  2806  
  2807  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Enable = true })
  2808  
  2809  	th.Client.Logout()
  2810  
  2811  	sr := &model.SwitchRequest{
  2812  		CurrentService: model.USER_AUTH_SERVICE_EMAIL,
  2813  		NewService:     model.USER_AUTH_SERVICE_GITLAB,
  2814  		Email:          th.BasicUser.Email,
  2815  		Password:       th.BasicUser.Password,
  2816  	}
  2817  
  2818  	link, resp := th.Client.SwitchAccountType(sr)
  2819  	CheckNoError(t, resp)
  2820  
  2821  	if link == "" {
  2822  		t.Fatal("bad link")
  2823  	}
  2824  
  2825  	th.App.SetLicense(model.NewTestLicense())
  2826  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExperimentalEnableAuthenticationTransfer = false })
  2827  
  2828  	sr = &model.SwitchRequest{
  2829  		CurrentService: model.USER_AUTH_SERVICE_EMAIL,
  2830  		NewService:     model.USER_AUTH_SERVICE_GITLAB,
  2831  	}
  2832  
  2833  	_, resp = th.Client.SwitchAccountType(sr)
  2834  	CheckForbiddenStatus(t, resp)
  2835  
  2836  	th.LoginBasic()
  2837  
  2838  	sr = &model.SwitchRequest{
  2839  		CurrentService: model.USER_AUTH_SERVICE_SAML,
  2840  		NewService:     model.USER_AUTH_SERVICE_EMAIL,
  2841  		Email:          th.BasicUser.Email,
  2842  		NewPassword:    th.BasicUser.Password,
  2843  	}
  2844  
  2845  	_, resp = th.Client.SwitchAccountType(sr)
  2846  	CheckForbiddenStatus(t, resp)
  2847  
  2848  	sr = &model.SwitchRequest{
  2849  		CurrentService: model.USER_AUTH_SERVICE_EMAIL,
  2850  		NewService:     model.USER_AUTH_SERVICE_LDAP,
  2851  	}
  2852  
  2853  	_, resp = th.Client.SwitchAccountType(sr)
  2854  	CheckForbiddenStatus(t, resp)
  2855  
  2856  	sr = &model.SwitchRequest{
  2857  		CurrentService: model.USER_AUTH_SERVICE_LDAP,
  2858  		NewService:     model.USER_AUTH_SERVICE_EMAIL,
  2859  	}
  2860  
  2861  	_, resp = th.Client.SwitchAccountType(sr)
  2862  	CheckForbiddenStatus(t, resp)
  2863  
  2864  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExperimentalEnableAuthenticationTransfer = true })
  2865  
  2866  	th.LoginBasic()
  2867  
  2868  	fakeAuthData := model.NewId()
  2869  	if result := <-th.App.Srv.Store.User().UpdateAuthData(th.BasicUser.Id, model.USER_AUTH_SERVICE_GITLAB, &fakeAuthData, th.BasicUser.Email, true); result.Err != nil {
  2870  		t.Fatal(result.Err)
  2871  	}
  2872  
  2873  	sr = &model.SwitchRequest{
  2874  		CurrentService: model.USER_AUTH_SERVICE_GITLAB,
  2875  		NewService:     model.USER_AUTH_SERVICE_EMAIL,
  2876  		Email:          th.BasicUser.Email,
  2877  		NewPassword:    th.BasicUser.Password,
  2878  	}
  2879  
  2880  	link, resp = th.Client.SwitchAccountType(sr)
  2881  	CheckNoError(t, resp)
  2882  
  2883  	if link != "/login?extra=signin_change" {
  2884  		t.Log(link)
  2885  		t.Fatal("bad link")
  2886  	}
  2887  
  2888  	th.Client.Logout()
  2889  	_, resp = th.Client.Login(th.BasicUser.Email, th.BasicUser.Password)
  2890  	CheckNoError(t, resp)
  2891  	th.Client.Logout()
  2892  
  2893  	sr = &model.SwitchRequest{
  2894  		CurrentService: model.USER_AUTH_SERVICE_GITLAB,
  2895  		NewService:     model.SERVICE_GOOGLE,
  2896  	}
  2897  
  2898  	_, resp = th.Client.SwitchAccountType(sr)
  2899  	CheckBadRequestStatus(t, resp)
  2900  
  2901  	sr = &model.SwitchRequest{
  2902  		CurrentService: model.USER_AUTH_SERVICE_EMAIL,
  2903  		NewService:     model.USER_AUTH_SERVICE_GITLAB,
  2904  		Password:       th.BasicUser.Password,
  2905  	}
  2906  
  2907  	_, resp = th.Client.SwitchAccountType(sr)
  2908  	CheckNotFoundStatus(t, resp)
  2909  
  2910  	sr = &model.SwitchRequest{
  2911  		CurrentService: model.USER_AUTH_SERVICE_EMAIL,
  2912  		NewService:     model.USER_AUTH_SERVICE_GITLAB,
  2913  		Email:          th.BasicUser.Email,
  2914  	}
  2915  
  2916  	_, resp = th.Client.SwitchAccountType(sr)
  2917  	CheckUnauthorizedStatus(t, resp)
  2918  
  2919  	sr = &model.SwitchRequest{
  2920  		CurrentService: model.USER_AUTH_SERVICE_GITLAB,
  2921  		NewService:     model.USER_AUTH_SERVICE_EMAIL,
  2922  		Email:          th.BasicUser.Email,
  2923  		NewPassword:    th.BasicUser.Password,
  2924  	}
  2925  
  2926  	_, resp = th.Client.SwitchAccountType(sr)
  2927  	CheckUnauthorizedStatus(t, resp)
  2928  }
  2929  
  2930  func assertToken(t *testing.T, th *TestHelper, token *model.UserAccessToken, expectedUserId string) {
  2931  	t.Helper()
  2932  
  2933  	oldSessionToken := th.Client.AuthToken
  2934  	defer func() { th.Client.AuthToken = oldSessionToken }()
  2935  
  2936  	th.Client.AuthToken = token.Token
  2937  	ruser, resp := th.Client.GetMe("")
  2938  	CheckNoError(t, resp)
  2939  
  2940  	assert.Equal(t, expectedUserId, ruser.Id, "returned wrong user")
  2941  }
  2942  
  2943  func assertInvalidToken(t *testing.T, th *TestHelper, token *model.UserAccessToken) {
  2944  	t.Helper()
  2945  
  2946  	oldSessionToken := th.Client.AuthToken
  2947  	defer func() { th.Client.AuthToken = oldSessionToken }()
  2948  
  2949  	th.Client.AuthToken = token.Token
  2950  	_, resp := th.Client.GetMe("")
  2951  	CheckUnauthorizedStatus(t, resp)
  2952  }
  2953  
  2954  func TestCreateUserAccessToken(t *testing.T) {
  2955  	t.Run("create token without permission", func(t *testing.T) {
  2956  		th := Setup().InitBasic()
  2957  		defer th.TearDown()
  2958  
  2959  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  2960  
  2961  		_, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token")
  2962  		CheckForbiddenStatus(t, resp)
  2963  	})
  2964  
  2965  	t.Run("create token for invalid user id", func(t *testing.T) {
  2966  		th := Setup().InitBasic()
  2967  		defer th.TearDown()
  2968  
  2969  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  2970  
  2971  		_, resp := th.Client.CreateUserAccessToken("notarealuserid", "test token")
  2972  		CheckBadRequestStatus(t, resp)
  2973  	})
  2974  
  2975  	t.Run("create token with invalid value", func(t *testing.T) {
  2976  		th := Setup().InitBasic()
  2977  		defer th.TearDown()
  2978  
  2979  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  2980  
  2981  		_, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "")
  2982  		CheckBadRequestStatus(t, resp)
  2983  	})
  2984  
  2985  	t.Run("create token with user access tokens disabled", func(t *testing.T) {
  2986  		th := Setup().InitBasic()
  2987  		defer th.TearDown()
  2988  
  2989  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = false })
  2990  		th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  2991  
  2992  		_, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token")
  2993  		CheckNotImplementedStatus(t, resp)
  2994  	})
  2995  
  2996  	t.Run("create user access token", func(t *testing.T) {
  2997  		th := Setup().InitBasic()
  2998  		defer th.TearDown()
  2999  
  3000  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3001  		th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3002  
  3003  		rtoken, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token")
  3004  		CheckNoError(t, resp)
  3005  
  3006  		assert.Equal(t, th.BasicUser.Id, rtoken.UserId, "wrong user id")
  3007  		assert.NotEmpty(t, rtoken.Token, "token should not be empty")
  3008  		assert.NotEmpty(t, rtoken.Id, "id should not be empty")
  3009  		assert.Equal(t, "test token", rtoken.Description, "description did not match")
  3010  		assert.True(t, rtoken.IsActive, "token should be active")
  3011  
  3012  		assertToken(t, th, rtoken, th.BasicUser.Id)
  3013  	})
  3014  
  3015  	t.Run("create user access token as second user, without permission", func(t *testing.T) {
  3016  		th := Setup().InitBasic()
  3017  		defer th.TearDown()
  3018  
  3019  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3020  
  3021  		_, resp := th.Client.CreateUserAccessToken(th.BasicUser2.Id, "test token")
  3022  		CheckForbiddenStatus(t, resp)
  3023  	})
  3024  
  3025  	t.Run("create user access token for basic user as as system admin", func(t *testing.T) {
  3026  		th := Setup().InitBasic()
  3027  		defer th.TearDown()
  3028  
  3029  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3030  
  3031  		rtoken, resp := th.SystemAdminClient.CreateUserAccessToken(th.BasicUser.Id, "test token")
  3032  		CheckNoError(t, resp)
  3033  		assert.Equal(t, th.BasicUser.Id, rtoken.UserId)
  3034  
  3035  		oldSessionToken := th.Client.AuthToken
  3036  		defer func() { th.Client.AuthToken = oldSessionToken }()
  3037  
  3038  		assertToken(t, th, rtoken, th.BasicUser.Id)
  3039  	})
  3040  
  3041  	t.Run("create access token as oauth session", func(t *testing.T) {
  3042  		th := Setup().InitBasic()
  3043  		defer th.TearDown()
  3044  
  3045  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3046  
  3047  		session, _ := th.App.GetSession(th.Client.AuthToken)
  3048  		session.IsOAuth = true
  3049  		th.App.AddSessionToCache(session)
  3050  
  3051  		_, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token")
  3052  		CheckForbiddenStatus(t, resp)
  3053  	})
  3054  
  3055  	t.Run("create access token for bot created by user", func(t *testing.T) {
  3056  		th := Setup().InitBasic()
  3057  		defer th.TearDown()
  3058  
  3059  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3060  
  3061  		defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
  3062  		th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID)
  3063  		th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3064  		th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false)
  3065  
  3066  		createdBot, resp := th.Client.CreateBot(&model.Bot{
  3067  			Username:    GenerateTestUsername(),
  3068  			DisplayName: "a bot",
  3069  			Description: "bot",
  3070  		})
  3071  		CheckCreatedStatus(t, resp)
  3072  		defer th.App.PermanentDeleteBot(createdBot.UserId)
  3073  
  3074  		t.Run("without MANAGE_BOT permission", func(t *testing.T) {
  3075  			th.RemovePermissionFromRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3076  
  3077  			_, resp = th.Client.CreateUserAccessToken(createdBot.UserId, "test token")
  3078  			CheckForbiddenStatus(t, resp)
  3079  		})
  3080  
  3081  		t.Run("with MANAGE_BOTS permission", func(t *testing.T) {
  3082  			th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3083  
  3084  			token, resp := th.Client.CreateUserAccessToken(createdBot.UserId, "test token")
  3085  			CheckNoError(t, resp)
  3086  			assert.Equal(t, createdBot.UserId, token.UserId)
  3087  			assertToken(t, th, token, createdBot.UserId)
  3088  		})
  3089  	})
  3090  
  3091  	t.Run("create access token for bot created by another user, only having MANAGE_BOTS permission", func(t *testing.T) {
  3092  		th := Setup().InitBasic()
  3093  		defer th.TearDown()
  3094  
  3095  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3096  
  3097  		defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
  3098  		th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID)
  3099  		th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3100  		th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3101  		th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false)
  3102  
  3103  		createdBot, resp := th.SystemAdminClient.CreateBot(&model.Bot{
  3104  			Username:    GenerateTestUsername(),
  3105  			DisplayName: "a bot",
  3106  			Description: "bot",
  3107  		})
  3108  		CheckCreatedStatus(t, resp)
  3109  		defer th.App.PermanentDeleteBot(createdBot.UserId)
  3110  
  3111  		t.Run("only having MANAGE_BOTS permission", func(t *testing.T) {
  3112  			_, resp = th.Client.CreateUserAccessToken(createdBot.UserId, "test token")
  3113  			CheckForbiddenStatus(t, resp)
  3114  		})
  3115  
  3116  		t.Run("with MANAGE_OTHERS_BOTS permission", func(t *testing.T) {
  3117  			th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3118  
  3119  			rtoken, resp := th.Client.CreateUserAccessToken(createdBot.UserId, "test token")
  3120  			CheckNoError(t, resp)
  3121  			assert.Equal(t, createdBot.UserId, rtoken.UserId)
  3122  
  3123  			assertToken(t, th, rtoken, createdBot.UserId)
  3124  		})
  3125  	})
  3126  }
  3127  
  3128  func TestGetUserAccessToken(t *testing.T) {
  3129  	t.Run("get for invalid user id", func(t *testing.T) {
  3130  		th := Setup().InitBasic()
  3131  		defer th.TearDown()
  3132  
  3133  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3134  
  3135  		_, resp := th.Client.GetUserAccessToken("123")
  3136  		CheckBadRequestStatus(t, resp)
  3137  	})
  3138  
  3139  	t.Run("get for unknown user id", func(t *testing.T) {
  3140  		th := Setup().InitBasic()
  3141  		defer th.TearDown()
  3142  
  3143  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3144  
  3145  		_, resp := th.Client.GetUserAccessToken(model.NewId())
  3146  		CheckForbiddenStatus(t, resp)
  3147  	})
  3148  
  3149  	t.Run("get my token", func(t *testing.T) {
  3150  		th := Setup().InitBasic()
  3151  		defer th.TearDown()
  3152  
  3153  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3154  		th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3155  
  3156  		token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token")
  3157  		CheckNoError(t, resp)
  3158  
  3159  		rtoken, resp := th.Client.GetUserAccessToken(token.Id)
  3160  		CheckNoError(t, resp)
  3161  
  3162  		assert.Equal(t, th.BasicUser.Id, rtoken.UserId, "wrong user id")
  3163  		assert.Empty(t, rtoken.Token, "token should be blank")
  3164  		assert.NotEmpty(t, rtoken.Id, "id should not be empty")
  3165  		assert.Equal(t, "test token", rtoken.Description, "description did not match")
  3166  	})
  3167  
  3168  	t.Run("get user token as system admin", func(t *testing.T) {
  3169  		th := Setup().InitBasic()
  3170  		defer th.TearDown()
  3171  
  3172  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3173  
  3174  		th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3175  
  3176  		token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token")
  3177  		CheckNoError(t, resp)
  3178  
  3179  		rtoken, resp := th.SystemAdminClient.GetUserAccessToken(token.Id)
  3180  		CheckNoError(t, resp)
  3181  
  3182  		assert.Equal(t, th.BasicUser.Id, rtoken.UserId, "wrong user id")
  3183  		assert.Empty(t, rtoken.Token, "token should be blank")
  3184  		assert.NotEmpty(t, rtoken.Id, "id should not be empty")
  3185  		assert.Equal(t, "test token", rtoken.Description, "description did not match")
  3186  	})
  3187  
  3188  	t.Run("get token for bot created by user", func(t *testing.T) {
  3189  		th := Setup().InitBasic()
  3190  		defer th.TearDown()
  3191  
  3192  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3193  
  3194  		defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
  3195  		th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID)
  3196  		th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3197  		th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3198  		th.AddPermissionToRole(model.PERMISSION_READ_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3199  		th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false)
  3200  
  3201  		createdBot, resp := th.Client.CreateBot(&model.Bot{
  3202  			Username:    GenerateTestUsername(),
  3203  			DisplayName: "a bot",
  3204  			Description: "bot",
  3205  		})
  3206  		CheckCreatedStatus(t, resp)
  3207  		defer th.App.PermanentDeleteBot(createdBot.UserId)
  3208  
  3209  		token, resp := th.Client.CreateUserAccessToken(createdBot.UserId, "test token")
  3210  		CheckNoError(t, resp)
  3211  
  3212  		t.Run("without MANAGE_BOTS permission", func(t *testing.T) {
  3213  			th.RemovePermissionFromRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3214  
  3215  			_, resp := th.Client.GetUserAccessToken(token.Id)
  3216  			CheckForbiddenStatus(t, resp)
  3217  		})
  3218  
  3219  		t.Run("with MANAGE_BOTS permission", func(t *testing.T) {
  3220  			th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3221  
  3222  			returnedToken, resp := th.Client.GetUserAccessToken(token.Id)
  3223  			CheckNoError(t, resp)
  3224  
  3225  			// Actual token won't be returned.
  3226  			returnedToken.Token = token.Token
  3227  			assert.Equal(t, token, returnedToken)
  3228  		})
  3229  	})
  3230  
  3231  	t.Run("get token for bot created by another user", func(t *testing.T) {
  3232  		th := Setup().InitBasic()
  3233  		defer th.TearDown()
  3234  
  3235  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3236  
  3237  		defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
  3238  		th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID)
  3239  		th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3240  		th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3241  		th.AddPermissionToRole(model.PERMISSION_READ_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3242  		th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false)
  3243  
  3244  		createdBot, resp := th.SystemAdminClient.CreateBot(&model.Bot{
  3245  			Username:    GenerateTestUsername(),
  3246  			DisplayName: "a bot",
  3247  			Description: "bot",
  3248  		})
  3249  		CheckCreatedStatus(t, resp)
  3250  		defer th.App.PermanentDeleteBot(createdBot.UserId)
  3251  
  3252  		token, resp := th.SystemAdminClient.CreateUserAccessToken(createdBot.UserId, "test token")
  3253  		CheckNoError(t, resp)
  3254  
  3255  		t.Run("only having MANAGE_BOTS permission", func(t *testing.T) {
  3256  			_, resp = th.Client.GetUserAccessToken(token.Id)
  3257  			CheckForbiddenStatus(t, resp)
  3258  		})
  3259  
  3260  		t.Run("with MANAGE_OTHERS_BOTS permission", func(t *testing.T) {
  3261  			th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3262  
  3263  			returnedToken, resp := th.Client.GetUserAccessToken(token.Id)
  3264  			CheckNoError(t, resp)
  3265  
  3266  			// Actual token won't be returned.
  3267  			returnedToken.Token = token.Token
  3268  			assert.Equal(t, token, returnedToken)
  3269  		})
  3270  	})
  3271  }
  3272  
  3273  func TestGetUserAccessTokensForUser(t *testing.T) {
  3274  	t.Run("multiple tokens, offset 0, limit 100", func(t *testing.T) {
  3275  		th := Setup().InitBasic()
  3276  		defer th.TearDown()
  3277  
  3278  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3279  
  3280  		th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3281  
  3282  		_, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token")
  3283  		CheckNoError(t, resp)
  3284  
  3285  		_, resp = th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token 2")
  3286  		CheckNoError(t, resp)
  3287  
  3288  		rtokens, resp := th.Client.GetUserAccessTokensForUser(th.BasicUser.Id, 0, 100)
  3289  		CheckNoError(t, resp)
  3290  
  3291  		assert.Len(t, rtokens, 2, "should have 2 tokens")
  3292  		for _, uat := range rtokens {
  3293  			assert.Equal(t, th.BasicUser.Id, uat.UserId, "wrong user id")
  3294  		}
  3295  	})
  3296  
  3297  	t.Run("multiple tokens as system admin, offset 0, limit 100", func(t *testing.T) {
  3298  		th := Setup().InitBasic()
  3299  		defer th.TearDown()
  3300  
  3301  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3302  
  3303  		th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3304  
  3305  		_, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token")
  3306  		CheckNoError(t, resp)
  3307  
  3308  		_, resp = th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token 2")
  3309  		CheckNoError(t, resp)
  3310  
  3311  		rtokens, resp := th.Client.GetUserAccessTokensForUser(th.BasicUser.Id, 0, 100)
  3312  		CheckNoError(t, resp)
  3313  
  3314  		assert.Len(t, rtokens, 2, "should have 2 tokens")
  3315  		for _, uat := range rtokens {
  3316  			assert.Equal(t, th.BasicUser.Id, uat.UserId, "wrong user id")
  3317  		}
  3318  	})
  3319  
  3320  	t.Run("multiple tokens, offset 1, limit 1", func(t *testing.T) {
  3321  		th := Setup().InitBasic()
  3322  		defer th.TearDown()
  3323  
  3324  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3325  
  3326  		th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3327  
  3328  		_, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token")
  3329  		CheckNoError(t, resp)
  3330  
  3331  		_, resp = th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token 2")
  3332  		CheckNoError(t, resp)
  3333  
  3334  		rtokens, resp := th.Client.GetUserAccessTokensForUser(th.BasicUser.Id, 1, 1)
  3335  		CheckNoError(t, resp)
  3336  
  3337  		assert.Len(t, rtokens, 1, "should have 1 tokens")
  3338  		for _, uat := range rtokens {
  3339  			assert.Equal(t, th.BasicUser.Id, uat.UserId, "wrong user id")
  3340  		}
  3341  	})
  3342  }
  3343  
  3344  func TestGetUserAccessTokens(t *testing.T) {
  3345  	t.Run("GetUserAccessTokens, not a system admin", func(t *testing.T) {
  3346  		th := Setup().InitBasic()
  3347  		defer th.TearDown()
  3348  
  3349  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3350  
  3351  		th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3352  
  3353  		_, resp := th.Client.GetUserAccessTokens(0, 100)
  3354  		CheckForbiddenStatus(t, resp)
  3355  	})
  3356  
  3357  	t.Run("GetUserAccessTokens, as a system admin, page 1, perPage 1", func(t *testing.T) {
  3358  		th := Setup().InitBasic()
  3359  		defer th.TearDown()
  3360  
  3361  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3362  
  3363  		th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3364  
  3365  		_, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token 2")
  3366  		CheckNoError(t, resp)
  3367  
  3368  		_, resp = th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token 2")
  3369  		CheckNoError(t, resp)
  3370  
  3371  		rtokens, resp := th.SystemAdminClient.GetUserAccessTokens(1, 1)
  3372  		CheckNoError(t, resp)
  3373  
  3374  		assert.Len(t, rtokens, 1, "should have 1 token")
  3375  	})
  3376  
  3377  	t.Run("GetUserAccessTokens, as a system admin, page 0, perPage 2", func(t *testing.T) {
  3378  		th := Setup().InitBasic()
  3379  		defer th.TearDown()
  3380  
  3381  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3382  
  3383  		th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3384  
  3385  		_, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token 2")
  3386  		CheckNoError(t, resp)
  3387  
  3388  		_, resp = th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token 2")
  3389  		CheckNoError(t, resp)
  3390  
  3391  		rtokens, resp := th.SystemAdminClient.GetUserAccessTokens(0, 2)
  3392  		CheckNoError(t, resp)
  3393  
  3394  		assert.Len(t, rtokens, 2, "should have 2 tokens")
  3395  	})
  3396  }
  3397  
  3398  func TestSearchUserAccessToken(t *testing.T) {
  3399  	th := Setup().InitBasic()
  3400  	defer th.TearDown()
  3401  
  3402  	testDescription := "test token"
  3403  
  3404  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3405  
  3406  	th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3407  	token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  3408  	CheckNoError(t, resp)
  3409  
  3410  	_, resp = th.Client.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: token.Id})
  3411  	CheckForbiddenStatus(t, resp)
  3412  
  3413  	rtokens, resp := th.SystemAdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: th.BasicUser.Id})
  3414  	CheckNoError(t, resp)
  3415  
  3416  	if len(rtokens) != 1 {
  3417  		t.Fatal("should have 1 tokens")
  3418  	}
  3419  
  3420  	rtokens, resp = th.SystemAdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: token.Id})
  3421  	CheckNoError(t, resp)
  3422  
  3423  	if len(rtokens) != 1 {
  3424  		t.Fatal("should have 1 tokens")
  3425  	}
  3426  
  3427  	rtokens, resp = th.SystemAdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: th.BasicUser.Username})
  3428  	CheckNoError(t, resp)
  3429  
  3430  	if len(rtokens) != 1 {
  3431  		t.Fatal("should have 1 tokens")
  3432  	}
  3433  
  3434  	rtokens, resp = th.SystemAdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: "not found"})
  3435  	CheckNoError(t, resp)
  3436  
  3437  	if len(rtokens) != 0 {
  3438  		t.Fatal("should have 0 tokens")
  3439  	}
  3440  }
  3441  
  3442  func TestRevokeUserAccessToken(t *testing.T) {
  3443  	t.Run("revoke user token", func(t *testing.T) {
  3444  		th := Setup().InitBasic()
  3445  		defer th.TearDown()
  3446  
  3447  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3448  
  3449  		th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3450  		token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token")
  3451  		CheckNoError(t, resp)
  3452  		assertToken(t, th, token, th.BasicUser.Id)
  3453  
  3454  		ok, resp := th.Client.RevokeUserAccessToken(token.Id)
  3455  		CheckNoError(t, resp)
  3456  		assert.True(t, ok, "should have passed")
  3457  
  3458  		assertInvalidToken(t, th, token)
  3459  	})
  3460  
  3461  	t.Run("revoke token belonging to another user", func(t *testing.T) {
  3462  		th := Setup().InitBasic()
  3463  		defer th.TearDown()
  3464  
  3465  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3466  
  3467  		token, resp := th.SystemAdminClient.CreateUserAccessToken(th.BasicUser2.Id, "test token")
  3468  		CheckNoError(t, resp)
  3469  
  3470  		ok, resp := th.Client.RevokeUserAccessToken(token.Id)
  3471  		CheckForbiddenStatus(t, resp)
  3472  		assert.False(t, ok, "should have failed")
  3473  	})
  3474  
  3475  	t.Run("revoke token for bot created by user", func(t *testing.T) {
  3476  		th := Setup().InitBasic()
  3477  		defer th.TearDown()
  3478  
  3479  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3480  
  3481  		defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
  3482  		th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID)
  3483  		th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3484  		th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3485  		th.AddPermissionToRole(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3486  		th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false)
  3487  
  3488  		createdBot, resp := th.Client.CreateBot(&model.Bot{
  3489  			Username:    GenerateTestUsername(),
  3490  			DisplayName: "a bot",
  3491  			Description: "bot",
  3492  		})
  3493  		CheckCreatedStatus(t, resp)
  3494  		defer th.App.PermanentDeleteBot(createdBot.UserId)
  3495  
  3496  		token, resp := th.Client.CreateUserAccessToken(createdBot.UserId, "test token")
  3497  		CheckNoError(t, resp)
  3498  
  3499  		t.Run("without MANAGE_BOTS permission", func(t *testing.T) {
  3500  			th.RemovePermissionFromRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3501  
  3502  			_, resp := th.Client.RevokeUserAccessToken(token.Id)
  3503  			CheckForbiddenStatus(t, resp)
  3504  		})
  3505  
  3506  		t.Run("with MANAGE_BOTS permission", func(t *testing.T) {
  3507  			th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3508  
  3509  			ok, resp := th.Client.RevokeUserAccessToken(token.Id)
  3510  			CheckNoError(t, resp)
  3511  			assert.True(t, ok, "should have passed")
  3512  		})
  3513  	})
  3514  
  3515  	t.Run("revoke token for bot created by another user", func(t *testing.T) {
  3516  		th := Setup().InitBasic()
  3517  		defer th.TearDown()
  3518  
  3519  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3520  
  3521  		defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
  3522  		th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID)
  3523  		th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3524  		th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3525  		th.AddPermissionToRole(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3526  		th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false)
  3527  
  3528  		createdBot, resp := th.SystemAdminClient.CreateBot(&model.Bot{
  3529  			Username:    GenerateTestUsername(),
  3530  			DisplayName: "a bot",
  3531  			Description: "bot",
  3532  		})
  3533  		CheckCreatedStatus(t, resp)
  3534  		defer th.App.PermanentDeleteBot(createdBot.UserId)
  3535  
  3536  		token, resp := th.SystemAdminClient.CreateUserAccessToken(createdBot.UserId, "test token")
  3537  		CheckNoError(t, resp)
  3538  
  3539  		t.Run("only having MANAGE_BOTS permission", func(t *testing.T) {
  3540  			_, resp = th.Client.RevokeUserAccessToken(token.Id)
  3541  			CheckForbiddenStatus(t, resp)
  3542  		})
  3543  
  3544  		t.Run("with MANAGE_OTHERS_BOTS permission", func(t *testing.T) {
  3545  			th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3546  
  3547  			ok, resp := th.Client.RevokeUserAccessToken(token.Id)
  3548  			CheckNoError(t, resp)
  3549  			assert.True(t, ok, "should have passed")
  3550  		})
  3551  	})
  3552  }
  3553  
  3554  func TestDisableUserAccessToken(t *testing.T) {
  3555  	t.Run("disable user token", func(t *testing.T) {
  3556  		th := Setup().InitBasic()
  3557  		defer th.TearDown()
  3558  
  3559  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3560  
  3561  		th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3562  		token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token")
  3563  		CheckNoError(t, resp)
  3564  		assertToken(t, th, token, th.BasicUser.Id)
  3565  
  3566  		ok, resp := th.Client.DisableUserAccessToken(token.Id)
  3567  		CheckNoError(t, resp)
  3568  		assert.True(t, ok, "should have passed")
  3569  
  3570  		assertInvalidToken(t, th, token)
  3571  	})
  3572  
  3573  	t.Run("disable token belonging to another user", func(t *testing.T) {
  3574  		th := Setup().InitBasic()
  3575  		defer th.TearDown()
  3576  
  3577  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3578  
  3579  		token, resp := th.SystemAdminClient.CreateUserAccessToken(th.BasicUser2.Id, "test token")
  3580  		CheckNoError(t, resp)
  3581  
  3582  		ok, resp := th.Client.DisableUserAccessToken(token.Id)
  3583  		CheckForbiddenStatus(t, resp)
  3584  		assert.False(t, ok, "should have failed")
  3585  	})
  3586  
  3587  	t.Run("disable token for bot created by user", func(t *testing.T) {
  3588  		th := Setup().InitBasic()
  3589  		defer th.TearDown()
  3590  
  3591  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3592  
  3593  		defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
  3594  		th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID)
  3595  		th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3596  		th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3597  		th.AddPermissionToRole(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3598  		th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false)
  3599  
  3600  		createdBot, resp := th.Client.CreateBot(&model.Bot{
  3601  			Username:    GenerateTestUsername(),
  3602  			DisplayName: "a bot",
  3603  			Description: "bot",
  3604  		})
  3605  		CheckCreatedStatus(t, resp)
  3606  		defer th.App.PermanentDeleteBot(createdBot.UserId)
  3607  
  3608  		token, resp := th.Client.CreateUserAccessToken(createdBot.UserId, "test token")
  3609  		CheckNoError(t, resp)
  3610  
  3611  		t.Run("without MANAGE_BOTS permission", func(t *testing.T) {
  3612  			th.RemovePermissionFromRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3613  
  3614  			_, resp := th.Client.DisableUserAccessToken(token.Id)
  3615  			CheckForbiddenStatus(t, resp)
  3616  		})
  3617  
  3618  		t.Run("with MANAGE_BOTS permission", func(t *testing.T) {
  3619  			th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3620  
  3621  			ok, resp := th.Client.DisableUserAccessToken(token.Id)
  3622  			CheckNoError(t, resp)
  3623  			assert.True(t, ok, "should have passed")
  3624  		})
  3625  	})
  3626  
  3627  	t.Run("disable token for bot created by another user", func(t *testing.T) {
  3628  		th := Setup().InitBasic()
  3629  		defer th.TearDown()
  3630  
  3631  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3632  
  3633  		defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
  3634  		th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID)
  3635  		th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3636  		th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3637  		th.AddPermissionToRole(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3638  		th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false)
  3639  
  3640  		createdBot, resp := th.SystemAdminClient.CreateBot(&model.Bot{
  3641  			Username:    GenerateTestUsername(),
  3642  			DisplayName: "a bot",
  3643  			Description: "bot",
  3644  		})
  3645  		CheckCreatedStatus(t, resp)
  3646  		defer th.App.PermanentDeleteBot(createdBot.UserId)
  3647  
  3648  		token, resp := th.SystemAdminClient.CreateUserAccessToken(createdBot.UserId, "test token")
  3649  		CheckNoError(t, resp)
  3650  
  3651  		t.Run("only having MANAGE_BOTS permission", func(t *testing.T) {
  3652  			_, resp = th.Client.DisableUserAccessToken(token.Id)
  3653  			CheckForbiddenStatus(t, resp)
  3654  		})
  3655  
  3656  		t.Run("with MANAGE_OTHERS_BOTS permission", func(t *testing.T) {
  3657  			th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3658  
  3659  			ok, resp := th.Client.DisableUserAccessToken(token.Id)
  3660  			CheckNoError(t, resp)
  3661  			assert.True(t, ok, "should have passed")
  3662  		})
  3663  	})
  3664  }
  3665  
  3666  func TestEnableUserAccessToken(t *testing.T) {
  3667  	t.Run("enable user token", func(t *testing.T) {
  3668  		th := Setup().InitBasic()
  3669  		defer th.TearDown()
  3670  
  3671  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3672  
  3673  		th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3674  		token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token")
  3675  		CheckNoError(t, resp)
  3676  		assertToken(t, th, token, th.BasicUser.Id)
  3677  
  3678  		ok, resp := th.Client.DisableUserAccessToken(token.Id)
  3679  		CheckNoError(t, resp)
  3680  		assert.True(t, ok, "should have passed")
  3681  
  3682  		assertInvalidToken(t, th, token)
  3683  
  3684  		ok, resp = th.Client.EnableUserAccessToken(token.Id)
  3685  		CheckNoError(t, resp)
  3686  		assert.True(t, ok, "should have passed")
  3687  
  3688  		assertToken(t, th, token, th.BasicUser.Id)
  3689  	})
  3690  
  3691  	t.Run("enable token belonging to another user", func(t *testing.T) {
  3692  		th := Setup().InitBasic()
  3693  		defer th.TearDown()
  3694  
  3695  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3696  
  3697  		token, resp := th.SystemAdminClient.CreateUserAccessToken(th.BasicUser2.Id, "test token")
  3698  		CheckNoError(t, resp)
  3699  
  3700  		ok, resp := th.SystemAdminClient.DisableUserAccessToken(token.Id)
  3701  		CheckNoError(t, resp)
  3702  		assert.True(t, ok, "should have passed")
  3703  
  3704  		ok, resp = th.Client.DisableUserAccessToken(token.Id)
  3705  		CheckForbiddenStatus(t, resp)
  3706  		assert.False(t, ok, "should have failed")
  3707  	})
  3708  
  3709  	t.Run("enable token for bot created by user", func(t *testing.T) {
  3710  		th := Setup().InitBasic()
  3711  		defer th.TearDown()
  3712  
  3713  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3714  
  3715  		defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
  3716  		th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID)
  3717  		th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3718  		th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3719  		th.AddPermissionToRole(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3720  		th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false)
  3721  
  3722  		createdBot, resp := th.Client.CreateBot(&model.Bot{
  3723  			Username:    GenerateTestUsername(),
  3724  			DisplayName: "a bot",
  3725  			Description: "bot",
  3726  		})
  3727  		CheckCreatedStatus(t, resp)
  3728  		defer th.App.PermanentDeleteBot(createdBot.UserId)
  3729  
  3730  		token, resp := th.Client.CreateUserAccessToken(createdBot.UserId, "test token")
  3731  		CheckNoError(t, resp)
  3732  
  3733  		ok, resp := th.Client.DisableUserAccessToken(token.Id)
  3734  		CheckNoError(t, resp)
  3735  		assert.True(t, ok, "should have passed")
  3736  
  3737  		t.Run("without MANAGE_BOTS permission", func(t *testing.T) {
  3738  			th.RemovePermissionFromRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3739  
  3740  			_, resp := th.Client.EnableUserAccessToken(token.Id)
  3741  			CheckForbiddenStatus(t, resp)
  3742  		})
  3743  
  3744  		t.Run("with MANAGE_BOTS permission", func(t *testing.T) {
  3745  			th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3746  
  3747  			ok, resp := th.Client.EnableUserAccessToken(token.Id)
  3748  			CheckNoError(t, resp)
  3749  			assert.True(t, ok, "should have passed")
  3750  		})
  3751  	})
  3752  
  3753  	t.Run("enable token for bot created by another user", func(t *testing.T) {
  3754  		th := Setup().InitBasic()
  3755  		defer th.TearDown()
  3756  
  3757  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3758  
  3759  		defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
  3760  		th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID)
  3761  		th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3762  		th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3763  		th.AddPermissionToRole(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID)
  3764  		th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false)
  3765  
  3766  		createdBot, resp := th.SystemAdminClient.CreateBot(&model.Bot{
  3767  			Username:    GenerateTestUsername(),
  3768  			DisplayName: "a bot",
  3769  			Description: "bot",
  3770  		})
  3771  		CheckCreatedStatus(t, resp)
  3772  		defer th.App.PermanentDeleteBot(createdBot.UserId)
  3773  
  3774  		token, resp := th.SystemAdminClient.CreateUserAccessToken(createdBot.UserId, "test token")
  3775  		CheckNoError(t, resp)
  3776  
  3777  		ok, resp := th.SystemAdminClient.DisableUserAccessToken(token.Id)
  3778  		CheckNoError(t, resp)
  3779  		assert.True(t, ok, "should have passed")
  3780  
  3781  		t.Run("only having MANAGE_BOTS permission", func(t *testing.T) {
  3782  			_, resp := th.Client.EnableUserAccessToken(token.Id)
  3783  			CheckForbiddenStatus(t, resp)
  3784  		})
  3785  
  3786  		t.Run("with MANAGE_OTHERS_BOTS permission", func(t *testing.T) {
  3787  			th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID)
  3788  
  3789  			ok, resp := th.Client.EnableUserAccessToken(token.Id)
  3790  			CheckNoError(t, resp)
  3791  			assert.True(t, ok, "should have passed")
  3792  		})
  3793  	})
  3794  }
  3795  
  3796  func TestUserAccessTokenInactiveUser(t *testing.T) {
  3797  	th := Setup().InitBasic()
  3798  	defer th.TearDown()
  3799  
  3800  	testDescription := "test token"
  3801  
  3802  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3803  
  3804  	th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3805  	token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  3806  	CheckNoError(t, resp)
  3807  
  3808  	th.Client.AuthToken = token.Token
  3809  	_, resp = th.Client.GetMe("")
  3810  	CheckNoError(t, resp)
  3811  
  3812  	th.App.UpdateActive(th.BasicUser, false)
  3813  
  3814  	_, resp = th.Client.GetMe("")
  3815  	CheckUnauthorizedStatus(t, resp)
  3816  }
  3817  
  3818  func TestUserAccessTokenDisableConfig(t *testing.T) {
  3819  	th := Setup().InitBasic()
  3820  	defer th.TearDown()
  3821  
  3822  	testDescription := "test token"
  3823  
  3824  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true })
  3825  
  3826  	th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false)
  3827  	token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
  3828  	CheckNoError(t, resp)
  3829  
  3830  	oldSessionToken := th.Client.AuthToken
  3831  	th.Client.AuthToken = token.Token
  3832  	_, resp = th.Client.GetMe("")
  3833  	CheckNoError(t, resp)
  3834  
  3835  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = false })
  3836  
  3837  	_, resp = th.Client.GetMe("")
  3838  	CheckUnauthorizedStatus(t, resp)
  3839  
  3840  	th.Client.AuthToken = oldSessionToken
  3841  	_, resp = th.Client.GetMe("")
  3842  	CheckNoError(t, resp)
  3843  }
  3844  
  3845  func TestGetUsersByStatus(t *testing.T) {
  3846  	th := Setup()
  3847  	defer th.TearDown()
  3848  
  3849  	team, err := th.App.CreateTeam(&model.Team{
  3850  		DisplayName: "dn_" + model.NewId(),
  3851  		Name:        GenerateTestTeamName(),
  3852  		Email:       th.GenerateTestEmail(),
  3853  		Type:        model.TEAM_OPEN,
  3854  	})
  3855  	if err != nil {
  3856  		t.Fatalf("failed to create team: %v", err)
  3857  	}
  3858  
  3859  	channel, err := th.App.CreateChannel(&model.Channel{
  3860  		DisplayName: "dn_" + model.NewId(),
  3861  		Name:        "name_" + model.NewId(),
  3862  		Type:        model.CHANNEL_OPEN,
  3863  		TeamId:      team.Id,
  3864  		CreatorId:   model.NewId(),
  3865  	}, false)
  3866  	if err != nil {
  3867  		t.Fatalf("failed to create channel: %v", err)
  3868  	}
  3869  
  3870  	createUserWithStatus := func(username string, status string) *model.User {
  3871  		id := model.NewId()
  3872  
  3873  		user, err := th.App.CreateUser(&model.User{
  3874  			Email:    "success+" + id + "@simulator.amazonses.com",
  3875  			Username: "un_" + username + "_" + id,
  3876  			Nickname: "nn_" + id,
  3877  			Password: "Password1",
  3878  		})
  3879  		if err != nil {
  3880  			t.Fatalf("failed to create user: %v", err)
  3881  		}
  3882  
  3883  		th.LinkUserToTeam(user, team)
  3884  		th.AddUserToChannel(user, channel)
  3885  
  3886  		th.App.SaveAndBroadcastStatus(&model.Status{
  3887  			UserId: user.Id,
  3888  			Status: status,
  3889  			Manual: true,
  3890  		})
  3891  
  3892  		return user
  3893  	}
  3894  
  3895  	// Creating these out of order in case that affects results
  3896  	offlineUser1 := createUserWithStatus("offline1", model.STATUS_OFFLINE)
  3897  	offlineUser2 := createUserWithStatus("offline2", model.STATUS_OFFLINE)
  3898  	awayUser1 := createUserWithStatus("away1", model.STATUS_AWAY)
  3899  	awayUser2 := createUserWithStatus("away2", model.STATUS_AWAY)
  3900  	onlineUser1 := createUserWithStatus("online1", model.STATUS_ONLINE)
  3901  	onlineUser2 := createUserWithStatus("online2", model.STATUS_ONLINE)
  3902  	dndUser1 := createUserWithStatus("dnd1", model.STATUS_DND)
  3903  	dndUser2 := createUserWithStatus("dnd2", model.STATUS_DND)
  3904  
  3905  	client := th.CreateClient()
  3906  	if _, resp := client.Login(onlineUser2.Username, "Password1"); resp.Error != nil {
  3907  		t.Fatal(resp.Error)
  3908  	}
  3909  
  3910  	t.Run("sorting by status then alphabetical", func(t *testing.T) {
  3911  		usersByStatus, resp := client.GetUsersInChannelByStatus(channel.Id, 0, 8, "")
  3912  		if resp.Error != nil {
  3913  			t.Fatal(resp.Error)
  3914  		}
  3915  
  3916  		expectedUsersByStatus := []*model.User{
  3917  			onlineUser1,
  3918  			onlineUser2,
  3919  			awayUser1,
  3920  			awayUser2,
  3921  			dndUser1,
  3922  			dndUser2,
  3923  			offlineUser1,
  3924  			offlineUser2,
  3925  		}
  3926  
  3927  		if len(usersByStatus) != len(expectedUsersByStatus) {
  3928  			t.Fatalf("received only %v users, expected %v", len(usersByStatus), len(expectedUsersByStatus))
  3929  		}
  3930  
  3931  		for i := range usersByStatus {
  3932  			if usersByStatus[i].Id != expectedUsersByStatus[i].Id {
  3933  				t.Fatalf("received user %v at index %v, expected %v", usersByStatus[i].Username, i, expectedUsersByStatus[i].Username)
  3934  			}
  3935  		}
  3936  	})
  3937  
  3938  	t.Run("paging", func(t *testing.T) {
  3939  		usersByStatus, resp := client.GetUsersInChannelByStatus(channel.Id, 0, 3, "")
  3940  		if resp.Error != nil {
  3941  			t.Fatal(resp.Error)
  3942  		}
  3943  
  3944  		if len(usersByStatus) != 3 {
  3945  			t.Fatal("received too many users")
  3946  		}
  3947  
  3948  		if usersByStatus[0].Id != onlineUser1.Id && usersByStatus[1].Id != onlineUser2.Id {
  3949  			t.Fatal("expected to receive online users first")
  3950  		}
  3951  
  3952  		if usersByStatus[2].Id != awayUser1.Id {
  3953  			t.Fatal("expected to receive away users second")
  3954  		}
  3955  
  3956  		usersByStatus, resp = client.GetUsersInChannelByStatus(channel.Id, 1, 3, "")
  3957  		if resp.Error != nil {
  3958  			t.Fatal(resp.Error)
  3959  		}
  3960  
  3961  		if usersByStatus[0].Id != awayUser2.Id {
  3962  			t.Fatal("expected to receive away users second")
  3963  		}
  3964  
  3965  		if usersByStatus[1].Id != dndUser1.Id && usersByStatus[2].Id != dndUser2.Id {
  3966  			t.Fatal("expected to receive dnd users third")
  3967  		}
  3968  
  3969  		usersByStatus, resp = client.GetUsersInChannelByStatus(channel.Id, 1, 4, "")
  3970  		if resp.Error != nil {
  3971  			t.Fatal(resp.Error)
  3972  		}
  3973  
  3974  		if len(usersByStatus) != 4 {
  3975  			t.Fatal("received too many users")
  3976  		}
  3977  
  3978  		if usersByStatus[0].Id != dndUser1.Id && usersByStatus[1].Id != dndUser2.Id {
  3979  			t.Fatal("expected to receive dnd users third")
  3980  		}
  3981  
  3982  		if usersByStatus[2].Id != offlineUser1.Id && usersByStatus[3].Id != offlineUser2.Id {
  3983  			t.Fatal("expected to receive offline users last")
  3984  		}
  3985  	})
  3986  }
  3987  
  3988  func TestRegisterTermsOfServiceAction(t *testing.T) {
  3989  	th := Setup().InitBasic()
  3990  	defer th.TearDown()
  3991  
  3992  	success, resp := th.Client.RegisterTermsOfServiceAction(th.BasicUser.Id, "st_1", true)
  3993  	CheckErrorMessage(t, resp, "store.sql_terms_of_service_store.get.no_rows.app_error")
  3994  
  3995  	termsOfService, err := th.App.CreateTermsOfService("terms of service", th.BasicUser.Id)
  3996  	if err != nil {
  3997  		t.Fatal(err)
  3998  	}
  3999  
  4000  	success, resp = th.Client.RegisterTermsOfServiceAction(th.BasicUser.Id, termsOfService.Id, true)
  4001  	CheckNoError(t, resp)
  4002  
  4003  	assert.True(t, *success)
  4004  	_, err = th.App.GetUser(th.BasicUser.Id)
  4005  	if err != nil {
  4006  		t.Fatal(err)
  4007  	}
  4008  }
  4009  
  4010  func TestGetUserTermsOfService(t *testing.T) {
  4011  	th := Setup().InitBasic()
  4012  	defer th.TearDown()
  4013  
  4014  	_, resp := th.Client.GetUserTermsOfService(th.BasicUser.Id, "")
  4015  	CheckErrorMessage(t, resp, "store.sql_user_terms_of_service.get_by_user.no_rows.app_error")
  4016  
  4017  	termsOfService, err := th.App.CreateTermsOfService("terms of service", th.BasicUser.Id)
  4018  	if err != nil {
  4019  		t.Fatal(err)
  4020  	}
  4021  
  4022  	success, resp := th.Client.RegisterTermsOfServiceAction(th.BasicUser.Id, termsOfService.Id, true)
  4023  	CheckNoError(t, resp)
  4024  	assert.True(t, *success)
  4025  
  4026  	userTermsOfService, resp := th.Client.GetUserTermsOfService(th.BasicUser.Id, "")
  4027  	CheckNoError(t, resp)
  4028  
  4029  	assert.Equal(t, th.BasicUser.Id, userTermsOfService.UserId)
  4030  	assert.Equal(t, termsOfService.Id, userTermsOfService.TermsOfServiceId)
  4031  	assert.NotEmpty(t, userTermsOfService.CreateAt)
  4032  }
  4033  
  4034  func TestLoginLockout(t *testing.T) {
  4035  	th := Setup().InitBasic()
  4036  	defer th.TearDown()
  4037  
  4038  	_, resp := th.Client.Logout()
  4039  	CheckNoError(t, resp)
  4040  
  4041  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.MaximumLoginAttempts = 3 })
  4042  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true })
  4043  
  4044  	_, resp = th.Client.Login(th.BasicUser.Email, "wrong")
  4045  	CheckErrorMessage(t, resp, "api.user.check_user_password.invalid.app_error")
  4046  	_, resp = th.Client.Login(th.BasicUser.Email, "wrong")
  4047  	CheckErrorMessage(t, resp, "api.user.check_user_password.invalid.app_error")
  4048  	_, resp = th.Client.Login(th.BasicUser.Email, "wrong")
  4049  	CheckErrorMessage(t, resp, "api.user.check_user_password.invalid.app_error")
  4050  	_, resp = th.Client.Login(th.BasicUser.Email, "wrong")
  4051  	CheckErrorMessage(t, resp, "api.user.check_user_login_attempts.too_many.app_error")
  4052  	_, resp = th.Client.Login(th.BasicUser.Email, "wrong")
  4053  	CheckErrorMessage(t, resp, "api.user.check_user_login_attempts.too_many.app_error")
  4054  
  4055  	// Fake user has MFA enabled
  4056  	if result := <-th.Server.Store.User().UpdateMfaActive(th.BasicUser2.Id, true); result.Err != nil {
  4057  		t.Fatal(result.Err)
  4058  	}
  4059  	_, resp = th.Client.LoginWithMFA(th.BasicUser2.Email, th.BasicUser2.Password, "000000")
  4060  	CheckErrorMessage(t, resp, "api.user.check_user_mfa.bad_code.app_error")
  4061  	_, resp = th.Client.LoginWithMFA(th.BasicUser2.Email, th.BasicUser2.Password, "000000")
  4062  	CheckErrorMessage(t, resp, "api.user.check_user_mfa.bad_code.app_error")
  4063  	_, resp = th.Client.LoginWithMFA(th.BasicUser2.Email, th.BasicUser2.Password, "000000")
  4064  	CheckErrorMessage(t, resp, "api.user.check_user_mfa.bad_code.app_error")
  4065  	_, resp = th.Client.LoginWithMFA(th.BasicUser2.Email, th.BasicUser2.Password, "000000")
  4066  	CheckErrorMessage(t, resp, "api.user.check_user_login_attempts.too_many.app_error")
  4067  	_, resp = th.Client.LoginWithMFA(th.BasicUser2.Email, th.BasicUser2.Password, "000000")
  4068  	CheckErrorMessage(t, resp, "api.user.check_user_login_attempts.too_many.app_error")
  4069  }