github.com/xzl8028/xenia-server@v0.0.0-20190809101854-18450a97da63/api4/user_test.go (about)

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