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

     1  // Copyright (c) 2017-present Xenia, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package api4
     5  
     6  import (
     7  	"fmt"
     8  	"net/http"
     9  	"reflect"
    10  	"sort"
    11  	"strconv"
    12  	"strings"
    13  	"testing"
    14  	"time"
    15  
    16  	"github.com/xzl8028/xenia-server/model"
    17  	"github.com/xzl8028/xenia-server/utils"
    18  	"github.com/stretchr/testify/assert"
    19  	"github.com/stretchr/testify/require"
    20  )
    21  
    22  func TestCreateChannel(t *testing.T) {
    23  	th := Setup().InitBasic()
    24  	defer th.TearDown()
    25  	Client := th.Client
    26  	team := th.BasicTeam
    27  
    28  	channel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id}
    29  	private := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_PRIVATE, TeamId: team.Id}
    30  
    31  	rchannel, resp := Client.CreateChannel(channel)
    32  	CheckNoError(t, resp)
    33  	CheckCreatedStatus(t, resp)
    34  
    35  	if rchannel.Name != channel.Name {
    36  		t.Fatal("names did not match")
    37  	}
    38  
    39  	if rchannel.DisplayName != channel.DisplayName {
    40  		t.Fatal("display names did not match")
    41  	}
    42  
    43  	if rchannel.TeamId != channel.TeamId {
    44  		t.Fatal("team ids did not match")
    45  	}
    46  
    47  	rprivate, resp := Client.CreateChannel(private)
    48  	CheckNoError(t, resp)
    49  
    50  	if rprivate.Name != private.Name {
    51  		t.Fatal("names did not match")
    52  	}
    53  
    54  	if rprivate.Type != model.CHANNEL_PRIVATE {
    55  		t.Fatal("wrong channel type")
    56  	}
    57  
    58  	if rprivate.CreatorId != th.BasicUser.Id {
    59  		t.Fatal("wrong creator id")
    60  	}
    61  
    62  	_, resp = Client.CreateChannel(channel)
    63  	CheckErrorMessage(t, resp, "store.sql_channel.save_channel.exists.app_error")
    64  	CheckBadRequestStatus(t, resp)
    65  
    66  	direct := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_DIRECT, TeamId: team.Id}
    67  	_, resp = Client.CreateChannel(direct)
    68  	CheckErrorMessage(t, resp, "api.channel.create_channel.direct_channel.app_error")
    69  	CheckBadRequestStatus(t, resp)
    70  
    71  	Client.Logout()
    72  	_, resp = Client.CreateChannel(channel)
    73  	CheckUnauthorizedStatus(t, resp)
    74  
    75  	userNotOnTeam := th.CreateUser()
    76  	Client.Login(userNotOnTeam.Email, userNotOnTeam.Password)
    77  
    78  	_, resp = Client.CreateChannel(channel)
    79  	CheckForbiddenStatus(t, resp)
    80  
    81  	_, resp = Client.CreateChannel(private)
    82  	CheckForbiddenStatus(t, resp)
    83  
    84  	// Check the appropriate permissions are enforced.
    85  	defaultRolePermissions := th.SaveDefaultRolePermissions()
    86  	defer func() {
    87  		th.RestoreDefaultRolePermissions(defaultRolePermissions)
    88  	}()
    89  
    90  	th.AddPermissionToRole(model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, model.TEAM_USER_ROLE_ID)
    91  	th.AddPermissionToRole(model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, model.TEAM_USER_ROLE_ID)
    92  
    93  	th.LoginBasic()
    94  
    95  	channel.Name = GenerateTestChannelName()
    96  	_, resp = Client.CreateChannel(channel)
    97  	CheckNoError(t, resp)
    98  
    99  	private.Name = GenerateTestChannelName()
   100  	_, resp = Client.CreateChannel(private)
   101  	CheckNoError(t, resp)
   102  
   103  	th.AddPermissionToRole(model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, model.TEAM_ADMIN_ROLE_ID)
   104  	th.AddPermissionToRole(model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, model.TEAM_ADMIN_ROLE_ID)
   105  	th.RemovePermissionFromRole(model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, model.TEAM_USER_ROLE_ID)
   106  	th.RemovePermissionFromRole(model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, model.TEAM_USER_ROLE_ID)
   107  
   108  	_, resp = Client.CreateChannel(channel)
   109  	CheckForbiddenStatus(t, resp)
   110  
   111  	_, resp = Client.CreateChannel(private)
   112  	CheckForbiddenStatus(t, resp)
   113  
   114  	th.LoginTeamAdmin()
   115  
   116  	channel.Name = GenerateTestChannelName()
   117  	_, resp = Client.CreateChannel(channel)
   118  	CheckNoError(t, resp)
   119  
   120  	private.Name = GenerateTestChannelName()
   121  	_, resp = Client.CreateChannel(private)
   122  	CheckNoError(t, resp)
   123  
   124  	channel.Name = GenerateTestChannelName()
   125  	_, resp = th.SystemAdminClient.CreateChannel(channel)
   126  	CheckNoError(t, resp)
   127  
   128  	private.Name = GenerateTestChannelName()
   129  	_, resp = th.SystemAdminClient.CreateChannel(private)
   130  	CheckNoError(t, resp)
   131  
   132  	// Test posting Garbage
   133  	if r, err := Client.DoApiPost("/channels", "garbage"); err == nil {
   134  		t.Fatal("should have errored")
   135  	} else {
   136  		if r.StatusCode != http.StatusBadRequest {
   137  			t.Log("actual: " + strconv.Itoa(r.StatusCode))
   138  			t.Log("expected: " + strconv.Itoa(http.StatusBadRequest))
   139  			t.Fatal("wrong status code")
   140  		}
   141  	}
   142  
   143  	// Test GroupConstrained flag
   144  	groupConstrainedChannel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id, GroupConstrained: model.NewBool(true)}
   145  	rchannel, resp = Client.CreateChannel(groupConstrainedChannel)
   146  	CheckNoError(t, resp)
   147  
   148  	if *rchannel.GroupConstrained != *groupConstrainedChannel.GroupConstrained {
   149  		t.Fatal("GroupConstrained flags do not match")
   150  	}
   151  }
   152  
   153  func TestUpdateChannel(t *testing.T) {
   154  	th := Setup().InitBasic()
   155  	defer th.TearDown()
   156  	Client := th.Client
   157  	team := th.BasicTeam
   158  
   159  	channel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id}
   160  	private := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_PRIVATE, TeamId: team.Id}
   161  
   162  	channel, _ = Client.CreateChannel(channel)
   163  	private, _ = Client.CreateChannel(private)
   164  
   165  	//Update a open channel
   166  	channel.DisplayName = "My new display name"
   167  	channel.Header = "My fancy header"
   168  	channel.Purpose = "Xenia ftw!"
   169  
   170  	newChannel, resp := Client.UpdateChannel(channel)
   171  	CheckNoError(t, resp)
   172  
   173  	if newChannel.DisplayName != channel.DisplayName {
   174  		t.Fatal("Update failed for DisplayName")
   175  	}
   176  
   177  	if newChannel.Header != channel.Header {
   178  		t.Fatal("Update failed for Header")
   179  	}
   180  
   181  	if newChannel.Purpose != channel.Purpose {
   182  		t.Fatal("Update failed for Purpose")
   183  	}
   184  
   185  	// Test GroupConstrained flag
   186  	channel.GroupConstrained = model.NewBool(true)
   187  	rchannel, resp := Client.UpdateChannel(channel)
   188  	CheckNoError(t, resp)
   189  	CheckOKStatus(t, resp)
   190  
   191  	if *rchannel.GroupConstrained != *channel.GroupConstrained {
   192  		t.Fatal("GroupConstrained flags do not match")
   193  	}
   194  
   195  	//Update a private channel
   196  	private.DisplayName = "My new display name for private channel"
   197  	private.Header = "My fancy private header"
   198  	private.Purpose = "Xenia ftw! in private mode"
   199  
   200  	newPrivateChannel, resp := Client.UpdateChannel(private)
   201  	CheckNoError(t, resp)
   202  
   203  	if newPrivateChannel.DisplayName != private.DisplayName {
   204  		t.Fatal("Update failed for DisplayName in private channel")
   205  	}
   206  
   207  	if newPrivateChannel.Header != private.Header {
   208  		t.Fatal("Update failed for Header in private channel")
   209  	}
   210  
   211  	if newPrivateChannel.Purpose != private.Purpose {
   212  		t.Fatal("Update failed for Purpose in private channel")
   213  	}
   214  
   215  	//Non existing channel
   216  	channel1 := &model.Channel{DisplayName: "Test API Name for apiv4", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id}
   217  	_, resp = Client.UpdateChannel(channel1)
   218  	CheckNotFoundStatus(t, resp)
   219  
   220  	//Try to update with not logged user
   221  	Client.Logout()
   222  	_, resp = Client.UpdateChannel(channel)
   223  	CheckUnauthorizedStatus(t, resp)
   224  
   225  	//Try to update using another user
   226  	user := th.CreateUser()
   227  	Client.Login(user.Email, user.Password)
   228  
   229  	channel.DisplayName = "Should not update"
   230  	_, resp = Client.UpdateChannel(channel)
   231  	CheckForbiddenStatus(t, resp)
   232  
   233  	// Test updating the header of someone else's GM channel.
   234  	user1 := th.CreateUser()
   235  	user2 := th.CreateUser()
   236  	user3 := th.CreateUser()
   237  
   238  	groupChannel, resp := Client.CreateGroupChannel([]string{user1.Id, user2.Id})
   239  	CheckNoError(t, resp)
   240  
   241  	groupChannel.Header = "lolololol"
   242  	Client.Logout()
   243  	Client.Login(user3.Email, user3.Password)
   244  	_, resp = Client.UpdateChannel(groupChannel)
   245  	CheckForbiddenStatus(t, resp)
   246  
   247  	// Test updating the header of someone else's GM channel.
   248  	Client.Logout()
   249  	Client.Login(user.Email, user.Password)
   250  
   251  	directChannel, resp := Client.CreateDirectChannel(user.Id, user1.Id)
   252  	CheckNoError(t, resp)
   253  
   254  	directChannel.Header = "lolololol"
   255  	Client.Logout()
   256  	Client.Login(user3.Email, user3.Password)
   257  	_, resp = Client.UpdateChannel(directChannel)
   258  	CheckForbiddenStatus(t, resp)
   259  }
   260  
   261  func TestPatchChannel(t *testing.T) {
   262  	th := Setup().InitBasic()
   263  	defer th.TearDown()
   264  	Client := th.Client
   265  
   266  	patch := &model.ChannelPatch{
   267  		Name:        new(string),
   268  		DisplayName: new(string),
   269  		Header:      new(string),
   270  		Purpose:     new(string),
   271  	}
   272  	*patch.Name = model.NewId()
   273  	*patch.DisplayName = model.NewId()
   274  	*patch.Header = model.NewId()
   275  	*patch.Purpose = model.NewId()
   276  
   277  	channel, resp := Client.PatchChannel(th.BasicChannel.Id, patch)
   278  	CheckNoError(t, resp)
   279  
   280  	if *patch.Name != channel.Name {
   281  		t.Fatal("do not match")
   282  	} else if *patch.DisplayName != channel.DisplayName {
   283  		t.Fatal("do not match")
   284  	} else if *patch.Header != channel.Header {
   285  		t.Fatal("do not match")
   286  	} else if *patch.Purpose != channel.Purpose {
   287  		t.Fatal("do not match")
   288  	}
   289  
   290  	patch.Name = nil
   291  	oldName := channel.Name
   292  	channel, resp = Client.PatchChannel(th.BasicChannel.Id, patch)
   293  	CheckNoError(t, resp)
   294  
   295  	if channel.Name != oldName {
   296  		t.Fatal("should not have updated")
   297  	}
   298  
   299  	// Test GroupConstrained flag
   300  	patch.GroupConstrained = model.NewBool(true)
   301  	rchannel, resp := Client.PatchChannel(th.BasicChannel.Id, patch)
   302  	CheckNoError(t, resp)
   303  	CheckOKStatus(t, resp)
   304  
   305  	if *rchannel.GroupConstrained != *patch.GroupConstrained {
   306  		t.Fatal("GroupConstrained flags do not match")
   307  	}
   308  	patch.GroupConstrained = nil
   309  
   310  	_, resp = Client.PatchChannel("junk", patch)
   311  	CheckBadRequestStatus(t, resp)
   312  
   313  	_, resp = Client.PatchChannel(model.NewId(), patch)
   314  	CheckNotFoundStatus(t, resp)
   315  
   316  	user := th.CreateUser()
   317  	Client.Login(user.Email, user.Password)
   318  	_, resp = Client.PatchChannel(th.BasicChannel.Id, patch)
   319  	CheckForbiddenStatus(t, resp)
   320  
   321  	_, resp = th.SystemAdminClient.PatchChannel(th.BasicChannel.Id, patch)
   322  	CheckNoError(t, resp)
   323  
   324  	_, resp = th.SystemAdminClient.PatchChannel(th.BasicPrivateChannel.Id, patch)
   325  	CheckNoError(t, resp)
   326  
   327  	// Test updating the header of someone else's GM channel.
   328  	user1 := th.CreateUser()
   329  	user2 := th.CreateUser()
   330  	user3 := th.CreateUser()
   331  
   332  	groupChannel, resp := Client.CreateGroupChannel([]string{user1.Id, user2.Id})
   333  	CheckNoError(t, resp)
   334  
   335  	Client.Logout()
   336  	Client.Login(user3.Email, user3.Password)
   337  
   338  	channelPatch := &model.ChannelPatch{}
   339  	channelPatch.Header = new(string)
   340  	*channelPatch.Header = "lolololol"
   341  
   342  	_, resp = Client.PatchChannel(groupChannel.Id, channelPatch)
   343  	CheckForbiddenStatus(t, resp)
   344  
   345  	// Test updating the header of someone else's GM channel.
   346  	Client.Logout()
   347  	Client.Login(user.Email, user.Password)
   348  
   349  	directChannel, resp := Client.CreateDirectChannel(user.Id, user1.Id)
   350  	CheckNoError(t, resp)
   351  
   352  	Client.Logout()
   353  	Client.Login(user3.Email, user3.Password)
   354  	_, resp = Client.PatchChannel(directChannel.Id, channelPatch)
   355  	CheckForbiddenStatus(t, resp)
   356  }
   357  
   358  func TestCreateDirectChannel(t *testing.T) {
   359  	th := Setup().InitBasic()
   360  	defer th.TearDown()
   361  	Client := th.Client
   362  	user1 := th.BasicUser
   363  	user2 := th.BasicUser2
   364  	user3 := th.CreateUser()
   365  
   366  	dm, resp := Client.CreateDirectChannel(user1.Id, user2.Id)
   367  	CheckNoError(t, resp)
   368  
   369  	channelName := ""
   370  	if user2.Id > user1.Id {
   371  		channelName = user1.Id + "__" + user2.Id
   372  	} else {
   373  		channelName = user2.Id + "__" + user1.Id
   374  	}
   375  
   376  	if dm.Name != channelName {
   377  		t.Fatal("dm name didn't match")
   378  	}
   379  
   380  	_, resp = Client.CreateDirectChannel("junk", user2.Id)
   381  	CheckBadRequestStatus(t, resp)
   382  
   383  	_, resp = Client.CreateDirectChannel(user1.Id, model.NewId())
   384  	CheckBadRequestStatus(t, resp)
   385  
   386  	_, resp = Client.CreateDirectChannel(model.NewId(), user1.Id)
   387  	CheckBadRequestStatus(t, resp)
   388  
   389  	_, resp = Client.CreateDirectChannel(model.NewId(), user2.Id)
   390  	CheckForbiddenStatus(t, resp)
   391  
   392  	if r, err := Client.DoApiPost("/channels/direct", "garbage"); err == nil {
   393  		t.Fatal("should have errored")
   394  	} else {
   395  		if r.StatusCode != http.StatusBadRequest {
   396  			t.Log("actual: " + strconv.Itoa(r.StatusCode))
   397  			t.Log("expected: " + strconv.Itoa(http.StatusBadRequest))
   398  			t.Fatal("wrong status code")
   399  		}
   400  	}
   401  
   402  	Client.Logout()
   403  	_, resp = Client.CreateDirectChannel(model.NewId(), user2.Id)
   404  	CheckUnauthorizedStatus(t, resp)
   405  
   406  	_, resp = th.SystemAdminClient.CreateDirectChannel(user3.Id, user2.Id)
   407  	CheckNoError(t, resp)
   408  }
   409  
   410  func TestDeleteDirectChannel(t *testing.T) {
   411  	th := Setup().InitBasic()
   412  	defer th.TearDown()
   413  	Client := th.Client
   414  	user := th.BasicUser
   415  	user2 := th.BasicUser2
   416  
   417  	rgc, resp := Client.CreateDirectChannel(user.Id, user2.Id)
   418  	CheckNoError(t, resp)
   419  	CheckCreatedStatus(t, resp)
   420  	require.NotNil(t, rgc, "should have created a direct channel")
   421  
   422  	deleted, resp := Client.DeleteChannel(rgc.Id)
   423  	CheckErrorMessage(t, resp, "api.channel.delete_channel.type.invalid")
   424  	require.False(t, deleted, "should not have been able to delete direct channel.")
   425  }
   426  
   427  func TestCreateGroupChannel(t *testing.T) {
   428  	th := Setup().InitBasic()
   429  	defer th.TearDown()
   430  	Client := th.Client
   431  	user := th.BasicUser
   432  	user2 := th.BasicUser2
   433  	user3 := th.CreateUser()
   434  
   435  	userIds := []string{user.Id, user2.Id, user3.Id}
   436  
   437  	rgc, resp := Client.CreateGroupChannel(userIds)
   438  	CheckNoError(t, resp)
   439  	CheckCreatedStatus(t, resp)
   440  
   441  	if rgc == nil {
   442  		t.Fatal("should have created a group channel")
   443  	}
   444  
   445  	if rgc.Type != model.CHANNEL_GROUP {
   446  		t.Fatal("should have created a channel of group type")
   447  	}
   448  
   449  	m, _ := th.App.GetChannelMembersPage(rgc.Id, 0, 10)
   450  	if len(*m) != 3 {
   451  		t.Fatal("should have 3 channel members")
   452  	}
   453  
   454  	// saving duplicate group channel
   455  	rgc2, resp := Client.CreateGroupChannel([]string{user3.Id, user2.Id})
   456  	CheckNoError(t, resp)
   457  
   458  	if rgc.Id != rgc2.Id {
   459  		t.Fatal("should have returned existing channel")
   460  	}
   461  
   462  	m2, _ := th.App.GetChannelMembersPage(rgc2.Id, 0, 10)
   463  	if !reflect.DeepEqual(*m, *m2) {
   464  		t.Fatal("should be equal")
   465  	}
   466  
   467  	_, resp = Client.CreateGroupChannel([]string{user2.Id})
   468  	CheckBadRequestStatus(t, resp)
   469  
   470  	user4 := th.CreateUser()
   471  	user5 := th.CreateUser()
   472  	user6 := th.CreateUser()
   473  	user7 := th.CreateUser()
   474  	user8 := th.CreateUser()
   475  	user9 := th.CreateUser()
   476  
   477  	rgc, resp = Client.CreateGroupChannel([]string{user.Id, user2.Id, user3.Id, user4.Id, user5.Id, user6.Id, user7.Id, user8.Id, user9.Id})
   478  	CheckBadRequestStatus(t, resp)
   479  
   480  	if rgc != nil {
   481  		t.Fatal("should return nil")
   482  	}
   483  
   484  	_, resp = Client.CreateGroupChannel([]string{user.Id, user2.Id, user3.Id, GenerateTestId()})
   485  	CheckBadRequestStatus(t, resp)
   486  
   487  	_, resp = Client.CreateGroupChannel([]string{user.Id, user2.Id, user3.Id, "junk"})
   488  	CheckBadRequestStatus(t, resp)
   489  
   490  	Client.Logout()
   491  
   492  	_, resp = Client.CreateGroupChannel(userIds)
   493  	CheckUnauthorizedStatus(t, resp)
   494  
   495  	_, resp = th.SystemAdminClient.CreateGroupChannel(userIds)
   496  	CheckNoError(t, resp)
   497  }
   498  
   499  func TestDeleteGroupChannel(t *testing.T) {
   500  	th := Setup().InitBasic()
   501  	defer th.TearDown()
   502  	Client := th.Client
   503  	user := th.BasicUser
   504  	user2 := th.BasicUser2
   505  	user3 := th.CreateUser()
   506  
   507  	userIds := []string{user.Id, user2.Id, user3.Id}
   508  
   509  	rgc, resp := Client.CreateGroupChannel(userIds)
   510  	CheckNoError(t, resp)
   511  	CheckCreatedStatus(t, resp)
   512  	require.NotNil(t, rgc, "should have created a group channel")
   513  
   514  	deleted, resp := Client.DeleteChannel(rgc.Id)
   515  	CheckErrorMessage(t, resp, "api.channel.delete_channel.type.invalid")
   516  	require.False(t, deleted, "should not have been able to delete group channel.")
   517  }
   518  
   519  func TestGetChannel(t *testing.T) {
   520  	th := Setup().InitBasic()
   521  	defer th.TearDown()
   522  	Client := th.Client
   523  
   524  	channel, resp := Client.GetChannel(th.BasicChannel.Id, "")
   525  	CheckNoError(t, resp)
   526  
   527  	if channel.Id != th.BasicChannel.Id {
   528  		t.Fatal("ids did not match")
   529  	}
   530  
   531  	Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
   532  	_, resp = Client.GetChannel(th.BasicChannel.Id, "")
   533  	CheckNoError(t, resp)
   534  
   535  	channel, resp = Client.GetChannel(th.BasicPrivateChannel.Id, "")
   536  	CheckNoError(t, resp)
   537  
   538  	if channel.Id != th.BasicPrivateChannel.Id {
   539  		t.Fatal("ids did not match")
   540  	}
   541  
   542  	Client.RemoveUserFromChannel(th.BasicPrivateChannel.Id, th.BasicUser.Id)
   543  	_, resp = Client.GetChannel(th.BasicPrivateChannel.Id, "")
   544  	CheckForbiddenStatus(t, resp)
   545  
   546  	_, resp = Client.GetChannel(model.NewId(), "")
   547  	CheckNotFoundStatus(t, resp)
   548  
   549  	Client.Logout()
   550  	_, resp = Client.GetChannel(th.BasicChannel.Id, "")
   551  	CheckUnauthorizedStatus(t, resp)
   552  
   553  	user := th.CreateUser()
   554  	Client.Login(user.Email, user.Password)
   555  	_, resp = Client.GetChannel(th.BasicChannel.Id, "")
   556  	CheckForbiddenStatus(t, resp)
   557  
   558  	_, resp = th.SystemAdminClient.GetChannel(th.BasicChannel.Id, "")
   559  	CheckNoError(t, resp)
   560  
   561  	_, resp = th.SystemAdminClient.GetChannel(th.BasicPrivateChannel.Id, "")
   562  	CheckNoError(t, resp)
   563  
   564  	_, resp = th.SystemAdminClient.GetChannel(th.BasicUser.Id, "")
   565  	CheckNotFoundStatus(t, resp)
   566  }
   567  
   568  func TestGetDeletedChannelsForTeam(t *testing.T) {
   569  	th := Setup().InitBasic()
   570  	defer th.TearDown()
   571  	Client := th.Client
   572  	team := th.BasicTeam
   573  
   574  	_, resp := Client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
   575  	CheckForbiddenStatus(t, resp)
   576  
   577  	th.LoginTeamAdmin()
   578  
   579  	channels, resp := Client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
   580  	CheckNoError(t, resp)
   581  	numInitialChannelsForTeam := len(channels)
   582  
   583  	// create and delete public channel
   584  	publicChannel1 := th.CreatePublicChannel()
   585  	Client.DeleteChannel(publicChannel1.Id)
   586  
   587  	channels, resp = Client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
   588  	CheckNoError(t, resp)
   589  	if len(channels) != numInitialChannelsForTeam+1 {
   590  		t.Fatal("should be 1 deleted channel")
   591  	}
   592  
   593  	publicChannel2 := th.CreatePublicChannel()
   594  	Client.DeleteChannel(publicChannel2.Id)
   595  
   596  	channels, resp = Client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
   597  	CheckNoError(t, resp)
   598  	if len(channels) != numInitialChannelsForTeam+2 {
   599  		t.Fatal("should be 2 deleted channels")
   600  	}
   601  
   602  	channels, resp = Client.GetDeletedChannelsForTeam(team.Id, 0, 1, "")
   603  	CheckNoError(t, resp)
   604  	if len(channels) != 1 {
   605  		t.Fatal("should be one channel per page")
   606  	}
   607  
   608  	channels, resp = Client.GetDeletedChannelsForTeam(team.Id, 1, 1, "")
   609  	CheckNoError(t, resp)
   610  	if len(channels) != 1 {
   611  		t.Fatal("should be one channel per page")
   612  	}
   613  }
   614  
   615  func TestGetPublicChannelsForTeam(t *testing.T) {
   616  	th := Setup().InitBasic()
   617  	defer th.TearDown()
   618  	Client := th.Client
   619  	team := th.BasicTeam
   620  	publicChannel1 := th.BasicChannel
   621  	publicChannel2 := th.BasicChannel2
   622  
   623  	channels, resp := Client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
   624  	CheckNoError(t, resp)
   625  	if len(channels) != 4 {
   626  		t.Fatal("wrong length")
   627  	}
   628  
   629  	for i, c := range channels {
   630  		if c.Type != model.CHANNEL_OPEN {
   631  			t.Fatal("should include open channel only")
   632  		}
   633  
   634  		// only check the created 2 public channels
   635  		if i < 2 && !(c.DisplayName == publicChannel1.DisplayName || c.DisplayName == publicChannel2.DisplayName) {
   636  			t.Logf("channel %v: %v", i, c.DisplayName)
   637  			t.Fatal("should match public channel display name only")
   638  		}
   639  	}
   640  
   641  	privateChannel := th.CreatePrivateChannel()
   642  	channels, resp = Client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
   643  	CheckNoError(t, resp)
   644  	if len(channels) != 4 {
   645  		t.Fatal("wrong length")
   646  	}
   647  
   648  	for _, c := range channels {
   649  		if c.Type != model.CHANNEL_OPEN {
   650  			t.Fatal("should not include private channel")
   651  		}
   652  
   653  		if c.DisplayName == privateChannel.DisplayName {
   654  			t.Fatal("should not match private channel display name")
   655  		}
   656  	}
   657  
   658  	channels, resp = Client.GetPublicChannelsForTeam(team.Id, 0, 1, "")
   659  	CheckNoError(t, resp)
   660  	if len(channels) != 1 {
   661  		t.Fatal("should be one channel per page")
   662  	}
   663  
   664  	channels, resp = Client.GetPublicChannelsForTeam(team.Id, 1, 1, "")
   665  	CheckNoError(t, resp)
   666  	if len(channels) != 1 {
   667  		t.Fatal("should be one channel per page")
   668  	}
   669  
   670  	channels, resp = Client.GetPublicChannelsForTeam(team.Id, 10000, 100, "")
   671  	CheckNoError(t, resp)
   672  	if len(channels) != 0 {
   673  		t.Fatal("should be no channel")
   674  	}
   675  
   676  	_, resp = Client.GetPublicChannelsForTeam("junk", 0, 100, "")
   677  	CheckBadRequestStatus(t, resp)
   678  
   679  	_, resp = Client.GetPublicChannelsForTeam(model.NewId(), 0, 100, "")
   680  	CheckForbiddenStatus(t, resp)
   681  
   682  	Client.Logout()
   683  	_, resp = Client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
   684  	CheckUnauthorizedStatus(t, resp)
   685  
   686  	user := th.CreateUser()
   687  	Client.Login(user.Email, user.Password)
   688  	_, resp = Client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
   689  	CheckForbiddenStatus(t, resp)
   690  
   691  	_, resp = th.SystemAdminClient.GetPublicChannelsForTeam(team.Id, 0, 100, "")
   692  	CheckNoError(t, resp)
   693  }
   694  
   695  func TestGetPublicChannelsByIdsForTeam(t *testing.T) {
   696  	th := Setup().InitBasic()
   697  	defer th.TearDown()
   698  	Client := th.Client
   699  	teamId := th.BasicTeam.Id
   700  	input := []string{th.BasicChannel.Id}
   701  	output := []string{th.BasicChannel.DisplayName}
   702  
   703  	channels, resp := Client.GetPublicChannelsByIdsForTeam(teamId, input)
   704  	CheckNoError(t, resp)
   705  
   706  	if len(channels) != 1 {
   707  		t.Fatal("should return 1 channel")
   708  	}
   709  
   710  	if (channels)[0].DisplayName != output[0] {
   711  		t.Fatal("missing channel")
   712  	}
   713  
   714  	input = append(input, GenerateTestId())
   715  	input = append(input, th.BasicChannel2.Id)
   716  	input = append(input, th.BasicPrivateChannel.Id)
   717  	output = append(output, th.BasicChannel2.DisplayName)
   718  	sort.Strings(output)
   719  
   720  	channels, resp = Client.GetPublicChannelsByIdsForTeam(teamId, input)
   721  	CheckNoError(t, resp)
   722  
   723  	if len(channels) != 2 {
   724  		t.Fatal("should return 2 channels")
   725  	}
   726  
   727  	for i, c := range channels {
   728  		if c.DisplayName != output[i] {
   729  			t.Fatal("missing channel")
   730  		}
   731  	}
   732  
   733  	_, resp = Client.GetPublicChannelsByIdsForTeam(GenerateTestId(), input)
   734  	CheckForbiddenStatus(t, resp)
   735  
   736  	_, resp = Client.GetPublicChannelsByIdsForTeam(teamId, []string{})
   737  	CheckBadRequestStatus(t, resp)
   738  
   739  	_, resp = Client.GetPublicChannelsByIdsForTeam(teamId, []string{"junk"})
   740  	CheckBadRequestStatus(t, resp)
   741  
   742  	_, resp = Client.GetPublicChannelsByIdsForTeam(teamId, []string{GenerateTestId()})
   743  	CheckNotFoundStatus(t, resp)
   744  
   745  	_, resp = Client.GetPublicChannelsByIdsForTeam(teamId, []string{th.BasicPrivateChannel.Id})
   746  	CheckNotFoundStatus(t, resp)
   747  
   748  	Client.Logout()
   749  
   750  	_, resp = Client.GetPublicChannelsByIdsForTeam(teamId, input)
   751  	CheckUnauthorizedStatus(t, resp)
   752  
   753  	_, resp = th.SystemAdminClient.GetPublicChannelsByIdsForTeam(teamId, input)
   754  	CheckNoError(t, resp)
   755  }
   756  
   757  func TestGetChannelsForTeamForUser(t *testing.T) {
   758  	th := Setup().InitBasic()
   759  	defer th.TearDown()
   760  	Client := th.Client
   761  
   762  	channels, resp := Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, "")
   763  	CheckNoError(t, resp)
   764  
   765  	found := make([]bool, 3)
   766  	for _, c := range channels {
   767  		if c.Id == th.BasicChannel.Id {
   768  			found[0] = true
   769  		} else if c.Id == th.BasicChannel2.Id {
   770  			found[1] = true
   771  		} else if c.Id == th.BasicPrivateChannel.Id {
   772  			found[2] = true
   773  		}
   774  
   775  		if c.TeamId != th.BasicTeam.Id && c.TeamId != "" {
   776  			t.Fatal("wrong team")
   777  		}
   778  	}
   779  
   780  	for _, f := range found {
   781  		if !f {
   782  			t.Fatal("missing a channel")
   783  		}
   784  	}
   785  
   786  	channels, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, resp.Etag)
   787  	CheckEtag(t, channels, resp)
   788  
   789  	_, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, "junk", "")
   790  	CheckBadRequestStatus(t, resp)
   791  
   792  	_, resp = Client.GetChannelsForTeamForUser("junk", th.BasicUser.Id, "")
   793  	CheckBadRequestStatus(t, resp)
   794  
   795  	_, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser2.Id, "")
   796  	CheckForbiddenStatus(t, resp)
   797  
   798  	_, resp = Client.GetChannelsForTeamForUser(model.NewId(), th.BasicUser.Id, "")
   799  	CheckForbiddenStatus(t, resp)
   800  
   801  	_, resp = th.SystemAdminClient.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, "")
   802  	CheckNoError(t, resp)
   803  }
   804  
   805  func TestGetAllChannels(t *testing.T) {
   806  	th := Setup().InitBasic()
   807  	defer th.TearDown()
   808  	Client := th.Client
   809  
   810  	channels, resp := th.SystemAdminClient.GetAllChannels(0, 20, "")
   811  	CheckNoError(t, resp)
   812  
   813  	// At least, all the not-deleted channels created during the InitBasic
   814  	require.True(t, len(*channels) >= 3)
   815  	for _, c := range *channels {
   816  		require.NotEqual(t, c.TeamId, "")
   817  	}
   818  
   819  	channels, resp = th.SystemAdminClient.GetAllChannels(0, 10, "")
   820  	CheckNoError(t, resp)
   821  	require.True(t, len(*channels) >= 3)
   822  
   823  	channels, resp = th.SystemAdminClient.GetAllChannels(1, 1, "")
   824  	CheckNoError(t, resp)
   825  	require.Len(t, *channels, 1)
   826  
   827  	channels, resp = th.SystemAdminClient.GetAllChannels(10000, 10000, "")
   828  	CheckNoError(t, resp)
   829  	require.Len(t, *channels, 0)
   830  
   831  	_, resp = Client.GetAllChannels(0, 20, "")
   832  	CheckForbiddenStatus(t, resp)
   833  }
   834  
   835  func TestGetAllChannelsWithCount(t *testing.T) {
   836  	th := Setup().InitBasic()
   837  	defer th.TearDown()
   838  	Client := th.Client
   839  
   840  	channels, total, resp := th.SystemAdminClient.GetAllChannelsWithCount(0, 20, "")
   841  	CheckNoError(t, resp)
   842  
   843  	// At least, all the not-deleted channels created during the InitBasic
   844  	require.True(t, len(*channels) >= 3)
   845  	for _, c := range *channels {
   846  		require.NotEqual(t, c.TeamId, "")
   847  	}
   848  	require.Equal(t, int64(5), total)
   849  
   850  	channels, _, resp = th.SystemAdminClient.GetAllChannelsWithCount(0, 10, "")
   851  	CheckNoError(t, resp)
   852  	require.True(t, len(*channels) >= 3)
   853  
   854  	channels, _, resp = th.SystemAdminClient.GetAllChannelsWithCount(1, 1, "")
   855  	CheckNoError(t, resp)
   856  	require.Len(t, *channels, 1)
   857  
   858  	channels, _, resp = th.SystemAdminClient.GetAllChannelsWithCount(10000, 10000, "")
   859  	CheckNoError(t, resp)
   860  	require.Len(t, *channels, 0)
   861  
   862  	_, _, resp = Client.GetAllChannelsWithCount(0, 20, "")
   863  	CheckForbiddenStatus(t, resp)
   864  }
   865  
   866  func TestSearchChannels(t *testing.T) {
   867  	th := Setup().InitBasic()
   868  	defer th.TearDown()
   869  	Client := th.Client
   870  
   871  	search := &model.ChannelSearch{Term: th.BasicChannel.Name}
   872  
   873  	channels, resp := Client.SearchChannels(th.BasicTeam.Id, search)
   874  	CheckNoError(t, resp)
   875  
   876  	found := false
   877  	for _, c := range channels {
   878  		if c.Type != model.CHANNEL_OPEN {
   879  			t.Fatal("should only return public channels")
   880  		}
   881  
   882  		if c.Id == th.BasicChannel.Id {
   883  			found = true
   884  		}
   885  	}
   886  
   887  	if !found {
   888  		t.Fatal("didn't find channel")
   889  	}
   890  
   891  	search.Term = th.BasicPrivateChannel.Name
   892  	channels, resp = Client.SearchChannels(th.BasicTeam.Id, search)
   893  	CheckNoError(t, resp)
   894  
   895  	found = false
   896  	for _, c := range channels {
   897  		if c.Id == th.BasicPrivateChannel.Id {
   898  			found = true
   899  		}
   900  	}
   901  
   902  	if found {
   903  		t.Fatal("shouldn't find private channel")
   904  	}
   905  
   906  	search.Term = ""
   907  	_, resp = Client.SearchChannels(th.BasicTeam.Id, search)
   908  	CheckNoError(t, resp)
   909  
   910  	search.Term = th.BasicChannel.Name
   911  	_, resp = Client.SearchChannels(model.NewId(), search)
   912  	CheckForbiddenStatus(t, resp)
   913  
   914  	_, resp = Client.SearchChannels("junk", search)
   915  	CheckBadRequestStatus(t, resp)
   916  
   917  	_, resp = th.SystemAdminClient.SearchChannels(th.BasicTeam.Id, search)
   918  	CheckNoError(t, resp)
   919  }
   920  
   921  func TestSearchAllChannels(t *testing.T) {
   922  	th := Setup().InitBasic()
   923  	defer th.TearDown()
   924  	Client := th.Client
   925  
   926  	search := &model.ChannelSearch{Term: th.BasicChannel.Name}
   927  
   928  	channels, resp := th.SystemAdminClient.SearchAllChannels(search)
   929  	CheckNoError(t, resp)
   930  
   931  	assert.Len(t, *channels, 1)
   932  	assert.Equal(t, (*channels)[0].Id, th.BasicChannel.Id)
   933  
   934  	search.Term = th.BasicPrivateChannel.Name
   935  	channels, resp = th.SystemAdminClient.SearchAllChannels(search)
   936  	CheckNoError(t, resp)
   937  
   938  	assert.Len(t, *channels, 1)
   939  	assert.Equal(t, (*channels)[0].Id, th.BasicPrivateChannel.Id)
   940  
   941  	search.Term = ""
   942  	channels, resp = th.SystemAdminClient.SearchAllChannels(search)
   943  	CheckNoError(t, resp)
   944  	// At least, all the not-deleted channels created during the InitBasic
   945  	assert.True(t, len(*channels) >= 3)
   946  
   947  	search.Term = th.BasicChannel.Name
   948  	_, resp = Client.SearchAllChannels(search)
   949  	CheckForbiddenStatus(t, resp)
   950  }
   951  
   952  func TestSearchGroupChannels(t *testing.T) {
   953  	th := Setup().InitBasic()
   954  	defer th.TearDown()
   955  	Client := th.Client
   956  
   957  	u1 := th.CreateUserWithClient(th.SystemAdminClient)
   958  
   959  	// Create a group channel in which base user belongs but not sysadmin
   960  	gc1, resp := th.Client.CreateGroupChannel([]string{th.BasicUser.Id, th.BasicUser2.Id, u1.Id})
   961  	CheckNoError(t, resp)
   962  	defer th.Client.DeleteChannel(gc1.Id)
   963  
   964  	gc2, resp := th.Client.CreateGroupChannel([]string{th.BasicUser.Id, th.BasicUser2.Id, th.SystemAdminUser.Id})
   965  	CheckNoError(t, resp)
   966  	defer th.Client.DeleteChannel(gc2.Id)
   967  
   968  	search := &model.ChannelSearch{Term: th.BasicUser2.Username}
   969  
   970  	// sysadmin should only find gc2 as he doesn't belong to gc1
   971  	channels, resp := th.SystemAdminClient.SearchGroupChannels(search)
   972  	CheckNoError(t, resp)
   973  
   974  	assert.Len(t, channels, 1)
   975  	assert.Equal(t, channels[0].Id, gc2.Id)
   976  
   977  	// basic user should find both
   978  	Client.Login(th.BasicUser.Username, th.BasicUser.Password)
   979  	channels, resp = Client.SearchGroupChannels(search)
   980  	CheckNoError(t, resp)
   981  
   982  	assert.Len(t, channels, 2)
   983  	channelIds := []string{}
   984  	for _, c := range channels {
   985  		channelIds = append(channelIds, c.Id)
   986  	}
   987  	assert.ElementsMatch(t, channelIds, []string{gc1.Id, gc2.Id})
   988  
   989  	// searching for sysadmin, it should only find gc1
   990  	search = &model.ChannelSearch{Term: th.SystemAdminUser.Username}
   991  	channels, resp = Client.SearchGroupChannels(search)
   992  	CheckNoError(t, resp)
   993  
   994  	assert.Len(t, channels, 1)
   995  	assert.Equal(t, channels[0].Id, gc2.Id)
   996  
   997  	// with an empty search, response should be empty
   998  	search = &model.ChannelSearch{Term: ""}
   999  	channels, resp = Client.SearchGroupChannels(search)
  1000  	CheckNoError(t, resp)
  1001  
  1002  	assert.Len(t, channels, 0)
  1003  
  1004  	// search unprivileged, forbidden
  1005  	th.Client.Logout()
  1006  	_, resp = Client.SearchAllChannels(search)
  1007  	CheckUnauthorizedStatus(t, resp)
  1008  }
  1009  
  1010  func TestDeleteChannel(t *testing.T) {
  1011  	th := Setup().InitBasic()
  1012  	defer th.TearDown()
  1013  	Client := th.Client
  1014  	team := th.BasicTeam
  1015  	user := th.BasicUser
  1016  	user2 := th.BasicUser2
  1017  
  1018  	// successful delete of public channel
  1019  	publicChannel1 := th.CreatePublicChannel()
  1020  	pass, resp := Client.DeleteChannel(publicChannel1.Id)
  1021  	CheckNoError(t, resp)
  1022  
  1023  	if !pass {
  1024  		t.Fatal("should have passed")
  1025  	}
  1026  
  1027  	if ch, err := th.App.GetChannel(publicChannel1.Id); err == nil && ch.DeleteAt == 0 {
  1028  		t.Fatal("should have failed to get deleted channel")
  1029  	}
  1030  
  1031  	post1 := &model.Post{ChannelId: publicChannel1.Id, Message: "a" + GenerateTestId() + "a"}
  1032  	if _, err := Client.CreatePost(post1); err == nil {
  1033  		t.Fatal("should have failed to post to deleted channel")
  1034  	}
  1035  
  1036  	// successful delete of private channel
  1037  	privateChannel2 := th.CreatePrivateChannel()
  1038  	_, resp = Client.DeleteChannel(privateChannel2.Id)
  1039  	CheckNoError(t, resp)
  1040  
  1041  	// successful delete of channel with multiple members
  1042  	publicChannel3 := th.CreatePublicChannel()
  1043  	th.App.AddUserToChannel(user, publicChannel3)
  1044  	th.App.AddUserToChannel(user2, publicChannel3)
  1045  	_, resp = Client.DeleteChannel(publicChannel3.Id)
  1046  	CheckNoError(t, resp)
  1047  
  1048  	// default channel cannot be deleted.
  1049  	defaultChannel, _ := th.App.GetChannelByName(model.DEFAULT_CHANNEL, team.Id, false)
  1050  	pass, resp = Client.DeleteChannel(defaultChannel.Id)
  1051  	CheckBadRequestStatus(t, resp)
  1052  
  1053  	if pass {
  1054  		t.Fatal("should have failed")
  1055  	}
  1056  
  1057  	// check system admin can delete a channel without any appropriate team or channel membership.
  1058  	sdTeam := th.CreateTeamWithClient(Client)
  1059  	sdPublicChannel := &model.Channel{
  1060  		DisplayName: "dn_" + model.NewId(),
  1061  		Name:        GenerateTestChannelName(),
  1062  		Type:        model.CHANNEL_OPEN,
  1063  		TeamId:      sdTeam.Id,
  1064  	}
  1065  	sdPublicChannel, resp = Client.CreateChannel(sdPublicChannel)
  1066  	CheckNoError(t, resp)
  1067  	_, resp = th.SystemAdminClient.DeleteChannel(sdPublicChannel.Id)
  1068  	CheckNoError(t, resp)
  1069  
  1070  	sdPrivateChannel := &model.Channel{
  1071  		DisplayName: "dn_" + model.NewId(),
  1072  		Name:        GenerateTestChannelName(),
  1073  		Type:        model.CHANNEL_PRIVATE,
  1074  		TeamId:      sdTeam.Id,
  1075  	}
  1076  	sdPrivateChannel, resp = Client.CreateChannel(sdPrivateChannel)
  1077  	CheckNoError(t, resp)
  1078  	_, resp = th.SystemAdminClient.DeleteChannel(sdPrivateChannel.Id)
  1079  	CheckNoError(t, resp)
  1080  
  1081  	th.LoginBasic()
  1082  	publicChannel5 := th.CreatePublicChannel()
  1083  	Client.Logout()
  1084  
  1085  	Client.Login(user.Id, user.Password)
  1086  	_, resp = Client.DeleteChannel(publicChannel5.Id)
  1087  	CheckUnauthorizedStatus(t, resp)
  1088  
  1089  	_, resp = Client.DeleteChannel("junk")
  1090  	CheckUnauthorizedStatus(t, resp)
  1091  
  1092  	Client.Logout()
  1093  	_, resp = Client.DeleteChannel(GenerateTestId())
  1094  	CheckUnauthorizedStatus(t, resp)
  1095  
  1096  	_, resp = th.SystemAdminClient.DeleteChannel(publicChannel5.Id)
  1097  	CheckNoError(t, resp)
  1098  }
  1099  
  1100  func TestDeleteChannel2(t *testing.T) {
  1101  	th := Setup().InitBasic()
  1102  	defer th.TearDown()
  1103  	Client := th.Client
  1104  	user := th.BasicUser
  1105  
  1106  	// Check the appropriate permissions are enforced.
  1107  	defaultRolePermissions := th.SaveDefaultRolePermissions()
  1108  	defer func() {
  1109  		th.RestoreDefaultRolePermissions(defaultRolePermissions)
  1110  	}()
  1111  
  1112  	th.AddPermissionToRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID)
  1113  	th.AddPermissionToRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID)
  1114  
  1115  	// channels created by SystemAdmin
  1116  	publicChannel6 := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_OPEN)
  1117  	privateChannel7 := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE)
  1118  	th.App.AddUserToChannel(user, publicChannel6)
  1119  	th.App.AddUserToChannel(user, privateChannel7)
  1120  	th.App.AddUserToChannel(user, privateChannel7)
  1121  
  1122  	// successful delete by user
  1123  	_, resp := Client.DeleteChannel(publicChannel6.Id)
  1124  	CheckNoError(t, resp)
  1125  
  1126  	_, resp = Client.DeleteChannel(privateChannel7.Id)
  1127  	CheckNoError(t, resp)
  1128  
  1129  	// Restrict permissions to Channel Admins
  1130  	th.RemovePermissionFromRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID)
  1131  	th.RemovePermissionFromRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID)
  1132  	th.AddPermissionToRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID)
  1133  	th.AddPermissionToRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID)
  1134  
  1135  	// channels created by SystemAdmin
  1136  	publicChannel6 = th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_OPEN)
  1137  	privateChannel7 = th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE)
  1138  	th.App.AddUserToChannel(user, publicChannel6)
  1139  	th.App.AddUserToChannel(user, privateChannel7)
  1140  	th.App.AddUserToChannel(user, privateChannel7)
  1141  
  1142  	// cannot delete by user
  1143  	_, resp = Client.DeleteChannel(publicChannel6.Id)
  1144  	CheckForbiddenStatus(t, resp)
  1145  
  1146  	_, resp = Client.DeleteChannel(privateChannel7.Id)
  1147  	CheckForbiddenStatus(t, resp)
  1148  
  1149  	// successful delete by channel admin
  1150  	th.MakeUserChannelAdmin(user, publicChannel6)
  1151  	th.MakeUserChannelAdmin(user, privateChannel7)
  1152  	th.App.Srv.Store.Channel().ClearCaches()
  1153  
  1154  	_, resp = Client.DeleteChannel(publicChannel6.Id)
  1155  	CheckNoError(t, resp)
  1156  
  1157  	_, resp = Client.DeleteChannel(privateChannel7.Id)
  1158  	CheckNoError(t, resp)
  1159  
  1160  	// Make sure team admins don't have permission to delete channels.
  1161  	th.RemovePermissionFromRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID)
  1162  	th.RemovePermissionFromRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID)
  1163  
  1164  	// last member of a public channel should have required permission to delete
  1165  	publicChannel6 = th.CreateChannelWithClient(th.Client, model.CHANNEL_OPEN)
  1166  	_, resp = Client.DeleteChannel(publicChannel6.Id)
  1167  	CheckForbiddenStatus(t, resp)
  1168  
  1169  	// last member of a private channel should not be able to delete it if they don't have required permissions
  1170  	privateChannel7 = th.CreateChannelWithClient(th.Client, model.CHANNEL_PRIVATE)
  1171  	_, resp = Client.DeleteChannel(privateChannel7.Id)
  1172  	CheckForbiddenStatus(t, resp)
  1173  }
  1174  
  1175  func TestConvertChannelToPrivate(t *testing.T) {
  1176  	th := Setup().InitBasic()
  1177  	defer th.TearDown()
  1178  	Client := th.Client
  1179  
  1180  	defaultChannel, _ := th.App.GetChannelByName(model.DEFAULT_CHANNEL, th.BasicTeam.Id, false)
  1181  	_, resp := Client.ConvertChannelToPrivate(defaultChannel.Id)
  1182  	CheckForbiddenStatus(t, resp)
  1183  
  1184  	privateChannel := th.CreatePrivateChannel()
  1185  	_, resp = Client.ConvertChannelToPrivate(privateChannel.Id)
  1186  	CheckForbiddenStatus(t, resp)
  1187  
  1188  	publicChannel := th.CreatePublicChannel()
  1189  	_, resp = Client.ConvertChannelToPrivate(publicChannel.Id)
  1190  	CheckForbiddenStatus(t, resp)
  1191  
  1192  	th.LoginTeamAdmin()
  1193  	rchannel, resp := Client.ConvertChannelToPrivate(publicChannel.Id)
  1194  	CheckOKStatus(t, resp)
  1195  	if rchannel.Type != model.CHANNEL_PRIVATE {
  1196  		t.Fatal("channel should be converted from public to private")
  1197  	}
  1198  
  1199  	rchannel, resp = th.SystemAdminClient.ConvertChannelToPrivate(privateChannel.Id)
  1200  	CheckBadRequestStatus(t, resp)
  1201  	if rchannel != nil {
  1202  		t.Fatal("should not return a channel")
  1203  	}
  1204  
  1205  	rchannel, resp = th.SystemAdminClient.ConvertChannelToPrivate(defaultChannel.Id)
  1206  	CheckBadRequestStatus(t, resp)
  1207  	if rchannel != nil {
  1208  		t.Fatal("should not return a channel")
  1209  	}
  1210  
  1211  	WebSocketClient, err := th.CreateWebSocketClient()
  1212  	if err != nil {
  1213  		t.Fatal(err)
  1214  	}
  1215  	WebSocketClient.Listen()
  1216  
  1217  	publicChannel2 := th.CreatePublicChannel()
  1218  	rchannel, resp = th.SystemAdminClient.ConvertChannelToPrivate(publicChannel2.Id)
  1219  	CheckOKStatus(t, resp)
  1220  	if rchannel.Type != model.CHANNEL_PRIVATE {
  1221  		t.Fatal("channel should be converted from public to private")
  1222  	}
  1223  
  1224  	stop := make(chan bool)
  1225  	eventHit := false
  1226  
  1227  	go func() {
  1228  		for {
  1229  			select {
  1230  			case resp := <-WebSocketClient.EventChannel:
  1231  				if resp.Event == model.WEBSOCKET_EVENT_CHANNEL_CONVERTED && resp.Data["channel_id"].(string) == publicChannel2.Id {
  1232  					eventHit = true
  1233  				}
  1234  			case <-stop:
  1235  				return
  1236  			}
  1237  		}
  1238  	}()
  1239  
  1240  	time.Sleep(400 * time.Millisecond)
  1241  
  1242  	stop <- true
  1243  
  1244  	if !eventHit {
  1245  		t.Fatal("did not receive channel_converted event")
  1246  	}
  1247  }
  1248  
  1249  func TestRestoreChannel(t *testing.T) {
  1250  	th := Setup().InitBasic()
  1251  	defer th.TearDown()
  1252  	Client := th.Client
  1253  
  1254  	publicChannel1 := th.CreatePublicChannel()
  1255  	Client.DeleteChannel(publicChannel1.Id)
  1256  
  1257  	privateChannel1 := th.CreatePrivateChannel()
  1258  	Client.DeleteChannel(privateChannel1.Id)
  1259  
  1260  	_, resp := Client.RestoreChannel(publicChannel1.Id)
  1261  	CheckForbiddenStatus(t, resp)
  1262  
  1263  	_, resp = Client.RestoreChannel(privateChannel1.Id)
  1264  	CheckForbiddenStatus(t, resp)
  1265  
  1266  	th.LoginTeamAdmin()
  1267  
  1268  	_, resp = Client.RestoreChannel(publicChannel1.Id)
  1269  	CheckOKStatus(t, resp)
  1270  
  1271  	_, resp = Client.RestoreChannel(privateChannel1.Id)
  1272  	CheckOKStatus(t, resp)
  1273  }
  1274  
  1275  func TestGetChannelByName(t *testing.T) {
  1276  	th := Setup().InitBasic()
  1277  	defer th.TearDown()
  1278  	Client := th.Client
  1279  
  1280  	channel, resp := Client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
  1281  	CheckNoError(t, resp)
  1282  
  1283  	if channel.Name != th.BasicChannel.Name {
  1284  		t.Fatal("names did not match")
  1285  	}
  1286  
  1287  	channel, resp = Client.GetChannelByName(th.BasicPrivateChannel.Name, th.BasicTeam.Id, "")
  1288  	CheckNoError(t, resp)
  1289  
  1290  	if channel.Name != th.BasicPrivateChannel.Name {
  1291  		t.Fatal("names did not match")
  1292  	}
  1293  
  1294  	_, resp = Client.GetChannelByName(strings.ToUpper(th.BasicPrivateChannel.Name), th.BasicTeam.Id, "")
  1295  	CheckNoError(t, resp)
  1296  
  1297  	_, resp = Client.GetChannelByName(th.BasicDeletedChannel.Name, th.BasicTeam.Id, "")
  1298  	CheckNotFoundStatus(t, resp)
  1299  
  1300  	channel, resp = Client.GetChannelByNameIncludeDeleted(th.BasicDeletedChannel.Name, th.BasicTeam.Id, "")
  1301  	CheckNoError(t, resp)
  1302  
  1303  	if channel.Name != th.BasicDeletedChannel.Name {
  1304  		t.Fatal("names did not match")
  1305  	}
  1306  
  1307  	Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
  1308  	_, resp = Client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
  1309  	CheckNoError(t, resp)
  1310  
  1311  	Client.RemoveUserFromChannel(th.BasicPrivateChannel.Id, th.BasicUser.Id)
  1312  	_, resp = Client.GetChannelByName(th.BasicPrivateChannel.Name, th.BasicTeam.Id, "")
  1313  	CheckForbiddenStatus(t, resp)
  1314  
  1315  	_, resp = Client.GetChannelByName(GenerateTestChannelName(), th.BasicTeam.Id, "")
  1316  	CheckNotFoundStatus(t, resp)
  1317  
  1318  	_, resp = Client.GetChannelByName(GenerateTestChannelName(), "junk", "")
  1319  	CheckBadRequestStatus(t, resp)
  1320  
  1321  	Client.Logout()
  1322  	_, resp = Client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
  1323  	CheckUnauthorizedStatus(t, resp)
  1324  
  1325  	user := th.CreateUser()
  1326  	Client.Login(user.Email, user.Password)
  1327  	_, resp = Client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
  1328  	CheckForbiddenStatus(t, resp)
  1329  
  1330  	_, resp = th.SystemAdminClient.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
  1331  	CheckNoError(t, resp)
  1332  }
  1333  
  1334  func TestGetChannelByNameForTeamName(t *testing.T) {
  1335  	th := Setup().InitBasic()
  1336  	defer th.TearDown()
  1337  	Client := th.Client
  1338  
  1339  	channel, resp := th.SystemAdminClient.GetChannelByNameForTeamName(th.BasicChannel.Name, th.BasicTeam.Name, "")
  1340  	CheckNoError(t, resp)
  1341  
  1342  	if channel.Name != th.BasicChannel.Name {
  1343  		t.Fatal("names did not match")
  1344  	}
  1345  
  1346  	_, resp = Client.GetChannelByNameForTeamName(th.BasicChannel.Name, th.BasicTeam.Name, "")
  1347  	CheckNoError(t, resp)
  1348  
  1349  	_, resp = Client.GetChannelByNameForTeamName(th.BasicDeletedChannel.Name, th.BasicTeam.Name, "")
  1350  	CheckNotFoundStatus(t, resp)
  1351  
  1352  	channel, resp = Client.GetChannelByNameForTeamNameIncludeDeleted(th.BasicDeletedChannel.Name, th.BasicTeam.Name, "")
  1353  	CheckNoError(t, resp)
  1354  
  1355  	if channel.Name != th.BasicDeletedChannel.Name {
  1356  		t.Fatal("names did not match")
  1357  	}
  1358  
  1359  	_, resp = Client.GetChannelByNameForTeamName(th.BasicChannel.Name, model.NewRandomString(15), "")
  1360  	CheckNotFoundStatus(t, resp)
  1361  
  1362  	_, resp = Client.GetChannelByNameForTeamName(GenerateTestChannelName(), th.BasicTeam.Name, "")
  1363  	CheckNotFoundStatus(t, resp)
  1364  
  1365  	Client.Logout()
  1366  	_, resp = Client.GetChannelByNameForTeamName(th.BasicChannel.Name, th.BasicTeam.Name, "")
  1367  	CheckUnauthorizedStatus(t, resp)
  1368  
  1369  	user := th.CreateUser()
  1370  	Client.Login(user.Email, user.Password)
  1371  	_, resp = Client.GetChannelByNameForTeamName(th.BasicChannel.Name, th.BasicTeam.Name, "")
  1372  	CheckForbiddenStatus(t, resp)
  1373  }
  1374  
  1375  func TestGetChannelMembers(t *testing.T) {
  1376  	th := Setup().InitBasic()
  1377  	defer th.TearDown()
  1378  	Client := th.Client
  1379  
  1380  	members, resp := Client.GetChannelMembers(th.BasicChannel.Id, 0, 60, "")
  1381  	CheckNoError(t, resp)
  1382  
  1383  	if len(*members) != 3 {
  1384  		t.Fatal("should only be 3 users in channel")
  1385  	}
  1386  
  1387  	members, resp = Client.GetChannelMembers(th.BasicChannel.Id, 0, 2, "")
  1388  	CheckNoError(t, resp)
  1389  
  1390  	if len(*members) != 2 {
  1391  		t.Fatal("should only be 2 users")
  1392  	}
  1393  
  1394  	members, resp = Client.GetChannelMembers(th.BasicChannel.Id, 1, 1, "")
  1395  	CheckNoError(t, resp)
  1396  
  1397  	if len(*members) != 1 {
  1398  		t.Fatal("should only be 1 user")
  1399  	}
  1400  
  1401  	members, resp = Client.GetChannelMembers(th.BasicChannel.Id, 1000, 100000, "")
  1402  	CheckNoError(t, resp)
  1403  
  1404  	if len(*members) != 0 {
  1405  		t.Fatal("should be 0 users")
  1406  	}
  1407  
  1408  	_, resp = Client.GetChannelMembers("", 0, 60, "")
  1409  	CheckBadRequestStatus(t, resp)
  1410  
  1411  	_, resp = Client.GetChannelMembers("junk", 0, 60, "")
  1412  	CheckBadRequestStatus(t, resp)
  1413  
  1414  	_, resp = Client.GetChannelMembers(model.NewId(), 0, 60, "")
  1415  	CheckForbiddenStatus(t, resp)
  1416  
  1417  	Client.Logout()
  1418  	_, resp = Client.GetChannelMembers(th.BasicChannel.Id, 0, 60, "")
  1419  	CheckUnauthorizedStatus(t, resp)
  1420  
  1421  	user := th.CreateUser()
  1422  	Client.Login(user.Email, user.Password)
  1423  	_, resp = Client.GetChannelMembers(th.BasicChannel.Id, 0, 60, "")
  1424  	CheckForbiddenStatus(t, resp)
  1425  
  1426  	_, resp = th.SystemAdminClient.GetChannelMembers(th.BasicChannel.Id, 0, 60, "")
  1427  	CheckNoError(t, resp)
  1428  }
  1429  
  1430  func TestGetChannelMembersByIds(t *testing.T) {
  1431  	th := Setup().InitBasic()
  1432  	defer th.TearDown()
  1433  	Client := th.Client
  1434  
  1435  	cm, resp := Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{th.BasicUser.Id})
  1436  	CheckNoError(t, resp)
  1437  
  1438  	if (*cm)[0].UserId != th.BasicUser.Id {
  1439  		t.Fatal("returned wrong user")
  1440  	}
  1441  
  1442  	_, resp = Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{})
  1443  	CheckBadRequestStatus(t, resp)
  1444  
  1445  	cm1, resp := Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{"junk"})
  1446  	CheckNoError(t, resp)
  1447  	if len(*cm1) > 0 {
  1448  		t.Fatal("no users should be returned")
  1449  	}
  1450  
  1451  	cm1, resp = Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{"junk", th.BasicUser.Id})
  1452  	CheckNoError(t, resp)
  1453  	if len(*cm1) != 1 {
  1454  		t.Fatal("1 member should be returned")
  1455  	}
  1456  
  1457  	cm1, resp = Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{th.BasicUser2.Id, th.BasicUser.Id})
  1458  	CheckNoError(t, resp)
  1459  	if len(*cm1) != 2 {
  1460  		t.Fatal("2 members should be returned")
  1461  	}
  1462  
  1463  	_, resp = Client.GetChannelMembersByIds("junk", []string{th.BasicUser.Id})
  1464  	CheckBadRequestStatus(t, resp)
  1465  
  1466  	_, resp = Client.GetChannelMembersByIds(model.NewId(), []string{th.BasicUser.Id})
  1467  	CheckForbiddenStatus(t, resp)
  1468  
  1469  	Client.Logout()
  1470  	_, resp = Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{th.BasicUser.Id})
  1471  	CheckUnauthorizedStatus(t, resp)
  1472  
  1473  	_, resp = th.SystemAdminClient.GetChannelMembersByIds(th.BasicChannel.Id, []string{th.BasicUser2.Id, th.BasicUser.Id})
  1474  	CheckNoError(t, resp)
  1475  }
  1476  
  1477  func TestGetChannelMember(t *testing.T) {
  1478  	th := Setup().InitBasic()
  1479  	defer th.TearDown()
  1480  	Client := th.Client
  1481  
  1482  	member, resp := Client.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1483  	CheckNoError(t, resp)
  1484  
  1485  	if member.ChannelId != th.BasicChannel.Id {
  1486  		t.Fatal("wrong channel id")
  1487  	}
  1488  
  1489  	if member.UserId != th.BasicUser.Id {
  1490  		t.Fatal("wrong user id")
  1491  	}
  1492  
  1493  	_, resp = Client.GetChannelMember("", th.BasicUser.Id, "")
  1494  	CheckNotFoundStatus(t, resp)
  1495  
  1496  	_, resp = Client.GetChannelMember("junk", th.BasicUser.Id, "")
  1497  	CheckBadRequestStatus(t, resp)
  1498  
  1499  	_, resp = Client.GetChannelMember(model.NewId(), th.BasicUser.Id, "")
  1500  	CheckForbiddenStatus(t, resp)
  1501  
  1502  	_, resp = Client.GetChannelMember(th.BasicChannel.Id, "", "")
  1503  	CheckNotFoundStatus(t, resp)
  1504  
  1505  	_, resp = Client.GetChannelMember(th.BasicChannel.Id, "junk", "")
  1506  	CheckBadRequestStatus(t, resp)
  1507  
  1508  	_, resp = Client.GetChannelMember(th.BasicChannel.Id, model.NewId(), "")
  1509  	CheckNotFoundStatus(t, resp)
  1510  
  1511  	Client.Logout()
  1512  	_, resp = Client.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1513  	CheckUnauthorizedStatus(t, resp)
  1514  
  1515  	user := th.CreateUser()
  1516  	Client.Login(user.Email, user.Password)
  1517  	_, resp = Client.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1518  	CheckForbiddenStatus(t, resp)
  1519  
  1520  	_, resp = th.SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1521  	CheckNoError(t, resp)
  1522  }
  1523  
  1524  func TestGetChannelMembersForUser(t *testing.T) {
  1525  	th := Setup().InitBasic()
  1526  	defer th.TearDown()
  1527  	Client := th.Client
  1528  
  1529  	members, resp := Client.GetChannelMembersForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
  1530  	CheckNoError(t, resp)
  1531  
  1532  	if len(*members) != 6 {
  1533  		t.Fatal("should have 6 members on team")
  1534  	}
  1535  
  1536  	_, resp = Client.GetChannelMembersForUser("", th.BasicTeam.Id, "")
  1537  	CheckNotFoundStatus(t, resp)
  1538  
  1539  	_, resp = Client.GetChannelMembersForUser("junk", th.BasicTeam.Id, "")
  1540  	CheckBadRequestStatus(t, resp)
  1541  
  1542  	_, resp = Client.GetChannelMembersForUser(model.NewId(), th.BasicTeam.Id, "")
  1543  	CheckForbiddenStatus(t, resp)
  1544  
  1545  	_, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, "", "")
  1546  	CheckNotFoundStatus(t, resp)
  1547  
  1548  	_, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, "junk", "")
  1549  	CheckBadRequestStatus(t, resp)
  1550  
  1551  	_, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, model.NewId(), "")
  1552  	CheckForbiddenStatus(t, resp)
  1553  
  1554  	Client.Logout()
  1555  	_, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
  1556  	CheckUnauthorizedStatus(t, resp)
  1557  
  1558  	user := th.CreateUser()
  1559  	Client.Login(user.Email, user.Password)
  1560  	_, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
  1561  	CheckForbiddenStatus(t, resp)
  1562  
  1563  	_, resp = th.SystemAdminClient.GetChannelMembersForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
  1564  	CheckNoError(t, resp)
  1565  }
  1566  
  1567  func TestViewChannel(t *testing.T) {
  1568  	th := Setup().InitBasic()
  1569  	defer th.TearDown()
  1570  	Client := th.Client
  1571  
  1572  	view := &model.ChannelView{
  1573  		ChannelId: th.BasicChannel.Id,
  1574  	}
  1575  
  1576  	viewResp, resp := Client.ViewChannel(th.BasicUser.Id, view)
  1577  	CheckNoError(t, resp)
  1578  
  1579  	if viewResp.Status != "OK" {
  1580  		t.Fatal("should have passed")
  1581  	}
  1582  
  1583  	channel, _ := th.App.GetChannel(th.BasicChannel.Id)
  1584  
  1585  	if lastViewedAt := viewResp.LastViewedAtTimes[channel.Id]; lastViewedAt != channel.LastPostAt {
  1586  		t.Fatal("LastPostAt does not match returned LastViewedAt time")
  1587  	}
  1588  
  1589  	view.PrevChannelId = th.BasicChannel.Id
  1590  	_, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1591  	CheckNoError(t, resp)
  1592  
  1593  	view.PrevChannelId = ""
  1594  	_, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1595  	CheckNoError(t, resp)
  1596  
  1597  	view.PrevChannelId = "junk"
  1598  	_, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1599  	CheckBadRequestStatus(t, resp)
  1600  
  1601  	// All blank is OK we use it for clicking off of the browser.
  1602  	view.PrevChannelId = ""
  1603  	view.ChannelId = ""
  1604  	_, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1605  	CheckNoError(t, resp)
  1606  
  1607  	view.PrevChannelId = ""
  1608  	view.ChannelId = "junk"
  1609  	_, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1610  	CheckBadRequestStatus(t, resp)
  1611  
  1612  	view.ChannelId = "correctlysizedjunkdddfdfdf"
  1613  	_, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1614  	CheckBadRequestStatus(t, resp)
  1615  	view.ChannelId = th.BasicChannel.Id
  1616  
  1617  	member, resp := Client.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1618  	CheckNoError(t, resp)
  1619  	channel, resp = Client.GetChannel(th.BasicChannel.Id, "")
  1620  	CheckNoError(t, resp)
  1621  
  1622  	if member.MsgCount != channel.TotalMsgCount {
  1623  		t.Fatal("should match message counts")
  1624  	}
  1625  
  1626  	if member.MentionCount != 0 {
  1627  		t.Fatal("should have no mentions")
  1628  	}
  1629  
  1630  	_, resp = Client.ViewChannel("junk", view)
  1631  	CheckBadRequestStatus(t, resp)
  1632  
  1633  	_, resp = Client.ViewChannel(th.BasicUser2.Id, view)
  1634  	CheckForbiddenStatus(t, resp)
  1635  
  1636  	if r, err := Client.DoApiPost(fmt.Sprintf("/channels/members/%v/view", th.BasicUser.Id), "garbage"); err == nil {
  1637  		t.Fatal("should have errored")
  1638  	} else {
  1639  		if r.StatusCode != http.StatusBadRequest {
  1640  			t.Log("actual: " + strconv.Itoa(r.StatusCode))
  1641  			t.Log("expected: " + strconv.Itoa(http.StatusBadRequest))
  1642  			t.Fatal("wrong status code")
  1643  		}
  1644  	}
  1645  
  1646  	Client.Logout()
  1647  	_, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1648  	CheckUnauthorizedStatus(t, resp)
  1649  
  1650  	_, resp = th.SystemAdminClient.ViewChannel(th.BasicUser.Id, view)
  1651  	CheckNoError(t, resp)
  1652  }
  1653  
  1654  func TestGetChannelUnread(t *testing.T) {
  1655  	th := Setup().InitBasic()
  1656  	defer th.TearDown()
  1657  	Client := th.Client
  1658  	user := th.BasicUser
  1659  	channel := th.BasicChannel
  1660  
  1661  	channelUnread, resp := Client.GetChannelUnread(channel.Id, user.Id)
  1662  	CheckNoError(t, resp)
  1663  	if channelUnread.TeamId != th.BasicTeam.Id {
  1664  		t.Fatal("wrong team id returned for a regular user call")
  1665  	} else if channelUnread.ChannelId != channel.Id {
  1666  		t.Fatal("wrong team id returned for a regular user call")
  1667  	}
  1668  
  1669  	_, resp = Client.GetChannelUnread("junk", user.Id)
  1670  	CheckBadRequestStatus(t, resp)
  1671  
  1672  	_, resp = Client.GetChannelUnread(channel.Id, "junk")
  1673  	CheckBadRequestStatus(t, resp)
  1674  
  1675  	_, resp = Client.GetChannelUnread(channel.Id, model.NewId())
  1676  	CheckForbiddenStatus(t, resp)
  1677  
  1678  	_, resp = Client.GetChannelUnread(model.NewId(), user.Id)
  1679  	CheckForbiddenStatus(t, resp)
  1680  
  1681  	newUser := th.CreateUser()
  1682  	Client.Login(newUser.Email, newUser.Password)
  1683  	_, resp = Client.GetChannelUnread(th.BasicChannel.Id, user.Id)
  1684  	CheckForbiddenStatus(t, resp)
  1685  
  1686  	Client.Logout()
  1687  
  1688  	_, resp = th.SystemAdminClient.GetChannelUnread(channel.Id, user.Id)
  1689  	CheckNoError(t, resp)
  1690  
  1691  	_, resp = th.SystemAdminClient.GetChannelUnread(model.NewId(), user.Id)
  1692  	CheckForbiddenStatus(t, resp)
  1693  
  1694  	_, resp = th.SystemAdminClient.GetChannelUnread(channel.Id, model.NewId())
  1695  	CheckNotFoundStatus(t, resp)
  1696  }
  1697  
  1698  func TestGetChannelStats(t *testing.T) {
  1699  	th := Setup().InitBasic()
  1700  	defer th.TearDown()
  1701  	Client := th.Client
  1702  	channel := th.CreatePrivateChannel()
  1703  
  1704  	stats, resp := Client.GetChannelStats(channel.Id, "")
  1705  	CheckNoError(t, resp)
  1706  
  1707  	if stats.ChannelId != channel.Id {
  1708  		t.Fatal("couldnt't get extra info")
  1709  	} else if stats.MemberCount != 1 {
  1710  		t.Fatal("got incorrect member count")
  1711  	}
  1712  
  1713  	_, resp = Client.GetChannelStats("junk", "")
  1714  	CheckBadRequestStatus(t, resp)
  1715  
  1716  	_, resp = Client.GetChannelStats(model.NewId(), "")
  1717  	CheckForbiddenStatus(t, resp)
  1718  
  1719  	Client.Logout()
  1720  	_, resp = Client.GetChannelStats(channel.Id, "")
  1721  	CheckUnauthorizedStatus(t, resp)
  1722  
  1723  	th.LoginBasic2()
  1724  
  1725  	_, resp = Client.GetChannelStats(channel.Id, "")
  1726  	CheckForbiddenStatus(t, resp)
  1727  
  1728  	_, resp = th.SystemAdminClient.GetChannelStats(channel.Id, "")
  1729  	CheckNoError(t, resp)
  1730  }
  1731  
  1732  func TestGetPinnedPosts(t *testing.T) {
  1733  	th := Setup().InitBasic()
  1734  	defer th.TearDown()
  1735  	Client := th.Client
  1736  	channel := th.BasicChannel
  1737  
  1738  	posts, resp := Client.GetPinnedPosts(channel.Id, "")
  1739  	CheckNoError(t, resp)
  1740  	if len(posts.Posts) != 0 {
  1741  		t.Fatal("should not have gotten a pinned post")
  1742  	}
  1743  
  1744  	pinnedPost := th.CreatePinnedPost()
  1745  	posts, resp = Client.GetPinnedPosts(channel.Id, "")
  1746  	CheckNoError(t, resp)
  1747  	if len(posts.Posts) != 1 {
  1748  		t.Fatal("should have returned 1 pinned post")
  1749  	}
  1750  	if _, ok := posts.Posts[pinnedPost.Id]; !ok {
  1751  		t.Fatal("missing pinned post")
  1752  	}
  1753  
  1754  	posts, resp = Client.GetPinnedPosts(channel.Id, resp.Etag)
  1755  	CheckEtag(t, posts, resp)
  1756  
  1757  	_, resp = Client.GetPinnedPosts(GenerateTestId(), "")
  1758  	CheckForbiddenStatus(t, resp)
  1759  
  1760  	_, resp = Client.GetPinnedPosts("junk", "")
  1761  	CheckBadRequestStatus(t, resp)
  1762  
  1763  	Client.Logout()
  1764  	_, resp = Client.GetPinnedPosts(channel.Id, "")
  1765  	CheckUnauthorizedStatus(t, resp)
  1766  
  1767  	_, resp = th.SystemAdminClient.GetPinnedPosts(channel.Id, "")
  1768  	CheckNoError(t, resp)
  1769  }
  1770  
  1771  func TestUpdateChannelRoles(t *testing.T) {
  1772  	th := Setup().InitBasic()
  1773  	defer th.TearDown()
  1774  	Client := th.Client
  1775  
  1776  	const CHANNEL_ADMIN = "channel_user channel_admin"
  1777  	const CHANNEL_MEMBER = "channel_user"
  1778  
  1779  	// User 1 creates a channel, making them channel admin by default.
  1780  	channel := th.CreatePublicChannel()
  1781  
  1782  	// Adds User 2 to the channel, making them a channel member by default.
  1783  	th.App.AddUserToChannel(th.BasicUser2, channel)
  1784  
  1785  	// User 1 promotes User 2
  1786  	pass, resp := Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_ADMIN)
  1787  	CheckNoError(t, resp)
  1788  
  1789  	if !pass {
  1790  		t.Fatal("should have passed")
  1791  	}
  1792  
  1793  	member, resp := Client.GetChannelMember(channel.Id, th.BasicUser2.Id, "")
  1794  	CheckNoError(t, resp)
  1795  
  1796  	if member.Roles != CHANNEL_ADMIN {
  1797  		t.Fatal("roles don't match")
  1798  	}
  1799  
  1800  	// User 1 demotes User 2
  1801  	_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_MEMBER)
  1802  	CheckNoError(t, resp)
  1803  
  1804  	th.LoginBasic2()
  1805  
  1806  	// User 2 cannot demote User 1
  1807  	_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER)
  1808  	CheckForbiddenStatus(t, resp)
  1809  
  1810  	// User 2 cannot promote self
  1811  	_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_ADMIN)
  1812  	CheckForbiddenStatus(t, resp)
  1813  
  1814  	th.LoginBasic()
  1815  
  1816  	// User 1 demotes self
  1817  	_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER)
  1818  	CheckNoError(t, resp)
  1819  
  1820  	// System Admin promotes User 1
  1821  	_, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_ADMIN)
  1822  	CheckNoError(t, resp)
  1823  
  1824  	// System Admin demotes User 1
  1825  	_, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER)
  1826  	CheckNoError(t, resp)
  1827  
  1828  	// System Admin promotes User 1
  1829  	_, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_ADMIN)
  1830  	CheckNoError(t, resp)
  1831  
  1832  	th.LoginBasic()
  1833  
  1834  	_, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, "junk")
  1835  	CheckBadRequestStatus(t, resp)
  1836  
  1837  	_, resp = Client.UpdateChannelRoles(channel.Id, "junk", CHANNEL_MEMBER)
  1838  	CheckBadRequestStatus(t, resp)
  1839  
  1840  	_, resp = Client.UpdateChannelRoles("junk", th.BasicUser.Id, CHANNEL_MEMBER)
  1841  	CheckBadRequestStatus(t, resp)
  1842  
  1843  	_, resp = Client.UpdateChannelRoles(channel.Id, model.NewId(), CHANNEL_MEMBER)
  1844  	CheckNotFoundStatus(t, resp)
  1845  
  1846  	_, resp = Client.UpdateChannelRoles(model.NewId(), th.BasicUser.Id, CHANNEL_MEMBER)
  1847  	CheckForbiddenStatus(t, resp)
  1848  }
  1849  
  1850  func TestUpdateChannelMemberSchemeRoles(t *testing.T) {
  1851  	th := Setup().InitBasic()
  1852  	defer th.TearDown()
  1853  	SystemAdminClient := th.SystemAdminClient
  1854  	th.LoginBasic()
  1855  
  1856  	s1 := &model.SchemeRoles{
  1857  		SchemeAdmin: false,
  1858  		SchemeUser:  false,
  1859  		SchemeGuest: false,
  1860  	}
  1861  	_, r1 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s1)
  1862  	CheckNoError(t, r1)
  1863  
  1864  	tm1, rtm1 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1865  	CheckNoError(t, rtm1)
  1866  	assert.Equal(t, false, tm1.SchemeGuest)
  1867  	assert.Equal(t, false, tm1.SchemeUser)
  1868  	assert.Equal(t, false, tm1.SchemeAdmin)
  1869  
  1870  	s2 := &model.SchemeRoles{
  1871  		SchemeAdmin: false,
  1872  		SchemeUser:  true,
  1873  		SchemeGuest: false,
  1874  	}
  1875  	_, r2 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s2)
  1876  	CheckNoError(t, r2)
  1877  
  1878  	tm2, rtm2 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1879  	CheckNoError(t, rtm2)
  1880  	assert.Equal(t, false, tm2.SchemeGuest)
  1881  	assert.Equal(t, true, tm2.SchemeUser)
  1882  	assert.Equal(t, false, tm2.SchemeAdmin)
  1883  
  1884  	s3 := &model.SchemeRoles{
  1885  		SchemeAdmin: true,
  1886  		SchemeUser:  false,
  1887  		SchemeGuest: false,
  1888  	}
  1889  	_, r3 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s3)
  1890  	CheckNoError(t, r3)
  1891  
  1892  	tm3, rtm3 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1893  	CheckNoError(t, rtm3)
  1894  	assert.Equal(t, false, tm3.SchemeGuest)
  1895  	assert.Equal(t, false, tm3.SchemeUser)
  1896  	assert.Equal(t, true, tm3.SchemeAdmin)
  1897  
  1898  	s4 := &model.SchemeRoles{
  1899  		SchemeAdmin: true,
  1900  		SchemeUser:  true,
  1901  		SchemeGuest: false,
  1902  	}
  1903  	_, r4 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s4)
  1904  	CheckNoError(t, r4)
  1905  
  1906  	tm4, rtm4 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1907  	CheckNoError(t, rtm4)
  1908  	assert.Equal(t, false, tm4.SchemeGuest)
  1909  	assert.Equal(t, true, tm4.SchemeUser)
  1910  	assert.Equal(t, true, tm4.SchemeAdmin)
  1911  
  1912  	s5 := &model.SchemeRoles{
  1913  		SchemeAdmin: false,
  1914  		SchemeUser:  false,
  1915  		SchemeGuest: true,
  1916  	}
  1917  	_, r5 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s5)
  1918  	CheckNoError(t, r5)
  1919  
  1920  	tm5, rtm5 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1921  	CheckNoError(t, rtm5)
  1922  	assert.Equal(t, true, tm5.SchemeGuest)
  1923  	assert.Equal(t, false, tm5.SchemeUser)
  1924  	assert.Equal(t, false, tm5.SchemeAdmin)
  1925  
  1926  	s6 := &model.SchemeRoles{
  1927  		SchemeAdmin: false,
  1928  		SchemeUser:  true,
  1929  		SchemeGuest: true,
  1930  	}
  1931  	_, resp := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s6)
  1932  	CheckBadRequestStatus(t, resp)
  1933  
  1934  	_, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles(model.NewId(), th.BasicUser.Id, s4)
  1935  	CheckForbiddenStatus(t, resp)
  1936  
  1937  	_, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, model.NewId(), s4)
  1938  	CheckNotFoundStatus(t, resp)
  1939  
  1940  	_, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles("ASDF", th.BasicUser.Id, s4)
  1941  	CheckBadRequestStatus(t, resp)
  1942  
  1943  	_, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, "ASDF", s4)
  1944  	CheckBadRequestStatus(t, resp)
  1945  
  1946  	th.LoginBasic2()
  1947  	_, resp = th.Client.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s4)
  1948  	CheckForbiddenStatus(t, resp)
  1949  
  1950  	SystemAdminClient.Logout()
  1951  	_, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.SystemAdminUser.Id, s4)
  1952  	CheckUnauthorizedStatus(t, resp)
  1953  }
  1954  
  1955  func TestUpdateChannelNotifyProps(t *testing.T) {
  1956  	th := Setup().InitBasic()
  1957  	defer th.TearDown()
  1958  	Client := th.Client
  1959  
  1960  	props := map[string]string{}
  1961  	props[model.DESKTOP_NOTIFY_PROP] = model.CHANNEL_NOTIFY_MENTION
  1962  	props[model.MARK_UNREAD_NOTIFY_PROP] = model.CHANNEL_MARK_UNREAD_MENTION
  1963  
  1964  	pass, resp := Client.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, props)
  1965  	CheckNoError(t, resp)
  1966  
  1967  	if !pass {
  1968  		t.Fatal("should have passed")
  1969  	}
  1970  
  1971  	member, err := th.App.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id)
  1972  	if err != nil {
  1973  		t.Fatal(err)
  1974  	}
  1975  
  1976  	if member.NotifyProps[model.DESKTOP_NOTIFY_PROP] != model.CHANNEL_NOTIFY_MENTION {
  1977  		t.Fatal("bad update")
  1978  	} else if member.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] != model.CHANNEL_MARK_UNREAD_MENTION {
  1979  		t.Fatal("bad update")
  1980  	}
  1981  
  1982  	_, resp = Client.UpdateChannelNotifyProps("junk", th.BasicUser.Id, props)
  1983  	CheckBadRequestStatus(t, resp)
  1984  
  1985  	_, resp = Client.UpdateChannelNotifyProps(th.BasicChannel.Id, "junk", props)
  1986  	CheckBadRequestStatus(t, resp)
  1987  
  1988  	_, resp = Client.UpdateChannelNotifyProps(model.NewId(), th.BasicUser.Id, props)
  1989  	CheckNotFoundStatus(t, resp)
  1990  
  1991  	_, resp = Client.UpdateChannelNotifyProps(th.BasicChannel.Id, model.NewId(), props)
  1992  	CheckForbiddenStatus(t, resp)
  1993  
  1994  	_, resp = Client.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, map[string]string{})
  1995  	CheckNoError(t, resp)
  1996  
  1997  	Client.Logout()
  1998  	_, resp = Client.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, props)
  1999  	CheckUnauthorizedStatus(t, resp)
  2000  
  2001  	_, resp = th.SystemAdminClient.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, props)
  2002  	CheckNoError(t, resp)
  2003  }
  2004  
  2005  func TestAddChannelMember(t *testing.T) {
  2006  	th := Setup().InitBasic()
  2007  	defer th.TearDown()
  2008  	Client := th.Client
  2009  	user := th.BasicUser
  2010  	user2 := th.BasicUser2
  2011  	team := th.BasicTeam
  2012  	publicChannel := th.CreatePublicChannel()
  2013  	privateChannel := th.CreatePrivateChannel()
  2014  
  2015  	user3 := th.CreateUserWithClient(th.SystemAdminClient)
  2016  	_, resp := th.SystemAdminClient.AddTeamMember(team.Id, user3.Id)
  2017  	CheckNoError(t, resp)
  2018  
  2019  	cm, resp := Client.AddChannelMember(publicChannel.Id, user2.Id)
  2020  	CheckNoError(t, resp)
  2021  	CheckCreatedStatus(t, resp)
  2022  
  2023  	if cm.ChannelId != publicChannel.Id {
  2024  		t.Fatal("should have returned exact channel")
  2025  	}
  2026  
  2027  	if cm.UserId != user2.Id {
  2028  		t.Fatal("should have returned exact user added to public channel")
  2029  	}
  2030  
  2031  	cm, resp = Client.AddChannelMember(privateChannel.Id, user2.Id)
  2032  	CheckNoError(t, resp)
  2033  
  2034  	if cm.ChannelId != privateChannel.Id {
  2035  		t.Fatal("should have returned exact channel")
  2036  	}
  2037  
  2038  	if cm.UserId != user2.Id {
  2039  		t.Fatal("should have returned exact user added to private channel")
  2040  	}
  2041  
  2042  	post := &model.Post{ChannelId: publicChannel.Id, Message: "a" + GenerateTestId() + "a"}
  2043  	rpost, err := Client.CreatePost(post)
  2044  	if err == nil {
  2045  		t.Fatal("should have created a post")
  2046  	}
  2047  
  2048  	Client.RemoveUserFromChannel(publicChannel.Id, user.Id)
  2049  	_, resp = Client.AddChannelMemberWithRootId(publicChannel.Id, user.Id, rpost.Id)
  2050  	CheckNoError(t, resp)
  2051  	CheckCreatedStatus(t, resp)
  2052  
  2053  	Client.RemoveUserFromChannel(publicChannel.Id, user.Id)
  2054  	_, resp = Client.AddChannelMemberWithRootId(publicChannel.Id, user.Id, "junk")
  2055  	CheckBadRequestStatus(t, resp)
  2056  
  2057  	_, resp = Client.AddChannelMemberWithRootId(publicChannel.Id, user.Id, GenerateTestId())
  2058  	CheckNotFoundStatus(t, resp)
  2059  
  2060  	Client.RemoveUserFromChannel(publicChannel.Id, user.Id)
  2061  	_, resp = Client.AddChannelMember(publicChannel.Id, user.Id)
  2062  	CheckNoError(t, resp)
  2063  
  2064  	cm, resp = Client.AddChannelMember(publicChannel.Id, "junk")
  2065  	CheckBadRequestStatus(t, resp)
  2066  
  2067  	if cm != nil {
  2068  		t.Fatal("should return nothing")
  2069  	}
  2070  
  2071  	_, resp = Client.AddChannelMember(publicChannel.Id, GenerateTestId())
  2072  	CheckNotFoundStatus(t, resp)
  2073  
  2074  	_, resp = Client.AddChannelMember("junk", user2.Id)
  2075  	CheckBadRequestStatus(t, resp)
  2076  
  2077  	_, resp = Client.AddChannelMember(GenerateTestId(), user2.Id)
  2078  	CheckNotFoundStatus(t, resp)
  2079  
  2080  	otherUser := th.CreateUser()
  2081  	otherChannel := th.CreatePublicChannel()
  2082  	Client.Logout()
  2083  	Client.Login(user2.Id, user2.Password)
  2084  
  2085  	_, resp = Client.AddChannelMember(publicChannel.Id, otherUser.Id)
  2086  	CheckUnauthorizedStatus(t, resp)
  2087  
  2088  	_, resp = Client.AddChannelMember(privateChannel.Id, otherUser.Id)
  2089  	CheckUnauthorizedStatus(t, resp)
  2090  
  2091  	_, resp = Client.AddChannelMember(otherChannel.Id, otherUser.Id)
  2092  	CheckUnauthorizedStatus(t, resp)
  2093  
  2094  	Client.Logout()
  2095  	Client.Login(user.Id, user.Password)
  2096  
  2097  	// should fail adding user who is not a member of the team
  2098  	_, resp = Client.AddChannelMember(otherChannel.Id, otherUser.Id)
  2099  	CheckUnauthorizedStatus(t, resp)
  2100  
  2101  	Client.DeleteChannel(otherChannel.Id)
  2102  
  2103  	// should fail adding user to a deleted channel
  2104  	_, resp = Client.AddChannelMember(otherChannel.Id, user2.Id)
  2105  	CheckUnauthorizedStatus(t, resp)
  2106  
  2107  	Client.Logout()
  2108  	_, resp = Client.AddChannelMember(publicChannel.Id, user2.Id)
  2109  	CheckUnauthorizedStatus(t, resp)
  2110  
  2111  	_, resp = Client.AddChannelMember(privateChannel.Id, user2.Id)
  2112  	CheckUnauthorizedStatus(t, resp)
  2113  
  2114  	_, resp = th.SystemAdminClient.AddChannelMember(publicChannel.Id, user2.Id)
  2115  	CheckNoError(t, resp)
  2116  
  2117  	_, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, user2.Id)
  2118  	CheckNoError(t, resp)
  2119  
  2120  	// Check the appropriate permissions are enforced.
  2121  	defaultRolePermissions := th.SaveDefaultRolePermissions()
  2122  	defer func() {
  2123  		th.RestoreDefaultRolePermissions(defaultRolePermissions)
  2124  	}()
  2125  
  2126  	th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID)
  2127  
  2128  	// Check that a regular channel user can add other users.
  2129  	Client.Login(user2.Username, user2.Password)
  2130  	privateChannel = th.CreatePrivateChannel()
  2131  	_, resp = Client.AddChannelMember(privateChannel.Id, user.Id)
  2132  	CheckNoError(t, resp)
  2133  	Client.Logout()
  2134  
  2135  	Client.Login(user.Username, user.Password)
  2136  	_, resp = Client.AddChannelMember(privateChannel.Id, user3.Id)
  2137  	CheckNoError(t, resp)
  2138  	Client.Logout()
  2139  
  2140  	// Restrict the permission for adding users to Channel Admins
  2141  	th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_ADMIN_ROLE_ID)
  2142  	th.RemovePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID)
  2143  
  2144  	Client.Login(user2.Username, user2.Password)
  2145  	privateChannel = th.CreatePrivateChannel()
  2146  	_, resp = Client.AddChannelMember(privateChannel.Id, user.Id)
  2147  	CheckNoError(t, resp)
  2148  	Client.Logout()
  2149  
  2150  	Client.Login(user.Username, user.Password)
  2151  	_, resp = Client.AddChannelMember(privateChannel.Id, user3.Id)
  2152  	CheckForbiddenStatus(t, resp)
  2153  	Client.Logout()
  2154  
  2155  	th.MakeUserChannelAdmin(user, privateChannel)
  2156  	th.App.InvalidateAllCaches()
  2157  
  2158  	Client.Login(user.Username, user.Password)
  2159  	_, resp = Client.AddChannelMember(privateChannel.Id, user3.Id)
  2160  	CheckNoError(t, resp)
  2161  	Client.Logout()
  2162  
  2163  	// Set a channel to group-constrained
  2164  	privateChannel.GroupConstrained = model.NewBool(true)
  2165  	_, appErr := th.App.UpdateChannel(privateChannel)
  2166  	require.Nil(t, appErr)
  2167  
  2168  	// User is not in associated groups so shouldn't be allowed
  2169  	_, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, user.Id)
  2170  	CheckErrorMessage(t, resp, "api.channel.add_members.user_denied")
  2171  
  2172  	// Associate group to team
  2173  	_, appErr = th.App.CreateGroupSyncable(&model.GroupSyncable{
  2174  		GroupId:    th.Group.Id,
  2175  		SyncableId: privateChannel.Id,
  2176  		Type:       model.GroupSyncableTypeChannel,
  2177  	})
  2178  	require.Nil(t, appErr)
  2179  
  2180  	// Add user to group
  2181  	_, appErr = th.App.UpsertGroupMember(th.Group.Id, user.Id)
  2182  	require.Nil(t, appErr)
  2183  
  2184  	_, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, user.Id)
  2185  	CheckNoError(t, resp)
  2186  }
  2187  
  2188  func TestAddChannelMemberAddMyself(t *testing.T) {
  2189  	th := Setup().InitBasic()
  2190  	defer th.TearDown()
  2191  	Client := th.Client
  2192  	user := th.CreateUser()
  2193  	th.LinkUserToTeam(user, th.BasicTeam)
  2194  	notMemberPublicChannel1 := th.CreatePublicChannel()
  2195  	notMemberPublicChannel2 := th.CreatePublicChannel()
  2196  	notMemberPrivateChannel := th.CreatePrivateChannel()
  2197  
  2198  	memberPublicChannel := th.CreatePublicChannel()
  2199  	memberPrivateChannel := th.CreatePrivateChannel()
  2200  	th.AddUserToChannel(user, memberPublicChannel)
  2201  	th.AddUserToChannel(user, memberPrivateChannel)
  2202  
  2203  	testCases := []struct {
  2204  		Name                     string
  2205  		Channel                  *model.Channel
  2206  		WithJoinPublicPermission bool
  2207  		ExpectedError            string
  2208  	}{
  2209  		{
  2210  			"Add myself to a public channel with JOIN_PUBLIC_CHANNEL permission",
  2211  			notMemberPublicChannel1,
  2212  			true,
  2213  			"",
  2214  		},
  2215  		{
  2216  			"Try to add myself to a private channel with the JOIN_PUBLIC_CHANNEL permission",
  2217  			notMemberPrivateChannel,
  2218  			true,
  2219  			"api.context.permissions.app_error",
  2220  		},
  2221  		{
  2222  			"Try to add myself to a public channel without the JOIN_PUBLIC_CHANNEL permission",
  2223  			notMemberPublicChannel2,
  2224  			false,
  2225  			"api.context.permissions.app_error",
  2226  		},
  2227  		{
  2228  			"Add myself a public channel where I'm already a member, not having JOIN_PUBLIC_CHANNEL or MANAGE MEMBERS permission",
  2229  			memberPublicChannel,
  2230  			false,
  2231  			"",
  2232  		},
  2233  		{
  2234  			"Add myself a private channel where I'm already a member, not having JOIN_PUBLIC_CHANNEL or MANAGE MEMBERS permission",
  2235  			memberPrivateChannel,
  2236  			false,
  2237  			"",
  2238  		},
  2239  	}
  2240  	Client.Login(user.Email, user.Password)
  2241  	for _, tc := range testCases {
  2242  		t.Run(tc.Name, func(t *testing.T) {
  2243  
  2244  			// Check the appropriate permissions are enforced.
  2245  			defaultRolePermissions := th.SaveDefaultRolePermissions()
  2246  			defer func() {
  2247  				th.RestoreDefaultRolePermissions(defaultRolePermissions)
  2248  			}()
  2249  
  2250  			if !tc.WithJoinPublicPermission {
  2251  				th.RemovePermissionFromRole(model.PERMISSION_JOIN_PUBLIC_CHANNELS.Id, model.TEAM_USER_ROLE_ID)
  2252  			}
  2253  
  2254  			_, resp := Client.AddChannelMember(tc.Channel.Id, user.Id)
  2255  			if tc.ExpectedError == "" {
  2256  				CheckNoError(t, resp)
  2257  			} else {
  2258  				CheckErrorMessage(t, resp, tc.ExpectedError)
  2259  			}
  2260  		})
  2261  	}
  2262  }
  2263  
  2264  func TestRemoveChannelMember(t *testing.T) {
  2265  	th := Setup().InitBasic()
  2266  	user1 := th.BasicUser
  2267  	user2 := th.BasicUser2
  2268  	team := th.BasicTeam
  2269  	defer th.TearDown()
  2270  	Client := th.Client
  2271  
  2272  	pass, resp := Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser2.Id)
  2273  	CheckNoError(t, resp)
  2274  
  2275  	if !pass {
  2276  		t.Fatal("should have passed")
  2277  	}
  2278  
  2279  	_, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, "junk")
  2280  	CheckBadRequestStatus(t, resp)
  2281  
  2282  	_, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, model.NewId())
  2283  	CheckNotFoundStatus(t, resp)
  2284  
  2285  	_, resp = Client.RemoveUserFromChannel(model.NewId(), th.BasicUser2.Id)
  2286  	CheckNotFoundStatus(t, resp)
  2287  
  2288  	th.LoginBasic2()
  2289  	_, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
  2290  	CheckForbiddenStatus(t, resp)
  2291  
  2292  	th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel)
  2293  	_, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser2.Id)
  2294  	CheckNoError(t, resp)
  2295  
  2296  	_, resp = Client.RemoveUserFromChannel(th.BasicChannel2.Id, th.BasicUser.Id)
  2297  	CheckNoError(t, resp)
  2298  
  2299  	_, resp = th.SystemAdminClient.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
  2300  	CheckNoError(t, resp)
  2301  
  2302  	// Leave deleted channel
  2303  	th.LoginBasic()
  2304  	deletedChannel := th.CreatePublicChannel()
  2305  	th.App.AddUserToChannel(th.BasicUser, deletedChannel)
  2306  	th.App.AddUserToChannel(th.BasicUser2, deletedChannel)
  2307  
  2308  	deletedChannel.DeleteAt = 1
  2309  	th.App.UpdateChannel(deletedChannel)
  2310  
  2311  	_, resp = Client.RemoveUserFromChannel(deletedChannel.Id, th.BasicUser.Id)
  2312  	CheckNoError(t, resp)
  2313  
  2314  	th.LoginBasic()
  2315  	private := th.CreatePrivateChannel()
  2316  	th.App.AddUserToChannel(th.BasicUser2, private)
  2317  
  2318  	_, resp = Client.RemoveUserFromChannel(private.Id, th.BasicUser2.Id)
  2319  	CheckNoError(t, resp)
  2320  
  2321  	th.LoginBasic2()
  2322  	_, resp = Client.RemoveUserFromChannel(private.Id, th.BasicUser.Id)
  2323  	CheckForbiddenStatus(t, resp)
  2324  
  2325  	_, resp = th.SystemAdminClient.RemoveUserFromChannel(private.Id, th.BasicUser.Id)
  2326  	CheckNoError(t, resp)
  2327  
  2328  	th.LoginBasic()
  2329  	th.UpdateUserToNonTeamAdmin(user1, team)
  2330  	th.App.InvalidateAllCaches()
  2331  
  2332  	// Check the appropriate permissions are enforced.
  2333  	defaultRolePermissions := th.SaveDefaultRolePermissions()
  2334  	defer func() {
  2335  		th.RestoreDefaultRolePermissions(defaultRolePermissions)
  2336  	}()
  2337  
  2338  	th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID)
  2339  
  2340  	// Check that a regular channel user can remove other users.
  2341  	privateChannel := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE)
  2342  	_, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, user1.Id)
  2343  	CheckNoError(t, resp)
  2344  	_, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, user2.Id)
  2345  	CheckNoError(t, resp)
  2346  
  2347  	_, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id)
  2348  	CheckNoError(t, resp)
  2349  
  2350  	// Restrict the permission for adding users to Channel Admins
  2351  	th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_ADMIN_ROLE_ID)
  2352  	th.RemovePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID)
  2353  
  2354  	privateChannel = th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE)
  2355  	_, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, user1.Id)
  2356  	CheckNoError(t, resp)
  2357  	_, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, user2.Id)
  2358  	CheckNoError(t, resp)
  2359  
  2360  	_, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id)
  2361  	CheckForbiddenStatus(t, resp)
  2362  
  2363  	th.MakeUserChannelAdmin(user1, privateChannel)
  2364  	th.App.InvalidateAllCaches()
  2365  
  2366  	_, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id)
  2367  	CheckNoError(t, resp)
  2368  
  2369  	_, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, th.SystemAdminUser.Id)
  2370  	CheckNoError(t, resp)
  2371  
  2372  	// If the channel is group-constrained the user cannot be removed
  2373  	privateChannel.GroupConstrained = model.NewBool(true)
  2374  	_, err := th.App.UpdateChannel(privateChannel)
  2375  	require.Nil(t, err)
  2376  	_, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id)
  2377  	require.Equal(t, "api.channel.remove_member.group_constrained.app_error", resp.Error.Id)
  2378  
  2379  	// If the channel is group-constrained user can remove self
  2380  	_, resp = th.SystemAdminClient.RemoveUserFromChannel(privateChannel.Id, th.SystemAdminUser.Id)
  2381  	CheckNoError(t, resp)
  2382  
  2383  	// Test on preventing removal of user from a direct channel
  2384  	directChannel, resp := Client.CreateDirectChannel(user1.Id, user2.Id)
  2385  	CheckNoError(t, resp)
  2386  
  2387  	_, resp = Client.RemoveUserFromChannel(directChannel.Id, user1.Id)
  2388  	CheckBadRequestStatus(t, resp)
  2389  
  2390  	_, resp = Client.RemoveUserFromChannel(directChannel.Id, user2.Id)
  2391  	CheckBadRequestStatus(t, resp)
  2392  
  2393  	_, resp = th.SystemAdminClient.RemoveUserFromChannel(directChannel.Id, user1.Id)
  2394  	CheckBadRequestStatus(t, resp)
  2395  
  2396  	// Test on preventing removal of user from a group channel
  2397  	user3 := th.CreateUser()
  2398  	groupChannel, resp := Client.CreateGroupChannel([]string{user1.Id, user2.Id, user3.Id})
  2399  	CheckNoError(t, resp)
  2400  
  2401  	_, resp = Client.RemoveUserFromChannel(groupChannel.Id, user1.Id)
  2402  	CheckBadRequestStatus(t, resp)
  2403  
  2404  	_, resp = th.SystemAdminClient.RemoveUserFromChannel(groupChannel.Id, user1.Id)
  2405  	CheckBadRequestStatus(t, resp)
  2406  }
  2407  
  2408  func TestAutocompleteChannels(t *testing.T) {
  2409  	th := Setup().InitBasic()
  2410  	defer th.TearDown()
  2411  
  2412  	// A private channel to make sure private channels are not used
  2413  	utils.DisableDebugLogForTest()
  2414  	ptown, _ := th.Client.CreateChannel(&model.Channel{
  2415  		DisplayName: "Town",
  2416  		Name:        "town",
  2417  		Type:        model.CHANNEL_PRIVATE,
  2418  		TeamId:      th.BasicTeam.Id,
  2419  	})
  2420  	utils.EnableDebugLogForTest()
  2421  	defer func() {
  2422  		th.Client.DeleteChannel(ptown.Id)
  2423  	}()
  2424  
  2425  	for _, tc := range []struct {
  2426  		description      string
  2427  		teamId           string
  2428  		fragment         string
  2429  		expectedIncludes []string
  2430  		expectedExcludes []string
  2431  	}{
  2432  		{
  2433  			"Basic town-square",
  2434  			th.BasicTeam.Id,
  2435  			"town",
  2436  			[]string{"town-square"},
  2437  			[]string{"off-topic", "town"},
  2438  		},
  2439  		{
  2440  			"Basic off-topic",
  2441  			th.BasicTeam.Id,
  2442  			"off-to",
  2443  			[]string{"off-topic"},
  2444  			[]string{"town-square", "town"},
  2445  		},
  2446  		{
  2447  			"Basic town square and off topic",
  2448  			th.BasicTeam.Id,
  2449  			"to",
  2450  			[]string{"off-topic", "town-square"},
  2451  			[]string{"town"},
  2452  		},
  2453  	} {
  2454  		t.Run(tc.description, func(t *testing.T) {
  2455  			channels, resp := th.Client.AutocompleteChannelsForTeam(tc.teamId, tc.fragment)
  2456  			if resp.Error != nil {
  2457  				t.Fatal("Err: " + resp.Error.Error())
  2458  			}
  2459  			for _, expectedInclude := range tc.expectedIncludes {
  2460  				found := false
  2461  				for _, channel := range *channels {
  2462  					if channel.Name == expectedInclude {
  2463  						found = true
  2464  						break
  2465  					}
  2466  				}
  2467  				if !found {
  2468  					t.Fatal("Expected but didn't find channel: " + expectedInclude)
  2469  				}
  2470  			}
  2471  			for _, expectedExclude := range tc.expectedExcludes {
  2472  				for _, channel := range *channels {
  2473  					if channel.Name == expectedExclude {
  2474  						t.Fatal("Found channel we didn't want: " + expectedExclude)
  2475  					}
  2476  				}
  2477  			}
  2478  		})
  2479  	}
  2480  }
  2481  
  2482  func TestAutocompleteChannelsForSearch(t *testing.T) {
  2483  	th := Setup().InitBasic()
  2484  	defer th.TearDown()
  2485  
  2486  	th.LoginSystemAdminWithClient(th.SystemAdminClient)
  2487  	th.LoginBasicWithClient(th.Client)
  2488  
  2489  	u1 := th.CreateUserWithClient(th.SystemAdminClient)
  2490  	u2 := th.CreateUserWithClient(th.SystemAdminClient)
  2491  	u3 := th.CreateUserWithClient(th.SystemAdminClient)
  2492  	u4 := th.CreateUserWithClient(th.SystemAdminClient)
  2493  
  2494  	// A private channel to make sure private channels are not used
  2495  	utils.DisableDebugLogForTest()
  2496  	ptown, _ := th.SystemAdminClient.CreateChannel(&model.Channel{
  2497  		DisplayName: "Town",
  2498  		Name:        "town",
  2499  		Type:        model.CHANNEL_PRIVATE,
  2500  		TeamId:      th.BasicTeam.Id,
  2501  	})
  2502  	defer func() {
  2503  		th.Client.DeleteChannel(ptown.Id)
  2504  	}()
  2505  	mypriv, _ := th.Client.CreateChannel(&model.Channel{
  2506  		DisplayName: "My private town",
  2507  		Name:        "townpriv",
  2508  		Type:        model.CHANNEL_PRIVATE,
  2509  		TeamId:      th.BasicTeam.Id,
  2510  	})
  2511  	defer func() {
  2512  		th.Client.DeleteChannel(mypriv.Id)
  2513  	}()
  2514  	utils.EnableDebugLogForTest()
  2515  
  2516  	dc1, resp := th.Client.CreateDirectChannel(th.BasicUser.Id, u1.Id)
  2517  	CheckNoError(t, resp)
  2518  	defer func() {
  2519  		th.Client.DeleteChannel(dc1.Id)
  2520  	}()
  2521  
  2522  	dc2, resp := th.SystemAdminClient.CreateDirectChannel(u2.Id, u3.Id)
  2523  	CheckNoError(t, resp)
  2524  	defer func() {
  2525  		th.SystemAdminClient.DeleteChannel(dc2.Id)
  2526  	}()
  2527  
  2528  	gc1, resp := th.Client.CreateGroupChannel([]string{th.BasicUser.Id, u2.Id, u3.Id})
  2529  	CheckNoError(t, resp)
  2530  	defer func() {
  2531  		th.Client.DeleteChannel(gc1.Id)
  2532  	}()
  2533  
  2534  	gc2, resp := th.SystemAdminClient.CreateGroupChannel([]string{u2.Id, u3.Id, u4.Id})
  2535  	CheckNoError(t, resp)
  2536  	defer func() {
  2537  		th.SystemAdminClient.DeleteChannel(gc2.Id)
  2538  	}()
  2539  
  2540  	for _, tc := range []struct {
  2541  		description      string
  2542  		teamId           string
  2543  		fragment         string
  2544  		expectedIncludes []string
  2545  		expectedExcludes []string
  2546  	}{
  2547  		{
  2548  			"Basic town-square",
  2549  			th.BasicTeam.Id,
  2550  			"town",
  2551  			[]string{"town-square", "townpriv"},
  2552  			[]string{"off-topic", "town"},
  2553  		},
  2554  		{
  2555  			"Basic off-topic",
  2556  			th.BasicTeam.Id,
  2557  			"off-to",
  2558  			[]string{"off-topic"},
  2559  			[]string{"town-square", "town", "townpriv"},
  2560  		},
  2561  		{
  2562  			"Basic town square and off topic",
  2563  			th.BasicTeam.Id,
  2564  			"to",
  2565  			[]string{"off-topic", "town-square", "townpriv"},
  2566  			[]string{"town"},
  2567  		},
  2568  		{
  2569  			"Direct and group messages",
  2570  			th.BasicTeam.Id,
  2571  			"fakeuser",
  2572  			[]string{dc1.Name, gc1.Name},
  2573  			[]string{dc2.Name, gc2.Name},
  2574  		},
  2575  	} {
  2576  		t.Run(tc.description, func(t *testing.T) {
  2577  			channels, resp := th.Client.AutocompleteChannelsForTeamForSearch(tc.teamId, tc.fragment)
  2578  			if resp.Error != nil {
  2579  				t.Fatal("Err: " + resp.Error.Error())
  2580  			}
  2581  			for _, expectedInclude := range tc.expectedIncludes {
  2582  				found := false
  2583  				for _, channel := range *channels {
  2584  					if channel.Name == expectedInclude {
  2585  						found = true
  2586  						break
  2587  					}
  2588  				}
  2589  				if !found {
  2590  					t.Fatal("Expected but didn't find channel: " + expectedInclude + " Channels: " + fmt.Sprintf("%v", channels))
  2591  				}
  2592  			}
  2593  
  2594  			for _, expectedExclude := range tc.expectedExcludes {
  2595  				for _, channel := range *channels {
  2596  					if channel.Name == expectedExclude {
  2597  						t.Fatal("Found channel we didn't want: " + expectedExclude)
  2598  					}
  2599  				}
  2600  			}
  2601  		})
  2602  	}
  2603  }
  2604  
  2605  func TestUpdateChannelScheme(t *testing.T) {
  2606  	th := Setup().InitBasic()
  2607  	defer th.TearDown()
  2608  
  2609  	th.App.SetLicense(model.NewTestLicense(""))
  2610  
  2611  	th.App.SetPhase2PermissionsMigrationStatus(true)
  2612  
  2613  	team, resp := th.SystemAdminClient.CreateTeam(&model.Team{
  2614  		DisplayName:     "Name",
  2615  		Description:     "Some description",
  2616  		CompanyName:     "Some company name",
  2617  		AllowOpenInvite: false,
  2618  		InviteId:        "inviteid0",
  2619  		Name:            "z-z-" + model.NewId() + "a",
  2620  		Email:           "success+" + model.NewId() + "@simulator.amazonses.com",
  2621  		Type:            model.TEAM_OPEN,
  2622  	})
  2623  	CheckNoError(t, resp)
  2624  
  2625  	channel, resp := th.SystemAdminClient.CreateChannel(&model.Channel{
  2626  		DisplayName: "Name",
  2627  		Name:        "z-z-" + model.NewId() + "a",
  2628  		Type:        model.CHANNEL_OPEN,
  2629  		TeamId:      team.Id,
  2630  	})
  2631  	CheckNoError(t, resp)
  2632  
  2633  	channelScheme, resp := th.SystemAdminClient.CreateScheme(&model.Scheme{
  2634  		DisplayName: "DisplayName",
  2635  		Name:        model.NewId(),
  2636  		Description: "Some description",
  2637  		Scope:       model.SCHEME_SCOPE_CHANNEL,
  2638  	})
  2639  	CheckNoError(t, resp)
  2640  
  2641  	teamScheme, resp := th.SystemAdminClient.CreateScheme(&model.Scheme{
  2642  		DisplayName: "DisplayName",
  2643  		Name:        model.NewId(),
  2644  		Description: "Some description",
  2645  		Scope:       model.SCHEME_SCOPE_TEAM,
  2646  	})
  2647  	CheckNoError(t, resp)
  2648  
  2649  	// Test the setup/base case.
  2650  	_, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, channelScheme.Id)
  2651  	CheckNoError(t, resp)
  2652  
  2653  	// Test various invalid channel and scheme id combinations.
  2654  	_, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, "x")
  2655  	CheckBadRequestStatus(t, resp)
  2656  	_, resp = th.SystemAdminClient.UpdateChannelScheme("x", channelScheme.Id)
  2657  	CheckBadRequestStatus(t, resp)
  2658  	_, resp = th.SystemAdminClient.UpdateChannelScheme("x", "x")
  2659  	CheckBadRequestStatus(t, resp)
  2660  
  2661  	// Test that permissions are required.
  2662  	_, resp = th.Client.UpdateChannelScheme(channel.Id, channelScheme.Id)
  2663  	CheckForbiddenStatus(t, resp)
  2664  
  2665  	// Test that a license is requried.
  2666  	th.App.SetLicense(nil)
  2667  	_, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, channelScheme.Id)
  2668  	CheckNotImplementedStatus(t, resp)
  2669  	th.App.SetLicense(model.NewTestLicense(""))
  2670  
  2671  	// Test an invalid scheme scope.
  2672  	_, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, teamScheme.Id)
  2673  	CheckBadRequestStatus(t, resp)
  2674  
  2675  	// Test that an unauthenticated user gets rejected.
  2676  	th.SystemAdminClient.Logout()
  2677  	_, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, channelScheme.Id)
  2678  	CheckUnauthorizedStatus(t, resp)
  2679  }
  2680  
  2681  func TestGetChannelMembersTimezones(t *testing.T) {
  2682  	th := Setup().InitBasic()
  2683  	defer th.TearDown()
  2684  	Client := th.Client
  2685  
  2686  	user := th.BasicUser
  2687  	user.Timezone["useAutomaticTimezone"] = "false"
  2688  	user.Timezone["manualTimezone"] = "XOXO/BLABLA"
  2689  	_, resp := Client.UpdateUser(user)
  2690  	CheckNoError(t, resp)
  2691  
  2692  	user2 := th.BasicUser2
  2693  	user2.Timezone["automaticTimezone"] = "NoWhere/Island"
  2694  	_, resp = th.SystemAdminClient.UpdateUser(user2)
  2695  	CheckNoError(t, resp)
  2696  
  2697  	timezone, resp := Client.GetChannelMembersTimezones(th.BasicChannel.Id)
  2698  	CheckNoError(t, resp)
  2699  	if len(timezone) != 2 {
  2700  		t.Fatal("should return 2 timezones")
  2701  	}
  2702  
  2703  	//both users have same timezone
  2704  	user2.Timezone["automaticTimezone"] = "XOXO/BLABLA"
  2705  	_, resp = th.SystemAdminClient.UpdateUser(user2)
  2706  	CheckNoError(t, resp)
  2707  
  2708  	timezone, resp = Client.GetChannelMembersTimezones(th.BasicChannel.Id)
  2709  	CheckNoError(t, resp)
  2710  	if len(timezone) != 1 {
  2711  		t.Fatal("should return 1 timezone")
  2712  	}
  2713  
  2714  	//no timezone set should return empty
  2715  	user2.Timezone["automaticTimezone"] = ""
  2716  	_, resp = th.SystemAdminClient.UpdateUser(user2)
  2717  	CheckNoError(t, resp)
  2718  
  2719  	user.Timezone["manualTimezone"] = ""
  2720  	_, resp = Client.UpdateUser(user)
  2721  
  2722  	timezone, resp = Client.GetChannelMembersTimezones(th.BasicChannel.Id)
  2723  	CheckNoError(t, resp)
  2724  	if len(timezone) > 0 {
  2725  		t.Fatal("should return 0 timezone")
  2726  	}
  2727  
  2728  }
  2729  
  2730  func TestChannelMembersMinusGroupMembers(t *testing.T) {
  2731  	th := Setup().InitBasic()
  2732  	defer th.TearDown()
  2733  
  2734  	user1 := th.BasicUser
  2735  	user2 := th.BasicUser2
  2736  
  2737  	channel := th.CreatePrivateChannel()
  2738  
  2739  	_, err := th.App.AddChannelMember(user1.Id, channel, "", "")
  2740  	require.Nil(t, err)
  2741  	_, err = th.App.AddChannelMember(user2.Id, channel, "", "")
  2742  	require.Nil(t, err)
  2743  
  2744  	channel.GroupConstrained = model.NewBool(true)
  2745  	channel, err = th.App.UpdateChannel(channel)
  2746  	require.Nil(t, err)
  2747  
  2748  	group1 := th.CreateGroup()
  2749  	group2 := th.CreateGroup()
  2750  
  2751  	_, err = th.App.UpsertGroupMember(group1.Id, user1.Id)
  2752  	require.Nil(t, err)
  2753  	_, err = th.App.UpsertGroupMember(group2.Id, user2.Id)
  2754  	require.Nil(t, err)
  2755  
  2756  	// No permissions
  2757  	_, _, res := th.Client.ChannelMembersMinusGroupMembers(channel.Id, []string{group1.Id, group2.Id}, 0, 100, "")
  2758  	require.Equal(t, "api.context.permissions.app_error", res.Error.Id)
  2759  
  2760  	testCases := map[string]struct {
  2761  		groupIDs        []string
  2762  		page            int
  2763  		perPage         int
  2764  		length          int
  2765  		count           int
  2766  		otherAssertions func([]*model.UserWithGroups)
  2767  	}{
  2768  		"All groups, expect no users removed": {
  2769  			groupIDs: []string{group1.Id, group2.Id},
  2770  			page:     0,
  2771  			perPage:  100,
  2772  			length:   0,
  2773  			count:    0,
  2774  		},
  2775  		"Some nonexistent group, page 0": {
  2776  			groupIDs: []string{model.NewId()},
  2777  			page:     0,
  2778  			perPage:  1,
  2779  			length:   1,
  2780  			count:    2,
  2781  		},
  2782  		"Some nonexistent group, page 1": {
  2783  			groupIDs: []string{model.NewId()},
  2784  			page:     1,
  2785  			perPage:  1,
  2786  			length:   1,
  2787  			count:    2,
  2788  		},
  2789  		"One group, expect one user removed": {
  2790  			groupIDs: []string{group1.Id},
  2791  			page:     0,
  2792  			perPage:  100,
  2793  			length:   1,
  2794  			count:    1,
  2795  			otherAssertions: func(uwg []*model.UserWithGroups) {
  2796  				require.Equal(t, uwg[0].Id, user2.Id)
  2797  			},
  2798  		},
  2799  		"Other group, expect other user removed": {
  2800  			groupIDs: []string{group2.Id},
  2801  			page:     0,
  2802  			perPage:  100,
  2803  			length:   1,
  2804  			count:    1,
  2805  			otherAssertions: func(uwg []*model.UserWithGroups) {
  2806  				require.Equal(t, uwg[0].Id, user1.Id)
  2807  			},
  2808  		},
  2809  	}
  2810  
  2811  	for name, tc := range testCases {
  2812  		t.Run(name, func(t *testing.T) {
  2813  			uwg, count, res := th.SystemAdminClient.ChannelMembersMinusGroupMembers(channel.Id, tc.groupIDs, tc.page, tc.perPage, "")
  2814  			require.Nil(t, res.Error)
  2815  			require.Len(t, uwg, tc.length)
  2816  			require.Equal(t, tc.count, int(count))
  2817  			if tc.otherAssertions != nil {
  2818  				tc.otherAssertions(uwg)
  2819  			}
  2820  		})
  2821  	}
  2822  }