1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105 |
- // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
- // See LICENSE.txt for license information.
- package api4
- import (
- "fmt"
- "net/http"
- "sort"
- "strings"
- "sync"
- "testing"
- "time"
- "github.com/mattermost/mattermost-server/v5/model"
- "github.com/mattermost/mattermost-server/v5/plugin/plugintest/mock"
- "github.com/mattermost/mattermost-server/v5/store/storetest/mocks"
- "github.com/mattermost/mattermost-server/v5/utils"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
- )
- func TestCreateChannel(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- team := th.BasicTeam
- channel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id}
- private := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_PRIVATE, TeamId: team.Id}
- rchannel, resp := Client.CreateChannel(channel)
- CheckNoError(t, resp)
- CheckCreatedStatus(t, resp)
- require.Equal(t, channel.Name, rchannel.Name, "names did not match")
- require.Equal(t, channel.DisplayName, rchannel.DisplayName, "display names did not match")
- require.Equal(t, channel.TeamId, rchannel.TeamId, "team ids did not match")
- rprivate, resp := Client.CreateChannel(private)
- CheckNoError(t, resp)
- require.Equal(t, private.Name, rprivate.Name, "names did not match")
- require.Equal(t, model.CHANNEL_PRIVATE, rprivate.Type, "wrong channel type")
- require.Equal(t, th.BasicUser.Id, rprivate.CreatorId, "wrong creator id")
- _, resp = Client.CreateChannel(channel)
- CheckErrorMessage(t, resp, "store.sql_channel.save_channel.exists.app_error")
- CheckBadRequestStatus(t, resp)
- direct := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_DIRECT, TeamId: team.Id}
- _, resp = Client.CreateChannel(direct)
- CheckErrorMessage(t, resp, "api.channel.create_channel.direct_channel.app_error")
- CheckBadRequestStatus(t, resp)
- Client.Logout()
- _, resp = Client.CreateChannel(channel)
- CheckUnauthorizedStatus(t, resp)
- userNotOnTeam := th.CreateUser()
- Client.Login(userNotOnTeam.Email, userNotOnTeam.Password)
- _, resp = Client.CreateChannel(channel)
- CheckForbiddenStatus(t, resp)
- _, resp = Client.CreateChannel(private)
- CheckForbiddenStatus(t, resp)
- // Check the appropriate permissions are enforced.
- defaultRolePermissions := th.SaveDefaultRolePermissions()
- defer func() {
- th.RestoreDefaultRolePermissions(defaultRolePermissions)
- }()
- th.AddPermissionToRole(model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, model.TEAM_USER_ROLE_ID)
- th.AddPermissionToRole(model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, model.TEAM_USER_ROLE_ID)
- th.LoginBasic()
- channel.Name = GenerateTestChannelName()
- _, resp = Client.CreateChannel(channel)
- CheckNoError(t, resp)
- private.Name = GenerateTestChannelName()
- _, resp = Client.CreateChannel(private)
- CheckNoError(t, resp)
- th.AddPermissionToRole(model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, model.TEAM_ADMIN_ROLE_ID)
- th.AddPermissionToRole(model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, model.TEAM_ADMIN_ROLE_ID)
- th.RemovePermissionFromRole(model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, model.TEAM_USER_ROLE_ID)
- th.RemovePermissionFromRole(model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, model.TEAM_USER_ROLE_ID)
- _, resp = Client.CreateChannel(channel)
- CheckForbiddenStatus(t, resp)
- _, resp = Client.CreateChannel(private)
- CheckForbiddenStatus(t, resp)
- th.LoginTeamAdmin()
- channel.Name = GenerateTestChannelName()
- _, resp = Client.CreateChannel(channel)
- CheckNoError(t, resp)
- private.Name = GenerateTestChannelName()
- _, resp = Client.CreateChannel(private)
- CheckNoError(t, resp)
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
- channel.Name = GenerateTestChannelName()
- _, resp = client.CreateChannel(channel)
- CheckNoError(t, resp)
- private.Name = GenerateTestChannelName()
- _, resp = client.CreateChannel(private)
- CheckNoError(t, resp)
- })
- // Test posting Garbage
- r, err := Client.DoApiPost("/channels", "garbage")
- require.NotNil(t, err, "expected error")
- require.Equal(t, http.StatusBadRequest, r.StatusCode, "Expected 400 Bad Request")
- // Test GroupConstrained flag
- groupConstrainedChannel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id, GroupConstrained: model.NewBool(true)}
- rchannel, resp = Client.CreateChannel(groupConstrainedChannel)
- CheckNoError(t, resp)
- require.Equal(t, *groupConstrainedChannel.GroupConstrained, *rchannel.GroupConstrained, "GroupConstrained flags do not match")
- }
- func TestUpdateChannel(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- team := th.BasicTeam
- channel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id}
- private := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_PRIVATE, TeamId: team.Id}
- channel, _ = Client.CreateChannel(channel)
- private, _ = Client.CreateChannel(private)
- //Update a open channel
- channel.DisplayName = "My new display name"
- channel.Header = "My fancy header"
- channel.Purpose = "Mattermost ftw!"
- newChannel, resp := Client.UpdateChannel(channel)
- CheckNoError(t, resp)
- require.Equal(t, channel.DisplayName, newChannel.DisplayName, "Update failed for DisplayName")
- require.Equal(t, channel.Header, newChannel.Header, "Update failed for Header")
- require.Equal(t, channel.Purpose, newChannel.Purpose, "Update failed for Purpose")
- // Test GroupConstrained flag
- channel.GroupConstrained = model.NewBool(true)
- rchannel, resp := Client.UpdateChannel(channel)
- CheckNoError(t, resp)
- CheckOKStatus(t, resp)
- require.Equal(t, *channel.GroupConstrained, *rchannel.GroupConstrained, "GroupConstrained flags do not match")
- //Update a private channel
- private.DisplayName = "My new display name for private channel"
- private.Header = "My fancy private header"
- private.Purpose = "Mattermost ftw! in private mode"
- newPrivateChannel, resp := Client.UpdateChannel(private)
- CheckNoError(t, resp)
- require.Equal(t, private.DisplayName, newPrivateChannel.DisplayName, "Update failed for DisplayName in private channel")
- require.Equal(t, private.Header, newPrivateChannel.Header, "Update failed for Header in private channel")
- require.Equal(t, private.Purpose, newPrivateChannel.Purpose, "Update failed for Purpose in private channel")
- // Test that changing the type fails and returns error
- private.Type = model.CHANNEL_OPEN
- newPrivateChannel, resp = Client.UpdateChannel(private)
- CheckBadRequestStatus(t, resp)
- // Test that keeping the same type succeeds
- private.Type = model.CHANNEL_PRIVATE
- newPrivateChannel, resp = Client.UpdateChannel(private)
- CheckNoError(t, resp)
- //Non existing channel
- channel1 := &model.Channel{DisplayName: "Test API Name for apiv4", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id}
- _, resp = Client.UpdateChannel(channel1)
- CheckNotFoundStatus(t, resp)
- //Try to update with not logged user
- Client.Logout()
- _, resp = Client.UpdateChannel(channel)
- CheckUnauthorizedStatus(t, resp)
- //Try to update using another user
- user := th.CreateUser()
- Client.Login(user.Email, user.Password)
- channel.DisplayName = "Should not update"
- _, resp = Client.UpdateChannel(channel)
- CheckForbiddenStatus(t, resp)
- // Test updating the header of someone else's GM channel.
- user1 := th.CreateUser()
- user2 := th.CreateUser()
- user3 := th.CreateUser()
- groupChannel, resp := Client.CreateGroupChannel([]string{user1.Id, user2.Id})
- CheckNoError(t, resp)
- groupChannel.Header = "lolololol"
- Client.Logout()
- Client.Login(user3.Email, user3.Password)
- _, resp = Client.UpdateChannel(groupChannel)
- CheckForbiddenStatus(t, resp)
- // Test updating the header of someone else's GM channel.
- Client.Logout()
- Client.Login(user.Email, user.Password)
- directChannel, resp := Client.CreateDirectChannel(user.Id, user1.Id)
- CheckNoError(t, resp)
- directChannel.Header = "lolololol"
- Client.Logout()
- Client.Login(user3.Email, user3.Password)
- _, resp = Client.UpdateChannel(directChannel)
- CheckForbiddenStatus(t, resp)
- }
- func TestPatchChannel(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- patch := &model.ChannelPatch{
- Name: new(string),
- DisplayName: new(string),
- Header: new(string),
- Purpose: new(string),
- }
- *patch.Name = model.NewId()
- *patch.DisplayName = model.NewId()
- *patch.Header = model.NewId()
- *patch.Purpose = model.NewId()
- channel, resp := Client.PatchChannel(th.BasicChannel.Id, patch)
- CheckNoError(t, resp)
- require.Equal(t, *patch.Name, channel.Name, "do not match")
- require.Equal(t, *patch.DisplayName, channel.DisplayName, "do not match")
- require.Equal(t, *patch.Header, channel.Header, "do not match")
- require.Equal(t, *patch.Purpose, channel.Purpose, "do not match")
- patch.Name = nil
- oldName := channel.Name
- channel, resp = Client.PatchChannel(th.BasicChannel.Id, patch)
- CheckNoError(t, resp)
- require.Equal(t, oldName, channel.Name, "should not have updated")
- // Test GroupConstrained flag
- patch.GroupConstrained = model.NewBool(true)
- rchannel, resp := Client.PatchChannel(th.BasicChannel.Id, patch)
- CheckNoError(t, resp)
- CheckOKStatus(t, resp)
- require.Equal(t, *rchannel.GroupConstrained, *patch.GroupConstrained, "GroupConstrained flags do not match")
- patch.GroupConstrained = nil
- _, resp = Client.PatchChannel("junk", patch)
- CheckBadRequestStatus(t, resp)
- _, resp = Client.PatchChannel(model.NewId(), patch)
- CheckNotFoundStatus(t, resp)
- user := th.CreateUser()
- Client.Login(user.Email, user.Password)
- _, resp = Client.PatchChannel(th.BasicChannel.Id, patch)
- CheckForbiddenStatus(t, resp)
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
- _, resp = client.PatchChannel(th.BasicChannel.Id, patch)
- CheckNoError(t, resp)
- _, resp = client.PatchChannel(th.BasicPrivateChannel.Id, patch)
- CheckNoError(t, resp)
- })
- // Test updating the header of someone else's GM channel.
- user1 := th.CreateUser()
- user2 := th.CreateUser()
- user3 := th.CreateUser()
- groupChannel, resp := Client.CreateGroupChannel([]string{user1.Id, user2.Id})
- CheckNoError(t, resp)
- Client.Logout()
- Client.Login(user3.Email, user3.Password)
- channelPatch := &model.ChannelPatch{}
- channelPatch.Header = new(string)
- *channelPatch.Header = "lolololol"
- _, resp = Client.PatchChannel(groupChannel.Id, channelPatch)
- CheckForbiddenStatus(t, resp)
- // Test updating the header of someone else's GM channel.
- Client.Logout()
- Client.Login(user.Email, user.Password)
- directChannel, resp := Client.CreateDirectChannel(user.Id, user1.Id)
- CheckNoError(t, resp)
- Client.Logout()
- Client.Login(user3.Email, user3.Password)
- _, resp = Client.PatchChannel(directChannel.Id, channelPatch)
- CheckForbiddenStatus(t, resp)
- }
- func TestChannelUnicodeNames(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- team := th.BasicTeam
- t.Run("create channel unicode", func(t *testing.T) {
- channel := &model.Channel{
- Name: "\u206cenglish\u206dchannel",
- DisplayName: "The \u206cEnglish\u206d Channel",
- Type: model.CHANNEL_OPEN,
- TeamId: team.Id}
- rchannel, resp := Client.CreateChannel(channel)
- CheckNoError(t, resp)
- CheckCreatedStatus(t, resp)
- require.Equal(t, "englishchannel", rchannel.Name, "bad unicode should be filtered from name")
- require.Equal(t, "The English Channel", rchannel.DisplayName, "bad unicode should be filtered from display name")
- })
- t.Run("update channel unicode", func(t *testing.T) {
- channel := &model.Channel{
- DisplayName: "Test API Name",
- Name: GenerateTestChannelName(),
- Type: model.CHANNEL_OPEN,
- TeamId: team.Id,
- }
- channel, _ = Client.CreateChannel(channel)
- channel.Name = "\u206ahistorychannel"
- channel.DisplayName = "UFO's and \ufff9stuff\ufffb."
- newChannel, resp := Client.UpdateChannel(channel)
- CheckNoError(t, resp)
- require.Equal(t, "historychannel", newChannel.Name, "bad unicode should be filtered from name")
- require.Equal(t, "UFO's and stuff.", newChannel.DisplayName, "bad unicode should be filtered from display name")
- })
- t.Run("patch channel unicode", func(t *testing.T) {
- patch := &model.ChannelPatch{
- Name: new(string),
- DisplayName: new(string),
- Header: new(string),
- Purpose: new(string),
- }
- *patch.Name = "\u206ecommunitychannel\u206f"
- *patch.DisplayName = "Natalie Tran's \ufffcAwesome Channel"
- channel, resp := Client.PatchChannel(th.BasicChannel.Id, patch)
- CheckNoError(t, resp)
- require.Equal(t, "communitychannel", channel.Name, "bad unicode should be filtered from name")
- require.Equal(t, "Natalie Tran's Awesome Channel", channel.DisplayName, "bad unicode should be filtered from display name")
- })
- }
- func TestCreateDirectChannel(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- user1 := th.BasicUser
- user2 := th.BasicUser2
- user3 := th.CreateUser()
- dm, resp := Client.CreateDirectChannel(user1.Id, user2.Id)
- CheckNoError(t, resp)
- channelName := ""
- if user2.Id > user1.Id {
- channelName = user1.Id + "__" + user2.Id
- } else {
- channelName = user2.Id + "__" + user1.Id
- }
- require.Equal(t, channelName, dm.Name, "dm name didn't match")
- _, resp = Client.CreateDirectChannel("junk", user2.Id)
- CheckBadRequestStatus(t, resp)
- _, resp = Client.CreateDirectChannel(user1.Id, model.NewId())
- CheckBadRequestStatus(t, resp)
- _, resp = Client.CreateDirectChannel(model.NewId(), user1.Id)
- CheckBadRequestStatus(t, resp)
- _, resp = Client.CreateDirectChannel(model.NewId(), user2.Id)
- CheckForbiddenStatus(t, resp)
- r, err := Client.DoApiPost("/channels/direct", "garbage")
- require.NotNil(t, err)
- require.Equal(t, http.StatusBadRequest, r.StatusCode)
- Client.Logout()
- _, resp = Client.CreateDirectChannel(model.NewId(), user2.Id)
- CheckUnauthorizedStatus(t, resp)
- _, resp = th.SystemAdminClient.CreateDirectChannel(user3.Id, user2.Id)
- CheckNoError(t, resp)
- }
- func TestCreateDirectChannelAsGuest(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- user1 := th.BasicUser
- enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable
- defer func() {
- th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts })
- th.App.Srv().RemoveLicense()
- }()
- th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true })
- th.App.Srv().SetLicense(model.NewTestLicense())
- id := model.NewId()
- guest := &model.User{
- Email: "success+" + id + "@simulator.amazonses.com",
- Username: "un_" + id,
- Nickname: "nn_" + id,
- Password: "Password1",
- EmailVerified: true,
- }
- guest, err := th.App.CreateGuest(guest)
- require.Nil(t, err)
- _, resp := Client.Login(guest.Username, "Password1")
- CheckNoError(t, resp)
- t.Run("Try to created DM with not visible user", func(t *testing.T) {
- _, resp := Client.CreateDirectChannel(guest.Id, user1.Id)
- CheckForbiddenStatus(t, resp)
- _, resp = Client.CreateDirectChannel(user1.Id, guest.Id)
- CheckForbiddenStatus(t, resp)
- })
- t.Run("Creating DM with visible user", func(t *testing.T) {
- th.LinkUserToTeam(guest, th.BasicTeam)
- th.AddUserToChannel(guest, th.BasicChannel)
- _, resp := Client.CreateDirectChannel(guest.Id, user1.Id)
- CheckNoError(t, resp)
- })
- }
- func TestDeleteDirectChannel(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- user := th.BasicUser
- user2 := th.BasicUser2
- rgc, resp := Client.CreateDirectChannel(user.Id, user2.Id)
- CheckNoError(t, resp)
- CheckCreatedStatus(t, resp)
- require.NotNil(t, rgc, "should have created a direct channel")
- deleted, resp := Client.DeleteChannel(rgc.Id)
- CheckErrorMessage(t, resp, "api.channel.delete_channel.type.invalid")
- require.False(t, deleted, "should not have been able to delete direct channel.")
- }
- func TestCreateGroupChannel(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- user := th.BasicUser
- user2 := th.BasicUser2
- user3 := th.CreateUser()
- userIds := []string{user.Id, user2.Id, user3.Id}
- rgc, resp := Client.CreateGroupChannel(userIds)
- CheckNoError(t, resp)
- CheckCreatedStatus(t, resp)
- require.NotNil(t, rgc, "should have created a group channel")
- require.Equal(t, model.CHANNEL_GROUP, rgc.Type, "should have created a channel of group type")
- m, _ := th.App.GetChannelMembersPage(rgc.Id, 0, 10)
- require.Len(t, *m, 3, "should have 3 channel members")
- // saving duplicate group channel
- rgc2, resp := Client.CreateGroupChannel([]string{user3.Id, user2.Id})
- CheckNoError(t, resp)
- require.Equal(t, rgc.Id, rgc2.Id, "should have returned existing channel")
- m2, _ := th.App.GetChannelMembersPage(rgc2.Id, 0, 10)
- require.Equal(t, m, m2)
- _, resp = Client.CreateGroupChannel([]string{user2.Id})
- CheckBadRequestStatus(t, resp)
- user4 := th.CreateUser()
- user5 := th.CreateUser()
- user6 := th.CreateUser()
- user7 := th.CreateUser()
- user8 := th.CreateUser()
- user9 := th.CreateUser()
- rgc, resp = Client.CreateGroupChannel([]string{user.Id, user2.Id, user3.Id, user4.Id, user5.Id, user6.Id, user7.Id, user8.Id, user9.Id})
- CheckBadRequestStatus(t, resp)
- require.Nil(t, rgc)
- _, resp = Client.CreateGroupChannel([]string{user.Id, user2.Id, user3.Id, GenerateTestId()})
- CheckBadRequestStatus(t, resp)
- _, resp = Client.CreateGroupChannel([]string{user.Id, user2.Id, user3.Id, "junk"})
- CheckBadRequestStatus(t, resp)
- Client.Logout()
- _, resp = Client.CreateGroupChannel(userIds)
- CheckUnauthorizedStatus(t, resp)
- _, resp = th.SystemAdminClient.CreateGroupChannel(userIds)
- CheckNoError(t, resp)
- }
- func TestCreateGroupChannelAsGuest(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- user1 := th.BasicUser
- user2 := th.BasicUser2
- user3 := th.CreateUser()
- user4 := th.CreateUser()
- user5 := th.CreateUser()
- th.LinkUserToTeam(user2, th.BasicTeam)
- th.AddUserToChannel(user2, th.BasicChannel)
- th.LinkUserToTeam(user3, th.BasicTeam)
- th.AddUserToChannel(user3, th.BasicChannel)
- enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable
- defer func() {
- th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts })
- th.App.Srv().RemoveLicense()
- }()
- th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true })
- th.App.Srv().SetLicense(model.NewTestLicense())
- id := model.NewId()
- guest := &model.User{
- Email: "success+" + id + "@simulator.amazonses.com",
- Username: "un_" + id,
- Nickname: "nn_" + id,
- Password: "Password1",
- EmailVerified: true,
- }
- guest, err := th.App.CreateGuest(guest)
- require.Nil(t, err)
- _, resp := Client.Login(guest.Username, "Password1")
- CheckNoError(t, resp)
- t.Run("Try to created GM with not visible users", func(t *testing.T) {
- _, resp := Client.CreateGroupChannel([]string{guest.Id, user1.Id, user2.Id, user3.Id})
- CheckForbiddenStatus(t, resp)
- _, resp = Client.CreateGroupChannel([]string{user1.Id, user2.Id, guest.Id, user3.Id})
- CheckForbiddenStatus(t, resp)
- })
- t.Run("Try to created GM with visible and not visible users", func(t *testing.T) {
- th.LinkUserToTeam(guest, th.BasicTeam)
- th.AddUserToChannel(guest, th.BasicChannel)
- _, resp := Client.CreateGroupChannel([]string{guest.Id, user1.Id, user3.Id, user4.Id, user5.Id})
- CheckForbiddenStatus(t, resp)
- _, resp = Client.CreateGroupChannel([]string{user1.Id, user2.Id, guest.Id, user4.Id, user5.Id})
- CheckForbiddenStatus(t, resp)
- })
- t.Run("Creating GM with visible users", func(t *testing.T) {
- _, resp := Client.CreateGroupChannel([]string{guest.Id, user1.Id, user2.Id, user3.Id})
- CheckNoError(t, resp)
- })
- }
- func TestDeleteGroupChannel(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- user := th.BasicUser
- user2 := th.BasicUser2
- user3 := th.CreateUser()
- userIds := []string{user.Id, user2.Id, user3.Id}
- th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
- rgc, resp := th.Client.CreateGroupChannel(userIds)
- CheckNoError(t, resp)
- CheckCreatedStatus(t, resp)
- require.NotNil(t, rgc, "should have created a group channel")
- deleted, resp := client.DeleteChannel(rgc.Id)
- CheckErrorMessage(t, resp, "api.channel.delete_channel.type.invalid")
- require.False(t, deleted, "should not have been able to delete group channel.")
- })
- }
- func TestGetChannel(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- channel, resp := Client.GetChannel(th.BasicChannel.Id, "")
- CheckNoError(t, resp)
- require.Equal(t, th.BasicChannel.Id, channel.Id, "ids did not match")
- Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
- _, resp = Client.GetChannel(th.BasicChannel.Id, "")
- CheckNoError(t, resp)
- channel, resp = Client.GetChannel(th.BasicPrivateChannel.Id, "")
- CheckNoError(t, resp)
- require.Equal(t, th.BasicPrivateChannel.Id, channel.Id, "ids did not match")
- Client.RemoveUserFromChannel(th.BasicPrivateChannel.Id, th.BasicUser.Id)
- _, resp = Client.GetChannel(th.BasicPrivateChannel.Id, "")
- CheckForbiddenStatus(t, resp)
- _, resp = Client.GetChannel(model.NewId(), "")
- CheckNotFoundStatus(t, resp)
- Client.Logout()
- _, resp = Client.GetChannel(th.BasicChannel.Id, "")
- CheckUnauthorizedStatus(t, resp)
- user := th.CreateUser()
- Client.Login(user.Email, user.Password)
- _, resp = Client.GetChannel(th.BasicChannel.Id, "")
- CheckForbiddenStatus(t, resp)
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
- _, resp = client.GetChannel(th.BasicChannel.Id, "")
- CheckNoError(t, resp)
- _, resp = client.GetChannel(th.BasicPrivateChannel.Id, "")
- CheckNoError(t, resp)
- _, resp = client.GetChannel(th.BasicUser.Id, "")
- CheckNotFoundStatus(t, resp)
- })
- }
- func TestGetDeletedChannelsForTeam(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- team := th.BasicTeam
- th.LoginTeamAdmin()
- channels, resp := Client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
- CheckNoError(t, resp)
- numInitialChannelsForTeam := len(channels)
- // create and delete public channel
- publicChannel1 := th.CreatePublicChannel()
- Client.DeleteChannel(publicChannel1.Id)
- th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
- channels, resp = client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
- CheckNoError(t, resp)
- require.Len(t, channels, numInitialChannelsForTeam+1, "should be 1 deleted channel")
- })
- publicChannel2 := th.CreatePublicChannel()
- Client.DeleteChannel(publicChannel2.Id)
- th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
- channels, resp = client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
- CheckNoError(t, resp)
- require.Len(t, channels, numInitialChannelsForTeam+2, "should be 2 deleted channels")
- })
- th.LoginBasic()
- privateChannel1 := th.CreatePrivateChannel()
- Client.DeleteChannel(privateChannel1.Id)
- channels, resp = Client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
- CheckNoError(t, resp)
- require.Len(t, channels, numInitialChannelsForTeam+3)
- // Login as different user and create private channel
- th.LoginBasic2()
- privateChannel2 := th.CreatePrivateChannel()
- Client.DeleteChannel(privateChannel2.Id)
- // Log back in as first user
- th.LoginBasic()
- channels, resp = Client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
- CheckNoError(t, resp)
- require.Len(t, channels, numInitialChannelsForTeam+3)
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
- channels, resp = client.GetDeletedChannelsForTeam(team.Id, 0, 100, "")
- CheckNoError(t, resp)
- require.Len(t, channels, numInitialChannelsForTeam+2)
- })
- channels, resp = Client.GetDeletedChannelsForTeam(team.Id, 0, 1, "")
- CheckNoError(t, resp)
- require.Len(t, channels, 1, "should be one channel per page")
- channels, resp = Client.GetDeletedChannelsForTeam(team.Id, 1, 1, "")
- CheckNoError(t, resp)
- require.Len(t, channels, 1, "should be one channel per page")
- }
- func TestGetPrivateChannelsForTeam(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- team := th.BasicTeam
- // normal user
- _, resp := th.Client.GetPrivateChannelsForTeam(team.Id, 0, 100, "")
- CheckForbiddenStatus(t, resp)
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
- channels, resp := c.GetPrivateChannelsForTeam(team.Id, 0, 100, "")
- CheckNoError(t, resp)
- // th.BasicPrivateChannel and th.BasicPrivateChannel2
- require.Len(t, channels, 2, "wrong number of private channels")
- for _, c := range channels {
- // check all channels included are private
- require.Equal(t, model.CHANNEL_PRIVATE, c.Type, "should include private channels only")
- }
- channels, resp = c.GetPrivateChannelsForTeam(team.Id, 0, 1, "")
- CheckNoError(t, resp)
- require.Len(t, channels, 1, "should be one channel per page")
- channels, resp = c.GetPrivateChannelsForTeam(team.Id, 1, 1, "")
- CheckNoError(t, resp)
- require.Len(t, channels, 1, "should be one channel per page")
- channels, resp = c.GetPrivateChannelsForTeam(team.Id, 10000, 100, "")
- CheckNoError(t, resp)
- require.Empty(t, channels, "should be no channel")
- _, resp = c.GetPrivateChannelsForTeam("junk", 0, 100, "")
- CheckBadRequestStatus(t, resp)
- })
- }
- func TestGetPublicChannelsForTeam(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- team := th.BasicTeam
- publicChannel1 := th.BasicChannel
- publicChannel2 := th.BasicChannel2
- channels, resp := Client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
- CheckNoError(t, resp)
- require.Len(t, channels, 4, "wrong path")
- for i, c := range channels {
- // check all channels included are open
- require.Equal(t, model.CHANNEL_OPEN, c.Type, "should include open channel only")
- // only check the created 2 public channels
- require.False(t, i < 2 && !(c.DisplayName == publicChannel1.DisplayName || c.DisplayName == publicChannel2.DisplayName), "should match public channel display name")
- }
- privateChannel := th.CreatePrivateChannel()
- channels, resp = Client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
- CheckNoError(t, resp)
- require.Len(t, channels, 4, "incorrect length of team public channels")
- for _, c := range channels {
- require.Equal(t, model.CHANNEL_OPEN, c.Type, "should not include private channel")
- require.NotEqual(t, privateChannel.DisplayName, c.DisplayName, "should not match private channel display name")
- }
- channels, resp = Client.GetPublicChannelsForTeam(team.Id, 0, 1, "")
- CheckNoError(t, resp)
- require.Len(t, channels, 1, "should be one channel per page")
- channels, resp = Client.GetPublicChannelsForTeam(team.Id, 1, 1, "")
- CheckNoError(t, resp)
- require.Len(t, channels, 1, "should be one channel per page")
- channels, resp = Client.GetPublicChannelsForTeam(team.Id, 10000, 100, "")
- CheckNoError(t, resp)
- require.Empty(t, channels, "should be no channel")
- _, resp = Client.GetPublicChannelsForTeam("junk", 0, 100, "")
- CheckBadRequestStatus(t, resp)
- _, resp = Client.GetPublicChannelsForTeam(model.NewId(), 0, 100, "")
- CheckForbiddenStatus(t, resp)
- Client.Logout()
- _, resp = Client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
- CheckUnauthorizedStatus(t, resp)
- user := th.CreateUser()
- Client.Login(user.Email, user.Password)
- _, resp = Client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
- CheckForbiddenStatus(t, resp)
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
- _, resp = client.GetPublicChannelsForTeam(team.Id, 0, 100, "")
- CheckNoError(t, resp)
- })
- }
- func TestGetPublicChannelsByIdsForTeam(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- teamId := th.BasicTeam.Id
- input := []string{th.BasicChannel.Id}
- output := []string{th.BasicChannel.DisplayName}
- channels, resp := Client.GetPublicChannelsByIdsForTeam(teamId, input)
- CheckNoError(t, resp)
- require.Len(t, channels, 1, "should return 1 channel")
- require.Equal(t, output[0], channels[0].DisplayName, "missing channel")
- input = append(input, GenerateTestId())
- input = append(input, th.BasicChannel2.Id)
- input = append(input, th.BasicPrivateChannel.Id)
- output = append(output, th.BasicChannel2.DisplayName)
- sort.Strings(output)
- channels, resp = Client.GetPublicChannelsByIdsForTeam(teamId, input)
- CheckNoError(t, resp)
- require.Len(t, channels, 2, "should return 2 channels")
- for i, c := range channels {
- require.Equal(t, output[i], c.DisplayName, "missing channel")
- }
- _, resp = Client.GetPublicChannelsByIdsForTeam(GenerateTestId(), input)
- CheckForbiddenStatus(t, resp)
- _, resp = Client.GetPublicChannelsByIdsForTeam(teamId, []string{})
- CheckBadRequestStatus(t, resp)
- _, resp = Client.GetPublicChannelsByIdsForTeam(teamId, []string{"junk"})
- CheckBadRequestStatus(t, resp)
- _, resp = Client.GetPublicChannelsByIdsForTeam(teamId, []string{GenerateTestId()})
- CheckNotFoundStatus(t, resp)
- _, resp = Client.GetPublicChannelsByIdsForTeam(teamId, []string{th.BasicPrivateChannel.Id})
- CheckNotFoundStatus(t, resp)
- Client.Logout()
- _, resp = Client.GetPublicChannelsByIdsForTeam(teamId, input)
- CheckUnauthorizedStatus(t, resp)
- _, resp = th.SystemAdminClient.GetPublicChannelsByIdsForTeam(teamId, input)
- CheckNoError(t, resp)
- }
- func TestGetChannelsForTeamForUser(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- t.Run("get channels for the team for user", func(t *testing.T) {
- channels, resp := Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "")
- CheckNoError(t, resp)
- found := make([]bool, 3)
- for _, c := range channels {
- if c.Id == th.BasicChannel.Id {
- found[0] = true
- } else if c.Id == th.BasicChannel2.Id {
- found[1] = true
- } else if c.Id == th.BasicPrivateChannel.Id {
- found[2] = true
- }
- require.True(t, c.TeamId == "" || c.TeamId == th.BasicTeam.Id)
- }
- for _, f := range found {
- require.True(t, f, "missing a channel")
- }
- channels, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, resp.Etag)
- CheckEtag(t, channels, resp)
- _, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, "junk", false, "")
- CheckBadRequestStatus(t, resp)
- _, resp = Client.GetChannelsForTeamForUser("junk", th.BasicUser.Id, false, "")
- CheckBadRequestStatus(t, resp)
- _, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser2.Id, false, "")
- CheckForbiddenStatus(t, resp)
- _, resp = Client.GetChannelsForTeamForUser(model.NewId(), th.BasicUser.Id, false, "")
- CheckForbiddenStatus(t, resp)
- _, resp = th.SystemAdminClient.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "")
- CheckNoError(t, resp)
- })
- t.Run("deleted channel could be retrieved using the proper flag", func(t *testing.T) {
- testChannel := &model.Channel{
- DisplayName: "dn_" + model.NewId(),
- Name: GenerateTestChannelName(),
- Type: model.CHANNEL_OPEN,
- TeamId: th.BasicTeam.Id,
- CreatorId: th.BasicUser.Id,
- }
- th.App.CreateChannel(testChannel, true)
- defer th.App.PermanentDeleteChannel(testChannel)
- channels, resp := Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "")
- CheckNoError(t, resp)
- assert.Equal(t, 6, len(channels))
- th.App.DeleteChannel(testChannel, th.BasicUser.Id)
- channels, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "")
- CheckNoError(t, resp)
- assert.Equal(t, 5, len(channels))
- // Should return all channels including basicDeleted.
- channels, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, true, "")
- CheckNoError(t, resp)
- assert.Equal(t, 7, len(channels))
- // Should stil return all channels including basicDeleted.
- now := time.Now().Add(-time.Minute).Unix() * 1000
- Client.GetChannelsForTeamAndUserWithLastDeleteAt(th.BasicTeam.Id, th.BasicUser.Id,
- true, int(now), "")
- CheckNoError(t, resp)
- assert.Equal(t, 7, len(channels))
- })
- }
- func TestGetAllChannels(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- var originalConfigVal bool
- th.App.UpdateConfig(func(cfg *model.Config) {
- originalConfigVal = *cfg.TeamSettings.ExperimentalViewArchivedChannels
- *cfg.TeamSettings.ExperimentalViewArchivedChannels = true
- })
- defer th.App.UpdateConfig(func(cfg *model.Config) {
- *cfg.TeamSettings.ExperimentalViewArchivedChannels = originalConfigVal
- })
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
- channels, resp := client.GetAllChannels(0, 20, "")
- CheckNoError(t, resp)
- // At least, all the not-deleted channels created during the InitBasic
- require.True(t, len(*channels) >= 3)
- for _, c := range *channels {
- require.NotEqual(t, c.TeamId, "")
- }
- channels, resp = client.GetAllChannels(0, 10, "")
- CheckNoError(t, resp)
- require.True(t, len(*channels) >= 3)
- channels, resp = client.GetAllChannels(1, 1, "")
- CheckNoError(t, resp)
- require.Len(t, *channels, 1)
- channels, resp = client.GetAllChannels(10000, 10000, "")
- CheckNoError(t, resp)
- require.Empty(t, *channels)
- channels, resp = client.GetAllChannels(0, 10000, "")
- require.Nil(t, resp.Error)
- beforeCount := len(*channels)
- firstChannel := (*channels)[0].Channel
- ok, resp := client.DeleteChannel(firstChannel.Id)
- require.Nil(t, resp.Error)
- require.True(t, ok)
- channels, resp = client.GetAllChannels(0, 10000, "")
- var ids []string
- for _, item := range *channels {
- ids = append(ids, item.Channel.Id)
- }
- require.Nil(t, resp.Error)
- require.Len(t, *channels, beforeCount-1)
- require.NotContains(t, ids, firstChannel.Id)
- channels, resp = client.GetAllChannelsIncludeDeleted(0, 10000, "")
- ids = []string{}
- for _, item := range *channels {
- ids = append(ids, item.Channel.Id)
- }
- require.Nil(t, resp.Error)
- require.True(t, len(*channels) > beforeCount)
- require.Contains(t, ids, firstChannel.Id)
- })
- _, resp := Client.GetAllChannels(0, 20, "")
- CheckForbiddenStatus(t, resp)
- }
- func TestGetAllChannelsWithCount(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- channels, total, resp := th.SystemAdminClient.GetAllChannelsWithCount(0, 20, "")
- CheckNoError(t, resp)
- // At least, all the not-deleted channels created during the InitBasic
- require.True(t, len(*channels) >= 3)
- for _, c := range *channels {
- require.NotEqual(t, c.TeamId, "")
- }
- require.Equal(t, int64(6), total)
- channels, _, resp = th.SystemAdminClient.GetAllChannelsWithCount(0, 10, "")
- CheckNoError(t, resp)
- require.True(t, len(*channels) >= 3)
- channels, _, resp = th.SystemAdminClient.GetAllChannelsWithCount(1, 1, "")
- CheckNoError(t, resp)
- require.Len(t, *channels, 1)
- channels, _, resp = th.SystemAdminClient.GetAllChannelsWithCount(10000, 10000, "")
- CheckNoError(t, resp)
- require.Empty(t, *channels)
- _, _, resp = Client.GetAllChannelsWithCount(0, 20, "")
- CheckForbiddenStatus(t, resp)
- }
- func TestSearchChannels(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- search := &model.ChannelSearch{Term: th.BasicChannel.Name}
- channels, resp := Client.SearchChannels(th.BasicTeam.Id, search)
- CheckNoError(t, resp)
- found := false
- for _, c := range channels {
- require.Equal(t, model.CHANNEL_OPEN, c.Type, "should only return public channels")
- if c.Id == th.BasicChannel.Id {
- found = true
- }
- }
- require.True(t, found, "didn't find channel")
- search.Term = th.BasicPrivateChannel.Name
- channels, resp = Client.SearchChannels(th.BasicTeam.Id, search)
- CheckNoError(t, resp)
- found = false
- for _, c := range channels {
- if c.Id == th.BasicPrivateChannel.Id {
- found = true
- }
- }
- require.False(t, found, "shouldn't find private channel")
- search.Term = ""
- _, resp = Client.SearchChannels(th.BasicTeam.Id, search)
- CheckNoError(t, resp)
- search.Term = th.BasicChannel.Name
- _, resp = Client.SearchChannels(model.NewId(), search)
- CheckNotFoundStatus(t, resp)
- _, resp = Client.SearchChannels("junk", search)
- CheckBadRequestStatus(t, resp)
- _, resp = th.SystemAdminClient.SearchChannels(th.BasicTeam.Id, search)
- CheckNoError(t, resp)
- // Check the appropriate permissions are enforced.
- defaultRolePermissions := th.SaveDefaultRolePermissions()
- defer func() {
- th.RestoreDefaultRolePermissions(defaultRolePermissions)
- }()
- // Remove list channels permission from the user
- th.RemovePermissionFromRole(model.PERMISSION_LIST_TEAM_CHANNELS.Id, model.TEAM_USER_ROLE_ID)
- t.Run("Search for a BasicChannel, which the user is a member of", func(t *testing.T) {
- search.Term = th.BasicChannel.Name
- channelList, resp := Client.SearchChannels(th.BasicTeam.Id, search)
- CheckNoError(t, resp)
- channelNames := []string{}
- for _, c := range channelList {
- channelNames = append(channelNames, c.Name)
- }
- require.Contains(t, channelNames, th.BasicChannel.Name)
- })
- t.Run("Remove the user from BasicChannel and search again, should not be returned", func(t *testing.T) {
- th.App.RemoveUserFromChannel(th.BasicUser.Id, th.BasicUser.Id, th.BasicChannel)
- search.Term = th.BasicChannel.Name
- channelList, resp := Client.SearchChannels(th.BasicTeam.Id, search)
- CheckNoError(t, resp)
- channelNames := []string{}
- for _, c := range channelList {
- channelNames = append(channelNames, c.Name)
- }
- require.NotContains(t, channelNames, th.BasicChannel.Name)
- })
- }
- func TestSearchArchivedChannels(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- search := &model.ChannelSearch{Term: th.BasicChannel.Name}
- Client.DeleteChannel(th.BasicChannel.Id)
- channels, resp := Client.SearchArchivedChannels(th.BasicTeam.Id, search)
- CheckNoError(t, resp)
- found := false
- for _, c := range channels {
- require.Equal(t, model.CHANNEL_OPEN, c.Type)
- if c.Id == th.BasicChannel.Id {
- found = true
- }
- }
- require.True(t, found)
- search.Term = th.BasicPrivateChannel.Name
- Client.DeleteChannel(th.BasicPrivateChannel.Id)
- channels, resp = Client.SearchArchivedChannels(th.BasicTeam.Id, search)
- CheckNoError(t, resp)
- found = false
- for _, c := range channels {
- if c.Id == th.BasicPrivateChannel.Id {
- found = true
- }
- }
- require.True(t, found)
- search.Term = ""
- _, resp = Client.SearchArchivedChannels(th.BasicTeam.Id, search)
- CheckNoError(t, resp)
- search.Term = th.BasicDeletedChannel.Name
- _, resp = Client.SearchArchivedChannels(model.NewId(), search)
- CheckNotFoundStatus(t, resp)
- _, resp = Client.SearchArchivedChannels("junk", search)
- CheckBadRequestStatus(t, resp)
- _, resp = th.SystemAdminClient.SearchArchivedChannels(th.BasicTeam.Id, search)
- CheckNoError(t, resp)
- // Check the appropriate permissions are enforced.
- defaultRolePermissions := th.SaveDefaultRolePermissions()
- defer func() {
- th.RestoreDefaultRolePermissions(defaultRolePermissions)
- }()
- // Remove list channels permission from the user
- th.RemovePermissionFromRole(model.PERMISSION_LIST_TEAM_CHANNELS.Id, model.TEAM_USER_ROLE_ID)
- t.Run("Search for a BasicDeletedChannel, which the user is a member of", func(t *testing.T) {
- search.Term = th.BasicDeletedChannel.Name
- channelList, resp := Client.SearchArchivedChannels(th.BasicTeam.Id, search)
- CheckNoError(t, resp)
- channelNames := []string{}
- for _, c := range channelList {
- channelNames = append(channelNames, c.Name)
- }
- require.Contains(t, channelNames, th.BasicDeletedChannel.Name)
- })
- t.Run("Remove the user from BasicDeletedChannel and search again, should still return", func(t *testing.T) {
- th.App.RemoveUserFromChannel(th.BasicUser.Id, th.BasicUser.Id, th.BasicDeletedChannel)
- search.Term = th.BasicDeletedChannel.Name
- channelList, resp := Client.SearchArchivedChannels(th.BasicTeam.Id, search)
- CheckNoError(t, resp)
- channelNames := []string{}
- for _, c := range channelList {
- channelNames = append(channelNames, c.Name)
- }
- require.Contains(t, channelNames, th.BasicDeletedChannel.Name)
- })
- }
- func TestSearchAllChannels(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- openChannel, chanErr := th.SystemAdminClient.CreateChannel(&model.Channel{
- DisplayName: "SearchAllChannels-FOOBARDISPLAYNAME",
- Name: "whatever",
- Type: model.CHANNEL_OPEN,
- TeamId: th.BasicTeam.Id,
- })
- CheckNoError(t, chanErr)
- privateChannel, privErr := th.SystemAdminClient.CreateChannel(&model.Channel{
- DisplayName: "SearchAllChannels-private1",
- Name: "private1",
- Type: model.CHANNEL_PRIVATE,
- TeamId: th.BasicTeam.Id,
- })
- CheckNoError(t, privErr)
- team := th.CreateTeam()
- groupConstrainedChannel, groupErr := th.SystemAdminClient.CreateChannel(&model.Channel{
- DisplayName: "SearchAllChannels-groupConstrained-1",
- Name: "groupconstrained1",
- Type: model.CHANNEL_PRIVATE,
- GroupConstrained: model.NewBool(true),
- TeamId: team.Id,
- })
- CheckNoError(t, groupErr)
- th.App.UpdateConfig(func(cfg *model.Config) {
- *cfg.TeamSettings.ExperimentalViewArchivedChannels = true
- })
- testCases := []struct {
- Description string
- Search *model.ChannelSearch
- ExpectedChannelIds []string
- }{
- {
- "Middle of word search",
- &model.ChannelSearch{Term: "bardisplay"},
- []string{openChannel.Id},
- },
- {
- "Prefix search",
- &model.ChannelSearch{Term: "SearchAllChannels-foobar"},
- []string{openChannel.Id},
- },
- {
- "Suffix search",
- &model.ChannelSearch{Term: "displayname"},
- []string{openChannel.Id},
- },
- {
- "Name search",
- &model.ChannelSearch{Term: "what"},
- []string{openChannel.Id},
- },
- {
- "Name suffix search",
- &model.ChannelSearch{Term: "ever"},
- []string{openChannel.Id},
- },
- {
- "Basic channel name middle of word search",
- &model.ChannelSearch{Term: th.BasicChannel.Name[2:14]},
- []string{th.BasicChannel.Id},
- },
- {
- "Upper case search",
- &model.ChannelSearch{Term: strings.ToUpper(th.BasicChannel.Name)},
- []string{th.BasicChannel.Id},
- },
- {
- "Mixed case search",
- &model.ChannelSearch{Term: th.BasicChannel.Name[0:2] + strings.ToUpper(th.BasicChannel.Name[2:5]) + th.BasicChannel.Name[5:]},
- []string{th.BasicChannel.Id},
- },
- {
- "Non mixed case search",
- &model.ChannelSearch{Term: th.BasicChannel.Name},
- []string{th.BasicChannel.Id},
- },
- {
- "Search private channel name",
- &model.ChannelSearch{Term: th.BasicPrivateChannel.Name},
- []string{th.BasicPrivateChannel.Id},
- },
- {
- "Search with private channel filter",
- &model.ChannelSearch{Private: true},
- []string{th.BasicPrivateChannel.Id, th.BasicPrivateChannel2.Id, privateChannel.Id, groupConstrainedChannel.Id},
- },
- {
- "Search with public channel filter",
- &model.ChannelSearch{Term: "SearchAllChannels", Public: true},
- []string{openChannel.Id},
- },
- {
- "Search with private channel filter",
- &model.ChannelSearch{Term: "SearchAllChannels", Private: true},
- []string{privateChannel.Id, groupConstrainedChannel.Id},
- },
- {
- "Search with teamIds channel filter",
- &model.ChannelSearch{Term: "SearchAllChannels", TeamIds: []string{th.BasicTeam.Id}},
- []string{openChannel.Id, privateChannel.Id},
- },
- {
- "Search with deleted without IncludeDeleted filter",
- &model.ChannelSearch{Term: th.BasicDeletedChannel.Name},
- []string{},
- },
- {
- "Search with deleted IncludeDeleted filter",
- &model.ChannelSearch{Term: th.BasicDeletedChannel.Name, IncludeDeleted: true},
- []string{th.BasicDeletedChannel.Id},
- },
- {
- "Search with deleted IncludeDeleted filter",
- &model.ChannelSearch{Term: th.BasicDeletedChannel.Name, IncludeDeleted: true},
- []string{th.BasicDeletedChannel.Id},
- },
- {
- "Search with deleted Deleted filter and empty term",
- &model.ChannelSearch{Term: "", Deleted: true},
- []string{th.BasicDeletedChannel.Id},
- },
- {
- "Search for group constrained",
- &model.ChannelSearch{Term: "SearchAllChannels", GroupConstrained: true},
- []string{groupConstrainedChannel.Id},
- },
- {
- "Search for group constrained and public",
- &model.ChannelSearch{Term: "SearchAllChannels", GroupConstrained: true, Public: true},
- []string{},
- },
- {
- "Search for exclude group constrained",
- &model.ChannelSearch{Term: "SearchAllChannels", ExcludeGroupConstrained: true},
- []string{openChannel.Id, privateChannel.Id},
- },
- }
- for _, testCase := range testCases {
- t.Run(testCase.Description, func(t *testing.T) {
- channels, resp := th.SystemAdminClient.SearchAllChannels(testCase.Search)
- CheckNoError(t, resp)
- assert.Equal(t, len(testCase.ExpectedChannelIds), len(*channels))
- actualChannelIds := []string{}
- for _, channelWithTeamData := range *channels {
- actualChannelIds = append(actualChannelIds, channelWithTeamData.Channel.Id)
- }
- assert.ElementsMatch(t, testCase.ExpectedChannelIds, actualChannelIds)
- })
- }
- // Searching with no terms returns all default channels
- allChannels, resp := th.SystemAdminClient.SearchAllChannels(&model.ChannelSearch{Term: ""})
- CheckNoError(t, resp)
- assert.True(t, len(*allChannels) >= 3)
- _, resp = Client.SearchAllChannels(&model.ChannelSearch{Term: ""})
- CheckForbiddenStatus(t, resp)
- }
- func TestSearchAllChannelsPaged(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- search := &model.ChannelSearch{Term: th.BasicChannel.Name}
- search.Term = ""
- search.Page = model.NewInt(0)
- search.PerPage = model.NewInt(2)
- channelsWithCount, resp := th.SystemAdminClient.SearchAllChannelsPaged(search)
- CheckNoError(t, resp)
- require.Len(t, *channelsWithCount.Channels, 2)
- search.Term = th.BasicChannel.Name
- _, resp = Client.SearchAllChannels(search)
- CheckForbiddenStatus(t, resp)
- }
- func TestSearchGroupChannels(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- u1 := th.CreateUserWithClient(th.SystemAdminClient)
- // Create a group channel in which base user belongs but not sysadmin
- gc1, resp := th.Client.CreateGroupChannel([]string{th.BasicUser.Id, th.BasicUser2.Id, u1.Id})
- CheckNoError(t, resp)
- defer th.Client.DeleteChannel(gc1.Id)
- gc2, resp := th.Client.CreateGroupChannel([]string{th.BasicUser.Id, th.BasicUser2.Id, th.SystemAdminUser.Id})
- CheckNoError(t, resp)
- defer th.Client.DeleteChannel(gc2.Id)
- search := &model.ChannelSearch{Term: th.BasicUser2.Username}
- // sysadmin should only find gc2 as he doesn't belong to gc1
- channels, resp := th.SystemAdminClient.SearchGroupChannels(search)
- CheckNoError(t, resp)
- assert.Len(t, channels, 1)
- assert.Equal(t, channels[0].Id, gc2.Id)
- // basic user should find both
- Client.Login(th.BasicUser.Username, th.BasicUser.Password)
- channels, resp = Client.SearchGroupChannels(search)
- CheckNoError(t, resp)
- assert.Len(t, channels, 2)
- channelIds := []string{}
- for _, c := range channels {
- channelIds = append(channelIds, c.Id)
- }
- assert.ElementsMatch(t, channelIds, []string{gc1.Id, gc2.Id})
- // searching for sysadmin, it should only find gc1
- search = &model.ChannelSearch{Term: th.SystemAdminUser.Username}
- channels, resp = Client.SearchGroupChannels(search)
- CheckNoError(t, resp)
- assert.Len(t, channels, 1)
- assert.Equal(t, channels[0].Id, gc2.Id)
- // with an empty search, response should be empty
- search = &model.ChannelSearch{Term: ""}
- channels, resp = Client.SearchGroupChannels(search)
- CheckNoError(t, resp)
- assert.Empty(t, channels)
- // search unprivileged, forbidden
- th.Client.Logout()
- _, resp = Client.SearchAllChannels(search)
- CheckUnauthorizedStatus(t, resp)
- }
- func TestDeleteChannel(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- c := th.Client
- team := th.BasicTeam
- user := th.BasicUser
- user2 := th.BasicUser2
- // successful delete of public channel
- th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
- publicChannel1 := th.CreatePublicChannel()
- pass, resp := client.DeleteChannel(publicChannel1.Id)
- CheckNoError(t, resp)
- require.True(t, pass, "should have passed")
- ch, err := th.App.GetChannel(publicChannel1.Id)
- require.True(t, err != nil || ch.DeleteAt != 0, "should have failed to get deleted channel, or returned one with a populated DeleteAt.")
- post1 := &model.Post{ChannelId: publicChannel1.Id, Message: "a" + GenerateTestId() + "a"}
- _, resp = client.CreatePost(post1)
- require.NotNil(t, resp, "expected response to not be nil")
- // successful delete of private channel
- privateChannel2 := th.CreatePrivateChannel()
- _, resp = client.DeleteChannel(privateChannel2.Id)
- CheckNoError(t, resp)
- // successful delete of channel with multiple members
- publicChannel3 := th.CreatePublicChannel()
- th.App.AddUserToChannel(user, publicChannel3)
- th.App.AddUserToChannel(user2, publicChannel3)
- _, resp = client.DeleteChannel(publicChannel3.Id)
- CheckNoError(t, resp)
- // default channel cannot be deleted.
- defaultChannel, _ := th.App.GetChannelByName(model.DEFAULT_CHANNEL, team.Id, false)
- pass, resp = client.DeleteChannel(defaultChannel.Id)
- CheckBadRequestStatus(t, resp)
- require.False(t, pass, "should have failed")
- // check system admin can delete a channel without any appropriate team or channel membership.
- sdTeam := th.CreateTeamWithClient(c)
- sdPublicChannel := &model.Channel{
- DisplayName: "dn_" + model.NewId(),
- Name: GenerateTestChannelName(),
- Type: model.CHANNEL_OPEN,
- TeamId: sdTeam.Id,
- }
- sdPublicChannel, resp = c.CreateChannel(sdPublicChannel)
- CheckNoError(t, resp)
- _, resp = client.DeleteChannel(sdPublicChannel.Id)
- CheckNoError(t, resp)
- sdPrivateChannel := &model.Channel{
- DisplayName: "dn_" + model.NewId(),
- Name: GenerateTestChannelName(),
- Type: model.CHANNEL_PRIVATE,
- TeamId: sdTeam.Id,
- }
- sdPrivateChannel, resp = c.CreateChannel(sdPrivateChannel)
- CheckNoError(t, resp)
- _, resp = client.DeleteChannel(sdPrivateChannel.Id)
- CheckNoError(t, resp)
- })
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
- th.LoginBasic()
- publicChannel5 := th.CreatePublicChannel()
- c.Logout()
- c.Login(user.Id, user.Password)
- _, resp := c.DeleteChannel(publicChannel5.Id)
- CheckUnauthorizedStatus(t, resp)
- _, resp = c.DeleteChannel("junk")
- CheckUnauthorizedStatus(t, resp)
- c.Logout()
- _, resp = c.DeleteChannel(GenerateTestId())
- CheckUnauthorizedStatus(t, resp)
- _, resp = client.DeleteChannel(publicChannel5.Id)
- CheckNoError(t, resp)
- })
- }
- func TestDeleteChannel2(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- user := th.BasicUser
- // Check the appropriate permissions are enforced.
- defaultRolePermissions := th.SaveDefaultRolePermissions()
- defer func() {
- th.RestoreDefaultRolePermissions(defaultRolePermissions)
- }()
- th.AddPermissionToRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID)
- th.AddPermissionToRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID)
- // channels created by SystemAdmin
- publicChannel6 := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_OPEN)
- privateChannel7 := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE)
- th.App.AddUserToChannel(user, publicChannel6)
- th.App.AddUserToChannel(user, privateChannel7)
- th.App.AddUserToChannel(user, privateChannel7)
- // successful delete by user
- _, resp := Client.DeleteChannel(publicChannel6.Id)
- CheckNoError(t, resp)
- _, resp = Client.DeleteChannel(privateChannel7.Id)
- CheckNoError(t, resp)
- // Restrict permissions to Channel Admins
- th.RemovePermissionFromRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID)
- th.RemovePermissionFromRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID)
- th.AddPermissionToRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID)
- th.AddPermissionToRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID)
- // channels created by SystemAdmin
- publicChannel6 = th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_OPEN)
- privateChannel7 = th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE)
- th.App.AddUserToChannel(user, publicChannel6)
- th.App.AddUserToChannel(user, privateChannel7)
- th.App.AddUserToChannel(user, privateChannel7)
- // cannot delete by user
- _, resp = Client.DeleteChannel(publicChannel6.Id)
- CheckForbiddenStatus(t, resp)
- _, resp = Client.DeleteChannel(privateChannel7.Id)
- CheckForbiddenStatus(t, resp)
- // successful delete by channel admin
- th.MakeUserChannelAdmin(user, publicChannel6)
- th.MakeUserChannelAdmin(user, privateChannel7)
- th.App.Srv().Store.Channel().ClearCaches()
- _, resp = Client.DeleteChannel(publicChannel6.Id)
- CheckNoError(t, resp)
- _, resp = Client.DeleteChannel(privateChannel7.Id)
- CheckNoError(t, resp)
- // Make sure team admins don't have permission to delete channels.
- th.RemovePermissionFromRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID)
- th.RemovePermissionFromRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID)
- // last member of a public channel should have required permission to delete
- publicChannel6 = th.CreateChannelWithClient(th.Client, model.CHANNEL_OPEN)
- _, resp = Client.DeleteChannel(publicChannel6.Id)
- CheckForbiddenStatus(t, resp)
- // last member of a private channel should not be able to delete it if they don't have required permissions
- privateChannel7 = th.CreateChannelWithClient(th.Client, model.CHANNEL_PRIVATE)
- _, resp = Client.DeleteChannel(privateChannel7.Id)
- CheckForbiddenStatus(t, resp)
- }
- func TestConvertChannelToPrivate(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- defaultChannel, _ := th.App.GetChannelByName(model.DEFAULT_CHANNEL, th.BasicTeam.Id, false)
- _, resp := Client.ConvertChannelToPrivate(defaultChannel.Id)
- CheckForbiddenStatus(t, resp)
- privateChannel := th.CreatePrivateChannel()
- _, resp = Client.ConvertChannelToPrivate(privateChannel.Id)
- CheckForbiddenStatus(t, resp)
- publicChannel := th.CreatePublicChannel()
- _, resp = Client.ConvertChannelToPrivate(publicChannel.Id)
- CheckForbiddenStatus(t, resp)
- th.LoginTeamAdmin()
- rchannel, resp := Client.ConvertChannelToPrivate(publicChannel.Id)
- CheckOKStatus(t, resp)
- require.Equal(t, model.CHANNEL_PRIVATE, rchannel.Type, "channel should be converted from public to private")
- rchannel, resp = th.SystemAdminClient.ConvertChannelToPrivate(privateChannel.Id)
- CheckBadRequestStatus(t, resp)
- require.Nil(t, rchannel, "should not return a channel")
- rchannel, resp = th.SystemAdminClient.ConvertChannelToPrivate(defaultChannel.Id)
- CheckBadRequestStatus(t, resp)
- require.Nil(t, rchannel, "should not return a channel")
- WebSocketClient, err := th.CreateWebSocketClient()
- require.Nil(t, err)
- WebSocketClient.Listen()
- publicChannel2 := th.CreatePublicChannel()
- rchannel, resp = th.SystemAdminClient.ConvertChannelToPrivate(publicChannel2.Id)
- CheckOKStatus(t, resp)
- require.Equal(t, model.CHANNEL_PRIVATE, rchannel.Type, "channel should be converted from public to private")
- stop := make(chan bool)
- eventHit := false
- go func() {
- for {
- select {
- case resp := <-WebSocketClient.EventChannel:
- if resp.EventType() == model.WEBSOCKET_EVENT_CHANNEL_CONVERTED && resp.GetData()["channel_id"].(string) == publicChannel2.Id {
- eventHit = true
- }
- case <-stop:
- return
- }
- }
- }()
- time.Sleep(400 * time.Millisecond)
- stop <- true
- require.True(t, eventHit, "did not receive channel_converted event")
- }
- func TestUpdateChannelPrivacy(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- type testTable []struct {
- name string
- channel *model.Channel
- expectedPrivacy string
- }
- defaultChannel, _ := th.App.GetChannelByName(model.DEFAULT_CHANNEL, th.BasicTeam.Id, false)
- privateChannel := th.CreatePrivateChannel()
- publicChannel := th.CreatePublicChannel()
- tt := testTable{
- {"Updating default channel should fail with forbidden status if not logged in", defaultChannel, model.CHANNEL_OPEN},
- {"Updating private channel should fail with forbidden status if not logged in", privateChannel, model.CHANNEL_PRIVATE},
- {"Updating public channel should fail with forbidden status if not logged in", publicChannel, model.CHANNEL_OPEN},
- }
- for _, tc := range tt {
- t.Run(tc.name, func(t *testing.T) {
- _, resp := Client.UpdateChannelPrivacy(tc.channel.Id, tc.expectedPrivacy)
- CheckForbiddenStatus(t, resp)
- })
- }
- th.LoginTeamAdmin()
- tt = testTable{
- {"Converting default channel to private should fail", defaultChannel, model.CHANNEL_PRIVATE},
- {"Updating privacy to an invalid setting should fail", publicChannel, "invalid"},
- }
- for _, tc := range tt {
- t.Run(tc.name, func(t *testing.T) {
- _, resp := Client.UpdateChannelPrivacy(tc.channel.Id, tc.expectedPrivacy)
- CheckBadRequestStatus(t, resp)
- })
- }
- tt = testTable{
- {"Default channel should stay public", defaultChannel, model.CHANNEL_OPEN},
- {"Public channel should stay public", publicChannel, model.CHANNEL_OPEN},
- {"Private channel should stay private", privateChannel, model.CHANNEL_PRIVATE},
- {"Public channel should convert to private", publicChannel, model.CHANNEL_PRIVATE},
- {"Private channel should convert to public", privateChannel, model.CHANNEL_OPEN},
- }
- for _, tc := range tt {
- t.Run(tc.name, func(t *testing.T) {
- updatedChannel, resp := Client.UpdateChannelPrivacy(tc.channel.Id, tc.expectedPrivacy)
- CheckNoError(t, resp)
- assert.Equal(t, tc.expectedPrivacy, updatedChannel.Type)
- updatedChannel, err := th.App.GetChannel(tc.channel.Id)
- require.Nil(t, err)
- assert.Equal(t, tc.expectedPrivacy, updatedChannel.Type)
- })
- }
- }
- func TestRestoreChannel(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- publicChannel1 := th.CreatePublicChannel()
- Client.DeleteChannel(publicChannel1.Id)
- privateChannel1 := th.CreatePrivateChannel()
- Client.DeleteChannel(privateChannel1.Id)
- _, resp := Client.RestoreChannel(publicChannel1.Id)
- CheckForbiddenStatus(t, resp)
- _, resp = Client.RestoreChannel(privateChannel1.Id)
- CheckForbiddenStatus(t, resp)
- th.LoginTeamAdmin()
- _, resp = Client.RestoreChannel(publicChannel1.Id)
- CheckOKStatus(t, resp)
- _, resp = Client.RestoreChannel(privateChannel1.Id)
- CheckOKStatus(t, resp)
- }
- func TestGetChannelByName(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- channel, resp := Client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
- CheckNoError(t, resp)
- require.Equal(t, th.BasicChannel.Name, channel.Name, "names did not match")
- channel, resp = Client.GetChannelByName(th.BasicPrivateChannel.Name, th.BasicTeam.Id, "")
- CheckNoError(t, resp)
- require.Equal(t, th.BasicPrivateChannel.Name, channel.Name, "names did not match")
- _, resp = Client.GetChannelByName(strings.ToUpper(th.BasicPrivateChannel.Name), th.BasicTeam.Id, "")
- CheckNoError(t, resp)
- _, resp = Client.GetChannelByName(th.BasicDeletedChannel.Name, th.BasicTeam.Id, "")
- CheckNotFoundStatus(t, resp)
- channel, resp = Client.GetChannelByNameIncludeDeleted(th.BasicDeletedChannel.Name, th.BasicTeam.Id, "")
- CheckNoError(t, resp)
- require.Equal(t, th.BasicDeletedChannel.Name, channel.Name, "names did not match")
- Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
- _, resp = Client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
- CheckNoError(t, resp)
- Client.RemoveUserFromChannel(th.BasicPrivateChannel.Id, th.BasicUser.Id)
- _, resp = Client.GetChannelByName(th.BasicPrivateChannel.Name, th.BasicTeam.Id, "")
- CheckNotFoundStatus(t, resp)
- _, resp = Client.GetChannelByName(GenerateTestChannelName(), th.BasicTeam.Id, "")
- CheckNotFoundStatus(t, resp)
- _, resp = Client.GetChannelByName(GenerateTestChannelName(), "junk", "")
- CheckBadRequestStatus(t, resp)
- Client.Logout()
- _, resp = Client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
- CheckUnauthorizedStatus(t, resp)
- user := th.CreateUser()
- Client.Login(user.Email, user.Password)
- _, resp = Client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
- CheckForbiddenStatus(t, resp)
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
- _, resp = client.GetChannelByName(th.BasicChannel.Name, th.BasicTeam.Id, "")
- CheckNoError(t, resp)
- })
- }
- func TestGetChannelByNameForTeamName(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- channel, resp := th.SystemAdminClient.GetChannelByNameForTeamName(th.BasicChannel.Name, th.BasicTeam.Name, "")
- CheckNoError(t, resp)
- require.Equal(t, th.BasicChannel.Name, channel.Name, "names did not match")
- _, resp = Client.GetChannelByNameForTeamName(th.BasicChannel.Name, th.BasicTeam.Name, "")
- CheckNoError(t, resp)
- _, resp = Client.GetChannelByNameForTeamName(th.BasicDeletedChannel.Name, th.BasicTeam.Name, "")
- CheckNotFoundStatus(t, resp)
- channel, resp = Client.GetChannelByNameForTeamNameIncludeDeleted(th.BasicDeletedChannel.Name, th.BasicTeam.Name, "")
- CheckNoError(t, resp)
- require.Equal(t, th.BasicDeletedChannel.Name, channel.Name, "names did not match")
- _, resp = Client.GetChannelByNameForTeamName(th.BasicChannel.Name, model.NewRandomString(15), "")
- CheckNotFoundStatus(t, resp)
- _, resp = Client.GetChannelByNameForTeamName(GenerateTestChannelName(), th.BasicTeam.Name, "")
- CheckNotFoundStatus(t, resp)
- Client.Logout()
- _, resp = Client.GetChannelByNameForTeamName(th.BasicChannel.Name, th.BasicTeam.Name, "")
- CheckUnauthorizedStatus(t, resp)
- user := th.CreateUser()
- Client.Login(user.Email, user.Password)
- _, resp = Client.GetChannelByNameForTeamName(th.BasicChannel.Name, th.BasicTeam.Name, "")
- CheckNotFoundStatus(t, resp)
- }
- func TestGetChannelMembers(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
- members, resp := client.GetChannelMembers(th.BasicChannel.Id, 0, 60, "")
- CheckNoError(t, resp)
- require.Len(t, *members, 3, "should only be 3 users in channel")
- members, resp = client.GetChannelMembers(th.BasicChannel.Id, 0, 2, "")
- CheckNoError(t, resp)
- require.Len(t, *members, 2, "should only be 2 users")
- members, resp = client.GetChannelMembers(th.BasicChannel.Id, 1, 1, "")
- CheckNoError(t, resp)
- require.Len(t, *members, 1, "should only be 1 user")
- members, resp = client.GetChannelMembers(th.BasicChannel.Id, 1000, 100000, "")
- CheckNoError(t, resp)
- require.Empty(t, *members, "should be 0 users")
- _, resp = client.GetChannelMembers("junk", 0, 60, "")
- CheckBadRequestStatus(t, resp)
- _, resp = client.GetChannelMembers("", 0, 60, "")
- CheckBadRequestStatus(t, resp)
- _, resp = client.GetChannelMembers(th.BasicChannel.Id, 0, 60, "")
- CheckNoError(t, resp)
- })
- _, resp := th.Client.GetChannelMembers(model.NewId(), 0, 60, "")
- CheckForbiddenStatus(t, resp)
- th.Client.Logout()
- _, resp = th.Client.GetChannelMembers(th.BasicChannel.Id, 0, 60, "")
- CheckUnauthorizedStatus(t, resp)
- user := th.CreateUser()
- th.Client.Login(user.Email, user.Password)
- _, resp = th.Client.GetChannelMembers(th.BasicChannel.Id, 0, 60, "")
- CheckForbiddenStatus(t, resp)
- }
- func TestGetChannelMembersByIds(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- cm, resp := Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{th.BasicUser.Id})
- CheckNoError(t, resp)
- require.Equal(t, th.BasicUser.Id, (*cm)[0].UserId, "returned wrong user")
- _, resp = Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{})
- CheckBadRequestStatus(t, resp)
- cm1, resp := Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{"junk"})
- CheckNoError(t, resp)
- require.Empty(t, *cm1, "no users should be returned")
- cm1, resp = Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{"junk", th.BasicUser.Id})
- CheckNoError(t, resp)
- require.Len(t, *cm1, 1, "1 member should be returned")
- cm1, resp = Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{th.BasicUser2.Id, th.BasicUser.Id})
- CheckNoError(t, resp)
- require.Len(t, *cm1, 2, "2 members should be returned")
- _, resp = Client.GetChannelMembersByIds("junk", []string{th.BasicUser.Id})
- CheckBadRequestStatus(t, resp)
- _, resp = Client.GetChannelMembersByIds(model.NewId(), []string{th.BasicUser.Id})
- CheckForbiddenStatus(t, resp)
- Client.Logout()
- _, resp = Client.GetChannelMembersByIds(th.BasicChannel.Id, []string{th.BasicUser.Id})
- CheckUnauthorizedStatus(t, resp)
- _, resp = th.SystemAdminClient.GetChannelMembersByIds(th.BasicChannel.Id, []string{th.BasicUser2.Id, th.BasicUser.Id})
- CheckNoError(t, resp)
- }
- func TestGetChannelMember(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- c := th.Client
- th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
- member, resp := client.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
- CheckNoError(t, resp)
- require.Equal(t, th.BasicChannel.Id, member.ChannelId, "wrong channel id")
- require.Equal(t, th.BasicUser.Id, member.UserId, "wrong user id")
- _, resp = client.GetChannelMember("", th.BasicUser.Id, "")
- CheckNotFoundStatus(t, resp)
- _, resp = client.GetChannelMember("junk", th.BasicUser.Id, "")
- CheckBadRequestStatus(t, resp)
- _, resp = client.GetChannelMember(th.BasicChannel.Id, "", "")
- CheckNotFoundStatus(t, resp)
- _, resp = client.GetChannelMember(th.BasicChannel.Id, "junk", "")
- CheckBadRequestStatus(t, resp)
- _, resp = client.GetChannelMember(th.BasicChannel.Id, model.NewId(), "")
- CheckNotFoundStatus(t, resp)
- _, resp = client.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
- CheckNoError(t, resp)
- })
- _, resp := c.GetChannelMember(model.NewId(), th.BasicUser.Id, "")
- CheckForbiddenStatus(t, resp)
- c.Logout()
- _, resp = c.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
- CheckUnauthorizedStatus(t, resp)
- user := th.CreateUser()
- c.Login(user.Email, user.Password)
- _, resp = c.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
- CheckForbiddenStatus(t, resp)
- }
- func TestGetChannelMembersForUser(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- members, resp := Client.GetChannelMembersForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
- CheckNoError(t, resp)
- require.Len(t, *members, 6, "should have 6 members on team")
- _, resp = Client.GetChannelMembersForUser("", th.BasicTeam.Id, "")
- CheckNotFoundStatus(t, resp)
- _, resp = Client.GetChannelMembersForUser("junk", th.BasicTeam.Id, "")
- CheckBadRequestStatus(t, resp)
- _, resp = Client.GetChannelMembersForUser(model.NewId(), th.BasicTeam.Id, "")
- CheckForbiddenStatus(t, resp)
- _, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, "", "")
- CheckNotFoundStatus(t, resp)
- _, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, "junk", "")
- CheckBadRequestStatus(t, resp)
- _, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, model.NewId(), "")
- CheckForbiddenStatus(t, resp)
- Client.Logout()
- _, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
- CheckUnauthorizedStatus(t, resp)
- user := th.CreateUser()
- Client.Login(user.Email, user.Password)
- _, resp = Client.GetChannelMembersForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
- CheckForbiddenStatus(t, resp)
- _, resp = th.SystemAdminClient.GetChannelMembersForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
- CheckNoError(t, resp)
- }
- func TestViewChannel(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- view := &model.ChannelView{
- ChannelId: th.BasicChannel.Id,
- }
- viewResp, resp := Client.ViewChannel(th.BasicUser.Id, view)
- CheckNoError(t, resp)
- require.Equal(t, "OK", viewResp.Status, "should have passed")
- channel, _ := th.App.GetChannel(th.BasicChannel.Id)
- require.Equal(t, channel.LastPostAt, viewResp.LastViewedAtTimes[channel.Id], "LastPostAt does not match returned LastViewedAt time")
- view.PrevChannelId = th.BasicChannel.Id
- _, resp = Client.ViewChannel(th.BasicUser.Id, view)
- CheckNoError(t, resp)
- view.PrevChannelId = ""
- _, resp = Client.ViewChannel(th.BasicUser.Id, view)
- CheckNoError(t, resp)
- view.PrevChannelId = "junk"
- _, resp = Client.ViewChannel(th.BasicUser.Id, view)
- CheckBadRequestStatus(t, resp)
- // All blank is OK we use it for clicking off of the browser.
- view.PrevChannelId = ""
- view.ChannelId = ""
- _, resp = Client.ViewChannel(th.BasicUser.Id, view)
- CheckNoError(t, resp)
- view.PrevChannelId = ""
- view.ChannelId = "junk"
- _, resp = Client.ViewChannel(th.BasicUser.Id, view)
- CheckBadRequestStatus(t, resp)
- view.ChannelId = "correctlysizedjunkdddfdfdf"
- _, resp = Client.ViewChannel(th.BasicUser.Id, view)
- CheckBadRequestStatus(t, resp)
- view.ChannelId = th.BasicChannel.Id
- member, resp := Client.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
- CheckNoError(t, resp)
- channel, resp = Client.GetChannel(th.BasicChannel.Id, "")
- CheckNoError(t, resp)
- require.Equal(t, channel.TotalMsgCount, member.MsgCount, "should match message counts")
- require.Equal(t, int64(0), member.MentionCount, "should have no mentions")
- _, resp = Client.ViewChannel("junk", view)
- CheckBadRequestStatus(t, resp)
- _, resp = Client.ViewChannel(th.BasicUser2.Id, view)
- CheckForbiddenStatus(t, resp)
- r, err := Client.DoApiPost(fmt.Sprintf("/channels/members/%v/view", th.BasicUser.Id), "garbage")
- require.NotNil(t, err)
- require.Equal(t, http.StatusBadRequest, r.StatusCode)
- Client.Logout()
- _, resp = Client.ViewChannel(th.BasicUser.Id, view)
- CheckUnauthorizedStatus(t, resp)
- _, resp = th.SystemAdminClient.ViewChannel(th.BasicUser.Id, view)
- CheckNoError(t, resp)
- }
- func TestGetChannelUnread(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- user := th.BasicUser
- channel := th.BasicChannel
- channelUnread, resp := Client.GetChannelUnread(channel.Id, user.Id)
- CheckNoError(t, resp)
- require.Equal(t, th.BasicTeam.Id, channelUnread.TeamId, "wrong team id returned for a regular user call")
- require.Equal(t, channel.Id, channelUnread.ChannelId, "wrong team id returned for a regular user call")
- _, resp = Client.GetChannelUnread("junk", user.Id)
- CheckBadRequestStatus(t, resp)
- _, resp = Client.GetChannelUnread(channel.Id, "junk")
- CheckBadRequestStatus(t, resp)
- _, resp = Client.GetChannelUnread(channel.Id, model.NewId())
- CheckForbiddenStatus(t, resp)
- _, resp = Client.GetChannelUnread(model.NewId(), user.Id)
- CheckForbiddenStatus(t, resp)
- newUser := th.CreateUser()
- Client.Login(newUser.Email, newUser.Password)
- _, resp = Client.GetChannelUnread(th.BasicChannel.Id, user.Id)
- CheckForbiddenStatus(t, resp)
- Client.Logout()
- _, resp = th.SystemAdminClient.GetChannelUnread(channel.Id, user.Id)
- CheckNoError(t, resp)
- _, resp = th.SystemAdminClient.GetChannelUnread(model.NewId(), user.Id)
- CheckForbiddenStatus(t, resp)
- _, resp = th.SystemAdminClient.GetChannelUnread(channel.Id, model.NewId())
- CheckNotFoundStatus(t, resp)
- }
- func TestGetChannelStats(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- channel := th.CreatePrivateChannel()
- stats, resp := Client.GetChannelStats(channel.Id, "")
- CheckNoError(t, resp)
- require.Equal(t, channel.Id, stats.ChannelId, "couldnt't get extra info")
- require.Equal(t, int64(1), stats.MemberCount, "got incorrect member count")
- require.Equal(t, int64(0), stats.PinnedPostCount, "got incorrect pinned post count")
- th.CreatePinnedPostWithClient(th.Client, channel)
- stats, resp = Client.GetChannelStats(channel.Id, "")
- CheckNoError(t, resp)
- require.Equal(t, int64(1), stats.PinnedPostCount, "should have returned 1 pinned post count")
- _, resp = Client.GetChannelStats("junk", "")
- CheckBadRequestStatus(t, resp)
- _, resp = Client.GetChannelStats(model.NewId(), "")
- CheckForbiddenStatus(t, resp)
- Client.Logout()
- _, resp = Client.GetChannelStats(channel.Id, "")
- CheckUnauthorizedStatus(t, resp)
- th.LoginBasic2()
- _, resp = Client.GetChannelStats(channel.Id, "")
- CheckForbiddenStatus(t, resp)
- _, resp = th.SystemAdminClient.GetChannelStats(channel.Id, "")
- CheckNoError(t, resp)
- }
- func TestGetPinnedPosts(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- channel := th.BasicChannel
- posts, resp := Client.GetPinnedPosts(channel.Id, "")
- CheckNoError(t, resp)
- require.Empty(t, posts.Posts, "should not have gotten a pinned post")
- pinnedPost := th.CreatePinnedPost()
- posts, resp = Client.GetPinnedPosts(channel.Id, "")
- CheckNoError(t, resp)
- require.Len(t, posts.Posts, 1, "should have returned 1 pinned post")
- require.Contains(t, posts.Posts, pinnedPost.Id, "missing pinned post")
- posts, resp = Client.GetPinnedPosts(channel.Id, resp.Etag)
- CheckEtag(t, posts, resp)
- _, resp = Client.GetPinnedPosts(GenerateTestId(), "")
- CheckForbiddenStatus(t, resp)
- _, resp = Client.GetPinnedPosts("junk", "")
- CheckBadRequestStatus(t, resp)
- Client.Logout()
- _, resp = Client.GetPinnedPosts(channel.Id, "")
- CheckUnauthorizedStatus(t, resp)
- _, resp = th.SystemAdminClient.GetPinnedPosts(channel.Id, "")
- CheckNoError(t, resp)
- }
- func TestUpdateChannelRoles(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- const CHANNEL_ADMIN = "channel_user channel_admin"
- const CHANNEL_MEMBER = "channel_user"
- // User 1 creates a channel, making them channel admin by default.
- channel := th.CreatePublicChannel()
- // Adds User 2 to the channel, making them a channel member by default.
- th.App.AddUserToChannel(th.BasicUser2, channel)
- // User 1 promotes User 2
- pass, resp := Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_ADMIN)
- CheckNoError(t, resp)
- require.True(t, pass, "should have passed")
- member, resp := Client.GetChannelMember(channel.Id, th.BasicUser2.Id, "")
- CheckNoError(t, resp)
- require.Equal(t, CHANNEL_ADMIN, member.Roles, "roles don't match")
- // User 1 demotes User 2
- _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_MEMBER)
- CheckNoError(t, resp)
- th.LoginBasic2()
- // User 2 cannot demote User 1
- _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER)
- CheckForbiddenStatus(t, resp)
- // User 2 cannot promote self
- _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_ADMIN)
- CheckForbiddenStatus(t, resp)
- th.LoginBasic()
- // User 1 demotes self
- _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER)
- CheckNoError(t, resp)
- // System Admin promotes User 1
- _, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_ADMIN)
- CheckNoError(t, resp)
- // System Admin demotes User 1
- _, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER)
- CheckNoError(t, resp)
- // System Admin promotes User 1
- _, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_ADMIN)
- CheckNoError(t, resp)
- th.LoginBasic()
- _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, "junk")
- CheckBadRequestStatus(t, resp)
- _, resp = Client.UpdateChannelRoles(channel.Id, "junk", CHANNEL_MEMBER)
- CheckBadRequestStatus(t, resp)
- _, resp = Client.UpdateChannelRoles("junk", th.BasicUser.Id, CHANNEL_MEMBER)
- CheckBadRequestStatus(t, resp)
- _, resp = Client.UpdateChannelRoles(channel.Id, model.NewId(), CHANNEL_MEMBER)
- CheckNotFoundStatus(t, resp)
- _, resp = Client.UpdateChannelRoles(model.NewId(), th.BasicUser.Id, CHANNEL_MEMBER)
- CheckForbiddenStatus(t, resp)
- }
- func TestUpdateChannelMemberSchemeRoles(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- SystemAdminClient := th.SystemAdminClient
- WebSocketClient, err := th.CreateWebSocketClient()
- WebSocketClient.Listen()
- require.Nil(t, err)
- th.LoginBasic()
- s1 := &model.SchemeRoles{
- SchemeAdmin: false,
- SchemeUser: false,
- SchemeGuest: false,
- }
- _, r1 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s1)
- CheckNoError(t, r1)
- timeout := time.After(600 * time.Millisecond)
- waiting := true
- for waiting {
- select {
- case event := <-WebSocketClient.EventChannel:
- if event.Event == model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED {
- require.Equal(t, model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED, event.Event)
- waiting = false
- }
- case <-timeout:
- require.Fail(t, "Should have received event channel member websocket event and not timedout")
- waiting = false
- }
- }
- tm1, rtm1 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
- CheckNoError(t, rtm1)
- assert.Equal(t, false, tm1.SchemeGuest)
- assert.Equal(t, false, tm1.SchemeUser)
- assert.Equal(t, false, tm1.SchemeAdmin)
- s2 := &model.SchemeRoles{
- SchemeAdmin: false,
- SchemeUser: true,
- SchemeGuest: false,
- }
- _, r2 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s2)
- CheckNoError(t, r2)
- tm2, rtm2 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
- CheckNoError(t, rtm2)
- assert.Equal(t, false, tm2.SchemeGuest)
- assert.Equal(t, true, tm2.SchemeUser)
- assert.Equal(t, false, tm2.SchemeAdmin)
- s3 := &model.SchemeRoles{
- SchemeAdmin: true,
- SchemeUser: false,
- SchemeGuest: false,
- }
- _, r3 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s3)
- CheckNoError(t, r3)
- tm3, rtm3 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
- CheckNoError(t, rtm3)
- assert.Equal(t, false, tm3.SchemeGuest)
- assert.Equal(t, false, tm3.SchemeUser)
- assert.Equal(t, true, tm3.SchemeAdmin)
- s4 := &model.SchemeRoles{
- SchemeAdmin: true,
- SchemeUser: true,
- SchemeGuest: false,
- }
- _, r4 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s4)
- CheckNoError(t, r4)
- tm4, rtm4 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
- CheckNoError(t, rtm4)
- assert.Equal(t, false, tm4.SchemeGuest)
- assert.Equal(t, true, tm4.SchemeUser)
- assert.Equal(t, true, tm4.SchemeAdmin)
- s5 := &model.SchemeRoles{
- SchemeAdmin: false,
- SchemeUser: false,
- SchemeGuest: true,
- }
- _, r5 := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s5)
- CheckNoError(t, r5)
- tm5, rtm5 := SystemAdminClient.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id, "")
- CheckNoError(t, rtm5)
- assert.Equal(t, true, tm5.SchemeGuest)
- assert.Equal(t, false, tm5.SchemeUser)
- assert.Equal(t, false, tm5.SchemeAdmin)
- s6 := &model.SchemeRoles{
- SchemeAdmin: false,
- SchemeUser: true,
- SchemeGuest: true,
- }
- _, resp := SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s6)
- CheckBadRequestStatus(t, resp)
- _, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles(model.NewId(), th.BasicUser.Id, s4)
- CheckForbiddenStatus(t, resp)
- _, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, model.NewId(), s4)
- CheckNotFoundStatus(t, resp)
- _, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles("ASDF", th.BasicUser.Id, s4)
- CheckBadRequestStatus(t, resp)
- _, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, "ASDF", s4)
- CheckBadRequestStatus(t, resp)
- th.LoginBasic2()
- _, resp = th.Client.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.BasicUser.Id, s4)
- CheckForbiddenStatus(t, resp)
- SystemAdminClient.Logout()
- _, resp = SystemAdminClient.UpdateChannelMemberSchemeRoles(th.BasicChannel.Id, th.SystemAdminUser.Id, s4)
- CheckUnauthorizedStatus(t, resp)
- }
- func TestUpdateChannelNotifyProps(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- props := map[string]string{}
- props[model.DESKTOP_NOTIFY_PROP] = model.CHANNEL_NOTIFY_MENTION
- props[model.MARK_UNREAD_NOTIFY_PROP] = model.CHANNEL_MARK_UNREAD_MENTION
- pass, resp := Client.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, props)
- CheckNoError(t, resp)
- require.True(t, pass, "should have passed")
- member, err := th.App.GetChannelMember(th.BasicChannel.Id, th.BasicUser.Id)
- require.Nil(t, err)
- require.Equal(t, model.CHANNEL_NOTIFY_MENTION, member.NotifyProps[model.DESKTOP_NOTIFY_PROP], "bad update")
- require.Equal(t, model.CHANNEL_MARK_UNREAD_MENTION, member.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP], "bad update")
- _, resp = Client.UpdateChannelNotifyProps("junk", th.BasicUser.Id, props)
- CheckBadRequestStatus(t, resp)
- _, resp = Client.UpdateChannelNotifyProps(th.BasicChannel.Id, "junk", props)
- CheckBadRequestStatus(t, resp)
- _, resp = Client.UpdateChannelNotifyProps(model.NewId(), th.BasicUser.Id, props)
- CheckNotFoundStatus(t, resp)
- _, resp = Client.UpdateChannelNotifyProps(th.BasicChannel.Id, model.NewId(), props)
- CheckForbiddenStatus(t, resp)
- _, resp = Client.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, map[string]string{})
- CheckNoError(t, resp)
- Client.Logout()
- _, resp = Client.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, props)
- CheckUnauthorizedStatus(t, resp)
- _, resp = th.SystemAdminClient.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, props)
- CheckNoError(t, resp)
- }
- func TestAddChannelMember(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- user := th.BasicUser
- user2 := th.BasicUser2
- team := th.BasicTeam
- publicChannel := th.CreatePublicChannel()
- privateChannel := th.CreatePrivateChannel()
- user3 := th.CreateUserWithClient(th.SystemAdminClient)
- _, resp := th.SystemAdminClient.AddTeamMember(team.Id, user3.Id)
- CheckNoError(t, resp)
- cm, resp := Client.AddChannelMember(publicChannel.Id, user2.Id)
- CheckNoError(t, resp)
- CheckCreatedStatus(t, resp)
- require.Equal(t, publicChannel.Id, cm.ChannelId, "should have returned exact channel")
- require.Equal(t, user2.Id, cm.UserId, "should have returned exact user added to public channel")
- cm, resp = Client.AddChannelMember(privateChannel.Id, user2.Id)
- CheckNoError(t, resp)
- require.Equal(t, privateChannel.Id, cm.ChannelId, "should have returned exact channel")
- require.Equal(t, user2.Id, cm.UserId, "should have returned exact user added to private channel")
- post := &model.Post{ChannelId: publicChannel.Id, Message: "a" + GenerateTestId() + "a"}
- rpost, err := Client.CreatePost(post)
- require.NotNil(t, err)
- Client.RemoveUserFromChannel(publicChannel.Id, user.Id)
- _, resp = Client.AddChannelMemberWithRootId(publicChannel.Id, user.Id, rpost.Id)
- CheckNoError(t, resp)
- CheckCreatedStatus(t, resp)
- Client.RemoveUserFromChannel(publicChannel.Id, user.Id)
- _, resp = Client.AddChannelMemberWithRootId(publicChannel.Id, user.Id, "junk")
- CheckBadRequestStatus(t, resp)
- _, resp = Client.AddChannelMemberWithRootId(publicChannel.Id, user.Id, GenerateTestId())
- CheckNotFoundStatus(t, resp)
- Client.RemoveUserFromChannel(publicChannel.Id, user.Id)
- _, resp = Client.AddChannelMember(publicChannel.Id, user.Id)
- CheckNoError(t, resp)
- cm, resp = Client.AddChannelMember(publicChannel.Id, "junk")
- CheckBadRequestStatus(t, resp)
- require.Nil(t, cm, "should return nothing")
- _, resp = Client.AddChannelMember(publicChannel.Id, GenerateTestId())
- CheckNotFoundStatus(t, resp)
- _, resp = Client.AddChannelMember("junk", user2.Id)
- CheckBadRequestStatus(t, resp)
- _, resp = Client.AddChannelMember(GenerateTestId(), user2.Id)
- CheckNotFoundStatus(t, resp)
- otherUser := th.CreateUser()
- otherChannel := th.CreatePublicChannel()
- Client.Logout()
- Client.Login(user2.Id, user2.Password)
- _, resp = Client.AddChannelMember(publicChannel.Id, otherUser.Id)
- CheckUnauthorizedStatus(t, resp)
- _, resp = Client.AddChannelMember(privateChannel.Id, otherUser.Id)
- CheckUnauthorizedStatus(t, resp)
- _, resp = Client.AddChannelMember(otherChannel.Id, otherUser.Id)
- CheckUnauthorizedStatus(t, resp)
- Client.Logout()
- Client.Login(user.Id, user.Password)
- // should fail adding user who is not a member of the team
- _, resp = Client.AddChannelMember(otherChannel.Id, otherUser.Id)
- CheckUnauthorizedStatus(t, resp)
- Client.DeleteChannel(otherChannel.Id)
- // should fail adding user to a deleted channel
- _, resp = Client.AddChannelMember(otherChannel.Id, user2.Id)
- CheckUnauthorizedStatus(t, resp)
- Client.Logout()
- _, resp = Client.AddChannelMember(publicChannel.Id, user2.Id)
- CheckUnauthorizedStatus(t, resp)
- _, resp = Client.AddChannelMember(privateChannel.Id, user2.Id)
- CheckUnauthorizedStatus(t, resp)
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
- _, resp = client.AddChannelMember(publicChannel.Id, user2.Id)
- CheckNoError(t, resp)
- _, resp = client.AddChannelMember(privateChannel.Id, user2.Id)
- CheckNoError(t, resp)
- })
- // Check the appropriate permissions are enforced.
- defaultRolePermissions := th.SaveDefaultRolePermissions()
- defer func() {
- th.RestoreDefaultRolePermissions(defaultRolePermissions)
- }()
- th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID)
- // Check that a regular channel user can add other users.
- Client.Login(user2.Username, user2.Password)
- privateChannel = th.CreatePrivateChannel()
- _, resp = Client.AddChannelMember(privateChannel.Id, user.Id)
- CheckNoError(t, resp)
- Client.Logout()
- Client.Login(user.Username, user.Password)
- _, resp = Client.AddChannelMember(privateChannel.Id, user3.Id)
- CheckNoError(t, resp)
- Client.Logout()
- // Restrict the permission for adding users to Channel Admins
- th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_ADMIN_ROLE_ID)
- th.RemovePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID)
- Client.Login(user2.Username, user2.Password)
- privateChannel = th.CreatePrivateChannel()
- _, resp = Client.AddChannelMember(privateChannel.Id, user.Id)
- CheckNoError(t, resp)
- Client.Logout()
- Client.Login(user.Username, user.Password)
- _, resp = Client.AddChannelMember(privateChannel.Id, user3.Id)
- CheckForbiddenStatus(t, resp)
- Client.Logout()
- th.MakeUserChannelAdmin(user, privateChannel)
- th.App.Srv().InvalidateAllCaches()
- Client.Login(user.Username, user.Password)
- _, resp = Client.AddChannelMember(privateChannel.Id, user3.Id)
- CheckNoError(t, resp)
- Client.Logout()
- // Set a channel to group-constrained
- privateChannel.GroupConstrained = model.NewBool(true)
- _, appErr := th.App.UpdateChannel(privateChannel)
- require.Nil(t, appErr)
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
- // User is not in associated groups so shouldn't be allowed
- _, resp = client.AddChannelMember(privateChannel.Id, user.Id)
- CheckErrorMessage(t, resp, "api.channel.add_members.user_denied")
- })
- // Associate group to team
- _, appErr = th.App.UpsertGroupSyncable(&model.GroupSyncable{
- GroupId: th.Group.Id,
- SyncableId: privateChannel.Id,
- Type: model.GroupSyncableTypeChannel,
- })
- require.Nil(t, appErr)
- // Add user to group
- _, appErr = th.App.UpsertGroupMember(th.Group.Id, user.Id)
- require.Nil(t, appErr)
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
- _, resp = client.AddChannelMember(privateChannel.Id, user.Id)
- CheckNoError(t, resp)
- })
- }
- func TestAddChannelMemberAddMyself(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- user := th.CreateUser()
- th.LinkUserToTeam(user, th.BasicTeam)
- notMemberPublicChannel1 := th.CreatePublicChannel()
- notMemberPublicChannel2 := th.CreatePublicChannel()
- notMemberPrivateChannel := th.CreatePrivateChannel()
- memberPublicChannel := th.CreatePublicChannel()
- memberPrivateChannel := th.CreatePrivateChannel()
- th.AddUserToChannel(user, memberPublicChannel)
- th.AddUserToChannel(user, memberPrivateChannel)
- testCases := []struct {
- Name string
- Channel *model.Channel
- WithJoinPublicPermission bool
- ExpectedError string
- }{
- {
- "Add myself to a public channel with JOIN_PUBLIC_CHANNEL permission",
- notMemberPublicChannel1,
- true,
- "",
- },
- {
- "Try to add myself to a private channel with the JOIN_PUBLIC_CHANNEL permission",
- notMemberPrivateChannel,
- true,
- "api.context.permissions.app_error",
- },
- {
- "Try to add myself to a public channel without the JOIN_PUBLIC_CHANNEL permission",
- notMemberPublicChannel2,
- false,
- "api.context.permissions.app_error",
- },
- {
- "Add myself a public channel where I'm already a member, not having JOIN_PUBLIC_CHANNEL or MANAGE MEMBERS permission",
- memberPublicChannel,
- false,
- "",
- },
- {
- "Add myself a private channel where I'm already a member, not having JOIN_PUBLIC_CHANNEL or MANAGE MEMBERS permission",
- memberPrivateChannel,
- false,
- "",
- },
- }
- Client.Login(user.Email, user.Password)
- for _, tc := range testCases {
- t.Run(tc.Name, func(t *testing.T) {
- // Check the appropriate permissions are enforced.
- defaultRolePermissions := th.SaveDefaultRolePermissions()
- defer func() {
- th.RestoreDefaultRolePermissions(defaultRolePermissions)
- }()
- if !tc.WithJoinPublicPermission {
- th.RemovePermissionFromRole(model.PERMISSION_JOIN_PUBLIC_CHANNELS.Id, model.TEAM_USER_ROLE_ID)
- }
- _, resp := Client.AddChannelMember(tc.Channel.Id, user.Id)
- if tc.ExpectedError == "" {
- CheckNoError(t, resp)
- } else {
- CheckErrorMessage(t, resp, tc.ExpectedError)
- }
- })
- }
- }
- func TestRemoveChannelMember(t *testing.T) {
- th := Setup(t).InitBasic()
- user1 := th.BasicUser
- user2 := th.BasicUser2
- team := th.BasicTeam
- defer th.TearDown()
- Client := th.Client
- th.App.UpdateConfig(func(cfg *model.Config) {
- *cfg.ServiceSettings.EnableBotAccountCreation = true
- })
- bot := th.CreateBotWithSystemAdminClient()
- th.App.AddUserToTeam(team.Id, bot.UserId, "")
- pass, resp := Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser2.Id)
- CheckNoError(t, resp)
- require.True(t, pass, "should have passed")
- _, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, "junk")
- CheckBadRequestStatus(t, resp)
- _, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, model.NewId())
- CheckNotFoundStatus(t, resp)
- _, resp = Client.RemoveUserFromChannel(model.NewId(), th.BasicUser2.Id)
- CheckNotFoundStatus(t, resp)
- th.LoginBasic2()
- _, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
- CheckForbiddenStatus(t, resp)
- t.Run("success", func(t *testing.T) {
- // Setup the system administrator to listen for websocket events from the channels.
- th.LinkUserToTeam(th.SystemAdminUser, th.BasicTeam)
- _, err := th.App.AddUserToChannel(th.SystemAdminUser, th.BasicChannel)
- require.Nil(t, err)
- _, err = th.App.AddUserToChannel(th.SystemAdminUser, th.BasicChannel2)
- require.Nil(t, err)
- props := map[string]string{}
- props[model.DESKTOP_NOTIFY_PROP] = model.CHANNEL_NOTIFY_ALL
- _, resp = th.SystemAdminClient.UpdateChannelNotifyProps(th.BasicChannel.Id, th.SystemAdminUser.Id, props)
- _, resp = th.SystemAdminClient.UpdateChannelNotifyProps(th.BasicChannel2.Id, th.SystemAdminUser.Id, props)
- CheckNoError(t, resp)
- wsClient, err := th.CreateWebSocketSystemAdminClient()
- require.Nil(t, err)
- wsClient.Listen()
- var closeWsClient sync.Once
- defer closeWsClient.Do(func() {
- wsClient.Close()
- })
- wsr := <-wsClient.EventChannel
- require.Equal(t, model.WEBSOCKET_EVENT_HELLO, wsr.EventType())
- // requirePost listens for websocket events and tries to find the post matching
- // the expected post's channel and message.
- requirePost := func(expectedPost *model.Post) {
- t.Helper()
- for {
- select {
- case event := <-wsClient.EventChannel:
- postData, ok := event.GetData()["post"]
- if !ok {
- continue
- }
- post := model.PostFromJson(strings.NewReader(postData.(string)))
- if post.ChannelId == expectedPost.ChannelId && post.Message == expectedPost.Message {
- return
- }
- case <-time.After(5 * time.Second):
- require.FailNow(t, "failed to find expected post after 5 seconds")
- return
- }
- }
- }
- th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel)
- _, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser2.Id)
- CheckNoError(t, resp)
- requirePost(&model.Post{
- Message: fmt.Sprintf("@%s left the channel.", th.BasicUser2.Username),
- ChannelId: th.BasicChannel.Id,
- })
- _, resp = Client.RemoveUserFromChannel(th.BasicChannel2.Id, th.BasicUser.Id)
- CheckNoError(t, resp)
- requirePost(&model.Post{
- Message: fmt.Sprintf("@%s removed from the channel.", th.BasicUser.Username),
- ChannelId: th.BasicChannel2.Id,
- })
- _, resp = th.SystemAdminClient.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
- CheckNoError(t, resp)
- requirePost(&model.Post{
- Message: fmt.Sprintf("@%s removed from the channel.", th.BasicUser.Username),
- ChannelId: th.BasicChannel.Id,
- })
- closeWsClient.Do(func() {
- wsClient.Close()
- })
- })
- // Leave deleted channel
- th.LoginBasic()
- deletedChannel := th.CreatePublicChannel()
- th.App.AddUserToChannel(th.BasicUser, deletedChannel)
- th.App.AddUserToChannel(th.BasicUser2, deletedChannel)
- deletedChannel.DeleteAt = 1
- th.App.UpdateChannel(deletedChannel)
- _, resp = Client.RemoveUserFromChannel(deletedChannel.Id, th.BasicUser.Id)
- CheckNoError(t, resp)
- th.LoginBasic()
- private := th.CreatePrivateChannel()
- th.App.AddUserToChannel(th.BasicUser2, private)
- _, resp = Client.RemoveUserFromChannel(private.Id, th.BasicUser2.Id)
- CheckNoError(t, resp)
- th.LoginBasic2()
- _, resp = Client.RemoveUserFromChannel(private.Id, th.BasicUser.Id)
- CheckForbiddenStatus(t, resp)
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
- th.App.AddUserToChannel(th.BasicUser, private)
- _, resp = client.RemoveUserFromChannel(private.Id, th.BasicUser.Id)
- CheckNoError(t, resp)
- })
- th.LoginBasic()
- th.UpdateUserToNonTeamAdmin(user1, team)
- th.App.Srv().InvalidateAllCaches()
- // Check the appropriate permissions are enforced.
- defaultRolePermissions := th.SaveDefaultRolePermissions()
- defer func() {
- th.RestoreDefaultRolePermissions(defaultRolePermissions)
- }()
- th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID)
- th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
- // Check that a regular channel user can remove other users.
- privateChannel := th.CreateChannelWithClient(client, model.CHANNEL_PRIVATE)
- _, resp = client.AddChannelMember(privateChannel.Id, user1.Id)
- CheckNoError(t, resp)
- _, resp = client.AddChannelMember(privateChannel.Id, user2.Id)
- CheckNoError(t, resp)
- _, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id)
- CheckNoError(t, resp)
- })
- // Restrict the permission for adding users to Channel Admins
- th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_ADMIN_ROLE_ID)
- th.RemovePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID)
- privateChannel := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE)
- _, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, user1.Id)
- CheckNoError(t, resp)
- _, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, user2.Id)
- CheckNoError(t, resp)
- _, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, bot.UserId)
- CheckNoError(t, resp)
- _, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id)
- CheckForbiddenStatus(t, resp)
- th.MakeUserChannelAdmin(user1, privateChannel)
- th.App.Srv().InvalidateAllCaches()
- _, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id)
- CheckNoError(t, resp)
- _, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, th.SystemAdminUser.Id)
- CheckNoError(t, resp)
- // If the channel is group-constrained the user cannot be removed
- privateChannel.GroupConstrained = model.NewBool(true)
- _, err := th.App.UpdateChannel(privateChannel)
- require.Nil(t, err)
- _, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id)
- require.Equal(t, "api.channel.remove_member.group_constrained.app_error", resp.Error.Id)
- // If the channel is group-constrained user can remove self
- _, resp = th.SystemAdminClient.RemoveUserFromChannel(privateChannel.Id, th.SystemAdminUser.Id)
- CheckNoError(t, resp)
- // Test on preventing removal of user from a direct channel
- directChannel, resp := Client.CreateDirectChannel(user1.Id, user2.Id)
- CheckNoError(t, resp)
- // If the channel is group-constrained a user can remove a bot
- _, resp = Client.RemoveUserFromChannel(privateChannel.Id, bot.UserId)
- CheckNoError(t, resp)
- _, resp = Client.RemoveUserFromChannel(directChannel.Id, user1.Id)
- CheckBadRequestStatus(t, resp)
- _, resp = Client.RemoveUserFromChannel(directChannel.Id, user2.Id)
- CheckBadRequestStatus(t, resp)
- _, resp = th.SystemAdminClient.RemoveUserFromChannel(directChannel.Id, user1.Id)
- CheckBadRequestStatus(t, resp)
- // Test on preventing removal of user from a group channel
- user3 := th.CreateUser()
- groupChannel, resp := Client.CreateGroupChannel([]string{user1.Id, user2.Id, user3.Id})
- CheckNoError(t, resp)
- th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
- _, resp = client.RemoveUserFromChannel(groupChannel.Id, user1.Id)
- CheckBadRequestStatus(t, resp)
- })
- }
- func TestAutocompleteChannels(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- // A private channel to make sure private channels are not used
- utils.DisableDebugLogForTest()
- ptown, _ := th.Client.CreateChannel(&model.Channel{
- DisplayName: "Town",
- Name: "town",
- Type: model.CHANNEL_PRIVATE,
- TeamId: th.BasicTeam.Id,
- })
- tower, _ := th.Client.CreateChannel(&model.Channel{
- DisplayName: "Tower",
- Name: "tower",
- Type: model.CHANNEL_OPEN,
- TeamId: th.BasicTeam.Id,
- })
- utils.EnableDebugLogForTest()
- defer func() {
- th.Client.DeleteChannel(ptown.Id)
- th.Client.DeleteChannel(tower.Id)
- }()
- for _, tc := range []struct {
- description string
- teamId string
- fragment string
- expectedIncludes []string
- expectedExcludes []string
- }{
- {
- "Basic town-square",
- th.BasicTeam.Id,
- "town",
- []string{"town-square"},
- []string{"off-topic", "town", "tower"},
- },
- {
- "Basic off-topic",
- th.BasicTeam.Id,
- "off-to",
- []string{"off-topic"},
- []string{"town-square", "town", "tower"},
- },
- {
- "Basic town square and off topic",
- th.BasicTeam.Id,
- "tow",
- []string{"town-square", "tower"},
- []string{"off-topic", "town"},
- },
- } {
- t.Run(tc.description, func(t *testing.T) {
- channels, resp := th.Client.AutocompleteChannelsForTeam(tc.teamId, tc.fragment)
- require.Nil(t, resp.Error)
- names := make([]string, len(*channels))
- for i, c := range *channels {
- names[i] = c.Name
- }
- for _, name := range tc.expectedIncludes {
- require.Contains(t, names, name, "channel not included")
- }
- for _, name := range tc.expectedExcludes {
- require.NotContains(t, names, name, "channel not excluded")
- }
- })
- }
- }
- func TestAutocompleteChannelsForSearch(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- th.LoginSystemAdminWithClient(th.SystemAdminClient)
- th.LoginBasicWithClient(th.Client)
- u1 := th.CreateUserWithClient(th.SystemAdminClient)
- defer th.App.PermanentDeleteUser(u1)
- u2 := th.CreateUserWithClient(th.SystemAdminClient)
- defer th.App.PermanentDeleteUser(u2)
- u3 := th.CreateUserWithClient(th.SystemAdminClient)
- defer th.App.PermanentDeleteUser(u3)
- u4 := th.CreateUserWithClient(th.SystemAdminClient)
- defer th.App.PermanentDeleteUser(u4)
- // A private channel to make sure private channels are not used
- utils.DisableDebugLogForTest()
- ptown, _ := th.SystemAdminClient.CreateChannel(&model.Channel{
- DisplayName: "Town",
- Name: "town",
- Type: model.CHANNEL_PRIVATE,
- TeamId: th.BasicTeam.Id,
- })
- defer func() {
- th.Client.DeleteChannel(ptown.Id)
- }()
- mypriv, _ := th.Client.CreateChannel(&model.Channel{
- DisplayName: "My private town",
- Name: "townpriv",
- Type: model.CHANNEL_PRIVATE,
- TeamId: th.BasicTeam.Id,
- })
- defer func() {
- th.Client.DeleteChannel(mypriv.Id)
- }()
- utils.EnableDebugLogForTest()
- dc1, resp := th.Client.CreateDirectChannel(th.BasicUser.Id, u1.Id)
- CheckNoError(t, resp)
- defer func() {
- th.Client.DeleteChannel(dc1.Id)
- }()
- dc2, resp := th.SystemAdminClient.CreateDirectChannel(u2.Id, u3.Id)
- CheckNoError(t, resp)
- defer func() {
- th.SystemAdminClient.DeleteChannel(dc2.Id)
- }()
- gc1, resp := th.Client.CreateGroupChannel([]string{th.BasicUser.Id, u2.Id, u3.Id})
- CheckNoError(t, resp)
- defer func() {
- th.Client.DeleteChannel(gc1.Id)
- }()
- gc2, resp := th.SystemAdminClient.CreateGroupChannel([]string{u2.Id, u3.Id, u4.Id})
- CheckNoError(t, resp)
- defer func() {
- th.SystemAdminClient.DeleteChannel(gc2.Id)
- }()
- for _, tc := range []struct {
- description string
- teamID string
- fragment string
- expectedIncludes []string
- expectedExcludes []string
- }{
- {
- "Basic town-square",
- th.BasicTeam.Id,
- "town",
- []string{"town-square", "townpriv"},
- []string{"off-topic", "town"},
- },
- {
- "Basic off-topic",
- th.BasicTeam.Id,
- "off-to",
- []string{"off-topic"},
- []string{"town-square", "town", "townpriv"},
- },
- {
- "Basic town square and townpriv",
- th.BasicTeam.Id,
- "tow",
- []string{"town-square", "townpriv"},
- []string{"off-topic", "town"},
- },
- {
- "Direct and group messages",
- th.BasicTeam.Id,
- "fakeuser",
- []string{dc1.Name, gc1.Name},
- []string{dc2.Name, gc2.Name},
- },
- } {
- t.Run(tc.description, func(t *testing.T) {
- channels, resp := th.Client.AutocompleteChannelsForTeamForSearch(tc.teamID, tc.fragment)
- require.Nil(t, resp.Error)
- names := make([]string, len(*channels))
- for i, c := range *channels {
- names[i] = c.Name
- }
- for _, name := range tc.expectedIncludes {
- require.Contains(t, names, name, "channel not included")
- }
- for _, name := range tc.expectedExcludes {
- require.NotContains(t, names, name, "channel not excluded")
- }
- })
- }
- }
- func TestAutocompleteChannelsForSearchGuestUsers(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- u1 := th.CreateUserWithClient(th.SystemAdminClient)
- defer th.App.PermanentDeleteUser(u1)
- enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable
- defer func() {
- th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts })
- th.App.Srv().RemoveLicense()
- }()
- th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true })
- th.App.Srv().SetLicense(model.NewTestLicense())
- id := model.NewId()
- guest := &model.User{
- Email: "success+" + id + "@simulator.amazonses.com",
- Username: "un_" + id,
- Nickname: "nn_" + id,
- Password: "Password1",
- EmailVerified: true,
- }
- guest, err := th.App.CreateGuest(guest)
- require.Nil(t, err)
- th.LoginSystemAdminWithClient(th.SystemAdminClient)
- _, resp := th.SystemAdminClient.AddTeamMember(th.BasicTeam.Id, guest.Id)
- CheckNoError(t, resp)
- // A private channel to make sure private channels are not used
- utils.DisableDebugLogForTest()
- town, _ := th.SystemAdminClient.CreateChannel(&model.Channel{
- DisplayName: "Town",
- Name: "town",
- Type: model.CHANNEL_OPEN,
- TeamId: th.BasicTeam.Id,
- })
- defer func() {
- th.SystemAdminClient.DeleteChannel(town.Id)
- }()
- _, resp = th.SystemAdminClient.AddChannelMember(town.Id, guest.Id)
- CheckNoError(t, resp)
- mypriv, _ := th.SystemAdminClient.CreateChannel(&model.Channel{
- DisplayName: "My private town",
- Name: "townpriv",
- Type: model.CHANNEL_PRIVATE,
- TeamId: th.BasicTeam.Id,
- })
- defer func() {
- th.SystemAdminClient.DeleteChannel(mypriv.Id)
- }()
- _, resp = th.SystemAdminClient.AddChannelMember(mypriv.Id, guest.Id)
- CheckNoError(t, resp)
- utils.EnableDebugLogForTest()
- dc1, resp := th.SystemAdminClient.CreateDirectChannel(th.BasicUser.Id, guest.Id)
- CheckNoError(t, resp)
- defer func() {
- th.SystemAdminClient.DeleteChannel(dc1.Id)
- }()
- dc2, resp := th.SystemAdminClient.CreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
- CheckNoError(t, resp)
- defer func() {
- th.SystemAdminClient.DeleteChannel(dc2.Id)
- }()
- gc1, resp := th.SystemAdminClient.CreateGroupChannel([]string{th.BasicUser.Id, th.BasicUser2.Id, guest.Id})
- CheckNoError(t, resp)
- defer func() {
- th.SystemAdminClient.DeleteChannel(gc1.Id)
- }()
- gc2, resp := th.SystemAdminClient.CreateGroupChannel([]string{th.BasicUser.Id, th.BasicUser2.Id, u1.Id})
- CheckNoError(t, resp)
- defer func() {
- th.SystemAdminClient.DeleteChannel(gc2.Id)
- }()
- _, resp = th.Client.Login(guest.Username, "Password1")
- CheckNoError(t, resp)
- for _, tc := range []struct {
- description string
- teamID string
- fragment string
- expectedIncludes []string
- expectedExcludes []string
- }{
- {
- "Should return those channel where is member",
- th.BasicTeam.Id,
- "town",
- []string{"town", "townpriv"},
- []string{"town-square", "off-topic"},
- },
- {
- "Should return empty if not member of the searched channels",
- th.BasicTeam.Id,
- "off-to",
- []string{},
- []string{"off-topic", "town-square", "town", "townpriv"},
- },
- {
- "Should return direct and group messages",
- th.BasicTeam.Id,
- "fakeuser",
- []string{dc1.Name, gc1.Name},
- []string{dc2.Name, gc2.Name},
- },
- } {
- t.Run(tc.description, func(t *testing.T) {
- channels, resp := th.Client.AutocompleteChannelsForTeamForSearch(tc.teamID, tc.fragment)
- require.Nil(t, resp.Error)
- names := make([]string, len(*channels))
- for i, c := range *channels {
- names[i] = c.Name
- }
- for _, name := range tc.expectedIncludes {
- require.Contains(t, names, name, "channel not included")
- }
- for _, name := range tc.expectedExcludes {
- require.NotContains(t, names, name, "channel not excluded")
- }
- })
- }
- }
- func TestUpdateChannelScheme(t *testing.T) {
- th := Setup(t)
- defer th.TearDown()
- th.App.Srv().SetLicense(model.NewTestLicense(""))
- th.App.SetPhase2PermissionsMigrationStatus(true)
- team, resp := th.SystemAdminClient.CreateTeam(&model.Team{
- DisplayName: "Name",
- Description: "Some description",
- CompanyName: "Some company name",
- AllowOpenInvite: false,
- InviteId: "inviteid0",
- Name: "z-z-" + model.NewId() + "a",
- Email: "success+" + model.NewId() + "@simulator.amazonses.com",
- Type: model.TEAM_OPEN,
- })
- CheckNoError(t, resp)
- channel, resp := th.SystemAdminClient.CreateChannel(&model.Channel{
- DisplayName: "Name",
- Name: "z-z-" + model.NewId() + "a",
- Type: model.CHANNEL_OPEN,
- TeamId: team.Id,
- })
- CheckNoError(t, resp)
- channelScheme, resp := th.SystemAdminClient.CreateScheme(&model.Scheme{
- DisplayName: "DisplayName",
- Name: model.NewId(),
- Description: "Some description",
- Scope: model.SCHEME_SCOPE_CHANNEL,
- })
- CheckNoError(t, resp)
- teamScheme, resp := th.SystemAdminClient.CreateScheme(&model.Scheme{
- DisplayName: "DisplayName",
- Name: model.NewId(),
- Description: "Some description",
- Scope: model.SCHEME_SCOPE_TEAM,
- })
- CheckNoError(t, resp)
- // Test the setup/base case.
- _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, channelScheme.Id)
- CheckNoError(t, resp)
- // Test various invalid channel and scheme id combinations.
- _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, "x")
- CheckBadRequestStatus(t, resp)
- _, resp = th.SystemAdminClient.UpdateChannelScheme("x", channelScheme.Id)
- CheckBadRequestStatus(t, resp)
- _, resp = th.SystemAdminClient.UpdateChannelScheme("x", "x")
- CheckBadRequestStatus(t, resp)
- // Test that permissions are required.
- _, resp = th.Client.UpdateChannelScheme(channel.Id, channelScheme.Id)
- CheckForbiddenStatus(t, resp)
- // Test that a license is required.
- th.App.Srv().SetLicense(nil)
- _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, channelScheme.Id)
- CheckNotImplementedStatus(t, resp)
- th.App.Srv().SetLicense(model.NewTestLicense(""))
- // Test an invalid scheme scope.
- _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, teamScheme.Id)
- CheckBadRequestStatus(t, resp)
- // Test that an unauthenticated user gets rejected.
- th.SystemAdminClient.Logout()
- _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, channelScheme.Id)
- CheckUnauthorizedStatus(t, resp)
- }
- func TestGetChannelMembersTimezones(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- user := th.BasicUser
- user.Timezone["useAutomaticTimezone"] = "false"
- user.Timezone["manualTimezone"] = "XOXO/BLABLA"
- _, resp := Client.UpdateUser(user)
- CheckNoError(t, resp)
- user2 := th.BasicUser2
- user2.Timezone["automaticTimezone"] = "NoWhere/Island"
- _, resp = th.SystemAdminClient.UpdateUser(user2)
- CheckNoError(t, resp)
- timezone, resp := Client.GetChannelMembersTimezones(th.BasicChannel.Id)
- CheckNoError(t, resp)
- require.Len(t, timezone, 2, "should return 2 timezones")
- //both users have same timezone
- user2.Timezone["automaticTimezone"] = "XOXO/BLABLA"
- _, resp = th.SystemAdminClient.UpdateUser(user2)
- CheckNoError(t, resp)
- timezone, resp = Client.GetChannelMembersTimezones(th.BasicChannel.Id)
- CheckNoError(t, resp)
- require.Len(t, timezone, 1, "should return 1 timezone")
- //no timezone set should return empty
- user2.Timezone["automaticTimezone"] = ""
- _, resp = th.SystemAdminClient.UpdateUser(user2)
- CheckNoError(t, resp)
- user.Timezone["manualTimezone"] = ""
- _, resp = Client.UpdateUser(user)
- CheckNoError(t, resp)
- timezone, resp = Client.GetChannelMembersTimezones(th.BasicChannel.Id)
- CheckNoError(t, resp)
- require.Empty(t, timezone, "should return 0 timezone")
- }
- func TestChannelMembersMinusGroupMembers(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- user1 := th.BasicUser
- user2 := th.BasicUser2
- channel := th.CreatePrivateChannel()
- _, err := th.App.AddChannelMember(user1.Id, channel, "", "")
- require.Nil(t, err)
- _, err = th.App.AddChannelMember(user2.Id, channel, "", "")
- require.Nil(t, err)
- channel.GroupConstrained = model.NewBool(true)
- channel, err = th.App.UpdateChannel(channel)
- require.Nil(t, err)
- group1 := th.CreateGroup()
- group2 := th.CreateGroup()
- _, err = th.App.UpsertGroupMember(group1.Id, user1.Id)
- require.Nil(t, err)
- _, err = th.App.UpsertGroupMember(group2.Id, user2.Id)
- require.Nil(t, err)
- // No permissions
- _, _, res := th.Client.ChannelMembersMinusGroupMembers(channel.Id, []string{group1.Id, group2.Id}, 0, 100, "")
- require.Equal(t, "api.context.permissions.app_error", res.Error.Id)
- testCases := map[string]struct {
- groupIDs []string
- page int
- perPage int
- length int
- count int
- otherAssertions func([]*model.UserWithGroups)
- }{
- "All groups, expect no users removed": {
- groupIDs: []string{group1.Id, group2.Id},
- page: 0,
- perPage: 100,
- length: 0,
- count: 0,
- },
- "Some nonexistent group, page 0": {
- groupIDs: []string{model.NewId()},
- page: 0,
- perPage: 1,
- length: 1,
- count: 2,
- },
- "Some nonexistent group, page 1": {
- groupIDs: []string{model.NewId()},
- page: 1,
- perPage: 1,
- length: 1,
- count: 2,
- },
- "One group, expect one user removed": {
- groupIDs: []string{group1.Id},
- page: 0,
- perPage: 100,
- length: 1,
- count: 1,
- otherAssertions: func(uwg []*model.UserWithGroups) {
- require.Equal(t, uwg[0].Id, user2.Id)
- },
- },
- "Other group, expect other user removed": {
- groupIDs: []string{group2.Id},
- page: 0,
- perPage: 100,
- length: 1,
- count: 1,
- otherAssertions: func(uwg []*model.UserWithGroups) {
- require.Equal(t, uwg[0].Id, user1.Id)
- },
- },
- }
- for name, tc := range testCases {
- t.Run(name, func(t *testing.T) {
- uwg, count, res := th.SystemAdminClient.ChannelMembersMinusGroupMembers(channel.Id, tc.groupIDs, tc.page, tc.perPage, "")
- require.Nil(t, res.Error)
- require.Len(t, uwg, tc.length)
- require.Equal(t, tc.count, int(count))
- if tc.otherAssertions != nil {
- tc.otherAssertions(uwg)
- }
- })
- }
- }
- func TestGetChannelModerations(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- channel := th.BasicChannel
- team := th.BasicTeam
- th.App.SetPhase2PermissionsMigrationStatus(true)
- t.Run("Errors without a license", func(t *testing.T) {
- _, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
- require.Equal(t, "api.channel.get_channel_moderations.license.error", res.Error.Id)
- })
- th.App.Srv().SetLicense(model.NewTestLicense())
- t.Run("Errors as a non sysadmin", func(t *testing.T) {
- _, res := th.Client.GetChannelModerations(channel.Id, "")
- require.Equal(t, "api.context.permissions.app_error", res.Error.Id)
- })
- th.App.Srv().SetLicense(model.NewTestLicense())
- t.Run("Returns default moderations with default roles", func(t *testing.T) {
- moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
- require.Nil(t, res.Error)
- require.Equal(t, len(moderations), 4)
- for _, moderation := range moderations {
- if moderation.Name == "manage_members" {
- require.Empty(t, moderation.Roles.Guests)
- } else {
- require.Equal(t, moderation.Roles.Guests.Value, true)
- require.Equal(t, moderation.Roles.Guests.Enabled, true)
- }
- require.Equal(t, moderation.Roles.Members.Value, true)
- require.Equal(t, moderation.Roles.Members.Enabled, true)
- }
- })
- 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) {
- scheme := th.SetupTeamScheme()
- team.SchemeId = &scheme.Id
- _, err := th.App.UpdateTeamScheme(team)
- require.Nil(t, err)
- th.RemovePermissionFromRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole)
- defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole)
- moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
- require.Nil(t, res.Error)
- for _, moderation := range moderations {
- if moderation.Name == model.PERMISSION_CREATE_POST.Id {
- require.Equal(t, moderation.Roles.Members.Value, true)
- require.Equal(t, moderation.Roles.Members.Enabled, true)
- require.Equal(t, moderation.Roles.Guests.Value, false)
- require.Equal(t, moderation.Roles.Guests.Enabled, false)
- }
- }
- })
- 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) {
- scheme := th.SetupChannelScheme()
- channel.SchemeId = &scheme.Id
- _, err := th.App.UpdateChannelScheme(channel)
- require.Nil(t, err)
- th.RemovePermissionFromRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole)
- defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole)
- moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
- require.Nil(t, res.Error)
- for _, moderation := range moderations {
- if moderation.Name == model.PERMISSION_CREATE_POST.Id {
- require.Equal(t, moderation.Roles.Members.Value, true)
- require.Equal(t, moderation.Roles.Members.Enabled, true)
- require.Equal(t, moderation.Roles.Guests.Value, false)
- require.Equal(t, moderation.Roles.Guests.Enabled, true)
- }
- }
- })
- t.Run("Returns value false and enabled false for permissions that are not present in channel & team scheme", func(t *testing.T) {
- teamScheme := th.SetupTeamScheme()
- team.SchemeId = &teamScheme.Id
- th.App.UpdateTeamScheme(team)
- scheme := th.SetupChannelScheme()
- channel.SchemeId = &scheme.Id
- th.App.UpdateChannelScheme(channel)
- th.RemovePermissionFromRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole)
- th.RemovePermissionFromRole(model.PERMISSION_CREATE_POST.Id, teamScheme.DefaultChannelGuestRole)
- defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole)
- defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, teamScheme.DefaultChannelGuestRole)
- moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
- require.Nil(t, res.Error)
- for _, moderation := range moderations {
- if moderation.Name == model.PERMISSION_CREATE_POST.Id {
- require.Equal(t, moderation.Roles.Members.Value, true)
- require.Equal(t, moderation.Roles.Members.Enabled, true)
- require.Equal(t, moderation.Roles.Guests.Value, false)
- require.Equal(t, moderation.Roles.Guests.Enabled, false)
- }
- }
- })
- t.Run("Retuns the correct value for manage_members depending on whether the channel is public or private", func(t *testing.T) {
- scheme := th.SetupTeamScheme()
- team.SchemeId = &scheme.Id
- _, err := th.App.UpdateTeamScheme(team)
- require.Nil(t, err)
- th.RemovePermissionFromRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, scheme.DefaultChannelUserRole)
- defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelUserRole)
- // public channel does not have the permission
- moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
- require.Nil(t, res.Error)
- for _, moderation := range moderations {
- if moderation.Name == "manage_members" {
- require.Equal(t, moderation.Roles.Members.Value, false)
- }
- }
- // private channel does have the permission
- moderations, res = th.SystemAdminClient.GetChannelModerations(th.BasicPrivateChannel.Id, "")
- require.Nil(t, res.Error)
- for _, moderation := range moderations {
- if moderation.Name == "manage_members" {
- require.Equal(t, moderation.Roles.Members.Value, true)
- }
- }
- })
- t.Run("Does not return an error if the team scheme has a blank DefaultChannelGuestRole field", func(t *testing.T) {
- scheme := th.SetupTeamScheme()
- scheme.DefaultChannelGuestRole = ""
- mockStore := mocks.Store{}
- mockSchemeStore := mocks.SchemeStore{}
- mockSchemeStore.On("Get", mock.Anything).Return(scheme, nil)
- mockStore.On("Scheme").Return(&mockSchemeStore)
- mockStore.On("Team").Return(th.App.Srv().Store.Team())
- mockStore.On("Channel").Return(th.App.Srv().Store.Channel())
- mockStore.On("User").Return(th.App.Srv().Store.User())
- mockStore.On("Post").Return(th.App.Srv().Store.Post())
- mockStore.On("FileInfo").Return(th.App.Srv().Store.FileInfo())
- mockStore.On("Webhook").Return(th.App.Srv().Store.Webhook())
- mockStore.On("System").Return(th.App.Srv().Store.System())
- mockStore.On("License").Return(th.App.Srv().Store.License())
- mockStore.On("Role").Return(th.App.Srv().Store.Role())
- mockStore.On("Close").Return(nil)
- th.App.Srv().Store = &mockStore
- team.SchemeId = &scheme.Id
- _, err := th.App.UpdateTeamScheme(team)
- require.Nil(t, err)
- _, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
- require.Nil(t, res.Error)
- })
- }
- func TestPatchChannelModerations(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- channel := th.BasicChannel
- emptyPatch := []*model.ChannelModerationPatch{}
- createPosts := model.CHANNEL_MODERATED_PERMISSIONS[0]
- th.App.SetPhase2PermissionsMigrationStatus(true)
- t.Run("Errors without a license", func(t *testing.T) {
- _, res := th.SystemAdminClient.PatchChannelModerations(channel.Id, emptyPatch)
- require.Equal(t, "api.channel.patch_channel_moderations.license.error", res.Error.Id)
- })
- th.App.Srv().SetLicense(model.NewTestLicense())
- t.Run("Errors as a non sysadmin", func(t *testing.T) {
- _, res := th.Client.PatchChannelModerations(channel.Id, emptyPatch)
- require.Equal(t, "api.context.permissions.app_error", res.Error.Id)
- })
- th.App.Srv().SetLicense(model.NewTestLicense())
- t.Run("Returns default moderations with empty patch", func(t *testing.T) {
- moderations, res := th.SystemAdminClient.PatchChannelModerations(channel.Id, emptyPatch)
- require.Nil(t, res.Error)
- require.Equal(t, len(moderations), 4)
- for _, moderation := range moderations {
- if moderation.Name == "manage_members" {
- require.Empty(t, moderation.Roles.Guests)
- } else {
- require.Equal(t, moderation.Roles.Guests.Value, true)
- require.Equal(t, moderation.Roles.Guests.Enabled, true)
- }
- require.Equal(t, moderation.Roles.Members.Value, true)
- require.Equal(t, moderation.Roles.Members.Enabled, true)
- }
- require.Nil(t, channel.SchemeId)
- })
- t.Run("Creates a scheme and returns the updated channel moderations when patching an existing permission", func(t *testing.T) {
- patch := []*model.ChannelModerationPatch{
- {
- Name: &createPosts,
- Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(false)},
- },
- }
- moderations, res := th.SystemAdminClient.PatchChannelModerations(channel.Id, patch)
- require.Nil(t, res.Error)
- require.Equal(t, len(moderations), 4)
- for _, moderation := range moderations {
- if moderation.Name == "manage_members" {
- require.Empty(t, moderation.Roles.Guests)
- } else {
- require.Equal(t, moderation.Roles.Guests.Value, true)
- require.Equal(t, moderation.Roles.Guests.Enabled, true)
- }
- if moderation.Name == createPosts {
- require.Equal(t, moderation.Roles.Members.Value, false)
- require.Equal(t, moderation.Roles.Members.Enabled, true)
- } else {
- require.Equal(t, moderation.Roles.Members.Value, true)
- require.Equal(t, moderation.Roles.Members.Enabled, true)
- }
- }
- channel, _ = th.App.GetChannel(channel.Id)
- require.NotNil(t, channel.SchemeId)
- })
- t.Run("Removes the existing scheme when moderated permissions are set back to higher scoped values", func(t *testing.T) {
- channel, _ = th.App.GetChannel(channel.Id)
- schemeId := channel.SchemeId
- scheme, _ := th.App.GetScheme(*schemeId)
- require.Equal(t, scheme.DeleteAt, int64(0))
- patch := []*model.ChannelModerationPatch{
- {
- Name: &createPosts,
- Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(true)},
- },
- }
- moderations, res := th.SystemAdminClient.PatchChannelModerations(channel.Id, patch)
- require.Nil(t, res.Error)
- require.Equal(t, len(moderations), 4)
- for _, moderation := range moderations {
- if moderation.Name == "manage_members" {
- require.Empty(t, moderation.Roles.Guests)
- } else {
- require.Equal(t, moderation.Roles.Guests.Value, true)
- require.Equal(t, moderation.Roles.Guests.Enabled, true)
- }
- require.Equal(t, moderation.Roles.Members.Value, true)
- require.Equal(t, moderation.Roles.Members.Enabled, true)
- }
- channel, _ = th.App.GetChannel(channel.Id)
- require.Nil(t, channel.SchemeId)
- scheme, _ = th.App.GetScheme(*schemeId)
- require.NotEqual(t, scheme.DeleteAt, int64(0))
- })
- t.Run("Does not return an error if the team scheme has a blank DefaultChannelGuestRole field", func(t *testing.T) {
- team := th.BasicTeam
- scheme := th.SetupTeamScheme()
- scheme.DefaultChannelGuestRole = ""
- mockStore := mocks.Store{}
- mockSchemeStore := mocks.SchemeStore{}
- mockSchemeStore.On("Get", mock.Anything).Return(scheme, nil)
- mockSchemeStore.On("Save", mock.Anything).Return(scheme, nil)
- mockSchemeStore.On("Delete", mock.Anything).Return(scheme, nil)
- mockStore.On("Scheme").Return(&mockSchemeStore)
- mockStore.On("Team").Return(th.App.Srv().Store.Team())
- mockStore.On("Channel").Return(th.App.Srv().Store.Channel())
- mockStore.On("User").Return(th.App.Srv().Store.User())
- mockStore.On("Post").Return(th.App.Srv().Store.Post())
- mockStore.On("FileInfo").Return(th.App.Srv().Store.FileInfo())
- mockStore.On("Webhook").Return(th.App.Srv().Store.Webhook())
- mockStore.On("System").Return(th.App.Srv().Store.System())
- mockStore.On("License").Return(th.App.Srv().Store.License())
- mockStore.On("Role").Return(th.App.Srv().Store.Role())
- mockStore.On("Close").Return(nil)
- th.App.Srv().Store = &mockStore
- team.SchemeId = &scheme.Id
- _, err := th.App.UpdateTeamScheme(team)
- require.Nil(t, err)
- moderations, res := th.SystemAdminClient.PatchChannelModerations(channel.Id, emptyPatch)
- require.Nil(t, res.Error)
- require.Equal(t, len(moderations), 4)
- for _, moderation := range moderations {
- if moderation.Name == "manage_members" {
- require.Empty(t, moderation.Roles.Guests)
- } else {
- require.Equal(t, moderation.Roles.Guests.Value, false)
- require.Equal(t, moderation.Roles.Guests.Enabled, false)
- }
- require.Equal(t, moderation.Roles.Members.Value, true)
- require.Equal(t, moderation.Roles.Members.Enabled, true)
- }
- patch := []*model.ChannelModerationPatch{
- {
- Name: &createPosts,
- Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(true)},
- },
- }
- moderations, res = th.SystemAdminClient.PatchChannelModerations(channel.Id, patch)
- require.Nil(t, res.Error)
- require.Equal(t, len(moderations), 4)
- for _, moderation := range moderations {
- if moderation.Name == "manage_members" {
- require.Empty(t, moderation.Roles.Guests)
- } else {
- require.Equal(t, moderation.Roles.Guests.Value, false)
- require.Equal(t, moderation.Roles.Guests.Enabled, false)
- }
- require.Equal(t, moderation.Roles.Members.Value, true)
- require.Equal(t, moderation.Roles.Members.Enabled, true)
- }
- })
- }
- func TestGetChannelMemberCountsByGroup(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- channel := th.BasicChannel
- t.Run("Errors without a license", func(t *testing.T) {
- _, res := th.SystemAdminClient.GetChannelMemberCountsByGroup(channel.Id, false, "")
- require.Equal(t, "api.channel.channel_member_counts_by_group.license.error", res.Error.Id)
- })
- th.App.Srv().SetLicense(model.NewTestLicense())
- t.Run("Errors without read permission to the channel", func(t *testing.T) {
- _, res := th.Client.GetChannelMemberCountsByGroup(model.NewId(), false, "")
- require.Equal(t, "api.context.permissions.app_error", res.Error.Id)
- })
- t.Run("Returns empty for a channel with no members or groups", func(t *testing.T) {
- memberCounts, _ := th.SystemAdminClient.GetChannelMemberCountsByGroup(channel.Id, false, "")
- require.Equal(t, []*model.ChannelMemberCountByGroup{}, memberCounts)
- })
- user := th.BasicUser
- user.Timezone["useAutomaticTimezone"] = "false"
- user.Timezone["manualTimezone"] = "XOXO/BLABLA"
- _, err := th.App.UpsertGroupMember(th.Group.Id, user.Id)
- require.Nil(t, err)
- _, resp := th.SystemAdminClient.UpdateUser(user)
- CheckNoError(t, resp)
- user2 := th.BasicUser2
- user2.Timezone["automaticTimezone"] = "NoWhere/Island"
- _, err = th.App.UpsertGroupMember(th.Group.Id, user2.Id)
- require.Nil(t, err)
- _, resp = th.SystemAdminClient.UpdateUser(user2)
- CheckNoError(t, resp)
- t.Run("Returns users in group without timezones", func(t *testing.T) {
- memberCounts, _ := th.SystemAdminClient.GetChannelMemberCountsByGroup(channel.Id, false, "")
- expectedMemberCounts := []*model.ChannelMemberCountByGroup{
- {
- GroupId: th.Group.Id,
- ChannelMemberCount: 2,
- ChannelMemberTimezonesCount: 0,
- },
- }
- require.Equal(t, expectedMemberCounts, memberCounts)
- })
- t.Run("Returns users in group with timezones", func(t *testing.T) {
- memberCounts, _ := th.SystemAdminClient.GetChannelMemberCountsByGroup(channel.Id, true, "")
- expectedMemberCounts := []*model.ChannelMemberCountByGroup{
- {
- GroupId: th.Group.Id,
- ChannelMemberCount: 2,
- ChannelMemberTimezonesCount: 2,
- },
- }
- require.Equal(t, expectedMemberCounts, memberCounts)
- })
- id := model.NewId()
- group := &model.Group{
- DisplayName: "dn_" + id,
- Name: model.NewString("name" + id),
- Source: model.GroupSourceLdap,
- RemoteId: model.NewId(),
- }
- _, err = th.App.CreateGroup(group)
- require.Nil(t, err)
- _, err = th.App.UpsertGroupMember(group.Id, user.Id)
- require.Nil(t, err)
- t.Run("Returns multiple groups with users in group with timezones", func(t *testing.T) {
- memberCounts, _ := th.SystemAdminClient.GetChannelMemberCountsByGroup(channel.Id, true, "")
- expectedMemberCounts := []*model.ChannelMemberCountByGroup{
- {
- GroupId: group.Id,
- ChannelMemberCount: 1,
- ChannelMemberTimezonesCount: 1,
- },
- {
- GroupId: th.Group.Id,
- ChannelMemberCount: 2,
- ChannelMemberTimezonesCount: 2,
- },
- }
- require.ElementsMatch(t, expectedMemberCounts, memberCounts)
- })
- }
- func TestMoveChannel(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- Client := th.Client
- team1 := th.BasicTeam
- team2 := th.CreateTeam()
- t.Run("Should move channel", func(t *testing.T) {
- publicChannel := th.CreatePublicChannel()
- ch, resp := th.SystemAdminClient.MoveChannel(publicChannel.Id, team2.Id, false)
- require.Nil(t, resp.Error)
- require.Equal(t, team2.Id, ch.TeamId)
- })
- t.Run("Should fail when trying to move a private channel", func(t *testing.T) {
- channel := th.CreatePrivateChannel()
- _, resp := Client.MoveChannel(channel.Id, team1.Id, false)
- require.NotNil(t, resp.Error)
- CheckErrorMessage(t, resp, "api.channel.move_channel.type.invalid")
- })
- t.Run("Should fail when trying to move a DM channel", func(t *testing.T) {
- user := th.CreateUser()
- dmChannel := th.CreateDmChannel(user)
- _, resp := Client.MoveChannel(dmChannel.Id, team1.Id, false)
- require.NotNil(t, resp.Error)
- CheckErrorMessage(t, resp, "api.channel.move_channel.type.invalid")
- })
- t.Run("Should fail when trying to move a group channel", func(t *testing.T) {
- user := th.CreateUser()
- gmChannel, err := th.App.CreateGroupChannel([]string{th.BasicUser.Id, th.SystemAdminUser.Id, th.TeamAdminUser.Id}, user.Id)
- require.Nil(t, err)
- _, resp := Client.MoveChannel(gmChannel.Id, team1.Id, false)
- require.NotNil(t, resp.Error)
- CheckErrorMessage(t, resp, "api.channel.move_channel.type.invalid")
- })
- t.Run("Should fail due to permissions", func(t *testing.T) {
- publicChannel := th.CreatePublicChannel()
- _, resp := Client.MoveChannel(publicChannel.Id, team1.Id, false)
- require.NotNil(t, resp.Error)
- CheckErrorMessage(t, resp, "api.context.permissions.app_error")
- })
- t.Run("Should fail to move channel due to a member not member of target team", func(t *testing.T) {
- publicChannel := th.CreatePublicChannel()
- user := th.BasicUser
- _, resp := th.SystemAdminClient.RemoveTeamMember(team2.Id, user.Id)
- CheckNoError(t, resp)
- _, resp = th.SystemAdminClient.AddChannelMember(publicChannel.Id, user.Id)
- CheckNoError(t, resp)
- _, resp = th.SystemAdminClient.MoveChannel(publicChannel.Id, team2.Id, false)
- require.NotNil(t, resp.Error)
- CheckErrorMessage(t, resp, "app.channel.move_channel.members_do_not_match.error")
- })
- t.Run("Should be able to (force) move channel by a member that is not member of target team", func(t *testing.T) {
- publicChannel := th.CreatePublicChannel()
- user := th.BasicUser
- _, resp := th.SystemAdminClient.RemoveTeamMember(team2.Id, user.Id)
- CheckNoError(t, resp)
- _, resp = th.SystemAdminClient.AddChannelMember(publicChannel.Id, user.Id)
- CheckNoError(t, resp)
- newChannel, resp := th.SystemAdminClient.MoveChannel(publicChannel.Id, team2.Id, true)
- require.Nil(t, resp.Error)
- require.Equal(t, team2.Id, newChannel.TeamId)
- })
- }
- func TestUpdateCategoryForTeamForUser(t *testing.T) {
- t.Run("should update the channel order of the Channels category", func(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- categories, resp := th.Client.GetSidebarCategoriesForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
- require.Nil(t, resp.Error)
- require.Len(t, categories.Categories, 3)
- require.Len(t, categories.Order, 3)
- channelsCategory := categories.Categories[1]
- require.Equal(t, model.SidebarCategoryChannels, channelsCategory.Type)
- require.Len(t, channelsCategory.Channels, 5) // Town Square, Off Topic, and the 3 channels created by InitBasic
- // Should return the correct values from the API
- updatedCategory := &model.SidebarCategoryWithChannels{
- SidebarCategory: channelsCategory.SidebarCategory,
- Channels: []string{channelsCategory.Channels[1], channelsCategory.Channels[0], channelsCategory.Channels[4], channelsCategory.Channels[3], channelsCategory.Channels[2]},
- }
- received, resp := th.Client.UpdateSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
- assert.Nil(t, resp.Error)
- assert.Equal(t, channelsCategory.Id, received.Id)
- assert.Equal(t, updatedCategory.Channels, received.Channels)
- // And when requesting the category later
- received, resp = th.Client.GetSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, channelsCategory.Id, "")
- assert.Nil(t, resp.Error)
- assert.Equal(t, channelsCategory.Id, received.Id)
- assert.Equal(t, updatedCategory.Channels, received.Channels)
- })
- t.Run("should update the sort order of the DM category", func(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- categories, resp := th.Client.GetSidebarCategoriesForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
- require.Nil(t, resp.Error)
- require.Len(t, categories.Categories, 3)
- require.Len(t, categories.Order, 3)
- dmsCategory := categories.Categories[2]
- require.Equal(t, model.SidebarCategoryDirectMessages, dmsCategory.Type)
- require.Equal(t, model.SidebarCategorySortRecent, dmsCategory.Sorting)
- // Should return the correct values from the API
- updatedCategory := &model.SidebarCategoryWithChannels{
- SidebarCategory: dmsCategory.SidebarCategory,
- Channels: dmsCategory.Channels,
- }
- updatedCategory.Sorting = model.SidebarCategorySortAlphabetical
- received, resp := th.Client.UpdateSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, dmsCategory.Id, updatedCategory)
- assert.Nil(t, resp.Error)
- assert.Equal(t, dmsCategory.Id, received.Id)
- assert.Equal(t, model.SidebarCategorySortAlphabetical, received.Sorting)
- // And when requesting the category later
- received, resp = th.Client.GetSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, dmsCategory.Id, "")
- assert.Nil(t, resp.Error)
- assert.Equal(t, dmsCategory.Id, received.Id)
- assert.Equal(t, model.SidebarCategorySortAlphabetical, received.Sorting)
- })
- t.Run("should update the display name of a custom category", func(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- customCategory, resp := th.Client.CreateSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{
- SidebarCategory: model.SidebarCategory{
- UserId: th.BasicUser.Id,
- TeamId: th.BasicTeam.Id,
- DisplayName: "custom123",
- },
- })
- require.Nil(t, resp.Error)
- require.Equal(t, "custom123", customCategory.DisplayName)
- // Should return the correct values from the API
- updatedCategory := &model.SidebarCategoryWithChannels{
- SidebarCategory: customCategory.SidebarCategory,
- Channels: customCategory.Channels,
- }
- updatedCategory.DisplayName = "abcCustom"
- received, resp := th.Client.UpdateSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, customCategory.Id, updatedCategory)
- assert.Nil(t, resp.Error)
- assert.Equal(t, customCategory.Id, received.Id)
- assert.Equal(t, updatedCategory.DisplayName, received.DisplayName)
- // And when requesting the category later
- received, resp = th.Client.GetSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, customCategory.Id, "")
- assert.Nil(t, resp.Error)
- assert.Equal(t, customCategory.Id, received.Id)
- assert.Equal(t, updatedCategory.DisplayName, received.DisplayName)
- })
- t.Run("should update the channel order of the category even if it contains archived channels", func(t *testing.T) {
- th := Setup(t).InitBasic()
- defer th.TearDown()
- categories, resp := th.Client.GetSidebarCategoriesForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, "")
- require.Nil(t, resp.Error)
- require.Len(t, categories.Categories, 3)
- require.Len(t, categories.Order, 3)
- channelsCategory := categories.Categories[1]
- require.Equal(t, model.SidebarCategoryChannels, channelsCategory.Type)
- require.Len(t, channelsCategory.Channels, 5) // Town Square, Off Topic, and the 3 channels created by InitBasic
- // Delete one of the channels
- _, resp = th.Client.DeleteChannel(th.BasicChannel.Id)
- require.Nil(t, resp.Error)
- // Should still be able to reorder the channels
- updatedCategory := &model.SidebarCategoryWithChannels{
- SidebarCategory: channelsCategory.SidebarCategory,
- Channels: []string{channelsCategory.Channels[1], channelsCategory.Channels[0], channelsCategory.Channels[4], channelsCategory.Channels[3], channelsCategory.Channels[2]},
- }
- received, resp := th.Client.UpdateSidebarCategoryForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
- require.Nil(t, resp.Error)
- assert.Equal(t, channelsCategory.Id, received.Id)
- assert.Equal(t, updatedCategory.Channels, received.Channels)
- })
- }
|