github.com/spreadshirt/mattermost-server@v5.3.2-0.20180927191755-a257d501df3d+incompatible/api4/user_test.go (about)

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