channel_test.go 134 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105
  1. // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
  2. // See LICENSE.txt for license information.
  3. package api4
  4. import (
  5. "fmt"
  6. "net/http"
  7. "sort"
  8. "strings"
  9. "sync"
  10. "testing"
  11. "time"
  12. "github.com/mattermost/mattermost-server/v5/model"
  13. "github.com/mattermost/mattermost-server/v5/plugin/plugintest/mock"
  14. "github.com/mattermost/mattermost-server/v5/store/storetest/mocks"
  15. "github.com/mattermost/mattermost-server/v5/utils"
  16. "github.com/stretchr/testify/assert"
  17. "github.com/stretchr/testify/require"
  18. )
  19. func TestCreateChannel(t *testing.T) {
  20. th := Setup(t).InitBasic()
  21. defer th.TearDown()
  22. Client := th.Client
  23. team := th.BasicTeam
  24. channel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id}
  25. private := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_PRIVATE, TeamId: team.Id}
  26. rchannel, resp := Client.CreateChannel(channel)
  27. CheckNoError(t, resp)
  28. CheckCreatedStatus(t, resp)
  29. require.Equal(t, channel.Name, rchannel.Name, "names did not match")
  30. require.Equal(t, channel.DisplayName, rchannel.DisplayName, "display names did not match")
  31. require.Equal(t, channel.TeamId, rchannel.TeamId, "team ids did not match")
  32. rprivate, resp := Client.CreateChannel(private)
  33. CheckNoError(t, resp)
  34. require.Equal(t, private.Name, rprivate.Name, "names did not match")
  35. require.Equal(t, model.CHANNEL_PRIVATE, rprivate.Type, "wrong channel type")
  36. require.Equal(t, th.BasicUser.Id, rprivate.CreatorId, "wrong creator id")
  37. _, resp = Client.CreateChannel(channel)
  38. CheckErrorMessage(t, resp, "store.sql_channel.save_channel.exists.app_error")
  39. CheckBadRequestStatus(t, resp)
  40. direct := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_DIRECT, TeamId: team.Id}
  41. _, resp = Client.CreateChannel(direct)
  42. CheckErrorMessage(t, resp, "api.channel.create_channel.direct_channel.app_error")
  43. CheckBadRequestStatus(t, resp)
  44. Client.Logout()
  45. _, resp = Client.CreateChannel(channel)
  46. CheckUnauthorizedStatus(t, resp)
  47. userNotOnTeam := th.CreateUser()
  48. Client.Login(userNotOnTeam.Email, userNotOnTeam.Password)
  49. _, resp = Client.CreateChannel(channel)
  50. CheckForbiddenStatus(t, resp)
  51. _, resp = Client.CreateChannel(private)
  52. CheckForbiddenStatus(t, resp)
  53. // Check the appropriate permissions are enforced.
  54. defaultRolePermissions := th.SaveDefaultRolePermissions()
  55. defer func() {
  56. th.RestoreDefaultRolePermissions(defaultRolePermissions)
  57. }()
  58. th.AddPermissionToRole(model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, model.TEAM_USER_ROLE_ID)
  59. th.AddPermissionToRole(model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, model.TEAM_USER_ROLE_ID)
  60. th.LoginBasic()
  61. channel.Name = GenerateTestChannelName()
  62. _, resp = Client.CreateChannel(channel)
  63. CheckNoError(t, resp)
  64. private.Name = GenerateTestChannelName()
  65. _, resp = Client.CreateChannel(private)
  66. CheckNoError(t, resp)
  67. th.AddPermissionToRole(model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, model.TEAM_ADMIN_ROLE_ID)
  68. th.AddPermissionToRole(model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, model.TEAM_ADMIN_ROLE_ID)
  69. th.RemovePermissionFromRole(model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, model.TEAM_USER_ROLE_ID)
  70. th.RemovePermissionFromRole(model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, model.TEAM_USER_ROLE_ID)
  71. _, resp = Client.CreateChannel(channel)
  72. CheckForbiddenStatus(t, resp)
  73. _, resp = Client.CreateChannel(private)
  74. CheckForbiddenStatus(t, resp)
  75. th.LoginTeamAdmin()
  76. channel.Name = GenerateTestChannelName()
  77. _, resp = Client.CreateChannel(channel)
  78. CheckNoError(t, resp)
  79. private.Name = GenerateTestChannelName()
  80. _, resp = Client.CreateChannel(private)
  81. CheckNoError(t, resp)
  82. th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
  83. channel.Name = GenerateTestChannelName()
  84. _, resp = client.CreateChannel(channel)
  85. CheckNoError(t, resp)
  86. private.Name = GenerateTestChannelName()
  87. _, resp = client.CreateChannel(private)
  88. CheckNoError(t, resp)
  89. })
  90. // Test posting Garbage
  91. r, err := Client.DoApiPost("/channels", "garbage")
  92. require.NotNil(t, err, "expected error")
  93. require.Equal(t, http.StatusBadRequest, r.StatusCode, "Expected 400 Bad Request")
  94. // Test GroupConstrained flag
  95. groupConstrainedChannel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id, GroupConstrained: model.NewBool(true)}
  96. rchannel, resp = Client.CreateChannel(groupConstrainedChannel)
  97. CheckNoError(t, resp)
  98. require.Equal(t, *groupConstrainedChannel.GroupConstrained, *rchannel.GroupConstrained, "GroupConstrained flags do not match")
  99. }
  100. func TestUpdateChannel(t *testing.T) {
  101. th := Setup(t).InitBasic()
  102. defer th.TearDown()
  103. Client := th.Client
  104. team := th.BasicTeam
  105. channel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id}
  106. private := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_PRIVATE, TeamId: team.Id}
  107. channel, _ = Client.CreateChannel(channel)
  108. private, _ = Client.CreateChannel(private)
  109. //Update a open channel
  110. channel.DisplayName = "My new display name"
  111. channel.Header = "My fancy header"
  112. channel.Purpose = "Mattermost ftw!"
  113. newChannel, resp := Client.UpdateChannel(channel)
  114. CheckNoError(t, resp)
  115. require.Equal(t, channel.DisplayName, newChannel.DisplayName, "Update failed for DisplayName")
  116. require.Equal(t, channel.Header, newChannel.Header, "Update failed for Header")
  117. require.Equal(t, channel.Purpose, newChannel.Purpose, "Update failed for Purpose")
  118. // Test GroupConstrained flag
  119. channel.GroupConstrained = model.NewBool(true)
  120. rchannel, resp := Client.UpdateChannel(channel)
  121. CheckNoError(t, resp)
  122. CheckOKStatus(t, resp)
  123. require.Equal(t, *channel.GroupConstrained, *rchannel.GroupConstrained, "GroupConstrained flags do not match")
  124. //Update a private channel
  125. private.DisplayName = "My new display name for private channel"
  126. private.Header = "My fancy private header"
  127. private.Purpose = "Mattermost ftw! in private mode"
  128. newPrivateChannel, resp := Client.UpdateChannel(private)
  129. CheckNoError(t, resp)
  130. require.Equal(t, private.DisplayName, newPrivateChannel.DisplayName, "Update failed for DisplayName in private channel")
  131. require.Equal(t, private.Header, newPrivateChannel.Header, "Update failed for Header in private channel")
  132. require.Equal(t, private.Purpose, newPrivateChannel.Purpose, "Update failed for Purpose in private channel")
  133. // Test that changing the type fails and returns error
  134. private.Type = model.CHANNEL_OPEN
  135. newPrivateChannel, resp = Client.UpdateChannel(private)
  136. CheckBadRequestStatus(t, resp)
  137. // Test that keeping the same type succeeds
  138. private.Type = model.CHANNEL_PRIVATE
  139. newPrivateChannel, resp = Client.UpdateChannel(private)
  140. CheckNoError(t, resp)
  141. //Non existing channel
  142. channel1 := &model.Channel{DisplayName: "Test API Name for apiv4", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id}
  143. _, resp = Client.UpdateChannel(channel1)
  144. CheckNotFoundStatus(t, resp)
  145. //Try to update with not logged user
  146. Client.Logout()
  147. _, resp = Client.UpdateChannel(channel)
  148. CheckUnauthorizedStatus(t, resp)
  149. //Try to update using another user
  150. user := th.CreateUser()
  151. Client.Login(user.Email, user.Password)
  152. channel.DisplayName = "Should not update"
  153. _, resp = Client.UpdateChannel(channel)
  154. CheckForbiddenStatus(t, resp)
  155. // Test updating the header of someone else's GM channel.
  156. user1 := th.CreateUser()
  157. user2 := th.CreateUser()
  158. user3 := th.CreateUser()
  159. groupChannel, resp := Client.CreateGroupChannel([]string{user1.Id, user2.Id})
  160. CheckNoError(t, resp)
  161. groupChannel.Header = "lolololol"
  162. Client.Logout()
  163. Client.Login(user3.Email, user3.Password)
  164. _, resp = Client.UpdateChannel(groupChannel)
  165. CheckForbiddenStatus(t, resp)
  166. // Test updating the header of someone else's GM channel.
  167. Client.Logout()
  168. Client.Login(user.Email, user.Password)
  169. directChannel, resp := Client.CreateDirectChannel(user.Id, user1.Id)
  170. CheckNoError(t, resp)
  171. directChannel.Header = "lolololol"
  172. Client.Logout()
  173. Client.Login(user3.Email, user3.Password)
  174. _, resp = Client.UpdateChannel(directChannel)
  175. CheckForbiddenStatus(t, resp)
  176. }
  177. func TestPatchChannel(t *testing.T) {
  178. th := Setup(t).InitBasic()
  179. defer th.TearDown()
  180. Client := th.Client
  181. patch := &model.ChannelPatch{
  182. Name: new(string),
  183. DisplayName: new(string),
  184. Header: new(string),
  185. Purpose: new(string),
  186. }
  187. *patch.Name = model.NewId()
  188. *patch.DisplayName = model.NewId()
  189. *patch.Header = model.NewId()
  190. *patch.Purpose = model.NewId()
  191. channel, resp := Client.PatchChannel(th.BasicChannel.Id, patch)
  192. CheckNoError(t, resp)
  193. require.Equal(t, *patch.Name, channel.Name, "do not match")
  194. require.Equal(t, *patch.DisplayName, channel.DisplayName, "do not match")
  195. require.Equal(t, *patch.Header, channel.Header, "do not match")
  196. require.Equal(t, *patch.Purpose, channel.Purpose, "do not match")
  197. patch.Name = nil
  198. oldName := channel.Name
  199. channel, resp = Client.PatchChannel(th.BasicChannel.Id, patch)
  200. CheckNoError(t, resp)
  201. require.Equal(t, oldName, channel.Name, "should not have updated")
  202. // Test GroupConstrained flag
  203. patch.GroupConstrained = model.NewBool(true)
  204. rchannel, resp := Client.PatchChannel(th.BasicChannel.Id, patch)
  205. CheckNoError(t, resp)
  206. CheckOKStatus(t, resp)
  207. require.Equal(t, *rchannel.GroupConstrained, *patch.GroupConstrained, "GroupConstrained flags do not match")
  208. patch.GroupConstrained = nil
  209. _, resp = Client.PatchChannel("junk", patch)
  210. CheckBadRequestStatus(t, resp)
  211. _, resp = Client.PatchChannel(model.NewId(), patch)
  212. CheckNotFoundStatus(t, resp)
  213. user := th.CreateUser()
  214. Client.Login(user.Email, user.Password)
  215. _, resp = Client.PatchChannel(th.BasicChannel.Id, patch)
  216. CheckForbiddenStatus(t, resp)
  217. th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
  218. _, resp = client.PatchChannel(th.BasicChannel.Id, patch)
  219. CheckNoError(t, resp)
  220. _, resp = client.PatchChannel(th.BasicPrivateChannel.Id, patch)
  221. CheckNoError(t, resp)
  222. })
  223. // Test updating the header of someone else's GM channel.
  224. user1 := th.CreateUser()
  225. user2 := th.CreateUser()
  226. user3 := th.CreateUser()
  227. groupChannel, resp := Client.CreateGroupChannel([]string{user1.Id, user2.Id})
  228. CheckNoError(t, resp)
  229. Client.Logout()
  230. Client.Login(user3.Email, user3.Password)
  231. channelPatch := &model.ChannelPatch{}
  232. channelPatch.Header = new(string)
  233. *channelPatch.Header = "lolololol"
  234. _, resp = Client.PatchChannel(groupChannel.Id, channelPatch)
  235. CheckForbiddenStatus(t, resp)
  236. // Test updating the header of someone else's GM channel.
  237. Client.Logout()
  238. Client.Login(user.Email, user.Password)
  239. directChannel, resp := Client.CreateDirectChannel(user.Id, user1.Id)
  240. CheckNoError(t, resp)
  241. Client.Logout()
  242. Client.Login(user3.Email, user3.Password)
  243. _, resp = Client.PatchChannel(directChannel.Id, channelPatch)
  244. CheckForbiddenStatus(t, resp)
  245. }
  246. func TestChannelUnicodeNames(t *testing.T) {
  247. th := Setup(t).InitBasic()
  248. defer th.TearDown()
  249. Client := th.Client
  250. team := th.BasicTeam
  251. t.Run("create channel unicode", func(t *testing.T) {
  252. channel := &model.Channel{
  253. Name: "\u206cenglish\u206dchannel",
  254. DisplayName: "The \u206cEnglish\u206d Channel",
  255. Type: model.CHANNEL_OPEN,
  256. TeamId: team.Id}
  257. rchannel, resp := Client.CreateChannel(channel)
  258. CheckNoError(t, resp)
  259. CheckCreatedStatus(t, resp)
  260. require.Equal(t, "englishchannel", rchannel.Name, "bad unicode should be filtered from name")
  261. require.Equal(t, "The English Channel", rchannel.DisplayName, "bad unicode should be filtered from display name")
  262. })
  263. t.Run("update channel unicode", func(t *testing.T) {
  264. channel := &model.Channel{
  265. DisplayName: "Test API Name",
  266. Name: GenerateTestChannelName(),
  267. Type: model.CHANNEL_OPEN,
  268. TeamId: team.Id,
  269. }
  270. channel, _ = Client.CreateChannel(channel)
  271. channel.Name = "\u206ahistorychannel"
  272. channel.DisplayName = "UFO's and \ufff9stuff\ufffb."
  273. newChannel, resp := Client.UpdateChannel(channel)
  274. CheckNoError(t, resp)
  275. require.Equal(t, "historychannel", newChannel.Name, "bad unicode should be filtered from name")
  276. require.Equal(t, "UFO's and stuff.", newChannel.DisplayName, "bad unicode should be filtered from display name")
  277. })
  278. t.Run("patch channel unicode", func(t *testing.T) {
  279. patch := &model.ChannelPatch{
  280. Name: new(string),
  281. DisplayName: new(string),
  282. Header: new(string),
  283. Purpose: new(string),
  284. }
  285. *patch.Name = "\u206ecommunitychannel\u206f"
  286. *patch.DisplayName = "Natalie Tran's \ufffcAwesome Channel"
  287. channel, resp := Client.PatchChannel(th.BasicChannel.Id, patch)
  288. CheckNoError(t, resp)
  289. require.Equal(t, "communitychannel", channel.Name, "bad unicode should be filtered from name")
  290. require.Equal(t, "Natalie Tran's Awesome Channel", channel.DisplayName, "bad unicode should be filtered from display name")
  291. })
  292. }
  293. func TestCreateDirectChannel(t *testing.T) {
  294. th := Setup(t).InitBasic()
  295. defer th.TearDown()
  296. Client := th.Client
  297. user1 := th.BasicUser
  298. user2 := th.BasicUser2
  299. user3 := th.CreateUser()
  300. dm, resp := Client.CreateDirectChannel(user1.Id, user2.Id)
  301. CheckNoError(t, resp)
  302. channelName := ""
  303. if user2.Id > user1.Id {
  304. channelName = user1.Id + "__" + user2.Id
  305. } else {
  306. channelName = user2.Id + "__" + user1.Id
  307. }
  308. require.Equal(t, channelName, dm.Name, "dm name didn't match")
  309. _, resp = Client.CreateDirectChannel("junk", user2.Id)
  310. CheckBadRequestStatus(t, resp)
  311. _, resp = Client.CreateDirectChannel(user1.Id, model.NewId())
  312. CheckBadRequestStatus(t, resp)
  313. _, resp = Client.CreateDirectChannel(model.NewId(), user1.Id)
  314. CheckBadRequestStatus(t, resp)
  315. _, resp = Client.CreateDirectChannel(model.NewId(), user2.Id)
  316. CheckForbiddenStatus(t, resp)
  317. r, err := Client.DoApiPost("/channels/direct", "garbage")
  318. require.NotNil(t, err)
  319. require.Equal(t, http.StatusBadRequest, r.StatusCode)
  320. Client.Logout()
  321. _, resp = Client.CreateDirectChannel(model.NewId(), user2.Id)
  322. CheckUnauthorizedStatus(t, resp)
  323. _, resp = th.SystemAdminClient.CreateDirectChannel(user3.Id, user2.Id)
  324. CheckNoError(t, resp)
  325. }
  326. func TestCreateDirectChannelAsGuest(t *testing.T) {
  327. th := Setup(t).InitBasic()
  328. defer th.TearDown()
  329. Client := th.Client
  330. user1 := th.BasicUser
  331. enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable
  332. defer func() {
  333. th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts })
  334. th.App.Srv().RemoveLicense()
  335. }()
  336. th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true })
  337. th.App.Srv().SetLicense(model.NewTestLicense())
  338. id := model.NewId()
  339. guest := &model.User{
  340. Email: "success+" + id + "@simulator.amazonses.com",
  341. Username: "un_" + id,
  342. Nickname: "nn_" + id,
  343. Password: "Password1",
  344. EmailVerified: true,
  345. }
  346. guest, err := th.App.CreateGuest(guest)
  347. require.Nil(t, err)
  348. _, resp := Client.Login(guest.Username, "Password1")
  349. CheckNoError(t, resp)
  350. t.Run("Try to created DM with not visible user", func(t *testing.T) {
  351. _, resp := Client.CreateDirectChannel(guest.Id, user1.Id)
  352. CheckForbiddenStatus(t, resp)
  353. _, resp = Client.CreateDirectChannel(user1.Id, guest.Id)
  354. CheckForbiddenStatus(t, resp)
  355. })
  356. t.Run("Creating DM with visible user", func(t *testing.T) {
  357. th.LinkUserToTeam(guest, th.BasicTeam)
  358. th.AddUserToChannel(guest, th.BasicChannel)
  359. _, resp := Client.CreateDirectChannel(guest.Id, user1.Id)
  360. CheckNoError(t, resp)
  361. })
  362. }
  363. func TestDeleteDirectChannel(t *testing.T) {
  364. th := Setup(t).InitBasic()
  365. defer th.TearDown()
  366. Client := th.Client
  367. user := th.BasicUser
  368. user2 := th.BasicUser2
  369. rgc, resp := Client.CreateDirectChannel(user.Id, user2.Id)
  370. CheckNoError(t, resp)
  371. CheckCreatedStatus(t, resp)
  372. require.NotNil(t, rgc, "should have created a direct channel")
  373. deleted, resp := Client.DeleteChannel(rgc.Id)
  374. CheckErrorMessage(t, resp, "api.channel.delete_channel.type.invalid")
  375. require.False(t, deleted, "should not have been able to delete direct channel.")
  376. }
  377. func TestCreateGroupChannel(t *testing.T) {
  378. th := Setup(t).InitBasic()
  379. defer th.TearDown()
  380. Client := th.Client
  381. user := th.BasicUser
  382. user2 := th.BasicUser2
  383. user3 := th.CreateUser()
  384. userIds := []string{user.Id, user2.Id, user3.Id}
  385. rgc, resp := Client.CreateGroupChannel(userIds)
  386. CheckNoError(t, resp)
  387. CheckCreatedStatus(t, resp)
  388. require.NotNil(t, rgc, "should have created a group channel")
  389. require.Equal(t, model.CHANNEL_GROUP, rgc.Type, "should have created a channel of group type")
  390. m, _ := th.App.GetChannelMembersPage(rgc.Id, 0, 10)
  391. require.Len(t, *m, 3, "should have 3 channel members")
  392. // saving duplicate group channel
  393. rgc2, resp := Client.CreateGroupChannel([]string{user3.Id, user2.Id})
  394. CheckNoError(t, resp)
  395. require.Equal(t, rgc.Id, rgc2.Id, "should have returned existing channel")
  396. m2, _ := th.App.GetChannelMembersPage(rgc2.Id, 0, 10)
  397. require.Equal(t, m, m2)
  398. _, resp = Client.CreateGroupChannel([]string{user2.Id})
  399. CheckBadRequestStatus(t, resp)
  400. user4 := th.CreateUser()
  401. user5 := th.CreateUser()
  402. user6 := th.CreateUser()
  403. user7 := th.CreateUser()
  404. user8 := th.CreateUser()
  405. user9 := th.CreateUser()
  406. rgc, resp = Client.CreateGroupChannel([]string{user.Id, user2.Id, user3.Id, user4.Id, user5.Id, user6.Id, user7.Id, user8.Id, user9.Id})
  407. CheckBadRequestStatus(t, resp)
  408. require.Nil(t, rgc)
  409. _, resp = Client.CreateGroupChannel([]string{user.Id, user2.Id, user3.Id, GenerateTestId()})
  410. CheckBadRequestStatus(t, resp)
  411. _, resp = Client.CreateGroupChannel([]string{user.Id, user2.Id, user3.Id, "junk"})
  412. CheckBadRequestStatus(t, resp)
  413. Client.Logout()
  414. _, resp = Client.CreateGroupChannel(userIds)
  415. CheckUnauthorizedStatus(t, resp)
  416. _, resp = th.SystemAdminClient.CreateGroupChannel(userIds)
  417. CheckNoError(t, resp)
  418. }
  419. func TestCreateGroupChannelAsGuest(t *testing.T) {
  420. th := Setup(t).InitBasic()
  421. defer th.TearDown()
  422. Client := th.Client
  423. user1 := th.BasicUser
  424. user2 := th.BasicUser2
  425. user3 := th.CreateUser()
  426. user4 := th.CreateUser()
  427. user5 := th.CreateUser()
  428. th.LinkUserToTeam(user2, th.BasicTeam)
  429. th.AddUserToChannel(user2, th.BasicChannel)
  430. th.LinkUserToTeam(user3, th.BasicTeam)
  431. th.AddUserToChannel(user3, th.BasicChannel)
  432. enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable
  433. defer func() {
  434. th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts })
  435. th.App.Srv().RemoveLicense()
  436. }()
  437. th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true })
  438. th.App.Srv().SetLicense(model.NewTestLicense())
  439. id := model.NewId()
  440. guest := &model.User{
  441. Email: "success+" + id + "@simulator.amazonses.com",
  442. Username: "un_" + id,
  443. Nickname: "nn_" + id,
  444. Password: "Password1",
  445. EmailVerified: true,
  446. }
  447. guest, err := th.App.CreateGuest(guest)
  448. require.Nil(t, err)
  449. _, resp := Client.Login(guest.Username, "Password1")
  450. CheckNoError(t, resp)
  451. t.Run("Try to created GM with not visible users", func(t *testing.T) {
  452. _, resp := Client.CreateGroupChannel([]string{guest.Id, user1.Id, user2.Id, user3.Id})
  453. CheckForbiddenStatus(t, resp)
  454. _, resp = Client.CreateGroupChannel([]string{user1.Id, user2.Id, guest.Id, user3.Id})
  455. CheckForbiddenStatus(t, resp)
  456. })
  457. t.Run("Try to created GM with visible and not visible users", func(t *testing.T) {
  458. th.LinkUserToTeam(guest, th.BasicTeam)
  459. th.AddUserToChannel(guest, th.BasicChannel)
  460. _, resp := Client.CreateGroupChannel([]string{guest.Id, user1.Id, user3.Id, user4.Id, user5.Id})
  461. CheckForbiddenStatus(t, resp)
  462. _, resp = Client.CreateGroupChannel([]string{user1.Id, user2.Id, guest.Id, user4.Id, user5.Id})
  463. CheckForbiddenStatus(t, resp)
  464. })
  465. t.Run("Creating GM with visible users", func(t *testing.T) {
  466. _, resp := Client.CreateGroupChannel([]string{guest.Id, user1.Id, user2.Id, user3.Id})
  467. CheckNoError(t, resp)
  468. })
  469. }
  470. func TestDeleteGroupChannel(t *testing.T) {
  471. th := Setup(t).InitBasic()
  472. defer th.TearDown()
  473. user := th.BasicUser
  474. user2 := th.BasicUser2
  475. user3 := th.CreateUser()
  476. userIds := []string{user.Id, user2.Id, user3.Id}
  477. th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
  478. rgc, resp := th.Client.CreateGroupChannel(userIds)
  479. CheckNoError(t, resp)
  480. CheckCreatedStatus(t, resp)
  481. require.NotNil(t, rgc, "should have created a group channel")
  482. deleted, resp := client.DeleteChannel(rgc.Id)
  483. CheckErrorMessage(t, resp, "api.channel.delete_channel.type.invalid")
  484. require.False(t, deleted, "should not have been able to delete group channel.")
  485. })
  486. }
  487. func TestGetChannel(t *testing.T) {
  488. th := Setup(t).InitBasic()
  489. defer th.TearDown()
  490. Client := th.Client
  491. channel, resp := Client.GetChannel(th.BasicChannel.Id, "")
  492. CheckNoError(t, resp)
  493. require.Equal(t, th.BasicChannel.Id, channel.Id, "ids did not match")
  494. Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
  495. _, resp = Client.GetChannel(th.BasicChannel.Id, "")
  496. CheckNoError(t, resp)
  497. channel, resp = Client.GetChannel(th.BasicPrivateChannel.Id, "")
  498. CheckNoError(t, resp)
  499. require.Equal(t, th.BasicPrivateChannel.Id, channel.Id, "ids did not match")
  500. Client.RemoveUserFromChannel(th.BasicPrivateChannel.Id, th.BasicUser.Id)
  501. _, resp = Client.GetChannel(th.BasicPrivateChannel.Id, "")
  502. CheckForbiddenStatus(t, resp)
  503. _, resp = Client.GetChannel(model.NewId(), "")
  504. CheckNotFoundStatus(t, resp)
  505. Client.Logout()
  506. _, resp = Client.GetChannel(th.BasicChannel.Id, "")
  507. CheckUnauthorizedStatus(t, resp)
  508. user := th.CreateUser()
  509. Client.Login(user.Email, user.Password)
  510. _, resp = Client.GetChannel(th.BasicChannel.Id, "")
  511. CheckForbiddenStatus(t, resp)
  512. th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
  513. _, resp = client.GetChannel(th.BasicChannel.Id, "")
  514. CheckNoError(t, resp)
  515. _, resp = client.GetChannel(th.BasicPrivateChannel.Id, "")
  516. CheckNoError(t, resp)
  517. _, resp = client.GetChannel(th.BasicUser.Id, "")
  518. CheckNotFoundStatus(t, resp)
  519. })
  520. }
  521. func TestGetDeletedChannelsForTeam(t *testing.T) {
  522. th := Setup(t).InitBasic()
  523. defer th.TearDown()
  524. Client := th.Client
  525. team := th.BasicTeam
  526. th.LoginTeamAdmin()
  527. channels, resp := Client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
  528. CheckNoError(t, resp)
  529. numInitialChannelsForTeam := len(channels)
  530. // create and delete public channel
  531. publicChannel1 := th.CreatePublicChannel()
  532. Client.DeleteChannel(publicChannel1.Id)
  533. th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
  534. channels, resp = client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
  535. CheckNoError(t, resp)
  536. require.Len(t, channels, numInitialChannelsForTeam+1, "should be 1 deleted channel")
  537. })
  538. publicChannel2 := th.CreatePublicChannel()
  539. Client.DeleteChannel(publicChannel2.Id)
  540. th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
  541. channels, resp = client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
  542. CheckNoError(t, resp)
  543. require.Len(t, channels, numInitialChannelsForTeam+2, "should be 2 deleted channels")
  544. })
  545. th.LoginBasic()
  546. privateChannel1 := th.CreatePrivateChannel()
  547. Client.DeleteChannel(privateChannel1.Id)
  548. channels, resp = Client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
  549. CheckNoError(t, resp)
  550. require.Len(t, channels, numInitialChannelsForTeam+3)
  551. // Login as different user and create private channel
  552. th.LoginBasic2()
  553. privateChannel2 := th.CreatePrivateChannel()
  554. Client.DeleteChannel(privateChannel2.Id)
  555. // Log back in as first user
  556. th.LoginBasic()
  557. channels, resp = Client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
  558. CheckNoError(t, resp)
  559. require.Len(t, channels, numInitialChannelsForTeam+3)
  560. th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
  561. channels, resp = client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
  562. CheckNoError(t, resp)
  563. require.Len(t, channels, numInitialChannelsForTeam+2)
  564. })
  565. channels, resp = Client.GetDeletedChannelsForTeam(team.Id, 0, 1, "")
  566. CheckNoError(t, resp)
  567. require.Len(t, channels, 1, "should be one channel per page")
  568. channels, resp = Client.GetDeletedChannelsForTeam(team.Id, 1, 1, "")
  569. CheckNoError(t, resp)
  570. require.Len(t, channels, 1, "should be one channel per page")
  571. }
  572. func TestGetPrivateChannelsForTeam(t *testing.T) {
  573. th := Setup(t).InitBasic()
  574. defer th.TearDown()
  575. team := th.BasicTeam
  576. // normal user
  577. _, resp := th.Client.GetPrivateChannelsForTeam(team.Id, 0, 100, "")
  578. CheckForbiddenStatus(t, resp)
  579. th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
  580. channels, resp := c.GetPrivateChannelsForTeam(team.Id, 0, 100, "")
  581. CheckNoError(t, resp)
  582. // th.BasicPrivateChannel and th.BasicPrivateChannel2
  583. require.Len(t, channels, 2, "wrong number of private channels")
  584. for _, c := range channels {
  585. // check all channels included are private
  586. require.Equal(t, model.CHANNEL_PRIVATE, c.Type, "should include private channels only")
  587. }
  588. channels, resp = c.GetPrivateChannelsForTeam(team.Id, 0, 1, "")
  589. CheckNoError(t, resp)
  590. require.Len(t, channels, 1, "should be one channel per page")
  591. channels, resp = c.GetPrivateChannelsForTeam(team.Id, 1, 1, "")
  592. CheckNoError(t, resp)
  593. require.Len(t, channels, 1, "should be one channel per page")
  594. channels, resp = c.GetPrivateChannelsForTeam(team.Id, 10000, 100, "")
  595. CheckNoError(t, resp)
  596. require.Empty(t, channels, "should be no channel")
  597. _, resp = c.GetPrivateChannelsForTeam("junk", 0, 100, "")
  598. CheckBadRequestStatus(t, resp)
  599. })
  600. }
  601. func TestGetPublicChannelsForTeam(t *testing.T) {
  602. th := Setup(t).InitBasic()
  603. defer th.TearDown()
  604. Client := th.Client
  605. team := th.BasicTeam
  606. publicChannel1 := th.BasicChannel
  607. publicChannel2 := th.BasicChannel2
  608. channels, resp := Client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
  609. CheckNoError(t, resp)
  610. require.Len(t, channels, 4, "wrong path")
  611. for i, c := range channels {
  612. // check all channels included are open
  613. require.Equal(t, model.CHANNEL_OPEN, c.Type, "should include open channel only")
  614. // only check the created 2 public channels
  615. require.False(t, i < 2 && !(c.DisplayName == publicChannel1.DisplayName || c.DisplayName == publicChannel2.DisplayName), "should match public channel display name")
  616. }
  617. privateChannel := th.CreatePrivateChannel()
  618. channels, resp = Client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
  619. CheckNoError(t, resp)
  620. require.Len(t, channels, 4, "incorrect length of team public channels")
  621. for _, c := range channels {
  622. require.Equal(t, model.CHANNEL_OPEN, c.Type, "should not include private channel")
  623. require.NotEqual(t, privateChannel.DisplayName, c.DisplayName, "should not match private channel display name")
  624. }
  625. channels, resp = Client.GetPublicChannelsForTeam(team.Id, 0, 1, "")
  626. CheckNoError(t, resp)
  627. require.Len(t, channels, 1, "should be one channel per page")
  628. channels, resp = Client.GetPublicChannelsForTeam(team.Id, 1, 1, "")
  629. CheckNoError(t, resp)
  630. require.Len(t, channels, 1, "should be one channel per page")
  631. channels, resp = Client.GetPublicChannelsForTeam(team.Id, 10000, 100, "")
  632. CheckNoError(t, resp)
  633. require.Empty(t, channels, "should be no channel")
  634. _, resp = Client.GetPublicChannelsForTeam("junk", 0, 100, "")
  635. CheckBadRequestStatus(t, resp)
  636. _, resp = Client.GetPublicChannelsForTeam(model.NewId(), 0, 100, "")
  637. CheckForbiddenStatus(t, resp)
  638. Client.Logout()
  639. _, resp = Client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
  640. CheckUnauthorizedStatus(t, resp)
  641. user := th.CreateUser()
  642. Client.Login(user.Email, user.Password)
  643. _, resp = Client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
  644. CheckForbiddenStatus(t, resp)
  645. th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
  646. _, resp = client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
  647. CheckNoError(t, resp)
  648. })
  649. }
  650. func TestGetPublicChannelsByIdsForTeam(t *testing.T) {
  651. th := Setup(t).InitBasic()
  652. defer th.TearDown()
  653. Client := th.Client
  654. teamId := th.BasicTeam.Id
  655. input := []string{th.BasicChannel.Id}
  656. output := []string{th.BasicChannel.DisplayName}
  657. channels, resp := Client.GetPublicChannelsByIdsForTeam(teamId, input)
  658. CheckNoError(t, resp)
  659. require.Len(t, channels, 1, "should return 1 channel")
  660. require.Equal(t, output[0], channels[0].DisplayName, "missing channel")
  661. input = append(input, GenerateTestId())
  662. input = append(input, th.BasicChannel2.Id)
  663. input = append(input, th.BasicPrivateChannel.Id)
  664. output = append(output, th.BasicChannel2.DisplayName)
  665. sort.Strings(output)
  666. channels, resp = Client.GetPublicChannelsByIdsForTeam(teamId, input)
  667. CheckNoError(t, resp)
  668. require.Len(t, channels, 2, "should return 2 channels")
  669. for i, c := range channels {
  670. require.Equal(t, output[i], c.DisplayName, "missing channel")
  671. }
  672. _, resp = Client.GetPublicChannelsByIdsForTeam(GenerateTestId(), input)
  673. CheckForbiddenStatus(t, resp)
  674. _, resp = Client.GetPublicChannelsByIdsForTeam(teamId, []string{})
  675. CheckBadRequestStatus(t, resp)
  676. _, resp = Client.GetPublicChannelsByIdsForTeam(teamId, []string{"junk"})
  677. CheckBadRequestStatus(t, resp)
  678. _, resp = Client.GetPublicChannelsByIdsForTeam(teamId, []string{GenerateTestId()})
  679. CheckNotFoundStatus(t, resp)
  680. _, resp = Client.GetPublicChannelsByIdsForTeam(teamId, []string{th.BasicPrivateChannel.Id})
  681. CheckNotFoundStatus(t, resp)
  682. Client.Logout()
  683. _, resp = Client.GetPublicChannelsByIdsForTeam(teamId, input)
  684. CheckUnauthorizedStatus(t, resp)
  685. _, resp = th.SystemAdminClient.GetPublicChannelsByIdsForTeam(teamId, input)
  686. CheckNoError(t, resp)
  687. }
  688. func TestGetChannelsForTeamForUser(t *testing.T) {
  689. th := Setup(t).InitBasic()
  690. defer th.TearDown()
  691. Client := th.Client
  692. t.Run("get channels for the team for user", func(t *testing.T) {
  693. channels, resp := Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "")
  694. CheckNoError(t, resp)
  695. found := make([]bool, 3)
  696. for _, c := range channels {
  697. if c.Id == th.BasicChannel.Id {
  698. found[0] = true
  699. } else if c.Id == th.BasicChannel2.Id {
  700. found[1] = true
  701. } else if c.Id == th.BasicPrivateChannel.Id {
  702. found[2] = true
  703. }
  704. require.True(t, c.TeamId == "" || c.TeamId == th.BasicTeam.Id)
  705. }
  706. for _, f := range found {
  707. require.True(t, f, "missing a channel")
  708. }
  709. channels, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, resp.Etag)
  710. CheckEtag(t, channels, resp)
  711. _, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, "junk", false, "")
  712. CheckBadRequestStatus(t, resp)
  713. _, resp = Client.GetChannelsForTeamForUser("junk", th.BasicUser.Id, false, "")
  714. CheckBadRequestStatus(t, resp)
  715. _, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser2.Id, false, "")
  716. CheckForbiddenStatus(t, resp)
  717. _, resp = Client.GetChannelsForTeamForUser(model.NewId(), th.BasicUser.Id, false, "")
  718. CheckForbiddenStatus(t, resp)
  719. _, resp = th.SystemAdminClient.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "")
  720. CheckNoError(t, resp)
  721. })
  722. t.Run("deleted channel could be retrieved using the proper flag", func(t *testing.T) {
  723. testChannel := &model.Channel{
  724. DisplayName: "dn_" + model.NewId(),
  725. Name: GenerateTestChannelName(),
  726. Type: model.CHANNEL_OPEN,
  727. TeamId: th.BasicTeam.Id,
  728. CreatorId: th.BasicUser.Id,
  729. }
  730. th.App.CreateChannel(testChannel, true)
  731. defer th.App.PermanentDeleteChannel(testChannel)
  732. channels, resp := Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "")
  733. CheckNoError(t, resp)
  734. assert.Equal(t, 6, len(channels))
  735. th.App.DeleteChannel(testChannel, th.BasicUser.Id)
  736. channels, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "")
  737. CheckNoError(t, resp)
  738. assert.Equal(t, 5, len(channels))
  739. // Should return all channels including basicDeleted.
  740. channels, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, true, "")
  741. CheckNoError(t, resp)
  742. assert.Equal(t, 7, len(channels))
  743. // Should stil return all channels including basicDeleted.
  744. now := time.Now().Add(-time.Minute).Unix() * 1000
  745. Client.GetChannelsForTeamAndUserWithLastDeleteAt(th.BasicTeam.Id, th.BasicUser.Id,
  746. true, int(now), "")
  747. CheckNoError(t, resp)
  748. assert.Equal(t, 7, len(channels))
  749. })
  750. }
  751. func TestGetAllChannels(t *testing.T) {
  752. th := Setup(t).InitBasic()
  753. defer th.TearDown()
  754. Client := th.Client
  755. var originalConfigVal bool
  756. th.App.UpdateConfig(func(cfg *model.Config) {
  757. originalConfigVal = *cfg.TeamSettings.ExperimentalViewArchivedChannels
  758. *cfg.TeamSettings.ExperimentalViewArchivedChannels = true
  759. })
  760. defer th.App.UpdateConfig(func(cfg *model.Config) {
  761. *cfg.TeamSettings.ExperimentalViewArchivedChannels = originalConfigVal
  762. })
  763. th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
  764. channels, resp := client.GetAllChannels(0, 20, "")
  765. CheckNoError(t, resp)
  766. // At least, all the not-deleted channels created during the InitBasic
  767. require.True(t, len(*channels) >= 3)
  768. for _, c := range *channels {
  769. require.NotEqual(t, c.TeamId, "")
  770. }
  771. channels, resp = client.GetAllChannels(0, 10, "")
  772. CheckNoError(t, resp)
  773. require.True(t, len(*channels) >= 3)
  774. channels, resp = client.GetAllChannels(1, 1, "")
  775. CheckNoError(t, resp)
  776. require.Len(t, *channels, 1)
  777. channels, resp = client.GetAllChannels(10000, 10000, "")
  778. CheckNoError(t, resp)
  779. require.Empty(t, *channels)
  780. channels, resp = client.GetAllChannels(0, 10000, "")
  781. require.Nil(t, resp.Error)
  782. beforeCount := len(*channels)
  783. firstChannel := (*channels)[0].Channel
  784. ok, resp := client.DeleteChannel(firstChannel.Id)
  785. require.Nil(t, resp.Error)
  786. require.True(t, ok)
  787. channels, resp = client.GetAllChannels(0, 10000, "")
  788. var ids []string
  789. for _, item := range *channels {
  790. ids = append(ids, item.Channel.Id)
  791. }
  792. require.Nil(t, resp.Error)
  793. require.Len(t, *channels, beforeCount-1)
  794. require.NotContains(t, ids, firstChannel.Id)
  795. channels, resp = client.GetAllChannelsIncludeDeleted(0, 10000, "")
  796. ids = []string{}
  797. for _, item := range *channels {
  798. ids = append(ids, item.Channel.Id)
  799. }
  800. require.Nil(t, resp.Error)
  801. require.True(t, len(*channels) > beforeCount)
  802. require.Contains(t, ids, firstChannel.Id)
  803. })
  804. _, resp := Client.GetAllChannels(0, 20, "")
  805. CheckForbiddenStatus(t, resp)
  806. }
  807. func TestGetAllChannelsWithCount(t *testing.T) {
  808. th := Setup(t).InitBasic()
  809. defer th.TearDown()
  810. Client := th.Client
  811. channels, total, resp := th.SystemAdminClient.GetAllChannelsWithCount(0, 20, "")
  812. CheckNoError(t, resp)
  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. require.Equal(t, int64(6), total)
  819. channels, _, resp = th.SystemAdminClient.GetAllChannelsWithCount(0, 10, "")
  820. CheckNoError(t, resp)
  821. require.True(t, len(*channels) >= 3)
  822. channels, _, resp = th.SystemAdminClient.GetAllChannelsWithCount(1, 1, "")
  823. CheckNoError(t, resp)
  824. require.Len(t, *channels, 1)
  825. channels, _, resp = th.SystemAdminClient.GetAllChannelsWithCount(10000, 10000, "")
  826. CheckNoError(t, resp)
  827. require.Empty(t, *channels)
  828. _, _, resp = Client.GetAllChannelsWithCount(0, 20, "")
  829. CheckForbiddenStatus(t, resp)
  830. }
  831. func TestSearchChannels(t *testing.T) {
  832. th := Setup(t).InitBasic()
  833. defer th.TearDown()
  834. Client := th.Client
  835. search := &model.ChannelSearch{Term: th.BasicChannel.Name}
  836. channels, resp := Client.SearchChannels(th.BasicTeam.Id, search)
  837. CheckNoError(t, resp)
  838. found := false
  839. for _, c := range channels {
  840. require.Equal(t, model.CHANNEL_OPEN, c.Type, "should only return public channels")
  841. if c.Id == th.BasicChannel.Id {
  842. found = true
  843. }
  844. }
  845. require.True(t, found, "didn't find channel")
  846. search.Term = th.BasicPrivateChannel.Name
  847. channels, resp = Client.SearchChannels(th.BasicTeam.Id, search)
  848. CheckNoError(t, resp)
  849. found = false
  850. for _, c := range channels {
  851. if c.Id == th.BasicPrivateChannel.Id {
  852. found = true
  853. }
  854. }
  855. require.False(t, found, "shouldn't find private channel")
  856. search.Term = ""
  857. _, resp = Client.SearchChannels(th.BasicTeam.Id, search)
  858. CheckNoError(t, resp)
  859. search.Term = th.BasicChannel.Name
  860. _, resp = Client.SearchChannels(model.NewId(), search)
  861. CheckNotFoundStatus(t, resp)
  862. _, resp = Client.SearchChannels("junk", search)
  863. CheckBadRequestStatus(t, resp)
  864. _, resp = th.SystemAdminClient.SearchChannels(th.BasicTeam.Id, search)
  865. CheckNoError(t, resp)
  866. // Check the appropriate permissions are enforced.
  867. defaultRolePermissions := th.SaveDefaultRolePermissions()
  868. defer func() {
  869. th.RestoreDefaultRolePermissions(defaultRolePermissions)
  870. }()
  871. // Remove list channels permission from the user
  872. th.RemovePermissionFromRole(model.PERMISSION_LIST_TEAM_CHANNELS.Id, model.TEAM_USER_ROLE_ID)
  873. t.Run("Search for a BasicChannel, which the user is a member of", func(t *testing.T) {
  874. search.Term = th.BasicChannel.Name
  875. channelList, resp := Client.SearchChannels(th.BasicTeam.Id, search)
  876. CheckNoError(t, resp)
  877. channelNames := []string{}
  878. for _, c := range channelList {
  879. channelNames = append(channelNames, c.Name)
  880. }
  881. require.Contains(t, channelNames, th.BasicChannel.Name)
  882. })
  883. t.Run("Remove the user from BasicChannel and search again, should not be returned", func(t *testing.T) {
  884. th.App.RemoveUserFromChannel(th.BasicUser.Id, th.BasicUser.Id, th.BasicChannel)
  885. search.Term = th.BasicChannel.Name
  886. channelList, resp := Client.SearchChannels(th.BasicTeam.Id, search)
  887. CheckNoError(t, resp)
  888. channelNames := []string{}
  889. for _, c := range channelList {
  890. channelNames = append(channelNames, c.Name)
  891. }
  892. require.NotContains(t, channelNames, th.BasicChannel.Name)
  893. })
  894. }
  895. func TestSearchArchivedChannels(t *testing.T) {
  896. th := Setup(t).InitBasic()
  897. defer th.TearDown()
  898. Client := th.Client
  899. search := &model.ChannelSearch{Term: th.BasicChannel.Name}
  900. Client.DeleteChannel(th.BasicChannel.Id)
  901. channels, resp := Client.SearchArchivedChannels(th.BasicTeam.Id, search)
  902. CheckNoError(t, resp)
  903. found := false
  904. for _, c := range channels {
  905. require.Equal(t, model.CHANNEL_OPEN, c.Type)
  906. if c.Id == th.BasicChannel.Id {
  907. found = true
  908. }
  909. }
  910. require.True(t, found)
  911. search.Term = th.BasicPrivateChannel.Name
  912. Client.DeleteChannel(th.BasicPrivateChannel.Id)
  913. channels, resp = Client.SearchArchivedChannels(th.BasicTeam.Id, search)
  914. CheckNoError(t, resp)
  915. found = false
  916. for _, c := range channels {
  917. if c.Id == th.BasicPrivateChannel.Id {
  918. found = true
  919. }
  920. }
  921. require.True(t, found)
  922. search.Term = ""
  923. _, resp = Client.SearchArchivedChannels(th.BasicTeam.Id, search)
  924. CheckNoError(t, resp)
  925. search.Term = th.BasicDeletedChannel.Name
  926. _, resp = Client.SearchArchivedChannels(model.NewId(), search)
  927. CheckNotFoundStatus(t, resp)
  928. _, resp = Client.SearchArchivedChannels("junk", search)
  929. CheckBadRequestStatus(t, resp)
  930. _, resp = th.SystemAdminClient.SearchArchivedChannels(th.BasicTeam.Id, search)
  931. CheckNoError(t, resp)
  932. // Check the appropriate permissions are enforced.
  933. defaultRolePermissions := th.SaveDefaultRolePermissions()
  934. defer func() {
  935. th.RestoreDefaultRolePermissions(defaultRolePermissions)
  936. }()
  937. // Remove list channels permission from the user
  938. th.RemovePermissionFromRole(model.PERMISSION_LIST_TEAM_CHANNELS.Id, model.TEAM_USER_ROLE_ID)
  939. t.Run("Search for a BasicDeletedChannel, which the user is a member of", func(t *testing.T) {
  940. search.Term = th.BasicDeletedChannel.Name
  941. channelList, resp := Client.SearchArchivedChannels(th.BasicTeam.Id, search)
  942. CheckNoError(t, resp)
  943. channelNames := []string{}
  944. for _, c := range channelList {
  945. channelNames = append(channelNames, c.Name)
  946. }
  947. require.Contains(t, channelNames, th.BasicDeletedChannel.Name)
  948. })
  949. t.Run("Remove the user from BasicDeletedChannel and search again, should still return", func(t *testing.T) {
  950. th.App.RemoveUserFromChannel(th.BasicUser.Id, th.BasicUser.Id, th.BasicDeletedChannel)
  951. search.Term = th.BasicDeletedChannel.Name
  952. channelList, resp := Client.SearchArchivedChannels(th.BasicTeam.Id, search)
  953. CheckNoError(t, resp)
  954. channelNames := []string{}
  955. for _, c := range channelList {
  956. channelNames = append(channelNames, c.Name)
  957. }
  958. require.Contains(t, channelNames, th.BasicDeletedChannel.Name)
  959. })
  960. }
  961. func TestSearchAllChannels(t *testing.T) {
  962. th := Setup(t).InitBasic()
  963. defer th.TearDown()
  964. Client := th.Client
  965. openChannel, chanErr := th.SystemAdminClient.CreateChannel(&model.Channel{
  966. DisplayName: "SearchAllChannels-FOOBARDISPLAYNAME",
  967. Name: "whatever",
  968. Type: model.CHANNEL_OPEN,
  969. TeamId: th.BasicTeam.Id,
  970. })
  971. CheckNoError(t, chanErr)
  972. privateChannel, privErr := th.SystemAdminClient.CreateChannel(&model.Channel{
  973. DisplayName: "SearchAllChannels-private1",
  974. Name: "private1",
  975. Type: model.CHANNEL_PRIVATE,
  976. TeamId: th.BasicTeam.Id,
  977. })
  978. CheckNoError(t, privErr)
  979. team := th.CreateTeam()
  980. groupConstrainedChannel, groupErr := th.SystemAdminClient.CreateChannel(&model.Channel{
  981. DisplayName: "SearchAllChannels-groupConstrained-1",
  982. Name: "groupconstrained1",
  983. Type: model.CHANNEL_PRIVATE,
  984. GroupConstrained: model.NewBool(true),
  985. TeamId: team.Id,
  986. })
  987. CheckNoError(t, groupErr)
  988. th.App.UpdateConfig(func(cfg *model.Config) {
  989. *cfg.TeamSettings.ExperimentalViewArchivedChannels = true
  990. })
  991. testCases := []struct {
  992. Description string
  993. Search *model.ChannelSearch
  994. ExpectedChannelIds []string
  995. }{
  996. {
  997. "Middle of word search",
  998. &model.ChannelSearch{Term: "bardisplay"},
  999. []string{openChannel.Id},
  1000. },
  1001. {
  1002. "Prefix search",
  1003. &model.ChannelSearch{Term: "SearchAllChannels-foobar"},
  1004. []string{openChannel.Id},
  1005. },
  1006. {
  1007. "Suffix search",
  1008. &model.ChannelSearch{Term: "displayname"},
  1009. []string{openChannel.Id},
  1010. },
  1011. {
  1012. "Name search",
  1013. &model.ChannelSearch{Term: "what"},
  1014. []string{openChannel.Id},
  1015. },
  1016. {
  1017. "Name suffix search",
  1018. &model.ChannelSearch{Term: "ever"},
  1019. []string{openChannel.Id},
  1020. },
  1021. {
  1022. "Basic channel name middle of word search",
  1023. &model.ChannelSearch{Term: th.BasicChannel.Name[2:14]},
  1024. []string{th.BasicChannel.Id},
  1025. },
  1026. {
  1027. "Upper case search",
  1028. &model.ChannelSearch{Term: strings.ToUpper(th.BasicChannel.Name)},
  1029. []string{th.BasicChannel.Id},
  1030. },
  1031. {
  1032. "Mixed case search",
  1033. &model.ChannelSearch{Term: th.BasicChannel.Name[0:2] + strings.ToUpper(th.BasicChannel.Name[2:5]) + th.BasicChannel.Name[5:]},
  1034. []string{th.BasicChannel.Id},
  1035. },
  1036. {
  1037. "Non mixed case search",
  1038. &model.ChannelSearch{Term: th.BasicChannel.Name},
  1039. []string{th.BasicChannel.Id},
  1040. },
  1041. {
  1042. "Search private channel name",
  1043. &model.ChannelSearch{Term: th.BasicPrivateChannel.Name},
  1044. []string{th.BasicPrivateChannel.Id},
  1045. },
  1046. {
  1047. "Search with private channel filter",
  1048. &model.ChannelSearch{Private: true},
  1049. []string{th.BasicPrivateChannel.Id, th.BasicPrivateChannel2.Id, privateChannel.Id, groupConstrainedChannel.Id},
  1050. },
  1051. {
  1052. "Search with public channel filter",
  1053. &model.ChannelSearch{Term: "SearchAllChannels", Public: true},
  1054. []string{openChannel.Id},
  1055. },
  1056. {
  1057. "Search with private channel filter",
  1058. &model.ChannelSearch{Term: "SearchAllChannels", Private: true},
  1059. []string{privateChannel.Id, groupConstrainedChannel.Id},
  1060. },
  1061. {
  1062. "Search with teamIds channel filter",
  1063. &model.ChannelSearch{Term: "SearchAllChannels", TeamIds: []string{th.BasicTeam.Id}},
  1064. []string{openChannel.Id, privateChannel.Id},
  1065. },
  1066. {
  1067. "Search with deleted without IncludeDeleted filter",
  1068. &model.ChannelSearch{Term: th.BasicDeletedChannel.Name},
  1069. []string{},
  1070. },
  1071. {
  1072. "Search with deleted IncludeDeleted filter",
  1073. &model.ChannelSearch{Term: th.BasicDeletedChannel.Name, IncludeDeleted: true},
  1074. []string{th.BasicDeletedChannel.Id},
  1075. },
  1076. {
  1077. "Search with deleted IncludeDeleted filter",
  1078. &model.ChannelSearch{Term: th.BasicDeletedChannel.Name, IncludeDeleted: true},
  1079. []string{th.BasicDeletedChannel.Id},
  1080. },
  1081. {
  1082. "Search with deleted Deleted filter and empty term",
  1083. &model.ChannelSearch{Term: "", Deleted: true},
  1084. []string{th.BasicDeletedChannel.Id},
  1085. },
  1086. {
  1087. "Search for group constrained",
  1088. &model.ChannelSearch{Term: "SearchAllChannels", GroupConstrained: true},
  1089. []string{groupConstrainedChannel.Id},
  1090. },
  1091. {
  1092. "Search for group constrained and public",
  1093. &model.ChannelSearch{Term: "SearchAllChannels", GroupConstrained: true, Public: true},
  1094. []string{},
  1095. },
  1096. {
  1097. "Search for exclude group constrained",
  1098. &model.ChannelSearch{Term: "SearchAllChannels", ExcludeGroupConstrained: true},
  1099. []string{openChannel.Id, privateChannel.Id},
  1100. },
  1101. }
  1102. for _, testCase := range testCases {
  1103. t.Run(testCase.Description, func(t *testing.T) {
  1104. channels, resp := th.SystemAdminClient.SearchAllChannels(testCase.Search)
  1105. CheckNoError(t, resp)
  1106. assert.Equal(t, len(testCase.ExpectedChannelIds), len(*channels))
  1107. actualChannelIds := []string{}
  1108. for _, channelWithTeamData := range *channels {
  1109. actualChannelIds = append(actualChannelIds, channelWithTeamData.Channel.Id)
  1110. }
  1111. assert.ElementsMatch(t, testCase.ExpectedChannelIds, actualChannelIds)
  1112. })
  1113. }
  1114. // Searching with no terms returns all default channels
  1115. allChannels, resp := th.SystemAdminClient.SearchAllChannels(&model.ChannelSearch{Term: ""})
  1116. CheckNoError(t, resp)
  1117. assert.True(t, len(*allChannels) >= 3)
  1118. _, resp = Client.SearchAllChannels(&model.ChannelSearch{Term: ""})
  1119. CheckForbiddenStatus(t, resp)
  1120. }
  1121. func TestSearchAllChannelsPaged(t *testing.T) {
  1122. th := Setup(t).InitBasic()
  1123. defer th.TearDown()
  1124. Client := th.Client
  1125. search := &model.ChannelSearch{Term: th.BasicChannel.Name}
  1126. search.Term = ""
  1127. search.Page = model.NewInt(0)
  1128. search.PerPage = model.NewInt(2)
  1129. channelsWithCount, resp := th.SystemAdminClient.SearchAllChannelsPaged(search)
  1130. CheckNoError(t, resp)
  1131. require.Len(t, *channelsWithCount.Channels, 2)
  1132. search.Term = th.BasicChannel.Name
  1133. _, resp = Client.SearchAllChannels(search)
  1134. CheckForbiddenStatus(t, resp)
  1135. }
  1136. func TestSearchGroupChannels(t *testing.T) {
  1137. th := Setup(t).InitBasic()
  1138. defer th.TearDown()
  1139. Client := th.Client
  1140. u1 := th.CreateUserWithClient(th.SystemAdminClient)
  1141. // Create a group channel in which base user belongs but not sysadmin
  1142. gc1, resp := th.Client.CreateGroupChannel([]string{th.BasicUser.Id, th.BasicUser2.Id, u1.Id})
  1143. CheckNoError(t, resp)
  1144. defer th.Client.DeleteChannel(gc1.Id)
  1145. gc2, resp := th.Client.CreateGroupChannel([]string{th.BasicUser.Id, th.BasicUser2.Id, th.SystemAdminUser.Id})
  1146. CheckNoError(t, resp)
  1147. defer th.Client.DeleteChannel(gc2.Id)
  1148. search := &model.ChannelSearch{Term: th.BasicUser2.Username}
  1149. // sysadmin should only find gc2 as he doesn't belong to gc1
  1150. channels, resp := th.SystemAdminClient.SearchGroupChannels(search)
  1151. CheckNoError(t, resp)
  1152. assert.Len(t, channels, 1)
  1153. assert.Equal(t, channels[0].Id, gc2.Id)
  1154. // basic user should find both
  1155. Client.Login(th.BasicUser.Username, th.BasicUser.Password)
  1156. channels, resp = Client.SearchGroupChannels(search)
  1157. CheckNoError(t, resp)
  1158. assert.Len(t, channels, 2)
  1159. channelIds := []string{}
  1160. for _, c := range channels {
  1161. channelIds = append(channelIds, c.Id)
  1162. }
  1163. assert.ElementsMatch(t, channelIds, []string{gc1.Id, gc2.Id})
  1164. // searching for sysadmin, it should only find gc1
  1165. search = &model.ChannelSearch{Term: th.SystemAdminUser.Username}
  1166. channels, resp = Client.SearchGroupChannels(search)
  1167. CheckNoError(t, resp)
  1168. assert.Len(t, channels, 1)
  1169. assert.Equal(t, channels[0].Id, gc2.Id)
  1170. // with an empty search, response should be empty
  1171. search = &model.ChannelSearch{Term: ""}
  1172. channels, resp = Client.SearchGroupChannels(search)
  1173. CheckNoError(t, resp)
  1174. assert.Empty(t, channels)
  1175. // search unprivileged, forbidden
  1176. th.Client.Logout()
  1177. _, resp = Client.SearchAllChannels(search)
  1178. CheckUnauthorizedStatus(t, resp)
  1179. }
  1180. func TestDeleteChannel(t *testing.T) {
  1181. th := Setup(t).InitBasic()
  1182. defer th.TearDown()
  1183. c := th.Client
  1184. team := th.BasicTeam
  1185. user := th.BasicUser
  1186. user2 := th.BasicUser2
  1187. // successful delete of public channel
  1188. th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
  1189. publicChannel1 := th.CreatePublicChannel()
  1190. pass, resp := client.DeleteChannel(publicChannel1.Id)
  1191. CheckNoError(t, resp)
  1192. require.True(t, pass, "should have passed")
  1193. ch, err := th.App.GetChannel(publicChannel1.Id)
  1194. require.True(t, err != nil || ch.DeleteAt != 0, "should have failed to get deleted channel, or returned one with a populated DeleteAt.")
  1195. post1 := &model.Post{ChannelId: publicChannel1.Id, Message: "a" + GenerateTestId() + "a"}
  1196. _, resp = client.CreatePost(post1)
  1197. require.NotNil(t, resp, "expected response to not be nil")
  1198. // successful delete of private channel
  1199. privateChannel2 := th.CreatePrivateChannel()
  1200. _, resp = client.DeleteChannel(privateChannel2.Id)
  1201. CheckNoError(t, resp)
  1202. // successful delete of channel with multiple members
  1203. publicChannel3 := th.CreatePublicChannel()
  1204. th.App.AddUserToChannel(user, publicChannel3)
  1205. th.App.AddUserToChannel(user2, publicChannel3)
  1206. _, resp = client.DeleteChannel(publicChannel3.Id)
  1207. CheckNoError(t, resp)
  1208. // default channel cannot be deleted.
  1209. defaultChannel, _ := th.App.GetChannelByName(model.DEFAULT_CHANNEL, team.Id, false)
  1210. pass, resp = client.DeleteChannel(defaultChannel.Id)
  1211. CheckBadRequestStatus(t, resp)
  1212. require.False(t, pass, "should have failed")
  1213. // check system admin can delete a channel without any appropriate team or channel membership.
  1214. sdTeam := th.CreateTeamWithClient(c)
  1215. sdPublicChannel := &model.Channel{
  1216. DisplayName: "dn_" + model.NewId(),
  1217. Name: GenerateTestChannelName(),
  1218. Type: model.CHANNEL_OPEN,
  1219. TeamId: sdTeam.Id,
  1220. }
  1221. sdPublicChannel, resp = c.CreateChannel(sdPublicChannel)
  1222. CheckNoError(t, resp)
  1223. _, resp = client.DeleteChannel(sdPublicChannel.Id)
  1224. CheckNoError(t, resp)
  1225. sdPrivateChannel := &model.Channel{
  1226. DisplayName: "dn_" + model.NewId(),
  1227. Name: GenerateTestChannelName(),
  1228. Type: model.CHANNEL_PRIVATE,
  1229. TeamId: sdTeam.Id,
  1230. }
  1231. sdPrivateChannel, resp = c.CreateChannel(sdPrivateChannel)
  1232. CheckNoError(t, resp)
  1233. _, resp = client.DeleteChannel(sdPrivateChannel.Id)
  1234. CheckNoError(t, resp)
  1235. })
  1236. th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
  1237. th.LoginBasic()
  1238. publicChannel5 := th.CreatePublicChannel()
  1239. c.Logout()
  1240. c.Login(user.Id, user.Password)
  1241. _, resp := c.DeleteChannel(publicChannel5.Id)
  1242. CheckUnauthorizedStatus(t, resp)
  1243. _, resp = c.DeleteChannel("junk")
  1244. CheckUnauthorizedStatus(t, resp)
  1245. c.Logout()
  1246. _, resp = c.DeleteChannel(GenerateTestId())
  1247. CheckUnauthorizedStatus(t, resp)
  1248. _, resp = client.DeleteChannel(publicChannel5.Id)
  1249. CheckNoError(t, resp)
  1250. })
  1251. }
  1252. func TestDeleteChannel2(t *testing.T) {
  1253. th := Setup(t).InitBasic()
  1254. defer th.TearDown()
  1255. Client := th.Client
  1256. user := th.BasicUser
  1257. // Check the appropriate permissions are enforced.
  1258. defaultRolePermissions := th.SaveDefaultRolePermissions()
  1259. defer func() {
  1260. th.RestoreDefaultRolePermissions(defaultRolePermissions)
  1261. }()
  1262. th.AddPermissionToRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID)
  1263. th.AddPermissionToRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID)
  1264. // channels created by SystemAdmin
  1265. publicChannel6 := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_OPEN)
  1266. privateChannel7 := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE)
  1267. th.App.AddUserToChannel(user, publicChannel6)
  1268. th.App.AddUserToChannel(user, privateChannel7)
  1269. th.App.AddUserToChannel(user, privateChannel7)
  1270. // successful delete by user
  1271. _, resp := Client.DeleteChannel(publicChannel6.Id)
  1272. CheckNoError(t, resp)
  1273. _, resp = Client.DeleteChannel(privateChannel7.Id)
  1274. CheckNoError(t, resp)
  1275. // Restrict permissions to Channel Admins
  1276. th.RemovePermissionFromRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID)
  1277. th.RemovePermissionFromRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID)
  1278. th.AddPermissionToRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID)
  1279. th.AddPermissionToRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID)
  1280. // channels created by SystemAdmin
  1281. publicChannel6 = th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_OPEN)
  1282. privateChannel7 = th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE)
  1283. th.App.AddUserToChannel(user, publicChannel6)
  1284. th.App.AddUserToChannel(user, privateChannel7)
  1285. th.App.AddUserToChannel(user, privateChannel7)
  1286. // cannot delete by user
  1287. _, resp = Client.DeleteChannel(publicChannel6.Id)
  1288. CheckForbiddenStatus(t, resp)
  1289. _, resp = Client.DeleteChannel(privateChannel7.Id)
  1290. CheckForbiddenStatus(t, resp)
  1291. // successful delete by channel admin
  1292. th.MakeUserChannelAdmin(user, publicChannel6)
  1293. th.MakeUserChannelAdmin(user, privateChannel7)
  1294. th.App.Srv().Store.Channel().ClearCaches()
  1295. _, resp = Client.DeleteChannel(publicChannel6.Id)
  1296. CheckNoError(t, resp)
  1297. _, resp = Client.DeleteChannel(privateChannel7.Id)
  1298. CheckNoError(t, resp)
  1299. // Make sure team admins don't have permission to delete channels.
  1300. th.RemovePermissionFromRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID)
  1301. th.RemovePermissionFromRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID)
  1302. // last member of a public channel should have required permission to delete
  1303. publicChannel6 = th.CreateChannelWithClient(th.Client, model.CHANNEL_OPEN)
  1304. _, resp = Client.DeleteChannel(publicChannel6.Id)
  1305. CheckForbiddenStatus(t, resp)
  1306. // last member of a private channel should not be able to delete it if they don't have required permissions
  1307. privateChannel7 = th.CreateChannelWithClient(th.Client, model.CHANNEL_PRIVATE)
  1308. _, resp = Client.DeleteChannel(privateChannel7.Id)
  1309. CheckForbiddenStatus(t, resp)
  1310. }
  1311. func TestConvertChannelToPrivate(t *testing.T) {
  1312. th := Setup(t).InitBasic()
  1313. defer th.TearDown()
  1314. Client := th.Client
  1315. defaultChannel, _ := th.App.GetChannelByName(model.DEFAULT_CHANNEL, th.BasicTeam.Id, false)
  1316. _, resp := Client.ConvertChannelToPrivate(defaultChannel.Id)
  1317. CheckForbiddenStatus(t, resp)
  1318. privateChannel := th.CreatePrivateChannel()
  1319. _, resp = Client.ConvertChannelToPrivate(privateChannel.Id)
  1320. CheckForbiddenStatus(t, resp)
  1321. publicChannel := th.CreatePublicChannel()
  1322. _, resp = Client.ConvertChannelToPrivate(publicChannel.Id)
  1323. CheckForbiddenStatus(t, resp)
  1324. th.LoginTeamAdmin()
  1325. rchannel, resp := Client.ConvertChannelToPrivate(publicChannel.Id)
  1326. CheckOKStatus(t, resp)
  1327. require.Equal(t, model.CHANNEL_PRIVATE, rchannel.Type, "channel should be converted from public to private")
  1328. rchannel, resp = th.SystemAdminClient.ConvertChannelToPrivate(privateChannel.Id)
  1329. CheckBadRequestStatus(t, resp)
  1330. require.Nil(t, rchannel, "should not return a channel")
  1331. rchannel, resp = th.SystemAdminClient.ConvertChannelToPrivate(defaultChannel.Id)
  1332. CheckBadRequestStatus(t, resp)
  1333. require.Nil(t, rchannel, "should not return a channel")
  1334. WebSocketClient, err := th.CreateWebSocketClient()
  1335. require.Nil(t, err)
  1336. WebSocketClient.Listen()
  1337. publicChannel2 := th.CreatePublicChannel()
  1338. rchannel, resp = th.SystemAdminClient.ConvertChannelToPrivate(publicChannel2.Id)
  1339. CheckOKStatus(t, resp)
  1340. require.Equal(t, model.CHANNEL_PRIVATE, rchannel.Type, "channel should be converted from public to private")
  1341. stop := make(chan bool)
  1342. eventHit := false
  1343. go func() {
  1344. for {
  1345. select {
  1346. case resp := <-WebSocketClient.EventChannel:
  1347. if resp.EventType() == model.WEBSOCKET_EVENT_CHANNEL_CONVERTED && resp.GetData()["channel_id"].(string) == publicChannel2.Id {
  1348. eventHit = true
  1349. }
  1350. case <-stop:
  1351. return
  1352. }
  1353. }
  1354. }()
  1355. time.Sleep(400 * time.Millisecond)
  1356. stop <- true
  1357. require.True(t, eventHit, "did not receive channel_converted event")
  1358. }
  1359. func TestUpdateChannelPrivacy(t *testing.T) {
  1360. th := Setup(t).InitBasic()
  1361. defer th.TearDown()
  1362. Client := th.Client
  1363. type testTable []struct {
  1364. name string
  1365. channel *model.Channel
  1366. expectedPrivacy string
  1367. }
  1368. defaultChannel, _ := th.App.GetChannelByName(model.DEFAULT_CHANNEL, th.BasicTeam.Id, false)
  1369. privateChannel := th.CreatePrivateChannel()
  1370. publicChannel := th.CreatePublicChannel()
  1371. tt := testTable{
  1372. {"Updating default channel should fail with forbidden status if not logged in", defaultChannel, model.CHANNEL_OPEN},
  1373. {"Updating private channel should fail with forbidden status if not logged in", privateChannel, model.CHANNEL_PRIVATE},
  1374. {"Updating public channel should fail with forbidden status if not logged in", publicChannel, model.CHANNEL_OPEN},
  1375. }
  1376. for _, tc := range tt {
  1377. t.Run(tc.name, func(t *testing.T) {
  1378. _, resp := Client.UpdateChannelPrivacy(tc.channel.Id, tc.expectedPrivacy)
  1379. CheckForbiddenStatus(t, resp)
  1380. })
  1381. }
  1382. th.LoginTeamAdmin()
  1383. tt = testTable{
  1384. {"Converting default channel to private should fail", defaultChannel, model.CHANNEL_PRIVATE},
  1385. {"Updating privacy to an invalid setting should fail", publicChannel, "invalid"},
  1386. }
  1387. for _, tc := range tt {
  1388. t.Run(tc.name, func(t *testing.T) {
  1389. _, resp := Client.UpdateChannelPrivacy(tc.channel.Id, tc.expectedPrivacy)
  1390. CheckBadRequestStatus(t, resp)
  1391. })
  1392. }
  1393. tt = testTable{
  1394. {"Default channel should stay public", defaultChannel, model.CHANNEL_OPEN},
  1395. {"Public channel should stay public", publicChannel, model.CHANNEL_OPEN},
  1396. {"Private channel should stay private", privateChannel, model.CHANNEL_PRIVATE},
  1397. {"Public channel should convert to private", publicChannel, model.CHANNEL_PRIVATE},
  1398. {"Private channel should convert to public", privateChannel, model.CHANNEL_OPEN},
  1399. }
  1400. for _, tc := range tt {
  1401. t.Run(tc.name, func(t *testing.T) {
  1402. updatedChannel, resp := Client.UpdateChannelPrivacy(tc.channel.Id, tc.expectedPrivacy)
  1403. CheckNoError(t, resp)
  1404. assert.Equal(t, tc.expectedPrivacy, updatedChannel.Type)
  1405. updatedChannel, err := th.App.GetChannel(tc.channel.Id)
  1406. require.Nil(t, err)
  1407. assert.Equal(t, tc.expectedPrivacy, updatedChannel.Type)
  1408. })
  1409. }
  1410. }
  1411. func TestRestoreChannel(t *testing.T) {
  1412. th := Setup(t).InitBasic()
  1413. defer th.TearDown()
  1414. Client := th.Client
  1415. publicChannel1 := th.CreatePublicChannel()
  1416. Client.DeleteChannel(publicChannel1.Id)
  1417. privateChannel1 := th.CreatePrivateChannel()
  1418. Client.DeleteChannel(privateChannel1.Id)
  1419. _, resp := Client.RestoreChannel(publicChannel1.Id)
  1420. CheckForbiddenStatus(t, resp)
  1421. _, resp = Client.RestoreChannel(privateChannel1.Id)
  1422. CheckForbiddenStatus(t, resp)
  1423. th.LoginTeamAdmin()
  1424. _, resp = Client.RestoreChannel(publicChannel1.Id)
  1425. CheckOKStatus(t, resp)
  1426. _, resp = Client.RestoreChannel(privateChannel1.Id)
  1427. CheckOKStatus(t, resp)
  1428. }
  1429. func TestGetChannelByName(t *testing.T) {
  1430. th := Setup(t).InitBasic()
  1431. defer th.TearDown()
  1432. Client := th.Client
  1433. channel, resp := Client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
  1434. CheckNoError(t, resp)
  1435. require.Equal(t, th.BasicChannel.Name, channel.Name, "names did not match")
  1436. channel, resp = Client.GetChannelByName(th.BasicPrivateChannel.Name, th.BasicTeam.Id, "")
  1437. CheckNoError(t, resp)
  1438. require.Equal(t, th.BasicPrivateChannel.Name, channel.Name, "names did not match")
  1439. _, resp = Client.GetChannelByName(strings.ToUpper(th.BasicPrivateChannel.Name), th.BasicTeam.Id, "")
  1440. CheckNoError(t, resp)
  1441. _, resp = Client.GetChannelByName(th.BasicDeletedChannel.Name, th.BasicTeam.Id, "")
  1442. CheckNotFoundStatus(t, resp)
  1443. channel, resp = Client.GetChannelByNameIncludeDeleted(th.BasicDeletedChannel.Name, th.BasicTeam.Id, "")
  1444. CheckNoError(t, resp)
  1445. require.Equal(t, th.BasicDeletedChannel.Name, channel.Name, "names did not match")
  1446. Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
  1447. _, resp = Client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
  1448. CheckNoError(t, resp)
  1449. Client.RemoveUserFromChannel(th.BasicPrivateChannel.Id, th.BasicUser.Id)
  1450. _, resp = Client.GetChannelByName(th.BasicPrivateChannel.Name, th.BasicTeam.Id, "")
  1451. CheckNotFoundStatus(t, resp)
  1452. _, resp = Client.GetChannelByName(GenerateTestChannelName(), th.BasicTeam.Id, "")
  1453. CheckNotFoundStatus(t, resp)
  1454. _, resp = Client.GetChannelByName(GenerateTestChannelName(), "junk", "")
  1455. CheckBadRequestStatus(t, resp)
  1456. Client.Logout()
  1457. _, resp = Client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
  1458. CheckUnauthorizedStatus(t, resp)
  1459. user := th.CreateUser()
  1460. Client.Login(user.Email, user.Password)
  1461. _, resp = Client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
  1462. CheckForbiddenStatus(t, resp)
  1463. th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
  1464. _, resp = client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
  1465. CheckNoError(t, resp)
  1466. })
  1467. }
  1468. func TestGetChannelByNameForTeamName(t *testing.T) {
  1469. th := Setup(t).InitBasic()
  1470. defer th.TearDown()
  1471. Client := th.Client
  1472. channel, resp := th.SystemAdminClient.GetChannelByNameForTeamName(th.BasicChannel.Name, th.BasicTeam.Name, "")
  1473. CheckNoError(t, resp)
  1474. require.Equal(t, th.BasicChannel.Name, channel.Name, "names did not match")
  1475. _, resp = Client.GetChannelByNameForTeamName(th.BasicChannel.Name, th.BasicTeam.Name, "")
  1476. CheckNoError(t, resp)
  1477. _, resp = Client.GetChannelByNameForTeamName(th.BasicDeletedChannel.Name, th.BasicTeam.Name, "")
  1478. CheckNotFoundStatus(t, resp)
  1479. channel, resp = Client.GetChannelByNameForTeamNameIncludeDeleted(th.BasicDeletedChannel.Name, th.BasicTeam.Name, "")
  1480. CheckNoError(t, resp)
  1481. require.Equal(t, th.BasicDeletedChannel.Name, channel.Name, "names did not match")
  1482. _, resp = Client.GetChannelByNameForTeamName(th.BasicChannel.Name, model.NewRandomString(15), "")
  1483. CheckNotFoundStatus(t, resp)
  1484. _, resp = Client.GetChannelByNameForTeamName(GenerateTestChannelName(), th.BasicTeam.Name, "")
  1485. CheckNotFoundStatus(t, resp)
  1486. Client.Logout()
  1487. _, resp = Client.GetChannelByNameForTeamName(th.BasicChannel.Name, th.BasicTeam.Name, "")
  1488. CheckUnauthorizedStatus(t, resp)
  1489. user := th.CreateUser()
  1490. Client.Login(user.Email, user.Password)
  1491. _, resp = Client.GetChannelByNameForTeamName(th.BasicChannel.Name, th.BasicTeam.Name, "")
  1492. CheckNotFoundStatus(t, resp)
  1493. }
  1494. func TestGetChannelMembers(t *testing.T) {
  1495. th := Setup(t).InitBasic()
  1496. defer th.TearDown()
  1497. th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
  1498. members, resp := client.GetChannelMembers(th.BasicChannel.Id, 0, 60, "")
  1499. CheckNoError(t, resp)
  1500. require.Len(t, *members, 3, "should only be 3 users in channel")
  1501. members, resp = client.GetChannelMembers(th.BasicChannel.Id, 0, 2, "")
  1502. CheckNoError(t, resp)
  1503. require.Len(t, *members, 2, "should only be 2 users")
  1504. members, resp = client.GetChannelMembers(th.BasicChannel.Id, 1, 1, "")
  1505. CheckNoError(t, resp)
  1506. require.Len(t, *members, 1, "should only be 1 user")
  1507. members, resp = client.GetChannelMembers(th.BasicChannel.Id, 1000, 100000, "")
  1508. CheckNoError(t, resp)
  1509. require.Empty(t, *members, "should be 0 users")
  1510. _, resp = client.GetChannelMembers("junk", 0, 60, "")
  1511. CheckBadRequestStatus(t, resp)
  1512. _, resp = client.GetChannelMembers("", 0, 60, "")
  1513. CheckBadRequestStatus(t, resp)
  1514. _, resp = client.GetChannelMembers(th.BasicChannel.Id, 0, 60, "")
  1515. CheckNoError(t, resp)
  1516. })
  1517. _, resp := th.Client.GetChannelMembers(model.NewId(), 0, 60, "")
  1518. CheckForbiddenStatus(t, resp)
  1519. th.Client.Logout()
  1520. _, resp = th.Client.GetChannelMembers(th.BasicChannel.Id, 0, 60, "")
  1521. CheckUnauthorizedStatus(t, resp)
  1522. user := th.CreateUser()
  1523. th.Client.Login(user.Email, user.Password)
  1524. _, resp = th.Client.GetChannelMembers(th.BasicChannel.Id, 0, 60, "")
  1525. CheckForbiddenStatus(t, resp)
  1526. }
  1527. func TestGetChannelMembersByIds(t *testing.T) {
  1528. th := Setup(t).InitBasic()
  1529. defer th.TearDown()
  1530. Client := th.Client
  1531. cm, resp := Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{th.BasicUser.Id})
  1532. CheckNoError(t, resp)
  1533. require.Equal(t, th.BasicUser.Id, (*cm)[0].UserId, "returned wrong user")
  1534. _, resp = Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{})
  1535. CheckBadRequestStatus(t, resp)
  1536. cm1, resp := Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{"junk"})
  1537. CheckNoError(t, resp)
  1538. require.Empty(t, *cm1, "no users should be returned")
  1539. cm1, resp = Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{"junk", th.BasicUser.Id})
  1540. CheckNoError(t, resp)
  1541. require.Len(t, *cm1, 1, "1 member should be returned")
  1542. cm1, resp = Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{th.BasicUser2.Id, th.BasicUser.Id})
  1543. CheckNoError(t, resp)
  1544. require.Len(t, *cm1, 2, "2 members should be returned")
  1545. _, resp = Client.GetChannelMembersByIds("junk", []string{th.BasicUser.Id})
  1546. CheckBadRequestStatus(t, resp)
  1547. _, resp = Client.GetChannelMembersByIds(model.NewId(), []string{th.BasicUser.Id})
  1548. CheckForbiddenStatus(t, resp)
  1549. Client.Logout()
  1550. _, resp = Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{th.BasicUser.Id})
  1551. CheckUnauthorizedStatus(t, resp)
  1552. _, resp = th.SystemAdminClient.GetChannelMembersByIds(th.BasicChannel.Id, []string{th.BasicUser2.Id, th.BasicUser.Id})
  1553. CheckNoError(t, resp)
  1554. }
  1555. func TestGetChannelMember(t *testing.T) {
  1556. th := Setup(t).InitBasic()
  1557. defer th.TearDown()
  1558. c := th.Client
  1559. th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
  1560. member, resp := client.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1561. CheckNoError(t, resp)
  1562. require.Equal(t, th.BasicChannel.Id, member.ChannelId, "wrong channel id")
  1563. require.Equal(t, th.BasicUser.Id, member.UserId, "wrong user id")
  1564. _, resp = client.GetChannelMember("", th.BasicUser.Id, "")
  1565. CheckNotFoundStatus(t, resp)
  1566. _, resp = client.GetChannelMember("junk", th.BasicUser.Id, "")
  1567. CheckBadRequestStatus(t, resp)
  1568. _, resp = client.GetChannelMember(th.BasicChannel.Id, "", "")
  1569. CheckNotFoundStatus(t, resp)
  1570. _, resp = client.GetChannelMember(th.BasicChannel.Id, "junk", "")
  1571. CheckBadRequestStatus(t, resp)
  1572. _, resp = client.GetChannelMember(th.BasicChannel.Id, model.NewId(), "")
  1573. CheckNotFoundStatus(t, resp)
  1574. _, resp = client.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1575. CheckNoError(t, resp)
  1576. })
  1577. _, resp := c.GetChannelMember(model.NewId(), th.BasicUser.Id, "")
  1578. CheckForbiddenStatus(t, resp)
  1579. c.Logout()
  1580. _, resp = c.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1581. CheckUnauthorizedStatus(t, resp)
  1582. user := th.CreateUser()
  1583. c.Login(user.Email, user.Password)
  1584. _, resp = c.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1585. CheckForbiddenStatus(t, resp)
  1586. }
  1587. func TestGetChannelMembersForUser(t *testing.T) {
  1588. th := Setup(t).InitBasic()
  1589. defer th.TearDown()
  1590. Client := th.Client
  1591. members, resp := Client.GetChannelMembersForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
  1592. CheckNoError(t, resp)
  1593. require.Len(t, *members, 6, "should have 6 members on team")
  1594. _, resp = Client.GetChannelMembersForUser("", th.BasicTeam.Id, "")
  1595. CheckNotFoundStatus(t, resp)
  1596. _, resp = Client.GetChannelMembersForUser("junk", th.BasicTeam.Id, "")
  1597. CheckBadRequestStatus(t, resp)
  1598. _, resp = Client.GetChannelMembersForUser(model.NewId(), th.BasicTeam.Id, "")
  1599. CheckForbiddenStatus(t, resp)
  1600. _, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, "", "")
  1601. CheckNotFoundStatus(t, resp)
  1602. _, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, "junk", "")
  1603. CheckBadRequestStatus(t, resp)
  1604. _, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, model.NewId(), "")
  1605. CheckForbiddenStatus(t, resp)
  1606. Client.Logout()
  1607. _, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
  1608. CheckUnauthorizedStatus(t, resp)
  1609. user := th.CreateUser()
  1610. Client.Login(user.Email, user.Password)
  1611. _, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
  1612. CheckForbiddenStatus(t, resp)
  1613. _, resp = th.SystemAdminClient.GetChannelMembersForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
  1614. CheckNoError(t, resp)
  1615. }
  1616. func TestViewChannel(t *testing.T) {
  1617. th := Setup(t).InitBasic()
  1618. defer th.TearDown()
  1619. Client := th.Client
  1620. view := &model.ChannelView{
  1621. ChannelId: th.BasicChannel.Id,
  1622. }
  1623. viewResp, resp := Client.ViewChannel(th.BasicUser.Id, view)
  1624. CheckNoError(t, resp)
  1625. require.Equal(t, "OK", viewResp.Status, "should have passed")
  1626. channel, _ := th.App.GetChannel(th.BasicChannel.Id)
  1627. require.Equal(t, channel.LastPostAt, viewResp.LastViewedAtTimes[channel.Id], "LastPostAt does not match returned LastViewedAt time")
  1628. view.PrevChannelId = th.BasicChannel.Id
  1629. _, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1630. CheckNoError(t, resp)
  1631. view.PrevChannelId = ""
  1632. _, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1633. CheckNoError(t, resp)
  1634. view.PrevChannelId = "junk"
  1635. _, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1636. CheckBadRequestStatus(t, resp)
  1637. // All blank is OK we use it for clicking off of the browser.
  1638. view.PrevChannelId = ""
  1639. view.ChannelId = ""
  1640. _, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1641. CheckNoError(t, resp)
  1642. view.PrevChannelId = ""
  1643. view.ChannelId = "junk"
  1644. _, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1645. CheckBadRequestStatus(t, resp)
  1646. view.ChannelId = "correctlysizedjunkdddfdfdf"
  1647. _, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1648. CheckBadRequestStatus(t, resp)
  1649. view.ChannelId = th.BasicChannel.Id
  1650. member, resp := Client.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1651. CheckNoError(t, resp)
  1652. channel, resp = Client.GetChannel(th.BasicChannel.Id, "")
  1653. CheckNoError(t, resp)
  1654. require.Equal(t, channel.TotalMsgCount, member.MsgCount, "should match message counts")
  1655. require.Equal(t, int64(0), member.MentionCount, "should have no mentions")
  1656. _, resp = Client.ViewChannel("junk", view)
  1657. CheckBadRequestStatus(t, resp)
  1658. _, resp = Client.ViewChannel(th.BasicUser2.Id, view)
  1659. CheckForbiddenStatus(t, resp)
  1660. r, err := Client.DoApiPost(fmt.Sprintf("/channels/members/%v/view", th.BasicUser.Id), "garbage")
  1661. require.NotNil(t, err)
  1662. require.Equal(t, http.StatusBadRequest, r.StatusCode)
  1663. Client.Logout()
  1664. _, resp = Client.ViewChannel(th.BasicUser.Id, view)
  1665. CheckUnauthorizedStatus(t, resp)
  1666. _, resp = th.SystemAdminClient.ViewChannel(th.BasicUser.Id, view)
  1667. CheckNoError(t, resp)
  1668. }
  1669. func TestGetChannelUnread(t *testing.T) {
  1670. th := Setup(t).InitBasic()
  1671. defer th.TearDown()
  1672. Client := th.Client
  1673. user := th.BasicUser
  1674. channel := th.BasicChannel
  1675. channelUnread, resp := Client.GetChannelUnread(channel.Id, user.Id)
  1676. CheckNoError(t, resp)
  1677. require.Equal(t, th.BasicTeam.Id, channelUnread.TeamId, "wrong team id returned for a regular user call")
  1678. require.Equal(t, channel.Id, channelUnread.ChannelId, "wrong team id returned for a regular user call")
  1679. _, resp = Client.GetChannelUnread("junk", user.Id)
  1680. CheckBadRequestStatus(t, resp)
  1681. _, resp = Client.GetChannelUnread(channel.Id, "junk")
  1682. CheckBadRequestStatus(t, resp)
  1683. _, resp = Client.GetChannelUnread(channel.Id, model.NewId())
  1684. CheckForbiddenStatus(t, resp)
  1685. _, resp = Client.GetChannelUnread(model.NewId(), user.Id)
  1686. CheckForbiddenStatus(t, resp)
  1687. newUser := th.CreateUser()
  1688. Client.Login(newUser.Email, newUser.Password)
  1689. _, resp = Client.GetChannelUnread(th.BasicChannel.Id, user.Id)
  1690. CheckForbiddenStatus(t, resp)
  1691. Client.Logout()
  1692. _, resp = th.SystemAdminClient.GetChannelUnread(channel.Id, user.Id)
  1693. CheckNoError(t, resp)
  1694. _, resp = th.SystemAdminClient.GetChannelUnread(model.NewId(), user.Id)
  1695. CheckForbiddenStatus(t, resp)
  1696. _, resp = th.SystemAdminClient.GetChannelUnread(channel.Id, model.NewId())
  1697. CheckNotFoundStatus(t, resp)
  1698. }
  1699. func TestGetChannelStats(t *testing.T) {
  1700. th := Setup(t).InitBasic()
  1701. defer th.TearDown()
  1702. Client := th.Client
  1703. channel := th.CreatePrivateChannel()
  1704. stats, resp := Client.GetChannelStats(channel.Id, "")
  1705. CheckNoError(t, resp)
  1706. require.Equal(t, channel.Id, stats.ChannelId, "couldnt't get extra info")
  1707. require.Equal(t, int64(1), stats.MemberCount, "got incorrect member count")
  1708. require.Equal(t, int64(0), stats.PinnedPostCount, "got incorrect pinned post count")
  1709. th.CreatePinnedPostWithClient(th.Client, channel)
  1710. stats, resp = Client.GetChannelStats(channel.Id, "")
  1711. CheckNoError(t, resp)
  1712. require.Equal(t, int64(1), stats.PinnedPostCount, "should have returned 1 pinned post count")
  1713. _, resp = Client.GetChannelStats("junk", "")
  1714. CheckBadRequestStatus(t, resp)
  1715. _, resp = Client.GetChannelStats(model.NewId(), "")
  1716. CheckForbiddenStatus(t, resp)
  1717. Client.Logout()
  1718. _, resp = Client.GetChannelStats(channel.Id, "")
  1719. CheckUnauthorizedStatus(t, resp)
  1720. th.LoginBasic2()
  1721. _, resp = Client.GetChannelStats(channel.Id, "")
  1722. CheckForbiddenStatus(t, resp)
  1723. _, resp = th.SystemAdminClient.GetChannelStats(channel.Id, "")
  1724. CheckNoError(t, resp)
  1725. }
  1726. func TestGetPinnedPosts(t *testing.T) {
  1727. th := Setup(t).InitBasic()
  1728. defer th.TearDown()
  1729. Client := th.Client
  1730. channel := th.BasicChannel
  1731. posts, resp := Client.GetPinnedPosts(channel.Id, "")
  1732. CheckNoError(t, resp)
  1733. require.Empty(t, posts.Posts, "should not have gotten a pinned post")
  1734. pinnedPost := th.CreatePinnedPost()
  1735. posts, resp = Client.GetPinnedPosts(channel.Id, "")
  1736. CheckNoError(t, resp)
  1737. require.Len(t, posts.Posts, 1, "should have returned 1 pinned post")
  1738. require.Contains(t, posts.Posts, pinnedPost.Id, "missing pinned post")
  1739. posts, resp = Client.GetPinnedPosts(channel.Id, resp.Etag)
  1740. CheckEtag(t, posts, resp)
  1741. _, resp = Client.GetPinnedPosts(GenerateTestId(), "")
  1742. CheckForbiddenStatus(t, resp)
  1743. _, resp = Client.GetPinnedPosts("junk", "")
  1744. CheckBadRequestStatus(t, resp)
  1745. Client.Logout()
  1746. _, resp = Client.GetPinnedPosts(channel.Id, "")
  1747. CheckUnauthorizedStatus(t, resp)
  1748. _, resp = th.SystemAdminClient.GetPinnedPosts(channel.Id, "")
  1749. CheckNoError(t, resp)
  1750. }
  1751. func TestUpdateChannelRoles(t *testing.T) {
  1752. th := Setup(t).InitBasic()
  1753. defer th.TearDown()
  1754. Client := th.Client
  1755. const CHANNEL_ADMIN = "channel_user channel_admin"
  1756. const CHANNEL_MEMBER = "channel_user"
  1757. // User 1 creates a channel, making them channel admin by default.
  1758. channel := th.CreatePublicChannel()
  1759. // Adds User 2 to the channel, making them a channel member by default.
  1760. th.App.AddUserToChannel(th.BasicUser2, channel)
  1761. // User 1 promotes User 2
  1762. pass, resp := Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_ADMIN)
  1763. CheckNoError(t, resp)
  1764. require.True(t, pass, "should have passed")
  1765. member, resp := Client.GetChannelMember(channel.Id, th.BasicUser2.Id, "")
  1766. CheckNoError(t, resp)
  1767. require.Equal(t, CHANNEL_ADMIN, member.Roles, "roles don't match")
  1768. // User 1 demotes User 2
  1769. _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_MEMBER)
  1770. CheckNoError(t, resp)
  1771. th.LoginBasic2()
  1772. // User 2 cannot demote User 1
  1773. _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER)
  1774. CheckForbiddenStatus(t, resp)
  1775. // User 2 cannot promote self
  1776. _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_ADMIN)
  1777. CheckForbiddenStatus(t, resp)
  1778. th.LoginBasic()
  1779. // User 1 demotes self
  1780. _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER)
  1781. CheckNoError(t, resp)
  1782. // System Admin promotes User 1
  1783. _, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_ADMIN)
  1784. CheckNoError(t, resp)
  1785. // System Admin demotes User 1
  1786. _, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER)
  1787. CheckNoError(t, resp)
  1788. // System Admin promotes User 1
  1789. _, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_ADMIN)
  1790. CheckNoError(t, resp)
  1791. th.LoginBasic()
  1792. _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, "junk")
  1793. CheckBadRequestStatus(t, resp)
  1794. _, resp = Client.UpdateChannelRoles(channel.Id, "junk", CHANNEL_MEMBER)
  1795. CheckBadRequestStatus(t, resp)
  1796. _, resp = Client.UpdateChannelRoles("junk", th.BasicUser.Id, CHANNEL_MEMBER)
  1797. CheckBadRequestStatus(t, resp)
  1798. _, resp = Client.UpdateChannelRoles(channel.Id, model.NewId(), CHANNEL_MEMBER)
  1799. CheckNotFoundStatus(t, resp)
  1800. _, resp = Client.UpdateChannelRoles(model.NewId(), th.BasicUser.Id, CHANNEL_MEMBER)
  1801. CheckForbiddenStatus(t, resp)
  1802. }
  1803. func TestUpdateChannelMemberSchemeRoles(t *testing.T) {
  1804. th := Setup(t).InitBasic()
  1805. defer th.TearDown()
  1806. SystemAdminClient := th.SystemAdminClient
  1807. WebSocketClient, err := th.CreateWebSocketClient()
  1808. WebSocketClient.Listen()
  1809. require.Nil(t, err)
  1810. th.LoginBasic()
  1811. s1 := &model.SchemeRoles{
  1812. SchemeAdmin: false,
  1813. SchemeUser: false,
  1814. SchemeGuest: false,
  1815. }
  1816. _, r1 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s1)
  1817. CheckNoError(t, r1)
  1818. timeout := time.After(600 * time.Millisecond)
  1819. waiting := true
  1820. for waiting {
  1821. select {
  1822. case event := <-WebSocketClient.EventChannel:
  1823. if event.Event == model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED {
  1824. require.Equal(t, model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED, event.Event)
  1825. waiting = false
  1826. }
  1827. case <-timeout:
  1828. require.Fail(t, "Should have received event channel member websocket event and not timedout")
  1829. waiting = false
  1830. }
  1831. }
  1832. tm1, rtm1 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1833. CheckNoError(t, rtm1)
  1834. assert.Equal(t, false, tm1.SchemeGuest)
  1835. assert.Equal(t, false, tm1.SchemeUser)
  1836. assert.Equal(t, false, tm1.SchemeAdmin)
  1837. s2 := &model.SchemeRoles{
  1838. SchemeAdmin: false,
  1839. SchemeUser: true,
  1840. SchemeGuest: false,
  1841. }
  1842. _, r2 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s2)
  1843. CheckNoError(t, r2)
  1844. tm2, rtm2 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1845. CheckNoError(t, rtm2)
  1846. assert.Equal(t, false, tm2.SchemeGuest)
  1847. assert.Equal(t, true, tm2.SchemeUser)
  1848. assert.Equal(t, false, tm2.SchemeAdmin)
  1849. s3 := &model.SchemeRoles{
  1850. SchemeAdmin: true,
  1851. SchemeUser: false,
  1852. SchemeGuest: false,
  1853. }
  1854. _, r3 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s3)
  1855. CheckNoError(t, r3)
  1856. tm3, rtm3 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1857. CheckNoError(t, rtm3)
  1858. assert.Equal(t, false, tm3.SchemeGuest)
  1859. assert.Equal(t, false, tm3.SchemeUser)
  1860. assert.Equal(t, true, tm3.SchemeAdmin)
  1861. s4 := &model.SchemeRoles{
  1862. SchemeAdmin: true,
  1863. SchemeUser: true,
  1864. SchemeGuest: false,
  1865. }
  1866. _, r4 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s4)
  1867. CheckNoError(t, r4)
  1868. tm4, rtm4 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1869. CheckNoError(t, rtm4)
  1870. assert.Equal(t, false, tm4.SchemeGuest)
  1871. assert.Equal(t, true, tm4.SchemeUser)
  1872. assert.Equal(t, true, tm4.SchemeAdmin)
  1873. s5 := &model.SchemeRoles{
  1874. SchemeAdmin: false,
  1875. SchemeUser: false,
  1876. SchemeGuest: true,
  1877. }
  1878. _, r5 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s5)
  1879. CheckNoError(t, r5)
  1880. tm5, rtm5 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
  1881. CheckNoError(t, rtm5)
  1882. assert.Equal(t, true, tm5.SchemeGuest)
  1883. assert.Equal(t, false, tm5.SchemeUser)
  1884. assert.Equal(t, false, tm5.SchemeAdmin)
  1885. s6 := &model.SchemeRoles{
  1886. SchemeAdmin: false,
  1887. SchemeUser: true,
  1888. SchemeGuest: true,
  1889. }
  1890. _, resp := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s6)
  1891. CheckBadRequestStatus(t, resp)
  1892. _, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles(model.NewId(), th.BasicUser.Id, s4)
  1893. CheckForbiddenStatus(t, resp)
  1894. _, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, model.NewId(), s4)
  1895. CheckNotFoundStatus(t, resp)
  1896. _, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles("ASDF", th.BasicUser.Id, s4)
  1897. CheckBadRequestStatus(t, resp)
  1898. _, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, "ASDF", s4)
  1899. CheckBadRequestStatus(t, resp)
  1900. th.LoginBasic2()
  1901. _, resp = th.Client.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s4)
  1902. CheckForbiddenStatus(t, resp)
  1903. SystemAdminClient.Logout()
  1904. _, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.SystemAdminUser.Id, s4)
  1905. CheckUnauthorizedStatus(t, resp)
  1906. }
  1907. func TestUpdateChannelNotifyProps(t *testing.T) {
  1908. th := Setup(t).InitBasic()
  1909. defer th.TearDown()
  1910. Client := th.Client
  1911. props := map[string]string{}
  1912. props[model.DESKTOP_NOTIFY_PROP] = model.CHANNEL_NOTIFY_MENTION
  1913. props[model.MARK_UNREAD_NOTIFY_PROP] = model.CHANNEL_MARK_UNREAD_MENTION
  1914. pass, resp := Client.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, props)
  1915. CheckNoError(t, resp)
  1916. require.True(t, pass, "should have passed")
  1917. member, err := th.App.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id)
  1918. require.Nil(t, err)
  1919. require.Equal(t, model.CHANNEL_NOTIFY_MENTION, member.NotifyProps[model.DESKTOP_NOTIFY_PROP], "bad update")
  1920. require.Equal(t, model.CHANNEL_MARK_UNREAD_MENTION, member.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP], "bad update")
  1921. _, resp = Client.UpdateChannelNotifyProps("junk", th.BasicUser.Id, props)
  1922. CheckBadRequestStatus(t, resp)
  1923. _, resp = Client.UpdateChannelNotifyProps(th.BasicChannel.Id, "junk", props)
  1924. CheckBadRequestStatus(t, resp)
  1925. _, resp = Client.UpdateChannelNotifyProps(model.NewId(), th.BasicUser.Id, props)
  1926. CheckNotFoundStatus(t, resp)
  1927. _, resp = Client.UpdateChannelNotifyProps(th.BasicChannel.Id, model.NewId(), props)
  1928. CheckForbiddenStatus(t, resp)
  1929. _, resp = Client.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, map[string]string{})
  1930. CheckNoError(t, resp)
  1931. Client.Logout()
  1932. _, resp = Client.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, props)
  1933. CheckUnauthorizedStatus(t, resp)
  1934. _, resp = th.SystemAdminClient.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, props)
  1935. CheckNoError(t, resp)
  1936. }
  1937. func TestAddChannelMember(t *testing.T) {
  1938. th := Setup(t).InitBasic()
  1939. defer th.TearDown()
  1940. Client := th.Client
  1941. user := th.BasicUser
  1942. user2 := th.BasicUser2
  1943. team := th.BasicTeam
  1944. publicChannel := th.CreatePublicChannel()
  1945. privateChannel := th.CreatePrivateChannel()
  1946. user3 := th.CreateUserWithClient(th.SystemAdminClient)
  1947. _, resp := th.SystemAdminClient.AddTeamMember(team.Id, user3.Id)
  1948. CheckNoError(t, resp)
  1949. cm, resp := Client.AddChannelMember(publicChannel.Id, user2.Id)
  1950. CheckNoError(t, resp)
  1951. CheckCreatedStatus(t, resp)
  1952. require.Equal(t, publicChannel.Id, cm.ChannelId, "should have returned exact channel")
  1953. require.Equal(t, user2.Id, cm.UserId, "should have returned exact user added to public channel")
  1954. cm, resp = Client.AddChannelMember(privateChannel.Id, user2.Id)
  1955. CheckNoError(t, resp)
  1956. require.Equal(t, privateChannel.Id, cm.ChannelId, "should have returned exact channel")
  1957. require.Equal(t, user2.Id, cm.UserId, "should have returned exact user added to private channel")
  1958. post := &model.Post{ChannelId: publicChannel.Id, Message: "a" + GenerateTestId() + "a"}
  1959. rpost, err := Client.CreatePost(post)
  1960. require.NotNil(t, err)
  1961. Client.RemoveUserFromChannel(publicChannel.Id, user.Id)
  1962. _, resp = Client.AddChannelMemberWithRootId(publicChannel.Id, user.Id, rpost.Id)
  1963. CheckNoError(t, resp)
  1964. CheckCreatedStatus(t, resp)
  1965. Client.RemoveUserFromChannel(publicChannel.Id, user.Id)
  1966. _, resp = Client.AddChannelMemberWithRootId(publicChannel.Id, user.Id, "junk")
  1967. CheckBadRequestStatus(t, resp)
  1968. _, resp = Client.AddChannelMemberWithRootId(publicChannel.Id, user.Id, GenerateTestId())
  1969. CheckNotFoundStatus(t, resp)
  1970. Client.RemoveUserFromChannel(publicChannel.Id, user.Id)
  1971. _, resp = Client.AddChannelMember(publicChannel.Id, user.Id)
  1972. CheckNoError(t, resp)
  1973. cm, resp = Client.AddChannelMember(publicChannel.Id, "junk")
  1974. CheckBadRequestStatus(t, resp)
  1975. require.Nil(t, cm, "should return nothing")
  1976. _, resp = Client.AddChannelMember(publicChannel.Id, GenerateTestId())
  1977. CheckNotFoundStatus(t, resp)
  1978. _, resp = Client.AddChannelMember("junk", user2.Id)
  1979. CheckBadRequestStatus(t, resp)
  1980. _, resp = Client.AddChannelMember(GenerateTestId(), user2.Id)
  1981. CheckNotFoundStatus(t, resp)
  1982. otherUser := th.CreateUser()
  1983. otherChannel := th.CreatePublicChannel()
  1984. Client.Logout()
  1985. Client.Login(user2.Id, user2.Password)
  1986. _, resp = Client.AddChannelMember(publicChannel.Id, otherUser.Id)
  1987. CheckUnauthorizedStatus(t, resp)
  1988. _, resp = Client.AddChannelMember(privateChannel.Id, otherUser.Id)
  1989. CheckUnauthorizedStatus(t, resp)
  1990. _, resp = Client.AddChannelMember(otherChannel.Id, otherUser.Id)
  1991. CheckUnauthorizedStatus(t, resp)
  1992. Client.Logout()
  1993. Client.Login(user.Id, user.Password)
  1994. // should fail adding user who is not a member of the team
  1995. _, resp = Client.AddChannelMember(otherChannel.Id, otherUser.Id)
  1996. CheckUnauthorizedStatus(t, resp)
  1997. Client.DeleteChannel(otherChannel.Id)
  1998. // should fail adding user to a deleted channel
  1999. _, resp = Client.AddChannelMember(otherChannel.Id, user2.Id)
  2000. CheckUnauthorizedStatus(t, resp)
  2001. Client.Logout()
  2002. _, resp = Client.AddChannelMember(publicChannel.Id, user2.Id)
  2003. CheckUnauthorizedStatus(t, resp)
  2004. _, resp = Client.AddChannelMember(privateChannel.Id, user2.Id)
  2005. CheckUnauthorizedStatus(t, resp)
  2006. th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
  2007. _, resp = client.AddChannelMember(publicChannel.Id, user2.Id)
  2008. CheckNoError(t, resp)
  2009. _, resp = client.AddChannelMember(privateChannel.Id, user2.Id)
  2010. CheckNoError(t, resp)
  2011. })
  2012. // Check the appropriate permissions are enforced.
  2013. defaultRolePermissions := th.SaveDefaultRolePermissions()
  2014. defer func() {
  2015. th.RestoreDefaultRolePermissions(defaultRolePermissions)
  2016. }()
  2017. th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID)
  2018. // Check that a regular channel user can add other users.
  2019. Client.Login(user2.Username, user2.Password)
  2020. privateChannel = th.CreatePrivateChannel()
  2021. _, resp = Client.AddChannelMember(privateChannel.Id, user.Id)
  2022. CheckNoError(t, resp)
  2023. Client.Logout()
  2024. Client.Login(user.Username, user.Password)
  2025. _, resp = Client.AddChannelMember(privateChannel.Id, user3.Id)
  2026. CheckNoError(t, resp)
  2027. Client.Logout()
  2028. // Restrict the permission for adding users to Channel Admins
  2029. th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_ADMIN_ROLE_ID)
  2030. th.RemovePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID)
  2031. Client.Login(user2.Username, user2.Password)
  2032. privateChannel = th.CreatePrivateChannel()
  2033. _, resp = Client.AddChannelMember(privateChannel.Id, user.Id)
  2034. CheckNoError(t, resp)
  2035. Client.Logout()
  2036. Client.Login(user.Username, user.Password)
  2037. _, resp = Client.AddChannelMember(privateChannel.Id, user3.Id)
  2038. CheckForbiddenStatus(t, resp)
  2039. Client.Logout()
  2040. th.MakeUserChannelAdmin(user, privateChannel)
  2041. th.App.Srv().InvalidateAllCaches()
  2042. Client.Login(user.Username, user.Password)
  2043. _, resp = Client.AddChannelMember(privateChannel.Id, user3.Id)
  2044. CheckNoError(t, resp)
  2045. Client.Logout()
  2046. // Set a channel to group-constrained
  2047. privateChannel.GroupConstrained = model.NewBool(true)
  2048. _, appErr := th.App.UpdateChannel(privateChannel)
  2049. require.Nil(t, appErr)
  2050. th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
  2051. // User is not in associated groups so shouldn't be allowed
  2052. _, resp = client.AddChannelMember(privateChannel.Id, user.Id)
  2053. CheckErrorMessage(t, resp, "api.channel.add_members.user_denied")
  2054. })
  2055. // Associate group to team
  2056. _, appErr = th.App.UpsertGroupSyncable(&model.GroupSyncable{
  2057. GroupId: th.Group.Id,
  2058. SyncableId: privateChannel.Id,
  2059. Type: model.GroupSyncableTypeChannel,
  2060. })
  2061. require.Nil(t, appErr)
  2062. // Add user to group
  2063. _, appErr = th.App.UpsertGroupMember(th.Group.Id, user.Id)
  2064. require.Nil(t, appErr)
  2065. th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
  2066. _, resp = client.AddChannelMember(privateChannel.Id, user.Id)
  2067. CheckNoError(t, resp)
  2068. })
  2069. }
  2070. func TestAddChannelMemberAddMyself(t *testing.T) {
  2071. th := Setup(t).InitBasic()
  2072. defer th.TearDown()
  2073. Client := th.Client
  2074. user := th.CreateUser()
  2075. th.LinkUserToTeam(user, th.BasicTeam)
  2076. notMemberPublicChannel1 := th.CreatePublicChannel()
  2077. notMemberPublicChannel2 := th.CreatePublicChannel()
  2078. notMemberPrivateChannel := th.CreatePrivateChannel()
  2079. memberPublicChannel := th.CreatePublicChannel()
  2080. memberPrivateChannel := th.CreatePrivateChannel()
  2081. th.AddUserToChannel(user, memberPublicChannel)
  2082. th.AddUserToChannel(user, memberPrivateChannel)
  2083. testCases := []struct {
  2084. Name string
  2085. Channel *model.Channel
  2086. WithJoinPublicPermission bool
  2087. ExpectedError string
  2088. }{
  2089. {
  2090. "Add myself to a public channel with JOIN_PUBLIC_CHANNEL permission",
  2091. notMemberPublicChannel1,
  2092. true,
  2093. "",
  2094. },
  2095. {
  2096. "Try to add myself to a private channel with the JOIN_PUBLIC_CHANNEL permission",
  2097. notMemberPrivateChannel,
  2098. true,
  2099. "api.context.permissions.app_error",
  2100. },
  2101. {
  2102. "Try to add myself to a public channel without the JOIN_PUBLIC_CHANNEL permission",
  2103. notMemberPublicChannel2,
  2104. false,
  2105. "api.context.permissions.app_error",
  2106. },
  2107. {
  2108. "Add myself a public channel where I'm already a member, not having JOIN_PUBLIC_CHANNEL or MANAGE MEMBERS permission",
  2109. memberPublicChannel,
  2110. false,
  2111. "",
  2112. },
  2113. {
  2114. "Add myself a private channel where I'm already a member, not having JOIN_PUBLIC_CHANNEL or MANAGE MEMBERS permission",
  2115. memberPrivateChannel,
  2116. false,
  2117. "",
  2118. },
  2119. }
  2120. Client.Login(user.Email, user.Password)
  2121. for _, tc := range testCases {
  2122. t.Run(tc.Name, func(t *testing.T) {
  2123. // Check the appropriate permissions are enforced.
  2124. defaultRolePermissions := th.SaveDefaultRolePermissions()
  2125. defer func() {
  2126. th.RestoreDefaultRolePermissions(defaultRolePermissions)
  2127. }()
  2128. if !tc.WithJoinPublicPermission {
  2129. th.RemovePermissionFromRole(model.PERMISSION_JOIN_PUBLIC_CHANNELS.Id, model.TEAM_USER_ROLE_ID)
  2130. }
  2131. _, resp := Client.AddChannelMember(tc.Channel.Id, user.Id)
  2132. if tc.ExpectedError == "" {
  2133. CheckNoError(t, resp)
  2134. } else {
  2135. CheckErrorMessage(t, resp, tc.ExpectedError)
  2136. }
  2137. })
  2138. }
  2139. }
  2140. func TestRemoveChannelMember(t *testing.T) {
  2141. th := Setup(t).InitBasic()
  2142. user1 := th.BasicUser
  2143. user2 := th.BasicUser2
  2144. team := th.BasicTeam
  2145. defer th.TearDown()
  2146. Client := th.Client
  2147. th.App.UpdateConfig(func(cfg *model.Config) {
  2148. *cfg.ServiceSettings.EnableBotAccountCreation = true
  2149. })
  2150. bot := th.CreateBotWithSystemAdminClient()
  2151. th.App.AddUserToTeam(team.Id, bot.UserId, "")
  2152. pass, resp := Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser2.Id)
  2153. CheckNoError(t, resp)
  2154. require.True(t, pass, "should have passed")
  2155. _, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, "junk")
  2156. CheckBadRequestStatus(t, resp)
  2157. _, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, model.NewId())
  2158. CheckNotFoundStatus(t, resp)
  2159. _, resp = Client.RemoveUserFromChannel(model.NewId(), th.BasicUser2.Id)
  2160. CheckNotFoundStatus(t, resp)
  2161. th.LoginBasic2()
  2162. _, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
  2163. CheckForbiddenStatus(t, resp)
  2164. t.Run("success", func(t *testing.T) {
  2165. // Setup the system administrator to listen for websocket events from the channels.
  2166. th.LinkUserToTeam(th.SystemAdminUser, th.BasicTeam)
  2167. _, err := th.App.AddUserToChannel(th.SystemAdminUser, th.BasicChannel)
  2168. require.Nil(t, err)
  2169. _, err = th.App.AddUserToChannel(th.SystemAdminUser, th.BasicChannel2)
  2170. require.Nil(t, err)
  2171. props := map[string]string{}
  2172. props[model.DESKTOP_NOTIFY_PROP] = model.CHANNEL_NOTIFY_ALL
  2173. _, resp = th.SystemAdminClient.UpdateChannelNotifyProps(th.BasicChannel.Id, th.SystemAdminUser.Id, props)
  2174. _, resp = th.SystemAdminClient.UpdateChannelNotifyProps(th.BasicChannel2.Id, th.SystemAdminUser.Id, props)
  2175. CheckNoError(t, resp)
  2176. wsClient, err := th.CreateWebSocketSystemAdminClient()
  2177. require.Nil(t, err)
  2178. wsClient.Listen()
  2179. var closeWsClient sync.Once
  2180. defer closeWsClient.Do(func() {
  2181. wsClient.Close()
  2182. })
  2183. wsr := <-wsClient.EventChannel
  2184. require.Equal(t, model.WEBSOCKET_EVENT_HELLO, wsr.EventType())
  2185. // requirePost listens for websocket events and tries to find the post matching
  2186. // the expected post's channel and message.
  2187. requirePost := func(expectedPost *model.Post) {
  2188. t.Helper()
  2189. for {
  2190. select {
  2191. case event := <-wsClient.EventChannel:
  2192. postData, ok := event.GetData()["post"]
  2193. if !ok {
  2194. continue
  2195. }
  2196. post := model.PostFromJson(strings.NewReader(postData.(string)))
  2197. if post.ChannelId == expectedPost.ChannelId && post.Message == expectedPost.Message {
  2198. return
  2199. }
  2200. case <-time.After(5 * time.Second):
  2201. require.FailNow(t, "failed to find expected post after 5 seconds")
  2202. return
  2203. }
  2204. }
  2205. }
  2206. th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel)
  2207. _, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser2.Id)
  2208. CheckNoError(t, resp)
  2209. requirePost(&model.Post{
  2210. Message: fmt.Sprintf("@%s left the channel.", th.BasicUser2.Username),
  2211. ChannelId: th.BasicChannel.Id,
  2212. })
  2213. _, resp = Client.RemoveUserFromChannel(th.BasicChannel2.Id, th.BasicUser.Id)
  2214. CheckNoError(t, resp)
  2215. requirePost(&model.Post{
  2216. Message: fmt.Sprintf("@%s removed from the channel.", th.BasicUser.Username),
  2217. ChannelId: th.BasicChannel2.Id,
  2218. })
  2219. _, resp = th.SystemAdminClient.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
  2220. CheckNoError(t, resp)
  2221. requirePost(&model.Post{
  2222. Message: fmt.Sprintf("@%s removed from the channel.", th.BasicUser.Username),
  2223. ChannelId: th.BasicChannel.Id,
  2224. })
  2225. closeWsClient.Do(func() {
  2226. wsClient.Close()
  2227. })
  2228. })
  2229. // Leave deleted channel
  2230. th.LoginBasic()
  2231. deletedChannel := th.CreatePublicChannel()
  2232. th.App.AddUserToChannel(th.BasicUser, deletedChannel)
  2233. th.App.AddUserToChannel(th.BasicUser2, deletedChannel)
  2234. deletedChannel.DeleteAt = 1
  2235. th.App.UpdateChannel(deletedChannel)
  2236. _, resp = Client.RemoveUserFromChannel(deletedChannel.Id, th.BasicUser.Id)
  2237. CheckNoError(t, resp)
  2238. th.LoginBasic()
  2239. private := th.CreatePrivateChannel()
  2240. th.App.AddUserToChannel(th.BasicUser2, private)
  2241. _, resp = Client.RemoveUserFromChannel(private.Id, th.BasicUser2.Id)
  2242. CheckNoError(t, resp)
  2243. th.LoginBasic2()
  2244. _, resp = Client.RemoveUserFromChannel(private.Id, th.BasicUser.Id)
  2245. CheckForbiddenStatus(t, resp)
  2246. th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
  2247. th.App.AddUserToChannel(th.BasicUser, private)
  2248. _, resp = client.RemoveUserFromChannel(private.Id, th.BasicUser.Id)
  2249. CheckNoError(t, resp)
  2250. })
  2251. th.LoginBasic()
  2252. th.UpdateUserToNonTeamAdmin(user1, team)
  2253. th.App.Srv().InvalidateAllCaches()
  2254. // Check the appropriate permissions are enforced.
  2255. defaultRolePermissions := th.SaveDefaultRolePermissions()
  2256. defer func() {
  2257. th.RestoreDefaultRolePermissions(defaultRolePermissions)
  2258. }()
  2259. th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID)
  2260. th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
  2261. // Check that a regular channel user can remove other users.
  2262. privateChannel := th.CreateChannelWithClient(client, model.CHANNEL_PRIVATE)
  2263. _, resp = client.AddChannelMember(privateChannel.Id, user1.Id)
  2264. CheckNoError(t, resp)
  2265. _, resp = client.AddChannelMember(privateChannel.Id, user2.Id)
  2266. CheckNoError(t, resp)
  2267. _, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id)
  2268. CheckNoError(t, resp)
  2269. })
  2270. // Restrict the permission for adding users to Channel Admins
  2271. th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_ADMIN_ROLE_ID)
  2272. th.RemovePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID)
  2273. privateChannel := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE)
  2274. _, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, user1.Id)
  2275. CheckNoError(t, resp)
  2276. _, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, user2.Id)
  2277. CheckNoError(t, resp)
  2278. _, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, bot.UserId)
  2279. CheckNoError(t, resp)
  2280. _, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id)
  2281. CheckForbiddenStatus(t, resp)
  2282. th.MakeUserChannelAdmin(user1, privateChannel)
  2283. th.App.Srv().InvalidateAllCaches()
  2284. _, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id)
  2285. CheckNoError(t, resp)
  2286. _, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, th.SystemAdminUser.Id)
  2287. CheckNoError(t, resp)
  2288. // If the channel is group-constrained the user cannot be removed
  2289. privateChannel.GroupConstrained = model.NewBool(true)
  2290. _, err := th.App.UpdateChannel(privateChannel)
  2291. require.Nil(t, err)
  2292. _, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id)
  2293. require.Equal(t, "api.channel.remove_member.group_constrained.app_error", resp.Error.Id)
  2294. // If the channel is group-constrained user can remove self
  2295. _, resp = th.SystemAdminClient.RemoveUserFromChannel(privateChannel.Id, th.SystemAdminUser.Id)
  2296. CheckNoError(t, resp)
  2297. // Test on preventing removal of user from a direct channel
  2298. directChannel, resp := Client.CreateDirectChannel(user1.Id, user2.Id)
  2299. CheckNoError(t, resp)
  2300. // If the channel is group-constrained a user can remove a bot
  2301. _, resp = Client.RemoveUserFromChannel(privateChannel.Id, bot.UserId)
  2302. CheckNoError(t, resp)
  2303. _, resp = Client.RemoveUserFromChannel(directChannel.Id, user1.Id)
  2304. CheckBadRequestStatus(t, resp)
  2305. _, resp = Client.RemoveUserFromChannel(directChannel.Id, user2.Id)
  2306. CheckBadRequestStatus(t, resp)
  2307. _, resp = th.SystemAdminClient.RemoveUserFromChannel(directChannel.Id, user1.Id)
  2308. CheckBadRequestStatus(t, resp)
  2309. // Test on preventing removal of user from a group channel
  2310. user3 := th.CreateUser()
  2311. groupChannel, resp := Client.CreateGroupChannel([]string{user1.Id, user2.Id, user3.Id})
  2312. CheckNoError(t, resp)
  2313. th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
  2314. _, resp = client.RemoveUserFromChannel(groupChannel.Id, user1.Id)
  2315. CheckBadRequestStatus(t, resp)
  2316. })
  2317. }
  2318. func TestAutocompleteChannels(t *testing.T) {
  2319. th := Setup(t).InitBasic()
  2320. defer th.TearDown()
  2321. // A private channel to make sure private channels are not used
  2322. utils.DisableDebugLogForTest()
  2323. ptown, _ := th.Client.CreateChannel(&model.Channel{
  2324. DisplayName: "Town",
  2325. Name: "town",
  2326. Type: model.CHANNEL_PRIVATE,
  2327. TeamId: th.BasicTeam.Id,
  2328. })
  2329. tower, _ := th.Client.CreateChannel(&model.Channel{
  2330. DisplayName: "Tower",
  2331. Name: "tower",
  2332. Type: model.CHANNEL_OPEN,
  2333. TeamId: th.BasicTeam.Id,
  2334. })
  2335. utils.EnableDebugLogForTest()
  2336. defer func() {
  2337. th.Client.DeleteChannel(ptown.Id)
  2338. th.Client.DeleteChannel(tower.Id)
  2339. }()
  2340. for _, tc := range []struct {
  2341. description string
  2342. teamId string
  2343. fragment string
  2344. expectedIncludes []string
  2345. expectedExcludes []string
  2346. }{
  2347. {
  2348. "Basic town-square",
  2349. th.BasicTeam.Id,
  2350. "town",
  2351. []string{"town-square"},
  2352. []string{"off-topic", "town", "tower"},
  2353. },
  2354. {
  2355. "Basic off-topic",
  2356. th.BasicTeam.Id,
  2357. "off-to",
  2358. []string{"off-topic"},
  2359. []string{"town-square", "town", "tower"},
  2360. },
  2361. {
  2362. "Basic town square and off topic",
  2363. th.BasicTeam.Id,
  2364. "tow",
  2365. []string{"town-square", "tower"},
  2366. []string{"off-topic", "town"},
  2367. },
  2368. } {
  2369. t.Run(tc.description, func(t *testing.T) {
  2370. channels, resp := th.Client.AutocompleteChannelsForTeam(tc.teamId, tc.fragment)
  2371. require.Nil(t, resp.Error)
  2372. names := make([]string, len(*channels))
  2373. for i, c := range *channels {
  2374. names[i] = c.Name
  2375. }
  2376. for _, name := range tc.expectedIncludes {
  2377. require.Contains(t, names, name, "channel not included")
  2378. }
  2379. for _, name := range tc.expectedExcludes {
  2380. require.NotContains(t, names, name, "channel not excluded")
  2381. }
  2382. })
  2383. }
  2384. }
  2385. func TestAutocompleteChannelsForSearch(t *testing.T) {
  2386. th := Setup(t).InitBasic()
  2387. defer th.TearDown()
  2388. th.LoginSystemAdminWithClient(th.SystemAdminClient)
  2389. th.LoginBasicWithClient(th.Client)
  2390. u1 := th.CreateUserWithClient(th.SystemAdminClient)
  2391. defer th.App.PermanentDeleteUser(u1)
  2392. u2 := th.CreateUserWithClient(th.SystemAdminClient)
  2393. defer th.App.PermanentDeleteUser(u2)
  2394. u3 := th.CreateUserWithClient(th.SystemAdminClient)
  2395. defer th.App.PermanentDeleteUser(u3)
  2396. u4 := th.CreateUserWithClient(th.SystemAdminClient)
  2397. defer th.App.PermanentDeleteUser(u4)
  2398. // A private channel to make sure private channels are not used
  2399. utils.DisableDebugLogForTest()
  2400. ptown, _ := th.SystemAdminClient.CreateChannel(&model.Channel{
  2401. DisplayName: "Town",
  2402. Name: "town",
  2403. Type: model.CHANNEL_PRIVATE,
  2404. TeamId: th.BasicTeam.Id,
  2405. })
  2406. defer func() {
  2407. th.Client.DeleteChannel(ptown.Id)
  2408. }()
  2409. mypriv, _ := th.Client.CreateChannel(&model.Channel{
  2410. DisplayName: "My private town",
  2411. Name: "townpriv",
  2412. Type: model.CHANNEL_PRIVATE,
  2413. TeamId: th.BasicTeam.Id,
  2414. })
  2415. defer func() {
  2416. th.Client.DeleteChannel(mypriv.Id)
  2417. }()
  2418. utils.EnableDebugLogForTest()
  2419. dc1, resp := th.Client.CreateDirectChannel(th.BasicUser.Id, u1.Id)
  2420. CheckNoError(t, resp)
  2421. defer func() {
  2422. th.Client.DeleteChannel(dc1.Id)
  2423. }()
  2424. dc2, resp := th.SystemAdminClient.CreateDirectChannel(u2.Id, u3.Id)
  2425. CheckNoError(t, resp)
  2426. defer func() {
  2427. th.SystemAdminClient.DeleteChannel(dc2.Id)
  2428. }()
  2429. gc1, resp := th.Client.CreateGroupChannel([]string{th.BasicUser.Id, u2.Id, u3.Id})
  2430. CheckNoError(t, resp)
  2431. defer func() {
  2432. th.Client.DeleteChannel(gc1.Id)
  2433. }()
  2434. gc2, resp := th.SystemAdminClient.CreateGroupChannel([]string{u2.Id, u3.Id, u4.Id})
  2435. CheckNoError(t, resp)
  2436. defer func() {
  2437. th.SystemAdminClient.DeleteChannel(gc2.Id)
  2438. }()
  2439. for _, tc := range []struct {
  2440. description string
  2441. teamID string
  2442. fragment string
  2443. expectedIncludes []string
  2444. expectedExcludes []string
  2445. }{
  2446. {
  2447. "Basic town-square",
  2448. th.BasicTeam.Id,
  2449. "town",
  2450. []string{"town-square", "townpriv"},
  2451. []string{"off-topic", "town"},
  2452. },
  2453. {
  2454. "Basic off-topic",
  2455. th.BasicTeam.Id,
  2456. "off-to",
  2457. []string{"off-topic"},
  2458. []string{"town-square", "town", "townpriv"},
  2459. },
  2460. {
  2461. "Basic town square and townpriv",
  2462. th.BasicTeam.Id,
  2463. "tow",
  2464. []string{"town-square", "townpriv"},
  2465. []string{"off-topic", "town"},
  2466. },
  2467. {
  2468. "Direct and group messages",
  2469. th.BasicTeam.Id,
  2470. "fakeuser",
  2471. []string{dc1.Name, gc1.Name},
  2472. []string{dc2.Name, gc2.Name},
  2473. },
  2474. } {
  2475. t.Run(tc.description, func(t *testing.T) {
  2476. channels, resp := th.Client.AutocompleteChannelsForTeamForSearch(tc.teamID, tc.fragment)
  2477. require.Nil(t, resp.Error)
  2478. names := make([]string, len(*channels))
  2479. for i, c := range *channels {
  2480. names[i] = c.Name
  2481. }
  2482. for _, name := range tc.expectedIncludes {
  2483. require.Contains(t, names, name, "channel not included")
  2484. }
  2485. for _, name := range tc.expectedExcludes {
  2486. require.NotContains(t, names, name, "channel not excluded")
  2487. }
  2488. })
  2489. }
  2490. }
  2491. func TestAutocompleteChannelsForSearchGuestUsers(t *testing.T) {
  2492. th := Setup(t).InitBasic()
  2493. defer th.TearDown()
  2494. u1 := th.CreateUserWithClient(th.SystemAdminClient)
  2495. defer th.App.PermanentDeleteUser(u1)
  2496. enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable
  2497. defer func() {
  2498. th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts })
  2499. th.App.Srv().RemoveLicense()
  2500. }()
  2501. th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true })
  2502. th.App.Srv().SetLicense(model.NewTestLicense())
  2503. id := model.NewId()
  2504. guest := &model.User{
  2505. Email: "success+" + id + "@simulator.amazonses.com",
  2506. Username: "un_" + id,
  2507. Nickname: "nn_" + id,
  2508. Password: "Password1",
  2509. EmailVerified: true,
  2510. }
  2511. guest, err := th.App.CreateGuest(guest)
  2512. require.Nil(t, err)
  2513. th.LoginSystemAdminWithClient(th.SystemAdminClient)
  2514. _, resp := th.SystemAdminClient.AddTeamMember(th.BasicTeam.Id, guest.Id)
  2515. CheckNoError(t, resp)
  2516. // A private channel to make sure private channels are not used
  2517. utils.DisableDebugLogForTest()
  2518. town, _ := th.SystemAdminClient.CreateChannel(&model.Channel{
  2519. DisplayName: "Town",
  2520. Name: "town",
  2521. Type: model.CHANNEL_OPEN,
  2522. TeamId: th.BasicTeam.Id,
  2523. })
  2524. defer func() {
  2525. th.SystemAdminClient.DeleteChannel(town.Id)
  2526. }()
  2527. _, resp = th.SystemAdminClient.AddChannelMember(town.Id, guest.Id)
  2528. CheckNoError(t, resp)
  2529. mypriv, _ := th.SystemAdminClient.CreateChannel(&model.Channel{
  2530. DisplayName: "My private town",
  2531. Name: "townpriv",
  2532. Type: model.CHANNEL_PRIVATE,
  2533. TeamId: th.BasicTeam.Id,
  2534. })
  2535. defer func() {
  2536. th.SystemAdminClient.DeleteChannel(mypriv.Id)
  2537. }()
  2538. _, resp = th.SystemAdminClient.AddChannelMember(mypriv.Id, guest.Id)
  2539. CheckNoError(t, resp)
  2540. utils.EnableDebugLogForTest()
  2541. dc1, resp := th.SystemAdminClient.CreateDirectChannel(th.BasicUser.Id, guest.Id)
  2542. CheckNoError(t, resp)
  2543. defer func() {
  2544. th.SystemAdminClient.DeleteChannel(dc1.Id)
  2545. }()
  2546. dc2, resp := th.SystemAdminClient.CreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
  2547. CheckNoError(t, resp)
  2548. defer func() {
  2549. th.SystemAdminClient.DeleteChannel(dc2.Id)
  2550. }()
  2551. gc1, resp := th.SystemAdminClient.CreateGroupChannel([]string{th.BasicUser.Id, th.BasicUser2.Id, guest.Id})
  2552. CheckNoError(t, resp)
  2553. defer func() {
  2554. th.SystemAdminClient.DeleteChannel(gc1.Id)
  2555. }()
  2556. gc2, resp := th.SystemAdminClient.CreateGroupChannel([]string{th.BasicUser.Id, th.BasicUser2.Id, u1.Id})
  2557. CheckNoError(t, resp)
  2558. defer func() {
  2559. th.SystemAdminClient.DeleteChannel(gc2.Id)
  2560. }()
  2561. _, resp = th.Client.Login(guest.Username, "Password1")
  2562. CheckNoError(t, resp)
  2563. for _, tc := range []struct {
  2564. description string
  2565. teamID string
  2566. fragment string
  2567. expectedIncludes []string
  2568. expectedExcludes []string
  2569. }{
  2570. {
  2571. "Should return those channel where is member",
  2572. th.BasicTeam.Id,
  2573. "town",
  2574. []string{"town", "townpriv"},
  2575. []string{"town-square", "off-topic"},
  2576. },
  2577. {
  2578. "Should return empty if not member of the searched channels",
  2579. th.BasicTeam.Id,
  2580. "off-to",
  2581. []string{},
  2582. []string{"off-topic", "town-square", "town", "townpriv"},
  2583. },
  2584. {
  2585. "Should return direct and group messages",
  2586. th.BasicTeam.Id,
  2587. "fakeuser",
  2588. []string{dc1.Name, gc1.Name},
  2589. []string{dc2.Name, gc2.Name},
  2590. },
  2591. } {
  2592. t.Run(tc.description, func(t *testing.T) {
  2593. channels, resp := th.Client.AutocompleteChannelsForTeamForSearch(tc.teamID, tc.fragment)
  2594. require.Nil(t, resp.Error)
  2595. names := make([]string, len(*channels))
  2596. for i, c := range *channels {
  2597. names[i] = c.Name
  2598. }
  2599. for _, name := range tc.expectedIncludes {
  2600. require.Contains(t, names, name, "channel not included")
  2601. }
  2602. for _, name := range tc.expectedExcludes {
  2603. require.NotContains(t, names, name, "channel not excluded")
  2604. }
  2605. })
  2606. }
  2607. }
  2608. func TestUpdateChannelScheme(t *testing.T) {
  2609. th := Setup(t)
  2610. defer th.TearDown()
  2611. th.App.Srv().SetLicense(model.NewTestLicense(""))
  2612. th.App.SetPhase2PermissionsMigrationStatus(true)
  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. channel, resp := th.SystemAdminClient.CreateChannel(&model.Channel{
  2625. DisplayName: "Name",
  2626. Name: "z-z-" + model.NewId() + "a",
  2627. Type: model.CHANNEL_OPEN,
  2628. TeamId: team.Id,
  2629. })
  2630. CheckNoError(t, resp)
  2631. channelScheme, resp := th.SystemAdminClient.CreateScheme(&model.Scheme{
  2632. DisplayName: "DisplayName",
  2633. Name: model.NewId(),
  2634. Description: "Some description",
  2635. Scope: model.SCHEME_SCOPE_CHANNEL,
  2636. })
  2637. CheckNoError(t, resp)
  2638. teamScheme, resp := th.SystemAdminClient.CreateScheme(&model.Scheme{
  2639. DisplayName: "DisplayName",
  2640. Name: model.NewId(),
  2641. Description: "Some description",
  2642. Scope: model.SCHEME_SCOPE_TEAM,
  2643. })
  2644. CheckNoError(t, resp)
  2645. // Test the setup/base case.
  2646. _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, channelScheme.Id)
  2647. CheckNoError(t, resp)
  2648. // Test various invalid channel and scheme id combinations.
  2649. _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, "x")
  2650. CheckBadRequestStatus(t, resp)
  2651. _, resp = th.SystemAdminClient.UpdateChannelScheme("x", channelScheme.Id)
  2652. CheckBadRequestStatus(t, resp)
  2653. _, resp = th.SystemAdminClient.UpdateChannelScheme("x", "x")
  2654. CheckBadRequestStatus(t, resp)
  2655. // Test that permissions are required.
  2656. _, resp = th.Client.UpdateChannelScheme(channel.Id, channelScheme.Id)
  2657. CheckForbiddenStatus(t, resp)
  2658. // Test that a license is required.
  2659. th.App.Srv().SetLicense(nil)
  2660. _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, channelScheme.Id)
  2661. CheckNotImplementedStatus(t, resp)
  2662. th.App.Srv().SetLicense(model.NewTestLicense(""))
  2663. // Test an invalid scheme scope.
  2664. _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, teamScheme.Id)
  2665. CheckBadRequestStatus(t, resp)
  2666. // Test that an unauthenticated user gets rejected.
  2667. th.SystemAdminClient.Logout()
  2668. _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, channelScheme.Id)
  2669. CheckUnauthorizedStatus(t, resp)
  2670. }
  2671. func TestGetChannelMembersTimezones(t *testing.T) {
  2672. th := Setup(t).InitBasic()
  2673. defer th.TearDown()
  2674. Client := th.Client
  2675. user := th.BasicUser
  2676. user.Timezone["useAutomaticTimezone"] = "false"
  2677. user.Timezone["manualTimezone"] = "XOXO/BLABLA"
  2678. _, resp := Client.UpdateUser(user)
  2679. CheckNoError(t, resp)
  2680. user2 := th.BasicUser2
  2681. user2.Timezone["automaticTimezone"] = "NoWhere/Island"
  2682. _, resp = th.SystemAdminClient.UpdateUser(user2)
  2683. CheckNoError(t, resp)
  2684. timezone, resp := Client.GetChannelMembersTimezones(th.BasicChannel.Id)
  2685. CheckNoError(t, resp)
  2686. require.Len(t, timezone, 2, "should return 2 timezones")
  2687. //both users have same timezone
  2688. user2.Timezone["automaticTimezone"] = "XOXO/BLABLA"
  2689. _, resp = th.SystemAdminClient.UpdateUser(user2)
  2690. CheckNoError(t, resp)
  2691. timezone, resp = Client.GetChannelMembersTimezones(th.BasicChannel.Id)
  2692. CheckNoError(t, resp)
  2693. require.Len(t, timezone, 1, "should return 1 timezone")
  2694. //no timezone set should return empty
  2695. user2.Timezone["automaticTimezone"] = ""
  2696. _, resp = th.SystemAdminClient.UpdateUser(user2)
  2697. CheckNoError(t, resp)
  2698. user.Timezone["manualTimezone"] = ""
  2699. _, resp = Client.UpdateUser(user)
  2700. CheckNoError(t, resp)
  2701. timezone, resp = Client.GetChannelMembersTimezones(th.BasicChannel.Id)
  2702. CheckNoError(t, resp)
  2703. require.Empty(t, timezone, "should return 0 timezone")
  2704. }
  2705. func TestChannelMembersMinusGroupMembers(t *testing.T) {
  2706. th := Setup(t).InitBasic()
  2707. defer th.TearDown()
  2708. user1 := th.BasicUser
  2709. user2 := th.BasicUser2
  2710. channel := th.CreatePrivateChannel()
  2711. _, err := th.App.AddChannelMember(user1.Id, channel, "", "")
  2712. require.Nil(t, err)
  2713. _, err = th.App.AddChannelMember(user2.Id, channel, "", "")
  2714. require.Nil(t, err)
  2715. channel.GroupConstrained = model.NewBool(true)
  2716. channel, err = th.App.UpdateChannel(channel)
  2717. require.Nil(t, err)
  2718. group1 := th.CreateGroup()
  2719. group2 := th.CreateGroup()
  2720. _, err = th.App.UpsertGroupMember(group1.Id, user1.Id)
  2721. require.Nil(t, err)
  2722. _, err = th.App.UpsertGroupMember(group2.Id, user2.Id)
  2723. require.Nil(t, err)
  2724. // No permissions
  2725. _, _, res := th.Client.ChannelMembersMinusGroupMembers(channel.Id, []string{group1.Id, group2.Id}, 0, 100, "")
  2726. require.Equal(t, "api.context.permissions.app_error", res.Error.Id)
  2727. testCases := map[string]struct {
  2728. groupIDs []string
  2729. page int
  2730. perPage int
  2731. length int
  2732. count int
  2733. otherAssertions func([]*model.UserWithGroups)
  2734. }{
  2735. "All groups, expect no users removed": {
  2736. groupIDs: []string{group1.Id, group2.Id},
  2737. page: 0,
  2738. perPage: 100,
  2739. length: 0,
  2740. count: 0,
  2741. },
  2742. "Some nonexistent group, page 0": {
  2743. groupIDs: []string{model.NewId()},
  2744. page: 0,
  2745. perPage: 1,
  2746. length: 1,
  2747. count: 2,
  2748. },
  2749. "Some nonexistent group, page 1": {
  2750. groupIDs: []string{model.NewId()},
  2751. page: 1,
  2752. perPage: 1,
  2753. length: 1,
  2754. count: 2,
  2755. },
  2756. "One group, expect one user removed": {
  2757. groupIDs: []string{group1.Id},
  2758. page: 0,
  2759. perPage: 100,
  2760. length: 1,
  2761. count: 1,
  2762. otherAssertions: func(uwg []*model.UserWithGroups) {
  2763. require.Equal(t, uwg[0].Id, user2.Id)
  2764. },
  2765. },
  2766. "Other group, expect other user removed": {
  2767. groupIDs: []string{group2.Id},
  2768. page: 0,
  2769. perPage: 100,
  2770. length: 1,
  2771. count: 1,
  2772. otherAssertions: func(uwg []*model.UserWithGroups) {
  2773. require.Equal(t, uwg[0].Id, user1.Id)
  2774. },
  2775. },
  2776. }
  2777. for name, tc := range testCases {
  2778. t.Run(name, func(t *testing.T) {
  2779. uwg, count, res := th.SystemAdminClient.ChannelMembersMinusGroupMembers(channel.Id, tc.groupIDs, tc.page, tc.perPage, "")
  2780. require.Nil(t, res.Error)
  2781. require.Len(t, uwg, tc.length)
  2782. require.Equal(t, tc.count, int(count))
  2783. if tc.otherAssertions != nil {
  2784. tc.otherAssertions(uwg)
  2785. }
  2786. })
  2787. }
  2788. }
  2789. func TestGetChannelModerations(t *testing.T) {
  2790. th := Setup(t).InitBasic()
  2791. defer th.TearDown()
  2792. channel := th.BasicChannel
  2793. team := th.BasicTeam
  2794. th.App.SetPhase2PermissionsMigrationStatus(true)
  2795. t.Run("Errors without a license", func(t *testing.T) {
  2796. _, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
  2797. require.Equal(t, "api.channel.get_channel_moderations.license.error", res.Error.Id)
  2798. })
  2799. th.App.Srv().SetLicense(model.NewTestLicense())
  2800. t.Run("Errors as a non sysadmin", func(t *testing.T) {
  2801. _, res := th.Client.GetChannelModerations(channel.Id, "")
  2802. require.Equal(t, "api.context.permissions.app_error", res.Error.Id)
  2803. })
  2804. th.App.Srv().SetLicense(model.NewTestLicense())
  2805. t.Run("Returns default moderations with default roles", func(t *testing.T) {
  2806. moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
  2807. require.Nil(t, res.Error)
  2808. require.Equal(t, len(moderations), 4)
  2809. for _, moderation := range moderations {
  2810. if moderation.Name == "manage_members" {
  2811. require.Empty(t, moderation.Roles.Guests)
  2812. } else {
  2813. require.Equal(t, moderation.Roles.Guests.Value, true)
  2814. require.Equal(t, moderation.Roles.Guests.Enabled, true)
  2815. }
  2816. require.Equal(t, moderation.Roles.Members.Value, true)
  2817. require.Equal(t, moderation.Roles.Members.Enabled, true)
  2818. }
  2819. })
  2820. t.Run("Returns value false and enabled false for permissions that are not present in higher scoped scheme when no channel scheme present", func(t *testing.T) {
  2821. scheme := th.SetupTeamScheme()
  2822. team.SchemeId = &scheme.Id
  2823. _, err := th.App.UpdateTeamScheme(team)
  2824. require.Nil(t, err)
  2825. th.RemovePermissionFromRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole)
  2826. defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole)
  2827. moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
  2828. require.Nil(t, res.Error)
  2829. for _, moderation := range moderations {
  2830. if moderation.Name == model.PERMISSION_CREATE_POST.Id {
  2831. require.Equal(t, moderation.Roles.Members.Value, true)
  2832. require.Equal(t, moderation.Roles.Members.Enabled, true)
  2833. require.Equal(t, moderation.Roles.Guests.Value, false)
  2834. require.Equal(t, moderation.Roles.Guests.Enabled, false)
  2835. }
  2836. }
  2837. })
  2838. t.Run("Returns value false and enabled true for permissions that are not present in channel scheme but present in team scheme", func(t *testing.T) {
  2839. scheme := th.SetupChannelScheme()
  2840. channel.SchemeId = &scheme.Id
  2841. _, err := th.App.UpdateChannelScheme(channel)
  2842. require.Nil(t, err)
  2843. th.RemovePermissionFromRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole)
  2844. defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole)
  2845. moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
  2846. require.Nil(t, res.Error)
  2847. for _, moderation := range moderations {
  2848. if moderation.Name == model.PERMISSION_CREATE_POST.Id {
  2849. require.Equal(t, moderation.Roles.Members.Value, true)
  2850. require.Equal(t, moderation.Roles.Members.Enabled, true)
  2851. require.Equal(t, moderation.Roles.Guests.Value, false)
  2852. require.Equal(t, moderation.Roles.Guests.Enabled, true)
  2853. }
  2854. }
  2855. })
  2856. t.Run("Returns value false and enabled false for permissions that are not present in channel & team scheme", func(t *testing.T) {
  2857. teamScheme := th.SetupTeamScheme()
  2858. team.SchemeId = &teamScheme.Id
  2859. th.App.UpdateTeamScheme(team)
  2860. scheme := th.SetupChannelScheme()
  2861. channel.SchemeId = &scheme.Id
  2862. th.App.UpdateChannelScheme(channel)
  2863. th.RemovePermissionFromRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole)
  2864. th.RemovePermissionFromRole(model.PERMISSION_CREATE_POST.Id, teamScheme.DefaultChannelGuestRole)
  2865. defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole)
  2866. defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, teamScheme.DefaultChannelGuestRole)
  2867. moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
  2868. require.Nil(t, res.Error)
  2869. for _, moderation := range moderations {
  2870. if moderation.Name == model.PERMISSION_CREATE_POST.Id {
  2871. require.Equal(t, moderation.Roles.Members.Value, true)
  2872. require.Equal(t, moderation.Roles.Members.Enabled, true)
  2873. require.Equal(t, moderation.Roles.Guests.Value, false)
  2874. require.Equal(t, moderation.Roles.Guests.Enabled, false)
  2875. }
  2876. }
  2877. })
  2878. t.Run("Retuns the correct value for manage_members depending on whether the channel is public or private", func(t *testing.T) {
  2879. scheme := th.SetupTeamScheme()
  2880. team.SchemeId = &scheme.Id
  2881. _, err := th.App.UpdateTeamScheme(team)
  2882. require.Nil(t, err)
  2883. th.RemovePermissionFromRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, scheme.DefaultChannelUserRole)
  2884. defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelUserRole)
  2885. // public channel does not have the permission
  2886. moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
  2887. require.Nil(t, res.Error)
  2888. for _, moderation := range moderations {
  2889. if moderation.Name == "manage_members" {
  2890. require.Equal(t, moderation.Roles.Members.Value, false)
  2891. }
  2892. }
  2893. // private channel does have the permission
  2894. moderations, res = th.SystemAdminClient.GetChannelModerations(th.BasicPrivateChannel.Id, "")
  2895. require.Nil(t, res.Error)
  2896. for _, moderation := range moderations {
  2897. if moderation.Name == "manage_members" {
  2898. require.Equal(t, moderation.Roles.Members.Value, true)
  2899. }
  2900. }
  2901. })
  2902. t.Run("Does not return an error if the team scheme has a blank DefaultChannelGuestRole field", func(t *testing.T) {
  2903. scheme := th.SetupTeamScheme()
  2904. scheme.DefaultChannelGuestRole = ""
  2905. mockStore := mocks.Store{}
  2906. mockSchemeStore := mocks.SchemeStore{}
  2907. mockSchemeStore.On("Get", mock.Anything).Return(scheme, nil)
  2908. mockStore.On("Scheme").Return(&mockSchemeStore)
  2909. mockStore.On("Team").Return(th.App.Srv().Store.Team())
  2910. mockStore.On("Channel").Return(th.App.Srv().Store.Channel())
  2911. mockStore.On("User").Return(th.App.Srv().Store.User())
  2912. mockStore.On("Post").Return(th.App.Srv().Store.Post())
  2913. mockStore.On("FileInfo").Return(th.App.Srv().Store.FileInfo())
  2914. mockStore.On("Webhook").Return(th.App.Srv().Store.Webhook())
  2915. mockStore.On("System").Return(th.App.Srv().Store.System())
  2916. mockStore.On("License").Return(th.App.Srv().Store.License())
  2917. mockStore.On("Role").Return(th.App.Srv().Store.Role())
  2918. mockStore.On("Close").Return(nil)
  2919. th.App.Srv().Store = &mockStore
  2920. team.SchemeId = &scheme.Id
  2921. _, err := th.App.UpdateTeamScheme(team)
  2922. require.Nil(t, err)
  2923. _, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
  2924. require.Nil(t, res.Error)
  2925. })
  2926. }
  2927. func TestPatchChannelModerations(t *testing.T) {
  2928. th := Setup(t).InitBasic()
  2929. defer th.TearDown()
  2930. channel := th.BasicChannel
  2931. emptyPatch := []*model.ChannelModerationPatch{}
  2932. createPosts := model.CHANNEL_MODERATED_PERMISSIONS[0]
  2933. th.App.SetPhase2PermissionsMigrationStatus(true)
  2934. t.Run("Errors without a license", func(t *testing.T) {
  2935. _, res := th.SystemAdminClient.PatchChannelModerations(channel.Id, emptyPatch)
  2936. require.Equal(t, "api.channel.patch_channel_moderations.license.error", res.Error.Id)
  2937. })
  2938. th.App.Srv().SetLicense(model.NewTestLicense())
  2939. t.Run("Errors as a non sysadmin", func(t *testing.T) {
  2940. _, res := th.Client.PatchChannelModerations(channel.Id, emptyPatch)
  2941. require.Equal(t, "api.context.permissions.app_error", res.Error.Id)
  2942. })
  2943. th.App.Srv().SetLicense(model.NewTestLicense())
  2944. t.Run("Returns default moderations with empty patch", func(t *testing.T) {
  2945. moderations, res := th.SystemAdminClient.PatchChannelModerations(channel.Id, emptyPatch)
  2946. require.Nil(t, res.Error)
  2947. require.Equal(t, len(moderations), 4)
  2948. for _, moderation := range moderations {
  2949. if moderation.Name == "manage_members" {
  2950. require.Empty(t, moderation.Roles.Guests)
  2951. } else {
  2952. require.Equal(t, moderation.Roles.Guests.Value, true)
  2953. require.Equal(t, moderation.Roles.Guests.Enabled, true)
  2954. }
  2955. require.Equal(t, moderation.Roles.Members.Value, true)
  2956. require.Equal(t, moderation.Roles.Members.Enabled, true)
  2957. }
  2958. require.Nil(t, channel.SchemeId)
  2959. })
  2960. t.Run("Creates a scheme and returns the updated channel moderations when patching an existing permission", func(t *testing.T) {
  2961. patch := []*model.ChannelModerationPatch{
  2962. {
  2963. Name: &createPosts,
  2964. Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(false)},
  2965. },
  2966. }
  2967. moderations, res := th.SystemAdminClient.PatchChannelModerations(channel.Id, patch)
  2968. require.Nil(t, res.Error)
  2969. require.Equal(t, len(moderations), 4)
  2970. for _, moderation := range moderations {
  2971. if moderation.Name == "manage_members" {
  2972. require.Empty(t, moderation.Roles.Guests)
  2973. } else {
  2974. require.Equal(t, moderation.Roles.Guests.Value, true)
  2975. require.Equal(t, moderation.Roles.Guests.Enabled, true)
  2976. }
  2977. if moderation.Name == createPosts {
  2978. require.Equal(t, moderation.Roles.Members.Value, false)
  2979. require.Equal(t, moderation.Roles.Members.Enabled, true)
  2980. } else {
  2981. require.Equal(t, moderation.Roles.Members.Value, true)
  2982. require.Equal(t, moderation.Roles.Members.Enabled, true)
  2983. }
  2984. }
  2985. channel, _ = th.App.GetChannel(channel.Id)
  2986. require.NotNil(t, channel.SchemeId)
  2987. })
  2988. t.Run("Removes the existing scheme when moderated permissions are set back to higher scoped values", func(t *testing.T) {
  2989. channel, _ = th.App.GetChannel(channel.Id)
  2990. schemeId := channel.SchemeId
  2991. scheme, _ := th.App.GetScheme(*schemeId)
  2992. require.Equal(t, scheme.DeleteAt, int64(0))
  2993. patch := []*model.ChannelModerationPatch{
  2994. {
  2995. Name: &createPosts,
  2996. Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(true)},
  2997. },
  2998. }
  2999. moderations, res := th.SystemAdminClient.PatchChannelModerations(channel.Id, patch)
  3000. require.Nil(t, res.Error)
  3001. require.Equal(t, len(moderations), 4)
  3002. for _, moderation := range moderations {
  3003. if moderation.Name == "manage_members" {
  3004. require.Empty(t, moderation.Roles.Guests)
  3005. } else {
  3006. require.Equal(t, moderation.Roles.Guests.Value, true)
  3007. require.Equal(t, moderation.Roles.Guests.Enabled, true)
  3008. }
  3009. require.Equal(t, moderation.Roles.Members.Value, true)
  3010. require.Equal(t, moderation.Roles.Members.Enabled, true)
  3011. }
  3012. channel, _ = th.App.GetChannel(channel.Id)
  3013. require.Nil(t, channel.SchemeId)
  3014. scheme, _ = th.App.GetScheme(*schemeId)
  3015. require.NotEqual(t, scheme.DeleteAt, int64(0))
  3016. })
  3017. t.Run("Does not return an error if the team scheme has a blank DefaultChannelGuestRole field", func(t *testing.T) {
  3018. team := th.BasicTeam
  3019. scheme := th.SetupTeamScheme()
  3020. scheme.DefaultChannelGuestRole = ""
  3021. mockStore := mocks.Store{}
  3022. mockSchemeStore := mocks.SchemeStore{}
  3023. mockSchemeStore.On("Get", mock.Anything).Return(scheme, nil)
  3024. mockSchemeStore.On("Save", mock.Anything).Return(scheme, nil)
  3025. mockSchemeStore.On("Delete", mock.Anything).Return(scheme, nil)
  3026. mockStore.On("Scheme").Return(&mockSchemeStore)
  3027. mockStore.On("Team").Return(th.App.Srv().Store.Team())
  3028. mockStore.On("Channel").Return(th.App.Srv().Store.Channel())
  3029. mockStore.On("User").Return(th.App.Srv().Store.User())
  3030. mockStore.On("Post").Return(th.App.Srv().Store.Post())
  3031. mockStore.On("FileInfo").Return(th.App.Srv().Store.FileInfo())
  3032. mockStore.On("Webhook").Return(th.App.Srv().Store.Webhook())
  3033. mockStore.On("System").Return(th.App.Srv().Store.System())
  3034. mockStore.On("License").Return(th.App.Srv().Store.License())
  3035. mockStore.On("Role").Return(th.App.Srv().Store.Role())
  3036. mockStore.On("Close").Return(nil)
  3037. th.App.Srv().Store = &mockStore
  3038. team.SchemeId = &scheme.Id
  3039. _, err := th.App.UpdateTeamScheme(team)
  3040. require.Nil(t, err)
  3041. moderations, res := th.SystemAdminClient.PatchChannelModerations(channel.Id, emptyPatch)
  3042. require.Nil(t, res.Error)
  3043. require.Equal(t, len(moderations), 4)
  3044. for _, moderation := range moderations {
  3045. if moderation.Name == "manage_members" {
  3046. require.Empty(t, moderation.Roles.Guests)
  3047. } else {
  3048. require.Equal(t, moderation.Roles.Guests.Value, false)
  3049. require.Equal(t, moderation.Roles.Guests.Enabled, false)
  3050. }
  3051. require.Equal(t, moderation.Roles.Members.Value, true)
  3052. require.Equal(t, moderation.Roles.Members.Enabled, true)
  3053. }
  3054. patch := []*model.ChannelModerationPatch{
  3055. {
  3056. Name: &createPosts,
  3057. Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(true)},
  3058. },
  3059. }
  3060. moderations, res = th.SystemAdminClient.PatchChannelModerations(channel.Id, patch)
  3061. require.Nil(t, res.Error)
  3062. require.Equal(t, len(moderations), 4)
  3063. for _, moderation := range moderations {
  3064. if moderation.Name == "manage_members" {
  3065. require.Empty(t, moderation.Roles.Guests)
  3066. } else {
  3067. require.Equal(t, moderation.Roles.Guests.Value, false)
  3068. require.Equal(t, moderation.Roles.Guests.Enabled, false)
  3069. }
  3070. require.Equal(t, moderation.Roles.Members.Value, true)
  3071. require.Equal(t, moderation.Roles.Members.Enabled, true)
  3072. }
  3073. })
  3074. }
  3075. func TestGetChannelMemberCountsByGroup(t *testing.T) {
  3076. th := Setup(t).InitBasic()
  3077. defer th.TearDown()
  3078. channel := th.BasicChannel
  3079. t.Run("Errors without a license", func(t *testing.T) {
  3080. _, res := th.SystemAdminClient.GetChannelMemberCountsByGroup(channel.Id, false, "")
  3081. require.Equal(t, "api.channel.channel_member_counts_by_group.license.error", res.Error.Id)
  3082. })
  3083. th.App.Srv().SetLicense(model.NewTestLicense())
  3084. t.Run("Errors without read permission to the channel", func(t *testing.T) {
  3085. _, res := th.Client.GetChannelMemberCountsByGroup(model.NewId(), false, "")
  3086. require.Equal(t, "api.context.permissions.app_error", res.Error.Id)
  3087. })
  3088. t.Run("Returns empty for a channel with no members or groups", func(t *testing.T) {
  3089. memberCounts, _ := th.SystemAdminClient.GetChannelMemberCountsByGroup(channel.Id, false, "")
  3090. require.Equal(t, []*model.ChannelMemberCountByGroup{}, memberCounts)
  3091. })
  3092. user := th.BasicUser
  3093. user.Timezone["useAutomaticTimezone"] = "false"
  3094. user.Timezone["manualTimezone"] = "XOXO/BLABLA"
  3095. _, err := th.App.UpsertGroupMember(th.Group.Id, user.Id)
  3096. require.Nil(t, err)
  3097. _, resp := th.SystemAdminClient.UpdateUser(user)
  3098. CheckNoError(t, resp)
  3099. user2 := th.BasicUser2
  3100. user2.Timezone["automaticTimezone"] = "NoWhere/Island"
  3101. _, err = th.App.UpsertGroupMember(th.Group.Id, user2.Id)
  3102. require.Nil(t, err)
  3103. _, resp = th.SystemAdminClient.UpdateUser(user2)
  3104. CheckNoError(t, resp)
  3105. t.Run("Returns users in group without timezones", func(t *testing.T) {
  3106. memberCounts, _ := th.SystemAdminClient.GetChannelMemberCountsByGroup(channel.Id, false, "")
  3107. expectedMemberCounts := []*model.ChannelMemberCountByGroup{
  3108. {
  3109. GroupId: th.Group.Id,
  3110. ChannelMemberCount: 2,
  3111. ChannelMemberTimezonesCount: 0,
  3112. },
  3113. }
  3114. require.Equal(t, expectedMemberCounts, memberCounts)
  3115. })
  3116. t.Run("Returns users in group with timezones", func(t *testing.T) {
  3117. memberCounts, _ := th.SystemAdminClient.GetChannelMemberCountsByGroup(channel.Id, true, "")
  3118. expectedMemberCounts := []*model.ChannelMemberCountByGroup{
  3119. {
  3120. GroupId: th.Group.Id,
  3121. ChannelMemberCount: 2,
  3122. ChannelMemberTimezonesCount: 2,
  3123. },
  3124. }
  3125. require.Equal(t, expectedMemberCounts, memberCounts)
  3126. })
  3127. id := model.NewId()
  3128. group := &model.Group{
  3129. DisplayName: "dn_" + id,
  3130. Name: model.NewString("name" + id),
  3131. Source: model.GroupSourceLdap,
  3132. RemoteId: model.NewId(),
  3133. }
  3134. _, err = th.App.CreateGroup(group)
  3135. require.Nil(t, err)
  3136. _, err = th.App.UpsertGroupMember(group.Id, user.Id)
  3137. require.Nil(t, err)
  3138. t.Run("Returns multiple groups with users in group with timezones", func(t *testing.T) {
  3139. memberCounts, _ := th.SystemAdminClient.GetChannelMemberCountsByGroup(channel.Id, true, "")
  3140. expectedMemberCounts := []*model.ChannelMemberCountByGroup{
  3141. {
  3142. GroupId: group.Id,
  3143. ChannelMemberCount: 1,
  3144. ChannelMemberTimezonesCount: 1,
  3145. },
  3146. {
  3147. GroupId: th.Group.Id,
  3148. ChannelMemberCount: 2,
  3149. ChannelMemberTimezonesCount: 2,
  3150. },
  3151. }
  3152. require.ElementsMatch(t, expectedMemberCounts, memberCounts)
  3153. })
  3154. }
  3155. func TestMoveChannel(t *testing.T) {
  3156. th := Setup(t).InitBasic()
  3157. defer th.TearDown()
  3158. Client := th.Client
  3159. team1 := th.BasicTeam
  3160. team2 := th.CreateTeam()
  3161. t.Run("Should move channel", func(t *testing.T) {
  3162. publicChannel := th.CreatePublicChannel()
  3163. ch, resp := th.SystemAdminClient.MoveChannel(publicChannel.Id, team2.Id, false)
  3164. require.Nil(t, resp.Error)
  3165. require.Equal(t, team2.Id, ch.TeamId)
  3166. })
  3167. t.Run("Should fail when trying to move a private channel", func(t *testing.T) {
  3168. channel := th.CreatePrivateChannel()
  3169. _, resp := Client.MoveChannel(channel.Id, team1.Id, false)
  3170. require.NotNil(t, resp.Error)
  3171. CheckErrorMessage(t, resp, "api.channel.move_channel.type.invalid")
  3172. })
  3173. t.Run("Should fail when trying to move a DM channel", func(t *testing.T) {
  3174. user := th.CreateUser()
  3175. dmChannel := th.CreateDmChannel(user)
  3176. _, resp := Client.MoveChannel(dmChannel.Id, team1.Id, false)
  3177. require.NotNil(t, resp.Error)
  3178. CheckErrorMessage(t, resp, "api.channel.move_channel.type.invalid")
  3179. })
  3180. t.Run("Should fail when trying to move a group channel", func(t *testing.T) {
  3181. user := th.CreateUser()
  3182. gmChannel, err := th.App.CreateGroupChannel([]string{th.BasicUser.Id, th.SystemAdminUser.Id, th.TeamAdminUser.Id}, user.Id)
  3183. require.Nil(t, err)
  3184. _, resp := Client.MoveChannel(gmChannel.Id, team1.Id, false)
  3185. require.NotNil(t, resp.Error)
  3186. CheckErrorMessage(t, resp, "api.channel.move_channel.type.invalid")
  3187. })
  3188. t.Run("Should fail due to permissions", func(t *testing.T) {
  3189. publicChannel := th.CreatePublicChannel()
  3190. _, resp := Client.MoveChannel(publicChannel.Id, team1.Id, false)
  3191. require.NotNil(t, resp.Error)
  3192. CheckErrorMessage(t, resp, "api.context.permissions.app_error")
  3193. })
  3194. t.Run("Should fail to move channel due to a member not member of target team", func(t *testing.T) {
  3195. publicChannel := th.CreatePublicChannel()
  3196. user := th.BasicUser
  3197. _, resp := th.SystemAdminClient.RemoveTeamMember(team2.Id, user.Id)
  3198. CheckNoError(t, resp)
  3199. _, resp = th.SystemAdminClient.AddChannelMember(publicChannel.Id, user.Id)
  3200. CheckNoError(t, resp)
  3201. _, resp = th.SystemAdminClient.MoveChannel(publicChannel.Id, team2.Id, false)
  3202. require.NotNil(t, resp.Error)
  3203. CheckErrorMessage(t, resp, "app.channel.move_channel.members_do_not_match.error")
  3204. })
  3205. t.Run("Should be able to (force) move channel by a member that is not member of target team", func(t *testing.T) {
  3206. publicChannel := th.CreatePublicChannel()
  3207. user := th.BasicUser
  3208. _, resp := th.SystemAdminClient.RemoveTeamMember(team2.Id, user.Id)
  3209. CheckNoError(t, resp)
  3210. _, resp = th.SystemAdminClient.AddChannelMember(publicChannel.Id, user.Id)
  3211. CheckNoError(t, resp)
  3212. newChannel, resp := th.SystemAdminClient.MoveChannel(publicChannel.Id, team2.Id, true)
  3213. require.Nil(t, resp.Error)
  3214. require.Equal(t, team2.Id, newChannel.TeamId)
  3215. })
  3216. }
  3217. func TestUpdateCategoryForTeamForUser(t *testing.T) {
  3218. t.Run("should update the channel order of the Channels category", func(t *testing.T) {
  3219. th := Setup(t).InitBasic()
  3220. defer th.TearDown()
  3221. categories, resp := th.Client.GetSidebarCategoriesForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
  3222. require.Nil(t, resp.Error)
  3223. require.Len(t, categories.Categories, 3)
  3224. require.Len(t, categories.Order, 3)
  3225. channelsCategory := categories.Categories[1]
  3226. require.Equal(t, model.SidebarCategoryChannels, channelsCategory.Type)
  3227. require.Len(t, channelsCategory.Channels, 5) // Town Square, Off Topic, and the 3 channels created by InitBasic
  3228. // Should return the correct values from the API
  3229. updatedCategory := &model.SidebarCategoryWithChannels{
  3230. SidebarCategory: channelsCategory.SidebarCategory,
  3231. Channels: []string{channelsCategory.Channels[1], channelsCategory.Channels[0], channelsCategory.Channels[4], channelsCategory.Channels[3], channelsCategory.Channels[2]},
  3232. }
  3233. received, resp := th.Client.UpdateSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
  3234. assert.Nil(t, resp.Error)
  3235. assert.Equal(t, channelsCategory.Id, received.Id)
  3236. assert.Equal(t, updatedCategory.Channels, received.Channels)
  3237. // And when requesting the category later
  3238. received, resp = th.Client.GetSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, channelsCategory.Id, "")
  3239. assert.Nil(t, resp.Error)
  3240. assert.Equal(t, channelsCategory.Id, received.Id)
  3241. assert.Equal(t, updatedCategory.Channels, received.Channels)
  3242. })
  3243. t.Run("should update the sort order of the DM category", func(t *testing.T) {
  3244. th := Setup(t).InitBasic()
  3245. defer th.TearDown()
  3246. categories, resp := th.Client.GetSidebarCategoriesForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
  3247. require.Nil(t, resp.Error)
  3248. require.Len(t, categories.Categories, 3)
  3249. require.Len(t, categories.Order, 3)
  3250. dmsCategory := categories.Categories[2]
  3251. require.Equal(t, model.SidebarCategoryDirectMessages, dmsCategory.Type)
  3252. require.Equal(t, model.SidebarCategorySortRecent, dmsCategory.Sorting)
  3253. // Should return the correct values from the API
  3254. updatedCategory := &model.SidebarCategoryWithChannels{
  3255. SidebarCategory: dmsCategory.SidebarCategory,
  3256. Channels: dmsCategory.Channels,
  3257. }
  3258. updatedCategory.Sorting = model.SidebarCategorySortAlphabetical
  3259. received, resp := th.Client.UpdateSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, dmsCategory.Id, updatedCategory)
  3260. assert.Nil(t, resp.Error)
  3261. assert.Equal(t, dmsCategory.Id, received.Id)
  3262. assert.Equal(t, model.SidebarCategorySortAlphabetical, received.Sorting)
  3263. // And when requesting the category later
  3264. received, resp = th.Client.GetSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, dmsCategory.Id, "")
  3265. assert.Nil(t, resp.Error)
  3266. assert.Equal(t, dmsCategory.Id, received.Id)
  3267. assert.Equal(t, model.SidebarCategorySortAlphabetical, received.Sorting)
  3268. })
  3269. t.Run("should update the display name of a custom category", func(t *testing.T) {
  3270. th := Setup(t).InitBasic()
  3271. defer th.TearDown()
  3272. customCategory, resp := th.Client.CreateSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{
  3273. SidebarCategory: model.SidebarCategory{
  3274. UserId: th.BasicUser.Id,
  3275. TeamId: th.BasicTeam.Id,
  3276. DisplayName: "custom123",
  3277. },
  3278. })
  3279. require.Nil(t, resp.Error)
  3280. require.Equal(t, "custom123", customCategory.DisplayName)
  3281. // Should return the correct values from the API
  3282. updatedCategory := &model.SidebarCategoryWithChannels{
  3283. SidebarCategory: customCategory.SidebarCategory,
  3284. Channels: customCategory.Channels,
  3285. }
  3286. updatedCategory.DisplayName = "abcCustom"
  3287. received, resp := th.Client.UpdateSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, customCategory.Id, updatedCategory)
  3288. assert.Nil(t, resp.Error)
  3289. assert.Equal(t, customCategory.Id, received.Id)
  3290. assert.Equal(t, updatedCategory.DisplayName, received.DisplayName)
  3291. // And when requesting the category later
  3292. received, resp = th.Client.GetSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, customCategory.Id, "")
  3293. assert.Nil(t, resp.Error)
  3294. assert.Equal(t, customCategory.Id, received.Id)
  3295. assert.Equal(t, updatedCategory.DisplayName, received.DisplayName)
  3296. })
  3297. t.Run("should update the channel order of the category even if it contains archived channels", func(t *testing.T) {
  3298. th := Setup(t).InitBasic()
  3299. defer th.TearDown()
  3300. categories, resp := th.Client.GetSidebarCategoriesForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
  3301. require.Nil(t, resp.Error)
  3302. require.Len(t, categories.Categories, 3)
  3303. require.Len(t, categories.Order, 3)
  3304. channelsCategory := categories.Categories[1]
  3305. require.Equal(t, model.SidebarCategoryChannels, channelsCategory.Type)
  3306. require.Len(t, channelsCategory.Channels, 5) // Town Square, Off Topic, and the 3 channels created by InitBasic
  3307. // Delete one of the channels
  3308. _, resp = th.Client.DeleteChannel(th.BasicChannel.Id)
  3309. require.Nil(t, resp.Error)
  3310. // Should still be able to reorder the channels
  3311. updatedCategory := &model.SidebarCategoryWithChannels{
  3312. SidebarCategory: channelsCategory.SidebarCategory,
  3313. Channels: []string{channelsCategory.Channels[1], channelsCategory.Channels[0], channelsCategory.Channels[4], channelsCategory.Channels[3], channelsCategory.Channels[2]},
  3314. }
  3315. received, resp := th.Client.UpdateSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
  3316. require.Nil(t, resp.Error)
  3317. assert.Equal(t, channelsCategory.Id, received.Id)
  3318. assert.Equal(t, updatedCategory.Channels, received.Channels)
  3319. })
  3320. }