github.com/haalcala/mattermost-server-change-repo/v5@v5.33.2/app/channel_test.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See LICENSE.txt for license information. 3 4 package app 5 6 import ( 7 "context" 8 "fmt" 9 "net/http" 10 "sort" 11 "strings" 12 "sync" 13 "testing" 14 15 "github.com/stretchr/testify/assert" 16 "github.com/stretchr/testify/require" 17 18 "github.com/mattermost/mattermost-server/v5/model" 19 "github.com/mattermost/mattermost-server/v5/store/storetest/mocks" 20 ) 21 22 func TestPermanentDeleteChannel(t *testing.T) { 23 th := Setup(t).InitBasic() 24 defer th.TearDown() 25 26 th.App.UpdateConfig(func(cfg *model.Config) { 27 *cfg.ServiceSettings.EnableIncomingWebhooks = true 28 *cfg.ServiceSettings.EnableOutgoingWebhooks = true 29 }) 30 31 channel, err := th.App.CreateChannel(&model.Channel{DisplayName: "deletion-test", Name: "deletion-test", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) 32 require.NotNil(t, channel, "Channel shouldn't be nil") 33 require.Nil(t, err) 34 defer func() { 35 th.App.PermanentDeleteChannel(channel) 36 }() 37 38 incoming, err := th.App.CreateIncomingWebhookForChannel(th.BasicUser.Id, channel, &model.IncomingWebhook{ChannelId: channel.Id}) 39 require.NotNil(t, incoming, "incoming webhook should not be nil") 40 require.Nil(t, err, "Unable to create Incoming Webhook for Channel") 41 defer th.App.DeleteIncomingWebhook(incoming.Id) 42 43 incoming, err = th.App.GetIncomingWebhook(incoming.Id) 44 require.NotNil(t, incoming, "incoming webhook should not be nil") 45 require.Nil(t, err, "Unable to get new incoming webhook") 46 47 outgoing, err := th.App.CreateOutgoingWebhook(&model.OutgoingWebhook{ 48 ChannelId: channel.Id, 49 TeamId: channel.TeamId, 50 CreatorId: th.BasicUser.Id, 51 CallbackURLs: []string{"http://foo"}, 52 }) 53 require.Nil(t, err) 54 defer th.App.DeleteOutgoingWebhook(outgoing.Id) 55 56 outgoing, err = th.App.GetOutgoingWebhook(outgoing.Id) 57 require.NotNil(t, outgoing, "Outgoing webhook should not be nil") 58 require.Nil(t, err, "Unable to get new outgoing webhook") 59 60 err = th.App.PermanentDeleteChannel(channel) 61 require.Nil(t, err) 62 63 incoming, err = th.App.GetIncomingWebhook(incoming.Id) 64 require.Nil(t, incoming, "Incoming webhook should be nil") 65 require.NotNil(t, err, "Incoming webhook wasn't deleted") 66 67 outgoing, err = th.App.GetOutgoingWebhook(outgoing.Id) 68 require.Nil(t, outgoing, "Outgoing webhook should be nil") 69 require.NotNil(t, err, "Outgoing webhook wasn't deleted") 70 } 71 72 func TestRemoveAllDeactivatedMembersFromChannel(t *testing.T) { 73 th := Setup(t).InitBasic() 74 defer th.TearDown() 75 var err *model.AppError 76 77 team := th.CreateTeam() 78 channel := th.CreateChannel(team) 79 defer func() { 80 th.App.PermanentDeleteChannel(channel) 81 th.App.PermanentDeleteTeam(team) 82 }() 83 84 _, err = th.App.AddUserToTeam(team.Id, th.BasicUser.Id, "") 85 require.Nil(t, err) 86 87 deacivatedUser := th.CreateUser() 88 _, err = th.App.AddUserToTeam(team.Id, deacivatedUser.Id, "") 89 require.Nil(t, err) 90 _, err = th.App.AddUserToChannel(deacivatedUser, channel) 91 require.Nil(t, err) 92 channelMembers, err := th.App.GetChannelMembersPage(channel.Id, 0, 10000000) 93 require.Nil(t, err) 94 require.Len(t, *channelMembers, 2) 95 _, err = th.App.UpdateActive(deacivatedUser, false) 96 require.Nil(t, err) 97 98 err = th.App.RemoveAllDeactivatedMembersFromChannel(channel) 99 require.Nil(t, err) 100 101 channelMembers, err = th.App.GetChannelMembersPage(channel.Id, 0, 10000000) 102 require.Nil(t, err) 103 require.Len(t, *channelMembers, 1) 104 } 105 106 func TestMoveChannel(t *testing.T) { 107 t.Run("should move channels between teams", func(t *testing.T) { 108 th := Setup(t).InitBasic() 109 defer th.TearDown() 110 var err *model.AppError 111 112 sourceTeam := th.CreateTeam() 113 targetTeam := th.CreateTeam() 114 channel1 := th.CreateChannel(sourceTeam) 115 defer func() { 116 th.App.PermanentDeleteChannel(channel1) 117 th.App.PermanentDeleteTeam(sourceTeam) 118 th.App.PermanentDeleteTeam(targetTeam) 119 }() 120 121 _, err = th.App.AddUserToTeam(sourceTeam.Id, th.BasicUser.Id, "") 122 require.Nil(t, err) 123 124 _, err = th.App.AddUserToTeam(sourceTeam.Id, th.BasicUser2.Id, "") 125 require.Nil(t, err) 126 127 _, err = th.App.AddUserToTeam(targetTeam.Id, th.BasicUser.Id, "") 128 require.Nil(t, err) 129 130 _, err = th.App.AddUserToChannel(th.BasicUser, channel1) 131 require.Nil(t, err) 132 133 _, err = th.App.AddUserToChannel(th.BasicUser2, channel1) 134 require.Nil(t, err) 135 136 err = th.App.MoveChannel(targetTeam, channel1, th.BasicUser) 137 require.NotNil(t, err, "Should have failed due to mismatched members.") 138 139 _, err = th.App.AddUserToTeam(targetTeam.Id, th.BasicUser2.Id, "") 140 require.Nil(t, err) 141 142 err = th.App.MoveChannel(targetTeam, channel1, th.BasicUser) 143 require.Nil(t, err) 144 145 // Test moving a channel with a deactivated user who isn't in the destination team. 146 // It should fail, unless removeDeactivatedMembers is true. 147 deacivatedUser := th.CreateUser() 148 channel2 := th.CreateChannel(sourceTeam) 149 defer th.App.PermanentDeleteChannel(channel2) 150 151 _, err = th.App.AddUserToTeam(sourceTeam.Id, deacivatedUser.Id, "") 152 require.Nil(t, err) 153 _, err = th.App.AddUserToChannel(th.BasicUser, channel2) 154 require.Nil(t, err) 155 156 _, err = th.App.AddUserToChannel(deacivatedUser, channel2) 157 require.Nil(t, err) 158 159 _, err = th.App.UpdateActive(deacivatedUser, false) 160 require.Nil(t, err) 161 162 err = th.App.MoveChannel(targetTeam, channel2, th.BasicUser) 163 require.NotNil(t, err, "Should have failed due to mismatched deacivated member.") 164 165 // Test moving a channel with no members. 166 channel3 := &model.Channel{ 167 DisplayName: "dn_" + model.NewId(), 168 Name: "name_" + model.NewId(), 169 Type: model.CHANNEL_OPEN, 170 TeamId: sourceTeam.Id, 171 CreatorId: th.BasicUser.Id, 172 } 173 174 channel3, err = th.App.CreateChannel(channel3, false) 175 require.Nil(t, err) 176 defer th.App.PermanentDeleteChannel(channel3) 177 178 err = th.App.MoveChannel(targetTeam, channel3, th.BasicUser) 179 assert.Nil(t, err) 180 }) 181 182 t.Run("should remove sidebar entries when moving channels from one team to another", func(t *testing.T) { 183 th := Setup(t).InitBasic() 184 defer th.TearDown() 185 186 sourceTeam := th.CreateTeam() 187 targetTeam := th.CreateTeam() 188 channel := th.CreateChannel(sourceTeam) 189 190 th.LinkUserToTeam(th.BasicUser, sourceTeam) 191 th.LinkUserToTeam(th.BasicUser, targetTeam) 192 th.AddUserToChannel(th.BasicUser, channel) 193 194 // Put the channel in a custom category so that it explicitly exists in SidebarChannels 195 category, err := th.App.CreateSidebarCategory(th.BasicUser.Id, sourceTeam.Id, &model.SidebarCategoryWithChannels{ 196 SidebarCategory: model.SidebarCategory{ 197 DisplayName: "new category", 198 }, 199 Channels: []string{channel.Id}, 200 }) 201 require.Nil(t, err) 202 require.Equal(t, []string{channel.Id}, category.Channels) 203 204 err = th.App.MoveChannel(targetTeam, channel, th.BasicUser) 205 require.Nil(t, err) 206 207 moved, err := th.App.GetChannel(channel.Id) 208 require.Nil(t, err) 209 require.Equal(t, targetTeam.Id, moved.TeamId) 210 211 // The channel should no longer be on the old team 212 updatedCategory, err := th.App.GetSidebarCategory(category.Id) 213 require.Nil(t, err) 214 assert.Equal(t, []string{}, updatedCategory.Channels) 215 216 // And it should be on the new team instead 217 categories, err := th.App.GetSidebarCategories(th.BasicUser.Id, targetTeam.Id) 218 require.Nil(t, err) 219 require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type) 220 assert.Contains(t, categories.Categories[1].Channels, channel.Id) 221 }) 222 } 223 224 func TestRemoveUsersFromChannelNotMemberOfTeam(t *testing.T) { 225 th := Setup(t).InitBasic() 226 defer th.TearDown() 227 228 team := th.CreateTeam() 229 team2 := th.CreateTeam() 230 channel1 := th.CreateChannel(team) 231 defer func() { 232 th.App.PermanentDeleteChannel(channel1) 233 th.App.PermanentDeleteTeam(team) 234 th.App.PermanentDeleteTeam(team2) 235 }() 236 237 _, err := th.App.AddUserToTeam(team.Id, th.BasicUser.Id, "") 238 require.Nil(t, err) 239 _, err = th.App.AddUserToTeam(team2.Id, th.BasicUser.Id, "") 240 require.Nil(t, err) 241 _, err = th.App.AddUserToTeam(team.Id, th.BasicUser2.Id, "") 242 require.Nil(t, err) 243 244 _, err = th.App.AddUserToChannel(th.BasicUser, channel1) 245 require.Nil(t, err) 246 _, err = th.App.AddUserToChannel(th.BasicUser2, channel1) 247 require.Nil(t, err) 248 249 err = th.App.RemoveUsersFromChannelNotMemberOfTeam(th.SystemAdminUser, channel1, team2) 250 require.Nil(t, err) 251 252 channelMembers, err := th.App.GetChannelMembersPage(channel1.Id, 0, 10000000) 253 require.Nil(t, err) 254 require.Len(t, *channelMembers, 1) 255 members := make([]model.ChannelMember, len(*channelMembers)) 256 for i, m := range *channelMembers { 257 members[i] = m 258 } 259 require.Equal(t, members[0].UserId, th.BasicUser.Id) 260 } 261 262 func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordTownSquare(t *testing.T) { 263 th := Setup(t).InitBasic() 264 defer th.TearDown() 265 266 // figure out the initial number of users in town square 267 channel, err := th.App.Srv().Store.Channel().GetByName(th.BasicTeam.Id, "town-square", true) 268 require.NoError(t, err) 269 townSquareChannelId := channel.Id 270 users, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId) 271 require.NoError(t, nErr) 272 initialNumTownSquareUsers := len(users) 273 274 // create a new user that joins the default channels 275 user := th.CreateUser() 276 th.App.JoinDefaultChannels(th.BasicTeam.Id, user, false, "") 277 278 // there should be a ChannelMemberHistory record for the user 279 histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId) 280 require.NoError(t, nErr) 281 assert.Len(t, histories, initialNumTownSquareUsers+1) 282 283 found := false 284 for _, history := range histories { 285 if user.Id == history.UserId && townSquareChannelId == history.ChannelId { 286 found = true 287 break 288 } 289 } 290 assert.True(t, found) 291 } 292 293 func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordOffTopic(t *testing.T) { 294 th := Setup(t).InitBasic() 295 defer th.TearDown() 296 297 // figure out the initial number of users in off-topic 298 channel, err := th.App.Srv().Store.Channel().GetByName(th.BasicTeam.Id, "off-topic", true) 299 require.NoError(t, err) 300 offTopicChannelId := channel.Id 301 users, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId) 302 require.NoError(t, nErr) 303 initialNumTownSquareUsers := len(users) 304 305 // create a new user that joins the default channels 306 user := th.CreateUser() 307 th.App.JoinDefaultChannels(th.BasicTeam.Id, user, false, "") 308 309 // there should be a ChannelMemberHistory record for the user 310 histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId) 311 require.NoError(t, nErr) 312 assert.Len(t, histories, initialNumTownSquareUsers+1) 313 314 found := false 315 for _, history := range histories { 316 if user.Id == history.UserId && offTopicChannelId == history.ChannelId { 317 found = true 318 break 319 } 320 } 321 assert.True(t, found) 322 } 323 324 func TestJoinDefaultChannelsExperimentalDefaultChannels(t *testing.T) { 325 th := Setup(t).InitBasic() 326 defer th.TearDown() 327 328 basicChannel2 := th.CreateChannel(th.BasicTeam) 329 defer th.App.PermanentDeleteChannel(basicChannel2) 330 defaultChannelList := []string{th.BasicChannel.Name, basicChannel2.Name, basicChannel2.Name} 331 th.App.Config().TeamSettings.ExperimentalDefaultChannels = defaultChannelList 332 333 user := th.CreateUser() 334 th.App.JoinDefaultChannels(th.BasicTeam.Id, user, false, "") 335 336 for _, channelName := range defaultChannelList { 337 channel, err := th.App.GetChannelByName(channelName, th.BasicTeam.Id, false) 338 require.Nil(t, err, "Expected nil, didn't receive nil") 339 340 member, err := th.App.GetChannelMember(channel.Id, user.Id) 341 342 require.NotNil(t, member, "Expected member object, got nil") 343 require.Nil(t, err, "Expected nil object, didn't receive nil") 344 } 345 } 346 347 func TestCreateChannelPublicCreatesChannelMemberHistoryRecord(t *testing.T) { 348 th := Setup(t).InitBasic() 349 defer th.TearDown() 350 351 // creates a public channel and adds basic user to it 352 publicChannel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN) 353 354 // there should be a ChannelMemberHistory record for the user 355 histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, publicChannel.Id) 356 require.NoError(t, err) 357 assert.Len(t, histories, 1) 358 assert.Equal(t, th.BasicUser.Id, histories[0].UserId) 359 assert.Equal(t, publicChannel.Id, histories[0].ChannelId) 360 } 361 362 func TestCreateChannelPrivateCreatesChannelMemberHistoryRecord(t *testing.T) { 363 th := Setup(t).InitBasic() 364 defer th.TearDown() 365 366 // creates a private channel and adds basic user to it 367 privateChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE) 368 369 // there should be a ChannelMemberHistory record for the user 370 histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, privateChannel.Id) 371 require.NoError(t, err) 372 assert.Len(t, histories, 1) 373 assert.Equal(t, th.BasicUser.Id, histories[0].UserId) 374 assert.Equal(t, privateChannel.Id, histories[0].ChannelId) 375 } 376 func TestCreateChannelDisplayNameTrimsWhitespace(t *testing.T) { 377 th := Setup(t).InitBasic() 378 defer th.TearDown() 379 380 channel, err := th.App.CreateChannel(&model.Channel{DisplayName: " Public 1 ", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) 381 defer th.App.PermanentDeleteChannel(channel) 382 require.Nil(t, err) 383 require.Equal(t, channel.DisplayName, "Public 1") 384 } 385 386 func TestUpdateChannelPrivacy(t *testing.T) { 387 th := Setup(t).InitBasic() 388 defer th.TearDown() 389 390 privateChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE) 391 privateChannel.Type = model.CHANNEL_OPEN 392 393 publicChannel, err := th.App.UpdateChannelPrivacy(privateChannel, th.BasicUser) 394 require.Nil(t, err, "Failed to update channel privacy.") 395 assert.Equal(t, publicChannel.Id, privateChannel.Id) 396 assert.Equal(t, publicChannel.Type, model.CHANNEL_OPEN) 397 } 398 399 func TestCreateGroupChannelCreatesChannelMemberHistoryRecord(t *testing.T) { 400 th := Setup(t).InitBasic() 401 defer th.TearDown() 402 403 user1 := th.CreateUser() 404 user2 := th.CreateUser() 405 406 groupUserIds := make([]string, 0) 407 groupUserIds = append(groupUserIds, user1.Id) 408 groupUserIds = append(groupUserIds, user2.Id) 409 groupUserIds = append(groupUserIds, th.BasicUser.Id) 410 411 channel, err := th.App.CreateGroupChannel(groupUserIds, th.BasicUser.Id) 412 413 require.Nil(t, err, "Failed to create group channel.") 414 histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) 415 require.NoError(t, nErr) 416 assert.Len(t, histories, 3) 417 418 channelMemberHistoryUserIds := make([]string, 0) 419 for _, history := range histories { 420 assert.Equal(t, channel.Id, history.ChannelId) 421 channelMemberHistoryUserIds = append(channelMemberHistoryUserIds, history.UserId) 422 } 423 424 sort.Strings(groupUserIds) 425 sort.Strings(channelMemberHistoryUserIds) 426 assert.Equal(t, groupUserIds, channelMemberHistoryUserIds) 427 } 428 429 func TestCreateDirectChannelCreatesChannelMemberHistoryRecord(t *testing.T) { 430 th := Setup(t) 431 defer th.TearDown() 432 433 user1 := th.CreateUser() 434 user2 := th.CreateUser() 435 436 channel, err := th.App.GetOrCreateDirectChannel(user1.Id, user2.Id) 437 require.Nil(t, err, "Failed to create direct channel.") 438 439 histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) 440 require.NoError(t, nErr) 441 assert.Len(t, histories, 2) 442 443 historyId0 := histories[0].UserId 444 historyId1 := histories[1].UserId 445 switch historyId0 { 446 case user1.Id: 447 assert.Equal(t, user2.Id, historyId1) 448 case user2.Id: 449 assert.Equal(t, user1.Id, historyId1) 450 default: 451 require.Fail(t, "Unexpected user id in ChannelMemberHistory table", historyId0) 452 } 453 } 454 455 func TestGetDirectChannelCreatesChannelMemberHistoryRecord(t *testing.T) { 456 th := Setup(t) 457 defer th.TearDown() 458 459 user1 := th.CreateUser() 460 user2 := th.CreateUser() 461 462 // this function call implicitly creates a direct channel between the two users if one doesn't already exist 463 channel, err := th.App.GetOrCreateDirectChannel(user1.Id, user2.Id) 464 require.Nil(t, err, "Failed to create direct channel.") 465 466 // there should be a ChannelMemberHistory record for both users 467 histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) 468 require.NoError(t, nErr) 469 assert.Len(t, histories, 2) 470 471 historyId0 := histories[0].UserId 472 historyId1 := histories[1].UserId 473 switch historyId0 { 474 case user1.Id: 475 assert.Equal(t, user2.Id, historyId1) 476 case user2.Id: 477 assert.Equal(t, user1.Id, historyId1) 478 default: 479 require.Fail(t, "Unexpected user id in ChannelMemberHistory table", historyId0) 480 } 481 } 482 483 func TestAddUserToChannelCreatesChannelMemberHistoryRecord(t *testing.T) { 484 th := Setup(t).InitBasic() 485 defer th.TearDown() 486 487 // create a user and add it to a channel 488 user := th.CreateUser() 489 _, err := th.App.AddTeamMember(th.BasicTeam.Id, user.Id) 490 require.Nil(t, err, "Failed to add user to team.") 491 492 groupUserIds := make([]string, 0) 493 groupUserIds = append(groupUserIds, th.BasicUser.Id) 494 groupUserIds = append(groupUserIds, user.Id) 495 496 channel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN) 497 498 _, err = th.App.AddUserToChannel(user, channel) 499 require.Nil(t, err, "Failed to add user to channel.") 500 501 // there should be a ChannelMemberHistory record for the user 502 histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) 503 require.NoError(t, nErr) 504 assert.Len(t, histories, 2) 505 channelMemberHistoryUserIds := make([]string, 0) 506 for _, history := range histories { 507 assert.Equal(t, channel.Id, history.ChannelId) 508 channelMemberHistoryUserIds = append(channelMemberHistoryUserIds, history.UserId) 509 } 510 assert.Equal(t, groupUserIds, channelMemberHistoryUserIds) 511 } 512 513 func TestLeaveDefaultChannel(t *testing.T) { 514 th := Setup(t).InitBasic() 515 defer th.TearDown() 516 517 guest := th.CreateGuest() 518 th.LinkUserToTeam(guest, th.BasicTeam) 519 520 townSquare, err := th.App.GetChannelByName("town-square", th.BasicTeam.Id, false) 521 require.Nil(t, err) 522 th.AddUserToChannel(guest, townSquare) 523 th.AddUserToChannel(th.BasicUser, townSquare) 524 525 t.Run("User tries to leave the default channel", func(t *testing.T) { 526 err = th.App.LeaveChannel(townSquare.Id, th.BasicUser.Id) 527 assert.NotNil(t, err, "It should fail to remove a regular user from the default channel") 528 assert.Equal(t, err.Id, "api.channel.remove.default.app_error") 529 _, err = th.App.GetChannelMember(townSquare.Id, th.BasicUser.Id) 530 assert.Nil(t, err) 531 }) 532 533 t.Run("Guest leaves the default channel", func(t *testing.T) { 534 err = th.App.LeaveChannel(townSquare.Id, guest.Id) 535 assert.Nil(t, err, "It should allow to remove a guest user from the default channel") 536 _, err = th.App.GetChannelMember(townSquare.Id, guest.Id) 537 assert.NotNil(t, err) 538 }) 539 } 540 541 func TestLeaveLastChannel(t *testing.T) { 542 th := Setup(t).InitBasic() 543 defer th.TearDown() 544 545 guest := th.CreateGuest() 546 th.LinkUserToTeam(guest, th.BasicTeam) 547 548 townSquare, err := th.App.GetChannelByName("town-square", th.BasicTeam.Id, false) 549 require.Nil(t, err) 550 th.AddUserToChannel(guest, townSquare) 551 th.AddUserToChannel(guest, th.BasicChannel) 552 553 t.Run("Guest leaves not last channel", func(t *testing.T) { 554 err = th.App.LeaveChannel(townSquare.Id, guest.Id) 555 require.Nil(t, err) 556 _, err = th.App.GetTeamMember(th.BasicTeam.Id, guest.Id) 557 assert.Nil(t, err, "It should maintain the team membership") 558 }) 559 560 t.Run("Guest leaves last channel", func(t *testing.T) { 561 err = th.App.LeaveChannel(th.BasicChannel.Id, guest.Id) 562 assert.Nil(t, err, "It should allow to remove a guest user from the default channel") 563 _, err = th.App.GetChannelMember(th.BasicChannel.Id, guest.Id) 564 assert.NotNil(t, err) 565 _, err = th.App.GetTeamMember(th.BasicTeam.Id, guest.Id) 566 assert.Nil(t, err, "It should remove the team membership") 567 }) 568 } 569 570 func TestAddChannelMemberNoUserRequestor(t *testing.T) { 571 th := Setup(t).InitBasic() 572 defer th.TearDown() 573 574 // create a user and add it to a channel 575 user := th.CreateUser() 576 _, err := th.App.AddTeamMember(th.BasicTeam.Id, user.Id) 577 require.Nil(t, err) 578 579 groupUserIds := make([]string, 0) 580 groupUserIds = append(groupUserIds, th.BasicUser.Id) 581 groupUserIds = append(groupUserIds, user.Id) 582 583 channel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN) 584 userRequestorId := "" 585 postRootId := "" 586 _, err = th.App.AddChannelMember(user.Id, channel, userRequestorId, postRootId) 587 require.Nil(t, err, "Failed to add user to channel.") 588 589 // there should be a ChannelMemberHistory record for the user 590 histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) 591 require.NoError(t, nErr) 592 assert.Len(t, histories, 2) 593 channelMemberHistoryUserIds := make([]string, 0) 594 for _, history := range histories { 595 assert.Equal(t, channel.Id, history.ChannelId) 596 channelMemberHistoryUserIds = append(channelMemberHistoryUserIds, history.UserId) 597 } 598 assert.Equal(t, groupUserIds, channelMemberHistoryUserIds) 599 600 postList, nErr := th.App.Srv().Store.Post().GetPosts(model.GetPostsOptions{ChannelId: channel.Id, Page: 0, PerPage: 1}, false) 601 require.NoError(t, nErr) 602 603 if assert.Len(t, postList.Order, 1) { 604 post := postList.Posts[postList.Order[0]] 605 606 assert.Equal(t, model.POST_JOIN_CHANNEL, post.Type) 607 assert.Equal(t, user.Id, post.UserId) 608 assert.Equal(t, user.Username, post.GetProp("username")) 609 } 610 } 611 612 func TestAppUpdateChannelScheme(t *testing.T) { 613 th := Setup(t).InitBasic() 614 defer th.TearDown() 615 616 channel := th.BasicChannel 617 mockID := model.NewString("x") 618 channel.SchemeId = mockID 619 620 updatedChannel, err := th.App.UpdateChannelScheme(channel) 621 require.Nil(t, err) 622 623 if updatedChannel.SchemeId != mockID { 624 require.Fail(t, "Wrong Channel SchemeId") 625 } 626 } 627 628 func TestSetChannelsMuted(t *testing.T) { 629 t.Run("should mute and unmute the given channels", func(t *testing.T) { 630 th := Setup(t).InitBasic() 631 defer th.TearDown() 632 633 channel1 := th.BasicChannel 634 635 channel2 := th.CreateChannel(th.BasicTeam) 636 th.AddUserToChannel(th.BasicUser, channel2) 637 638 // Ensure that both channels start unmuted 639 member1, err := th.App.GetChannelMember(channel1.Id, th.BasicUser.Id) 640 require.Nil(t, err) 641 require.False(t, member1.IsChannelMuted()) 642 643 member2, err := th.App.GetChannelMember(channel2.Id, th.BasicUser.Id) 644 require.Nil(t, err) 645 require.False(t, member2.IsChannelMuted()) 646 647 // Mute both channels 648 updated, err := th.App.setChannelsMuted([]string{channel1.Id, channel2.Id}, th.BasicUser.Id, true) 649 require.Nil(t, err) 650 assert.True(t, updated[0].IsChannelMuted()) 651 assert.True(t, updated[1].IsChannelMuted()) 652 653 // Verify that the channels are muted in the database 654 member1, err = th.App.GetChannelMember(channel1.Id, th.BasicUser.Id) 655 require.Nil(t, err) 656 require.True(t, member1.IsChannelMuted()) 657 658 member2, err = th.App.GetChannelMember(channel2.Id, th.BasicUser.Id) 659 require.Nil(t, err) 660 require.True(t, member2.IsChannelMuted()) 661 662 // Unm both channels 663 updated, err = th.App.setChannelsMuted([]string{channel1.Id, channel2.Id}, th.BasicUser.Id, false) 664 require.Nil(t, err) 665 assert.False(t, updated[0].IsChannelMuted()) 666 assert.False(t, updated[1].IsChannelMuted()) 667 668 // Verify that the channels are muted in the database 669 member1, err = th.App.GetChannelMember(channel1.Id, th.BasicUser.Id) 670 require.Nil(t, err) 671 require.False(t, member1.IsChannelMuted()) 672 673 member2, err = th.App.GetChannelMember(channel2.Id, th.BasicUser.Id) 674 require.Nil(t, err) 675 require.False(t, member2.IsChannelMuted()) 676 }) 677 } 678 679 func TestFillInChannelProps(t *testing.T) { 680 th := Setup(t).InitBasic() 681 defer th.TearDown() 682 683 channelPublic1, err := th.App.CreateChannel(&model.Channel{DisplayName: "Public 1", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) 684 require.Nil(t, err) 685 defer th.App.PermanentDeleteChannel(channelPublic1) 686 687 channelPublic2, err := th.App.CreateChannel(&model.Channel{DisplayName: "Public 2", Name: "public2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) 688 require.Nil(t, err) 689 defer th.App.PermanentDeleteChannel(channelPublic2) 690 691 channelPrivate, err := th.App.CreateChannel(&model.Channel{DisplayName: "Private", Name: "private", Type: model.CHANNEL_PRIVATE, TeamId: th.BasicTeam.Id}, false) 692 require.Nil(t, err) 693 defer th.App.PermanentDeleteChannel(channelPrivate) 694 695 otherTeamId := model.NewId() 696 otherTeam := &model.Team{ 697 DisplayName: "dn_" + otherTeamId, 698 Name: "name" + otherTeamId, 699 Email: "success+" + otherTeamId + "@simulator.amazonses.com", 700 Type: model.TEAM_OPEN, 701 } 702 otherTeam, err = th.App.CreateTeam(otherTeam) 703 require.Nil(t, err) 704 defer th.App.PermanentDeleteTeam(otherTeam) 705 706 channelOtherTeam, err := th.App.CreateChannel(&model.Channel{DisplayName: "Other Team Channel", Name: "other-team", Type: model.CHANNEL_OPEN, TeamId: otherTeam.Id}, false) 707 require.Nil(t, err) 708 defer th.App.PermanentDeleteChannel(channelOtherTeam) 709 710 // Note that purpose is intentionally plaintext below. 711 712 t.Run("single channels", func(t *testing.T) { 713 testCases := []struct { 714 Description string 715 Channel *model.Channel 716 ExpectedChannelProps map[string]interface{} 717 }{ 718 { 719 "channel on basic team without references", 720 &model.Channel{ 721 TeamId: th.BasicTeam.Id, 722 Header: "No references", 723 Purpose: "No references", 724 }, 725 nil, 726 }, 727 { 728 "channel on basic team", 729 &model.Channel{ 730 TeamId: th.BasicTeam.Id, 731 Header: "~public1, ~private, ~other-team", 732 Purpose: "~public2, ~private, ~other-team", 733 }, 734 map[string]interface{}{ 735 "channel_mentions": map[string]interface{}{ 736 "public1": map[string]interface{}{ 737 "display_name": "Public 1", 738 }, 739 }, 740 }, 741 }, 742 { 743 "channel on other team", 744 &model.Channel{ 745 TeamId: otherTeam.Id, 746 Header: "~public1, ~private, ~other-team", 747 Purpose: "~public2, ~private, ~other-team", 748 }, 749 map[string]interface{}{ 750 "channel_mentions": map[string]interface{}{ 751 "other-team": map[string]interface{}{ 752 "display_name": "Other Team Channel", 753 }, 754 }, 755 }, 756 }, 757 } 758 759 for _, testCase := range testCases { 760 t.Run(testCase.Description, func(t *testing.T) { 761 err = th.App.FillInChannelProps(testCase.Channel) 762 require.Nil(t, err) 763 764 assert.Equal(t, testCase.ExpectedChannelProps, testCase.Channel.Props) 765 }) 766 } 767 }) 768 769 t.Run("multiple channels", func(t *testing.T) { 770 testCases := []struct { 771 Description string 772 Channels *model.ChannelList 773 ExpectedChannelProps map[string]interface{} 774 }{ 775 { 776 "single channel on basic team", 777 &model.ChannelList{ 778 { 779 Name: "test", 780 TeamId: th.BasicTeam.Id, 781 Header: "~public1, ~private, ~other-team", 782 Purpose: "~public2, ~private, ~other-team", 783 }, 784 }, 785 map[string]interface{}{ 786 "test": map[string]interface{}{ 787 "channel_mentions": map[string]interface{}{ 788 "public1": map[string]interface{}{ 789 "display_name": "Public 1", 790 }, 791 }, 792 }, 793 }, 794 }, 795 { 796 "multiple channels on basic team", 797 &model.ChannelList{ 798 { 799 Name: "test", 800 TeamId: th.BasicTeam.Id, 801 Header: "~public1, ~private, ~other-team", 802 Purpose: "~public2, ~private, ~other-team", 803 }, 804 { 805 Name: "test2", 806 TeamId: th.BasicTeam.Id, 807 Header: "~private, ~other-team", 808 Purpose: "~public2, ~private, ~other-team", 809 }, 810 { 811 Name: "test3", 812 TeamId: th.BasicTeam.Id, 813 Header: "No references", 814 Purpose: "No references", 815 }, 816 }, 817 map[string]interface{}{ 818 "test": map[string]interface{}{ 819 "channel_mentions": map[string]interface{}{ 820 "public1": map[string]interface{}{ 821 "display_name": "Public 1", 822 }, 823 }, 824 }, 825 "test2": map[string]interface{}(nil), 826 "test3": map[string]interface{}(nil), 827 }, 828 }, 829 { 830 "multiple channels across teams", 831 &model.ChannelList{ 832 { 833 Name: "test", 834 TeamId: th.BasicTeam.Id, 835 Header: "~public1, ~private, ~other-team", 836 Purpose: "~public2, ~private, ~other-team", 837 }, 838 { 839 Name: "test2", 840 TeamId: otherTeam.Id, 841 Header: "~private, ~other-team", 842 Purpose: "~public2, ~private, ~other-team", 843 }, 844 { 845 Name: "test3", 846 TeamId: th.BasicTeam.Id, 847 Header: "No references", 848 Purpose: "No references", 849 }, 850 }, 851 map[string]interface{}{ 852 "test": map[string]interface{}{ 853 "channel_mentions": map[string]interface{}{ 854 "public1": map[string]interface{}{ 855 "display_name": "Public 1", 856 }, 857 }, 858 }, 859 "test2": map[string]interface{}{ 860 "channel_mentions": map[string]interface{}{ 861 "other-team": map[string]interface{}{ 862 "display_name": "Other Team Channel", 863 }, 864 }, 865 }, 866 "test3": map[string]interface{}(nil), 867 }, 868 }, 869 } 870 871 for _, testCase := range testCases { 872 t.Run(testCase.Description, func(t *testing.T) { 873 err = th.App.FillInChannelsProps(testCase.Channels) 874 require.Nil(t, err) 875 876 for _, channel := range *testCase.Channels { 877 assert.Equal(t, testCase.ExpectedChannelProps[channel.Name], channel.Props) 878 } 879 }) 880 } 881 }) 882 } 883 884 func TestRenameChannel(t *testing.T) { 885 th := Setup(t).InitBasic() 886 defer th.TearDown() 887 888 testCases := []struct { 889 Name string 890 Channel *model.Channel 891 ExpectError bool 892 ChannelName string 893 ExpectedName string 894 ExpectedDisplayName string 895 }{ 896 { 897 "Rename open channel", 898 th.createChannel(th.BasicTeam, model.CHANNEL_OPEN), 899 false, 900 "newchannelname", 901 "newchannelname", 902 "New Display Name", 903 }, 904 { 905 "Fail on rename open channel with bad name", 906 th.createChannel(th.BasicTeam, model.CHANNEL_OPEN), 907 true, 908 "6zii9a9g6pruzj451x3esok54h__wr4j4g8zqtnhmkw771pfpynqwo", 909 "", 910 "", 911 }, 912 { 913 "Success on rename open channel with consecutive underscores in name", 914 th.createChannel(th.BasicTeam, model.CHANNEL_OPEN), 915 false, 916 "foo__bar", 917 "foo__bar", 918 "New Display Name", 919 }, 920 { 921 "Fail on rename direct message channel", 922 th.CreateDmChannel(th.BasicUser2), 923 true, 924 "newchannelname", 925 "", 926 "", 927 }, 928 { 929 "Fail on rename group message channel", 930 th.CreateGroupChannel(th.BasicUser2, th.CreateUser()), 931 true, 932 "newchannelname", 933 "", 934 "", 935 }, 936 } 937 938 for _, tc := range testCases { 939 t.Run(tc.Name, func(t *testing.T) { 940 channel, err := th.App.RenameChannel(tc.Channel, tc.ChannelName, "New Display Name") 941 if tc.ExpectError { 942 assert.NotNil(t, err) 943 } else { 944 assert.Equal(t, tc.ExpectedName, channel.Name) 945 assert.Equal(t, tc.ExpectedDisplayName, channel.DisplayName) 946 } 947 }) 948 } 949 } 950 951 func TestGetChannelMembersTimezones(t *testing.T) { 952 th := Setup(t).InitBasic() 953 defer th.TearDown() 954 955 userRequestorId := "" 956 postRootId := "" 957 _, err := th.App.AddChannelMember(th.BasicUser2.Id, th.BasicChannel, userRequestorId, postRootId) 958 require.Nil(t, err, "Failed to add user to channel.") 959 960 user := th.BasicUser 961 user.Timezone["useAutomaticTimezone"] = "false" 962 user.Timezone["manualTimezone"] = "XOXO/BLABLA" 963 th.App.UpdateUser(user, false) 964 965 user2 := th.BasicUser2 966 user2.Timezone["automaticTimezone"] = "NoWhere/Island" 967 th.App.UpdateUser(user2, false) 968 969 user3 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} 970 ruser, _ := th.App.CreateUser(&user3) 971 th.App.AddUserToChannel(ruser, th.BasicChannel) 972 973 ruser.Timezone["automaticTimezone"] = "NoWhere/Island" 974 th.App.UpdateUser(ruser, false) 975 976 user4 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} 977 ruser, _ = th.App.CreateUser(&user4) 978 th.App.AddUserToChannel(ruser, th.BasicChannel) 979 980 timezones, err := th.App.GetChannelMembersTimezones(th.BasicChannel.Id) 981 require.Nil(t, err, "Failed to get the timezones for a channel.") 982 983 assert.Equal(t, 2, len(timezones)) 984 } 985 986 func TestGetChannelsForUser(t *testing.T) { 987 th := Setup(t).InitBasic() 988 channel := &model.Channel{ 989 DisplayName: "Public", 990 Name: "public", 991 Type: model.CHANNEL_OPEN, 992 CreatorId: th.BasicUser.Id, 993 TeamId: th.BasicTeam.Id, 994 } 995 th.App.CreateChannel(channel, true) 996 defer th.App.PermanentDeleteChannel(channel) 997 defer th.TearDown() 998 999 channelList, err := th.App.GetChannelsForUser(th.BasicTeam.Id, th.BasicUser.Id, false, 0) 1000 require.Nil(t, err) 1001 require.Len(t, *channelList, 4) 1002 1003 th.App.DeleteChannel(channel, th.BasicUser.Id) 1004 1005 // Now we get all the non-archived channels for the user 1006 channelList, err = th.App.GetChannelsForUser(th.BasicTeam.Id, th.BasicUser.Id, false, 0) 1007 require.Nil(t, err) 1008 require.Len(t, *channelList, 3) 1009 1010 // Now we get all the channels, even though are archived, for the user 1011 channelList, err = th.App.GetChannelsForUser(th.BasicTeam.Id, th.BasicUser.Id, true, 0) 1012 require.Nil(t, err) 1013 require.Len(t, *channelList, 4) 1014 } 1015 1016 func TestGetPublicChannelsForTeam(t *testing.T) { 1017 th := Setup(t) 1018 team := th.CreateTeam() 1019 defer th.TearDown() 1020 1021 var expectedChannels []*model.Channel 1022 1023 townSquare, err := th.App.GetChannelByName("town-square", team.Id, false) 1024 require.Nil(t, err) 1025 require.NotNil(t, townSquare) 1026 expectedChannels = append(expectedChannels, townSquare) 1027 1028 offTopic, err := th.App.GetChannelByName("off-topic", team.Id, false) 1029 require.Nil(t, err) 1030 require.NotNil(t, offTopic) 1031 expectedChannels = append(expectedChannels, offTopic) 1032 1033 for i := 0; i < 8; i++ { 1034 channel := model.Channel{ 1035 DisplayName: fmt.Sprintf("Public %v", i), 1036 Name: fmt.Sprintf("public_%v", i), 1037 Type: model.CHANNEL_OPEN, 1038 TeamId: team.Id, 1039 } 1040 var rchannel *model.Channel 1041 rchannel, err = th.App.CreateChannel(&channel, false) 1042 require.Nil(t, err) 1043 require.NotNil(t, rchannel) 1044 defer th.App.PermanentDeleteChannel(rchannel) 1045 1046 // Store the user ids for comparison later 1047 expectedChannels = append(expectedChannels, rchannel) 1048 } 1049 1050 // Fetch public channels multipile times 1051 channelList, err := th.App.GetPublicChannelsForTeam(team.Id, 0, 5) 1052 require.Nil(t, err) 1053 channelList2, err := th.App.GetPublicChannelsForTeam(team.Id, 5, 5) 1054 require.Nil(t, err) 1055 1056 channels := append(*channelList, *channelList2...) 1057 assert.ElementsMatch(t, expectedChannels, channels) 1058 } 1059 1060 func TestGetPrivateChannelsForTeam(t *testing.T) { 1061 th := Setup(t) 1062 team := th.CreateTeam() 1063 defer th.TearDown() 1064 1065 var expectedChannels []*model.Channel 1066 for i := 0; i < 8; i++ { 1067 channel := model.Channel{ 1068 DisplayName: fmt.Sprintf("Private %v", i), 1069 Name: fmt.Sprintf("private_%v", i), 1070 Type: model.CHANNEL_PRIVATE, 1071 TeamId: team.Id, 1072 } 1073 var rchannel *model.Channel 1074 rchannel, err := th.App.CreateChannel(&channel, false) 1075 require.Nil(t, err) 1076 require.NotNil(t, rchannel) 1077 defer th.App.PermanentDeleteChannel(rchannel) 1078 1079 // Store the user ids for comparison later 1080 expectedChannels = append(expectedChannels, rchannel) 1081 } 1082 1083 // Fetch private channels multipile times 1084 channelList, err := th.App.GetPrivateChannelsForTeam(team.Id, 0, 5) 1085 require.Nil(t, err) 1086 channelList2, err := th.App.GetPrivateChannelsForTeam(team.Id, 5, 5) 1087 require.Nil(t, err) 1088 1089 channels := append(*channelList, *channelList2...) 1090 assert.ElementsMatch(t, expectedChannels, channels) 1091 } 1092 1093 func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) { 1094 th := Setup(t).InitBasic() 1095 defer th.TearDown() 1096 1097 t.Run("from guest to user", func(t *testing.T) { 1098 user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} 1099 ruser, _ := th.App.CreateGuest(&user) 1100 1101 _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") 1102 require.Nil(t, err) 1103 1104 _, err = th.App.AddUserToChannel(ruser, th.BasicChannel) 1105 require.Nil(t, err) 1106 1107 _, err = th.App.UpdateChannelMemberRoles(th.BasicChannel.Id, ruser.Id, "channel_user") 1108 require.NotNil(t, err, "Should fail when try to modify the guest role") 1109 }) 1110 1111 t.Run("from user to guest", func(t *testing.T) { 1112 user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} 1113 ruser, _ := th.App.CreateUser(&user) 1114 1115 _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") 1116 require.Nil(t, err) 1117 1118 _, err = th.App.AddUserToChannel(ruser, th.BasicChannel) 1119 require.Nil(t, err) 1120 1121 _, err = th.App.UpdateChannelMemberRoles(th.BasicChannel.Id, ruser.Id, "channel_guest") 1122 require.NotNil(t, err, "Should fail when try to modify the guest role") 1123 }) 1124 1125 t.Run("from user to admin", func(t *testing.T) { 1126 user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} 1127 ruser, _ := th.App.CreateUser(&user) 1128 1129 _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") 1130 require.Nil(t, err) 1131 1132 _, err = th.App.AddUserToChannel(ruser, th.BasicChannel) 1133 require.Nil(t, err) 1134 1135 _, err = th.App.UpdateChannelMemberRoles(th.BasicChannel.Id, ruser.Id, "channel_user channel_admin") 1136 require.Nil(t, err, "Should work when you not modify guest role") 1137 }) 1138 1139 t.Run("from guest to guest plus custom", func(t *testing.T) { 1140 user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} 1141 ruser, _ := th.App.CreateGuest(&user) 1142 1143 _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") 1144 require.Nil(t, err) 1145 1146 _, err = th.App.AddUserToChannel(ruser, th.BasicChannel) 1147 require.Nil(t, err) 1148 1149 _, err = th.App.CreateRole(&model.Role{Name: "custom", DisplayName: "custom", Description: "custom"}) 1150 require.Nil(t, err) 1151 1152 _, err = th.App.UpdateChannelMemberRoles(th.BasicChannel.Id, ruser.Id, "channel_guest custom") 1153 require.Nil(t, err, "Should work when you not modify guest role") 1154 }) 1155 1156 t.Run("a guest cant have user role", func(t *testing.T) { 1157 user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} 1158 ruser, _ := th.App.CreateGuest(&user) 1159 1160 _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") 1161 require.Nil(t, err) 1162 1163 _, err = th.App.AddUserToChannel(ruser, th.BasicChannel) 1164 require.Nil(t, err) 1165 1166 _, err = th.App.UpdateChannelMemberRoles(th.BasicChannel.Id, ruser.Id, "channel_guest channel_user") 1167 require.NotNil(t, err, "Should work when you not modify guest role") 1168 }) 1169 } 1170 1171 func TestDefaultChannelNames(t *testing.T) { 1172 th := Setup(t) 1173 defer th.TearDown() 1174 1175 actual := th.App.DefaultChannelNames() 1176 expect := []string{"town-square", "off-topic"} 1177 require.ElementsMatch(t, expect, actual) 1178 1179 th.App.UpdateConfig(func(cfg *model.Config) { 1180 cfg.TeamSettings.ExperimentalDefaultChannels = []string{"foo", "bar"} 1181 }) 1182 1183 actual = th.App.DefaultChannelNames() 1184 expect = []string{"town-square", "foo", "bar"} 1185 require.ElementsMatch(t, expect, actual) 1186 } 1187 1188 func TestSearchChannelsForUser(t *testing.T) { 1189 th := Setup(t).InitBasic() 1190 defer th.TearDown() 1191 1192 c1, err := th.App.CreateChannel(&model.Channel{DisplayName: "test-dev-1", Name: "test-dev-1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) 1193 require.Nil(t, err) 1194 1195 c2, err := th.App.CreateChannel(&model.Channel{DisplayName: "test-dev-2", Name: "test-dev-2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) 1196 require.Nil(t, err) 1197 1198 c3, err := th.App.CreateChannel(&model.Channel{DisplayName: "dev-3", Name: "dev-3", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) 1199 require.Nil(t, err) 1200 1201 defer func() { 1202 th.App.PermanentDeleteChannel(c1) 1203 th.App.PermanentDeleteChannel(c2) 1204 th.App.PermanentDeleteChannel(c3) 1205 }() 1206 1207 // add user to test-dev-1 and dev3 1208 _, err = th.App.AddUserToChannel(th.BasicUser, c1) 1209 require.Nil(t, err) 1210 _, err = th.App.AddUserToChannel(th.BasicUser, c3) 1211 require.Nil(t, err) 1212 1213 searchAndCheck := func(t *testing.T, term string, expectedDisplayNames []string) { 1214 res, searchErr := th.App.SearchChannelsForUser(th.BasicUser.Id, th.BasicTeam.Id, term) 1215 require.Nil(t, searchErr) 1216 require.Len(t, *res, len(expectedDisplayNames)) 1217 1218 resultDisplayNames := []string{} 1219 for _, c := range *res { 1220 resultDisplayNames = append(resultDisplayNames, c.Name) 1221 } 1222 require.ElementsMatch(t, expectedDisplayNames, resultDisplayNames) 1223 } 1224 1225 t.Run("Search for test, only test-dev-1 should be returned", func(t *testing.T) { 1226 searchAndCheck(t, "test", []string{"test-dev-1"}) 1227 }) 1228 1229 t.Run("Search for dev, both test-dev-1 and dev-3 should be returned", func(t *testing.T) { 1230 searchAndCheck(t, "dev", []string{"test-dev-1", "dev-3"}) 1231 }) 1232 1233 t.Run("After adding user to test-dev-2, search for dev, the three channels should be returned", func(t *testing.T) { 1234 _, err = th.App.AddUserToChannel(th.BasicUser, c2) 1235 require.Nil(t, err) 1236 1237 searchAndCheck(t, "dev", []string{"test-dev-1", "test-dev-2", "dev-3"}) 1238 }) 1239 } 1240 1241 func TestMarkChannelAsUnreadFromPost(t *testing.T) { 1242 th := Setup(t).InitBasic() 1243 defer th.TearDown() 1244 1245 u1 := th.BasicUser 1246 u2 := th.BasicUser2 1247 c1 := th.BasicChannel 1248 pc1 := th.CreatePrivateChannel(th.BasicTeam) 1249 th.AddUserToChannel(u2, c1) 1250 th.AddUserToChannel(u1, pc1) 1251 th.AddUserToChannel(u2, pc1) 1252 1253 p1 := th.CreatePost(c1) 1254 p2 := th.CreatePost(c1) 1255 p3 := th.CreatePost(c1) 1256 1257 pp1 := th.CreatePost(pc1) 1258 require.NotNil(t, pp1) 1259 pp2 := th.CreatePost(pc1) 1260 1261 unread, err := th.App.GetChannelUnread(c1.Id, u1.Id) 1262 require.Nil(t, err) 1263 require.Equal(t, int64(4), unread.MsgCount) 1264 unread, err = th.App.GetChannelUnread(c1.Id, u2.Id) 1265 require.Nil(t, err) 1266 require.Equal(t, int64(4), unread.MsgCount) 1267 err = th.App.UpdateChannelLastViewedAt([]string{c1.Id, pc1.Id}, u1.Id) 1268 require.Nil(t, err) 1269 err = th.App.UpdateChannelLastViewedAt([]string{c1.Id, pc1.Id}, u2.Id) 1270 require.Nil(t, err) 1271 unread, err = th.App.GetChannelUnread(c1.Id, u2.Id) 1272 require.Nil(t, err) 1273 require.Equal(t, int64(0), unread.MsgCount) 1274 1275 t.Run("Unread but last one", func(t *testing.T) { 1276 response, err := th.App.MarkChannelAsUnreadFromPost(p2.Id, u1.Id) 1277 require.Nil(t, err) 1278 require.NotNil(t, response) 1279 assert.Equal(t, int64(2), response.MsgCount) 1280 unread, err := th.App.GetChannelUnread(c1.Id, u1.Id) 1281 require.Nil(t, err) 1282 assert.Equal(t, int64(2), unread.MsgCount) 1283 assert.Equal(t, p2.CreateAt-1, response.LastViewedAt) 1284 }) 1285 1286 t.Run("Unread last one", func(t *testing.T) { 1287 response, err := th.App.MarkChannelAsUnreadFromPost(p3.Id, u1.Id) 1288 require.Nil(t, err) 1289 require.NotNil(t, response) 1290 assert.Equal(t, int64(3), response.MsgCount) 1291 unread, err := th.App.GetChannelUnread(c1.Id, u1.Id) 1292 require.Nil(t, err) 1293 assert.Equal(t, int64(1), unread.MsgCount) 1294 assert.Equal(t, p3.CreateAt-1, response.LastViewedAt) 1295 }) 1296 1297 t.Run("Unread first one", func(t *testing.T) { 1298 response, err := th.App.MarkChannelAsUnreadFromPost(p1.Id, u1.Id) 1299 require.Nil(t, err) 1300 require.NotNil(t, response) 1301 assert.Equal(t, int64(1), response.MsgCount) 1302 unread, err := th.App.GetChannelUnread(c1.Id, u1.Id) 1303 require.Nil(t, err) 1304 assert.Equal(t, int64(3), unread.MsgCount) 1305 assert.Equal(t, p1.CreateAt-1, response.LastViewedAt) 1306 }) 1307 1308 t.Run("Other users are unaffected", func(t *testing.T) { 1309 unread, err := th.App.GetChannelUnread(c1.Id, u2.Id) 1310 require.Nil(t, err) 1311 assert.Equal(t, int64(0), unread.MsgCount) 1312 }) 1313 1314 t.Run("Unread on a private channel", func(t *testing.T) { 1315 response, err := th.App.MarkChannelAsUnreadFromPost(pp1.Id, u1.Id) 1316 require.Nil(t, err) 1317 require.NotNil(t, response) 1318 assert.Equal(t, int64(0), response.MsgCount) 1319 unread, err := th.App.GetChannelUnread(pc1.Id, u1.Id) 1320 require.Nil(t, err) 1321 assert.Equal(t, int64(2), unread.MsgCount) 1322 assert.Equal(t, pp1.CreateAt-1, response.LastViewedAt) 1323 1324 response, err = th.App.MarkChannelAsUnreadFromPost(pp2.Id, u1.Id) 1325 assert.Nil(t, err) 1326 assert.Equal(t, int64(1), response.MsgCount) 1327 unread, err = th.App.GetChannelUnread(pc1.Id, u1.Id) 1328 require.Nil(t, err) 1329 assert.Equal(t, int64(1), unread.MsgCount) 1330 assert.Equal(t, pp2.CreateAt-1, response.LastViewedAt) 1331 }) 1332 1333 t.Run("Unread with mentions", func(t *testing.T) { 1334 c2 := th.CreateChannel(th.BasicTeam) 1335 _, err := th.App.AddUserToChannel(u2, c2) 1336 require.Nil(t, err) 1337 1338 p4, err := th.App.CreatePost(&model.Post{ 1339 UserId: u2.Id, 1340 ChannelId: c2.Id, 1341 Message: "@" + u1.Username, 1342 }, c2, false, true) 1343 require.Nil(t, err) 1344 th.CreatePost(c2) 1345 1346 response, err := th.App.MarkChannelAsUnreadFromPost(p4.Id, u1.Id) 1347 assert.Nil(t, err) 1348 assert.Equal(t, int64(1), response.MsgCount) 1349 assert.Equal(t, int64(1), response.MentionCount) 1350 1351 unread, err := th.App.GetChannelUnread(c2.Id, u1.Id) 1352 require.Nil(t, err) 1353 assert.Equal(t, int64(1), unread.MsgCount) 1354 assert.Equal(t, int64(1), unread.MentionCount) 1355 }) 1356 1357 t.Run("Unread on a DM channel", func(t *testing.T) { 1358 dc := th.CreateDmChannel(u2) 1359 1360 dm1 := th.CreatePost(dc) 1361 th.CreatePost(dc) 1362 th.CreatePost(dc) 1363 1364 response, err := th.App.MarkChannelAsUnreadFromPost(dm1.Id, u2.Id) 1365 assert.Nil(t, err) 1366 assert.Equal(t, int64(0), response.MsgCount) 1367 assert.Equal(t, int64(3), response.MentionCount) 1368 1369 unread, err := th.App.GetChannelUnread(dc.Id, u2.Id) 1370 require.Nil(t, err) 1371 assert.Equal(t, int64(3), unread.MsgCount) 1372 assert.Equal(t, int64(3), unread.MentionCount) 1373 }) 1374 1375 t.Run("Can't unread an imaginary post", func(t *testing.T) { 1376 response, err := th.App.MarkChannelAsUnreadFromPost("invalid4ofngungryquinj976y", u1.Id) 1377 assert.NotNil(t, err) 1378 assert.Nil(t, response) 1379 }) 1380 } 1381 1382 func TestAddUserToChannel(t *testing.T) { 1383 th := Setup(t).InitBasic() 1384 defer th.TearDown() 1385 1386 user1 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} 1387 ruser1, _ := th.App.CreateUser(&user1) 1388 defer th.App.PermanentDeleteUser(&user1) 1389 bot := th.CreateBot() 1390 botUser, _ := th.App.GetUser(bot.UserId) 1391 defer th.App.PermanentDeleteBot(botUser.Id) 1392 1393 th.App.AddTeamMember(th.BasicTeam.Id, ruser1.Id) 1394 th.App.AddTeamMember(th.BasicTeam.Id, bot.UserId) 1395 1396 group := th.CreateGroup() 1397 1398 _, err := th.App.UpsertGroupMember(group.Id, user1.Id) 1399 require.Nil(t, err) 1400 1401 gs, err := th.App.UpsertGroupSyncable(&model.GroupSyncable{ 1402 AutoAdd: true, 1403 SyncableId: th.BasicChannel.Id, 1404 Type: model.GroupSyncableTypeChannel, 1405 GroupId: group.Id, 1406 SchemeAdmin: false, 1407 }) 1408 require.Nil(t, err) 1409 1410 err = th.App.JoinChannel(th.BasicChannel, ruser1.Id) 1411 require.Nil(t, err) 1412 1413 // verify user was added as a non-admin 1414 cm1, err := th.App.GetChannelMember(th.BasicChannel.Id, ruser1.Id) 1415 require.Nil(t, err) 1416 require.False(t, cm1.SchemeAdmin) 1417 1418 user2 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} 1419 ruser2, _ := th.App.CreateUser(&user2) 1420 defer th.App.PermanentDeleteUser(&user2) 1421 th.App.AddTeamMember(th.BasicTeam.Id, ruser2.Id) 1422 1423 _, err = th.App.UpsertGroupMember(group.Id, user2.Id) 1424 require.Nil(t, err) 1425 1426 gs.SchemeAdmin = true 1427 _, err = th.App.UpdateGroupSyncable(gs) 1428 require.Nil(t, err) 1429 1430 err = th.App.JoinChannel(th.BasicChannel, ruser2.Id) 1431 require.Nil(t, err) 1432 1433 // Should allow a bot to be added to a public group synced channel 1434 _, err = th.App.AddUserToChannel(botUser, th.BasicChannel) 1435 require.Nil(t, err) 1436 1437 // verify user was added as an admin 1438 cm2, err := th.App.GetChannelMember(th.BasicChannel.Id, ruser2.Id) 1439 require.Nil(t, err) 1440 require.True(t, cm2.SchemeAdmin) 1441 1442 privateChannel := th.CreatePrivateChannel(th.BasicTeam) 1443 privateChannel.GroupConstrained = model.NewBool(true) 1444 _, err = th.App.UpdateChannel(privateChannel) 1445 require.Nil(t, err) 1446 1447 _, err = th.App.UpsertGroupSyncable(&model.GroupSyncable{ 1448 GroupId: group.Id, 1449 SyncableId: privateChannel.Id, 1450 Type: model.GroupSyncableTypeChannel, 1451 }) 1452 require.Nil(t, err) 1453 1454 // Should allow a group synced user to be added to a group synced private channel 1455 _, err = th.App.AddUserToChannel(ruser1, privateChannel) 1456 require.Nil(t, err) 1457 1458 // Should allow a bot to be added to a private group synced channel 1459 _, err = th.App.AddUserToChannel(botUser, privateChannel) 1460 require.Nil(t, err) 1461 } 1462 1463 func TestRemoveUserFromChannel(t *testing.T) { 1464 th := Setup(t).InitBasic() 1465 defer th.TearDown() 1466 1467 user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} 1468 ruser, _ := th.App.CreateUser(&user) 1469 defer th.App.PermanentDeleteUser(ruser) 1470 1471 bot := th.CreateBot() 1472 botUser, _ := th.App.GetUser(bot.UserId) 1473 defer th.App.PermanentDeleteBot(botUser.Id) 1474 1475 th.App.AddTeamMember(th.BasicTeam.Id, ruser.Id) 1476 th.App.AddTeamMember(th.BasicTeam.Id, bot.UserId) 1477 1478 privateChannel := th.CreatePrivateChannel(th.BasicTeam) 1479 1480 _, err := th.App.AddUserToChannel(ruser, privateChannel) 1481 require.Nil(t, err) 1482 _, err = th.App.AddUserToChannel(botUser, privateChannel) 1483 require.Nil(t, err) 1484 1485 group := th.CreateGroup() 1486 _, err = th.App.UpsertGroupMember(group.Id, ruser.Id) 1487 require.Nil(t, err) 1488 1489 _, err = th.App.UpsertGroupSyncable(&model.GroupSyncable{ 1490 GroupId: group.Id, 1491 SyncableId: privateChannel.Id, 1492 Type: model.GroupSyncableTypeChannel, 1493 }) 1494 require.Nil(t, err) 1495 1496 privateChannel.GroupConstrained = model.NewBool(true) 1497 _, err = th.App.UpdateChannel(privateChannel) 1498 require.Nil(t, err) 1499 1500 // Should not allow a group synced user to be removed from channel 1501 err = th.App.RemoveUserFromChannel(ruser.Id, th.SystemAdminUser.Id, privateChannel) 1502 assert.Equal(t, err.Id, "api.channel.remove_members.denied") 1503 1504 // Should allow a user to remove themselves from group synced channel 1505 err = th.App.RemoveUserFromChannel(ruser.Id, ruser.Id, privateChannel) 1506 require.Nil(t, err) 1507 1508 // Should allow a bot to be removed from a group synced channel 1509 err = th.App.RemoveUserFromChannel(botUser.Id, th.SystemAdminUser.Id, privateChannel) 1510 require.Nil(t, err) 1511 } 1512 1513 func TestPatchChannelModerationsForChannel(t *testing.T) { 1514 th := Setup(t).InitBasic() 1515 defer th.TearDown() 1516 1517 th.App.SetPhase2PermissionsMigrationStatus(true) 1518 channel := th.BasicChannel 1519 1520 createPosts := model.ChannelModeratedPermissions[0] 1521 createReactions := model.ChannelModeratedPermissions[1] 1522 manageMembers := model.ChannelModeratedPermissions[2] 1523 channelMentions := model.ChannelModeratedPermissions[3] 1524 1525 nonChannelModeratedPermission := model.PERMISSION_CREATE_BOT.Id 1526 1527 testCases := []struct { 1528 Name string 1529 ChannelModerationsPatch []*model.ChannelModerationPatch 1530 PermissionsModeratedByPatch map[string]*model.ChannelModeratedRoles 1531 RevertChannelModerationsPatch []*model.ChannelModerationPatch 1532 HigherScopedMemberPermissions []string 1533 HigherScopedGuestPermissions []string 1534 ShouldError bool 1535 ShouldHaveNoChannelScheme bool 1536 }{ 1537 { 1538 Name: "Removing create posts from members role", 1539 ChannelModerationsPatch: []*model.ChannelModerationPatch{ 1540 { 1541 Name: &createPosts, 1542 Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(false)}, 1543 }, 1544 }, 1545 PermissionsModeratedByPatch: map[string]*model.ChannelModeratedRoles{ 1546 createPosts: { 1547 Members: &model.ChannelModeratedRole{Value: false, Enabled: true}, 1548 }, 1549 }, 1550 RevertChannelModerationsPatch: []*model.ChannelModerationPatch{ 1551 { 1552 Name: &createPosts, 1553 Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(true)}, 1554 }, 1555 }, 1556 }, 1557 { 1558 Name: "Removing create reactions from members role", 1559 ChannelModerationsPatch: []*model.ChannelModerationPatch{ 1560 { 1561 Name: &createReactions, 1562 Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(false)}, 1563 }, 1564 }, 1565 PermissionsModeratedByPatch: map[string]*model.ChannelModeratedRoles{ 1566 createReactions: { 1567 Members: &model.ChannelModeratedRole{Value: false, Enabled: true}, 1568 }, 1569 }, 1570 RevertChannelModerationsPatch: []*model.ChannelModerationPatch{ 1571 { 1572 Name: &createReactions, 1573 Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(true)}, 1574 }, 1575 }, 1576 }, 1577 { 1578 Name: "Removing channel mentions from members role", 1579 ChannelModerationsPatch: []*model.ChannelModerationPatch{ 1580 { 1581 Name: &channelMentions, 1582 Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(false)}, 1583 }, 1584 }, 1585 PermissionsModeratedByPatch: map[string]*model.ChannelModeratedRoles{ 1586 channelMentions: { 1587 Members: &model.ChannelModeratedRole{Value: false, Enabled: true}, 1588 }, 1589 }, 1590 RevertChannelModerationsPatch: []*model.ChannelModerationPatch{ 1591 { 1592 Name: &channelMentions, 1593 Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(true)}, 1594 }, 1595 }, 1596 }, 1597 { 1598 Name: "Removing manage members from members role", 1599 ChannelModerationsPatch: []*model.ChannelModerationPatch{ 1600 { 1601 Name: &manageMembers, 1602 Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(false)}, 1603 }, 1604 }, 1605 PermissionsModeratedByPatch: map[string]*model.ChannelModeratedRoles{ 1606 manageMembers: { 1607 Members: &model.ChannelModeratedRole{Value: false, Enabled: true}, 1608 }, 1609 }, 1610 RevertChannelModerationsPatch: []*model.ChannelModerationPatch{ 1611 { 1612 Name: &manageMembers, 1613 Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(true)}, 1614 }, 1615 }, 1616 }, 1617 { 1618 Name: "Removing create posts from guests role", 1619 ChannelModerationsPatch: []*model.ChannelModerationPatch{ 1620 { 1621 Name: &createPosts, 1622 Roles: &model.ChannelModeratedRolesPatch{Guests: model.NewBool(false)}, 1623 }, 1624 }, 1625 PermissionsModeratedByPatch: map[string]*model.ChannelModeratedRoles{ 1626 createPosts: { 1627 Guests: &model.ChannelModeratedRole{Value: false, Enabled: true}, 1628 }, 1629 }, 1630 RevertChannelModerationsPatch: []*model.ChannelModerationPatch{ 1631 { 1632 Name: &createPosts, 1633 Roles: &model.ChannelModeratedRolesPatch{Guests: model.NewBool(true)}, 1634 }, 1635 }, 1636 }, 1637 { 1638 Name: "Removing create reactions from guests role", 1639 ChannelModerationsPatch: []*model.ChannelModerationPatch{ 1640 { 1641 Name: &createReactions, 1642 Roles: &model.ChannelModeratedRolesPatch{Guests: model.NewBool(false)}, 1643 }, 1644 }, 1645 PermissionsModeratedByPatch: map[string]*model.ChannelModeratedRoles{ 1646 createReactions: { 1647 Guests: &model.ChannelModeratedRole{Value: false, Enabled: true}, 1648 }, 1649 }, 1650 RevertChannelModerationsPatch: []*model.ChannelModerationPatch{ 1651 { 1652 Name: &createReactions, 1653 Roles: &model.ChannelModeratedRolesPatch{Guests: model.NewBool(true)}, 1654 }, 1655 }, 1656 }, 1657 { 1658 Name: "Removing channel mentions from guests role", 1659 ChannelModerationsPatch: []*model.ChannelModerationPatch{ 1660 { 1661 Name: &channelMentions, 1662 Roles: &model.ChannelModeratedRolesPatch{Guests: model.NewBool(false)}, 1663 }, 1664 }, 1665 PermissionsModeratedByPatch: map[string]*model.ChannelModeratedRoles{ 1666 channelMentions: { 1667 Guests: &model.ChannelModeratedRole{Value: false, Enabled: true}, 1668 }, 1669 }, 1670 RevertChannelModerationsPatch: []*model.ChannelModerationPatch{ 1671 { 1672 Name: &channelMentions, 1673 Roles: &model.ChannelModeratedRolesPatch{Guests: model.NewBool(true)}, 1674 }, 1675 }, 1676 }, 1677 { 1678 Name: "Removing manage members from guests role should error", 1679 ChannelModerationsPatch: []*model.ChannelModerationPatch{ 1680 { 1681 Name: &manageMembers, 1682 Roles: &model.ChannelModeratedRolesPatch{Guests: model.NewBool(false)}, 1683 }, 1684 }, 1685 PermissionsModeratedByPatch: map[string]*model.ChannelModeratedRoles{}, 1686 ShouldError: true, 1687 }, 1688 { 1689 Name: "Removing a permission that is not channel moderated should error", 1690 ChannelModerationsPatch: []*model.ChannelModerationPatch{ 1691 { 1692 Name: &nonChannelModeratedPermission, 1693 Roles: &model.ChannelModeratedRolesPatch{ 1694 Members: model.NewBool(false), 1695 Guests: model.NewBool(false), 1696 }, 1697 }, 1698 }, 1699 PermissionsModeratedByPatch: map[string]*model.ChannelModeratedRoles{}, 1700 ShouldError: true, 1701 }, 1702 { 1703 Name: "Error when adding a permission that is disabled in the parent member role", 1704 ChannelModerationsPatch: []*model.ChannelModerationPatch{ 1705 { 1706 Name: &createPosts, 1707 Roles: &model.ChannelModeratedRolesPatch{ 1708 Members: model.NewBool(true), 1709 Guests: model.NewBool(false), 1710 }, 1711 }, 1712 }, 1713 PermissionsModeratedByPatch: map[string]*model.ChannelModeratedRoles{}, 1714 HigherScopedMemberPermissions: []string{}, 1715 ShouldError: true, 1716 }, 1717 { 1718 Name: "Error when adding a permission that is disabled in the parent guest role", 1719 ChannelModerationsPatch: []*model.ChannelModerationPatch{ 1720 { 1721 Name: &createPosts, 1722 Roles: &model.ChannelModeratedRolesPatch{ 1723 Members: model.NewBool(false), 1724 Guests: model.NewBool(true), 1725 }, 1726 }, 1727 }, 1728 PermissionsModeratedByPatch: map[string]*model.ChannelModeratedRoles{}, 1729 HigherScopedGuestPermissions: []string{}, 1730 ShouldError: true, 1731 }, 1732 { 1733 Name: "Removing a permission from the member role that is disabled in the parent guest role", 1734 ChannelModerationsPatch: []*model.ChannelModerationPatch{ 1735 { 1736 Name: &createPosts, 1737 Roles: &model.ChannelModeratedRolesPatch{ 1738 Members: model.NewBool(false), 1739 }, 1740 }, 1741 }, 1742 PermissionsModeratedByPatch: map[string]*model.ChannelModeratedRoles{ 1743 createPosts: { 1744 Members: &model.ChannelModeratedRole{Value: false, Enabled: true}, 1745 Guests: &model.ChannelModeratedRole{Value: false, Enabled: false}, 1746 }, 1747 createReactions: { 1748 Guests: &model.ChannelModeratedRole{Value: false, Enabled: false}, 1749 }, 1750 channelMentions: { 1751 Guests: &model.ChannelModeratedRole{Value: false, Enabled: false}, 1752 }, 1753 }, 1754 HigherScopedGuestPermissions: []string{}, 1755 ShouldError: false, 1756 }, 1757 { 1758 Name: "Channel should have no scheme when all moderated permissions are equivalent to higher scoped role", 1759 ChannelModerationsPatch: []*model.ChannelModerationPatch{ 1760 { 1761 Name: &createPosts, 1762 Roles: &model.ChannelModeratedRolesPatch{ 1763 Members: model.NewBool(true), 1764 Guests: model.NewBool(true), 1765 }, 1766 }, 1767 { 1768 Name: &createReactions, 1769 Roles: &model.ChannelModeratedRolesPatch{ 1770 Members: model.NewBool(true), 1771 Guests: model.NewBool(true), 1772 }, 1773 }, 1774 { 1775 Name: &channelMentions, 1776 Roles: &model.ChannelModeratedRolesPatch{ 1777 Members: model.NewBool(true), 1778 Guests: model.NewBool(true), 1779 }, 1780 }, 1781 { 1782 Name: &manageMembers, 1783 Roles: &model.ChannelModeratedRolesPatch{ 1784 Members: model.NewBool(true), 1785 }, 1786 }, 1787 }, 1788 PermissionsModeratedByPatch: map[string]*model.ChannelModeratedRoles{}, 1789 ShouldHaveNoChannelScheme: true, 1790 }, 1791 } 1792 1793 for _, tc := range testCases { 1794 t.Run(tc.Name, func(t *testing.T) { 1795 higherScopedPermissionsOverriden := tc.HigherScopedMemberPermissions != nil || tc.HigherScopedGuestPermissions != nil 1796 // If the test case restricts higher scoped permissions. 1797 if higherScopedPermissionsOverriden { 1798 higherScopedGuestRoleName, higherScopedMemberRoleName, _, _ := th.App.GetTeamSchemeChannelRoles(channel.TeamId) 1799 if tc.HigherScopedMemberPermissions != nil { 1800 higherScopedMemberRole, err := th.App.GetRoleByName(higherScopedMemberRoleName) 1801 require.Nil(t, err) 1802 originalPermissions := higherScopedMemberRole.Permissions 1803 1804 th.App.PatchRole(higherScopedMemberRole, &model.RolePatch{Permissions: &tc.HigherScopedMemberPermissions}) 1805 defer th.App.PatchRole(higherScopedMemberRole, &model.RolePatch{Permissions: &originalPermissions}) 1806 } 1807 1808 if tc.HigherScopedGuestPermissions != nil { 1809 higherScopedGuestRole, err := th.App.GetRoleByName(higherScopedGuestRoleName) 1810 require.Nil(t, err) 1811 originalPermissions := higherScopedGuestRole.Permissions 1812 1813 th.App.PatchRole(higherScopedGuestRole, &model.RolePatch{Permissions: &tc.HigherScopedGuestPermissions}) 1814 defer th.App.PatchRole(higherScopedGuestRole, &model.RolePatch{Permissions: &originalPermissions}) 1815 } 1816 } 1817 1818 moderations, err := th.App.PatchChannelModerationsForChannel(channel, tc.ChannelModerationsPatch) 1819 if tc.ShouldError { 1820 require.Error(t, err) 1821 return 1822 } 1823 require.Nil(t, err) 1824 1825 updatedChannel, _ := th.App.GetChannel(channel.Id) 1826 if tc.ShouldHaveNoChannelScheme { 1827 require.Nil(t, updatedChannel.SchemeId) 1828 } else { 1829 require.NotNil(t, updatedChannel.SchemeId) 1830 } 1831 1832 for _, moderation := range moderations { 1833 // If the permission is not found in the expected modified permissions table then require it to be true 1834 if permission, found := tc.PermissionsModeratedByPatch[moderation.Name]; found && permission.Members != nil { 1835 require.Equal(t, moderation.Roles.Members.Value, permission.Members.Value) 1836 require.Equal(t, moderation.Roles.Members.Enabled, permission.Members.Enabled) 1837 } else { 1838 require.Equal(t, moderation.Roles.Members.Value, true) 1839 require.Equal(t, moderation.Roles.Members.Enabled, true) 1840 } 1841 1842 if permission, found := tc.PermissionsModeratedByPatch[moderation.Name]; found && permission.Guests != nil { 1843 require.Equal(t, moderation.Roles.Guests.Value, permission.Guests.Value) 1844 require.Equal(t, moderation.Roles.Guests.Enabled, permission.Guests.Enabled) 1845 } else if moderation.Name == manageMembers { 1846 require.Empty(t, moderation.Roles.Guests) 1847 } else { 1848 require.Equal(t, moderation.Roles.Guests.Value, true) 1849 require.Equal(t, moderation.Roles.Guests.Enabled, true) 1850 } 1851 } 1852 1853 if tc.RevertChannelModerationsPatch != nil { 1854 th.App.PatchChannelModerationsForChannel(channel, tc.RevertChannelModerationsPatch) 1855 } 1856 }) 1857 } 1858 1859 t.Run("Handles concurrent patch requests gracefully", func(t *testing.T) { 1860 addCreatePosts := []*model.ChannelModerationPatch{ 1861 { 1862 Name: &createPosts, 1863 Roles: &model.ChannelModeratedRolesPatch{ 1864 Members: model.NewBool(false), 1865 Guests: model.NewBool(false), 1866 }, 1867 }, 1868 } 1869 removeCreatePosts := []*model.ChannelModerationPatch{ 1870 { 1871 Name: &createPosts, 1872 Roles: &model.ChannelModeratedRolesPatch{ 1873 Members: model.NewBool(false), 1874 Guests: model.NewBool(false), 1875 }, 1876 }, 1877 } 1878 1879 wg := sync.WaitGroup{} 1880 wg.Add(20) 1881 for i := 0; i < 10; i++ { 1882 go func() { 1883 th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), addCreatePosts) 1884 th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), removeCreatePosts) 1885 wg.Done() 1886 }() 1887 } 1888 for i := 0; i < 10; i++ { 1889 go func() { 1890 th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), addCreatePosts) 1891 th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), removeCreatePosts) 1892 wg.Done() 1893 }() 1894 } 1895 wg.Wait() 1896 1897 higherScopedGuestRoleName, higherScopedMemberRoleName, _, _ := th.App.GetTeamSchemeChannelRoles(channel.TeamId) 1898 higherScopedMemberRole, _ := th.App.GetRoleByName(higherScopedMemberRoleName) 1899 higherScopedGuestRole, _ := th.App.GetRoleByName(higherScopedGuestRoleName) 1900 assert.Contains(t, higherScopedMemberRole.Permissions, createPosts) 1901 assert.Contains(t, higherScopedGuestRole.Permissions, createPosts) 1902 }) 1903 1904 } 1905 1906 // TestMarkChannelsAsViewedPanic verifies that returning an error from a.GetUser 1907 // does not cause a panic. 1908 func TestMarkChannelsAsViewedPanic(t *testing.T) { 1909 th := SetupWithStoreMock(t) 1910 defer th.TearDown() 1911 1912 mockStore := th.App.Srv().Store.(*mocks.Store) 1913 mockUserStore := mocks.UserStore{} 1914 mockUserStore.On("Get", context.Background(), "userID").Return(nil, model.NewAppError("SqlUserStore.Get", "app.user.get.app_error", nil, "user_id=userID", http.StatusInternalServerError)) 1915 mockChannelStore := mocks.ChannelStore{} 1916 mockChannelStore.On("Get", "channelID", true).Return(&model.Channel{}, nil) 1917 mockChannelStore.On("GetMember", "channelID", "userID").Return(&model.ChannelMember{ 1918 NotifyProps: model.StringMap{ 1919 model.PUSH_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT, 1920 }}, nil) 1921 times := map[string]int64{ 1922 "userID": 1, 1923 } 1924 mockChannelStore.On("UpdateLastViewedAt", []string{"channelID"}, "userID", true).Return(times, nil) 1925 mockStore.On("User").Return(&mockUserStore) 1926 mockStore.On("Channel").Return(&mockChannelStore) 1927 1928 _, err := th.App.MarkChannelsAsViewed([]string{"channelID"}, "userID", th.App.Session().Id) 1929 require.Nil(t, err) 1930 } 1931 1932 func TestClearChannelMembersCache(t *testing.T) { 1933 th := SetupWithStoreMock(t) 1934 defer th.TearDown() 1935 1936 mockStore := th.App.Srv().Store.(*mocks.Store) 1937 mockChannelStore := mocks.ChannelStore{} 1938 cms := model.ChannelMembers{} 1939 for i := 0; i < 200; i++ { 1940 cms = append(cms, model.ChannelMember{ 1941 ChannelId: "1", 1942 }) 1943 } 1944 mockChannelStore.On("GetMembers", "channelID", 0, 100).Return(&cms, nil) 1945 mockChannelStore.On("GetMembers", "channelID", 100, 100).Return(&model.ChannelMembers{ 1946 model.ChannelMember{ 1947 ChannelId: "1", 1948 }}, nil) 1949 mockStore.On("Channel").Return(&mockChannelStore) 1950 1951 th.App.ClearChannelMembersCache("channelID") 1952 } 1953 1954 func TestGetMemberCountsByGroup(t *testing.T) { 1955 th := SetupWithStoreMock(t) 1956 defer th.TearDown() 1957 1958 mockStore := th.App.Srv().Store.(*mocks.Store) 1959 mockChannelStore := mocks.ChannelStore{} 1960 cmc := []*model.ChannelMemberCountByGroup{} 1961 for i := 0; i < 5; i++ { 1962 cmc = append(cmc, &model.ChannelMemberCountByGroup{ 1963 GroupId: model.NewId(), 1964 ChannelMemberCount: int64(i), 1965 ChannelMemberTimezonesCount: int64(i), 1966 }) 1967 } 1968 mockChannelStore.On("GetMemberCountsByGroup", "channelID", true).Return(cmc, nil) 1969 mockStore.On("Channel").Return(&mockChannelStore) 1970 resp, err := th.App.GetMemberCountsByGroup("channelID", true) 1971 require.Nil(t, err) 1972 require.ElementsMatch(t, cmc, resp) 1973 }