http_server.cpp 280 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540
  1. #include "smartbotic/webserver/http_server.hpp"
  2. #include "smartbotic/webserver/permissions.hpp"
  3. #include <nlohmann/json.hpp>
  4. #include <spdlog/spdlog.h>
  5. #include <algorithm>
  6. #include <chrono>
  7. #include <cstring>
  8. #include <filesystem>
  9. #include <fstream>
  10. #include <random>
  11. #include <sstream>
  12. namespace smartbotic::webserver {
  13. // ============================================================================
  14. // WebSocketServer Implementation
  15. // ============================================================================
  16. // Static instance pointer for callback access
  17. WebSocketServer* WebSocketServer::instance_ = nullptr;
  18. namespace {
  19. // Convert LLM MessageRole enum to lowercase string for JSON API
  20. auto MessageRoleToString(::smartbotic::llm::MessageRole role) -> std::string {
  21. switch (role) {
  22. case ::smartbotic::llm::MESSAGE_ROLE_SYSTEM: return "system";
  23. case ::smartbotic::llm::MESSAGE_ROLE_USER: return "user";
  24. case ::smartbotic::llm::MESSAGE_ROLE_ASSISTANT: return "assistant";
  25. case ::smartbotic::llm::MESSAGE_ROLE_TOOL: return "tool";
  26. default: return "unknown";
  27. }
  28. }
  29. auto GenerateSessionId() -> std::string {
  30. static std::random_device rd;
  31. static std::mt19937 gen(rd());
  32. static std::uniform_int_distribution<> dis(0, 15);
  33. static const char* hex = "0123456789abcdef";
  34. std::string uuid;
  35. uuid.reserve(36);
  36. for (int i = 0; i < 36; ++i) {
  37. if (i == 8 || i == 13 || i == 18 || i == 23) {
  38. uuid += '-';
  39. } else {
  40. uuid += hex[dis(gen)];
  41. }
  42. }
  43. return uuid;
  44. }
  45. } // namespace
  46. // LWS protocol definition - first protocol handles HTTP and is the default for WS
  47. static lws_protocols protocols[] = {
  48. {
  49. "http", // Default protocol name for HTTP/WS upgrade
  50. WebSocketServer::WsCallback,
  51. 0, // per_session_data_size - we manage our own
  52. 65536, // rx buffer size
  53. 0, // id
  54. nullptr, // user
  55. 65536 // tx_packet_size
  56. },
  57. LWS_PROTOCOL_LIST_TERM
  58. };
  59. WebSocketServer::WebSocketServer(uint16_t port, const std::string& path)
  60. : port_(port), path_(path) {
  61. instance_ = this;
  62. }
  63. WebSocketServer::~WebSocketServer() {
  64. Stop();
  65. instance_ = nullptr;
  66. }
  67. void WebSocketServer::Start() {
  68. if (running_.load()) {
  69. spdlog::warn("WebSocket server already running");
  70. return;
  71. }
  72. spdlog::info("Starting WebSocket server on port {}", port_);
  73. lws_context_creation_info info{};
  74. std::memset(&info, 0, sizeof(info));
  75. info.port = port_;
  76. info.protocols = protocols;
  77. info.gid = -1;
  78. info.uid = -1;
  79. info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
  80. info.vhost_name = "smartbotic-ws";
  81. // Suppress verbose lws logging
  82. lws_set_log_level(LLL_ERR | LLL_WARN, nullptr);
  83. context_ = lws_create_context(&info);
  84. if (context_ == nullptr) {
  85. spdlog::error("Failed to create libwebsocket context");
  86. return;
  87. }
  88. running_.store(true);
  89. eventLoopThread_ = std::thread(&WebSocketServer::RunEventLoop, this);
  90. spdlog::info("WebSocket server started on port {}", port_);
  91. }
  92. void WebSocketServer::Stop() {
  93. if (!running_.load()) {
  94. return;
  95. }
  96. spdlog::info("Stopping WebSocket server...");
  97. running_.store(false);
  98. // Cancel the event loop to wake up lws_service() immediately
  99. // This is async-signal-safe and can be called from signal handlers
  100. if (context_ != nullptr) {
  101. lws_cancel_service(context_);
  102. }
  103. if (eventLoopThread_.joinable()) {
  104. eventLoopThread_.join();
  105. }
  106. if (context_ != nullptr) {
  107. lws_context_destroy(context_);
  108. context_ = nullptr;
  109. }
  110. {
  111. std::lock_guard<std::mutex> lock(connectionsMutex_);
  112. connections_.clear();
  113. }
  114. spdlog::info("WebSocket server stopped");
  115. }
  116. void WebSocketServer::RunEventLoop() {
  117. while (running_.load()) {
  118. lws_service(context_, 50); // 50ms timeout
  119. }
  120. }
  121. void WebSocketServer::Broadcast(const std::string& message) {
  122. std::lock_guard<std::mutex> lock(connectionsMutex_);
  123. for (auto& [wsi, conn] : connections_) {
  124. QueueMessage(conn.get(), message);
  125. }
  126. }
  127. void WebSocketServer::SendToSession(const std::string& sessionId, const std::string& message) {
  128. std::lock_guard<std::mutex> lock(connectionsMutex_);
  129. for (auto& [wsi, conn] : connections_) {
  130. if (conn->sessionId == sessionId) {
  131. QueueMessage(conn.get(), message);
  132. break;
  133. }
  134. }
  135. }
  136. void WebSocketServer::SendToSubscribers(const std::string& subscription_key, const std::string& message) {
  137. std::lock_guard<std::mutex> lock(connectionsMutex_);
  138. for (auto& [wsi, conn] : connections_) {
  139. // Check if this connection is subscribed and authenticated
  140. if (!conn->authenticated) {
  141. continue;
  142. }
  143. const auto& subs = conn->subscriptions;
  144. if (std::find(subs.begin(), subs.end(), subscription_key) != subs.end()) {
  145. QueueMessage(conn.get(), message);
  146. }
  147. }
  148. }
  149. auto WebSocketServer::ConnectionCount() const -> size_t {
  150. std::lock_guard<std::mutex> lock(connectionsMutex_);
  151. return connections_.size();
  152. }
  153. void WebSocketServer::SetMessageHandler(WebSocketMessageHandler handler) {
  154. messageHandler_ = std::move(handler);
  155. }
  156. void WebSocketServer::HandleConnect(lws* wsi) {
  157. auto conn = std::make_unique<WsConnection>();
  158. conn->wsi = wsi;
  159. conn->sessionId = GenerateSessionId();
  160. spdlog::info("WebSocket client connected (session: {})", conn->sessionId);
  161. std::lock_guard<std::mutex> lock(connectionsMutex_);
  162. connections_[wsi] = std::move(conn);
  163. }
  164. void WebSocketServer::HandleDisconnect(lws* wsi) {
  165. std::lock_guard<std::mutex> lock(connectionsMutex_);
  166. auto it = connections_.find(wsi);
  167. if (it != connections_.end()) {
  168. spdlog::info("WebSocket client disconnected (session: {})", it->second->sessionId);
  169. connections_.erase(it);
  170. }
  171. }
  172. void WebSocketServer::HandleMessage(lws* wsi, const std::string& message) {
  173. WsConnection* conn = nullptr;
  174. {
  175. std::lock_guard<std::mutex> lock(connectionsMutex_);
  176. auto it = connections_.find(wsi);
  177. if (it != connections_.end()) {
  178. conn = it->second.get();
  179. }
  180. }
  181. // Call handler outside the lock to avoid deadlock with SendToSession
  182. if (conn && messageHandler_) {
  183. messageHandler_(conn, message);
  184. }
  185. }
  186. void WebSocketServer::QueueMessage(WsConnection* conn, const std::string& message) {
  187. std::lock_guard<std::mutex> lock(conn->sendMutex);
  188. // Prepend LWS_PRE bytes for libwebsockets
  189. conn->sendBuffer.resize(LWS_PRE + message.size());
  190. std::memcpy(conn->sendBuffer.data() + LWS_PRE, message.data(), message.size());
  191. lws_callback_on_writable(conn->wsi);
  192. }
  193. auto WebSocketServer::WsCallback(lws* wsi, lws_callback_reasons reason,
  194. void* user, void* in, size_t len) -> int {
  195. if (instance_ == nullptr) {
  196. return 0;
  197. }
  198. switch (reason) {
  199. case LWS_CALLBACK_PROTOCOL_INIT:
  200. spdlog::debug("WebSocket protocol initialized");
  201. break;
  202. case LWS_CALLBACK_ESTABLISHED:
  203. spdlog::debug("WebSocket connection established");
  204. instance_->HandleConnect(wsi);
  205. break;
  206. case LWS_CALLBACK_CLOSED:
  207. spdlog::debug("WebSocket connection closed");
  208. instance_->HandleDisconnect(wsi);
  209. break;
  210. case LWS_CALLBACK_RECEIVE: {
  211. std::string message(static_cast<char*>(in), len);
  212. spdlog::debug("WebSocket received {} bytes", len);
  213. instance_->HandleMessage(wsi, message);
  214. break;
  215. }
  216. case LWS_CALLBACK_SERVER_WRITEABLE: {
  217. std::lock_guard<std::mutex> lock(instance_->connectionsMutex_);
  218. auto it = instance_->connections_.find(wsi);
  219. if (it != instance_->connections_.end()) {
  220. auto& conn = it->second;
  221. std::lock_guard<std::mutex> sendLock(conn->sendMutex);
  222. if (conn->sendBuffer.size() > LWS_PRE) {
  223. size_t msgLen = conn->sendBuffer.size() - LWS_PRE;
  224. lws_write(wsi, conn->sendBuffer.data() + LWS_PRE, msgLen, LWS_WRITE_TEXT);
  225. conn->sendBuffer.clear();
  226. }
  227. }
  228. break;
  229. }
  230. case LWS_CALLBACK_HTTP:
  231. // Return non-zero to close the connection for non-WebSocket HTTP requests
  232. return -1;
  233. case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
  234. // Allow the connection
  235. return 0;
  236. default:
  237. break;
  238. }
  239. return 0;
  240. }
  241. // ============================================================================
  242. // HttpServer Implementation
  243. // ============================================================================
  244. HttpServer::HttpServer(HttpServerConfig config)
  245. : config_(std::move(config)),
  246. httpServer_(std::make_unique<httplib::Server>()),
  247. dbClient_(std::make_unique<DatabaseClient>(config_)),
  248. authService_(std::make_unique<AuthService>(config_.jwt)) {}
  249. HttpServer::~HttpServer() {
  250. if (running_.load()) {
  251. Stop();
  252. }
  253. }
  254. auto HttpServer::Start(bool require_database) -> bool {
  255. if (running_.load()) {
  256. spdlog::warn("Server already running");
  257. return true;
  258. }
  259. spdlog::info("Starting HTTP server on {}", config_.GetListenAddress());
  260. // Connect to database first (fail-fast if required)
  261. if (require_database) {
  262. spdlog::info("Connecting to database at {} (fail-fast mode enabled)", config_.database_address);
  263. if (!ConnectToDatabase()) {
  264. spdlog::error("Failed to connect to database - server startup aborted");
  265. return false;
  266. }
  267. } else {
  268. // Try to connect but don't fail if unavailable
  269. spdlog::info("Connecting to database at {} (optional mode)", config_.database_address);
  270. if (!ConnectToDatabase()) {
  271. spdlog::warn("Database connection failed - server will start without database connectivity");
  272. }
  273. }
  274. // Initialize services (only if database is connected)
  275. if (IsDatabaseConnected()) {
  276. if (!InitializeServices()) {
  277. spdlog::error("Failed to initialize services - server startup aborted");
  278. return false;
  279. }
  280. }
  281. // Setup routes
  282. SetupRoutes();
  283. // Start WebSocket server on separate port
  284. wsServer_ = std::make_unique<WebSocketServer>(config_.ws_port, config_.ws_path);
  285. // Setup WebSocket message handler using WsHandler if available
  286. if (wsHandler_) {
  287. wsServer_->SetMessageHandler([this](WsConnection* conn, const std::string& message) {
  288. wsHandler_->HandleMessage(conn, message,
  289. [this](WsConnection* c, const std::string& response) {
  290. wsServer_->SendToSession(c->sessionId, response);
  291. });
  292. });
  293. spdlog::info("WebSocket message handler configured with WsHandler");
  294. } else if (wsMessageHandler_) {
  295. wsServer_->SetMessageHandler(wsMessageHandler_);
  296. }
  297. wsServer_->Start();
  298. // Start HTTP server in a separate thread
  299. running_.store(true);
  300. httpThread_ = std::thread(&HttpServer::RunHttpServer, this);
  301. spdlog::info("HTTP server started successfully on {}", config_.GetListenAddress());
  302. spdlog::info("WebSocket server: ws://{}:{}{}", config_.address, config_.ws_port, config_.ws_path);
  303. spdlog::info("Static files: {}", config_.webui_path);
  304. spdlog::info("Database: {} ({})", config_.database_address,
  305. IsDatabaseConnected() ? "connected" : "not connected");
  306. return true;
  307. }
  308. void HttpServer::Stop() {
  309. if (!running_.load()) {
  310. return;
  311. }
  312. spdlog::info("Stopping HTTP server...");
  313. running_.store(false);
  314. // Stop WebSocket server first (this uses lws_cancel_service which is async-signal-safe)
  315. if (wsServer_) {
  316. wsServer_->Stop();
  317. }
  318. // Stop HTTP server - this makes listen() return
  319. if (httpServer_) {
  320. httpServer_->stop();
  321. }
  322. // Disconnect from database
  323. if (dbClient_) {
  324. dbClient_->Disconnect();
  325. }
  326. // NOTE: Don't join httpThread_ here - let Wait() handle it
  327. // This avoids race condition when Stop() is called from signal handler
  328. // while main thread is blocked in Wait()
  329. spdlog::info("HTTP server stop requested");
  330. }
  331. void HttpServer::Wait() {
  332. if (httpThread_.joinable()) {
  333. httpThread_.join();
  334. }
  335. spdlog::info("HTTP server stopped");
  336. }
  337. void HttpServer::BroadcastWebSocket(const std::string& message) {
  338. if (wsServer_) {
  339. wsServer_->Broadcast(message);
  340. }
  341. }
  342. void HttpServer::BroadcastDocumentEvent(const std::string& workspace_id,
  343. const std::string& collection,
  344. DocumentAction action,
  345. const std::string& document_id,
  346. const nlohmann::json& data) {
  347. if (!wsServer_ || !wsHandler_) {
  348. return;
  349. }
  350. std::string subscription_key = WsHandler::BuildSubscriptionKey(workspace_id, collection);
  351. // Build the event JSON
  352. nlohmann::json event = {
  353. {"type", "document"},
  354. {"action", DocumentActionToString(action)},
  355. {"workspace_id", workspace_id},
  356. {"collection", collection},
  357. {"document_id", document_id}
  358. };
  359. // Include data for create/update, exclude for delete
  360. if (action != DocumentAction::Delete && !data.is_null()) {
  361. event["data"] = data;
  362. }
  363. std::string event_str = event.dump();
  364. spdlog::debug("Broadcasting document event: {} {} in {} (key={})",
  365. DocumentActionToString(action), document_id, collection, subscription_key);
  366. wsServer_->SendToSubscribers(subscription_key, event_str);
  367. }
  368. void HttpServer::SetWebSocketMessageHandler(WebSocketMessageHandler handler) {
  369. wsMessageHandler_ = std::move(handler);
  370. if (wsServer_) {
  371. wsServer_->SetMessageHandler(wsMessageHandler_);
  372. }
  373. }
  374. auto HttpServer::GetWebSocketClientCount() const -> size_t {
  375. return wsServer_ ? wsServer_->ConnectionCount() : 0;
  376. }
  377. auto HttpServer::IsDatabaseConnected() const -> bool {
  378. return dbClient_ && dbClient_->IsConnected();
  379. }
  380. auto HttpServer::ConnectToDatabase() -> bool {
  381. if (!dbClient_) {
  382. dbClient_ = std::make_unique<DatabaseClient>(config_);
  383. }
  384. // Try to connect
  385. if (!dbClient_->Connect()) {
  386. return false;
  387. }
  388. // Perform a health check to verify the connection is working
  389. auto health = dbClient_->HealthCheck();
  390. if (!health.healthy) {
  391. spdlog::error("Database health check failed: {}", health.message);
  392. return false;
  393. }
  394. spdlog::info("Database health check passed (latency: {}ms)", health.latency.count());
  395. return true;
  396. }
  397. auto HttpServer::InitializeServices() -> bool {
  398. // Initialize UserService
  399. userService_ = std::make_unique<UserService>(*dbClient_);
  400. if (!userService_->Initialize()) {
  401. spdlog::error("Failed to initialize UserService");
  402. return false;
  403. }
  404. spdlog::info("UserService initialized successfully");
  405. // Initialize WorkspaceService
  406. workspaceService_ = std::make_unique<WorkspaceService>(*dbClient_);
  407. if (!workspaceService_->Initialize()) {
  408. spdlog::error("Failed to initialize WorkspaceService");
  409. return false;
  410. }
  411. spdlog::info("WorkspaceService initialized successfully");
  412. // Initialize GroupService
  413. groupService_ = std::make_unique<GroupService>(*dbClient_);
  414. if (!groupService_->Initialize()) {
  415. spdlog::error("Failed to initialize GroupService");
  416. return false;
  417. }
  418. spdlog::info("GroupService initialized successfully");
  419. // Initialize MembershipService
  420. membershipService_ = std::make_unique<MembershipService>(*dbClient_);
  421. if (!membershipService_->Initialize()) {
  422. spdlog::error("Failed to initialize MembershipService");
  423. return false;
  424. }
  425. spdlog::info("MembershipService initialized successfully");
  426. // Initialize ApiKeyService
  427. apiKeyService_ = std::make_unique<ApiKeyService>(*dbClient_);
  428. if (!apiKeyService_->Initialize()) {
  429. spdlog::error("Failed to initialize ApiKeyService");
  430. return false;
  431. }
  432. spdlog::info("ApiKeyService initialized successfully");
  433. // Initialize CollectionService
  434. collectionService_ = std::make_unique<CollectionService>(*dbClient_);
  435. spdlog::info("CollectionService initialized successfully");
  436. // Initialize DocumentService
  437. documentService_ = std::make_unique<DocumentService>(*dbClient_);
  438. spdlog::info("DocumentService initialized successfully");
  439. // Initialize ViewService
  440. viewService_ = std::make_unique<ViewService>(*dbClient_);
  441. if (!viewService_->Initialize()) {
  442. spdlog::error("Failed to initialize ViewService");
  443. return false;
  444. }
  445. spdlog::info("ViewService initialized successfully");
  446. // Initialize PageService
  447. pageService_ = std::make_unique<PageService>(*dbClient_);
  448. if (!pageService_->Initialize()) {
  449. spdlog::error("Failed to initialize PageService");
  450. return false;
  451. }
  452. spdlog::info("PageService initialized successfully");
  453. // Initialize AuthorizationService
  454. authorizationService_ = std::make_unique<AuthorizationService>(*groupService_, *collectionService_);
  455. if (!authorizationService_->Initialize()) {
  456. spdlog::error("Failed to initialize AuthorizationService");
  457. return false;
  458. }
  459. spdlog::info("AuthorizationService initialized successfully");
  460. // Initialize WsHandler for WebSocket real-time updates
  461. wsHandler_ = std::make_unique<WsHandler>(*authService_);
  462. spdlog::info("WsHandler initialized successfully");
  463. // Initialize LLM Client (connection to LLM service - optional, may not be available)
  464. LlmClientConfig llm_config;
  465. llm_config.address = config_.llm_address;
  466. llmClient_ = std::make_unique<LlmClient>(std::move(llm_config));
  467. if (llmClient_->Connect()) {
  468. spdlog::info("LLM client connected to {}", config_.llm_address);
  469. } else {
  470. spdlog::warn("LLM service not available at {} - LLM features will be disabled", config_.llm_address);
  471. }
  472. // Initialize ToolService for LLM tool calling
  473. toolService_ = std::make_unique<ToolService>(
  474. *authorizationService_,
  475. *workspaceService_,
  476. *viewService_,
  477. *pageService_,
  478. *documentService_,
  479. *collectionService_);
  480. toolService_->Initialize();
  481. spdlog::info("ToolService initialized successfully");
  482. // Note: WebSocket message handler is set up in Start() after wsServer_ is created
  483. return true;
  484. }
  485. void HttpServer::SetupRoutes() {
  486. // Pre-routing handler for CORS
  487. httpServer_->set_pre_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
  488. // Apply CORS headers if enabled
  489. if (config_.cors.enabled) {
  490. // Combine allowed origins
  491. std::string origins;
  492. for (size_t i = 0; i < config_.cors.allowed_origins.size(); ++i) {
  493. if (i > 0) origins += ", ";
  494. origins += config_.cors.allowed_origins[i];
  495. }
  496. res.set_header("Access-Control-Allow-Origin", origins);
  497. // Combine allowed methods
  498. std::string methods;
  499. for (size_t i = 0; i < config_.cors.allowed_methods.size(); ++i) {
  500. if (i > 0) methods += ", ";
  501. methods += config_.cors.allowed_methods[i];
  502. }
  503. res.set_header("Access-Control-Allow-Methods", methods);
  504. // Combine allowed headers
  505. std::string headers;
  506. for (size_t i = 0; i < config_.cors.allowed_headers.size(); ++i) {
  507. if (i > 0) headers += ", ";
  508. headers += config_.cors.allowed_headers[i];
  509. }
  510. res.set_header("Access-Control-Allow-Headers", headers);
  511. if (config_.cors.allow_credentials) {
  512. res.set_header("Access-Control-Allow-Credentials", "true");
  513. }
  514. res.set_header("Access-Control-Max-Age", std::to_string(config_.cors.max_age));
  515. }
  516. res.set_header("Server", "SmartBotic-Server/0.1.0");
  517. // Handle CORS preflight
  518. if (req.method == "OPTIONS") {
  519. res.status = 204;
  520. return httplib::Server::HandlerResponse::Handled;
  521. }
  522. return httplib::Server::HandlerResponse::Unhandled;
  523. });
  524. // Health check endpoint
  525. httpServer_->Get("/api/health", [this](const httplib::Request& req, httplib::Response& res) {
  526. HandleHealth(req, res);
  527. });
  528. // Version endpoint
  529. httpServer_->Get("/api/version", [this](const httplib::Request& req, httplib::Response& res) {
  530. HandleVersion(req, res);
  531. });
  532. // Bootstrap endpoint - creates first admin user if no users exist
  533. httpServer_->Post("/api/bootstrap", [this](const httplib::Request& req, httplib::Response& res) {
  534. HandleBootstrap(req, res);
  535. });
  536. // Setup authentication routes
  537. SetupAuthRoutes();
  538. // Setup user management routes
  539. SetupUserRoutes();
  540. // Setup API key routes (under /api/users/:id/api-keys)
  541. SetupApiKeyRoutes();
  542. // Setup membership routes (before workspace routes since they're more specific)
  543. SetupMembershipRoutes();
  544. // Setup document routes (most specific - before collections)
  545. SetupDocumentRoutes();
  546. // Setup view routes (schema definitions)
  547. SetupViewRoutes();
  548. // Setup page routes (page builder)
  549. SetupPageRoutes();
  550. // Setup LLM routes (AI assistant)
  551. SetupLlmRoutes();
  552. // Setup collection routes (before workspace routes since they're more specific)
  553. SetupCollectionRoutes();
  554. // Setup group management routes (before workspace routes since they're more specific)
  555. SetupGroupRoutes();
  556. // Setup workspace management routes
  557. SetupWorkspaceRoutes();
  558. // Mount static file directory for WebUI
  559. if (std::filesystem::exists(config_.webui_path)) {
  560. httpServer_->set_mount_point("/", config_.webui_path);
  561. spdlog::info("Mounted static files from: {}", config_.webui_path);
  562. } else {
  563. spdlog::warn("WebUI path does not exist: {}", config_.webui_path);
  564. }
  565. // Custom error handler for 404 (only if response body is empty)
  566. httpServer_->set_error_handler([](const httplib::Request& /*req*/, httplib::Response& res) {
  567. // Only set default error message if body hasn't been set by a handler
  568. if (res.body.empty()) {
  569. res.set_content(R"({"error":"Not found"})", "application/json");
  570. }
  571. });
  572. // Logger for requests
  573. httpServer_->set_logger([](const httplib::Request& req, const httplib::Response& res) {
  574. auto status = res.status;
  575. if (status >= 500) {
  576. spdlog::error("{} {} {}", req.method, req.path, status);
  577. } else if (status >= 400) {
  578. spdlog::warn("{} {} {}", req.method, req.path, status);
  579. } else {
  580. spdlog::info("{} {} {}", req.method, req.path, status);
  581. }
  582. });
  583. }
  584. void HttpServer::RunHttpServer() {
  585. if (!httpServer_->listen(config_.address, config_.port)) {
  586. spdlog::error("Failed to start HTTP server on {}", config_.GetListenAddress());
  587. running_.store(false);
  588. }
  589. }
  590. void HttpServer::HandleHealth(const httplib::Request& req, httplib::Response& res) {
  591. res.set_content(R"({"status":"healthy","service":"smartbotic-server"})", "application/json");
  592. }
  593. void HttpServer::HandleVersion(const httplib::Request& req, httplib::Response& res) {
  594. res.set_content(R"({"version":"0.1.0","name":"SmartBotic Web Server"})", "application/json");
  595. }
  596. void HttpServer::HandleBootstrap(const httplib::Request& req, httplib::Response& res) {
  597. // Bootstrap endpoint - creates first admin user if no users exist
  598. if (!userService_) {
  599. res.status = 500;
  600. res.set_content(R"({"error":"User service not available"})", "application/json");
  601. return;
  602. }
  603. // Check if any users exist
  604. auto users = userService_->ListUsers();
  605. if (!users.users.empty()) {
  606. res.status = 400;
  607. res.set_content(R"({"error":"System already bootstrapped - users exist"})", "application/json");
  608. return;
  609. }
  610. // Parse request body
  611. nlohmann::json body;
  612. try {
  613. body = nlohmann::json::parse(req.body);
  614. } catch (...) {
  615. res.status = 400;
  616. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  617. return;
  618. }
  619. // Validate required fields
  620. if (!body.contains("email") || !body.contains("password")) {
  621. res.status = 400;
  622. res.set_content(R"({"error":"Email and password are required"})", "application/json");
  623. return;
  624. }
  625. CreateUserRequest user_request;
  626. user_request.email = body["email"].get<std::string>();
  627. user_request.password = body["password"].get<std::string>();
  628. user_request.name = body.value("name", "Admin");
  629. // Create the admin user
  630. auto result = userService_->CreateUser(user_request);
  631. if (!result.success) {
  632. res.status = 400;
  633. nlohmann::json error_response;
  634. error_response["error"] = result.error;
  635. res.set_content(error_response.dump(), "application/json");
  636. return;
  637. }
  638. // Get the superadmin group to assign to the first user
  639. std::string superadmin_group_id;
  640. if (groupService_) {
  641. auto sa_group = groupService_->GetSuperadminGroup();
  642. if (sa_group.success && sa_group.group) {
  643. superadmin_group_id = sa_group.group->id;
  644. spdlog::info("Found superadmin group: {}", superadmin_group_id);
  645. } else {
  646. spdlog::warn("Superadmin group not found - first user will not have admin privileges");
  647. }
  648. }
  649. // Create a default workspace
  650. if (workspaceService_) {
  651. CreateWorkspaceRequest ws_request;
  652. ws_request.name = "Default Workspace";
  653. ws_request.settings["default"] = true;
  654. auto ws_result = workspaceService_->CreateWorkspace(ws_request);
  655. // Add user to workspace with superadmin group
  656. if (ws_result.success && ws_result.workspace && membershipService_) {
  657. AddMemberRequest member_request;
  658. member_request.workspace_id = ws_result.workspace->id;
  659. member_request.user_id = result.user->id;
  660. // Assign the superadmin group to the first user
  661. if (!superadmin_group_id.empty()) {
  662. member_request.group_ids = {superadmin_group_id};
  663. spdlog::info("Assigning superadmin group to bootstrap user");
  664. } else {
  665. member_request.group_ids = {};
  666. }
  667. [[maybe_unused]] auto member_result = membershipService_->AddMember(member_request);
  668. }
  669. }
  670. // Return success with user info
  671. nlohmann::json response;
  672. response["success"] = true;
  673. response["message"] = "System bootstrapped successfully";
  674. response["user"]["id"] = result.user->id;
  675. response["user"]["email"] = result.user->email;
  676. response["user"]["name"] = result.user->name;
  677. spdlog::info("System bootstrapped with admin user: {}", user_request.email);
  678. res.set_content(response.dump(), "application/json");
  679. }
  680. auto HttpServer::GetMimeType(const std::string& path) -> std::string {
  681. auto ext_pos = path.rfind('.');
  682. if (ext_pos == std::string::npos) {
  683. return "application/octet-stream";
  684. }
  685. std::string ext = path.substr(ext_pos);
  686. static const std::unordered_map<std::string, std::string> mime_types = {
  687. {".html", "text/html"},
  688. {".htm", "text/html"},
  689. {".css", "text/css"},
  690. {".js", "application/javascript"},
  691. {".json", "application/json"},
  692. {".png", "image/png"},
  693. {".jpg", "image/jpeg"},
  694. {".jpeg", "image/jpeg"},
  695. {".gif", "image/gif"},
  696. {".svg", "image/svg+xml"},
  697. {".ico", "image/x-icon"},
  698. {".woff", "font/woff"},
  699. {".woff2", "font/woff2"},
  700. {".ttf", "font/ttf"},
  701. {".eot", "application/vnd.ms-fontobject"},
  702. {".txt", "text/plain"},
  703. {".xml", "application/xml"},
  704. {".pdf", "application/pdf"},
  705. };
  706. auto it = mime_types.find(ext);
  707. if (it != mime_types.end()) {
  708. return it->second;
  709. }
  710. return "application/octet-stream";
  711. }
  712. // ============================================================================
  713. // Authentication Routes Implementation
  714. // ============================================================================
  715. void HttpServer::SetupAuthRoutes() {
  716. // POST /api/auth/login - Authenticate user and return JWT
  717. httpServer_->Post("/api/auth/login", [this](const httplib::Request& req, httplib::Response& res) {
  718. HandleAuthLogin(req, res);
  719. });
  720. // POST /api/auth/refresh - Refresh access token
  721. httpServer_->Post("/api/auth/refresh", [this](const httplib::Request& req, httplib::Response& res) {
  722. HandleAuthRefresh(req, res);
  723. });
  724. // POST /api/auth/logout - Invalidate refresh token
  725. httpServer_->Post("/api/auth/logout", [this](const httplib::Request& req, httplib::Response& res) {
  726. HandleAuthLogout(req, res);
  727. });
  728. // GET /api/auth/me - Get current authenticated user info
  729. httpServer_->Get("/api/auth/me", [this](const httplib::Request& req, httplib::Response& res) {
  730. HandleAuthMe(req, res);
  731. });
  732. spdlog::info("Authentication routes registered: /api/auth/login, /api/auth/refresh, /api/auth/logout, /api/auth/me");
  733. }
  734. void HttpServer::HandleAuthLogin(const httplib::Request& req, httplib::Response& res) {
  735. try {
  736. // Parse request body
  737. auto body = nlohmann::json::parse(req.body);
  738. if (!body.contains("email") || !body.contains("password")) {
  739. res.status = 400;
  740. res.set_content(R"({"error":"Missing email or password"})", "application/json");
  741. return;
  742. }
  743. std::string email = body["email"].get<std::string>();
  744. std::string password = body["password"].get<std::string>();
  745. if (config_.jwt.secret.empty()) {
  746. res.status = 500;
  747. res.set_content(R"({"error":"JWT secret not configured"})", "application/json");
  748. return;
  749. }
  750. if (!userService_) {
  751. res.status = 500;
  752. res.set_content(R"({"error":"User service not available"})", "application/json");
  753. return;
  754. }
  755. // Verify user credentials
  756. auto user_result = userService_->VerifyCredentials(email, password);
  757. if (!user_result.success || !user_result.user) {
  758. res.status = 401;
  759. res.set_content(R"({"error":"Invalid email or password"})", "application/json");
  760. return;
  761. }
  762. const auto& user = *user_result.user;
  763. // Get user's workspace memberships
  764. std::vector<std::string> workspace_ids;
  765. if (membershipService_) {
  766. auto memberships = membershipService_->ListUserMemberships(user.id);
  767. for (const auto& m : memberships.members) {
  768. workspace_ids.push_back(m.workspace_id);
  769. }
  770. }
  771. // Collect user's groups from memberships
  772. // Note: Superadmin status is determined by group membership, not by special logic
  773. // The first user gets superadmin group assigned during bootstrap
  774. std::vector<std::string> groups;
  775. if (membershipService_) {
  776. auto memberships = membershipService_->ListUserMemberships(user.id);
  777. for (const auto& m : memberships.members) {
  778. for (const auto& gid : m.group_ids) {
  779. if (std::find(groups.begin(), groups.end(), gid) == groups.end()) {
  780. groups.push_back(gid);
  781. }
  782. }
  783. }
  784. }
  785. auto tokens = authService_->GenerateTokens(user.id, email, workspace_ids, groups);
  786. nlohmann::json response = {
  787. {"access_token", tokens.access_token},
  788. {"refresh_token", tokens.refresh_token},
  789. {"token_type", "Bearer"},
  790. {"expires_in", tokens.access_expires_in}
  791. };
  792. spdlog::info("User logged in: {}", email);
  793. res.set_content(response.dump(), "application/json");
  794. } catch (const nlohmann::json::parse_error& e) {
  795. res.status = 400;
  796. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  797. } catch (const std::exception& e) {
  798. spdlog::error("Login error: {}", e.what());
  799. res.status = 500;
  800. res.set_content(R"({"error":"Internal server error"})", "application/json");
  801. }
  802. }
  803. void HttpServer::HandleAuthRefresh(const httplib::Request& req, httplib::Response& res) {
  804. try {
  805. // Parse request body
  806. auto body = nlohmann::json::parse(req.body);
  807. if (!body.contains("refresh_token")) {
  808. res.status = 400;
  809. res.set_content(R"({"error":"Missing refresh_token"})", "application/json");
  810. return;
  811. }
  812. std::string refresh_token = body["refresh_token"].get<std::string>();
  813. auto new_tokens = authService_->RefreshAccessToken(refresh_token);
  814. if (!new_tokens) {
  815. res.status = 401;
  816. res.set_content(R"({"error":"Invalid or expired refresh token"})", "application/json");
  817. return;
  818. }
  819. nlohmann::json response = {
  820. {"access_token", new_tokens->access_token},
  821. {"refresh_token", new_tokens->refresh_token},
  822. {"token_type", "Bearer"},
  823. {"expires_in", new_tokens->access_expires_in}
  824. };
  825. spdlog::debug("Token refreshed successfully");
  826. res.set_content(response.dump(), "application/json");
  827. } catch (const nlohmann::json::parse_error& e) {
  828. res.status = 400;
  829. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  830. } catch (const std::exception& e) {
  831. spdlog::error("Token refresh error: {}", e.what());
  832. res.status = 500;
  833. res.set_content(R"({"error":"Internal server error"})", "application/json");
  834. }
  835. }
  836. void HttpServer::HandleAuthLogout(const httplib::Request& req, httplib::Response& res) {
  837. try {
  838. // Parse request body
  839. auto body = nlohmann::json::parse(req.body);
  840. if (!body.contains("refresh_token")) {
  841. res.status = 400;
  842. res.set_content(R"({"error":"Missing refresh_token"})", "application/json");
  843. return;
  844. }
  845. std::string refresh_token = body["refresh_token"].get<std::string>();
  846. if (authService_->InvalidateRefreshToken(refresh_token)) {
  847. spdlog::debug("User logged out successfully");
  848. res.set_content(R"({"message":"Logged out successfully"})", "application/json");
  849. } else {
  850. res.status = 400;
  851. res.set_content(R"({"error":"Invalid refresh token"})", "application/json");
  852. }
  853. } catch (const nlohmann::json::parse_error& e) {
  854. res.status = 400;
  855. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  856. } catch (const std::exception& e) {
  857. spdlog::error("Logout error: {}", e.what());
  858. res.status = 500;
  859. res.set_content(R"({"error":"Internal server error"})", "application/json");
  860. }
  861. }
  862. void HttpServer::HandleAuthMe(const httplib::Request& req, httplib::Response& res) {
  863. auto auth_user = AuthenticateRequest(req);
  864. if (!auth_user) {
  865. res.status = 401;
  866. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  867. return;
  868. }
  869. // Build response with user info from token
  870. nlohmann::json response = {
  871. {"id", auth_user->user_id},
  872. {"email", auth_user->email},
  873. {"groups", auth_user->groups},
  874. {"workspace_ids", auth_user->workspace_ids}
  875. };
  876. // Try to get additional user info from database
  877. if (userService_) {
  878. auto user_result = userService_->GetUser(auth_user->user_id);
  879. if (user_result.success && user_result.user) {
  880. response["name"] = user_result.user->name;
  881. response["created_at"] = user_result.user->created_at;
  882. }
  883. }
  884. // Check if user is superadmin based on groups
  885. response["is_superadmin"] = IsSuperadmin(*auth_user);
  886. res.set_content(response.dump(), "application/json");
  887. }
  888. auto HttpServer::AuthenticateRequest(const httplib::Request& req) -> std::optional<AuthUser> {
  889. std::string auth_token;
  890. // First check X-API-Key header (direct API key)
  891. auto api_key_header = req.get_header_value("X-API-Key");
  892. if (!api_key_header.empty()) {
  893. auth_token = api_key_header;
  894. } else {
  895. // Check Authorization header
  896. auto auth_header = req.get_header_value("Authorization");
  897. if (auth_header.empty()) {
  898. return std::nullopt;
  899. }
  900. auto token = AuthService::ExtractBearerToken(auth_header);
  901. if (!token) {
  902. return std::nullopt;
  903. }
  904. auth_token = *token;
  905. }
  906. // Check if this is an API key (starts with "sk_")
  907. if (auth_token.starts_with("sk_")) {
  908. if (!apiKeyService_) {
  909. spdlog::warn("API key authentication attempted but service not available");
  910. return std::nullopt;
  911. }
  912. auto validation = apiKeyService_->ValidateApiKey(auth_token);
  913. if (!validation.valid || !validation.api_key) {
  914. spdlog::debug("API key validation failed: {}", validation.error);
  915. return std::nullopt;
  916. }
  917. // Check if key is expired
  918. if (validation.api_key->IsExpired()) {
  919. spdlog::debug("API key expired");
  920. return std::nullopt;
  921. }
  922. // Update last used timestamp (fire and forget)
  923. apiKeyService_->UpdateLastUsed(validation.api_key->id);
  924. // Build AuthUser from API key
  925. AuthUser auth_user;
  926. auth_user.user_id = validation.api_key->user_id;
  927. // Use API key permissions as groups
  928. auth_user.groups = validation.api_key->permissions;
  929. // Try to fetch additional user info
  930. if (userService_) {
  931. auto user_result = userService_->GetUser(validation.api_key->user_id);
  932. if (user_result.success && user_result.user) {
  933. auth_user.email = user_result.user->email;
  934. // Fetch workspace memberships for the user
  935. if (membershipService_) {
  936. auto memberships = membershipService_->ListUserMemberships(user_result.user->id);
  937. for (const auto& m : memberships.members) {
  938. auth_user.workspace_ids.push_back(m.workspace_id);
  939. }
  940. }
  941. } else {
  942. spdlog::debug("API key owner user not found in database: {}", validation.api_key->user_id);
  943. }
  944. }
  945. return auth_user;
  946. }
  947. // Otherwise, treat as JWT token
  948. auto validation = authService_->ValidateAccessToken(auth_token);
  949. if (!validation.valid) {
  950. spdlog::debug("Token validation failed: {}", validation.error);
  951. return std::nullopt;
  952. }
  953. // Verify the user still exists in the database
  954. // This handles cases where the database was reset or user was deleted
  955. if (userService_ && validation.user) {
  956. auto user_result = userService_->GetUser(validation.user->user_id);
  957. if (!user_result.success || !user_result.user) {
  958. spdlog::debug("Token user no longer exists in database: {}", validation.user->user_id);
  959. return std::nullopt;
  960. }
  961. }
  962. return validation.user;
  963. }
  964. // ============================================================================
  965. // User Management Routes Implementation
  966. // ============================================================================
  967. void HttpServer::SetupUserRoutes() {
  968. // POST /api/users - Create a new user (superadmin only)
  969. httpServer_->Post("/api/users", [this](const httplib::Request& req, httplib::Response& res) {
  970. HandleCreateUser(req, res);
  971. });
  972. // GET /api/users - List all users (superadmin only)
  973. httpServer_->Get("/api/users", [this](const httplib::Request& req, httplib::Response& res) {
  974. HandleListUsers(req, res);
  975. });
  976. // GET /api/users/:id - Get a specific user
  977. httpServer_->Get(R"(/api/users/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  978. HandleGetUser(req, res);
  979. });
  980. // PATCH /api/users/:id - Update a user
  981. httpServer_->Patch(R"(/api/users/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  982. HandleUpdateUser(req, res);
  983. });
  984. // DELETE /api/users/:id - Soft delete a user (superadmin only)
  985. httpServer_->Delete(R"(/api/users/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  986. HandleDeleteUser(req, res);
  987. });
  988. spdlog::info("User management routes registered: /api/users");
  989. }
  990. auto HttpServer::IsSuperadmin(const AuthUser& user) -> bool {
  991. // Delegate to authorization service for proper permission checking
  992. // This maintains backward compatibility while using the new RBAC system
  993. if (authorizationService_) {
  994. return authorizationService_->IsSuperadmin(user);
  995. }
  996. // Fallback to old behavior if authorization service not available
  997. return std::find(user.groups.begin(), user.groups.end(), "superadmin") != user.groups.end();
  998. }
  999. auto HttpServer::ResolveUserName(const std::string& user_id) -> std::string {
  1000. if (user_id.empty() || !userService_) {
  1001. return "";
  1002. }
  1003. auto result = userService_->GetUser(user_id, true);
  1004. if (result.success && result.user) {
  1005. return result.user->name;
  1006. }
  1007. return "";
  1008. }
  1009. void HttpServer::HandleCreateUser(const httplib::Request& req, httplib::Response& res) {
  1010. // Authenticate the request
  1011. auto auth_user = AuthenticateRequest(req);
  1012. if (!auth_user) {
  1013. res.status = 401;
  1014. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1015. return;
  1016. }
  1017. // Check permission to create users
  1018. if (!authorizationService_ || !authorizationService_->HasPermission(*auth_user, smartbotic::permissions::kUsersCreate)) {
  1019. res.status = 403;
  1020. res.set_content(R"({"error":"Forbidden - requires system:users:create permission"})", "application/json");
  1021. return;
  1022. }
  1023. // Check if UserService is available
  1024. if (!userService_) {
  1025. res.status = 503;
  1026. res.set_content(R"({"error":"User service not available"})", "application/json");
  1027. return;
  1028. }
  1029. try {
  1030. auto body = nlohmann::json::parse(req.body);
  1031. CreateUserRequest create_req;
  1032. create_req.actor_id = auth_user->user_id;
  1033. if (body.contains("email")) {
  1034. create_req.email = body["email"].get<std::string>();
  1035. }
  1036. if (body.contains("password")) {
  1037. create_req.password = body["password"].get<std::string>();
  1038. }
  1039. if (body.contains("name")) {
  1040. create_req.name = body["name"].get<std::string>();
  1041. }
  1042. auto result = userService_->CreateUser(create_req);
  1043. if (!result.success) {
  1044. res.status = 400;
  1045. nlohmann::json error_response = {{"error", result.error}};
  1046. res.set_content(error_response.dump(), "application/json");
  1047. return;
  1048. }
  1049. // Return created user (without password_hash)
  1050. nlohmann::json user_json = {
  1051. {"id", result.user->id},
  1052. {"email", result.user->email},
  1053. {"name", result.user->name},
  1054. {"created_at", result.user->created_at},
  1055. {"updated_at", result.user->updated_at}
  1056. };
  1057. res.status = 201;
  1058. res.set_content(user_json.dump(), "application/json");
  1059. } catch (const nlohmann::json::parse_error& e) {
  1060. res.status = 400;
  1061. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  1062. } catch (const std::exception& e) {
  1063. spdlog::error("Create user error: {}", e.what());
  1064. res.status = 500;
  1065. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1066. }
  1067. }
  1068. void HttpServer::HandleListUsers(const httplib::Request& req, httplib::Response& res) {
  1069. // Authenticate the request
  1070. auto auth_user = AuthenticateRequest(req);
  1071. if (!auth_user) {
  1072. res.status = 401;
  1073. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1074. return;
  1075. }
  1076. // Requires system:users:read permission
  1077. if (!authorizationService_->HasPermission(*auth_user, permissions::kUsersRead)) {
  1078. res.status = 403;
  1079. res.set_content(R"({"error":"Forbidden - requires system:users:read permission"})", "application/json");
  1080. return;
  1081. }
  1082. // Check if UserService is available
  1083. if (!userService_) {
  1084. res.status = 503;
  1085. res.set_content(R"({"error":"User service not available"})", "application/json");
  1086. return;
  1087. }
  1088. try {
  1089. // Parse query parameters
  1090. int limit = 100;
  1091. int offset = 0;
  1092. bool include_deleted = false;
  1093. if (req.has_param("limit")) {
  1094. limit = std::stoi(req.get_param_value("limit"));
  1095. if (limit < 1 || limit > 1000) {
  1096. limit = 100;
  1097. }
  1098. }
  1099. if (req.has_param("offset")) {
  1100. offset = std::stoi(req.get_param_value("offset"));
  1101. if (offset < 0) {
  1102. offset = 0;
  1103. }
  1104. }
  1105. if (req.has_param("include_deleted")) {
  1106. include_deleted = req.get_param_value("include_deleted") == "true";
  1107. }
  1108. auto result = userService_->ListUsers(limit, offset, include_deleted);
  1109. if (!result.success) {
  1110. res.status = 500;
  1111. nlohmann::json error_response = {{"error", result.error}};
  1112. res.set_content(error_response.dump(), "application/json");
  1113. return;
  1114. }
  1115. // Build response
  1116. nlohmann::json users_array = nlohmann::json::array();
  1117. for (const auto& user : result.users) {
  1118. nlohmann::json user_obj = {
  1119. {"id", user.id},
  1120. {"email", user.email},
  1121. {"name", user.name},
  1122. {"created_at", user.created_at},
  1123. {"updated_at", user.updated_at},
  1124. {"deleted_at", user.deleted_at},
  1125. {"created_by", user.created_by},
  1126. {"updated_by", user.updated_by},
  1127. {"created_by_name", ResolveUserName(user.created_by)},
  1128. {"updated_by_name", ResolveUserName(user.updated_by)}
  1129. };
  1130. users_array.push_back(user_obj);
  1131. }
  1132. nlohmann::json response = {
  1133. {"users", users_array},
  1134. {"total_count", result.total_count},
  1135. {"limit", limit},
  1136. {"offset", offset}
  1137. };
  1138. res.set_content(response.dump(), "application/json");
  1139. } catch (const std::exception& e) {
  1140. spdlog::error("List users error: {}", e.what());
  1141. res.status = 500;
  1142. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1143. }
  1144. }
  1145. void HttpServer::HandleGetUser(const httplib::Request& req, httplib::Response& res) {
  1146. // Authenticate the request
  1147. auto auth_user = AuthenticateRequest(req);
  1148. if (!auth_user) {
  1149. res.status = 401;
  1150. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1151. return;
  1152. }
  1153. // Check if UserService is available
  1154. if (!userService_) {
  1155. res.status = 503;
  1156. res.set_content(R"({"error":"User service not available"})", "application/json");
  1157. return;
  1158. }
  1159. try {
  1160. // Extract user ID from path
  1161. std::string user_id = req.matches[1].str();
  1162. // Users can only get their own info, or require system:users:read permission
  1163. bool is_own = (auth_user->user_id == user_id);
  1164. if (!is_own && !authorizationService_->HasPermission(*auth_user, permissions::kUsersRead)) {
  1165. res.status = 403;
  1166. res.set_content(R"({"error":"Forbidden - can only access your own user data or requires system:users:read permission"})", "application/json");
  1167. return;
  1168. }
  1169. auto result = userService_->GetUser(user_id);
  1170. if (!result.success) {
  1171. res.status = 404;
  1172. nlohmann::json error_response = {{"error", result.error}};
  1173. res.set_content(error_response.dump(), "application/json");
  1174. return;
  1175. }
  1176. // Return user (without password_hash)
  1177. nlohmann::json user_json = {
  1178. {"id", result.user->id},
  1179. {"email", result.user->email},
  1180. {"name", result.user->name},
  1181. {"created_at", result.user->created_at},
  1182. {"updated_at", result.user->updated_at}
  1183. };
  1184. res.set_content(user_json.dump(), "application/json");
  1185. } catch (const std::exception& e) {
  1186. spdlog::error("Get user error: {}", e.what());
  1187. res.status = 500;
  1188. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1189. }
  1190. }
  1191. void HttpServer::HandleUpdateUser(const httplib::Request& req, httplib::Response& res) {
  1192. // Authenticate the request
  1193. auto auth_user = AuthenticateRequest(req);
  1194. if (!auth_user) {
  1195. res.status = 401;
  1196. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1197. return;
  1198. }
  1199. // Check if UserService is available
  1200. if (!userService_) {
  1201. res.status = 503;
  1202. res.set_content(R"({"error":"User service not available"})", "application/json");
  1203. return;
  1204. }
  1205. try {
  1206. // Extract user ID from path
  1207. std::string user_id = req.matches[1].str();
  1208. // Users can only update their own info, or require system:users:update permission
  1209. bool is_own = (auth_user->user_id == user_id);
  1210. if (!is_own && !authorizationService_->HasPermission(*auth_user, permissions::kUsersUpdate)) {
  1211. res.status = 403;
  1212. res.set_content(R"({"error":"Forbidden - can only update your own user data or requires system:users:update permission"})", "application/json");
  1213. return;
  1214. }
  1215. auto body = nlohmann::json::parse(req.body);
  1216. UpdateUserRequest update_req;
  1217. update_req.actor_id = auth_user->user_id;
  1218. if (body.contains("email")) {
  1219. update_req.email = body["email"].get<std::string>();
  1220. }
  1221. if (body.contains("password")) {
  1222. update_req.password = body["password"].get<std::string>();
  1223. }
  1224. if (body.contains("name")) {
  1225. update_req.name = body["name"].get<std::string>();
  1226. }
  1227. auto result = userService_->UpdateUser(user_id, update_req);
  1228. if (!result.success) {
  1229. res.status = 400;
  1230. nlohmann::json error_response = {{"error", result.error}};
  1231. res.set_content(error_response.dump(), "application/json");
  1232. return;
  1233. }
  1234. // Return updated user (without password_hash)
  1235. nlohmann::json user_json = {
  1236. {"id", result.user->id},
  1237. {"email", result.user->email},
  1238. {"name", result.user->name},
  1239. {"created_at", result.user->created_at},
  1240. {"updated_at", result.user->updated_at}
  1241. };
  1242. res.set_content(user_json.dump(), "application/json");
  1243. } catch (const nlohmann::json::parse_error& e) {
  1244. res.status = 400;
  1245. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  1246. } catch (const std::exception& e) {
  1247. spdlog::error("Update user error: {}", e.what());
  1248. res.status = 500;
  1249. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1250. }
  1251. }
  1252. void HttpServer::HandleDeleteUser(const httplib::Request& req, httplib::Response& res) {
  1253. // Authenticate the request
  1254. auto auth_user = AuthenticateRequest(req);
  1255. if (!auth_user) {
  1256. res.status = 401;
  1257. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1258. return;
  1259. }
  1260. // Requires system:users:delete permission
  1261. if (!authorizationService_->HasPermission(*auth_user, permissions::kUsersDelete)) {
  1262. res.status = 403;
  1263. res.set_content(R"({"error":"Forbidden - requires system:users:delete permission"})", "application/json");
  1264. return;
  1265. }
  1266. // Check if UserService is available
  1267. if (!userService_) {
  1268. res.status = 503;
  1269. res.set_content(R"({"error":"User service not available"})", "application/json");
  1270. return;
  1271. }
  1272. try {
  1273. // Extract user ID from path
  1274. std::string user_id = req.matches[1].str();
  1275. auto result = userService_->DeleteUser(user_id);
  1276. if (!result.success) {
  1277. res.status = 404;
  1278. nlohmann::json error_response = {{"error", result.error}};
  1279. res.set_content(error_response.dump(), "application/json");
  1280. return;
  1281. }
  1282. res.set_content(R"({"message":"User deleted successfully"})", "application/json");
  1283. } catch (const std::exception& e) {
  1284. spdlog::error("Delete user error: {}", e.what());
  1285. res.status = 500;
  1286. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1287. }
  1288. }
  1289. // ============================================================================
  1290. // Workspace Management Routes Implementation
  1291. // ============================================================================
  1292. void HttpServer::SetupWorkspaceRoutes() {
  1293. // POST /api/workspaces - Create a new workspace (superadmin only)
  1294. httpServer_->Post("/api/workspaces", [this](const httplib::Request& req, httplib::Response& res) {
  1295. HandleCreateWorkspace(req, res);
  1296. });
  1297. // GET /api/workspaces - List workspaces (filtered by user membership for non-superadmin)
  1298. httpServer_->Get("/api/workspaces", [this](const httplib::Request& req, httplib::Response& res) {
  1299. HandleListWorkspaces(req, res);
  1300. });
  1301. // GET /api/workspaces/:id - Get a specific workspace
  1302. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1303. HandleGetWorkspace(req, res);
  1304. });
  1305. // PATCH /api/workspaces/:id - Update a workspace
  1306. httpServer_->Patch(R"(/api/workspaces/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1307. HandleUpdateWorkspace(req, res);
  1308. });
  1309. // DELETE /api/workspaces/:id - Soft delete a workspace (superadmin only)
  1310. httpServer_->Delete(R"(/api/workspaces/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1311. HandleDeleteWorkspace(req, res);
  1312. });
  1313. spdlog::info("Workspace management routes registered: /api/workspaces");
  1314. }
  1315. void HttpServer::HandleCreateWorkspace(const httplib::Request& req, httplib::Response& res) {
  1316. // Authenticate the request
  1317. auto auth_user = AuthenticateRequest(req);
  1318. if (!auth_user) {
  1319. res.status = 401;
  1320. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1321. return;
  1322. }
  1323. // Requires system:workspaces:create permission
  1324. if (!authorizationService_->HasPermission(*auth_user, permissions::kWorkspacesCreate)) {
  1325. res.status = 403;
  1326. res.set_content(R"({"error":"Forbidden - requires system:workspaces:create permission"})", "application/json");
  1327. return;
  1328. }
  1329. // Check if WorkspaceService is available
  1330. if (!workspaceService_) {
  1331. res.status = 503;
  1332. res.set_content(R"({"error":"Workspace service not available"})", "application/json");
  1333. return;
  1334. }
  1335. try {
  1336. auto body = nlohmann::json::parse(req.body);
  1337. CreateWorkspaceRequest create_req;
  1338. create_req.actor_id = auth_user->user_id;
  1339. if (body.contains("name")) {
  1340. create_req.name = body["name"].get<std::string>();
  1341. }
  1342. if (body.contains("settings")) {
  1343. create_req.settings = body["settings"];
  1344. }
  1345. auto result = workspaceService_->CreateWorkspace(create_req);
  1346. if (!result.success) {
  1347. res.status = 400;
  1348. nlohmann::json error_response = {{"error", result.error}};
  1349. res.set_content(error_response.dump(), "application/json");
  1350. return;
  1351. }
  1352. // Return created workspace
  1353. nlohmann::json workspace_json = {
  1354. {"id", result.workspace->id},
  1355. {"name", result.workspace->name},
  1356. {"settings", result.workspace->settings},
  1357. {"created_at", result.workspace->created_at},
  1358. {"updated_at", result.workspace->updated_at}
  1359. };
  1360. res.status = 201;
  1361. res.set_content(workspace_json.dump(), "application/json");
  1362. } catch (const nlohmann::json::parse_error& e) {
  1363. res.status = 400;
  1364. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  1365. } catch (const std::exception& e) {
  1366. spdlog::error("Create workspace error: {}", e.what());
  1367. res.status = 500;
  1368. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1369. }
  1370. }
  1371. void HttpServer::HandleListWorkspaces(const httplib::Request& req, httplib::Response& res) {
  1372. // Authenticate the request
  1373. auto auth_user = AuthenticateRequest(req);
  1374. if (!auth_user) {
  1375. res.status = 401;
  1376. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1377. return;
  1378. }
  1379. // Check if WorkspaceService is available
  1380. if (!workspaceService_) {
  1381. res.status = 503;
  1382. res.set_content(R"({"error":"Workspace service not available"})", "application/json");
  1383. return;
  1384. }
  1385. try {
  1386. WorkspaceListResult result;
  1387. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kWorkspacesRead);
  1388. // Users with system:workspaces:read can see all workspaces, others only see their memberships
  1389. if (has_system_access) {
  1390. // Parse query parameters
  1391. int limit = 100;
  1392. int offset = 0;
  1393. bool include_deleted = false;
  1394. if (req.has_param("limit")) {
  1395. limit = std::stoi(req.get_param_value("limit"));
  1396. if (limit < 1 || limit > 1000) {
  1397. limit = 100;
  1398. }
  1399. }
  1400. if (req.has_param("offset")) {
  1401. offset = std::stoi(req.get_param_value("offset"));
  1402. if (offset < 0) {
  1403. offset = 0;
  1404. }
  1405. }
  1406. if (req.has_param("include_deleted")) {
  1407. include_deleted = req.get_param_value("include_deleted") == "true";
  1408. }
  1409. result = workspaceService_->ListWorkspaces(limit, offset, include_deleted);
  1410. } else {
  1411. // Non-privileged user: filter by user's workspace memberships
  1412. result = workspaceService_->ListWorkspacesByIds(auth_user->workspace_ids, false);
  1413. }
  1414. if (!result.success) {
  1415. res.status = 500;
  1416. nlohmann::json error_response = {{"error", result.error}};
  1417. res.set_content(error_response.dump(), "application/json");
  1418. return;
  1419. }
  1420. // Build response
  1421. nlohmann::json workspaces_array = nlohmann::json::array();
  1422. for (const auto& workspace : result.workspaces) {
  1423. nlohmann::json ws_json = {
  1424. {"id", workspace.id},
  1425. {"name", workspace.name},
  1426. {"settings", workspace.settings},
  1427. {"created_at", workspace.created_at},
  1428. {"updated_at", workspace.updated_at},
  1429. {"created_by", workspace.created_by},
  1430. {"updated_by", workspace.updated_by},
  1431. {"created_by_name", ResolveUserName(workspace.created_by)},
  1432. {"updated_by_name", ResolveUserName(workspace.updated_by)}
  1433. };
  1434. if (has_system_access) {
  1435. ws_json["deleted_at"] = workspace.deleted_at;
  1436. }
  1437. workspaces_array.push_back(ws_json);
  1438. }
  1439. nlohmann::json response = {
  1440. {"workspaces", workspaces_array},
  1441. {"total_count", result.total_count}
  1442. };
  1443. res.set_content(response.dump(), "application/json");
  1444. } catch (const std::exception& e) {
  1445. spdlog::error("List workspaces error: {}", e.what());
  1446. res.status = 500;
  1447. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1448. }
  1449. }
  1450. void HttpServer::HandleGetWorkspace(const httplib::Request& req, httplib::Response& res) {
  1451. // Authenticate the request
  1452. auto auth_user = AuthenticateRequest(req);
  1453. if (!auth_user) {
  1454. res.status = 401;
  1455. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1456. return;
  1457. }
  1458. // Check if WorkspaceService is available
  1459. if (!workspaceService_) {
  1460. res.status = 503;
  1461. res.set_content(R"({"error":"Workspace service not available"})", "application/json");
  1462. return;
  1463. }
  1464. try {
  1465. // Extract workspace ID from path
  1466. std::string workspace_id = req.matches[1].str();
  1467. // Check access: must be member OR have system:workspaces:read permission
  1468. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  1469. auth_user->workspace_ids.end(),
  1470. workspace_id) != auth_user->workspace_ids.end());
  1471. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kWorkspacesRead);
  1472. if (!is_member && !has_system_access) {
  1473. res.status = 403;
  1474. res.set_content(R"({"error":"Forbidden - not a member of this workspace"})", "application/json");
  1475. return;
  1476. }
  1477. auto result = workspaceService_->GetWorkspace(workspace_id);
  1478. if (!result.success) {
  1479. res.status = 404;
  1480. nlohmann::json error_response = {{"error", result.error}};
  1481. res.set_content(error_response.dump(), "application/json");
  1482. return;
  1483. }
  1484. // Return workspace
  1485. nlohmann::json workspace_json = {
  1486. {"id", result.workspace->id},
  1487. {"name", result.workspace->name},
  1488. {"settings", result.workspace->settings},
  1489. {"created_at", result.workspace->created_at},
  1490. {"updated_at", result.workspace->updated_at}
  1491. };
  1492. res.set_content(workspace_json.dump(), "application/json");
  1493. } catch (const std::exception& e) {
  1494. spdlog::error("Get workspace error: {}", e.what());
  1495. res.status = 500;
  1496. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1497. }
  1498. }
  1499. void HttpServer::HandleUpdateWorkspace(const httplib::Request& req, httplib::Response& res) {
  1500. // Authenticate the request
  1501. auto auth_user = AuthenticateRequest(req);
  1502. if (!auth_user) {
  1503. res.status = 401;
  1504. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1505. return;
  1506. }
  1507. // Extract workspace ID from path (needed for IsWorkspaceAdmin check)
  1508. std::string workspace_id = req.matches[1].str();
  1509. // Requires system:workspaces:update permission OR workspace admin
  1510. bool can_update = authorizationService_->HasPermission(*auth_user, permissions::kWorkspacesUpdate) ||
  1511. authorizationService_->IsWorkspaceAdmin(*auth_user, workspace_id);
  1512. if (!can_update) {
  1513. res.status = 403;
  1514. res.set_content(R"({"error":"Forbidden - requires system:workspaces:update permission or workspace admin"})", "application/json");
  1515. return;
  1516. }
  1517. // Check if WorkspaceService is available
  1518. if (!workspaceService_) {
  1519. res.status = 503;
  1520. res.set_content(R"({"error":"Workspace service not available"})", "application/json");
  1521. return;
  1522. }
  1523. try {
  1524. auto body = nlohmann::json::parse(req.body);
  1525. UpdateWorkspaceRequest update_req;
  1526. update_req.actor_id = auth_user->user_id;
  1527. if (body.contains("name")) {
  1528. update_req.name = body["name"].get<std::string>();
  1529. }
  1530. if (body.contains("settings")) {
  1531. update_req.settings = body["settings"];
  1532. }
  1533. auto result = workspaceService_->UpdateWorkspace(workspace_id, update_req);
  1534. if (!result.success) {
  1535. res.status = 400;
  1536. nlohmann::json error_response = {{"error", result.error}};
  1537. res.set_content(error_response.dump(), "application/json");
  1538. return;
  1539. }
  1540. // Return updated workspace
  1541. nlohmann::json workspace_json = {
  1542. {"id", result.workspace->id},
  1543. {"name", result.workspace->name},
  1544. {"settings", result.workspace->settings},
  1545. {"created_at", result.workspace->created_at},
  1546. {"updated_at", result.workspace->updated_at}
  1547. };
  1548. res.set_content(workspace_json.dump(), "application/json");
  1549. } catch (const nlohmann::json::parse_error& e) {
  1550. res.status = 400;
  1551. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  1552. } catch (const std::exception& e) {
  1553. spdlog::error("Update workspace error: {}", e.what());
  1554. res.status = 500;
  1555. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1556. }
  1557. }
  1558. void HttpServer::HandleDeleteWorkspace(const httplib::Request& req, httplib::Response& res) {
  1559. // Authenticate the request
  1560. auto auth_user = AuthenticateRequest(req);
  1561. if (!auth_user) {
  1562. res.status = 401;
  1563. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1564. return;
  1565. }
  1566. // Requires system:workspaces:delete permission
  1567. if (!authorizationService_->HasPermission(*auth_user, permissions::kWorkspacesDelete)) {
  1568. res.status = 403;
  1569. res.set_content(R"({"error":"Forbidden - requires system:workspaces:delete permission"})", "application/json");
  1570. return;
  1571. }
  1572. // Check if WorkspaceService is available
  1573. if (!workspaceService_) {
  1574. res.status = 503;
  1575. res.set_content(R"({"error":"Workspace service not available"})", "application/json");
  1576. return;
  1577. }
  1578. try {
  1579. // Extract workspace ID from path
  1580. std::string workspace_id = req.matches[1].str();
  1581. auto result = workspaceService_->DeleteWorkspace(workspace_id);
  1582. if (!result.success) {
  1583. res.status = 404;
  1584. nlohmann::json error_response = {{"error", result.error}};
  1585. res.set_content(error_response.dump(), "application/json");
  1586. return;
  1587. }
  1588. res.set_content(R"({"message":"Workspace deleted successfully"})", "application/json");
  1589. } catch (const std::exception& e) {
  1590. spdlog::error("Delete workspace error: {}", e.what());
  1591. res.status = 500;
  1592. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1593. }
  1594. }
  1595. // ============================================================================
  1596. // Group Management Routes Implementation
  1597. // ============================================================================
  1598. void HttpServer::SetupGroupRoutes() {
  1599. // POST /api/workspaces/:wid/groups - Create a new group in workspace
  1600. httpServer_->Post(R"(/api/workspaces/([a-zA-Z0-9\-]+)/groups)", [this](const httplib::Request& req, httplib::Response& res) {
  1601. HandleCreateGroup(req, res);
  1602. });
  1603. // GET /api/workspaces/:wid/groups - List groups in workspace
  1604. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+)/groups)", [this](const httplib::Request& req, httplib::Response& res) {
  1605. HandleListGroups(req, res);
  1606. });
  1607. // GET /api/workspaces/:wid/groups/:id - Get a specific group
  1608. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+)/groups/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1609. HandleGetGroup(req, res);
  1610. });
  1611. // PATCH /api/workspaces/:wid/groups/:id - Update a group
  1612. httpServer_->Patch(R"(/api/workspaces/([a-zA-Z0-9\-]+)/groups/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1613. HandleUpdateGroup(req, res);
  1614. });
  1615. // DELETE /api/workspaces/:wid/groups/:id - Delete a group
  1616. httpServer_->Delete(R"(/api/workspaces/([a-zA-Z0-9\-]+)/groups/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1617. HandleDeleteGroup(req, res);
  1618. });
  1619. spdlog::info("Group management routes registered: /api/workspaces/:wid/groups");
  1620. }
  1621. void HttpServer::HandleCreateGroup(const httplib::Request& req, httplib::Response& res) {
  1622. // Authenticate the request
  1623. auto auth_user = AuthenticateRequest(req);
  1624. if (!auth_user) {
  1625. res.status = 401;
  1626. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1627. return;
  1628. }
  1629. // Extract workspace ID from path
  1630. std::string workspace_id = req.matches[1].str();
  1631. // Requires system:groups:create permission OR workspace group management permission
  1632. bool can_create = authorizationService_->HasPermission(*auth_user, permissions::kGroupsCreate) ||
  1633. authorizationService_->CanManageWorkspaceGroups(*auth_user, workspace_id);
  1634. if (!can_create) {
  1635. res.status = 403;
  1636. res.set_content(R"({"error":"Forbidden - requires system:groups:create permission or workspace group management"})", "application/json");
  1637. return;
  1638. }
  1639. // Check if GroupService is available
  1640. if (!groupService_) {
  1641. res.status = 503;
  1642. res.set_content(R"({"error":"Group service not available"})", "application/json");
  1643. return;
  1644. }
  1645. try {
  1646. auto body = nlohmann::json::parse(req.body);
  1647. CreateGroupRequest create_req;
  1648. create_req.workspace_id = workspace_id;
  1649. create_req.actor_id = auth_user->user_id;
  1650. if (body.contains("name")) {
  1651. create_req.name = body["name"].get<std::string>();
  1652. }
  1653. if (body.contains("permissions") && body["permissions"].is_array()) {
  1654. for (const auto& perm : body["permissions"]) {
  1655. if (perm.is_string()) {
  1656. create_req.permissions.push_back(perm.get<std::string>());
  1657. }
  1658. }
  1659. }
  1660. auto result = groupService_->CreateGroup(create_req);
  1661. if (!result.success) {
  1662. res.status = 400;
  1663. nlohmann::json error_response = {{"error", result.error}};
  1664. res.set_content(error_response.dump(), "application/json");
  1665. return;
  1666. }
  1667. // Return created group
  1668. nlohmann::json group_json = {
  1669. {"id", result.group->id},
  1670. {"workspace_id", result.group->workspace_id},
  1671. {"name", result.group->name},
  1672. {"permissions", result.group->permissions},
  1673. {"created_at", result.group->created_at},
  1674. {"updated_at", result.group->updated_at}
  1675. };
  1676. res.status = 201;
  1677. res.set_content(group_json.dump(), "application/json");
  1678. } catch (const nlohmann::json::parse_error& e) {
  1679. res.status = 400;
  1680. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  1681. } catch (const std::exception& e) {
  1682. spdlog::error("Create group error: {}", e.what());
  1683. res.status = 500;
  1684. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1685. }
  1686. }
  1687. void HttpServer::HandleListGroups(const httplib::Request& req, httplib::Response& res) {
  1688. // Authenticate the request
  1689. auto auth_user = AuthenticateRequest(req);
  1690. if (!auth_user) {
  1691. res.status = 401;
  1692. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1693. return;
  1694. }
  1695. // Extract workspace ID from path
  1696. std::string workspace_id = req.matches[1].str();
  1697. // Check access: must be member OR have system:groups:read permission
  1698. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  1699. auth_user->workspace_ids.end(),
  1700. workspace_id) != auth_user->workspace_ids.end());
  1701. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kGroupsRead);
  1702. if (!is_member && !has_system_access) {
  1703. res.status = 403;
  1704. res.set_content(R"({"error":"Forbidden - not a member of this workspace"})", "application/json");
  1705. return;
  1706. }
  1707. // Check if GroupService is available
  1708. if (!groupService_) {
  1709. res.status = 503;
  1710. res.set_content(R"({"error":"Group service not available"})", "application/json");
  1711. return;
  1712. }
  1713. try {
  1714. // Parse query parameters
  1715. int limit = 100;
  1716. int offset = 0;
  1717. bool include_deleted = false;
  1718. if (req.has_param("limit")) {
  1719. limit = std::stoi(req.get_param_value("limit"));
  1720. if (limit < 1 || limit > 1000) {
  1721. limit = 100;
  1722. }
  1723. }
  1724. if (req.has_param("offset")) {
  1725. offset = std::stoi(req.get_param_value("offset"));
  1726. if (offset < 0) {
  1727. offset = 0;
  1728. }
  1729. }
  1730. if (has_system_access && req.has_param("include_deleted")) {
  1731. include_deleted = req.get_param_value("include_deleted") == "true";
  1732. }
  1733. bool include_system = has_system_access &&
  1734. req.has_param("include_system") &&
  1735. req.get_param_value("include_system") == "true";
  1736. auto result = groupService_->ListGroups(workspace_id, limit, offset, include_deleted);
  1737. if (!result.success) {
  1738. res.status = 500;
  1739. nlohmann::json error_response = {{"error", result.error}};
  1740. res.set_content(error_response.dump(), "application/json");
  1741. return;
  1742. }
  1743. // Build response
  1744. nlohmann::json groups_array = nlohmann::json::array();
  1745. // Add global system groups first if requested
  1746. if (include_system) {
  1747. auto global_result = groupService_->ListSystemGroups();
  1748. if (global_result.success) {
  1749. for (const auto& group : global_result.groups) {
  1750. nlohmann::json grp_json = {
  1751. {"id", group.id},
  1752. {"workspace_id", group.workspace_id},
  1753. {"name", group.name},
  1754. {"permissions", group.permissions},
  1755. {"is_system", group.is_system},
  1756. {"parent_group_id", group.parent_group_id},
  1757. {"created_at", group.created_at},
  1758. {"updated_at", group.updated_at},
  1759. {"deleted_at", group.deleted_at},
  1760. {"created_by", group.created_by},
  1761. {"updated_by", group.updated_by},
  1762. {"created_by_name", ResolveUserName(group.created_by)},
  1763. {"updated_by_name", ResolveUserName(group.updated_by)}
  1764. };
  1765. groups_array.push_back(grp_json);
  1766. }
  1767. }
  1768. }
  1769. for (const auto& group : result.groups) {
  1770. nlohmann::json grp_json = {
  1771. {"id", group.id},
  1772. {"workspace_id", group.workspace_id},
  1773. {"name", group.name},
  1774. {"permissions", group.permissions},
  1775. {"is_system", group.is_system},
  1776. {"parent_group_id", group.parent_group_id},
  1777. {"created_at", group.created_at},
  1778. {"updated_at", group.updated_at},
  1779. {"created_by", group.created_by},
  1780. {"updated_by", group.updated_by},
  1781. {"created_by_name", ResolveUserName(group.created_by)},
  1782. {"updated_by_name", ResolveUserName(group.updated_by)}
  1783. };
  1784. if (has_system_access) {
  1785. grp_json["deleted_at"] = group.deleted_at;
  1786. }
  1787. groups_array.push_back(grp_json);
  1788. }
  1789. nlohmann::json response = {
  1790. {"groups", groups_array},
  1791. {"total_count", result.total_count}
  1792. };
  1793. res.set_content(response.dump(), "application/json");
  1794. } catch (const std::exception& e) {
  1795. spdlog::error("List groups error: {}", e.what());
  1796. res.status = 500;
  1797. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1798. }
  1799. }
  1800. void HttpServer::HandleGetGroup(const httplib::Request& req, httplib::Response& res) {
  1801. // Authenticate the request
  1802. auto auth_user = AuthenticateRequest(req);
  1803. if (!auth_user) {
  1804. res.status = 401;
  1805. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1806. return;
  1807. }
  1808. // Extract workspace ID and group ID from path
  1809. std::string workspace_id = req.matches[1].str();
  1810. std::string group_id = req.matches[2].str();
  1811. // Check access: must be member OR have system:groups:read permission
  1812. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  1813. auth_user->workspace_ids.end(),
  1814. workspace_id) != auth_user->workspace_ids.end());
  1815. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kGroupsRead);
  1816. if (!is_member && !has_system_access) {
  1817. res.status = 403;
  1818. res.set_content(R"({"error":"Forbidden - not a member of this workspace"})", "application/json");
  1819. return;
  1820. }
  1821. // Check if GroupService is available
  1822. if (!groupService_) {
  1823. res.status = 503;
  1824. res.set_content(R"({"error":"Group service not available"})", "application/json");
  1825. return;
  1826. }
  1827. try {
  1828. auto result = groupService_->GetGroup(group_id);
  1829. if (!result.success) {
  1830. res.status = 404;
  1831. nlohmann::json error_response = {{"error", result.error}};
  1832. res.set_content(error_response.dump(), "application/json");
  1833. return;
  1834. }
  1835. // Verify group belongs to the workspace
  1836. if (result.group->workspace_id != workspace_id) {
  1837. res.status = 404;
  1838. res.set_content(R"({"error":"Group not found in this workspace"})", "application/json");
  1839. return;
  1840. }
  1841. // Return group
  1842. nlohmann::json group_json = {
  1843. {"id", result.group->id},
  1844. {"workspace_id", result.group->workspace_id},
  1845. {"name", result.group->name},
  1846. {"permissions", result.group->permissions},
  1847. {"created_at", result.group->created_at},
  1848. {"updated_at", result.group->updated_at}
  1849. };
  1850. res.set_content(group_json.dump(), "application/json");
  1851. } catch (const std::exception& e) {
  1852. spdlog::error("Get group error: {}", e.what());
  1853. res.status = 500;
  1854. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1855. }
  1856. }
  1857. void HttpServer::HandleUpdateGroup(const httplib::Request& req, httplib::Response& res) {
  1858. // Authenticate the request
  1859. auto auth_user = AuthenticateRequest(req);
  1860. if (!auth_user) {
  1861. res.status = 401;
  1862. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1863. return;
  1864. }
  1865. // Extract workspace ID and group ID from path
  1866. std::string workspace_id = req.matches[1].str();
  1867. std::string group_id = req.matches[2].str();
  1868. // Requires system:groups:update permission OR workspace group management permission
  1869. bool can_update = authorizationService_->HasPermission(*auth_user, permissions::kGroupsUpdate) ||
  1870. authorizationService_->CanManageWorkspaceGroups(*auth_user, workspace_id);
  1871. if (!can_update) {
  1872. res.status = 403;
  1873. res.set_content(R"({"error":"Forbidden - requires system:groups:update permission or workspace group management"})", "application/json");
  1874. return;
  1875. }
  1876. // Check if GroupService is available
  1877. if (!groupService_) {
  1878. res.status = 503;
  1879. res.set_content(R"({"error":"Group service not available"})", "application/json");
  1880. return;
  1881. }
  1882. try {
  1883. // First verify group belongs to the workspace
  1884. auto existing = groupService_->GetGroup(group_id);
  1885. if (!existing.success) {
  1886. res.status = 404;
  1887. nlohmann::json error_response = {{"error", existing.error}};
  1888. res.set_content(error_response.dump(), "application/json");
  1889. return;
  1890. }
  1891. if (existing.group->workspace_id != workspace_id) {
  1892. res.status = 404;
  1893. res.set_content(R"({"error":"Group not found in this workspace"})", "application/json");
  1894. return;
  1895. }
  1896. auto body = nlohmann::json::parse(req.body);
  1897. UpdateGroupRequest update_req;
  1898. update_req.actor_id = auth_user->user_id;
  1899. if (body.contains("name")) {
  1900. update_req.name = body["name"].get<std::string>();
  1901. }
  1902. if (body.contains("permissions") && body["permissions"].is_array()) {
  1903. std::vector<std::string> perms;
  1904. for (const auto& perm : body["permissions"]) {
  1905. if (perm.is_string()) {
  1906. perms.push_back(perm.get<std::string>());
  1907. }
  1908. }
  1909. update_req.permissions = perms;
  1910. }
  1911. auto result = groupService_->UpdateGroup(group_id, update_req);
  1912. if (!result.success) {
  1913. res.status = 400;
  1914. nlohmann::json error_response = {{"error", result.error}};
  1915. res.set_content(error_response.dump(), "application/json");
  1916. return;
  1917. }
  1918. // Return updated group
  1919. nlohmann::json group_json = {
  1920. {"id", result.group->id},
  1921. {"workspace_id", result.group->workspace_id},
  1922. {"name", result.group->name},
  1923. {"permissions", result.group->permissions},
  1924. {"created_at", result.group->created_at},
  1925. {"updated_at", result.group->updated_at}
  1926. };
  1927. res.set_content(group_json.dump(), "application/json");
  1928. } catch (const nlohmann::json::parse_error& e) {
  1929. res.status = 400;
  1930. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  1931. } catch (const std::exception& e) {
  1932. spdlog::error("Update group error: {}", e.what());
  1933. res.status = 500;
  1934. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1935. }
  1936. }
  1937. void HttpServer::HandleDeleteGroup(const httplib::Request& req, httplib::Response& res) {
  1938. // Authenticate the request
  1939. auto auth_user = AuthenticateRequest(req);
  1940. if (!auth_user) {
  1941. res.status = 401;
  1942. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1943. return;
  1944. }
  1945. // Extract workspace ID and group ID from path
  1946. std::string workspace_id = req.matches[1].str();
  1947. std::string group_id = req.matches[2].str();
  1948. // Requires system:groups:delete permission OR workspace group management permission
  1949. bool can_delete = authorizationService_->HasPermission(*auth_user, permissions::kGroupsDelete) ||
  1950. authorizationService_->CanManageWorkspaceGroups(*auth_user, workspace_id);
  1951. if (!can_delete) {
  1952. res.status = 403;
  1953. res.set_content(R"({"error":"Forbidden - requires system:groups:delete permission or workspace group management"})", "application/json");
  1954. return;
  1955. }
  1956. // Check if GroupService is available
  1957. if (!groupService_) {
  1958. res.status = 503;
  1959. res.set_content(R"({"error":"Group service not available"})", "application/json");
  1960. return;
  1961. }
  1962. try {
  1963. // First verify group belongs to the workspace
  1964. auto existing = groupService_->GetGroup(group_id);
  1965. if (!existing.success) {
  1966. res.status = 404;
  1967. nlohmann::json error_response = {{"error", existing.error}};
  1968. res.set_content(error_response.dump(), "application/json");
  1969. return;
  1970. }
  1971. if (existing.group->workspace_id != workspace_id) {
  1972. res.status = 404;
  1973. res.set_content(R"({"error":"Group not found in this workspace"})", "application/json");
  1974. return;
  1975. }
  1976. auto result = groupService_->DeleteGroup(group_id);
  1977. if (!result.success) {
  1978. res.status = 400;
  1979. nlohmann::json error_response = {{"error", result.error}};
  1980. res.set_content(error_response.dump(), "application/json");
  1981. return;
  1982. }
  1983. res.set_content(R"({"message":"Group deleted successfully"})", "application/json");
  1984. } catch (const std::exception& e) {
  1985. spdlog::error("Delete group error: {}", e.what());
  1986. res.status = 500;
  1987. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1988. }
  1989. }
  1990. // ============================================================================
  1991. // Membership Routes
  1992. // ============================================================================
  1993. void HttpServer::SetupMembershipRoutes() {
  1994. // POST /api/workspaces/:wid/members - Add a user to workspace
  1995. httpServer_->Post(R"(/api/workspaces/([a-zA-Z0-9\-]+)/members)", [this](const httplib::Request& req, httplib::Response& res) {
  1996. HandleAddMember(req, res);
  1997. });
  1998. // GET /api/workspaces/:wid/members - List members in workspace
  1999. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+)/members)", [this](const httplib::Request& req, httplib::Response& res) {
  2000. HandleListMembers(req, res);
  2001. });
  2002. // GET /api/workspaces/:wid/members/:userId - Get a specific member
  2003. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+)/members/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  2004. HandleGetMember(req, res);
  2005. });
  2006. // PUT /api/workspaces/:wid/members/:userId - Update user's groups in workspace
  2007. httpServer_->Put(R"(/api/workspaces/([a-zA-Z0-9\-]+)/members/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  2008. HandleUpdateMember(req, res);
  2009. });
  2010. // DELETE /api/workspaces/:wid/members/:userId - Remove user from workspace
  2011. httpServer_->Delete(R"(/api/workspaces/([a-zA-Z0-9\-]+)/members/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  2012. HandleRemoveMember(req, res);
  2013. });
  2014. spdlog::info("Membership routes registered: /api/workspaces/:wid/members");
  2015. }
  2016. void HttpServer::HandleAddMember(const httplib::Request& req, httplib::Response& res) {
  2017. // Authenticate the request
  2018. auto auth_user = AuthenticateRequest(req);
  2019. if (!auth_user) {
  2020. res.status = 401;
  2021. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2022. return;
  2023. }
  2024. // Extract workspace ID from path
  2025. std::string workspace_id = req.matches[1].str();
  2026. // Requires system:memberships:create permission OR workspace member management permission
  2027. bool can_add = authorizationService_->HasPermission(*auth_user, permissions::kMembershipsCreate) ||
  2028. authorizationService_->CanManageWorkspaceMembers(*auth_user, workspace_id);
  2029. if (!can_add) {
  2030. res.status = 403;
  2031. res.set_content(R"({"error":"Forbidden - requires system:memberships:create permission or workspace member management"})", "application/json");
  2032. return;
  2033. }
  2034. // Check if MembershipService is available
  2035. if (!membershipService_) {
  2036. res.status = 503;
  2037. res.set_content(R"({"error":"Membership service not available"})", "application/json");
  2038. return;
  2039. }
  2040. try {
  2041. // Parse request body
  2042. auto json = nlohmann::json::parse(req.body);
  2043. AddMemberRequest add_req;
  2044. add_req.workspace_id = workspace_id;
  2045. if (json.contains("user_id") && json["user_id"].is_string()) {
  2046. add_req.user_id = json["user_id"].get<std::string>();
  2047. } else {
  2048. res.status = 400;
  2049. res.set_content(R"({"error":"user_id is required"})", "application/json");
  2050. return;
  2051. }
  2052. if (json.contains("group_ids") && json["group_ids"].is_array()) {
  2053. for (const auto& item : json["group_ids"]) {
  2054. if (item.is_string()) {
  2055. add_req.group_ids.push_back(item.get<std::string>());
  2056. }
  2057. }
  2058. }
  2059. auto result = membershipService_->AddMember(add_req);
  2060. if (!result.success) {
  2061. res.status = 400;
  2062. nlohmann::json error_response = {{"error", result.error}};
  2063. res.set_content(error_response.dump(), "application/json");
  2064. return;
  2065. }
  2066. // Return created membership
  2067. nlohmann::json member_json = {
  2068. {"id", result.member->id},
  2069. {"workspace_id", result.member->workspace_id},
  2070. {"user_id", result.member->user_id},
  2071. {"group_ids", result.member->group_ids},
  2072. {"created_at", result.member->created_at},
  2073. {"updated_at", result.member->updated_at}
  2074. };
  2075. res.status = 201;
  2076. res.set_content(member_json.dump(), "application/json");
  2077. } catch (const nlohmann::json::exception& e) {
  2078. res.status = 400;
  2079. nlohmann::json error_response = {{"error", "Invalid JSON: " + std::string(e.what())}};
  2080. res.set_content(error_response.dump(), "application/json");
  2081. } catch (const std::exception& e) {
  2082. spdlog::error("Add member error: {}", e.what());
  2083. res.status = 500;
  2084. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2085. }
  2086. }
  2087. void HttpServer::HandleListMembers(const httplib::Request& req, httplib::Response& res) {
  2088. // Authenticate the request
  2089. auto auth_user = AuthenticateRequest(req);
  2090. if (!auth_user) {
  2091. res.status = 401;
  2092. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2093. return;
  2094. }
  2095. // Extract workspace ID from path
  2096. std::string workspace_id = req.matches[1].str();
  2097. // Check access: must be member OR have system:memberships:read permission
  2098. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  2099. auth_user->workspace_ids.end(),
  2100. workspace_id) != auth_user->workspace_ids.end());
  2101. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kMembershipsRead);
  2102. if (!is_member && !has_system_access) {
  2103. res.status = 403;
  2104. res.set_content(R"({"error":"Forbidden - not a member of this workspace"})", "application/json");
  2105. return;
  2106. }
  2107. // Check if MembershipService is available
  2108. if (!membershipService_) {
  2109. res.status = 503;
  2110. res.set_content(R"({"error":"Membership service not available"})", "application/json");
  2111. return;
  2112. }
  2113. try {
  2114. // Get query parameters
  2115. int limit = 100;
  2116. int offset = 0;
  2117. bool include_deleted = false;
  2118. if (req.has_param("limit")) {
  2119. limit = std::stoi(req.get_param_value("limit"));
  2120. if (limit < 1 || limit > 1000) {
  2121. limit = 100;
  2122. }
  2123. }
  2124. if (req.has_param("offset")) {
  2125. offset = std::stoi(req.get_param_value("offset"));
  2126. if (offset < 0) {
  2127. offset = 0;
  2128. }
  2129. }
  2130. if (has_system_access && req.has_param("include_deleted")) {
  2131. include_deleted = req.get_param_value("include_deleted") == "true";
  2132. }
  2133. auto result = membershipService_->ListMembers(workspace_id, limit, offset, include_deleted);
  2134. if (!result.success) {
  2135. res.status = 500;
  2136. nlohmann::json error_response = {{"error", result.error}};
  2137. res.set_content(error_response.dump(), "application/json");
  2138. return;
  2139. }
  2140. // Build response with user details
  2141. nlohmann::json members_array = nlohmann::json::array();
  2142. for (const auto& member : result.members) {
  2143. nlohmann::json member_json = {
  2144. {"id", member.id},
  2145. {"workspace_id", member.workspace_id},
  2146. {"user_id", member.user_id},
  2147. {"group_ids", member.group_ids},
  2148. {"created_at", member.created_at},
  2149. {"updated_at", member.updated_at}
  2150. };
  2151. if (has_system_access) {
  2152. member_json["deleted_at"] = member.deleted_at;
  2153. }
  2154. // Fetch user details if UserService is available
  2155. if (userService_) {
  2156. auto user_result = userService_->GetUser(member.user_id);
  2157. if (user_result.success && user_result.user) {
  2158. member_json["user"] = {
  2159. {"id", user_result.user->id},
  2160. {"email", user_result.user->email},
  2161. {"name", user_result.user->name},
  2162. {"created_at", user_result.user->created_at}
  2163. };
  2164. }
  2165. }
  2166. members_array.push_back(member_json);
  2167. }
  2168. nlohmann::json response = {
  2169. {"members", members_array},
  2170. {"total_count", result.total_count}
  2171. };
  2172. res.set_content(response.dump(), "application/json");
  2173. } catch (const std::exception& e) {
  2174. spdlog::error("List members error: {}", e.what());
  2175. res.status = 500;
  2176. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2177. }
  2178. }
  2179. void HttpServer::HandleGetMember(const httplib::Request& req, httplib::Response& res) {
  2180. // Authenticate the request
  2181. auto auth_user = AuthenticateRequest(req);
  2182. if (!auth_user) {
  2183. res.status = 401;
  2184. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2185. return;
  2186. }
  2187. // Extract workspace ID and user ID from path
  2188. std::string workspace_id = req.matches[1].str();
  2189. std::string user_id = req.matches[2].str();
  2190. // Check access: must be member OR have system:memberships:read permission
  2191. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  2192. auth_user->workspace_ids.end(),
  2193. workspace_id) != auth_user->workspace_ids.end());
  2194. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kMembershipsRead);
  2195. if (!is_member && !has_system_access) {
  2196. res.status = 403;
  2197. res.set_content(R"({"error":"Forbidden - not a member of this workspace"})", "application/json");
  2198. return;
  2199. }
  2200. // Check if MembershipService is available
  2201. if (!membershipService_) {
  2202. res.status = 503;
  2203. res.set_content(R"({"error":"Membership service not available"})", "application/json");
  2204. return;
  2205. }
  2206. try {
  2207. auto result = membershipService_->GetMembershipByUser(workspace_id, user_id);
  2208. if (!result.success) {
  2209. res.status = 404;
  2210. nlohmann::json error_response = {{"error", result.error}};
  2211. res.set_content(error_response.dump(), "application/json");
  2212. return;
  2213. }
  2214. // Return membership
  2215. nlohmann::json member_json = {
  2216. {"id", result.member->id},
  2217. {"workspace_id", result.member->workspace_id},
  2218. {"user_id", result.member->user_id},
  2219. {"group_ids", result.member->group_ids},
  2220. {"created_at", result.member->created_at},
  2221. {"updated_at", result.member->updated_at}
  2222. };
  2223. res.set_content(member_json.dump(), "application/json");
  2224. } catch (const std::exception& e) {
  2225. spdlog::error("Get member error: {}", e.what());
  2226. res.status = 500;
  2227. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2228. }
  2229. }
  2230. void HttpServer::HandleUpdateMember(const httplib::Request& req, httplib::Response& res) {
  2231. // Authenticate the request
  2232. auto auth_user = AuthenticateRequest(req);
  2233. if (!auth_user) {
  2234. res.status = 401;
  2235. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2236. return;
  2237. }
  2238. // Extract workspace ID and user ID from path
  2239. std::string workspace_id = req.matches[1].str();
  2240. std::string user_id = req.matches[2].str();
  2241. // Requires system:memberships:update permission OR workspace member management permission
  2242. bool can_update = authorizationService_->HasPermission(*auth_user, permissions::kMembershipsUpdate) ||
  2243. authorizationService_->CanManageWorkspaceMembers(*auth_user, workspace_id);
  2244. if (!can_update) {
  2245. res.status = 403;
  2246. res.set_content(R"({"error":"Forbidden - requires system:memberships:update permission or workspace member management"})", "application/json");
  2247. return;
  2248. }
  2249. // Check if MembershipService is available
  2250. if (!membershipService_) {
  2251. res.status = 503;
  2252. res.set_content(R"({"error":"Membership service not available"})", "application/json");
  2253. return;
  2254. }
  2255. try {
  2256. // Parse request body
  2257. auto json = nlohmann::json::parse(req.body);
  2258. UpdateMemberRequest update_req;
  2259. if (json.contains("group_ids") && json["group_ids"].is_array()) {
  2260. std::vector<std::string> group_ids;
  2261. for (const auto& item : json["group_ids"]) {
  2262. if (item.is_string()) {
  2263. group_ids.push_back(item.get<std::string>());
  2264. }
  2265. }
  2266. update_req.group_ids = group_ids;
  2267. }
  2268. auto result = membershipService_->UpdateMembership(workspace_id, user_id, update_req);
  2269. if (!result.success) {
  2270. res.status = 400;
  2271. nlohmann::json error_response = {{"error", result.error}};
  2272. res.set_content(error_response.dump(), "application/json");
  2273. return;
  2274. }
  2275. // Return updated membership
  2276. nlohmann::json member_json = {
  2277. {"id", result.member->id},
  2278. {"workspace_id", result.member->workspace_id},
  2279. {"user_id", result.member->user_id},
  2280. {"group_ids", result.member->group_ids},
  2281. {"created_at", result.member->created_at},
  2282. {"updated_at", result.member->updated_at}
  2283. };
  2284. res.set_content(member_json.dump(), "application/json");
  2285. } catch (const nlohmann::json::exception& e) {
  2286. res.status = 400;
  2287. nlohmann::json error_response = {{"error", "Invalid JSON: " + std::string(e.what())}};
  2288. res.set_content(error_response.dump(), "application/json");
  2289. } catch (const std::exception& e) {
  2290. spdlog::error("Update member error: {}", e.what());
  2291. res.status = 500;
  2292. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2293. }
  2294. }
  2295. void HttpServer::HandleRemoveMember(const httplib::Request& req, httplib::Response& res) {
  2296. // Authenticate the request
  2297. auto auth_user = AuthenticateRequest(req);
  2298. if (!auth_user) {
  2299. res.status = 401;
  2300. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2301. return;
  2302. }
  2303. // Extract workspace ID and user ID from path
  2304. std::string workspace_id = req.matches[1].str();
  2305. std::string user_id = req.matches[2].str();
  2306. // Requires system:memberships:delete permission OR workspace member management permission
  2307. bool can_remove = authorizationService_->HasPermission(*auth_user, permissions::kMembershipsDelete) ||
  2308. authorizationService_->CanManageWorkspaceMembers(*auth_user, workspace_id);
  2309. if (!can_remove) {
  2310. res.status = 403;
  2311. res.set_content(R"({"error":"Forbidden - requires system:memberships:delete permission or workspace member management"})", "application/json");
  2312. return;
  2313. }
  2314. // Check if MembershipService is available
  2315. if (!membershipService_) {
  2316. res.status = 503;
  2317. res.set_content(R"({"error":"Membership service not available"})", "application/json");
  2318. return;
  2319. }
  2320. try {
  2321. auto result = membershipService_->RemoveMember(workspace_id, user_id);
  2322. if (!result.success) {
  2323. res.status = 400;
  2324. nlohmann::json error_response = {{"error", result.error}};
  2325. res.set_content(error_response.dump(), "application/json");
  2326. return;
  2327. }
  2328. res.set_content(R"({"message":"Member removed successfully"})", "application/json");
  2329. } catch (const std::exception& e) {
  2330. spdlog::error("Remove member error: {}", e.what());
  2331. res.status = 500;
  2332. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2333. }
  2334. }
  2335. // ============================================================================
  2336. // API Key Routes
  2337. // ============================================================================
  2338. void HttpServer::SetupApiKeyRoutes() {
  2339. // POST /api/users/:id/api-keys - Create an API key for a user
  2340. httpServer_->Post(R"(/api/users/([a-zA-Z0-9\-]+)/api-keys)", [this](const httplib::Request& req, httplib::Response& res) {
  2341. HandleCreateApiKey(req, res);
  2342. });
  2343. // GET /api/users/:id/api-keys - List user's API keys
  2344. httpServer_->Get(R"(/api/users/([a-zA-Z0-9\-]+)/api-keys)", [this](const httplib::Request& req, httplib::Response& res) {
  2345. HandleListApiKeys(req, res);
  2346. });
  2347. // DELETE /api/users/:id/api-keys/:keyId - Revoke an API key
  2348. httpServer_->Delete(R"(/api/users/([a-zA-Z0-9\-]+)/api-keys/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  2349. HandleRevokeApiKey(req, res);
  2350. });
  2351. spdlog::info("API key routes registered: /api/users/:id/api-keys");
  2352. }
  2353. void HttpServer::HandleCreateApiKey(const httplib::Request& req, httplib::Response& res) {
  2354. // Authenticate the request
  2355. auto auth_user = AuthenticateRequest(req);
  2356. if (!auth_user) {
  2357. res.status = 401;
  2358. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2359. return;
  2360. }
  2361. // Extract user ID from path
  2362. std::string target_user_id = req.matches[1].str();
  2363. // Check permissions: own OR system:api_keys:create permission
  2364. bool is_own = (auth_user->user_id == target_user_id);
  2365. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kApiKeysCreate);
  2366. if (!is_own && !has_system_access) {
  2367. res.status = 403;
  2368. res.set_content(R"({"error":"Forbidden - can only create API keys for yourself or requires system:api_keys:create permission"})", "application/json");
  2369. return;
  2370. }
  2371. // Check if ApiKeyService is available
  2372. if (!apiKeyService_) {
  2373. res.status = 503;
  2374. res.set_content(R"({"error":"API key service not available"})", "application/json");
  2375. return;
  2376. }
  2377. try {
  2378. // Parse request body
  2379. auto json = nlohmann::json::parse(req.body);
  2380. CreateApiKeyRequest create_req;
  2381. create_req.user_id = target_user_id;
  2382. if (json.contains("name") && json["name"].is_string()) {
  2383. create_req.name = json["name"].get<std::string>();
  2384. } else {
  2385. res.status = 400;
  2386. res.set_content(R"({"error":"name is required"})", "application/json");
  2387. return;
  2388. }
  2389. if (json.contains("permissions") && json["permissions"].is_array()) {
  2390. for (const auto& item : json["permissions"]) {
  2391. if (item.is_string()) {
  2392. std::string perm = item.get<std::string>();
  2393. // Users can only grant permissions they have (unless they have system access)
  2394. if (!has_system_access) {
  2395. // For now, allow all permissions - proper permission checking
  2396. // would require looking up user's actual permissions
  2397. }
  2398. create_req.permissions.push_back(perm);
  2399. }
  2400. }
  2401. }
  2402. if (json.contains("expires_at") && json["expires_at"].is_string()) {
  2403. create_req.expires_at = json["expires_at"].get<std::string>();
  2404. }
  2405. auto result = apiKeyService_->CreateApiKey(create_req);
  2406. if (!result.success) {
  2407. res.status = 400;
  2408. nlohmann::json error_response = {{"error", result.error}};
  2409. res.set_content(error_response.dump(), "application/json");
  2410. return;
  2411. }
  2412. // Return created key info INCLUDING the raw key (only time it's returned!)
  2413. nlohmann::json key_json = {
  2414. {"id", result.api_key->id},
  2415. {"user_id", result.api_key->user_id},
  2416. {"name", result.api_key->name},
  2417. {"key_prefix", result.api_key->key_prefix},
  2418. {"key", result.raw_key}, // THE RAW KEY - only returned once!
  2419. {"permissions", result.api_key->permissions},
  2420. {"created_at", result.api_key->created_at},
  2421. {"expires_at", result.api_key->expires_at}
  2422. };
  2423. res.status = 201;
  2424. res.set_content(key_json.dump(), "application/json");
  2425. } catch (const nlohmann::json::exception& e) {
  2426. res.status = 400;
  2427. nlohmann::json error_response = {{"error", "Invalid JSON: " + std::string(e.what())}};
  2428. res.set_content(error_response.dump(), "application/json");
  2429. } catch (const std::exception& e) {
  2430. spdlog::error("Create API key error: {}", e.what());
  2431. res.status = 500;
  2432. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2433. }
  2434. }
  2435. void HttpServer::HandleListApiKeys(const httplib::Request& req, httplib::Response& res) {
  2436. // Authenticate the request
  2437. auto auth_user = AuthenticateRequest(req);
  2438. if (!auth_user) {
  2439. res.status = 401;
  2440. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2441. return;
  2442. }
  2443. // Extract user ID from path
  2444. std::string target_user_id = req.matches[1].str();
  2445. // Check permissions: own OR system:api_keys:read permission
  2446. bool is_own = (auth_user->user_id == target_user_id);
  2447. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kApiKeysRead);
  2448. if (!is_own && !has_system_access) {
  2449. res.status = 403;
  2450. res.set_content(R"({"error":"Forbidden - can only list your own API keys or requires system:api_keys:read permission"})", "application/json");
  2451. return;
  2452. }
  2453. // Check if ApiKeyService is available
  2454. if (!apiKeyService_) {
  2455. res.status = 503;
  2456. res.set_content(R"({"error":"API key service not available"})", "application/json");
  2457. return;
  2458. }
  2459. try {
  2460. // Check for include_revoked parameter (requires system access)
  2461. bool include_revoked = false;
  2462. if (has_system_access && req.has_param("include_revoked")) {
  2463. include_revoked = req.get_param_value("include_revoked") == "true";
  2464. }
  2465. auto result = apiKeyService_->ListApiKeys(target_user_id, include_revoked);
  2466. if (!result.success) {
  2467. res.status = 500;
  2468. nlohmann::json error_response = {{"error", result.error}};
  2469. res.set_content(error_response.dump(), "application/json");
  2470. return;
  2471. }
  2472. // Build response (note: raw keys and hashes are NOT included)
  2473. nlohmann::json keys_array = nlohmann::json::array();
  2474. for (const auto& key : result.api_keys) {
  2475. nlohmann::json key_json = {
  2476. {"id", key.id},
  2477. {"user_id", key.user_id},
  2478. {"name", key.name},
  2479. {"key_prefix", key.key_prefix}, // Only prefix, not full key
  2480. {"permissions", key.permissions},
  2481. {"created_at", key.created_at},
  2482. {"updated_at", key.updated_at},
  2483. {"last_used_at", key.last_used_at},
  2484. {"expires_at", key.expires_at}
  2485. };
  2486. if (has_system_access) {
  2487. key_json["deleted_at"] = key.deleted_at;
  2488. }
  2489. keys_array.push_back(key_json);
  2490. }
  2491. nlohmann::json response = {
  2492. {"api_keys", keys_array},
  2493. {"total_count", result.total_count}
  2494. };
  2495. res.set_content(response.dump(), "application/json");
  2496. } catch (const std::exception& e) {
  2497. spdlog::error("List API keys error: {}", e.what());
  2498. res.status = 500;
  2499. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2500. }
  2501. }
  2502. void HttpServer::HandleRevokeApiKey(const httplib::Request& req, httplib::Response& res) {
  2503. // Authenticate the request
  2504. auto auth_user = AuthenticateRequest(req);
  2505. if (!auth_user) {
  2506. res.status = 401;
  2507. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2508. return;
  2509. }
  2510. // Extract user ID and key ID from path
  2511. std::string target_user_id = req.matches[1].str();
  2512. std::string key_id = req.matches[2].str();
  2513. // Check permissions: own OR system:api_keys:delete permission
  2514. bool is_own = (auth_user->user_id == target_user_id);
  2515. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kApiKeysDelete);
  2516. if (!is_own && !has_system_access) {
  2517. res.status = 403;
  2518. res.set_content(R"({"error":"Forbidden - can only revoke your own API keys or requires system:api_keys:delete permission"})", "application/json");
  2519. return;
  2520. }
  2521. // Check if ApiKeyService is available
  2522. if (!apiKeyService_) {
  2523. res.status = 503;
  2524. res.set_content(R"({"error":"API key service not available"})", "application/json");
  2525. return;
  2526. }
  2527. try {
  2528. auto result = apiKeyService_->RevokeApiKey(key_id, target_user_id);
  2529. if (!result.success) {
  2530. res.status = 400;
  2531. nlohmann::json error_response = {{"error", result.error}};
  2532. res.set_content(error_response.dump(), "application/json");
  2533. return;
  2534. }
  2535. res.set_content(R"({"message":"API key revoked successfully"})", "application/json");
  2536. } catch (const std::exception& e) {
  2537. spdlog::error("Revoke API key error: {}", e.what());
  2538. res.status = 500;
  2539. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2540. }
  2541. }
  2542. // ============================================================================
  2543. // Collection Routes
  2544. // ============================================================================
  2545. void HttpServer::SetupCollectionRoutes() {
  2546. // POST /api/workspaces/:wid/collections - Create a collection
  2547. httpServer_->Post(R"(/api/workspaces/([a-zA-Z0-9\-]+)/collections)", [this](const httplib::Request& req, httplib::Response& res) {
  2548. HandleCreateCollection(req, res);
  2549. });
  2550. // GET /api/workspaces/:wid/collections - List collections
  2551. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+)/collections)", [this](const httplib::Request& req, httplib::Response& res) {
  2552. HandleListCollections(req, res);
  2553. });
  2554. // GET /api/workspaces/:wid/collections/:name - Get a collection
  2555. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+)/collections/([a-zA-Z_][a-zA-Z0-9_]*))", [this](const httplib::Request& req, httplib::Response& res) {
  2556. HandleGetCollection(req, res);
  2557. });
  2558. // PUT /api/workspaces/:wid/collections/:name - Update a collection
  2559. httpServer_->Put(R"(/api/workspaces/([a-zA-Z0-9\-]+)/collections/([a-zA-Z_][a-zA-Z0-9_]*))", [this](const httplib::Request& req, httplib::Response& res) {
  2560. HandleUpdateCollection(req, res);
  2561. });
  2562. // DELETE /api/workspaces/:wid/collections/:name - Drop a collection
  2563. httpServer_->Delete(R"(/api/workspaces/([a-zA-Z0-9\-]+)/collections/([a-zA-Z_][a-zA-Z0-9_]*))", [this](const httplib::Request& req, httplib::Response& res) {
  2564. HandleDropCollection(req, res);
  2565. });
  2566. spdlog::info("Collection routes registered: /api/workspaces/:wid/collections");
  2567. }
  2568. void HttpServer::HandleCreateCollection(const httplib::Request& req, httplib::Response& res) {
  2569. // Authenticate the request
  2570. auto auth_user = AuthenticateRequest(req);
  2571. if (!auth_user) {
  2572. res.status = 401;
  2573. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2574. return;
  2575. }
  2576. // Extract workspace ID from path
  2577. std::string workspace_id = req.matches[1].str();
  2578. // Verify workspace exists and user has access
  2579. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  2580. if (!ws_result.success) {
  2581. res.status = 404;
  2582. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  2583. return;
  2584. }
  2585. // Requires system:collections:create permission OR workspace membership with manage_collections
  2586. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  2587. auth_user->workspace_ids.end(),
  2588. workspace_id) != auth_user->workspace_ids.end());
  2589. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kCollectionsCreate);
  2590. if (!is_member && !has_system_access) {
  2591. res.status = 403;
  2592. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  2593. return;
  2594. }
  2595. // Check if CollectionService is available
  2596. if (!collectionService_) {
  2597. res.status = 503;
  2598. res.set_content(R"({"error":"Collection service not available"})", "application/json");
  2599. return;
  2600. }
  2601. try {
  2602. // Parse request body
  2603. auto json = nlohmann::json::parse(req.body);
  2604. CreateCollectionRequest create_req;
  2605. create_req.workspace_id = workspace_id;
  2606. if (json.contains("name") && json["name"].is_string()) {
  2607. create_req.name = json["name"].get<std::string>();
  2608. } else {
  2609. res.status = 400;
  2610. res.set_content(R"({"error":"name is required"})", "application/json");
  2611. return;
  2612. }
  2613. // Parse settings
  2614. if (json.contains("schema") && json["schema"].is_string()) {
  2615. create_req.settings.schema = json["schema"].get<std::string>();
  2616. }
  2617. if (json.contains("encrypted_fields") && json["encrypted_fields"].is_array()) {
  2618. for (const auto& item : json["encrypted_fields"]) {
  2619. if (item.is_string()) {
  2620. create_req.settings.encrypted_fields.push_back(item.get<std::string>());
  2621. }
  2622. }
  2623. }
  2624. if (json.contains("ttl_seconds") && json["ttl_seconds"].is_number_integer()) {
  2625. create_req.settings.ttl_seconds = json["ttl_seconds"].get<int64_t>();
  2626. }
  2627. auto result = collectionService_->CreateCollection(create_req);
  2628. if (!result.success) {
  2629. res.status = 400;
  2630. nlohmann::json error_response = {{"error", result.error}};
  2631. res.set_content(error_response.dump(), "application/json");
  2632. return;
  2633. }
  2634. // Return created collection info
  2635. nlohmann::json coll_json = {
  2636. {"name", result.collection->name},
  2637. {"workspace_id", result.collection->workspace_id},
  2638. {"document_count", result.collection->document_count},
  2639. {"size_bytes", result.collection->size_bytes},
  2640. {"created_at", result.collection->created_at},
  2641. {"settings", {
  2642. {"schema", result.collection->settings.schema},
  2643. {"encrypted_fields", result.collection->settings.encrypted_fields},
  2644. {"ttl_seconds", result.collection->settings.ttl_seconds}
  2645. }}
  2646. };
  2647. res.status = 201;
  2648. res.set_content(coll_json.dump(), "application/json");
  2649. } catch (const nlohmann::json::exception& e) {
  2650. spdlog::warn("Create collection JSON parse error: {}", e.what());
  2651. res.status = 400;
  2652. res.set_content(R"({"error":"Invalid JSON in request body"})", "application/json");
  2653. } catch (const std::exception& e) {
  2654. spdlog::error("Create collection error: {}", e.what());
  2655. res.status = 500;
  2656. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2657. }
  2658. }
  2659. void HttpServer::HandleListCollections(const httplib::Request& req, httplib::Response& res) {
  2660. // Authenticate the request
  2661. auto auth_user = AuthenticateRequest(req);
  2662. if (!auth_user) {
  2663. res.status = 401;
  2664. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2665. return;
  2666. }
  2667. // Extract workspace ID from path
  2668. std::string workspace_id = req.matches[1].str();
  2669. // Verify workspace exists and user has access
  2670. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  2671. if (!ws_result.success) {
  2672. res.status = 404;
  2673. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  2674. return;
  2675. }
  2676. // Check access: must be member OR have system:collections:read permission
  2677. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  2678. auth_user->workspace_ids.end(),
  2679. workspace_id) != auth_user->workspace_ids.end());
  2680. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kCollectionsRead);
  2681. if (!is_member && !has_system_access) {
  2682. res.status = 403;
  2683. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  2684. return;
  2685. }
  2686. // Check if CollectionService is available
  2687. if (!collectionService_) {
  2688. res.status = 503;
  2689. res.set_content(R"({"error":"Collection service not available"})", "application/json");
  2690. return;
  2691. }
  2692. try {
  2693. // Check if user with system access wants to include system collections
  2694. bool include_system = has_system_access &&
  2695. req.has_param("include_system") &&
  2696. req.get_param_value("include_system") == "true";
  2697. auto result = collectionService_->ListCollections(workspace_id);
  2698. if (!result.success) {
  2699. res.status = 500;
  2700. nlohmann::json error_response = {{"error", result.error}};
  2701. res.set_content(error_response.dump(), "application/json");
  2702. return;
  2703. }
  2704. nlohmann::json collections_array = nlohmann::json::array();
  2705. for (const auto& coll : result.collections) {
  2706. // Check if collection name starts with underscore (system collection)
  2707. bool is_system = !coll.name.empty() && coll.name[0] == '_';
  2708. nlohmann::json coll_json = {
  2709. {"name", coll.name},
  2710. {"workspace_id", coll.workspace_id},
  2711. {"document_count", coll.document_count},
  2712. {"size_bytes", coll.size_bytes},
  2713. {"created_at", coll.created_at},
  2714. {"updated_at", coll.updated_at},
  2715. {"is_system", is_system},
  2716. {"created_by", coll.created_by},
  2717. {"updated_by", coll.updated_by},
  2718. {"created_by_name", ResolveUserName(coll.created_by)},
  2719. {"updated_by_name", ResolveUserName(coll.updated_by)},
  2720. {"settings", {
  2721. {"schema", coll.settings.schema},
  2722. {"encrypted_fields", coll.settings.encrypted_fields},
  2723. {"ttl_seconds", coll.settings.ttl_seconds}
  2724. }}
  2725. };
  2726. collections_array.push_back(coll_json);
  2727. }
  2728. // If superadmin requested system collections, add global system collections
  2729. if (include_system) {
  2730. auto system_result = collectionService_->ListSystemCollections();
  2731. if (system_result.success) {
  2732. for (const auto& coll : system_result.collections) {
  2733. nlohmann::json coll_json = {
  2734. {"name", coll.name},
  2735. {"workspace_id", ""},
  2736. {"document_count", coll.document_count},
  2737. {"size_bytes", coll.size_bytes},
  2738. {"created_at", coll.created_at},
  2739. {"updated_at", coll.updated_at},
  2740. {"is_system", true},
  2741. {"created_by", coll.created_by},
  2742. {"updated_by", coll.updated_by},
  2743. {"created_by_name", ResolveUserName(coll.created_by)},
  2744. {"updated_by_name", ResolveUserName(coll.updated_by)},
  2745. {"settings", nlohmann::json::object()}
  2746. };
  2747. collections_array.push_back(coll_json);
  2748. }
  2749. }
  2750. }
  2751. nlohmann::json response = {
  2752. {"collections", collections_array},
  2753. {"total_count", static_cast<int64_t>(collections_array.size())}
  2754. };
  2755. res.set_content(response.dump(), "application/json");
  2756. } catch (const std::exception& e) {
  2757. spdlog::error("List collections error: {}", e.what());
  2758. res.status = 500;
  2759. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2760. }
  2761. }
  2762. void HttpServer::HandleGetCollection(const httplib::Request& req, httplib::Response& res) {
  2763. // Authenticate the request
  2764. auto auth_user = AuthenticateRequest(req);
  2765. if (!auth_user) {
  2766. res.status = 401;
  2767. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2768. return;
  2769. }
  2770. // Extract workspace ID and collection name from path
  2771. std::string workspace_id = req.matches[1].str();
  2772. std::string collection_name = req.matches[2].str();
  2773. // Verify workspace exists and user has access
  2774. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  2775. if (!ws_result.success) {
  2776. res.status = 404;
  2777. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  2778. return;
  2779. }
  2780. // Check access: must be member OR have system:collections:read permission
  2781. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  2782. auth_user->workspace_ids.end(),
  2783. workspace_id) != auth_user->workspace_ids.end());
  2784. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kCollectionsRead);
  2785. if (!is_member && !has_system_access) {
  2786. res.status = 403;
  2787. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  2788. return;
  2789. }
  2790. // Check if CollectionService is available
  2791. if (!collectionService_) {
  2792. res.status = 503;
  2793. res.set_content(R"({"error":"Collection service not available"})", "application/json");
  2794. return;
  2795. }
  2796. try {
  2797. auto result = collectionService_->GetCollection(workspace_id, collection_name);
  2798. if (!result.success) {
  2799. res.status = 404;
  2800. nlohmann::json error_response = {{"error", result.error}};
  2801. res.set_content(error_response.dump(), "application/json");
  2802. return;
  2803. }
  2804. nlohmann::json coll_json = {
  2805. {"name", result.collection->name},
  2806. {"workspace_id", result.collection->workspace_id},
  2807. {"document_count", result.collection->document_count},
  2808. {"size_bytes", result.collection->size_bytes},
  2809. {"created_at", result.collection->created_at},
  2810. {"updated_at", result.collection->updated_at},
  2811. {"settings", {
  2812. {"schema", result.collection->settings.schema},
  2813. {"encrypted_fields", result.collection->settings.encrypted_fields},
  2814. {"ttl_seconds", result.collection->settings.ttl_seconds}
  2815. }}
  2816. };
  2817. res.set_content(coll_json.dump(), "application/json");
  2818. } catch (const std::exception& e) {
  2819. spdlog::error("Get collection error: {}", e.what());
  2820. res.status = 500;
  2821. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2822. }
  2823. }
  2824. void HttpServer::HandleUpdateCollection(const httplib::Request& req, httplib::Response& res) {
  2825. // Authenticate the request
  2826. auto auth_user = AuthenticateRequest(req);
  2827. if (!auth_user) {
  2828. res.status = 401;
  2829. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2830. return;
  2831. }
  2832. // Extract workspace ID and collection name from path
  2833. std::string workspace_id = req.matches[1].str();
  2834. std::string collection_name = req.matches[2].str();
  2835. // Verify workspace exists and user has access
  2836. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  2837. if (!ws_result.success) {
  2838. res.status = 404;
  2839. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  2840. return;
  2841. }
  2842. // Requires system:collections:update permission OR workspace membership
  2843. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  2844. auth_user->workspace_ids.end(),
  2845. workspace_id) != auth_user->workspace_ids.end());
  2846. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kCollectionsUpdate);
  2847. if (!is_member && !has_system_access) {
  2848. res.status = 403;
  2849. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  2850. return;
  2851. }
  2852. // Check if CollectionService is available
  2853. if (!collectionService_) {
  2854. res.status = 503;
  2855. res.set_content(R"({"error":"Collection service not available"})", "application/json");
  2856. return;
  2857. }
  2858. try {
  2859. // Parse request body
  2860. auto json = nlohmann::json::parse(req.body);
  2861. // Get existing settings first
  2862. auto get_result = collectionService_->GetCollection(workspace_id, collection_name);
  2863. if (!get_result.success) {
  2864. res.status = 404;
  2865. res.set_content(R"({"error":"Collection not found"})", "application/json");
  2866. return;
  2867. }
  2868. CollectionSettings settings = get_result.collection->settings;
  2869. // Update only provided fields
  2870. if (json.contains("schema") && json["schema"].is_string()) {
  2871. settings.schema = json["schema"].get<std::string>();
  2872. }
  2873. if (json.contains("encrypted_fields") && json["encrypted_fields"].is_array()) {
  2874. settings.encrypted_fields.clear();
  2875. for (const auto& item : json["encrypted_fields"]) {
  2876. if (item.is_string()) {
  2877. settings.encrypted_fields.push_back(item.get<std::string>());
  2878. }
  2879. }
  2880. }
  2881. if (json.contains("ttl_seconds") && json["ttl_seconds"].is_number_integer()) {
  2882. settings.ttl_seconds = json["ttl_seconds"].get<int64_t>();
  2883. }
  2884. auto result = collectionService_->UpdateCollection(workspace_id, collection_name, settings);
  2885. if (!result.success) {
  2886. res.status = 400;
  2887. nlohmann::json error_response = {{"error", result.error}};
  2888. res.set_content(error_response.dump(), "application/json");
  2889. return;
  2890. }
  2891. nlohmann::json coll_json = {
  2892. {"name", result.collection->name},
  2893. {"workspace_id", result.collection->workspace_id},
  2894. {"document_count", result.collection->document_count},
  2895. {"size_bytes", result.collection->size_bytes},
  2896. {"created_at", result.collection->created_at},
  2897. {"updated_at", result.collection->updated_at},
  2898. {"settings", {
  2899. {"schema", result.collection->settings.schema},
  2900. {"encrypted_fields", result.collection->settings.encrypted_fields},
  2901. {"ttl_seconds", result.collection->settings.ttl_seconds}
  2902. }}
  2903. };
  2904. res.set_content(coll_json.dump(), "application/json");
  2905. } catch (const nlohmann::json::exception& e) {
  2906. spdlog::warn("Update collection JSON parse error: {}", e.what());
  2907. res.status = 400;
  2908. res.set_content(R"({"error":"Invalid JSON in request body"})", "application/json");
  2909. } catch (const std::exception& e) {
  2910. spdlog::error("Update collection error: {}", e.what());
  2911. res.status = 500;
  2912. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2913. }
  2914. }
  2915. // ============================================================================
  2916. // Document Routes
  2917. // ============================================================================
  2918. void HttpServer::SetupDocumentRoutes() {
  2919. // POST /api/workspaces/:wid/collections/:name/documents - Create a document
  2920. httpServer_->Post(R"(/api/workspaces/([a-zA-Z0-9\-]+)/collections/([a-zA-Z_][a-zA-Z0-9_]*)/documents)", [this](const httplib::Request& req, httplib::Response& res) {
  2921. HandleCreateDocument(req, res);
  2922. });
  2923. // GET /api/workspaces/:wid/collections/:name/documents - List documents
  2924. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+)/collections/([a-zA-Z_][a-zA-Z0-9_]*)/documents)", [this](const httplib::Request& req, httplib::Response& res) {
  2925. HandleListDocuments(req, res);
  2926. });
  2927. // GET /api/workspaces/:wid/collections/:name/documents/:id - Get a document
  2928. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+)/collections/([a-zA-Z_][a-zA-Z0-9_]*)/documents/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  2929. HandleGetDocument(req, res);
  2930. });
  2931. // PUT /api/workspaces/:wid/collections/:name/documents/:id - Update a document
  2932. httpServer_->Put(R"(/api/workspaces/([a-zA-Z0-9\-]+)/collections/([a-zA-Z_][a-zA-Z0-9_]*)/documents/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  2933. HandleUpdateDocument(req, res);
  2934. });
  2935. // PATCH /api/workspaces/:wid/collections/:name/documents/:id - Update a document (partial)
  2936. httpServer_->Patch(R"(/api/workspaces/([a-zA-Z0-9\-]+)/collections/([a-zA-Z_][a-zA-Z0-9_]*)/documents/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  2937. HandleUpdateDocument(req, res);
  2938. });
  2939. // DELETE /api/workspaces/:wid/collections/:name/documents/:id - Delete a document
  2940. httpServer_->Delete(R"(/api/workspaces/([a-zA-Z0-9\-]+)/collections/([a-zA-Z_][a-zA-Z0-9_]*)/documents/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  2941. HandleDeleteDocument(req, res);
  2942. });
  2943. spdlog::info("Document routes registered: /api/workspaces/:wid/collections/:name/documents");
  2944. }
  2945. void HttpServer::HandleCreateDocument(const httplib::Request& req, httplib::Response& res) {
  2946. // Authenticate the request
  2947. auto auth_user = AuthenticateRequest(req);
  2948. if (!auth_user) {
  2949. res.status = 401;
  2950. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2951. return;
  2952. }
  2953. // Extract workspace ID and collection name from path
  2954. std::string workspace_id = req.matches[1].str();
  2955. std::string collection_name = req.matches[2].str();
  2956. // Verify workspace exists and user has access
  2957. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  2958. if (!ws_result.success) {
  2959. res.status = 404;
  2960. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  2961. return;
  2962. }
  2963. // Check document create permission using AuthorizationService
  2964. if (!authorizationService_->CanCreateDocument(*auth_user, workspace_id, collection_name)) {
  2965. res.status = 403;
  2966. res.set_content(R"({"error":"Forbidden - no permission to create documents in this collection"})", "application/json");
  2967. return;
  2968. }
  2969. // Check if DocumentService is available
  2970. if (!documentService_) {
  2971. res.status = 503;
  2972. res.set_content(R"({"error":"Document service not available"})", "application/json");
  2973. return;
  2974. }
  2975. try {
  2976. // Parse request body
  2977. auto json = nlohmann::json::parse(req.body);
  2978. CreateDocumentRequest create_req;
  2979. create_req.workspace_id = workspace_id;
  2980. create_req.collection = collection_name;
  2981. create_req.user_id = auth_user->user_id; // Set user for _created_by tracking
  2982. if (json.contains("id") && json["id"].is_string()) {
  2983. create_req.id = json["id"].get<std::string>();
  2984. }
  2985. if (json.contains("data") && json["data"].is_object()) {
  2986. create_req.data = json["data"];
  2987. } else {
  2988. // Treat entire body as data if no "data" field
  2989. create_req.data = json;
  2990. create_req.data.erase("id"); // Remove id from data
  2991. }
  2992. auto result = documentService_->CreateDocument(create_req);
  2993. if (!result.success) {
  2994. res.status = 400;
  2995. nlohmann::json error_response = {{"error", result.error}};
  2996. res.set_content(error_response.dump(), "application/json");
  2997. return;
  2998. }
  2999. // Return created document info
  3000. nlohmann::json doc_json = {
  3001. {"id", result.document->id},
  3002. {"collection", result.document->collection},
  3003. {"workspace_id", result.document->workspace_id},
  3004. {"data", result.document->data},
  3005. {"created_at", result.document->created_at},
  3006. {"updated_at", result.document->updated_at},
  3007. {"version", result.document->version}
  3008. };
  3009. // Broadcast document create event to WebSocket subscribers
  3010. BroadcastDocumentEvent(workspace_id, collection_name, DocumentAction::Create,
  3011. result.document->id, result.document->data);
  3012. res.status = 201;
  3013. res.set_content(doc_json.dump(), "application/json");
  3014. } catch (const nlohmann::json::exception& e) {
  3015. spdlog::warn("Create document JSON parse error: {}", e.what());
  3016. res.status = 400;
  3017. res.set_content(R"({"error":"Invalid JSON in request body"})", "application/json");
  3018. } catch (const std::exception& e) {
  3019. spdlog::error("Create document error: {}", e.what());
  3020. res.status = 500;
  3021. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3022. }
  3023. }
  3024. void HttpServer::HandleListDocuments(const httplib::Request& req, httplib::Response& res) {
  3025. // Authenticate the request
  3026. auto auth_user = AuthenticateRequest(req);
  3027. if (!auth_user) {
  3028. res.status = 401;
  3029. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3030. return;
  3031. }
  3032. // Extract workspace ID and collection name from path
  3033. std::string workspace_id = req.matches[1].str();
  3034. std::string collection_name = req.matches[2].str();
  3035. // Verify workspace exists and user has access
  3036. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3037. if (!ws_result.success) {
  3038. res.status = 404;
  3039. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3040. return;
  3041. }
  3042. // Check collection read permission using AuthorizationService
  3043. if (!authorizationService_->CanReadCollection(*auth_user, workspace_id, collection_name)) {
  3044. res.status = 403;
  3045. res.set_content(R"({"error":"Forbidden - no permission to read documents in this collection"})", "application/json");
  3046. return;
  3047. }
  3048. // Check if DocumentService is available
  3049. if (!documentService_) {
  3050. res.status = 503;
  3051. res.set_content(R"({"error":"Document service not available"})", "application/json");
  3052. return;
  3053. }
  3054. try {
  3055. DocumentQuery query;
  3056. query.workspace_id = workspace_id;
  3057. query.collection = collection_name;
  3058. // Parse query parameters
  3059. if (req.has_param("limit")) {
  3060. query.limit = std::stoi(req.get_param_value("limit"));
  3061. if (query.limit < 1) query.limit = 1;
  3062. if (query.limit > 1000) query.limit = 1000;
  3063. }
  3064. if (req.has_param("offset")) {
  3065. query.offset = std::stoi(req.get_param_value("offset"));
  3066. if (query.offset < 0) query.offset = 0;
  3067. }
  3068. if (req.has_param("sort")) {
  3069. query.sort_field = req.get_param_value("sort");
  3070. }
  3071. if (req.has_param("order")) {
  3072. query.sort_ascending = (req.get_param_value("order") != "desc");
  3073. }
  3074. if (req.has_param("filter")) {
  3075. try {
  3076. query.filter = nlohmann::json::parse(req.get_param_value("filter"));
  3077. } catch (...) {
  3078. // Invalid filter JSON - ignore
  3079. }
  3080. }
  3081. auto result = documentService_->ListDocuments(query);
  3082. if (!result.success) {
  3083. res.status = 500;
  3084. nlohmann::json error_response = {{"error", result.error}};
  3085. res.set_content(error_response.dump(), "application/json");
  3086. return;
  3087. }
  3088. nlohmann::json docs_array = nlohmann::json::array();
  3089. for (const auto& doc : result.documents) {
  3090. // Resolve user names for _created_by and _updated_by
  3091. nlohmann::json enriched_data = doc.data;
  3092. if (doc.data.contains("_created_by") && doc.data["_created_by"].is_string()) {
  3093. std::string created_by_name = ResolveUserName(doc.data["_created_by"].get<std::string>());
  3094. if (!created_by_name.empty()) {
  3095. enriched_data["_created_by_name"] = created_by_name;
  3096. }
  3097. }
  3098. if (doc.data.contains("_updated_by") && doc.data["_updated_by"].is_string()) {
  3099. std::string updated_by_name = ResolveUserName(doc.data["_updated_by"].get<std::string>());
  3100. if (!updated_by_name.empty()) {
  3101. enriched_data["_updated_by_name"] = updated_by_name;
  3102. }
  3103. }
  3104. nlohmann::json doc_json = {
  3105. {"id", doc.id},
  3106. {"collection", doc.collection},
  3107. {"workspace_id", doc.workspace_id},
  3108. {"data", enriched_data},
  3109. {"created_at", doc.created_at},
  3110. {"updated_at", doc.updated_at},
  3111. {"version", doc.version}
  3112. };
  3113. docs_array.push_back(doc_json);
  3114. }
  3115. nlohmann::json response = {
  3116. {"documents", docs_array},
  3117. {"total_count", result.total_count}
  3118. };
  3119. res.set_content(response.dump(), "application/json");
  3120. } catch (const std::exception& e) {
  3121. spdlog::error("List documents error: {}", e.what());
  3122. res.status = 500;
  3123. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3124. }
  3125. }
  3126. void HttpServer::HandleGetDocument(const httplib::Request& req, httplib::Response& res) {
  3127. // Authenticate the request
  3128. auto auth_user = AuthenticateRequest(req);
  3129. if (!auth_user) {
  3130. res.status = 401;
  3131. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3132. return;
  3133. }
  3134. // Extract workspace ID, collection name, and document ID from path
  3135. std::string workspace_id = req.matches[1].str();
  3136. std::string collection_name = req.matches[2].str();
  3137. std::string document_id = req.matches[3].str();
  3138. // Verify workspace exists and user has access
  3139. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3140. if (!ws_result.success) {
  3141. res.status = 404;
  3142. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3143. return;
  3144. }
  3145. // Check if DocumentService is available
  3146. if (!documentService_) {
  3147. res.status = 503;
  3148. res.set_content(R"({"error":"Document service not available"})", "application/json");
  3149. return;
  3150. }
  3151. try {
  3152. auto result = documentService_->GetDocument(workspace_id, collection_name, document_id);
  3153. if (!result.success) {
  3154. res.status = 404;
  3155. nlohmann::json error_response = {{"error", result.error}};
  3156. res.set_content(error_response.dump(), "application/json");
  3157. return;
  3158. }
  3159. // Check document read permission with ownership
  3160. std::string doc_owner = result.document->data.value("_created_by", "");
  3161. if (!authorizationService_->CanReadDocument(*auth_user, workspace_id, collection_name, doc_owner)) {
  3162. res.status = 403;
  3163. res.set_content(R"({"error":"Forbidden - no permission to read this document"})", "application/json");
  3164. return;
  3165. }
  3166. nlohmann::json doc_json = {
  3167. {"id", result.document->id},
  3168. {"collection", result.document->collection},
  3169. {"workspace_id", result.document->workspace_id},
  3170. {"data", result.document->data},
  3171. {"created_at", result.document->created_at},
  3172. {"updated_at", result.document->updated_at},
  3173. {"version", result.document->version}
  3174. };
  3175. res.set_content(doc_json.dump(), "application/json");
  3176. } catch (const std::exception& e) {
  3177. spdlog::error("Get document error: {}", e.what());
  3178. res.status = 500;
  3179. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3180. }
  3181. }
  3182. void HttpServer::HandleUpdateDocument(const httplib::Request& req, httplib::Response& res) {
  3183. // Authenticate the request
  3184. auto auth_user = AuthenticateRequest(req);
  3185. if (!auth_user) {
  3186. res.status = 401;
  3187. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3188. return;
  3189. }
  3190. // Extract workspace ID, collection name, and document ID from path
  3191. std::string workspace_id = req.matches[1].str();
  3192. std::string collection_name = req.matches[2].str();
  3193. std::string document_id = req.matches[3].str();
  3194. // Verify workspace exists and user has access
  3195. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3196. if (!ws_result.success) {
  3197. res.status = 404;
  3198. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3199. return;
  3200. }
  3201. // Check if DocumentService is available
  3202. if (!documentService_) {
  3203. res.status = 503;
  3204. res.set_content(R"({"error":"Document service not available"})", "application/json");
  3205. return;
  3206. }
  3207. try {
  3208. // First get the document to check ownership
  3209. auto existing = documentService_->GetDocument(workspace_id, collection_name, document_id);
  3210. if (!existing.success) {
  3211. res.status = 404;
  3212. nlohmann::json error_response = {{"error", existing.error}};
  3213. res.set_content(error_response.dump(), "application/json");
  3214. return;
  3215. }
  3216. // Check document write permission with ownership
  3217. std::string doc_owner = existing.document->data.value("_created_by", "");
  3218. if (!authorizationService_->CanWriteDocument(*auth_user, workspace_id, collection_name, doc_owner)) {
  3219. res.status = 403;
  3220. res.set_content(R"({"error":"Forbidden - no permission to update this document"})", "application/json");
  3221. return;
  3222. }
  3223. // Parse request body
  3224. auto json = nlohmann::json::parse(req.body);
  3225. UpdateDocumentRequest update_req;
  3226. update_req.workspace_id = workspace_id;
  3227. update_req.collection = collection_name;
  3228. update_req.id = document_id;
  3229. update_req.user_id = auth_user->user_id; // Set user for _updated_by tracking
  3230. if (json.contains("data") && json["data"].is_object()) {
  3231. update_req.data = json["data"];
  3232. } else {
  3233. // Treat entire body as data if no "data" field
  3234. update_req.data = json;
  3235. }
  3236. if (json.contains("merge") && json["merge"].is_boolean()) {
  3237. update_req.merge = json["merge"].get<bool>();
  3238. }
  3239. if (json.contains("expected_version") && json["expected_version"].is_number_integer()) {
  3240. update_req.expected_version = json["expected_version"].get<int64_t>();
  3241. }
  3242. auto result = documentService_->UpdateDocument(update_req);
  3243. if (!result.success) {
  3244. res.status = 400;
  3245. nlohmann::json error_response = {{"error", result.error}};
  3246. res.set_content(error_response.dump(), "application/json");
  3247. return;
  3248. }
  3249. nlohmann::json doc_json = {
  3250. {"id", result.document->id},
  3251. {"collection", result.document->collection},
  3252. {"workspace_id", result.document->workspace_id},
  3253. {"data", result.document->data},
  3254. {"created_at", result.document->created_at},
  3255. {"updated_at", result.document->updated_at},
  3256. {"version", result.document->version}
  3257. };
  3258. // Broadcast document update event to WebSocket subscribers
  3259. BroadcastDocumentEvent(workspace_id, collection_name, DocumentAction::Update,
  3260. result.document->id, result.document->data);
  3261. res.set_content(doc_json.dump(), "application/json");
  3262. } catch (const nlohmann::json::exception& e) {
  3263. spdlog::warn("Update document JSON parse error: {}", e.what());
  3264. res.status = 400;
  3265. res.set_content(R"({"error":"Invalid JSON in request body"})", "application/json");
  3266. } catch (const std::exception& e) {
  3267. spdlog::error("Update document error: {}", e.what());
  3268. res.status = 500;
  3269. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3270. }
  3271. }
  3272. void HttpServer::HandleDeleteDocument(const httplib::Request& req, httplib::Response& res) {
  3273. // Authenticate the request
  3274. auto auth_user = AuthenticateRequest(req);
  3275. if (!auth_user) {
  3276. res.status = 401;
  3277. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3278. return;
  3279. }
  3280. // Extract workspace ID, collection name, and document ID from path
  3281. std::string workspace_id = req.matches[1].str();
  3282. std::string collection_name = req.matches[2].str();
  3283. std::string document_id = req.matches[3].str();
  3284. // Verify workspace exists and user has access
  3285. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3286. if (!ws_result.success) {
  3287. res.status = 404;
  3288. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3289. return;
  3290. }
  3291. // Check if DocumentService is available
  3292. if (!documentService_) {
  3293. res.status = 503;
  3294. res.set_content(R"({"error":"Document service not available"})", "application/json");
  3295. return;
  3296. }
  3297. try {
  3298. // First get the document to check ownership
  3299. auto existing = documentService_->GetDocument(workspace_id, collection_name, document_id);
  3300. if (!existing.success) {
  3301. res.status = 404;
  3302. nlohmann::json error_response = {{"error", existing.error}};
  3303. res.set_content(error_response.dump(), "application/json");
  3304. return;
  3305. }
  3306. // Check document delete permission with ownership
  3307. std::string doc_owner = existing.document->data.value("_created_by", "");
  3308. if (!authorizationService_->CanDeleteDocument(*auth_user, workspace_id, collection_name, doc_owner)) {
  3309. res.status = 403;
  3310. res.set_content(R"({"error":"Forbidden - no permission to delete this document"})", "application/json");
  3311. return;
  3312. }
  3313. auto result = documentService_->DeleteDocument(workspace_id, collection_name, document_id);
  3314. if (!result.success) {
  3315. res.status = 404;
  3316. nlohmann::json error_response = {{"error", result.error}};
  3317. res.set_content(error_response.dump(), "application/json");
  3318. return;
  3319. }
  3320. // Broadcast document delete event to WebSocket subscribers
  3321. BroadcastDocumentEvent(workspace_id, collection_name, DocumentAction::Delete,
  3322. document_id, nlohmann::json::object());
  3323. res.set_content(R"({"message":"Document deleted successfully"})", "application/json");
  3324. } catch (const std::exception& e) {
  3325. spdlog::error("Delete document error: {}", e.what());
  3326. res.status = 500;
  3327. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3328. }
  3329. }
  3330. void HttpServer::HandleDropCollection(const httplib::Request& req, httplib::Response& res) {
  3331. // Authenticate the request
  3332. auto auth_user = AuthenticateRequest(req);
  3333. if (!auth_user) {
  3334. res.status = 401;
  3335. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3336. return;
  3337. }
  3338. // Extract workspace ID and collection name from path
  3339. std::string workspace_id = req.matches[1].str();
  3340. std::string collection_name = req.matches[2].str();
  3341. // Verify workspace exists and user has access
  3342. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3343. if (!ws_result.success) {
  3344. res.status = 404;
  3345. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3346. return;
  3347. }
  3348. // Requires system:collections:delete permission OR workspace membership
  3349. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  3350. auth_user->workspace_ids.end(),
  3351. workspace_id) != auth_user->workspace_ids.end());
  3352. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kCollectionsDelete);
  3353. if (!is_member && !has_system_access) {
  3354. res.status = 403;
  3355. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  3356. return;
  3357. }
  3358. // Check if CollectionService is available
  3359. if (!collectionService_) {
  3360. res.status = 503;
  3361. res.set_content(R"({"error":"Collection service not available"})", "application/json");
  3362. return;
  3363. }
  3364. try {
  3365. // Check for force parameter
  3366. bool force = false;
  3367. if (req.has_param("force")) {
  3368. force = req.get_param_value("force") == "true";
  3369. }
  3370. auto result = collectionService_->DropCollection(workspace_id, collection_name, force);
  3371. if (!result.success) {
  3372. res.status = 400;
  3373. nlohmann::json error_response = {{"error", result.error}};
  3374. res.set_content(error_response.dump(), "application/json");
  3375. return;
  3376. }
  3377. res.set_content(R"({"message":"Collection dropped successfully"})", "application/json");
  3378. } catch (const std::exception& e) {
  3379. spdlog::error("Drop collection error: {}", e.what());
  3380. res.status = 500;
  3381. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3382. }
  3383. }
  3384. // ============================================================================
  3385. // View Routes
  3386. // ============================================================================
  3387. void HttpServer::SetupViewRoutes() {
  3388. // POST /api/workspaces/:workspace_id/views - Create a new view
  3389. httpServer_->Post(R"(/api/workspaces/([^/]+)/views)",
  3390. [this](const httplib::Request& req, httplib::Response& res) {
  3391. HandleCreateView(req, res);
  3392. });
  3393. // GET /api/workspaces/:workspace_id/views - List all views
  3394. httpServer_->Get(R"(/api/workspaces/([^/]+)/views)",
  3395. [this](const httplib::Request& req, httplib::Response& res) {
  3396. HandleListViews(req, res);
  3397. });
  3398. // GET /api/workspaces/:workspace_id/views/:view_id - Get a specific view
  3399. httpServer_->Get(R"(/api/workspaces/([^/]+)/views/([^/]+))",
  3400. [this](const httplib::Request& req, httplib::Response& res) {
  3401. HandleGetView(req, res);
  3402. });
  3403. // PATCH /api/workspaces/:workspace_id/views/:view_id - Update a view
  3404. httpServer_->Patch(R"(/api/workspaces/([^/]+)/views/([^/]+))",
  3405. [this](const httplib::Request& req, httplib::Response& res) {
  3406. HandleUpdateView(req, res);
  3407. });
  3408. // DELETE /api/workspaces/:workspace_id/views/:view_id - Delete a view
  3409. httpServer_->Delete(R"(/api/workspaces/([^/]+)/views/([^/]+))",
  3410. [this](const httplib::Request& req, httplib::Response& res) {
  3411. HandleDeleteView(req, res);
  3412. });
  3413. spdlog::info("View routes configured");
  3414. }
  3415. void HttpServer::HandleCreateView(const httplib::Request& req, httplib::Response& res) {
  3416. // Authenticate the request
  3417. auto auth_user = AuthenticateRequest(req);
  3418. if (!auth_user) {
  3419. res.status = 401;
  3420. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3421. return;
  3422. }
  3423. // Extract workspace ID from path
  3424. std::string workspace_id = req.matches[1].str();
  3425. // Verify workspace exists
  3426. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3427. if (!ws_result.success) {
  3428. res.status = 404;
  3429. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3430. return;
  3431. }
  3432. // Requires system:views:create permission OR workspace membership
  3433. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  3434. auth_user->workspace_ids.end(),
  3435. workspace_id) != auth_user->workspace_ids.end());
  3436. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kViewsCreate);
  3437. if (!is_member && !has_system_access) {
  3438. res.status = 403;
  3439. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  3440. return;
  3441. }
  3442. // Check if ViewService is available
  3443. if (!viewService_) {
  3444. res.status = 503;
  3445. res.set_content(R"({"error":"View service not available"})", "application/json");
  3446. return;
  3447. }
  3448. // Parse request body
  3449. nlohmann::json body;
  3450. try {
  3451. body = nlohmann::json::parse(req.body);
  3452. } catch (const nlohmann::json::parse_error& /*e*/) {
  3453. res.status = 400;
  3454. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  3455. return;
  3456. }
  3457. // Validate required fields
  3458. if (!body.contains("name") || !body["name"].is_string()) {
  3459. res.status = 400;
  3460. res.set_content(R"({"error":"name is required"})", "application/json");
  3461. return;
  3462. }
  3463. if (!body.contains("collection_name") || !body["collection_name"].is_string()) {
  3464. res.status = 400;
  3465. res.set_content(R"({"error":"collection_name is required"})", "application/json");
  3466. return;
  3467. }
  3468. try {
  3469. CreateViewRequest request;
  3470. request.workspace_id = workspace_id;
  3471. request.name = body["name"].get<std::string>();
  3472. request.collection_name = body["collection_name"].get<std::string>();
  3473. // Parse schema if provided
  3474. if (body.contains("schema") && body["schema"].is_object()) {
  3475. const auto& schema_json = body["schema"];
  3476. if (schema_json.contains("title")) {
  3477. request.schema.title = schema_json.value("title", "");
  3478. }
  3479. if (schema_json.contains("description")) {
  3480. request.schema.description = schema_json.value("description", "");
  3481. }
  3482. if (schema_json.contains("layout")) {
  3483. request.schema.layout = schema_json["layout"];
  3484. }
  3485. if (schema_json.contains("fields") && schema_json["fields"].is_array()) {
  3486. for (const auto& field_json : schema_json["fields"]) {
  3487. SchemaField field;
  3488. field.name = field_json.value("name", "");
  3489. field.group = field_json.value("group", "");
  3490. // Validate field name - names starting with "_" are reserved for system fields
  3491. if (!field.name.empty() && field.name[0] == '_' && field.group != "_system") {
  3492. res.status = 400;
  3493. res.set_content(R"({"error":"Field names starting with '_' are reserved for system fields"})", "application/json");
  3494. return;
  3495. }
  3496. field.type = StringToFieldType(field_json.value("type", "text"));
  3497. field.label = field_json.value("label", "");
  3498. field.description = field_json.value("description", "");
  3499. field.required = field_json.value("required", false);
  3500. field.display_order = field_json.value("display_order", 0);
  3501. field.widget = field_json.value("widget", "");
  3502. field.default_value = field_json.value("default_value", nlohmann::json());
  3503. field.options = field_json.value("options", nlohmann::json());
  3504. field.reference_collection = field_json.value("reference_collection", "");
  3505. field.computed_expression = field_json.value("computed_expression", "");
  3506. request.schema.fields.push_back(field);
  3507. }
  3508. }
  3509. }
  3510. // Parse settings if provided
  3511. if (body.contains("settings") && body["settings"].is_object()) {
  3512. const auto& settings_json = body["settings"];
  3513. request.settings.is_default = settings_json.value("is_default", false);
  3514. request.settings.show_in_sidebar = settings_json.value("show_in_sidebar", true);
  3515. request.settings.show_create_button = settings_json.value("show_create_button", true);
  3516. request.settings.icon = settings_json.value("icon", "");
  3517. request.settings.filters = settings_json.value("filters", nlohmann::json::object());
  3518. request.settings.sort = settings_json.value("sort", nlohmann::json::object());
  3519. request.settings.quick_create_mode = settings_json.value("quick_create_mode", "modal");
  3520. request.settings.quick_edit_mode = settings_json.value("quick_edit_mode", "modal");
  3521. request.settings.show_edit_button = settings_json.value("show_edit_button", true);
  3522. if (settings_json.contains("quick_create_fields") && settings_json["quick_create_fields"].is_array()) {
  3523. for (const auto& field : settings_json["quick_create_fields"]) {
  3524. if (field.is_string()) {
  3525. request.settings.quick_create_fields.push_back(field.get<std::string>());
  3526. }
  3527. }
  3528. }
  3529. if (settings_json.contains("quick_edit_fields") && settings_json["quick_edit_fields"].is_array()) {
  3530. for (const auto& field : settings_json["quick_edit_fields"]) {
  3531. if (field.is_string()) {
  3532. request.settings.quick_edit_fields.push_back(field.get<std::string>());
  3533. }
  3534. }
  3535. }
  3536. }
  3537. auto result = viewService_->CreateView(request);
  3538. if (!result.success) {
  3539. res.status = 400;
  3540. nlohmann::json error_response = {{"error", result.error}};
  3541. res.set_content(error_response.dump(), "application/json");
  3542. return;
  3543. }
  3544. // Build response with view info
  3545. nlohmann::json view_json = {
  3546. {"id", result.view->id},
  3547. {"workspace_id", result.view->workspace_id},
  3548. {"name", result.view->name},
  3549. {"collection_name", result.view->collection_name},
  3550. {"created_at", result.view->created_at},
  3551. {"updated_at", result.view->updated_at}
  3552. };
  3553. // Add schema
  3554. nlohmann::json schema_json = {
  3555. {"title", result.view->schema.title},
  3556. {"description", result.view->schema.description},
  3557. {"layout", result.view->schema.layout}
  3558. };
  3559. nlohmann::json fields_json = nlohmann::json::array();
  3560. for (const auto& field : result.view->schema.fields) {
  3561. nlohmann::json field_json = {
  3562. {"name", field.name},
  3563. {"type", FieldTypeToString(field.type)},
  3564. {"label", field.label},
  3565. {"description", field.description},
  3566. {"required", field.required},
  3567. {"display_order", field.display_order},
  3568. {"widget", field.widget},
  3569. {"group", field.group}
  3570. };
  3571. if (!field.default_value.is_null()) {
  3572. field_json["default_value"] = field.default_value;
  3573. }
  3574. if (!field.options.is_null()) {
  3575. field_json["options"] = field.options;
  3576. }
  3577. if (!field.reference_collection.empty()) {
  3578. field_json["reference_collection"] = field.reference_collection;
  3579. }
  3580. if (!field.computed_expression.empty()) {
  3581. field_json["computed_expression"] = field.computed_expression;
  3582. }
  3583. fields_json.push_back(field_json);
  3584. }
  3585. schema_json["fields"] = fields_json;
  3586. view_json["schema"] = schema_json;
  3587. // Add settings
  3588. nlohmann::json create_settings_json = {
  3589. {"is_default", result.view->settings.is_default},
  3590. {"show_in_sidebar", result.view->settings.show_in_sidebar},
  3591. {"show_create_button", result.view->settings.show_create_button},
  3592. {"show_edit_button", result.view->settings.show_edit_button},
  3593. {"icon", result.view->settings.icon},
  3594. {"filters", result.view->settings.filters},
  3595. {"sort", result.view->settings.sort},
  3596. {"quick_create_mode", result.view->settings.quick_create_mode},
  3597. {"quick_edit_mode", result.view->settings.quick_edit_mode}
  3598. };
  3599. if (!result.view->settings.quick_create_fields.empty()) {
  3600. create_settings_json["quick_create_fields"] = result.view->settings.quick_create_fields;
  3601. }
  3602. if (!result.view->settings.quick_edit_fields.empty()) {
  3603. create_settings_json["quick_edit_fields"] = result.view->settings.quick_edit_fields;
  3604. }
  3605. view_json["settings"] = create_settings_json;
  3606. res.status = 201;
  3607. res.set_content(view_json.dump(), "application/json");
  3608. } catch (const std::exception& e) {
  3609. spdlog::error("Create view error: {}", e.what());
  3610. res.status = 500;
  3611. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3612. }
  3613. }
  3614. void HttpServer::HandleListViews(const httplib::Request& req, httplib::Response& res) {
  3615. // Authenticate the request
  3616. auto auth_user = AuthenticateRequest(req);
  3617. if (!auth_user) {
  3618. res.status = 401;
  3619. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3620. return;
  3621. }
  3622. // Extract workspace ID from path
  3623. std::string workspace_id = req.matches[1].str();
  3624. // Verify workspace exists
  3625. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3626. if (!ws_result.success) {
  3627. res.status = 404;
  3628. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3629. return;
  3630. }
  3631. // Check access: must be member OR have system:views:read permission
  3632. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  3633. auth_user->workspace_ids.end(),
  3634. workspace_id) != auth_user->workspace_ids.end());
  3635. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kViewsRead);
  3636. if (!is_member && !has_system_access) {
  3637. res.status = 403;
  3638. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  3639. return;
  3640. }
  3641. // Check if ViewService is available
  3642. if (!viewService_) {
  3643. res.status = 503;
  3644. res.set_content(R"({"error":"View service not available"})", "application/json");
  3645. return;
  3646. }
  3647. try {
  3648. ViewListResult result;
  3649. // Check if filtering by collection
  3650. if (req.has_param("collection")) {
  3651. std::string collection_name = req.get_param_value("collection");
  3652. result = viewService_->ListViewsForCollection(workspace_id, collection_name);
  3653. } else {
  3654. result = viewService_->ListViews(workspace_id);
  3655. }
  3656. if (!result.success) {
  3657. res.status = 500;
  3658. nlohmann::json error_response = {{"error", result.error}};
  3659. res.set_content(error_response.dump(), "application/json");
  3660. return;
  3661. }
  3662. nlohmann::json views_json = nlohmann::json::array();
  3663. for (const auto& view : result.views) {
  3664. nlohmann::json view_json = {
  3665. {"id", view.id},
  3666. {"workspace_id", view.workspace_id},
  3667. {"name", view.name},
  3668. {"collection_name", view.collection_name},
  3669. {"created_at", view.created_at},
  3670. {"updated_at", view.updated_at}
  3671. };
  3672. // Add schema summary (fields count and title)
  3673. view_json["schema"] = {
  3674. {"title", view.schema.title},
  3675. {"field_count", view.schema.fields.size()}
  3676. };
  3677. // Add settings
  3678. nlohmann::json settings_json = {
  3679. {"is_default", view.settings.is_default},
  3680. {"show_in_sidebar", view.settings.show_in_sidebar},
  3681. {"show_create_button", view.settings.show_create_button},
  3682. {"show_edit_button", view.settings.show_edit_button},
  3683. {"icon", view.settings.icon},
  3684. {"quick_create_mode", view.settings.quick_create_mode},
  3685. {"quick_edit_mode", view.settings.quick_edit_mode}
  3686. };
  3687. if (!view.settings.quick_create_fields.empty()) {
  3688. settings_json["quick_create_fields"] = view.settings.quick_create_fields;
  3689. }
  3690. if (!view.settings.quick_edit_fields.empty()) {
  3691. settings_json["quick_edit_fields"] = view.settings.quick_edit_fields;
  3692. }
  3693. view_json["settings"] = settings_json;
  3694. views_json.push_back(view_json);
  3695. }
  3696. nlohmann::json response = {{"views", views_json}};
  3697. res.set_content(response.dump(), "application/json");
  3698. } catch (const std::exception& e) {
  3699. spdlog::error("List views error: {}", e.what());
  3700. res.status = 500;
  3701. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3702. }
  3703. }
  3704. void HttpServer::HandleGetView(const httplib::Request& req, httplib::Response& res) {
  3705. // Authenticate the request
  3706. auto auth_user = AuthenticateRequest(req);
  3707. if (!auth_user) {
  3708. res.status = 401;
  3709. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3710. return;
  3711. }
  3712. // Extract workspace ID and view ID from path
  3713. std::string workspace_id = req.matches[1].str();
  3714. std::string view_id = req.matches[2].str();
  3715. // Verify workspace exists
  3716. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3717. if (!ws_result.success) {
  3718. res.status = 404;
  3719. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3720. return;
  3721. }
  3722. // Check access: must be member OR have system:views:read permission
  3723. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  3724. auth_user->workspace_ids.end(),
  3725. workspace_id) != auth_user->workspace_ids.end());
  3726. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kViewsRead);
  3727. if (!is_member && !has_system_access) {
  3728. res.status = 403;
  3729. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  3730. return;
  3731. }
  3732. // Check if ViewService is available
  3733. if (!viewService_) {
  3734. res.status = 503;
  3735. res.set_content(R"({"error":"View service not available"})", "application/json");
  3736. return;
  3737. }
  3738. try {
  3739. auto result = viewService_->GetView(workspace_id, view_id);
  3740. if (!result.success || !result.view) {
  3741. res.status = 404;
  3742. nlohmann::json error_response = {{"error", result.error}};
  3743. res.set_content(error_response.dump(), "application/json");
  3744. return;
  3745. }
  3746. // Build full response with view info
  3747. nlohmann::json view_json = {
  3748. {"id", result.view->id},
  3749. {"workspace_id", result.view->workspace_id},
  3750. {"name", result.view->name},
  3751. {"collection_name", result.view->collection_name},
  3752. {"created_at", result.view->created_at},
  3753. {"updated_at", result.view->updated_at}
  3754. };
  3755. // Add schema
  3756. nlohmann::json schema_json = {
  3757. {"title", result.view->schema.title},
  3758. {"description", result.view->schema.description},
  3759. {"layout", result.view->schema.layout}
  3760. };
  3761. nlohmann::json fields_json = nlohmann::json::array();
  3762. for (const auto& field : result.view->schema.fields) {
  3763. nlohmann::json field_json = {
  3764. {"name", field.name},
  3765. {"type", FieldTypeToString(field.type)},
  3766. {"label", field.label},
  3767. {"description", field.description},
  3768. {"required", field.required},
  3769. {"display_order", field.display_order},
  3770. {"widget", field.widget},
  3771. {"group", field.group}
  3772. };
  3773. if (!field.default_value.is_null()) {
  3774. field_json["default_value"] = field.default_value;
  3775. }
  3776. if (!field.options.is_null()) {
  3777. field_json["options"] = field.options;
  3778. }
  3779. if (!field.reference_collection.empty()) {
  3780. field_json["reference_collection"] = field.reference_collection;
  3781. }
  3782. if (!field.computed_expression.empty()) {
  3783. field_json["computed_expression"] = field.computed_expression;
  3784. }
  3785. fields_json.push_back(field_json);
  3786. }
  3787. schema_json["fields"] = fields_json;
  3788. view_json["schema"] = schema_json;
  3789. // Add settings
  3790. nlohmann::json settings_json = {
  3791. {"is_default", result.view->settings.is_default},
  3792. {"show_in_sidebar", result.view->settings.show_in_sidebar},
  3793. {"show_create_button", result.view->settings.show_create_button},
  3794. {"show_edit_button", result.view->settings.show_edit_button},
  3795. {"icon", result.view->settings.icon},
  3796. {"filters", result.view->settings.filters},
  3797. {"sort", result.view->settings.sort},
  3798. {"quick_create_mode", result.view->settings.quick_create_mode},
  3799. {"quick_edit_mode", result.view->settings.quick_edit_mode}
  3800. };
  3801. if (!result.view->settings.quick_create_fields.empty()) {
  3802. settings_json["quick_create_fields"] = result.view->settings.quick_create_fields;
  3803. }
  3804. if (!result.view->settings.quick_edit_fields.empty()) {
  3805. settings_json["quick_edit_fields"] = result.view->settings.quick_edit_fields;
  3806. }
  3807. view_json["settings"] = settings_json;
  3808. res.set_content(view_json.dump(), "application/json");
  3809. } catch (const std::exception& e) {
  3810. spdlog::error("Get view error: {}", e.what());
  3811. res.status = 500;
  3812. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3813. }
  3814. }
  3815. void HttpServer::HandleUpdateView(const httplib::Request& req, httplib::Response& res) {
  3816. // Authenticate the request
  3817. auto auth_user = AuthenticateRequest(req);
  3818. if (!auth_user) {
  3819. res.status = 401;
  3820. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3821. return;
  3822. }
  3823. // Extract workspace ID and view ID from path
  3824. std::string workspace_id = req.matches[1].str();
  3825. std::string view_id = req.matches[2].str();
  3826. // Verify workspace exists
  3827. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3828. if (!ws_result.success) {
  3829. res.status = 404;
  3830. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3831. return;
  3832. }
  3833. // Requires system:views:update permission OR workspace membership
  3834. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  3835. auth_user->workspace_ids.end(),
  3836. workspace_id) != auth_user->workspace_ids.end());
  3837. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kViewsUpdate);
  3838. if (!is_member && !has_system_access) {
  3839. res.status = 403;
  3840. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  3841. return;
  3842. }
  3843. // Check if ViewService is available
  3844. if (!viewService_) {
  3845. res.status = 503;
  3846. res.set_content(R"({"error":"View service not available"})", "application/json");
  3847. return;
  3848. }
  3849. // Parse request body
  3850. nlohmann::json body;
  3851. try {
  3852. body = nlohmann::json::parse(req.body);
  3853. } catch (const nlohmann::json::parse_error& /*e*/) {
  3854. res.status = 400;
  3855. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  3856. return;
  3857. }
  3858. try {
  3859. UpdateViewRequest request;
  3860. request.workspace_id = workspace_id;
  3861. request.id = view_id;
  3862. if (body.contains("name") && body["name"].is_string()) {
  3863. request.name = body["name"].get<std::string>();
  3864. }
  3865. if (body.contains("collection_name") && body["collection_name"].is_string()) {
  3866. request.collection_name = body["collection_name"].get<std::string>();
  3867. }
  3868. // Parse schema if provided
  3869. if (body.contains("schema") && body["schema"].is_object()) {
  3870. ViewSchema schema;
  3871. const auto& schema_json = body["schema"];
  3872. schema.title = schema_json.value("title", "");
  3873. schema.description = schema_json.value("description", "");
  3874. schema.layout = schema_json.value("layout", nlohmann::json::object());
  3875. if (schema_json.contains("fields") && schema_json["fields"].is_array()) {
  3876. for (const auto& field_json : schema_json["fields"]) {
  3877. SchemaField field;
  3878. field.name = field_json.value("name", "");
  3879. field.group = field_json.value("group", "");
  3880. // Validate field name - names starting with "_" are reserved for system fields
  3881. if (!field.name.empty() && field.name[0] == '_' && field.group != "_system") {
  3882. res.status = 400;
  3883. res.set_content(R"({"error":"Field names starting with '_' are reserved for system fields"})", "application/json");
  3884. return;
  3885. }
  3886. field.type = StringToFieldType(field_json.value("type", "text"));
  3887. field.label = field_json.value("label", "");
  3888. field.description = field_json.value("description", "");
  3889. field.required = field_json.value("required", false);
  3890. field.display_order = field_json.value("display_order", 0);
  3891. field.widget = field_json.value("widget", "");
  3892. field.default_value = field_json.value("default_value", nlohmann::json());
  3893. field.options = field_json.value("options", nlohmann::json());
  3894. field.reference_collection = field_json.value("reference_collection", "");
  3895. field.computed_expression = field_json.value("computed_expression", "");
  3896. schema.fields.push_back(field);
  3897. }
  3898. }
  3899. request.schema = schema;
  3900. }
  3901. // Parse settings if provided
  3902. if (body.contains("settings") && body["settings"].is_object()) {
  3903. ViewSettings settings;
  3904. const auto& settings_json = body["settings"];
  3905. settings.is_default = settings_json.value("is_default", false);
  3906. settings.show_in_sidebar = settings_json.value("show_in_sidebar", true);
  3907. settings.show_create_button = settings_json.value("show_create_button", true);
  3908. settings.icon = settings_json.value("icon", "");
  3909. settings.filters = settings_json.value("filters", nlohmann::json::object());
  3910. settings.sort = settings_json.value("sort", nlohmann::json::object());
  3911. settings.quick_create_mode = settings_json.value("quick_create_mode", "modal");
  3912. settings.quick_edit_mode = settings_json.value("quick_edit_mode", "modal");
  3913. settings.show_edit_button = settings_json.value("show_edit_button", true);
  3914. if (settings_json.contains("quick_create_fields") && settings_json["quick_create_fields"].is_array()) {
  3915. for (const auto& field : settings_json["quick_create_fields"]) {
  3916. if (field.is_string()) {
  3917. settings.quick_create_fields.push_back(field.get<std::string>());
  3918. }
  3919. }
  3920. }
  3921. if (settings_json.contains("quick_edit_fields") && settings_json["quick_edit_fields"].is_array()) {
  3922. for (const auto& field : settings_json["quick_edit_fields"]) {
  3923. if (field.is_string()) {
  3924. settings.quick_edit_fields.push_back(field.get<std::string>());
  3925. }
  3926. }
  3927. }
  3928. request.settings = settings;
  3929. }
  3930. auto result = viewService_->UpdateView(request);
  3931. if (!result.success || !result.view) {
  3932. res.status = 400;
  3933. nlohmann::json error_response = {{"error", result.error}};
  3934. res.set_content(error_response.dump(), "application/json");
  3935. return;
  3936. }
  3937. // Build response with updated view info
  3938. nlohmann::json view_json = {
  3939. {"id", result.view->id},
  3940. {"workspace_id", result.view->workspace_id},
  3941. {"name", result.view->name},
  3942. {"collection_name", result.view->collection_name},
  3943. {"created_at", result.view->created_at},
  3944. {"updated_at", result.view->updated_at}
  3945. };
  3946. // Add schema
  3947. nlohmann::json schema_json = {
  3948. {"title", result.view->schema.title},
  3949. {"description", result.view->schema.description},
  3950. {"layout", result.view->schema.layout}
  3951. };
  3952. nlohmann::json fields_json = nlohmann::json::array();
  3953. for (const auto& field : result.view->schema.fields) {
  3954. nlohmann::json field_json = {
  3955. {"name", field.name},
  3956. {"type", FieldTypeToString(field.type)},
  3957. {"label", field.label},
  3958. {"description", field.description},
  3959. {"required", field.required},
  3960. {"display_order", field.display_order},
  3961. {"widget", field.widget},
  3962. {"group", field.group}
  3963. };
  3964. if (!field.default_value.is_null()) {
  3965. field_json["default_value"] = field.default_value;
  3966. }
  3967. if (!field.options.is_null()) {
  3968. field_json["options"] = field.options;
  3969. }
  3970. if (!field.reference_collection.empty()) {
  3971. field_json["reference_collection"] = field.reference_collection;
  3972. }
  3973. if (!field.computed_expression.empty()) {
  3974. field_json["computed_expression"] = field.computed_expression;
  3975. }
  3976. fields_json.push_back(field_json);
  3977. }
  3978. schema_json["fields"] = fields_json;
  3979. view_json["schema"] = schema_json;
  3980. // Add settings
  3981. nlohmann::json settings_json = {
  3982. {"is_default", result.view->settings.is_default},
  3983. {"show_in_sidebar", result.view->settings.show_in_sidebar},
  3984. {"show_create_button", result.view->settings.show_create_button},
  3985. {"show_edit_button", result.view->settings.show_edit_button},
  3986. {"icon", result.view->settings.icon},
  3987. {"filters", result.view->settings.filters},
  3988. {"sort", result.view->settings.sort},
  3989. {"quick_create_mode", result.view->settings.quick_create_mode},
  3990. {"quick_edit_mode", result.view->settings.quick_edit_mode}
  3991. };
  3992. if (!result.view->settings.quick_create_fields.empty()) {
  3993. settings_json["quick_create_fields"] = result.view->settings.quick_create_fields;
  3994. }
  3995. if (!result.view->settings.quick_edit_fields.empty()) {
  3996. settings_json["quick_edit_fields"] = result.view->settings.quick_edit_fields;
  3997. }
  3998. view_json["settings"] = settings_json;
  3999. res.set_content(view_json.dump(), "application/json");
  4000. } catch (const std::exception& e) {
  4001. spdlog::error("Update view error: {}", e.what());
  4002. res.status = 500;
  4003. res.set_content(R"({"error":"Internal server error"})", "application/json");
  4004. }
  4005. }
  4006. void HttpServer::HandleDeleteView(const httplib::Request& req, httplib::Response& res) {
  4007. // Authenticate the request
  4008. auto auth_user = AuthenticateRequest(req);
  4009. if (!auth_user) {
  4010. res.status = 401;
  4011. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  4012. return;
  4013. }
  4014. // Extract workspace ID and view ID from path
  4015. std::string workspace_id = req.matches[1].str();
  4016. std::string view_id = req.matches[2].str();
  4017. // Verify workspace exists
  4018. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  4019. if (!ws_result.success) {
  4020. res.status = 404;
  4021. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  4022. return;
  4023. }
  4024. // Requires system:views:delete permission OR workspace membership
  4025. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  4026. auth_user->workspace_ids.end(),
  4027. workspace_id) != auth_user->workspace_ids.end());
  4028. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kViewsDelete);
  4029. if (!is_member && !has_system_access) {
  4030. res.status = 403;
  4031. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  4032. return;
  4033. }
  4034. // Check if ViewService is available
  4035. if (!viewService_) {
  4036. res.status = 503;
  4037. res.set_content(R"({"error":"View service not available"})", "application/json");
  4038. return;
  4039. }
  4040. try {
  4041. auto result = viewService_->DeleteView(workspace_id, view_id);
  4042. if (!result.success) {
  4043. res.status = 404;
  4044. nlohmann::json error_response = {{"error", result.error}};
  4045. res.set_content(error_response.dump(), "application/json");
  4046. return;
  4047. }
  4048. res.set_content(R"({"message":"View deleted successfully"})", "application/json");
  4049. } catch (const std::exception& e) {
  4050. spdlog::error("Delete view error: {}", e.what());
  4051. res.status = 500;
  4052. res.set_content(R"({"error":"Internal server error"})", "application/json");
  4053. }
  4054. }
  4055. // ============================================================================
  4056. // Page Routes
  4057. // ============================================================================
  4058. void HttpServer::SetupPageRoutes() {
  4059. // POST /api/workspaces/:workspace_id/pages - Create a new page
  4060. httpServer_->Post(R"(/api/workspaces/([^/]+)/pages$)",
  4061. [this](const httplib::Request& req, httplib::Response& res) {
  4062. HandleCreatePage(req, res);
  4063. });
  4064. // GET /api/workspaces/:workspace_id/pages - List all pages
  4065. httpServer_->Get(R"(/api/workspaces/([^/]+)/pages$)",
  4066. [this](const httplib::Request& req, httplib::Response& res) {
  4067. HandleListPages(req, res);
  4068. });
  4069. // GET /api/workspaces/:workspace_id/pages/sidebar - List sidebar pages
  4070. httpServer_->Get(R"(/api/workspaces/([^/]+)/pages/sidebar$)",
  4071. [this](const httplib::Request& req, httplib::Response& res) {
  4072. HandleListSidebarPages(req, res);
  4073. });
  4074. // GET /api/workspaces/:workspace_id/pages/slug/:slug - Get page by slug
  4075. httpServer_->Get(R"(/api/workspaces/([^/]+)/pages/slug/([^/]+)$)",
  4076. [this](const httplib::Request& req, httplib::Response& res) {
  4077. HandleGetPageBySlug(req, res);
  4078. });
  4079. // GET /api/workspaces/:workspace_id/pages/:page_id - Get a specific page
  4080. httpServer_->Get(R"(/api/workspaces/([^/]+)/pages/([^/]+)$)",
  4081. [this](const httplib::Request& req, httplib::Response& res) {
  4082. HandleGetPage(req, res);
  4083. });
  4084. // PATCH /api/workspaces/:workspace_id/pages/:page_id - Update a page
  4085. httpServer_->Patch(R"(/api/workspaces/([^/]+)/pages/([^/]+)$)",
  4086. [this](const httplib::Request& req, httplib::Response& res) {
  4087. HandleUpdatePage(req, res);
  4088. });
  4089. // PATCH /api/workspaces/:workspace_id/pages/:page_id/share - Update page sharing
  4090. httpServer_->Patch(R"(/api/workspaces/([^/]+)/pages/([^/]+)/share$)",
  4091. [this](const httplib::Request& req, httplib::Response& res) {
  4092. HandleUpdatePageSharing(req, res);
  4093. });
  4094. // DELETE /api/workspaces/:workspace_id/pages/:page_id - Delete a page
  4095. httpServer_->Delete(R"(/api/workspaces/([^/]+)/pages/([^/]+)$)",
  4096. [this](const httplib::Request& req, httplib::Response& res) {
  4097. HandleDeletePage(req, res);
  4098. });
  4099. spdlog::info("Page routes configured");
  4100. }
  4101. void HttpServer::HandleCreatePage(const httplib::Request& req, httplib::Response& res) {
  4102. // Authenticate the request
  4103. auto auth_user = AuthenticateRequest(req);
  4104. if (!auth_user) {
  4105. res.status = 401;
  4106. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  4107. return;
  4108. }
  4109. // Extract workspace ID from path
  4110. std::string workspace_id = req.matches[1].str();
  4111. // Verify workspace exists
  4112. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  4113. if (!ws_result.success) {
  4114. res.status = 404;
  4115. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  4116. return;
  4117. }
  4118. // Check permission to create pages
  4119. if (!authorizationService_->CanCreatePage(*auth_user, workspace_id)) {
  4120. res.status = 403;
  4121. res.set_content(R"({"error":"Forbidden - insufficient permissions to create pages"})", "application/json");
  4122. return;
  4123. }
  4124. // Check if PageService is available
  4125. if (!pageService_) {
  4126. res.status = 503;
  4127. res.set_content(R"({"error":"Page service not available"})", "application/json");
  4128. return;
  4129. }
  4130. // Parse request body
  4131. nlohmann::json body;
  4132. try {
  4133. body = nlohmann::json::parse(req.body);
  4134. } catch (const nlohmann::json::parse_error& /*e*/) {
  4135. res.status = 400;
  4136. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  4137. return;
  4138. }
  4139. // Validate required fields
  4140. if (!body.contains("name") || !body["name"].is_string()) {
  4141. res.status = 400;
  4142. res.set_content(R"({"error":"name is required"})", "application/json");
  4143. return;
  4144. }
  4145. try {
  4146. CreatePageRequest request;
  4147. request.workspace_id = workspace_id;
  4148. request.name = body["name"].get<std::string>();
  4149. request.slug = body.value("slug", "");
  4150. request.created_by = auth_user->user_id; // Set owner to current user
  4151. // Parse layout if provided
  4152. if (body.contains("layout") && body["layout"].is_object()) {
  4153. const auto& layout_json = body["layout"];
  4154. request.layout.version = layout_json.value("version", 1);
  4155. request.layout.grid_columns = layout_json.value("grid_columns", 12);
  4156. if (layout_json.contains("components") && layout_json["components"].is_array()) {
  4157. for (const auto& comp_json : layout_json["components"]) {
  4158. LayoutComponent comp;
  4159. comp.id = comp_json.value("id", "");
  4160. comp.type = comp_json.value("type", "");
  4161. comp.config = comp_json.value("config", nlohmann::json::object());
  4162. if (comp_json.contains("position") && comp_json["position"].is_object()) {
  4163. const auto& pos = comp_json["position"];
  4164. comp.position.x = pos.value("x", 0);
  4165. comp.position.y = pos.value("y", 0);
  4166. comp.position.width = pos.value("width", 12);
  4167. comp.position.height = pos.value("height", 1);
  4168. }
  4169. request.layout.components.push_back(comp);
  4170. }
  4171. }
  4172. }
  4173. // Parse settings if provided
  4174. if (body.contains("settings") && body["settings"].is_object()) {
  4175. const auto& settings_json = body["settings"];
  4176. request.settings.show_in_sidebar = settings_json.value("show_in_sidebar", true);
  4177. request.settings.icon = settings_json.value("icon", "");
  4178. request.settings.menu_order = settings_json.value("menu_order", 0);
  4179. }
  4180. auto result = pageService_->CreatePage(request);
  4181. if (!result.success) {
  4182. res.status = 400;
  4183. nlohmann::json error_response = {{"error", result.error}};
  4184. res.set_content(error_response.dump(), "application/json");
  4185. return;
  4186. }
  4187. // Build response with page info
  4188. nlohmann::json page_json = {
  4189. {"id", result.page->id},
  4190. {"workspace_id", result.page->workspace_id},
  4191. {"name", result.page->name},
  4192. {"slug", result.page->slug},
  4193. {"created_at", result.page->created_at},
  4194. {"updated_at", result.page->updated_at},
  4195. {"created_by", result.page->created_by},
  4196. {"shared_with_groups", result.page->shared_with_groups}
  4197. };
  4198. // Add layout
  4199. nlohmann::json layout_json = {
  4200. {"version", result.page->layout.version},
  4201. {"grid_columns", result.page->layout.grid_columns}
  4202. };
  4203. nlohmann::json components_json = nlohmann::json::array();
  4204. for (const auto& comp : result.page->layout.components) {
  4205. nlohmann::json comp_json = {
  4206. {"id", comp.id},
  4207. {"type", comp.type},
  4208. {"position", {
  4209. {"x", comp.position.x},
  4210. {"y", comp.position.y},
  4211. {"width", comp.position.width},
  4212. {"height", comp.position.height}
  4213. }},
  4214. {"config", comp.config}
  4215. };
  4216. components_json.push_back(comp_json);
  4217. }
  4218. layout_json["components"] = components_json;
  4219. page_json["layout"] = layout_json;
  4220. // Add settings
  4221. page_json["settings"] = {
  4222. {"show_in_sidebar", result.page->settings.show_in_sidebar},
  4223. {"icon", result.page->settings.icon},
  4224. {"menu_order", result.page->settings.menu_order}
  4225. };
  4226. res.status = 201;
  4227. res.set_content(page_json.dump(), "application/json");
  4228. } catch (const std::exception& e) {
  4229. spdlog::error("Create page error: {}", e.what());
  4230. res.status = 500;
  4231. res.set_content(R"({"error":"Internal server error"})", "application/json");
  4232. }
  4233. }
  4234. void HttpServer::HandleListPages(const httplib::Request& req, httplib::Response& res) {
  4235. // Authenticate the request
  4236. auto auth_user = AuthenticateRequest(req);
  4237. if (!auth_user) {
  4238. res.status = 401;
  4239. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  4240. return;
  4241. }
  4242. // Extract workspace ID from path
  4243. std::string workspace_id = req.matches[1].str();
  4244. // Verify workspace exists
  4245. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  4246. if (!ws_result.success) {
  4247. res.status = 404;
  4248. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  4249. return;
  4250. }
  4251. // Check if PageService is available
  4252. if (!pageService_) {
  4253. res.status = 503;
  4254. res.set_content(R"({"error":"Page service not available"})", "application/json");
  4255. return;
  4256. }
  4257. try {
  4258. auto result = pageService_->ListPages(workspace_id);
  4259. if (!result.success) {
  4260. res.status = 500;
  4261. nlohmann::json error_response = {{"error", result.error}};
  4262. res.set_content(error_response.dump(), "application/json");
  4263. return;
  4264. }
  4265. // Filter pages based on user permissions
  4266. nlohmann::json pages_json = nlohmann::json::array();
  4267. for (const auto& page : result.pages) {
  4268. // Check if user can view this page
  4269. if (!authorizationService_->CanViewPage(*auth_user, workspace_id,
  4270. page.created_by, page.shared_with_groups)) {
  4271. continue; // Skip pages user cannot view
  4272. }
  4273. nlohmann::json page_json = {
  4274. {"id", page.id},
  4275. {"workspace_id", page.workspace_id},
  4276. {"name", page.name},
  4277. {"slug", page.slug},
  4278. {"created_at", page.created_at},
  4279. {"updated_at", page.updated_at},
  4280. {"created_by", page.created_by},
  4281. {"shared_with_groups", page.shared_with_groups},
  4282. {"settings", {
  4283. {"show_in_sidebar", page.settings.show_in_sidebar},
  4284. {"icon", page.settings.icon},
  4285. {"menu_order", page.settings.menu_order}
  4286. }}
  4287. };
  4288. pages_json.push_back(page_json);
  4289. }
  4290. nlohmann::json response = {{"pages", pages_json}};
  4291. res.set_content(response.dump(), "application/json");
  4292. } catch (const std::exception& e) {
  4293. spdlog::error("List pages error: {}", e.what());
  4294. res.status = 500;
  4295. res.set_content(R"({"error":"Internal server error"})", "application/json");
  4296. }
  4297. }
  4298. void HttpServer::HandleListSidebarPages(const httplib::Request& req, httplib::Response& res) {
  4299. // Authenticate the request
  4300. auto auth_user = AuthenticateRequest(req);
  4301. if (!auth_user) {
  4302. res.status = 401;
  4303. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  4304. return;
  4305. }
  4306. // Extract workspace ID from path
  4307. std::string workspace_id = req.matches[1].str();
  4308. // Verify workspace exists
  4309. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  4310. if (!ws_result.success) {
  4311. res.status = 404;
  4312. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  4313. return;
  4314. }
  4315. // Check if PageService is available
  4316. if (!pageService_) {
  4317. res.status = 503;
  4318. res.set_content(R"({"error":"Page service not available"})", "application/json");
  4319. return;
  4320. }
  4321. try {
  4322. auto result = pageService_->ListSidebarPages(workspace_id);
  4323. if (!result.success) {
  4324. res.status = 500;
  4325. nlohmann::json error_response = {{"error", result.error}};
  4326. res.set_content(error_response.dump(), "application/json");
  4327. return;
  4328. }
  4329. // Filter pages based on user permissions
  4330. nlohmann::json pages_json = nlohmann::json::array();
  4331. for (const auto& page : result.pages) {
  4332. // Check if user can view this page
  4333. if (!authorizationService_->CanViewPage(*auth_user, workspace_id,
  4334. page.created_by, page.shared_with_groups)) {
  4335. continue; // Skip pages user cannot view
  4336. }
  4337. nlohmann::json page_json = {
  4338. {"id", page.id},
  4339. {"workspace_id", page.workspace_id},
  4340. {"name", page.name},
  4341. {"slug", page.slug},
  4342. {"created_by", page.created_by},
  4343. {"settings", {
  4344. {"show_in_sidebar", page.settings.show_in_sidebar},
  4345. {"icon", page.settings.icon},
  4346. {"menu_order", page.settings.menu_order}
  4347. }}
  4348. };
  4349. pages_json.push_back(page_json);
  4350. }
  4351. nlohmann::json response = {{"pages", pages_json}};
  4352. res.set_content(response.dump(), "application/json");
  4353. } catch (const std::exception& e) {
  4354. spdlog::error("List sidebar pages error: {}", e.what());
  4355. res.status = 500;
  4356. res.set_content(R"({"error":"Internal server error"})", "application/json");
  4357. }
  4358. }
  4359. void HttpServer::HandleGetPageBySlug(const httplib::Request& req, httplib::Response& res) {
  4360. // Authenticate the request
  4361. auto auth_user = AuthenticateRequest(req);
  4362. if (!auth_user) {
  4363. res.status = 401;
  4364. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  4365. return;
  4366. }
  4367. // Extract workspace ID and slug from path
  4368. std::string workspace_id = req.matches[1].str();
  4369. std::string slug = req.matches[2].str();
  4370. // Check if PageService is available
  4371. if (!pageService_) {
  4372. res.status = 503;
  4373. res.set_content(R"({"error":"Page service not available"})", "application/json");
  4374. return;
  4375. }
  4376. try {
  4377. auto result = pageService_->GetPageBySlug(workspace_id, slug);
  4378. if (!result.success) {
  4379. res.status = 404;
  4380. nlohmann::json error_response = {{"error", result.error}};
  4381. res.set_content(error_response.dump(), "application/json");
  4382. return;
  4383. }
  4384. // Check if user can view this page
  4385. if (!authorizationService_->CanViewPage(*auth_user, workspace_id,
  4386. result.page->created_by, result.page->shared_with_groups)) {
  4387. res.status = 403;
  4388. res.set_content(R"({"error":"Forbidden - no access to this page"})", "application/json");
  4389. return;
  4390. }
  4391. // Build full response with layout
  4392. nlohmann::json page_json = {
  4393. {"id", result.page->id},
  4394. {"workspace_id", result.page->workspace_id},
  4395. {"name", result.page->name},
  4396. {"slug", result.page->slug},
  4397. {"created_at", result.page->created_at},
  4398. {"updated_at", result.page->updated_at},
  4399. {"created_by", result.page->created_by},
  4400. {"shared_with_groups", result.page->shared_with_groups}
  4401. };
  4402. // Add layout
  4403. nlohmann::json layout_json = {
  4404. {"version", result.page->layout.version},
  4405. {"grid_columns", result.page->layout.grid_columns}
  4406. };
  4407. nlohmann::json components_json = nlohmann::json::array();
  4408. for (const auto& comp : result.page->layout.components) {
  4409. nlohmann::json comp_json = {
  4410. {"id", comp.id},
  4411. {"type", comp.type},
  4412. {"position", {
  4413. {"x", comp.position.x},
  4414. {"y", comp.position.y},
  4415. {"width", comp.position.width},
  4416. {"height", comp.position.height}
  4417. }},
  4418. {"config", comp.config}
  4419. };
  4420. components_json.push_back(comp_json);
  4421. }
  4422. layout_json["components"] = components_json;
  4423. page_json["layout"] = layout_json;
  4424. // Add settings
  4425. page_json["settings"] = {
  4426. {"show_in_sidebar", result.page->settings.show_in_sidebar},
  4427. {"icon", result.page->settings.icon},
  4428. {"menu_order", result.page->settings.menu_order}
  4429. };
  4430. res.set_content(page_json.dump(), "application/json");
  4431. } catch (const std::exception& e) {
  4432. spdlog::error("Get page by slug error: {}", e.what());
  4433. res.status = 500;
  4434. res.set_content(R"({"error":"Internal server error"})", "application/json");
  4435. }
  4436. }
  4437. void HttpServer::HandleGetPage(const httplib::Request& req, httplib::Response& res) {
  4438. // Authenticate the request
  4439. auto auth_user = AuthenticateRequest(req);
  4440. if (!auth_user) {
  4441. res.status = 401;
  4442. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  4443. return;
  4444. }
  4445. // Extract workspace ID and page ID from path
  4446. std::string workspace_id = req.matches[1].str();
  4447. std::string page_id = req.matches[2].str();
  4448. // Check if PageService is available
  4449. if (!pageService_) {
  4450. res.status = 503;
  4451. res.set_content(R"({"error":"Page service not available"})", "application/json");
  4452. return;
  4453. }
  4454. try {
  4455. auto result = pageService_->GetPage(workspace_id, page_id);
  4456. if (!result.success) {
  4457. res.status = 404;
  4458. nlohmann::json error_response = {{"error", result.error}};
  4459. res.set_content(error_response.dump(), "application/json");
  4460. return;
  4461. }
  4462. // Check if user can view this page
  4463. if (!authorizationService_->CanViewPage(*auth_user, workspace_id,
  4464. result.page->created_by, result.page->shared_with_groups)) {
  4465. res.status = 403;
  4466. res.set_content(R"({"error":"Forbidden - no access to this page"})", "application/json");
  4467. return;
  4468. }
  4469. // Build full response with layout
  4470. nlohmann::json page_json = {
  4471. {"id", result.page->id},
  4472. {"workspace_id", result.page->workspace_id},
  4473. {"name", result.page->name},
  4474. {"slug", result.page->slug},
  4475. {"created_at", result.page->created_at},
  4476. {"updated_at", result.page->updated_at},
  4477. {"created_by", result.page->created_by},
  4478. {"shared_with_groups", result.page->shared_with_groups}
  4479. };
  4480. // Add layout
  4481. nlohmann::json layout_json = {
  4482. {"version", result.page->layout.version},
  4483. {"grid_columns", result.page->layout.grid_columns}
  4484. };
  4485. nlohmann::json components_json = nlohmann::json::array();
  4486. for (const auto& comp : result.page->layout.components) {
  4487. nlohmann::json comp_json = {
  4488. {"id", comp.id},
  4489. {"type", comp.type},
  4490. {"position", {
  4491. {"x", comp.position.x},
  4492. {"y", comp.position.y},
  4493. {"width", comp.position.width},
  4494. {"height", comp.position.height}
  4495. }},
  4496. {"config", comp.config}
  4497. };
  4498. components_json.push_back(comp_json);
  4499. }
  4500. layout_json["components"] = components_json;
  4501. page_json["layout"] = layout_json;
  4502. // Add settings
  4503. page_json["settings"] = {
  4504. {"show_in_sidebar", result.page->settings.show_in_sidebar},
  4505. {"icon", result.page->settings.icon},
  4506. {"menu_order", result.page->settings.menu_order}
  4507. };
  4508. res.set_content(page_json.dump(), "application/json");
  4509. } catch (const std::exception& e) {
  4510. spdlog::error("Get page error: {}", e.what());
  4511. res.status = 500;
  4512. res.set_content(R"({"error":"Internal server error"})", "application/json");
  4513. }
  4514. }
  4515. void HttpServer::HandleUpdatePage(const httplib::Request& req, httplib::Response& res) {
  4516. // Authenticate the request
  4517. auto auth_user = AuthenticateRequest(req);
  4518. if (!auth_user) {
  4519. res.status = 401;
  4520. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  4521. return;
  4522. }
  4523. // Extract workspace ID and page ID from path
  4524. std::string workspace_id = req.matches[1].str();
  4525. std::string page_id = req.matches[2].str();
  4526. // Check if PageService is available
  4527. if (!pageService_) {
  4528. res.status = 503;
  4529. res.set_content(R"({"error":"Page service not available"})", "application/json");
  4530. return;
  4531. }
  4532. // Get existing page to check ownership
  4533. auto existing = pageService_->GetPage(workspace_id, page_id);
  4534. if (!existing.success || !existing.page) {
  4535. res.status = 404;
  4536. res.set_content(R"({"error":"Page not found"})", "application/json");
  4537. return;
  4538. }
  4539. // Check permission to edit
  4540. if (!authorizationService_->CanEditPage(*auth_user, workspace_id, existing.page->created_by)) {
  4541. res.status = 403;
  4542. res.set_content(R"({"error":"Forbidden - insufficient permissions to edit this page"})", "application/json");
  4543. return;
  4544. }
  4545. // Parse request body
  4546. nlohmann::json body;
  4547. try {
  4548. body = nlohmann::json::parse(req.body);
  4549. } catch (const nlohmann::json::parse_error& /*e*/) {
  4550. res.status = 400;
  4551. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  4552. return;
  4553. }
  4554. try {
  4555. UpdatePageRequest request;
  4556. request.workspace_id = workspace_id;
  4557. request.id = page_id;
  4558. if (body.contains("name") && body["name"].is_string()) {
  4559. request.name = body["name"].get<std::string>();
  4560. }
  4561. if (body.contains("slug") && body["slug"].is_string()) {
  4562. request.slug = body["slug"].get<std::string>();
  4563. }
  4564. // Parse layout if provided
  4565. if (body.contains("layout") && body["layout"].is_object()) {
  4566. PageLayout layout;
  4567. const auto& layout_json = body["layout"];
  4568. layout.version = layout_json.value("version", 1);
  4569. layout.grid_columns = layout_json.value("grid_columns", 12);
  4570. if (layout_json.contains("components") && layout_json["components"].is_array()) {
  4571. for (const auto& comp_json : layout_json["components"]) {
  4572. LayoutComponent comp;
  4573. comp.id = comp_json.value("id", "");
  4574. comp.type = comp_json.value("type", "");
  4575. comp.config = comp_json.value("config", nlohmann::json::object());
  4576. if (comp_json.contains("position") && comp_json["position"].is_object()) {
  4577. const auto& pos = comp_json["position"];
  4578. comp.position.x = pos.value("x", 0);
  4579. comp.position.y = pos.value("y", 0);
  4580. comp.position.width = pos.value("width", 12);
  4581. comp.position.height = pos.value("height", 1);
  4582. }
  4583. layout.components.push_back(comp);
  4584. }
  4585. }
  4586. request.layout = layout;
  4587. }
  4588. // Parse settings if provided
  4589. if (body.contains("settings") && body["settings"].is_object()) {
  4590. PageSettings settings;
  4591. const auto& settings_json = body["settings"];
  4592. settings.show_in_sidebar = settings_json.value("show_in_sidebar", true);
  4593. settings.icon = settings_json.value("icon", "");
  4594. settings.menu_order = settings_json.value("menu_order", 0);
  4595. request.settings = settings;
  4596. }
  4597. auto result = pageService_->UpdatePage(request);
  4598. if (!result.success) {
  4599. res.status = 400;
  4600. nlohmann::json error_response = {{"error", result.error}};
  4601. res.set_content(error_response.dump(), "application/json");
  4602. return;
  4603. }
  4604. // Build response with page info
  4605. nlohmann::json page_json = {
  4606. {"id", result.page->id},
  4607. {"workspace_id", result.page->workspace_id},
  4608. {"name", result.page->name},
  4609. {"slug", result.page->slug},
  4610. {"created_at", result.page->created_at},
  4611. {"updated_at", result.page->updated_at},
  4612. {"created_by", result.page->created_by},
  4613. {"shared_with_groups", result.page->shared_with_groups}
  4614. };
  4615. // Add layout
  4616. nlohmann::json layout_json = {
  4617. {"version", result.page->layout.version},
  4618. {"grid_columns", result.page->layout.grid_columns}
  4619. };
  4620. nlohmann::json components_json = nlohmann::json::array();
  4621. for (const auto& comp : result.page->layout.components) {
  4622. nlohmann::json comp_json = {
  4623. {"id", comp.id},
  4624. {"type", comp.type},
  4625. {"position", {
  4626. {"x", comp.position.x},
  4627. {"y", comp.position.y},
  4628. {"width", comp.position.width},
  4629. {"height", comp.position.height}
  4630. }},
  4631. {"config", comp.config}
  4632. };
  4633. components_json.push_back(comp_json);
  4634. }
  4635. layout_json["components"] = components_json;
  4636. page_json["layout"] = layout_json;
  4637. // Add settings
  4638. page_json["settings"] = {
  4639. {"show_in_sidebar", result.page->settings.show_in_sidebar},
  4640. {"icon", result.page->settings.icon},
  4641. {"menu_order", result.page->settings.menu_order}
  4642. };
  4643. res.set_content(page_json.dump(), "application/json");
  4644. } catch (const std::exception& e) {
  4645. spdlog::error("Update page error: {}", e.what());
  4646. res.status = 500;
  4647. res.set_content(R"({"error":"Internal server error"})", "application/json");
  4648. }
  4649. }
  4650. void HttpServer::HandleUpdatePageSharing(const httplib::Request& req, httplib::Response& res) {
  4651. // Authenticate the request
  4652. auto auth_user = AuthenticateRequest(req);
  4653. if (!auth_user) {
  4654. res.status = 401;
  4655. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  4656. return;
  4657. }
  4658. // Extract workspace ID and page ID from path
  4659. std::string workspace_id = req.matches[1].str();
  4660. std::string page_id = req.matches[2].str();
  4661. // Check if PageService is available
  4662. if (!pageService_) {
  4663. res.status = 503;
  4664. res.set_content(R"({"error":"Page service not available"})", "application/json");
  4665. return;
  4666. }
  4667. // Get existing page to check ownership
  4668. auto existing = pageService_->GetPage(workspace_id, page_id);
  4669. if (!existing.success || !existing.page) {
  4670. res.status = 404;
  4671. res.set_content(R"({"error":"Page not found"})", "application/json");
  4672. return;
  4673. }
  4674. // Check permission to share
  4675. if (!authorizationService_->CanSharePage(*auth_user, workspace_id, existing.page->created_by)) {
  4676. res.status = 403;
  4677. res.set_content(R"({"error":"Forbidden - insufficient permissions to share this page"})", "application/json");
  4678. return;
  4679. }
  4680. // Parse request body
  4681. nlohmann::json body;
  4682. try {
  4683. body = nlohmann::json::parse(req.body);
  4684. } catch (const nlohmann::json::parse_error& /*e*/) {
  4685. res.status = 400;
  4686. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  4687. return;
  4688. }
  4689. // Validate shared_with_groups field
  4690. if (!body.contains("shared_with_groups") || !body["shared_with_groups"].is_array()) {
  4691. res.status = 400;
  4692. res.set_content(R"({"error":"shared_with_groups array is required"})", "application/json");
  4693. return;
  4694. }
  4695. try {
  4696. std::vector<std::string> shared_with_groups;
  4697. for (const auto& group : body["shared_with_groups"]) {
  4698. if (group.is_string()) {
  4699. shared_with_groups.push_back(group.get<std::string>());
  4700. }
  4701. }
  4702. auto result = pageService_->UpdatePageSharing(workspace_id, page_id, shared_with_groups);
  4703. if (!result.success) {
  4704. res.status = 400;
  4705. nlohmann::json error_response = {{"error", result.error}};
  4706. res.set_content(error_response.dump(), "application/json");
  4707. return;
  4708. }
  4709. // Build response
  4710. nlohmann::json response = {
  4711. {"id", result.page->id},
  4712. {"shared_with_groups", result.page->shared_with_groups},
  4713. {"message", "Page sharing updated successfully"}
  4714. };
  4715. res.set_content(response.dump(), "application/json");
  4716. } catch (const std::exception& e) {
  4717. spdlog::error("Update page sharing error: {}", e.what());
  4718. res.status = 500;
  4719. res.set_content(R"({"error":"Internal server error"})", "application/json");
  4720. }
  4721. }
  4722. void HttpServer::HandleDeletePage(const httplib::Request& req, httplib::Response& res) {
  4723. // Authenticate the request
  4724. auto auth_user = AuthenticateRequest(req);
  4725. if (!auth_user) {
  4726. res.status = 401;
  4727. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  4728. return;
  4729. }
  4730. // Extract workspace ID and page ID from path
  4731. std::string workspace_id = req.matches[1].str();
  4732. std::string page_id = req.matches[2].str();
  4733. // Check if PageService is available
  4734. if (!pageService_) {
  4735. res.status = 503;
  4736. res.set_content(R"({"error":"Page service not available"})", "application/json");
  4737. return;
  4738. }
  4739. // Get existing page to check ownership
  4740. auto existing = pageService_->GetPage(workspace_id, page_id);
  4741. if (!existing.success || !existing.page) {
  4742. res.status = 404;
  4743. res.set_content(R"({"error":"Page not found"})", "application/json");
  4744. return;
  4745. }
  4746. // Check permission to delete
  4747. if (!authorizationService_->CanDeletePage(*auth_user, workspace_id, existing.page->created_by)) {
  4748. res.status = 403;
  4749. res.set_content(R"({"error":"Forbidden - insufficient permissions to delete this page"})", "application/json");
  4750. return;
  4751. }
  4752. try {
  4753. auto result = pageService_->DeletePage(workspace_id, page_id);
  4754. if (!result.success) {
  4755. res.status = 404;
  4756. nlohmann::json error_response = {{"error", result.error}};
  4757. res.set_content(error_response.dump(), "application/json");
  4758. return;
  4759. }
  4760. res.set_content(R"({"message":"Page deleted successfully"})", "application/json");
  4761. } catch (const std::exception& e) {
  4762. spdlog::error("Delete page error: {}", e.what());
  4763. res.status = 500;
  4764. res.set_content(R"({"error":"Internal server error"})", "application/json");
  4765. }
  4766. }
  4767. // ============================================================================
  4768. // LLM Routes
  4769. // ============================================================================
  4770. void HttpServer::SetupLlmRoutes() {
  4771. // Session management
  4772. httpServer_->Post("/api/llm/sessions",
  4773. [this](const httplib::Request& req, httplib::Response& res) {
  4774. HandleLlmCreateSession(req, res);
  4775. });
  4776. httpServer_->Get("/api/llm/sessions",
  4777. [this](const httplib::Request& req, httplib::Response& res) {
  4778. HandleLlmListSessions(req, res);
  4779. });
  4780. httpServer_->Get(R"(/api/llm/sessions/([^/]+))",
  4781. [this](const httplib::Request& req, httplib::Response& res) {
  4782. HandleLlmGetSession(req, res);
  4783. });
  4784. httpServer_->Delete(R"(/api/llm/sessions/([^/]+))",
  4785. [this](const httplib::Request& req, httplib::Response& res) {
  4786. HandleLlmDeleteSession(req, res);
  4787. });
  4788. httpServer_->Post(R"(/api/llm/sessions/([^/]+)/messages)",
  4789. [this](const httplib::Request& req, httplib::Response& res) {
  4790. HandleLlmSendMessage(req, res);
  4791. });
  4792. httpServer_->Post(R"(/api/llm/sessions/([^/]+)/stream)",
  4793. [this](const httplib::Request& req, httplib::Response& res) {
  4794. HandleLlmStreamMessage(req, res);
  4795. });
  4796. httpServer_->Post(R"(/api/llm/sessions/([^/]+)/clear)",
  4797. [this](const httplib::Request& req, httplib::Response& res) {
  4798. HandleLlmClearMessages(req, res);
  4799. });
  4800. httpServer_->Post(R"(/api/llm/sessions/([^/]+)/compress)",
  4801. [this](const httplib::Request& req, httplib::Response& res) {
  4802. HandleLlmCompressSession(req, res);
  4803. });
  4804. httpServer_->Post(R"(/api/llm/sessions/([^/]+)/generate-title)",
  4805. [this](const httplib::Request& req, httplib::Response& res) {
  4806. HandleLlmGenerateTitle(req, res);
  4807. });
  4808. // Models and providers (read-only)
  4809. httpServer_->Get("/api/llm/providers",
  4810. [this](const httplib::Request& req, httplib::Response& res) {
  4811. HandleLlmListProviders(req, res);
  4812. });
  4813. httpServer_->Get("/api/llm/models",
  4814. [this](const httplib::Request& req, httplib::Response& res) {
  4815. HandleLlmListModels(req, res);
  4816. });
  4817. httpServer_->Post("/api/llm/models/refresh",
  4818. [this](const httplib::Request& req, httplib::Response& res) {
  4819. HandleLlmRefreshModels(req, res);
  4820. });
  4821. httpServer_->Get(R"(/api/llm/providers/([^/]+)/health)",
  4822. [this](const httplib::Request& req, httplib::Response& res) {
  4823. HandleLlmGetProviderHealth(req, res);
  4824. });
  4825. // Admin routes for provider configuration
  4826. httpServer_->Get("/api/llm/admin/providers",
  4827. [this](const httplib::Request& req, httplib::Response& res) {
  4828. HandleLlmAdminListProviders(req, res);
  4829. });
  4830. httpServer_->Post("/api/llm/admin/providers",
  4831. [this](const httplib::Request& req, httplib::Response& res) {
  4832. HandleLlmAdminCreateProvider(req, res);
  4833. });
  4834. httpServer_->Put(R"(/api/llm/admin/providers/([^/]+))",
  4835. [this](const httplib::Request& req, httplib::Response& res) {
  4836. HandleLlmAdminUpdateProvider(req, res);
  4837. });
  4838. httpServer_->Delete(R"(/api/llm/admin/providers/([^/]+))",
  4839. [this](const httplib::Request& req, httplib::Response& res) {
  4840. HandleLlmAdminDeleteProvider(req, res);
  4841. });
  4842. // Workspace BYOK routes
  4843. httpServer_->Put(R"(/api/llm/workspaces/([^/]+)/key)",
  4844. [this](const httplib::Request& req, httplib::Response& res) {
  4845. HandleLlmSetWorkspaceKey(req, res);
  4846. });
  4847. httpServer_->Get(R"(/api/llm/workspaces/([^/]+)/key)",
  4848. [this](const httplib::Request& req, httplib::Response& res) {
  4849. HandleLlmGetWorkspaceKey(req, res);
  4850. });
  4851. httpServer_->Delete(R"(/api/llm/workspaces/([^/]+)/key)",
  4852. [this](const httplib::Request& req, httplib::Response& res) {
  4853. HandleLlmDeleteWorkspaceKey(req, res);
  4854. });
  4855. // Tool calling routes
  4856. httpServer_->Get("/api/llm/tools",
  4857. [this](const httplib::Request& req, httplib::Response& res) {
  4858. HandleLlmGetTools(req, res);
  4859. });
  4860. httpServer_->Post(R"(/api/llm/sessions/([^/]+)/tools/execute)",
  4861. [this](const httplib::Request& req, httplib::Response& res) {
  4862. HandleLlmExecuteTool(req, res);
  4863. });
  4864. httpServer_->Post(R"(/api/llm/sessions/([^/]+)/tools/results)",
  4865. [this](const httplib::Request& req, httplib::Response& res) {
  4866. HandleLlmSubmitToolResults(req, res);
  4867. });
  4868. spdlog::info("LLM routes configured");
  4869. }
  4870. void HttpServer::HandleLlmCreateSession(const httplib::Request& req, httplib::Response& res) {
  4871. auto auth_user = AuthenticateRequest(req);
  4872. if (!auth_user) {
  4873. res.status = 401;
  4874. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  4875. return;
  4876. }
  4877. // Check LLM chat permission
  4878. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  4879. res.status = 403;
  4880. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  4881. return;
  4882. }
  4883. if (!llmClient_ || !llmClient_->IsConnected()) {
  4884. res.status = 503;
  4885. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  4886. return;
  4887. }
  4888. nlohmann::json body;
  4889. try {
  4890. if (!req.body.empty()) {
  4891. body = nlohmann::json::parse(req.body);
  4892. }
  4893. } catch (const nlohmann::json::parse_error&) {
  4894. res.status = 400;
  4895. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  4896. return;
  4897. }
  4898. try {
  4899. ::smartbotic::llm::CreateSessionRequest request;
  4900. request.set_user_id(auth_user->user_id);
  4901. if (body.contains("workspace_id") && body["workspace_id"].is_string()) {
  4902. request.set_workspace_id(body["workspace_id"].get<std::string>());
  4903. }
  4904. if (body.contains("title") && body["title"].is_string()) {
  4905. request.set_title(body["title"].get<std::string>());
  4906. }
  4907. if (body.contains("model_id") && body["model_id"].is_string()) {
  4908. request.set_model_id(body["model_id"].get<std::string>());
  4909. }
  4910. if (body.contains("system_prompt") && body["system_prompt"].is_string()) {
  4911. request.set_system_prompt(body["system_prompt"].get<std::string>());
  4912. }
  4913. auto [status, session] = llmClient_->CreateSession(request);
  4914. if (!status.ok()) {
  4915. res.status = 500;
  4916. nlohmann::json error = {{"error", status.error_message()}};
  4917. res.set_content(error.dump(), "application/json");
  4918. return;
  4919. }
  4920. nlohmann::json response;
  4921. response["id"] = session.id();
  4922. response["user_id"] = session.user_id();
  4923. response["workspace_id"] = session.workspace_id();
  4924. response["title"] = session.title();
  4925. response["model_id"] = session.model_id();
  4926. response["system_prompt"] = session.system_prompt();
  4927. response["created_at"] = session.created_at().seconds();
  4928. response["updated_at"] = session.updated_at().seconds();
  4929. res.set_content(response.dump(), "application/json");
  4930. } catch (const std::exception& e) {
  4931. spdlog::error("LLM create session error: {}", e.what());
  4932. res.status = 500;
  4933. res.set_content(R"({"error":"Internal server error"})", "application/json");
  4934. }
  4935. }
  4936. void HttpServer::HandleLlmListSessions(const httplib::Request& req, httplib::Response& res) {
  4937. auto auth_user = AuthenticateRequest(req);
  4938. if (!auth_user) {
  4939. res.status = 401;
  4940. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  4941. return;
  4942. }
  4943. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  4944. res.status = 403;
  4945. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  4946. return;
  4947. }
  4948. if (!llmClient_ || !llmClient_->IsConnected()) {
  4949. res.status = 503;
  4950. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  4951. return;
  4952. }
  4953. try {
  4954. ::smartbotic::llm::ListSessionsRequest request;
  4955. request.set_user_id(auth_user->user_id);
  4956. if (req.has_param("workspace_id")) {
  4957. request.set_workspace_id(req.get_param_value("workspace_id"));
  4958. }
  4959. if (req.has_param("limit")) {
  4960. request.set_page_size(std::stoi(req.get_param_value("limit")));
  4961. }
  4962. auto [status, list_response] = llmClient_->ListSessions(request);
  4963. if (!status.ok()) {
  4964. res.status = 500;
  4965. nlohmann::json error = {{"error", status.error_message()}};
  4966. res.set_content(error.dump(), "application/json");
  4967. return;
  4968. }
  4969. nlohmann::json sessions_array = nlohmann::json::array();
  4970. for (const auto& session : list_response.sessions()) {
  4971. nlohmann::json s;
  4972. s["id"] = session.id();
  4973. s["user_id"] = session.user_id();
  4974. s["workspace_id"] = session.workspace_id();
  4975. s["title"] = session.title();
  4976. s["model_id"] = session.model_id();
  4977. s["message_count"] = session.message_count();
  4978. s["created_at"] = session.created_at().seconds();
  4979. s["updated_at"] = session.updated_at().seconds();
  4980. sessions_array.push_back(s);
  4981. }
  4982. nlohmann::json response;
  4983. response["sessions"] = sessions_array;
  4984. response["total"] = list_response.total_count();
  4985. res.set_content(response.dump(), "application/json");
  4986. } catch (const std::exception& e) {
  4987. spdlog::error("LLM list sessions error: {}", e.what());
  4988. res.status = 500;
  4989. res.set_content(R"({"error":"Internal server error"})", "application/json");
  4990. }
  4991. }
  4992. void HttpServer::HandleLlmGetSession(const httplib::Request& req, httplib::Response& res) {
  4993. auto auth_user = AuthenticateRequest(req);
  4994. if (!auth_user) {
  4995. res.status = 401;
  4996. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  4997. return;
  4998. }
  4999. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  5000. res.status = 403;
  5001. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  5002. return;
  5003. }
  5004. if (!llmClient_ || !llmClient_->IsConnected()) {
  5005. res.status = 503;
  5006. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5007. return;
  5008. }
  5009. std::string session_id = req.matches[1].str();
  5010. try {
  5011. ::smartbotic::llm::GetSessionRequest request;
  5012. request.set_session_id(session_id);
  5013. request.set_user_id(auth_user->user_id);
  5014. request.set_include_messages(true);
  5015. auto [status, session] = llmClient_->GetSession(request);
  5016. if (!status.ok()) {
  5017. // NOT_FOUND includes "Session not found" or "Access denied"
  5018. if (status.error_code() == grpc::StatusCode::NOT_FOUND) {
  5019. res.status = 404;
  5020. res.set_content(R"({"error":"Session not found"})", "application/json");
  5021. } else {
  5022. res.status = 500;
  5023. nlohmann::json error = {{"error", status.error_message()}};
  5024. res.set_content(error.dump(), "application/json");
  5025. }
  5026. return;
  5027. }
  5028. nlohmann::json response;
  5029. response["id"] = session.id();
  5030. response["user_id"] = session.user_id();
  5031. response["workspace_id"] = session.workspace_id();
  5032. response["title"] = session.title();
  5033. response["model_id"] = session.model_id();
  5034. response["system_prompt"] = session.system_prompt();
  5035. response["created_at"] = session.created_at().seconds();
  5036. response["updated_at"] = session.updated_at().seconds();
  5037. nlohmann::json messages_array = nlohmann::json::array();
  5038. for (const auto& msg : session.messages()) {
  5039. nlohmann::json m;
  5040. m["id"] = msg.id();
  5041. m["role"] = MessageRoleToString(msg.role());
  5042. // Extract text content from message parts
  5043. std::string msg_text;
  5044. for (const auto& part : msg.content()) {
  5045. if (part.has_text()) {
  5046. msg_text += part.text();
  5047. }
  5048. }
  5049. m["content"] = msg_text;
  5050. m["created_at"] = msg.created_at().seconds();
  5051. if (msg.has_page_context()) {
  5052. m["page_context"] = {
  5053. {"path", msg.page_context().path()},
  5054. {"title", msg.page_context().title()},
  5055. {"workspace_id", msg.page_context().workspace_id()},
  5056. {"collection", msg.page_context().collection()},
  5057. {"view_id", msg.page_context().view_id()}
  5058. };
  5059. }
  5060. messages_array.push_back(m);
  5061. }
  5062. response["messages"] = messages_array;
  5063. res.set_content(response.dump(), "application/json");
  5064. } catch (const std::exception& e) {
  5065. spdlog::error("LLM get session error: {}", e.what());
  5066. res.status = 500;
  5067. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5068. }
  5069. }
  5070. void HttpServer::HandleLlmDeleteSession(const httplib::Request& req, httplib::Response& res) {
  5071. auto auth_user = AuthenticateRequest(req);
  5072. if (!auth_user) {
  5073. res.status = 401;
  5074. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5075. return;
  5076. }
  5077. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  5078. res.status = 403;
  5079. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  5080. return;
  5081. }
  5082. if (!llmClient_ || !llmClient_->IsConnected()) {
  5083. res.status = 503;
  5084. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5085. return;
  5086. }
  5087. std::string session_id = req.matches[1].str();
  5088. try {
  5089. // First verify session ownership (user_id is verified by session store)
  5090. ::smartbotic::llm::GetSessionRequest get_request;
  5091. get_request.set_session_id(session_id);
  5092. get_request.set_user_id(auth_user->user_id);
  5093. auto [get_status, session] = llmClient_->GetSession(get_request);
  5094. if (!get_status.ok()) {
  5095. res.status = 404;
  5096. res.set_content(R"({"error":"Session not found"})", "application/json");
  5097. return;
  5098. }
  5099. ::smartbotic::llm::DeleteSessionRequest request;
  5100. request.set_session_id(session_id);
  5101. request.set_user_id(auth_user->user_id);
  5102. auto [status, delete_response] = llmClient_->DeleteSession(request);
  5103. if (!status.ok()) {
  5104. res.status = 500;
  5105. nlohmann::json error = {{"error", status.error_message()}};
  5106. res.set_content(error.dump(), "application/json");
  5107. return;
  5108. }
  5109. res.set_content(R"({"message":"Session deleted successfully"})", "application/json");
  5110. } catch (const std::exception& e) {
  5111. spdlog::error("LLM delete session error: {}", e.what());
  5112. res.status = 500;
  5113. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5114. }
  5115. }
  5116. void HttpServer::HandleLlmSendMessage(const httplib::Request& req, httplib::Response& res) {
  5117. auto auth_user = AuthenticateRequest(req);
  5118. if (!auth_user) {
  5119. res.status = 401;
  5120. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5121. return;
  5122. }
  5123. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  5124. res.status = 403;
  5125. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  5126. return;
  5127. }
  5128. if (!llmClient_ || !llmClient_->IsConnected()) {
  5129. res.status = 503;
  5130. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5131. return;
  5132. }
  5133. std::string session_id = req.matches[1].str();
  5134. nlohmann::json body;
  5135. try {
  5136. body = nlohmann::json::parse(req.body);
  5137. } catch (const nlohmann::json::parse_error&) {
  5138. res.status = 400;
  5139. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  5140. return;
  5141. }
  5142. if (!body.contains("content") || !body["content"].is_string()) {
  5143. res.status = 400;
  5144. res.set_content(R"({"error":"content is required"})", "application/json");
  5145. return;
  5146. }
  5147. try {
  5148. // Verify session ownership (user_id is verified by session store)
  5149. ::smartbotic::llm::GetSessionRequest get_request;
  5150. get_request.set_session_id(session_id);
  5151. get_request.set_user_id(auth_user->user_id);
  5152. get_request.set_include_messages(true);
  5153. auto [get_status, session] = llmClient_->GetSession(get_request);
  5154. if (!get_status.ok()) {
  5155. // NOT_FOUND could be "Session not found" or "Access denied"
  5156. res.status = 404;
  5157. res.set_content(R"({"error":"Session not found"})", "application/json");
  5158. return;
  5159. }
  5160. ::smartbotic::llm::ChatRequest request;
  5161. request.set_session_id(session_id);
  5162. request.set_user_id(auth_user->user_id);
  5163. auto* content_part = request.add_content();
  5164. content_part->set_text(body["content"].get<std::string>());
  5165. if (body.contains("page_context") && body["page_context"].is_object()) {
  5166. auto* ctx = request.mutable_page_context();
  5167. const auto& pc = body["page_context"];
  5168. if (pc.contains("path")) ctx->set_path(pc["path"].get<std::string>());
  5169. if (pc.contains("title")) ctx->set_title(pc["title"].get<std::string>());
  5170. if (pc.contains("workspace_id")) ctx->set_workspace_id(pc["workspace_id"].get<std::string>());
  5171. if (pc.contains("collection")) ctx->set_collection(pc["collection"].get<std::string>());
  5172. if (pc.contains("view_id")) ctx->set_view_id(pc["view_id"].get<std::string>());
  5173. }
  5174. auto [status, chat_response] = llmClient_->Chat(request);
  5175. if (!status.ok()) {
  5176. res.status = 500;
  5177. nlohmann::json error = {{"error", status.error_message()}};
  5178. res.set_content(error.dump(), "application/json");
  5179. return;
  5180. }
  5181. nlohmann::json response;
  5182. response["session_id"] = chat_response.session_id();
  5183. response["message_id"] = chat_response.assistant_message().id();
  5184. // Extract text content from assistant message
  5185. std::string content_text;
  5186. for (const auto& part : chat_response.assistant_message().content()) {
  5187. if (part.has_text()) {
  5188. content_text += part.text();
  5189. }
  5190. }
  5191. response["content"] = content_text;
  5192. response["finish_reason"] = static_cast<int>(chat_response.finish_reason());
  5193. if (chat_response.tool_calls_size() > 0) {
  5194. nlohmann::json tool_calls = nlohmann::json::array();
  5195. for (const auto& tc : chat_response.tool_calls()) {
  5196. tool_calls.push_back({
  5197. {"id", tc.id()},
  5198. {"name", tc.name()},
  5199. {"arguments", tc.arguments()}
  5200. });
  5201. }
  5202. response["tool_calls"] = tool_calls;
  5203. }
  5204. response["usage"] = {
  5205. {"prompt_tokens", chat_response.usage().prompt_tokens()},
  5206. {"completion_tokens", chat_response.usage().completion_tokens()},
  5207. {"total_tokens", chat_response.usage().total_tokens()}
  5208. };
  5209. res.set_content(response.dump(), "application/json");
  5210. } catch (const std::exception& e) {
  5211. spdlog::error("LLM send message error: {}", e.what());
  5212. res.status = 500;
  5213. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5214. }
  5215. }
  5216. void HttpServer::HandleLlmStreamMessage(const httplib::Request& req, httplib::Response& res) {
  5217. auto auth_user = AuthenticateRequest(req);
  5218. if (!auth_user) {
  5219. res.status = 401;
  5220. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5221. return;
  5222. }
  5223. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  5224. res.status = 403;
  5225. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  5226. return;
  5227. }
  5228. if (!llmClient_ || !llmClient_->IsConnected()) {
  5229. res.status = 503;
  5230. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5231. return;
  5232. }
  5233. std::string session_id = req.matches[1].str();
  5234. nlohmann::json body;
  5235. try {
  5236. body = nlohmann::json::parse(req.body);
  5237. } catch (const nlohmann::json::parse_error&) {
  5238. res.status = 400;
  5239. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  5240. return;
  5241. }
  5242. if (!body.contains("content") || !body["content"].is_string()) {
  5243. res.status = 400;
  5244. res.set_content(R"({"error":"content is required"})", "application/json");
  5245. return;
  5246. }
  5247. try {
  5248. // Verify session ownership (user_id is verified by session store)
  5249. ::smartbotic::llm::GetSessionRequest get_request;
  5250. get_request.set_session_id(session_id);
  5251. get_request.set_user_id(auth_user->user_id);
  5252. get_request.set_include_messages(true);
  5253. auto [get_status, session] = llmClient_->GetSession(get_request);
  5254. if (!get_status.ok()) {
  5255. // NOT_FOUND could be "Session not found" or "Access denied"
  5256. res.status = 404;
  5257. res.set_content(R"({"error":"Session not found"})", "application/json");
  5258. return;
  5259. }
  5260. ::smartbotic::llm::ChatRequest request;
  5261. request.set_session_id(session_id);
  5262. request.set_user_id(auth_user->user_id);
  5263. auto* stream_content_part = request.add_content();
  5264. stream_content_part->set_text(body["content"].get<std::string>());
  5265. // Get workspace settings to find provider_id
  5266. if (!session.workspace_id().empty() && workspaceService_) {
  5267. auto ws_result = workspaceService_->GetWorkspace(session.workspace_id(), false);
  5268. if (ws_result.success && ws_result.workspace) {
  5269. try {
  5270. if (ws_result.workspace->settings.contains("llm_provider_id")) {
  5271. std::string provider_id = ws_result.workspace->settings["llm_provider_id"].get<std::string>();
  5272. if (!provider_id.empty()) {
  5273. request.set_provider_id(provider_id);
  5274. spdlog::debug("Using provider_id '{}' from workspace settings", provider_id);
  5275. }
  5276. }
  5277. } catch (...) {
  5278. // Ignore JSON errors
  5279. }
  5280. }
  5281. }
  5282. if (body.contains("page_context") && body["page_context"].is_object()) {
  5283. auto* ctx = request.mutable_page_context();
  5284. const auto& pc = body["page_context"];
  5285. if (pc.contains("path")) ctx->set_path(pc["path"].get<std::string>());
  5286. if (pc.contains("title")) ctx->set_title(pc["title"].get<std::string>());
  5287. if (pc.contains("workspace_id")) ctx->set_workspace_id(pc["workspace_id"].get<std::string>());
  5288. if (pc.contains("collection")) ctx->set_collection(pc["collection"].get<std::string>());
  5289. if (pc.contains("view_id")) ctx->set_view_id(pc["view_id"].get<std::string>());
  5290. }
  5291. // Add available tools for this user
  5292. if (toolService_) {
  5293. auto tools = toolService_->GetAvailableTools(*auth_user, session.workspace_id());
  5294. for (const auto& tool : tools) {
  5295. auto* tool_def = request.add_tools();
  5296. tool_def->set_name(tool.name);
  5297. tool_def->set_description(tool.description);
  5298. tool_def->set_input_schema(tool.input_schema);
  5299. }
  5300. spdlog::debug("Added {} tools to chat request", tools.size());
  5301. }
  5302. // Set up SSE response
  5303. res.set_header("Content-Type", "text/event-stream");
  5304. res.set_header("Cache-Control", "no-cache");
  5305. res.set_header("Connection", "keep-alive");
  5306. std::string sse_content;
  5307. auto stream_status = llmClient_->ChatStream(request,
  5308. [&sse_content](const ::smartbotic::llm::ChatStreamChunk& chunk) -> bool {
  5309. nlohmann::json event;
  5310. event["session_id"] = chunk.session_id();
  5311. // ChatStreamChunk uses oneof for content_delta, tool_call, thinking_delta, or metadata
  5312. if (chunk.has_content_delta()) {
  5313. event["delta"] = chunk.content_delta();
  5314. }
  5315. if (chunk.has_thinking_delta()) {
  5316. event["thinking_delta"] = chunk.thinking_delta();
  5317. }
  5318. if (chunk.has_tool_call()) {
  5319. event["tool_call"] = {
  5320. {"id", chunk.tool_call().id()},
  5321. {"name", chunk.tool_call().name()},
  5322. {"arguments", chunk.tool_call().arguments()}
  5323. };
  5324. }
  5325. if (chunk.has_metadata()) {
  5326. const auto& meta = chunk.metadata();
  5327. event["finish_reason"] = static_cast<int>(meta.finish_reason());
  5328. event["message_id"] = meta.assistant_message().id();
  5329. }
  5330. sse_content += "data: " + event.dump() + "\n\n";
  5331. return true;
  5332. });
  5333. if (!stream_status.ok()) {
  5334. spdlog::error("LLM ChatStream failed: code={}, message={}",
  5335. static_cast<int>(stream_status.error_code()),
  5336. stream_status.error_message());
  5337. res.status = 500;
  5338. nlohmann::json error = {{"error", stream_status.error_message()}};
  5339. res.set_content(error.dump(), "application/json");
  5340. return;
  5341. }
  5342. // Send final done event
  5343. sse_content += "data: [DONE]\n\n";
  5344. res.set_content(sse_content, "text/event-stream");
  5345. } catch (const std::exception& e) {
  5346. spdlog::error("LLM stream message error: {}", e.what());
  5347. res.status = 500;
  5348. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5349. }
  5350. }
  5351. void HttpServer::HandleLlmClearMessages(const httplib::Request& req, httplib::Response& res) {
  5352. auto auth_user = AuthenticateRequest(req);
  5353. if (!auth_user) {
  5354. res.status = 401;
  5355. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5356. return;
  5357. }
  5358. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  5359. res.status = 403;
  5360. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  5361. return;
  5362. }
  5363. if (!llmClient_ || !llmClient_->IsConnected()) {
  5364. res.status = 503;
  5365. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5366. return;
  5367. }
  5368. std::string session_id = req.matches[1].str();
  5369. try {
  5370. // Verify session ownership (user_id is verified by session store)
  5371. ::smartbotic::llm::GetSessionRequest get_request;
  5372. get_request.set_session_id(session_id);
  5373. get_request.set_user_id(auth_user->user_id);
  5374. get_request.set_include_messages(true);
  5375. auto [get_status, session] = llmClient_->GetSession(get_request);
  5376. if (!get_status.ok()) {
  5377. // NOT_FOUND could be "Session not found" or "Access denied"
  5378. res.status = 404;
  5379. res.set_content(R"({"error":"Session not found"})", "application/json");
  5380. return;
  5381. }
  5382. ::smartbotic::llm::ClearSessionMessagesRequest request;
  5383. request.set_session_id(session_id);
  5384. request.set_user_id(auth_user->user_id);
  5385. auto [status, updated_session] = llmClient_->ClearSessionMessages(request);
  5386. if (!status.ok()) {
  5387. res.status = 500;
  5388. nlohmann::json error = {{"error", status.error_message()}};
  5389. res.set_content(error.dump(), "application/json");
  5390. return;
  5391. }
  5392. res.set_content(R"({"message":"Messages cleared successfully"})", "application/json");
  5393. } catch (const std::exception& e) {
  5394. spdlog::error("LLM clear messages error: {}", e.what());
  5395. res.status = 500;
  5396. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5397. }
  5398. }
  5399. void HttpServer::HandleLlmCompressSession(const httplib::Request& req, httplib::Response& res) {
  5400. auto auth_user = AuthenticateRequest(req);
  5401. if (!auth_user) {
  5402. res.status = 401;
  5403. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5404. return;
  5405. }
  5406. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  5407. res.status = 403;
  5408. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  5409. return;
  5410. }
  5411. if (!llmClient_ || !llmClient_->IsConnected()) {
  5412. res.status = 503;
  5413. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5414. return;
  5415. }
  5416. std::string session_id = req.matches[1].str();
  5417. try {
  5418. // Verify session ownership
  5419. ::smartbotic::llm::GetSessionRequest get_request;
  5420. get_request.set_session_id(session_id);
  5421. get_request.set_user_id(auth_user->user_id);
  5422. get_request.set_include_messages(false);
  5423. auto [get_status, session] = llmClient_->GetSession(get_request);
  5424. if (!get_status.ok()) {
  5425. res.status = 404;
  5426. res.set_content(R"({"error":"Session not found"})", "application/json");
  5427. return;
  5428. }
  5429. ::smartbotic::llm::CompressSessionRequest request;
  5430. request.set_session_id(session_id);
  5431. request.set_user_id(auth_user->user_id);
  5432. request.set_workspace_id(session.workspace_id());
  5433. auto [status, updated_session] = llmClient_->CompressSession(request);
  5434. if (!status.ok()) {
  5435. res.status = 500;
  5436. nlohmann::json error = {{"error", status.error_message()}};
  5437. res.set_content(error.dump(), "application/json");
  5438. return;
  5439. }
  5440. // Convert session to JSON response
  5441. nlohmann::json response;
  5442. response["id"] = updated_session.id();
  5443. response["user_id"] = updated_session.user_id();
  5444. response["workspace_id"] = updated_session.workspace_id();
  5445. response["title"] = updated_session.title();
  5446. response["model_id"] = updated_session.model_id();
  5447. response["message_count"] = updated_session.messages_size();
  5448. // Include context info if available
  5449. if (updated_session.has_context_info()) {
  5450. response["context_info"] = {
  5451. {"used_tokens", updated_session.context_info().used_tokens()},
  5452. {"max_tokens", updated_session.context_info().max_tokens()},
  5453. {"usage_percent", updated_session.context_info().usage_percent()}
  5454. };
  5455. }
  5456. // Include messages
  5457. nlohmann::json messages_array = nlohmann::json::array();
  5458. for (const auto& msg : updated_session.messages()) {
  5459. nlohmann::json msg_json;
  5460. msg_json["id"] = msg.id();
  5461. msg_json["role"] = MessageRoleToString(msg.role());
  5462. // Extract text content
  5463. std::string content_text;
  5464. for (const auto& part : msg.content()) {
  5465. if (part.has_text()) {
  5466. content_text += part.text();
  5467. }
  5468. }
  5469. msg_json["content"] = content_text;
  5470. msg_json["created_at"] = msg.created_at().seconds();
  5471. messages_array.push_back(msg_json);
  5472. }
  5473. response["messages"] = messages_array;
  5474. res.set_content(response.dump(), "application/json");
  5475. } catch (const std::exception& e) {
  5476. spdlog::error("LLM compress session error: {}", e.what());
  5477. res.status = 500;
  5478. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5479. }
  5480. }
  5481. void HttpServer::HandleLlmGenerateTitle(const httplib::Request& req, httplib::Response& res) {
  5482. auto auth_user = AuthenticateRequest(req);
  5483. if (!auth_user) {
  5484. res.status = 401;
  5485. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5486. return;
  5487. }
  5488. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  5489. res.status = 403;
  5490. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  5491. return;
  5492. }
  5493. if (!llmClient_ || !llmClient_->IsConnected()) {
  5494. res.status = 503;
  5495. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5496. return;
  5497. }
  5498. std::string session_id = req.matches[1].str();
  5499. try {
  5500. // Verify session ownership
  5501. ::smartbotic::llm::GetSessionRequest get_request;
  5502. get_request.set_session_id(session_id);
  5503. get_request.set_user_id(auth_user->user_id);
  5504. get_request.set_include_messages(false);
  5505. auto [get_status, session] = llmClient_->GetSession(get_request);
  5506. if (!get_status.ok()) {
  5507. res.status = 404;
  5508. res.set_content(R"({"error":"Session not found"})", "application/json");
  5509. return;
  5510. }
  5511. ::smartbotic::llm::GenerateTitleRequest request;
  5512. request.set_session_id(session_id);
  5513. request.set_user_id(auth_user->user_id);
  5514. request.set_workspace_id(session.workspace_id());
  5515. auto [status, title_response] = llmClient_->GenerateTitle(request);
  5516. if (!status.ok()) {
  5517. res.status = 500;
  5518. nlohmann::json error = {{"error", status.error_message()}};
  5519. res.set_content(error.dump(), "application/json");
  5520. return;
  5521. }
  5522. nlohmann::json response;
  5523. response["title"] = title_response.title();
  5524. res.set_content(response.dump(), "application/json");
  5525. } catch (const std::exception& e) {
  5526. spdlog::error("LLM generate title error: {}", e.what());
  5527. res.status = 500;
  5528. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5529. }
  5530. }
  5531. void HttpServer::HandleLlmListProviders(const httplib::Request& req, httplib::Response& res) {
  5532. auto auth_user = AuthenticateRequest(req);
  5533. if (!auth_user) {
  5534. res.status = 401;
  5535. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5536. return;
  5537. }
  5538. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  5539. res.status = 403;
  5540. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  5541. return;
  5542. }
  5543. if (!llmClient_ || !llmClient_->IsConnected()) {
  5544. res.status = 503;
  5545. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5546. return;
  5547. }
  5548. try {
  5549. ::smartbotic::llm::ListProvidersRequest request;
  5550. request.set_include_disabled(false); // Only show enabled providers
  5551. auto [status, list_response] = llmClient_->ListProviders(request);
  5552. if (!status.ok()) {
  5553. res.status = 500;
  5554. nlohmann::json error = {{"error", status.error_message()}};
  5555. res.set_content(error.dump(), "application/json");
  5556. return;
  5557. }
  5558. nlohmann::json providers_array = nlohmann::json::array();
  5559. for (const auto& provider : list_response.providers()) {
  5560. nlohmann::json p;
  5561. p["id"] = provider.id();
  5562. p["name"] = provider.name();
  5563. p["type"] = ::smartbotic::llm::ProviderType_Name(provider.type());
  5564. p["base_url"] = provider.base_url();
  5565. p["enabled"] = provider.enabled();
  5566. p["healthy"] = provider.healthy();
  5567. providers_array.push_back(p);
  5568. }
  5569. nlohmann::json response;
  5570. response["providers"] = providers_array;
  5571. res.set_content(response.dump(), "application/json");
  5572. } catch (const std::exception& e) {
  5573. spdlog::error("LLM list providers error: {}", e.what());
  5574. res.status = 500;
  5575. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5576. }
  5577. }
  5578. void HttpServer::HandleLlmListModels(const httplib::Request& req, httplib::Response& res) {
  5579. auto auth_user = AuthenticateRequest(req);
  5580. if (!auth_user) {
  5581. res.status = 401;
  5582. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5583. return;
  5584. }
  5585. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  5586. res.status = 403;
  5587. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  5588. return;
  5589. }
  5590. if (!llmClient_ || !llmClient_->IsConnected()) {
  5591. res.status = 503;
  5592. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5593. return;
  5594. }
  5595. try {
  5596. ::smartbotic::llm::ListModelsRequest request;
  5597. if (req.has_param("provider_id")) {
  5598. request.set_provider_id(req.get_param_value("provider_id"));
  5599. }
  5600. auto [status, list_response] = llmClient_->ListModels(request);
  5601. if (!status.ok()) {
  5602. res.status = 500;
  5603. nlohmann::json error = {{"error", status.error_message()}};
  5604. res.set_content(error.dump(), "application/json");
  5605. return;
  5606. }
  5607. nlohmann::json models_array = nlohmann::json::array();
  5608. for (const auto& model : list_response.models()) {
  5609. nlohmann::json m;
  5610. m["id"] = model.id();
  5611. m["name"] = model.name();
  5612. m["provider_id"] = model.provider_id();
  5613. m["provider_type"] = ::smartbotic::llm::ProviderType_Name(model.provider_type());
  5614. m["context_length"] = model.context_length();
  5615. m["supports_tools"] = model.supports_tools();
  5616. m["supports_vision"] = model.supports_vision();
  5617. models_array.push_back(m);
  5618. }
  5619. nlohmann::json response;
  5620. response["models"] = models_array;
  5621. res.set_content(response.dump(), "application/json");
  5622. } catch (const std::exception& e) {
  5623. spdlog::error("LLM list models error: {}", e.what());
  5624. res.status = 500;
  5625. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5626. }
  5627. }
  5628. void HttpServer::HandleLlmRefreshModels(const httplib::Request& req, httplib::Response& res) {
  5629. auto auth_user = AuthenticateRequest(req);
  5630. if (!auth_user) {
  5631. res.status = 401;
  5632. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5633. return;
  5634. }
  5635. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmProvidersRead)) {
  5636. res.status = 403;
  5637. res.set_content(R"({"error":"Forbidden - no provider access"})", "application/json");
  5638. return;
  5639. }
  5640. if (!llmClient_ || !llmClient_->IsConnected()) {
  5641. res.status = 503;
  5642. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5643. return;
  5644. }
  5645. try {
  5646. ::smartbotic::llm::RefreshModelsRequest request;
  5647. nlohmann::json body;
  5648. if (!req.body.empty()) {
  5649. try {
  5650. body = nlohmann::json::parse(req.body);
  5651. if (body.contains("provider_id") && body["provider_id"].is_string()) {
  5652. request.set_provider_id(body["provider_id"].get<std::string>());
  5653. }
  5654. } catch (...) {
  5655. // Ignore parse errors, proceed without provider_id filter
  5656. }
  5657. }
  5658. auto [status, refresh_response] = llmClient_->RefreshModels(request);
  5659. if (!status.ok()) {
  5660. res.status = 500;
  5661. nlohmann::json error = {{"error", status.error_message()}};
  5662. res.set_content(error.dump(), "application/json");
  5663. return;
  5664. }
  5665. nlohmann::json response;
  5666. response["models_found"] = refresh_response.models_found();
  5667. if (refresh_response.errors_size() > 0) {
  5668. nlohmann::json errors_array = nlohmann::json::array();
  5669. for (const auto& err : refresh_response.errors()) {
  5670. errors_array.push_back(err);
  5671. }
  5672. response["errors"] = errors_array;
  5673. }
  5674. res.set_content(response.dump(), "application/json");
  5675. } catch (const std::exception& e) {
  5676. spdlog::error("LLM refresh models error: {}", e.what());
  5677. res.status = 500;
  5678. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5679. }
  5680. }
  5681. void HttpServer::HandleLlmGetProviderHealth(const httplib::Request& req, httplib::Response& res) {
  5682. auto auth_user = AuthenticateRequest(req);
  5683. if (!auth_user) {
  5684. res.status = 401;
  5685. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5686. return;
  5687. }
  5688. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  5689. res.status = 403;
  5690. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  5691. return;
  5692. }
  5693. if (!llmClient_ || !llmClient_->IsConnected()) {
  5694. res.status = 503;
  5695. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5696. return;
  5697. }
  5698. std::string provider_id = req.matches[1].str();
  5699. try {
  5700. ::smartbotic::llm::GetProviderHealthRequest request;
  5701. request.set_provider_id(provider_id);
  5702. auto [status, health_response] = llmClient_->GetProviderHealth(request);
  5703. if (!status.ok()) {
  5704. if (status.error_code() == grpc::StatusCode::NOT_FOUND) {
  5705. res.status = 404;
  5706. res.set_content(R"({"error":"Provider not found"})", "application/json");
  5707. } else {
  5708. res.status = 500;
  5709. nlohmann::json error = {{"error", status.error_message()}};
  5710. res.set_content(error.dump(), "application/json");
  5711. }
  5712. return;
  5713. }
  5714. nlohmann::json response;
  5715. response["provider_id"] = health_response.provider_id();
  5716. response["healthy"] = health_response.healthy();
  5717. response["latency_ms"] = health_response.latency_ms();
  5718. if (!health_response.error().empty()) {
  5719. response["error"] = health_response.error();
  5720. }
  5721. res.set_content(response.dump(), "application/json");
  5722. } catch (const std::exception& e) {
  5723. spdlog::error("LLM get provider health error: {}", e.what());
  5724. res.status = 500;
  5725. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5726. }
  5727. }
  5728. void HttpServer::HandleLlmAdminListProviders(const httplib::Request& req, httplib::Response& res) {
  5729. auto auth_user = AuthenticateRequest(req);
  5730. if (!auth_user) {
  5731. res.status = 401;
  5732. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5733. return;
  5734. }
  5735. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmProvidersRead)) {
  5736. res.status = 403;
  5737. res.set_content(R"({"error":"Forbidden - no provider admin access"})", "application/json");
  5738. return;
  5739. }
  5740. if (!llmClient_ || !llmClient_->IsConnected()) {
  5741. res.status = 503;
  5742. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5743. return;
  5744. }
  5745. try {
  5746. ::smartbotic::llm::ListProviderConfigsRequest request;
  5747. request.set_include_disabled(true); // Admin sees all
  5748. auto [status, list_response] = llmClient_->ListProviderConfigs(request);
  5749. if (!status.ok()) {
  5750. res.status = 500;
  5751. nlohmann::json error = {{"error", status.error_message()}};
  5752. res.set_content(error.dump(), "application/json");
  5753. return;
  5754. }
  5755. nlohmann::json providers_array = nlohmann::json::array();
  5756. for (const auto& provider : list_response.providers()) {
  5757. nlohmann::json p;
  5758. p["id"] = provider.id();
  5759. p["name"] = provider.name();
  5760. p["type"] = ::smartbotic::llm::ProviderType_Name(provider.type());
  5761. p["base_url"] = provider.base_url();
  5762. p["enabled"] = provider.enabled();
  5763. p["has_api_key"] = provider.has_api_key();
  5764. providers_array.push_back(p);
  5765. }
  5766. nlohmann::json response;
  5767. response["providers"] = providers_array;
  5768. res.set_content(response.dump(), "application/json");
  5769. } catch (const std::exception& e) {
  5770. spdlog::error("LLM admin list providers error: {}", e.what());
  5771. res.status = 500;
  5772. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5773. }
  5774. }
  5775. void HttpServer::HandleLlmAdminCreateProvider(const httplib::Request& req, httplib::Response& res) {
  5776. auto auth_user = AuthenticateRequest(req);
  5777. if (!auth_user) {
  5778. res.status = 401;
  5779. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5780. return;
  5781. }
  5782. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmProvidersCreate)) {
  5783. res.status = 403;
  5784. res.set_content(R"({"error":"Forbidden - no provider create access"})", "application/json");
  5785. return;
  5786. }
  5787. if (!llmClient_ || !llmClient_->IsConnected()) {
  5788. res.status = 503;
  5789. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5790. return;
  5791. }
  5792. nlohmann::json body;
  5793. try {
  5794. body = nlohmann::json::parse(req.body);
  5795. } catch (const nlohmann::json::parse_error&) {
  5796. res.status = 400;
  5797. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  5798. return;
  5799. }
  5800. if (!body.contains("name") || !body["name"].is_string()) {
  5801. res.status = 400;
  5802. res.set_content(R"({"error":"name is required"})", "application/json");
  5803. return;
  5804. }
  5805. if (!body.contains("type") || !body["type"].is_string()) {
  5806. res.status = 400;
  5807. res.set_content(R"({"error":"type is required"})", "application/json");
  5808. return;
  5809. }
  5810. try {
  5811. ::smartbotic::llm::SetProviderConfigRequest request;
  5812. // Leave id empty for new provider
  5813. request.set_name(body["name"].get<std::string>());
  5814. std::string type_str = body["type"].get<std::string>();
  5815. ::smartbotic::llm::ProviderType type;
  5816. if (!::smartbotic::llm::ProviderType_Parse(type_str, &type)) {
  5817. res.status = 400;
  5818. res.set_content(R"({"error":"Invalid provider type"})", "application/json");
  5819. return;
  5820. }
  5821. request.set_type(type);
  5822. if (body.contains("base_url") && body["base_url"].is_string()) {
  5823. request.set_base_url(body["base_url"].get<std::string>());
  5824. }
  5825. if (body.contains("api_key") && body["api_key"].is_string()) {
  5826. request.set_api_key(body["api_key"].get<std::string>());
  5827. }
  5828. request.set_enabled(body.value("enabled", true));
  5829. auto [status, provider] = llmClient_->SetProviderConfig(request);
  5830. if (!status.ok()) {
  5831. res.status = 500;
  5832. nlohmann::json error = {{"error", status.error_message()}};
  5833. res.set_content(error.dump(), "application/json");
  5834. return;
  5835. }
  5836. nlohmann::json response;
  5837. response["id"] = provider.id();
  5838. response["name"] = provider.name();
  5839. response["type"] = ::smartbotic::llm::ProviderType_Name(provider.type());
  5840. response["base_url"] = provider.base_url();
  5841. response["enabled"] = provider.enabled();
  5842. response["has_api_key"] = provider.has_api_key();
  5843. res.status = 201;
  5844. res.set_content(response.dump(), "application/json");
  5845. } catch (const std::exception& e) {
  5846. spdlog::error("LLM admin create provider error: {}", e.what());
  5847. res.status = 500;
  5848. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5849. }
  5850. }
  5851. void HttpServer::HandleLlmAdminUpdateProvider(const httplib::Request& req, httplib::Response& res) {
  5852. auto auth_user = AuthenticateRequest(req);
  5853. if (!auth_user) {
  5854. res.status = 401;
  5855. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5856. return;
  5857. }
  5858. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmProvidersUpdate)) {
  5859. res.status = 403;
  5860. res.set_content(R"({"error":"Forbidden - no provider update access"})", "application/json");
  5861. return;
  5862. }
  5863. if (!llmClient_ || !llmClient_->IsConnected()) {
  5864. res.status = 503;
  5865. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5866. return;
  5867. }
  5868. std::string provider_id = req.matches[1].str();
  5869. nlohmann::json body;
  5870. try {
  5871. body = nlohmann::json::parse(req.body);
  5872. } catch (const nlohmann::json::parse_error&) {
  5873. res.status = 400;
  5874. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  5875. return;
  5876. }
  5877. try {
  5878. ::smartbotic::llm::SetProviderConfigRequest request;
  5879. request.set_id(provider_id);
  5880. if (body.contains("name") && body["name"].is_string()) {
  5881. request.set_name(body["name"].get<std::string>());
  5882. }
  5883. if (body.contains("type") && body["type"].is_string()) {
  5884. std::string type_str = body["type"].get<std::string>();
  5885. ::smartbotic::llm::ProviderType type;
  5886. if (::smartbotic::llm::ProviderType_Parse(type_str, &type)) {
  5887. request.set_type(type);
  5888. }
  5889. }
  5890. if (body.contains("base_url") && body["base_url"].is_string()) {
  5891. request.set_base_url(body["base_url"].get<std::string>());
  5892. }
  5893. if (body.contains("api_key") && body["api_key"].is_string()) {
  5894. request.set_api_key(body["api_key"].get<std::string>());
  5895. }
  5896. if (body.contains("enabled") && body["enabled"].is_boolean()) {
  5897. request.set_enabled(body["enabled"].get<bool>());
  5898. }
  5899. auto [status, provider] = llmClient_->SetProviderConfig(request);
  5900. if (!status.ok()) {
  5901. res.status = 500;
  5902. nlohmann::json error = {{"error", status.error_message()}};
  5903. res.set_content(error.dump(), "application/json");
  5904. return;
  5905. }
  5906. nlohmann::json response;
  5907. response["id"] = provider.id();
  5908. response["name"] = provider.name();
  5909. response["type"] = ::smartbotic::llm::ProviderType_Name(provider.type());
  5910. response["base_url"] = provider.base_url();
  5911. response["enabled"] = provider.enabled();
  5912. response["has_api_key"] = provider.has_api_key();
  5913. res.set_content(response.dump(), "application/json");
  5914. } catch (const std::exception& e) {
  5915. spdlog::error("LLM admin update provider error: {}", e.what());
  5916. res.status = 500;
  5917. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5918. }
  5919. }
  5920. void HttpServer::HandleLlmAdminDeleteProvider(const httplib::Request& req, httplib::Response& res) {
  5921. auto auth_user = AuthenticateRequest(req);
  5922. if (!auth_user) {
  5923. res.status = 401;
  5924. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5925. return;
  5926. }
  5927. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmProvidersDelete)) {
  5928. res.status = 403;
  5929. res.set_content(R"({"error":"Forbidden - no provider delete access"})", "application/json");
  5930. return;
  5931. }
  5932. if (!llmClient_ || !llmClient_->IsConnected()) {
  5933. res.status = 503;
  5934. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5935. return;
  5936. }
  5937. std::string provider_id = req.matches[1].str();
  5938. try {
  5939. ::smartbotic::llm::DeleteProviderConfigRequest request;
  5940. request.set_provider_id(provider_id);
  5941. auto [status, delete_response] = llmClient_->DeleteProviderConfig(request);
  5942. if (!status.ok()) {
  5943. res.status = 500;
  5944. nlohmann::json error = {{"error", status.error_message()}};
  5945. res.set_content(error.dump(), "application/json");
  5946. return;
  5947. }
  5948. res.set_content(R"({"message":"Provider deleted successfully"})", "application/json");
  5949. } catch (const std::exception& e) {
  5950. spdlog::error("LLM admin delete provider error: {}", e.what());
  5951. res.status = 500;
  5952. res.set_content(R"({"error":"Internal server error"})", "application/json");
  5953. }
  5954. }
  5955. void HttpServer::HandleLlmSetWorkspaceKey(const httplib::Request& req, httplib::Response& res) {
  5956. auto auth_user = AuthenticateRequest(req);
  5957. if (!auth_user) {
  5958. res.status = 401;
  5959. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  5960. return;
  5961. }
  5962. std::string workspace_id = req.matches[1].str();
  5963. // Check BYOK permission for this workspace
  5964. std::string byok_permission = permissions::BuildWorkspacePermission(workspace_id, "llm_byok");
  5965. if (!authorizationService_->HasPermission(*auth_user, byok_permission)) {
  5966. res.status = 403;
  5967. res.set_content(R"({"error":"Forbidden - no BYOK access for this workspace"})", "application/json");
  5968. return;
  5969. }
  5970. if (!llmClient_ || !llmClient_->IsConnected()) {
  5971. res.status = 503;
  5972. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  5973. return;
  5974. }
  5975. nlohmann::json body;
  5976. try {
  5977. body = nlohmann::json::parse(req.body);
  5978. } catch (const nlohmann::json::parse_error&) {
  5979. res.status = 400;
  5980. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  5981. return;
  5982. }
  5983. if (!body.contains("provider_id") || !body["provider_id"].is_string()) {
  5984. res.status = 400;
  5985. res.set_content(R"({"error":"provider_id is required"})", "application/json");
  5986. return;
  5987. }
  5988. if (!body.contains("api_key") || !body["api_key"].is_string()) {
  5989. res.status = 400;
  5990. res.set_content(R"({"error":"api_key is required"})", "application/json");
  5991. return;
  5992. }
  5993. try {
  5994. ::smartbotic::llm::SetWorkspaceApiKeyRequest request;
  5995. request.set_workspace_id(workspace_id);
  5996. request.set_provider_id(body["provider_id"].get<std::string>());
  5997. request.set_api_key(body["api_key"].get<std::string>());
  5998. auto status = llmClient_->SetWorkspaceApiKey(request);
  5999. if (!status.ok()) {
  6000. res.status = 500;
  6001. nlohmann::json error = {{"error", status.error_message()}};
  6002. res.set_content(error.dump(), "application/json");
  6003. return;
  6004. }
  6005. res.set_content(R"({"message":"Workspace API key set successfully"})", "application/json");
  6006. } catch (const std::exception& e) {
  6007. spdlog::error("LLM set workspace key error: {}", e.what());
  6008. res.status = 500;
  6009. res.set_content(R"({"error":"Internal server error"})", "application/json");
  6010. }
  6011. }
  6012. void HttpServer::HandleLlmGetWorkspaceKey(const httplib::Request& req, httplib::Response& res) {
  6013. auto auth_user = AuthenticateRequest(req);
  6014. if (!auth_user) {
  6015. res.status = 401;
  6016. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  6017. return;
  6018. }
  6019. std::string workspace_id = req.matches[1].str();
  6020. // Check BYOK permission for this workspace
  6021. std::string byok_permission = permissions::BuildWorkspacePermission(workspace_id, "llm_byok");
  6022. if (!authorizationService_->HasPermission(*auth_user, byok_permission)) {
  6023. res.status = 403;
  6024. res.set_content(R"({"error":"Forbidden - no BYOK access for this workspace"})", "application/json");
  6025. return;
  6026. }
  6027. if (!llmClient_ || !llmClient_->IsConnected()) {
  6028. res.status = 503;
  6029. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  6030. return;
  6031. }
  6032. std::string provider_id;
  6033. if (req.has_param("provider_id")) {
  6034. provider_id = req.get_param_value("provider_id");
  6035. } else {
  6036. res.status = 400;
  6037. res.set_content(R"({"error":"provider_id query parameter is required"})", "application/json");
  6038. return;
  6039. }
  6040. try {
  6041. ::smartbotic::llm::GetWorkspaceApiKeyRequest request;
  6042. request.set_workspace_id(workspace_id);
  6043. request.set_provider_id(provider_id);
  6044. auto [status, key_response] = llmClient_->GetWorkspaceApiKey(request);
  6045. if (!status.ok()) {
  6046. res.status = 500;
  6047. nlohmann::json error = {{"error", status.error_message()}};
  6048. res.set_content(error.dump(), "application/json");
  6049. return;
  6050. }
  6051. nlohmann::json response;
  6052. response["workspace_id"] = key_response.workspace_id();
  6053. response["provider_id"] = key_response.provider_id();
  6054. response["has_api_key"] = key_response.has_api_key();
  6055. res.set_content(response.dump(), "application/json");
  6056. } catch (const std::exception& e) {
  6057. spdlog::error("LLM get workspace key error: {}", e.what());
  6058. res.status = 500;
  6059. res.set_content(R"({"error":"Internal server error"})", "application/json");
  6060. }
  6061. }
  6062. void HttpServer::HandleLlmDeleteWorkspaceKey(const httplib::Request& req, httplib::Response& res) {
  6063. auto auth_user = AuthenticateRequest(req);
  6064. if (!auth_user) {
  6065. res.status = 401;
  6066. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  6067. return;
  6068. }
  6069. std::string workspace_id = req.matches[1].str();
  6070. // Check BYOK permission for this workspace
  6071. std::string byok_permission = permissions::BuildWorkspacePermission(workspace_id, "llm_byok");
  6072. if (!authorizationService_->HasPermission(*auth_user, byok_permission)) {
  6073. res.status = 403;
  6074. res.set_content(R"({"error":"Forbidden - no BYOK access for this workspace"})", "application/json");
  6075. return;
  6076. }
  6077. if (!llmClient_ || !llmClient_->IsConnected()) {
  6078. res.status = 503;
  6079. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  6080. return;
  6081. }
  6082. std::string provider_id;
  6083. if (req.has_param("provider_id")) {
  6084. provider_id = req.get_param_value("provider_id");
  6085. } else {
  6086. res.status = 400;
  6087. res.set_content(R"({"error":"provider_id query parameter is required"})", "application/json");
  6088. return;
  6089. }
  6090. try {
  6091. ::smartbotic::llm::DeleteWorkspaceApiKeyRequest request;
  6092. request.set_workspace_id(workspace_id);
  6093. request.set_provider_id(provider_id);
  6094. auto [status, delete_response] = llmClient_->DeleteWorkspaceApiKey(request);
  6095. if (!status.ok()) {
  6096. res.status = 500;
  6097. nlohmann::json error = {{"error", status.error_message()}};
  6098. res.set_content(error.dump(), "application/json");
  6099. return;
  6100. }
  6101. res.set_content(R"({"message":"Workspace API key deleted successfully"})", "application/json");
  6102. } catch (const std::exception& e) {
  6103. spdlog::error("LLM delete workspace key error: {}", e.what());
  6104. res.status = 500;
  6105. res.set_content(R"({"error":"Internal server error"})", "application/json");
  6106. }
  6107. }
  6108. // ============================================================================
  6109. // LLM Tool Endpoints
  6110. // ============================================================================
  6111. void HttpServer::HandleLlmGetTools(const httplib::Request& req, httplib::Response& res) {
  6112. auto auth_user = AuthenticateRequest(req);
  6113. if (!auth_user) {
  6114. res.status = 401;
  6115. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  6116. return;
  6117. }
  6118. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  6119. res.status = 403;
  6120. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  6121. return;
  6122. }
  6123. if (!toolService_) {
  6124. res.status = 503;
  6125. res.set_content(R"({"error":"Tool service not available"})", "application/json");
  6126. return;
  6127. }
  6128. // Get workspace_id from query parameter
  6129. std::string workspace_id;
  6130. if (req.has_param("workspace_id")) {
  6131. workspace_id = req.get_param_value("workspace_id");
  6132. }
  6133. try {
  6134. auto tools = toolService_->GetAvailableTools(*auth_user, workspace_id);
  6135. nlohmann::json response;
  6136. response["tools"] = nlohmann::json::array();
  6137. for (const auto& tool : tools) {
  6138. nlohmann::json tool_json;
  6139. tool_json["name"] = tool.name;
  6140. tool_json["description"] = tool.description;
  6141. tool_json["category"] = tool.category;
  6142. // Parse input_schema string to JSON
  6143. try {
  6144. tool_json["input_schema"] = nlohmann::json::parse(tool.input_schema);
  6145. } catch (...) {
  6146. tool_json["input_schema"] = nlohmann::json::object();
  6147. }
  6148. // Include permission info (for debugging)
  6149. tool_json["permissions"] = {
  6150. {"any_of", tool.permissions.any_of},
  6151. {"all_of", tool.permissions.all_of},
  6152. {"requires_workspace_context", tool.permissions.requires_workspace_context}
  6153. };
  6154. response["tools"].push_back(tool_json);
  6155. }
  6156. res.set_content(response.dump(), "application/json");
  6157. } catch (const std::exception& e) {
  6158. spdlog::error("GetTools error: {}", e.what());
  6159. res.status = 500;
  6160. res.set_content(R"({"error":"Internal server error"})", "application/json");
  6161. }
  6162. }
  6163. void HttpServer::HandleLlmExecuteTool(const httplib::Request& req, httplib::Response& res) {
  6164. auto auth_user = AuthenticateRequest(req);
  6165. if (!auth_user) {
  6166. res.status = 401;
  6167. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  6168. return;
  6169. }
  6170. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  6171. res.status = 403;
  6172. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  6173. return;
  6174. }
  6175. if (!toolService_) {
  6176. res.status = 503;
  6177. res.set_content(R"({"error":"Tool service not available"})", "application/json");
  6178. return;
  6179. }
  6180. std::string session_id = req.matches[1].str();
  6181. nlohmann::json body;
  6182. try {
  6183. body = nlohmann::json::parse(req.body);
  6184. } catch (const nlohmann::json::parse_error&) {
  6185. res.status = 400;
  6186. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  6187. return;
  6188. }
  6189. // Validate required fields
  6190. if (!body.contains("tool_name") || !body["tool_name"].is_string()) {
  6191. res.status = 400;
  6192. res.set_content(R"({"error":"tool_name is required"})", "application/json");
  6193. return;
  6194. }
  6195. if (!body.contains("arguments") || !body["arguments"].is_object()) {
  6196. res.status = 400;
  6197. res.set_content(R"({"error":"arguments is required"})", "application/json");
  6198. return;
  6199. }
  6200. std::string tool_name = body["tool_name"].get<std::string>();
  6201. nlohmann::json arguments = body["arguments"];
  6202. // Get workspace_id from body or context
  6203. std::string workspace_id;
  6204. if (body.contains("workspace_id") && body["workspace_id"].is_string()) {
  6205. workspace_id = body["workspace_id"].get<std::string>();
  6206. }
  6207. try {
  6208. // Build execution context
  6209. ToolExecutionContext ctx;
  6210. ctx.user_id = auth_user->user_id;
  6211. ctx.workspace_id = workspace_id;
  6212. ctx.session_id = session_id;
  6213. ctx.user = *auth_user;
  6214. // Check if tool is a navigation tool (handled client-side)
  6215. if (toolService_->IsNavigationTool(tool_name)) {
  6216. // For navigation tools, we still validate on server but return navigation data
  6217. // The actual navigation happens client-side
  6218. auto tool = toolService_->GetTool(tool_name);
  6219. if (!tool) {
  6220. res.status = 404;
  6221. res.set_content(R"({"error":"Tool not found"})", "application/json");
  6222. return;
  6223. }
  6224. if (!toolService_->CanUseTool(*auth_user, tool_name, workspace_id)) {
  6225. res.status = 403;
  6226. nlohmann::json error = {{"error", "Permission denied for tool: " + tool_name}};
  6227. res.set_content(error.dump(), "application/json");
  6228. return;
  6229. }
  6230. // Build navigation response
  6231. nlohmann::json response;
  6232. response["success"] = true;
  6233. response["is_navigation"] = true;
  6234. response["tool_name"] = tool_name;
  6235. response["arguments"] = arguments;
  6236. // Determine navigation target based on tool and arguments
  6237. nlohmann::json navigation;
  6238. if (tool_name == "navigate_to_dashboard") {
  6239. navigation["type"] = "dashboard";
  6240. } else if (tool_name == "navigate_to_page") {
  6241. navigation["type"] = "page";
  6242. if (arguments.contains("page_slug")) {
  6243. navigation["slug"] = arguments["page_slug"];
  6244. }
  6245. if (arguments.contains("page_id")) {
  6246. navigation["page_id"] = arguments["page_id"];
  6247. }
  6248. } else if (tool_name == "navigate_to_view") {
  6249. navigation["type"] = "view";
  6250. if (arguments.contains("view_id")) {
  6251. navigation["view_id"] = arguments["view_id"];
  6252. }
  6253. if (arguments.contains("collection_name")) {
  6254. navigation["collection_name"] = arguments["collection_name"];
  6255. }
  6256. if (arguments.contains("filter")) {
  6257. navigation["filter"] = arguments["filter"];
  6258. }
  6259. } else if (tool_name == "navigate_to_document") {
  6260. std::string action = arguments.value("action", "create");
  6261. navigation["type"] = action == "create" ? "document_create" : "document_edit";
  6262. navigation["view_id"] = arguments.value("view_id", "");
  6263. if (arguments.contains("document_id")) {
  6264. navigation["document_id"] = arguments["document_id"];
  6265. }
  6266. } else if (tool_name == "navigate_to_workspace_settings") {
  6267. navigation["type"] = "settings";
  6268. navigation["slug"] = "workspace";
  6269. } else if (tool_name == "navigate_to_user_management") {
  6270. navigation["type"] = "settings";
  6271. navigation["slug"] = "users";
  6272. }
  6273. response["navigation"] = navigation;
  6274. response["content"] = "Navigation to " + tool_name;
  6275. res.set_content(response.dump(), "application/json");
  6276. return;
  6277. }
  6278. // Execute non-navigation tool
  6279. auto result = toolService_->ExecuteTool(tool_name, arguments, ctx);
  6280. nlohmann::json response;
  6281. response["success"] = result.success;
  6282. response["content"] = result.content;
  6283. response["is_error"] = result.is_error;
  6284. if (result.navigation) {
  6285. response["navigation"] = {
  6286. {"type", result.navigation->type},
  6287. {"slug", result.navigation->slug},
  6288. {"view_id", result.navigation->view_id},
  6289. {"document_id", result.navigation->document_id},
  6290. {"filter", result.navigation->filter}
  6291. };
  6292. }
  6293. res.set_content(response.dump(), "application/json");
  6294. } catch (const std::exception& e) {
  6295. spdlog::error("ExecuteTool error: {}", e.what());
  6296. res.status = 500;
  6297. res.set_content(R"({"error":"Internal server error"})", "application/json");
  6298. }
  6299. }
  6300. void HttpServer::HandleLlmSubmitToolResults(const httplib::Request& req, httplib::Response& res) {
  6301. auto auth_user = AuthenticateRequest(req);
  6302. if (!auth_user) {
  6303. res.status = 401;
  6304. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  6305. return;
  6306. }
  6307. if (!authorizationService_->HasPermission(*auth_user, permissions::kLlmChat)) {
  6308. res.status = 403;
  6309. res.set_content(R"({"error":"Forbidden - no LLM chat access"})", "application/json");
  6310. return;
  6311. }
  6312. if (!llmClient_ || !llmClient_->IsConnected()) {
  6313. res.status = 503;
  6314. res.set_content(R"({"error":"LLM service not available"})", "application/json");
  6315. return;
  6316. }
  6317. std::string session_id = req.matches[1].str();
  6318. nlohmann::json body;
  6319. try {
  6320. body = nlohmann::json::parse(req.body);
  6321. } catch (const nlohmann::json::parse_error&) {
  6322. res.status = 400;
  6323. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  6324. return;
  6325. }
  6326. if (!body.contains("tool_results") || !body["tool_results"].is_array()) {
  6327. res.status = 400;
  6328. res.set_content(R"({"error":"tool_results array is required"})", "application/json");
  6329. return;
  6330. }
  6331. try {
  6332. // Verify session ownership
  6333. ::smartbotic::llm::GetSessionRequest get_request;
  6334. get_request.set_session_id(session_id);
  6335. get_request.set_user_id(auth_user->user_id);
  6336. get_request.set_include_messages(false);
  6337. auto [get_status, session] = llmClient_->GetSession(get_request);
  6338. if (!get_status.ok()) {
  6339. res.status = 404;
  6340. res.set_content(R"({"error":"Session not found"})", "application/json");
  6341. return;
  6342. }
  6343. // Build SubmitToolResults request
  6344. ::smartbotic::llm::SubmitToolResultsRequest tool_request;
  6345. tool_request.set_session_id(session_id);
  6346. tool_request.set_user_id(auth_user->user_id);
  6347. for (const auto& result : body["tool_results"]) {
  6348. auto* tool_result = tool_request.add_tool_results();
  6349. tool_result->set_tool_call_id(result.value("tool_call_id", ""));
  6350. tool_result->set_content(result.value("content", ""));
  6351. tool_result->set_is_error(result.value("is_error", false));
  6352. }
  6353. // Setup SSE response for streaming
  6354. res.set_header("Content-Type", "text/event-stream");
  6355. res.set_header("Cache-Control", "no-cache");
  6356. res.set_header("Connection", "keep-alive");
  6357. std::string sse_content;
  6358. auto stream_status = llmClient_->SubmitToolResultsStream(tool_request,
  6359. [&sse_content](const ::smartbotic::llm::ChatStreamChunk& chunk) -> bool {
  6360. nlohmann::json event;
  6361. event["session_id"] = chunk.session_id();
  6362. if (chunk.has_content_delta()) {
  6363. event["delta"] = chunk.content_delta();
  6364. }
  6365. if (chunk.has_thinking_delta()) {
  6366. event["thinking_delta"] = chunk.thinking_delta();
  6367. }
  6368. if (chunk.has_tool_call()) {
  6369. event["tool_call"] = {
  6370. {"id", chunk.tool_call().id()},
  6371. {"name", chunk.tool_call().name()},
  6372. {"arguments", chunk.tool_call().arguments()}
  6373. };
  6374. }
  6375. if (chunk.has_metadata()) {
  6376. const auto& meta = chunk.metadata();
  6377. event["finish_reason"] = static_cast<int>(meta.finish_reason());
  6378. event["message_id"] = meta.assistant_message().id();
  6379. }
  6380. sse_content += "data: " + event.dump() + "\n\n";
  6381. return true;
  6382. });
  6383. if (!stream_status.ok()) {
  6384. spdlog::error("SubmitToolResults stream error: {}", stream_status.error_message());
  6385. sse_content += "data: {\"error\":\"Stream error\"}\n\n";
  6386. }
  6387. sse_content += "data: [DONE]\n\n";
  6388. res.set_content(sse_content, "text/event-stream");
  6389. } catch (const std::exception& e) {
  6390. spdlog::error("SubmitToolResults error: {}", e.what());
  6391. res.status = 500;
  6392. res.set_content(R"({"error":"Internal server error"})", "application/json");
  6393. }
  6394. }
  6395. } // namespace smartbotic::webserver