http_server.cpp 169 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588
  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. auto GenerateSessionId() -> std::string {
  20. static std::random_device rd;
  21. static std::mt19937 gen(rd());
  22. static std::uniform_int_distribution<> dis(0, 15);
  23. static const char* hex = "0123456789abcdef";
  24. std::string uuid;
  25. uuid.reserve(36);
  26. for (int i = 0; i < 36; ++i) {
  27. if (i == 8 || i == 13 || i == 18 || i == 23) {
  28. uuid += '-';
  29. } else {
  30. uuid += hex[dis(gen)];
  31. }
  32. }
  33. return uuid;
  34. }
  35. } // namespace
  36. // LWS protocol definition - first protocol handles HTTP and is the default for WS
  37. static lws_protocols protocols[] = {
  38. {
  39. "http", // Default protocol name for HTTP/WS upgrade
  40. WebSocketServer::WsCallback,
  41. 0, // per_session_data_size - we manage our own
  42. 65536, // rx buffer size
  43. 0, // id
  44. nullptr, // user
  45. 65536 // tx_packet_size
  46. },
  47. LWS_PROTOCOL_LIST_TERM
  48. };
  49. WebSocketServer::WebSocketServer(uint16_t port, const std::string& path)
  50. : port_(port), path_(path) {
  51. instance_ = this;
  52. }
  53. WebSocketServer::~WebSocketServer() {
  54. Stop();
  55. instance_ = nullptr;
  56. }
  57. void WebSocketServer::Start() {
  58. if (running_.load()) {
  59. spdlog::warn("WebSocket server already running");
  60. return;
  61. }
  62. spdlog::info("Starting WebSocket server on port {}", port_);
  63. lws_context_creation_info info{};
  64. std::memset(&info, 0, sizeof(info));
  65. info.port = port_;
  66. info.protocols = protocols;
  67. info.gid = -1;
  68. info.uid = -1;
  69. info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
  70. info.vhost_name = "smartbotic-ws";
  71. // Suppress verbose lws logging
  72. lws_set_log_level(LLL_ERR | LLL_WARN, nullptr);
  73. context_ = lws_create_context(&info);
  74. if (context_ == nullptr) {
  75. spdlog::error("Failed to create libwebsocket context");
  76. return;
  77. }
  78. running_.store(true);
  79. eventLoopThread_ = std::thread(&WebSocketServer::RunEventLoop, this);
  80. spdlog::info("WebSocket server started on port {}", port_);
  81. }
  82. void WebSocketServer::Stop() {
  83. if (!running_.load()) {
  84. return;
  85. }
  86. spdlog::info("Stopping WebSocket server...");
  87. running_.store(false);
  88. // Cancel the event loop to wake up lws_service() immediately
  89. // This is async-signal-safe and can be called from signal handlers
  90. if (context_ != nullptr) {
  91. lws_cancel_service(context_);
  92. }
  93. if (eventLoopThread_.joinable()) {
  94. eventLoopThread_.join();
  95. }
  96. if (context_ != nullptr) {
  97. lws_context_destroy(context_);
  98. context_ = nullptr;
  99. }
  100. {
  101. std::lock_guard<std::mutex> lock(connectionsMutex_);
  102. connections_.clear();
  103. }
  104. spdlog::info("WebSocket server stopped");
  105. }
  106. void WebSocketServer::RunEventLoop() {
  107. while (running_.load()) {
  108. lws_service(context_, 50); // 50ms timeout
  109. }
  110. }
  111. void WebSocketServer::Broadcast(const std::string& message) {
  112. std::lock_guard<std::mutex> lock(connectionsMutex_);
  113. for (auto& [wsi, conn] : connections_) {
  114. QueueMessage(conn.get(), message);
  115. }
  116. }
  117. void WebSocketServer::SendToSession(const std::string& sessionId, const std::string& message) {
  118. std::lock_guard<std::mutex> lock(connectionsMutex_);
  119. for (auto& [wsi, conn] : connections_) {
  120. if (conn->sessionId == sessionId) {
  121. QueueMessage(conn.get(), message);
  122. break;
  123. }
  124. }
  125. }
  126. void WebSocketServer::SendToSubscribers(const std::string& subscription_key, const std::string& message) {
  127. std::lock_guard<std::mutex> lock(connectionsMutex_);
  128. for (auto& [wsi, conn] : connections_) {
  129. // Check if this connection is subscribed and authenticated
  130. if (!conn->authenticated) {
  131. continue;
  132. }
  133. const auto& subs = conn->subscriptions;
  134. if (std::find(subs.begin(), subs.end(), subscription_key) != subs.end()) {
  135. QueueMessage(conn.get(), message);
  136. }
  137. }
  138. }
  139. auto WebSocketServer::ConnectionCount() const -> size_t {
  140. std::lock_guard<std::mutex> lock(connectionsMutex_);
  141. return connections_.size();
  142. }
  143. void WebSocketServer::SetMessageHandler(WebSocketMessageHandler handler) {
  144. messageHandler_ = std::move(handler);
  145. }
  146. void WebSocketServer::HandleConnect(lws* wsi) {
  147. auto conn = std::make_unique<WsConnection>();
  148. conn->wsi = wsi;
  149. conn->sessionId = GenerateSessionId();
  150. spdlog::info("WebSocket client connected (session: {})", conn->sessionId);
  151. std::lock_guard<std::mutex> lock(connectionsMutex_);
  152. connections_[wsi] = std::move(conn);
  153. }
  154. void WebSocketServer::HandleDisconnect(lws* wsi) {
  155. std::lock_guard<std::mutex> lock(connectionsMutex_);
  156. auto it = connections_.find(wsi);
  157. if (it != connections_.end()) {
  158. spdlog::info("WebSocket client disconnected (session: {})", it->second->sessionId);
  159. connections_.erase(it);
  160. }
  161. }
  162. void WebSocketServer::HandleMessage(lws* wsi, const std::string& message) {
  163. WsConnection* conn = nullptr;
  164. {
  165. std::lock_guard<std::mutex> lock(connectionsMutex_);
  166. auto it = connections_.find(wsi);
  167. if (it != connections_.end()) {
  168. conn = it->second.get();
  169. }
  170. }
  171. // Call handler outside the lock to avoid deadlock with SendToSession
  172. if (conn && messageHandler_) {
  173. messageHandler_(conn, message);
  174. }
  175. }
  176. void WebSocketServer::QueueMessage(WsConnection* conn, const std::string& message) {
  177. std::lock_guard<std::mutex> lock(conn->sendMutex);
  178. // Prepend LWS_PRE bytes for libwebsockets
  179. conn->sendBuffer.resize(LWS_PRE + message.size());
  180. std::memcpy(conn->sendBuffer.data() + LWS_PRE, message.data(), message.size());
  181. lws_callback_on_writable(conn->wsi);
  182. }
  183. auto WebSocketServer::WsCallback(lws* wsi, lws_callback_reasons reason,
  184. void* user, void* in, size_t len) -> int {
  185. if (instance_ == nullptr) {
  186. return 0;
  187. }
  188. switch (reason) {
  189. case LWS_CALLBACK_PROTOCOL_INIT:
  190. spdlog::debug("WebSocket protocol initialized");
  191. break;
  192. case LWS_CALLBACK_ESTABLISHED:
  193. spdlog::debug("WebSocket connection established");
  194. instance_->HandleConnect(wsi);
  195. break;
  196. case LWS_CALLBACK_CLOSED:
  197. spdlog::debug("WebSocket connection closed");
  198. instance_->HandleDisconnect(wsi);
  199. break;
  200. case LWS_CALLBACK_RECEIVE: {
  201. std::string message(static_cast<char*>(in), len);
  202. spdlog::debug("WebSocket received {} bytes", len);
  203. instance_->HandleMessage(wsi, message);
  204. break;
  205. }
  206. case LWS_CALLBACK_SERVER_WRITEABLE: {
  207. std::lock_guard<std::mutex> lock(instance_->connectionsMutex_);
  208. auto it = instance_->connections_.find(wsi);
  209. if (it != instance_->connections_.end()) {
  210. auto& conn = it->second;
  211. std::lock_guard<std::mutex> sendLock(conn->sendMutex);
  212. if (conn->sendBuffer.size() > LWS_PRE) {
  213. size_t msgLen = conn->sendBuffer.size() - LWS_PRE;
  214. lws_write(wsi, conn->sendBuffer.data() + LWS_PRE, msgLen, LWS_WRITE_TEXT);
  215. conn->sendBuffer.clear();
  216. }
  217. }
  218. break;
  219. }
  220. case LWS_CALLBACK_HTTP:
  221. // Return non-zero to close the connection for non-WebSocket HTTP requests
  222. return -1;
  223. case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
  224. // Allow the connection
  225. return 0;
  226. default:
  227. break;
  228. }
  229. return 0;
  230. }
  231. // ============================================================================
  232. // HttpServer Implementation
  233. // ============================================================================
  234. HttpServer::HttpServer(HttpServerConfig config)
  235. : config_(std::move(config)),
  236. httpServer_(std::make_unique<httplib::Server>()),
  237. dbClient_(std::make_unique<DatabaseClient>(config_)),
  238. authService_(std::make_unique<AuthService>(config_.jwt)) {}
  239. HttpServer::~HttpServer() {
  240. if (running_.load()) {
  241. Stop();
  242. }
  243. }
  244. auto HttpServer::Start(bool require_database) -> bool {
  245. if (running_.load()) {
  246. spdlog::warn("Server already running");
  247. return true;
  248. }
  249. spdlog::info("Starting HTTP server on {}", config_.GetListenAddress());
  250. // Connect to database first (fail-fast if required)
  251. if (require_database) {
  252. spdlog::info("Connecting to database at {} (fail-fast mode enabled)", config_.database_address);
  253. if (!ConnectToDatabase()) {
  254. spdlog::error("Failed to connect to database - server startup aborted");
  255. return false;
  256. }
  257. } else {
  258. // Try to connect but don't fail if unavailable
  259. spdlog::info("Connecting to database at {} (optional mode)", config_.database_address);
  260. if (!ConnectToDatabase()) {
  261. spdlog::warn("Database connection failed - server will start without database connectivity");
  262. }
  263. }
  264. // Initialize services (only if database is connected)
  265. if (IsDatabaseConnected()) {
  266. if (!InitializeServices()) {
  267. spdlog::error("Failed to initialize services - server startup aborted");
  268. return false;
  269. }
  270. }
  271. // Setup routes
  272. SetupRoutes();
  273. // Start WebSocket server on separate port
  274. wsServer_ = std::make_unique<WebSocketServer>(config_.ws_port, config_.ws_path);
  275. // Setup WebSocket message handler using WsHandler if available
  276. if (wsHandler_) {
  277. wsServer_->SetMessageHandler([this](WsConnection* conn, const std::string& message) {
  278. wsHandler_->HandleMessage(conn, message,
  279. [this](WsConnection* c, const std::string& response) {
  280. wsServer_->SendToSession(c->sessionId, response);
  281. });
  282. });
  283. spdlog::info("WebSocket message handler configured with WsHandler");
  284. } else if (wsMessageHandler_) {
  285. wsServer_->SetMessageHandler(wsMessageHandler_);
  286. }
  287. wsServer_->Start();
  288. // Start HTTP server in a separate thread
  289. running_.store(true);
  290. httpThread_ = std::thread(&HttpServer::RunHttpServer, this);
  291. spdlog::info("HTTP server started successfully on {}", config_.GetListenAddress());
  292. spdlog::info("WebSocket server: ws://{}:{}{}", config_.address, config_.ws_port, config_.ws_path);
  293. spdlog::info("Static files: {}", config_.webui_path);
  294. spdlog::info("Database: {} ({})", config_.database_address,
  295. IsDatabaseConnected() ? "connected" : "not connected");
  296. return true;
  297. }
  298. void HttpServer::Stop() {
  299. if (!running_.load()) {
  300. return;
  301. }
  302. spdlog::info("Stopping HTTP server...");
  303. running_.store(false);
  304. // Stop WebSocket server first (this uses lws_cancel_service which is async-signal-safe)
  305. if (wsServer_) {
  306. wsServer_->Stop();
  307. }
  308. // Stop HTTP server - this makes listen() return
  309. if (httpServer_) {
  310. httpServer_->stop();
  311. }
  312. // Disconnect from database
  313. if (dbClient_) {
  314. dbClient_->Disconnect();
  315. }
  316. // NOTE: Don't join httpThread_ here - let Wait() handle it
  317. // This avoids race condition when Stop() is called from signal handler
  318. // while main thread is blocked in Wait()
  319. spdlog::info("HTTP server stop requested");
  320. }
  321. void HttpServer::Wait() {
  322. if (httpThread_.joinable()) {
  323. httpThread_.join();
  324. }
  325. spdlog::info("HTTP server stopped");
  326. }
  327. void HttpServer::BroadcastWebSocket(const std::string& message) {
  328. if (wsServer_) {
  329. wsServer_->Broadcast(message);
  330. }
  331. }
  332. void HttpServer::BroadcastDocumentEvent(const std::string& workspace_id,
  333. const std::string& collection,
  334. DocumentAction action,
  335. const std::string& document_id,
  336. const nlohmann::json& data) {
  337. if (!wsServer_ || !wsHandler_) {
  338. return;
  339. }
  340. std::string subscription_key = WsHandler::BuildSubscriptionKey(workspace_id, collection);
  341. // Build the event JSON
  342. nlohmann::json event = {
  343. {"type", "document"},
  344. {"action", DocumentActionToString(action)},
  345. {"workspace_id", workspace_id},
  346. {"collection", collection},
  347. {"document_id", document_id}
  348. };
  349. // Include data for create/update, exclude for delete
  350. if (action != DocumentAction::Delete && !data.is_null()) {
  351. event["data"] = data;
  352. }
  353. std::string event_str = event.dump();
  354. spdlog::debug("Broadcasting document event: {} {} in {} (key={})",
  355. DocumentActionToString(action), document_id, collection, subscription_key);
  356. wsServer_->SendToSubscribers(subscription_key, event_str);
  357. }
  358. void HttpServer::SetWebSocketMessageHandler(WebSocketMessageHandler handler) {
  359. wsMessageHandler_ = std::move(handler);
  360. if (wsServer_) {
  361. wsServer_->SetMessageHandler(wsMessageHandler_);
  362. }
  363. }
  364. auto HttpServer::GetWebSocketClientCount() const -> size_t {
  365. return wsServer_ ? wsServer_->ConnectionCount() : 0;
  366. }
  367. auto HttpServer::IsDatabaseConnected() const -> bool {
  368. return dbClient_ && dbClient_->IsConnected();
  369. }
  370. auto HttpServer::ConnectToDatabase() -> bool {
  371. if (!dbClient_) {
  372. dbClient_ = std::make_unique<DatabaseClient>(config_);
  373. }
  374. // Try to connect
  375. if (!dbClient_->Connect()) {
  376. return false;
  377. }
  378. // Perform a health check to verify the connection is working
  379. auto health = dbClient_->HealthCheck();
  380. if (!health.healthy) {
  381. spdlog::error("Database health check failed: {}", health.message);
  382. return false;
  383. }
  384. spdlog::info("Database health check passed (latency: {}ms)", health.latency.count());
  385. return true;
  386. }
  387. auto HttpServer::InitializeServices() -> bool {
  388. // Initialize UserService
  389. userService_ = std::make_unique<UserService>(*dbClient_);
  390. if (!userService_->Initialize()) {
  391. spdlog::error("Failed to initialize UserService");
  392. return false;
  393. }
  394. spdlog::info("UserService initialized successfully");
  395. // Initialize WorkspaceService
  396. workspaceService_ = std::make_unique<WorkspaceService>(*dbClient_);
  397. if (!workspaceService_->Initialize()) {
  398. spdlog::error("Failed to initialize WorkspaceService");
  399. return false;
  400. }
  401. spdlog::info("WorkspaceService initialized successfully");
  402. // Initialize GroupService
  403. groupService_ = std::make_unique<GroupService>(*dbClient_);
  404. if (!groupService_->Initialize()) {
  405. spdlog::error("Failed to initialize GroupService");
  406. return false;
  407. }
  408. spdlog::info("GroupService initialized successfully");
  409. // Initialize MembershipService
  410. membershipService_ = std::make_unique<MembershipService>(*dbClient_);
  411. if (!membershipService_->Initialize()) {
  412. spdlog::error("Failed to initialize MembershipService");
  413. return false;
  414. }
  415. spdlog::info("MembershipService initialized successfully");
  416. // Initialize ApiKeyService
  417. apiKeyService_ = std::make_unique<ApiKeyService>(*dbClient_);
  418. if (!apiKeyService_->Initialize()) {
  419. spdlog::error("Failed to initialize ApiKeyService");
  420. return false;
  421. }
  422. spdlog::info("ApiKeyService initialized successfully");
  423. // Initialize CollectionService
  424. collectionService_ = std::make_unique<CollectionService>(*dbClient_);
  425. spdlog::info("CollectionService initialized successfully");
  426. // Initialize DocumentService
  427. documentService_ = std::make_unique<DocumentService>(*dbClient_);
  428. spdlog::info("DocumentService initialized successfully");
  429. // Initialize ViewService
  430. viewService_ = std::make_unique<ViewService>(*dbClient_);
  431. if (!viewService_->Initialize()) {
  432. spdlog::error("Failed to initialize ViewService");
  433. return false;
  434. }
  435. spdlog::info("ViewService initialized successfully");
  436. // Initialize AuthorizationService
  437. authorizationService_ = std::make_unique<AuthorizationService>(*groupService_, *collectionService_);
  438. if (!authorizationService_->Initialize()) {
  439. spdlog::error("Failed to initialize AuthorizationService");
  440. return false;
  441. }
  442. spdlog::info("AuthorizationService initialized successfully");
  443. // Initialize WsHandler for WebSocket real-time updates
  444. wsHandler_ = std::make_unique<WsHandler>(*authService_);
  445. spdlog::info("WsHandler initialized successfully");
  446. // Note: WebSocket message handler is set up in Start() after wsServer_ is created
  447. return true;
  448. }
  449. void HttpServer::SetupRoutes() {
  450. // Pre-routing handler for CORS
  451. httpServer_->set_pre_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
  452. // Apply CORS headers if enabled
  453. if (config_.cors.enabled) {
  454. // Combine allowed origins
  455. std::string origins;
  456. for (size_t i = 0; i < config_.cors.allowed_origins.size(); ++i) {
  457. if (i > 0) origins += ", ";
  458. origins += config_.cors.allowed_origins[i];
  459. }
  460. res.set_header("Access-Control-Allow-Origin", origins);
  461. // Combine allowed methods
  462. std::string methods;
  463. for (size_t i = 0; i < config_.cors.allowed_methods.size(); ++i) {
  464. if (i > 0) methods += ", ";
  465. methods += config_.cors.allowed_methods[i];
  466. }
  467. res.set_header("Access-Control-Allow-Methods", methods);
  468. // Combine allowed headers
  469. std::string headers;
  470. for (size_t i = 0; i < config_.cors.allowed_headers.size(); ++i) {
  471. if (i > 0) headers += ", ";
  472. headers += config_.cors.allowed_headers[i];
  473. }
  474. res.set_header("Access-Control-Allow-Headers", headers);
  475. if (config_.cors.allow_credentials) {
  476. res.set_header("Access-Control-Allow-Credentials", "true");
  477. }
  478. res.set_header("Access-Control-Max-Age", std::to_string(config_.cors.max_age));
  479. }
  480. res.set_header("Server", "SmartBotic-Server/0.1.0");
  481. // Handle CORS preflight
  482. if (req.method == "OPTIONS") {
  483. res.status = 204;
  484. return httplib::Server::HandlerResponse::Handled;
  485. }
  486. return httplib::Server::HandlerResponse::Unhandled;
  487. });
  488. // Health check endpoint
  489. httpServer_->Get("/api/health", [this](const httplib::Request& req, httplib::Response& res) {
  490. HandleHealth(req, res);
  491. });
  492. // Version endpoint
  493. httpServer_->Get("/api/version", [this](const httplib::Request& req, httplib::Response& res) {
  494. HandleVersion(req, res);
  495. });
  496. // Bootstrap endpoint - creates first admin user if no users exist
  497. httpServer_->Post("/api/bootstrap", [this](const httplib::Request& req, httplib::Response& res) {
  498. HandleBootstrap(req, res);
  499. });
  500. // Setup authentication routes
  501. SetupAuthRoutes();
  502. // Setup user management routes
  503. SetupUserRoutes();
  504. // Setup API key routes (under /api/users/:id/api-keys)
  505. SetupApiKeyRoutes();
  506. // Setup membership routes (before workspace routes since they're more specific)
  507. SetupMembershipRoutes();
  508. // Setup document routes (most specific - before collections)
  509. SetupDocumentRoutes();
  510. // Setup view routes (schema definitions)
  511. SetupViewRoutes();
  512. // Setup collection routes (before workspace routes since they're more specific)
  513. SetupCollectionRoutes();
  514. // Setup group management routes (before workspace routes since they're more specific)
  515. SetupGroupRoutes();
  516. // Setup workspace management routes
  517. SetupWorkspaceRoutes();
  518. // Mount static file directory for WebUI
  519. if (std::filesystem::exists(config_.webui_path)) {
  520. httpServer_->set_mount_point("/", config_.webui_path);
  521. spdlog::info("Mounted static files from: {}", config_.webui_path);
  522. } else {
  523. spdlog::warn("WebUI path does not exist: {}", config_.webui_path);
  524. }
  525. // Custom error handler for 404 (only if response body is empty)
  526. httpServer_->set_error_handler([](const httplib::Request& /*req*/, httplib::Response& res) {
  527. // Only set default error message if body hasn't been set by a handler
  528. if (res.body.empty()) {
  529. res.set_content(R"({"error":"Not found"})", "application/json");
  530. }
  531. });
  532. // Logger for requests
  533. httpServer_->set_logger([](const httplib::Request& req, const httplib::Response& res) {
  534. auto status = res.status;
  535. if (status >= 500) {
  536. spdlog::error("{} {} {}", req.method, req.path, status);
  537. } else if (status >= 400) {
  538. spdlog::warn("{} {} {}", req.method, req.path, status);
  539. } else {
  540. spdlog::info("{} {} {}", req.method, req.path, status);
  541. }
  542. });
  543. }
  544. void HttpServer::RunHttpServer() {
  545. if (!httpServer_->listen(config_.address, config_.port)) {
  546. spdlog::error("Failed to start HTTP server on {}", config_.GetListenAddress());
  547. running_.store(false);
  548. }
  549. }
  550. void HttpServer::HandleHealth(const httplib::Request& req, httplib::Response& res) {
  551. res.set_content(R"({"status":"healthy","service":"smartbotic-server"})", "application/json");
  552. }
  553. void HttpServer::HandleVersion(const httplib::Request& req, httplib::Response& res) {
  554. res.set_content(R"({"version":"0.1.0","name":"SmartBotic Web Server"})", "application/json");
  555. }
  556. void HttpServer::HandleBootstrap(const httplib::Request& req, httplib::Response& res) {
  557. // Bootstrap endpoint - creates first admin user if no users exist
  558. if (!userService_) {
  559. res.status = 500;
  560. res.set_content(R"({"error":"User service not available"})", "application/json");
  561. return;
  562. }
  563. // Check if any users exist
  564. auto users = userService_->ListUsers();
  565. if (!users.users.empty()) {
  566. res.status = 400;
  567. res.set_content(R"({"error":"System already bootstrapped - users exist"})", "application/json");
  568. return;
  569. }
  570. // Parse request body
  571. nlohmann::json body;
  572. try {
  573. body = nlohmann::json::parse(req.body);
  574. } catch (...) {
  575. res.status = 400;
  576. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  577. return;
  578. }
  579. // Validate required fields
  580. if (!body.contains("email") || !body.contains("password")) {
  581. res.status = 400;
  582. res.set_content(R"({"error":"Email and password are required"})", "application/json");
  583. return;
  584. }
  585. CreateUserRequest user_request;
  586. user_request.email = body["email"].get<std::string>();
  587. user_request.password = body["password"].get<std::string>();
  588. user_request.name = body.value("name", "Admin");
  589. // Create the admin user
  590. auto result = userService_->CreateUser(user_request);
  591. if (!result.success) {
  592. res.status = 400;
  593. nlohmann::json error_response;
  594. error_response["error"] = result.error;
  595. res.set_content(error_response.dump(), "application/json");
  596. return;
  597. }
  598. // Create a default workspace
  599. if (workspaceService_) {
  600. CreateWorkspaceRequest ws_request;
  601. ws_request.name = "Default Workspace";
  602. ws_request.settings["default"] = true;
  603. auto ws_result = workspaceService_->CreateWorkspace(ws_request);
  604. // Add user to workspace
  605. if (ws_result.success && ws_result.workspace && membershipService_) {
  606. AddMemberRequest member_request;
  607. member_request.workspace_id = ws_result.workspace->id;
  608. member_request.user_id = result.user->id;
  609. member_request.group_ids = {};
  610. [[maybe_unused]] auto member_result = membershipService_->AddMember(member_request);
  611. }
  612. }
  613. // Return success with user info
  614. nlohmann::json response;
  615. response["success"] = true;
  616. response["message"] = "System bootstrapped successfully";
  617. response["user"]["id"] = result.user->id;
  618. response["user"]["email"] = result.user->email;
  619. response["user"]["name"] = result.user->name;
  620. spdlog::info("System bootstrapped with admin user: {}", user_request.email);
  621. res.set_content(response.dump(), "application/json");
  622. }
  623. auto HttpServer::GetMimeType(const std::string& path) -> std::string {
  624. auto ext_pos = path.rfind('.');
  625. if (ext_pos == std::string::npos) {
  626. return "application/octet-stream";
  627. }
  628. std::string ext = path.substr(ext_pos);
  629. static const std::unordered_map<std::string, std::string> mime_types = {
  630. {".html", "text/html"},
  631. {".htm", "text/html"},
  632. {".css", "text/css"},
  633. {".js", "application/javascript"},
  634. {".json", "application/json"},
  635. {".png", "image/png"},
  636. {".jpg", "image/jpeg"},
  637. {".jpeg", "image/jpeg"},
  638. {".gif", "image/gif"},
  639. {".svg", "image/svg+xml"},
  640. {".ico", "image/x-icon"},
  641. {".woff", "font/woff"},
  642. {".woff2", "font/woff2"},
  643. {".ttf", "font/ttf"},
  644. {".eot", "application/vnd.ms-fontobject"},
  645. {".txt", "text/plain"},
  646. {".xml", "application/xml"},
  647. {".pdf", "application/pdf"},
  648. };
  649. auto it = mime_types.find(ext);
  650. if (it != mime_types.end()) {
  651. return it->second;
  652. }
  653. return "application/octet-stream";
  654. }
  655. // ============================================================================
  656. // Authentication Routes Implementation
  657. // ============================================================================
  658. void HttpServer::SetupAuthRoutes() {
  659. // POST /api/auth/login - Authenticate user and return JWT
  660. httpServer_->Post("/api/auth/login", [this](const httplib::Request& req, httplib::Response& res) {
  661. HandleAuthLogin(req, res);
  662. });
  663. // POST /api/auth/refresh - Refresh access token
  664. httpServer_->Post("/api/auth/refresh", [this](const httplib::Request& req, httplib::Response& res) {
  665. HandleAuthRefresh(req, res);
  666. });
  667. // POST /api/auth/logout - Invalidate refresh token
  668. httpServer_->Post("/api/auth/logout", [this](const httplib::Request& req, httplib::Response& res) {
  669. HandleAuthLogout(req, res);
  670. });
  671. // GET /api/auth/me - Get current authenticated user info
  672. httpServer_->Get("/api/auth/me", [this](const httplib::Request& req, httplib::Response& res) {
  673. HandleAuthMe(req, res);
  674. });
  675. spdlog::info("Authentication routes registered: /api/auth/login, /api/auth/refresh, /api/auth/logout, /api/auth/me");
  676. }
  677. void HttpServer::HandleAuthLogin(const httplib::Request& req, httplib::Response& res) {
  678. try {
  679. // Parse request body
  680. auto body = nlohmann::json::parse(req.body);
  681. if (!body.contains("email") || !body.contains("password")) {
  682. res.status = 400;
  683. res.set_content(R"({"error":"Missing email or password"})", "application/json");
  684. return;
  685. }
  686. std::string email = body["email"].get<std::string>();
  687. std::string password = body["password"].get<std::string>();
  688. if (config_.jwt.secret.empty()) {
  689. res.status = 500;
  690. res.set_content(R"({"error":"JWT secret not configured"})", "application/json");
  691. return;
  692. }
  693. if (!userService_) {
  694. res.status = 500;
  695. res.set_content(R"({"error":"User service not available"})", "application/json");
  696. return;
  697. }
  698. // Verify user credentials
  699. auto user_result = userService_->VerifyCredentials(email, password);
  700. if (!user_result.success || !user_result.user) {
  701. res.status = 401;
  702. res.set_content(R"({"error":"Invalid email or password"})", "application/json");
  703. return;
  704. }
  705. const auto& user = *user_result.user;
  706. // Get user's workspace memberships
  707. std::vector<std::string> workspace_ids;
  708. if (membershipService_) {
  709. auto memberships = membershipService_->ListUserMemberships(user.id);
  710. for (const auto& m : memberships.members) {
  711. workspace_ids.push_back(m.workspace_id);
  712. }
  713. }
  714. // Collect user's groups from memberships
  715. std::vector<std::string> groups;
  716. if (membershipService_) {
  717. auto memberships = membershipService_->ListUserMemberships(user.id);
  718. for (const auto& m : memberships.members) {
  719. for (const auto& gid : m.group_ids) {
  720. if (std::find(groups.begin(), groups.end(), gid) == groups.end()) {
  721. groups.push_back(gid);
  722. }
  723. }
  724. }
  725. }
  726. // First registered user is automatically superadmin
  727. if (groupService_) {
  728. auto superadmin_group = groupService_->GetSuperadminGroup();
  729. if (superadmin_group.success && superadmin_group.group) {
  730. auto all_users = userService_->ListUsers();
  731. if (!all_users.users.empty() && all_users.users[0].id == user.id) {
  732. const auto& sa_id = superadmin_group.group->id;
  733. if (std::find(groups.begin(), groups.end(), sa_id) == groups.end()) {
  734. groups.push_back(sa_id);
  735. }
  736. }
  737. }
  738. }
  739. auto tokens = authService_->GenerateTokens(user.id, email, workspace_ids, groups);
  740. nlohmann::json response = {
  741. {"access_token", tokens.access_token},
  742. {"refresh_token", tokens.refresh_token},
  743. {"token_type", "Bearer"},
  744. {"expires_in", tokens.access_expires_in}
  745. };
  746. spdlog::info("User logged in: {}", email);
  747. res.set_content(response.dump(), "application/json");
  748. } catch (const nlohmann::json::parse_error& e) {
  749. res.status = 400;
  750. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  751. } catch (const std::exception& e) {
  752. spdlog::error("Login error: {}", e.what());
  753. res.status = 500;
  754. res.set_content(R"({"error":"Internal server error"})", "application/json");
  755. }
  756. }
  757. void HttpServer::HandleAuthRefresh(const httplib::Request& req, httplib::Response& res) {
  758. try {
  759. // Parse request body
  760. auto body = nlohmann::json::parse(req.body);
  761. if (!body.contains("refresh_token")) {
  762. res.status = 400;
  763. res.set_content(R"({"error":"Missing refresh_token"})", "application/json");
  764. return;
  765. }
  766. std::string refresh_token = body["refresh_token"].get<std::string>();
  767. auto new_tokens = authService_->RefreshAccessToken(refresh_token);
  768. if (!new_tokens) {
  769. res.status = 401;
  770. res.set_content(R"({"error":"Invalid or expired refresh token"})", "application/json");
  771. return;
  772. }
  773. nlohmann::json response = {
  774. {"access_token", new_tokens->access_token},
  775. {"refresh_token", new_tokens->refresh_token},
  776. {"token_type", "Bearer"},
  777. {"expires_in", new_tokens->access_expires_in}
  778. };
  779. spdlog::debug("Token refreshed successfully");
  780. res.set_content(response.dump(), "application/json");
  781. } catch (const nlohmann::json::parse_error& e) {
  782. res.status = 400;
  783. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  784. } catch (const std::exception& e) {
  785. spdlog::error("Token refresh error: {}", e.what());
  786. res.status = 500;
  787. res.set_content(R"({"error":"Internal server error"})", "application/json");
  788. }
  789. }
  790. void HttpServer::HandleAuthLogout(const httplib::Request& req, httplib::Response& res) {
  791. try {
  792. // Parse request body
  793. auto body = nlohmann::json::parse(req.body);
  794. if (!body.contains("refresh_token")) {
  795. res.status = 400;
  796. res.set_content(R"({"error":"Missing refresh_token"})", "application/json");
  797. return;
  798. }
  799. std::string refresh_token = body["refresh_token"].get<std::string>();
  800. if (authService_->InvalidateRefreshToken(refresh_token)) {
  801. spdlog::debug("User logged out successfully");
  802. res.set_content(R"({"message":"Logged out successfully"})", "application/json");
  803. } else {
  804. res.status = 400;
  805. res.set_content(R"({"error":"Invalid refresh token"})", "application/json");
  806. }
  807. } catch (const nlohmann::json::parse_error& e) {
  808. res.status = 400;
  809. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  810. } catch (const std::exception& e) {
  811. spdlog::error("Logout error: {}", e.what());
  812. res.status = 500;
  813. res.set_content(R"({"error":"Internal server error"})", "application/json");
  814. }
  815. }
  816. void HttpServer::HandleAuthMe(const httplib::Request& req, httplib::Response& res) {
  817. auto auth_user = AuthenticateRequest(req);
  818. if (!auth_user) {
  819. res.status = 401;
  820. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  821. return;
  822. }
  823. // Build response with user info from token
  824. nlohmann::json response = {
  825. {"id", auth_user->user_id},
  826. {"email", auth_user->email},
  827. {"groups", auth_user->groups},
  828. {"workspace_ids", auth_user->workspace_ids}
  829. };
  830. // Try to get additional user info from database
  831. if (userService_) {
  832. auto user_result = userService_->GetUser(auth_user->user_id);
  833. if (user_result.success && user_result.user) {
  834. response["name"] = user_result.user->name;
  835. response["created_at"] = user_result.user->created_at;
  836. }
  837. }
  838. // Check if user is superadmin based on groups
  839. response["is_superadmin"] = IsSuperadmin(*auth_user);
  840. res.set_content(response.dump(), "application/json");
  841. }
  842. auto HttpServer::AuthenticateRequest(const httplib::Request& req) -> std::optional<AuthUser> {
  843. std::string auth_token;
  844. // First check X-API-Key header (direct API key)
  845. auto api_key_header = req.get_header_value("X-API-Key");
  846. if (!api_key_header.empty()) {
  847. auth_token = api_key_header;
  848. } else {
  849. // Check Authorization header
  850. auto auth_header = req.get_header_value("Authorization");
  851. if (auth_header.empty()) {
  852. return std::nullopt;
  853. }
  854. auto token = AuthService::ExtractBearerToken(auth_header);
  855. if (!token) {
  856. return std::nullopt;
  857. }
  858. auth_token = *token;
  859. }
  860. // Check if this is an API key (starts with "sk_")
  861. if (auth_token.starts_with("sk_")) {
  862. if (!apiKeyService_) {
  863. spdlog::warn("API key authentication attempted but service not available");
  864. return std::nullopt;
  865. }
  866. auto validation = apiKeyService_->ValidateApiKey(auth_token);
  867. if (!validation.valid || !validation.api_key) {
  868. spdlog::debug("API key validation failed: {}", validation.error);
  869. return std::nullopt;
  870. }
  871. // Check if key is expired
  872. if (validation.api_key->IsExpired()) {
  873. spdlog::debug("API key expired");
  874. return std::nullopt;
  875. }
  876. // Update last used timestamp (fire and forget)
  877. apiKeyService_->UpdateLastUsed(validation.api_key->id);
  878. // Build AuthUser from API key
  879. AuthUser auth_user;
  880. auth_user.user_id = validation.api_key->user_id;
  881. // Use API key permissions as groups
  882. auth_user.groups = validation.api_key->permissions;
  883. // Try to fetch additional user info
  884. if (userService_) {
  885. auto user_result = userService_->GetUser(validation.api_key->user_id);
  886. if (user_result.success && user_result.user) {
  887. auth_user.email = user_result.user->email;
  888. // Fetch workspace memberships for the user
  889. if (membershipService_) {
  890. auto memberships = membershipService_->ListUserMemberships(user_result.user->id);
  891. for (const auto& m : memberships.members) {
  892. auth_user.workspace_ids.push_back(m.workspace_id);
  893. }
  894. }
  895. } else {
  896. spdlog::debug("API key owner user not found in database: {}", validation.api_key->user_id);
  897. }
  898. }
  899. return auth_user;
  900. }
  901. // Otherwise, treat as JWT token
  902. auto validation = authService_->ValidateAccessToken(auth_token);
  903. if (!validation.valid) {
  904. spdlog::debug("Token validation failed: {}", validation.error);
  905. return std::nullopt;
  906. }
  907. return validation.user;
  908. }
  909. // ============================================================================
  910. // User Management Routes Implementation
  911. // ============================================================================
  912. void HttpServer::SetupUserRoutes() {
  913. // POST /api/users - Create a new user (superadmin only)
  914. httpServer_->Post("/api/users", [this](const httplib::Request& req, httplib::Response& res) {
  915. HandleCreateUser(req, res);
  916. });
  917. // GET /api/users - List all users (superadmin only)
  918. httpServer_->Get("/api/users", [this](const httplib::Request& req, httplib::Response& res) {
  919. HandleListUsers(req, res);
  920. });
  921. // GET /api/users/:id - Get a specific user
  922. httpServer_->Get(R"(/api/users/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  923. HandleGetUser(req, res);
  924. });
  925. // PATCH /api/users/:id - Update a user
  926. httpServer_->Patch(R"(/api/users/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  927. HandleUpdateUser(req, res);
  928. });
  929. // DELETE /api/users/:id - Soft delete a user (superadmin only)
  930. httpServer_->Delete(R"(/api/users/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  931. HandleDeleteUser(req, res);
  932. });
  933. spdlog::info("User management routes registered: /api/users");
  934. }
  935. auto HttpServer::IsSuperadmin(const AuthUser& user) -> bool {
  936. // Delegate to authorization service for proper permission checking
  937. // This maintains backward compatibility while using the new RBAC system
  938. if (authorizationService_) {
  939. return authorizationService_->IsSuperadmin(user);
  940. }
  941. // Fallback to old behavior if authorization service not available
  942. return std::find(user.groups.begin(), user.groups.end(), "superadmin") != user.groups.end();
  943. }
  944. auto HttpServer::ResolveUserName(const std::string& user_id) -> std::string {
  945. if (user_id.empty() || !userService_) {
  946. return "";
  947. }
  948. auto result = userService_->GetUser(user_id, true);
  949. if (result.success && result.user) {
  950. return result.user->name;
  951. }
  952. return "";
  953. }
  954. void HttpServer::HandleCreateUser(const httplib::Request& req, httplib::Response& res) {
  955. // Authenticate the request
  956. auto auth_user = AuthenticateRequest(req);
  957. if (!auth_user) {
  958. res.status = 401;
  959. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  960. return;
  961. }
  962. // Check permission to create users
  963. if (!authorizationService_ || !authorizationService_->HasPermission(*auth_user, smartbotic::permissions::kUsersCreate)) {
  964. res.status = 403;
  965. res.set_content(R"({"error":"Forbidden - requires system:users:create permission"})", "application/json");
  966. return;
  967. }
  968. // Check if UserService is available
  969. if (!userService_) {
  970. res.status = 503;
  971. res.set_content(R"({"error":"User service not available"})", "application/json");
  972. return;
  973. }
  974. try {
  975. auto body = nlohmann::json::parse(req.body);
  976. CreateUserRequest create_req;
  977. create_req.actor_id = auth_user->user_id;
  978. if (body.contains("email")) {
  979. create_req.email = body["email"].get<std::string>();
  980. }
  981. if (body.contains("password")) {
  982. create_req.password = body["password"].get<std::string>();
  983. }
  984. if (body.contains("name")) {
  985. create_req.name = body["name"].get<std::string>();
  986. }
  987. auto result = userService_->CreateUser(create_req);
  988. if (!result.success) {
  989. res.status = 400;
  990. nlohmann::json error_response = {{"error", result.error}};
  991. res.set_content(error_response.dump(), "application/json");
  992. return;
  993. }
  994. // Return created user (without password_hash)
  995. nlohmann::json user_json = {
  996. {"id", result.user->id},
  997. {"email", result.user->email},
  998. {"name", result.user->name},
  999. {"created_at", result.user->created_at},
  1000. {"updated_at", result.user->updated_at}
  1001. };
  1002. res.status = 201;
  1003. res.set_content(user_json.dump(), "application/json");
  1004. } catch (const nlohmann::json::parse_error& e) {
  1005. res.status = 400;
  1006. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  1007. } catch (const std::exception& e) {
  1008. spdlog::error("Create user error: {}", e.what());
  1009. res.status = 500;
  1010. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1011. }
  1012. }
  1013. void HttpServer::HandleListUsers(const httplib::Request& req, httplib::Response& res) {
  1014. // Authenticate the request
  1015. auto auth_user = AuthenticateRequest(req);
  1016. if (!auth_user) {
  1017. res.status = 401;
  1018. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1019. return;
  1020. }
  1021. // Requires system:users:read permission
  1022. if (!authorizationService_->HasPermission(*auth_user, permissions::kUsersRead)) {
  1023. res.status = 403;
  1024. res.set_content(R"({"error":"Forbidden - requires system:users:read permission"})", "application/json");
  1025. return;
  1026. }
  1027. // Check if UserService is available
  1028. if (!userService_) {
  1029. res.status = 503;
  1030. res.set_content(R"({"error":"User service not available"})", "application/json");
  1031. return;
  1032. }
  1033. try {
  1034. // Parse query parameters
  1035. int limit = 100;
  1036. int offset = 0;
  1037. bool include_deleted = false;
  1038. if (req.has_param("limit")) {
  1039. limit = std::stoi(req.get_param_value("limit"));
  1040. if (limit < 1 || limit > 1000) {
  1041. limit = 100;
  1042. }
  1043. }
  1044. if (req.has_param("offset")) {
  1045. offset = std::stoi(req.get_param_value("offset"));
  1046. if (offset < 0) {
  1047. offset = 0;
  1048. }
  1049. }
  1050. if (req.has_param("include_deleted")) {
  1051. include_deleted = req.get_param_value("include_deleted") == "true";
  1052. }
  1053. auto result = userService_->ListUsers(limit, offset, include_deleted);
  1054. if (!result.success) {
  1055. res.status = 500;
  1056. nlohmann::json error_response = {{"error", result.error}};
  1057. res.set_content(error_response.dump(), "application/json");
  1058. return;
  1059. }
  1060. // Build response
  1061. nlohmann::json users_array = nlohmann::json::array();
  1062. for (const auto& user : result.users) {
  1063. nlohmann::json user_obj = {
  1064. {"id", user.id},
  1065. {"email", user.email},
  1066. {"name", user.name},
  1067. {"created_at", user.created_at},
  1068. {"updated_at", user.updated_at},
  1069. {"deleted_at", user.deleted_at},
  1070. {"created_by", user.created_by},
  1071. {"updated_by", user.updated_by},
  1072. {"created_by_name", ResolveUserName(user.created_by)},
  1073. {"updated_by_name", ResolveUserName(user.updated_by)}
  1074. };
  1075. users_array.push_back(user_obj);
  1076. }
  1077. nlohmann::json response = {
  1078. {"users", users_array},
  1079. {"total_count", result.total_count},
  1080. {"limit", limit},
  1081. {"offset", offset}
  1082. };
  1083. res.set_content(response.dump(), "application/json");
  1084. } catch (const std::exception& e) {
  1085. spdlog::error("List users error: {}", e.what());
  1086. res.status = 500;
  1087. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1088. }
  1089. }
  1090. void HttpServer::HandleGetUser(const httplib::Request& req, httplib::Response& res) {
  1091. // Authenticate the request
  1092. auto auth_user = AuthenticateRequest(req);
  1093. if (!auth_user) {
  1094. res.status = 401;
  1095. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1096. return;
  1097. }
  1098. // Check if UserService is available
  1099. if (!userService_) {
  1100. res.status = 503;
  1101. res.set_content(R"({"error":"User service not available"})", "application/json");
  1102. return;
  1103. }
  1104. try {
  1105. // Extract user ID from path
  1106. std::string user_id = req.matches[1].str();
  1107. // Users can only get their own info, or require system:users:read permission
  1108. bool is_own = (auth_user->user_id == user_id);
  1109. if (!is_own && !authorizationService_->HasPermission(*auth_user, permissions::kUsersRead)) {
  1110. res.status = 403;
  1111. res.set_content(R"({"error":"Forbidden - can only access your own user data or requires system:users:read permission"})", "application/json");
  1112. return;
  1113. }
  1114. auto result = userService_->GetUser(user_id);
  1115. if (!result.success) {
  1116. res.status = 404;
  1117. nlohmann::json error_response = {{"error", result.error}};
  1118. res.set_content(error_response.dump(), "application/json");
  1119. return;
  1120. }
  1121. // Return user (without password_hash)
  1122. nlohmann::json user_json = {
  1123. {"id", result.user->id},
  1124. {"email", result.user->email},
  1125. {"name", result.user->name},
  1126. {"created_at", result.user->created_at},
  1127. {"updated_at", result.user->updated_at}
  1128. };
  1129. res.set_content(user_json.dump(), "application/json");
  1130. } catch (const std::exception& e) {
  1131. spdlog::error("Get user error: {}", e.what());
  1132. res.status = 500;
  1133. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1134. }
  1135. }
  1136. void HttpServer::HandleUpdateUser(const httplib::Request& req, httplib::Response& res) {
  1137. // Authenticate the request
  1138. auto auth_user = AuthenticateRequest(req);
  1139. if (!auth_user) {
  1140. res.status = 401;
  1141. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1142. return;
  1143. }
  1144. // Check if UserService is available
  1145. if (!userService_) {
  1146. res.status = 503;
  1147. res.set_content(R"({"error":"User service not available"})", "application/json");
  1148. return;
  1149. }
  1150. try {
  1151. // Extract user ID from path
  1152. std::string user_id = req.matches[1].str();
  1153. // Users can only update their own info, or require system:users:update permission
  1154. bool is_own = (auth_user->user_id == user_id);
  1155. if (!is_own && !authorizationService_->HasPermission(*auth_user, permissions::kUsersUpdate)) {
  1156. res.status = 403;
  1157. res.set_content(R"({"error":"Forbidden - can only update your own user data or requires system:users:update permission"})", "application/json");
  1158. return;
  1159. }
  1160. auto body = nlohmann::json::parse(req.body);
  1161. UpdateUserRequest update_req;
  1162. update_req.actor_id = auth_user->user_id;
  1163. if (body.contains("email")) {
  1164. update_req.email = body["email"].get<std::string>();
  1165. }
  1166. if (body.contains("password")) {
  1167. update_req.password = body["password"].get<std::string>();
  1168. }
  1169. if (body.contains("name")) {
  1170. update_req.name = body["name"].get<std::string>();
  1171. }
  1172. auto result = userService_->UpdateUser(user_id, update_req);
  1173. if (!result.success) {
  1174. res.status = 400;
  1175. nlohmann::json error_response = {{"error", result.error}};
  1176. res.set_content(error_response.dump(), "application/json");
  1177. return;
  1178. }
  1179. // Return updated user (without password_hash)
  1180. nlohmann::json user_json = {
  1181. {"id", result.user->id},
  1182. {"email", result.user->email},
  1183. {"name", result.user->name},
  1184. {"created_at", result.user->created_at},
  1185. {"updated_at", result.user->updated_at}
  1186. };
  1187. res.set_content(user_json.dump(), "application/json");
  1188. } catch (const nlohmann::json::parse_error& e) {
  1189. res.status = 400;
  1190. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  1191. } catch (const std::exception& e) {
  1192. spdlog::error("Update user error: {}", e.what());
  1193. res.status = 500;
  1194. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1195. }
  1196. }
  1197. void HttpServer::HandleDeleteUser(const httplib::Request& req, httplib::Response& res) {
  1198. // Authenticate the request
  1199. auto auth_user = AuthenticateRequest(req);
  1200. if (!auth_user) {
  1201. res.status = 401;
  1202. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1203. return;
  1204. }
  1205. // Requires system:users:delete permission
  1206. if (!authorizationService_->HasPermission(*auth_user, permissions::kUsersDelete)) {
  1207. res.status = 403;
  1208. res.set_content(R"({"error":"Forbidden - requires system:users:delete permission"})", "application/json");
  1209. return;
  1210. }
  1211. // Check if UserService is available
  1212. if (!userService_) {
  1213. res.status = 503;
  1214. res.set_content(R"({"error":"User service not available"})", "application/json");
  1215. return;
  1216. }
  1217. try {
  1218. // Extract user ID from path
  1219. std::string user_id = req.matches[1].str();
  1220. auto result = userService_->DeleteUser(user_id);
  1221. if (!result.success) {
  1222. res.status = 404;
  1223. nlohmann::json error_response = {{"error", result.error}};
  1224. res.set_content(error_response.dump(), "application/json");
  1225. return;
  1226. }
  1227. res.set_content(R"({"message":"User deleted successfully"})", "application/json");
  1228. } catch (const std::exception& e) {
  1229. spdlog::error("Delete user error: {}", e.what());
  1230. res.status = 500;
  1231. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1232. }
  1233. }
  1234. // ============================================================================
  1235. // Workspace Management Routes Implementation
  1236. // ============================================================================
  1237. void HttpServer::SetupWorkspaceRoutes() {
  1238. // POST /api/workspaces - Create a new workspace (superadmin only)
  1239. httpServer_->Post("/api/workspaces", [this](const httplib::Request& req, httplib::Response& res) {
  1240. HandleCreateWorkspace(req, res);
  1241. });
  1242. // GET /api/workspaces - List workspaces (filtered by user membership for non-superadmin)
  1243. httpServer_->Get("/api/workspaces", [this](const httplib::Request& req, httplib::Response& res) {
  1244. HandleListWorkspaces(req, res);
  1245. });
  1246. // GET /api/workspaces/:id - Get a specific workspace
  1247. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1248. HandleGetWorkspace(req, res);
  1249. });
  1250. // PATCH /api/workspaces/:id - Update a workspace
  1251. httpServer_->Patch(R"(/api/workspaces/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1252. HandleUpdateWorkspace(req, res);
  1253. });
  1254. // DELETE /api/workspaces/:id - Soft delete a workspace (superadmin only)
  1255. httpServer_->Delete(R"(/api/workspaces/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1256. HandleDeleteWorkspace(req, res);
  1257. });
  1258. spdlog::info("Workspace management routes registered: /api/workspaces");
  1259. }
  1260. void HttpServer::HandleCreateWorkspace(const httplib::Request& req, httplib::Response& res) {
  1261. // Authenticate the request
  1262. auto auth_user = AuthenticateRequest(req);
  1263. if (!auth_user) {
  1264. res.status = 401;
  1265. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1266. return;
  1267. }
  1268. // Requires system:workspaces:create permission
  1269. if (!authorizationService_->HasPermission(*auth_user, permissions::kWorkspacesCreate)) {
  1270. res.status = 403;
  1271. res.set_content(R"({"error":"Forbidden - requires system:workspaces:create permission"})", "application/json");
  1272. return;
  1273. }
  1274. // Check if WorkspaceService is available
  1275. if (!workspaceService_) {
  1276. res.status = 503;
  1277. res.set_content(R"({"error":"Workspace service not available"})", "application/json");
  1278. return;
  1279. }
  1280. try {
  1281. auto body = nlohmann::json::parse(req.body);
  1282. CreateWorkspaceRequest create_req;
  1283. create_req.actor_id = auth_user->user_id;
  1284. if (body.contains("name")) {
  1285. create_req.name = body["name"].get<std::string>();
  1286. }
  1287. if (body.contains("settings")) {
  1288. create_req.settings = body["settings"];
  1289. }
  1290. auto result = workspaceService_->CreateWorkspace(create_req);
  1291. if (!result.success) {
  1292. res.status = 400;
  1293. nlohmann::json error_response = {{"error", result.error}};
  1294. res.set_content(error_response.dump(), "application/json");
  1295. return;
  1296. }
  1297. // Return created workspace
  1298. nlohmann::json workspace_json = {
  1299. {"id", result.workspace->id},
  1300. {"name", result.workspace->name},
  1301. {"settings", result.workspace->settings},
  1302. {"created_at", result.workspace->created_at},
  1303. {"updated_at", result.workspace->updated_at}
  1304. };
  1305. res.status = 201;
  1306. res.set_content(workspace_json.dump(), "application/json");
  1307. } catch (const nlohmann::json::parse_error& e) {
  1308. res.status = 400;
  1309. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  1310. } catch (const std::exception& e) {
  1311. spdlog::error("Create workspace error: {}", e.what());
  1312. res.status = 500;
  1313. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1314. }
  1315. }
  1316. void HttpServer::HandleListWorkspaces(const httplib::Request& req, httplib::Response& res) {
  1317. // Authenticate the request
  1318. auto auth_user = AuthenticateRequest(req);
  1319. if (!auth_user) {
  1320. res.status = 401;
  1321. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1322. return;
  1323. }
  1324. // Check if WorkspaceService is available
  1325. if (!workspaceService_) {
  1326. res.status = 503;
  1327. res.set_content(R"({"error":"Workspace service not available"})", "application/json");
  1328. return;
  1329. }
  1330. try {
  1331. WorkspaceListResult result;
  1332. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kWorkspacesRead);
  1333. // Users with system:workspaces:read can see all workspaces, others only see their memberships
  1334. if (has_system_access) {
  1335. // Parse query parameters
  1336. int limit = 100;
  1337. int offset = 0;
  1338. bool include_deleted = false;
  1339. if (req.has_param("limit")) {
  1340. limit = std::stoi(req.get_param_value("limit"));
  1341. if (limit < 1 || limit > 1000) {
  1342. limit = 100;
  1343. }
  1344. }
  1345. if (req.has_param("offset")) {
  1346. offset = std::stoi(req.get_param_value("offset"));
  1347. if (offset < 0) {
  1348. offset = 0;
  1349. }
  1350. }
  1351. if (req.has_param("include_deleted")) {
  1352. include_deleted = req.get_param_value("include_deleted") == "true";
  1353. }
  1354. result = workspaceService_->ListWorkspaces(limit, offset, include_deleted);
  1355. } else {
  1356. // Non-privileged user: filter by user's workspace memberships
  1357. result = workspaceService_->ListWorkspacesByIds(auth_user->workspace_ids, false);
  1358. }
  1359. if (!result.success) {
  1360. res.status = 500;
  1361. nlohmann::json error_response = {{"error", result.error}};
  1362. res.set_content(error_response.dump(), "application/json");
  1363. return;
  1364. }
  1365. // Build response
  1366. nlohmann::json workspaces_array = nlohmann::json::array();
  1367. for (const auto& workspace : result.workspaces) {
  1368. nlohmann::json ws_json = {
  1369. {"id", workspace.id},
  1370. {"name", workspace.name},
  1371. {"settings", workspace.settings},
  1372. {"created_at", workspace.created_at},
  1373. {"updated_at", workspace.updated_at},
  1374. {"created_by", workspace.created_by},
  1375. {"updated_by", workspace.updated_by},
  1376. {"created_by_name", ResolveUserName(workspace.created_by)},
  1377. {"updated_by_name", ResolveUserName(workspace.updated_by)}
  1378. };
  1379. if (has_system_access) {
  1380. ws_json["deleted_at"] = workspace.deleted_at;
  1381. }
  1382. workspaces_array.push_back(ws_json);
  1383. }
  1384. nlohmann::json response = {
  1385. {"workspaces", workspaces_array},
  1386. {"total_count", result.total_count}
  1387. };
  1388. res.set_content(response.dump(), "application/json");
  1389. } catch (const std::exception& e) {
  1390. spdlog::error("List workspaces error: {}", e.what());
  1391. res.status = 500;
  1392. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1393. }
  1394. }
  1395. void HttpServer::HandleGetWorkspace(const httplib::Request& req, httplib::Response& res) {
  1396. // Authenticate the request
  1397. auto auth_user = AuthenticateRequest(req);
  1398. if (!auth_user) {
  1399. res.status = 401;
  1400. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1401. return;
  1402. }
  1403. // Check if WorkspaceService is available
  1404. if (!workspaceService_) {
  1405. res.status = 503;
  1406. res.set_content(R"({"error":"Workspace service not available"})", "application/json");
  1407. return;
  1408. }
  1409. try {
  1410. // Extract workspace ID from path
  1411. std::string workspace_id = req.matches[1].str();
  1412. // Check access: must be member OR have system:workspaces:read permission
  1413. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  1414. auth_user->workspace_ids.end(),
  1415. workspace_id) != auth_user->workspace_ids.end());
  1416. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kWorkspacesRead);
  1417. if (!is_member && !has_system_access) {
  1418. res.status = 403;
  1419. res.set_content(R"({"error":"Forbidden - not a member of this workspace"})", "application/json");
  1420. return;
  1421. }
  1422. auto result = workspaceService_->GetWorkspace(workspace_id);
  1423. if (!result.success) {
  1424. res.status = 404;
  1425. nlohmann::json error_response = {{"error", result.error}};
  1426. res.set_content(error_response.dump(), "application/json");
  1427. return;
  1428. }
  1429. // Return workspace
  1430. nlohmann::json workspace_json = {
  1431. {"id", result.workspace->id},
  1432. {"name", result.workspace->name},
  1433. {"settings", result.workspace->settings},
  1434. {"created_at", result.workspace->created_at},
  1435. {"updated_at", result.workspace->updated_at}
  1436. };
  1437. res.set_content(workspace_json.dump(), "application/json");
  1438. } catch (const std::exception& e) {
  1439. spdlog::error("Get workspace error: {}", e.what());
  1440. res.status = 500;
  1441. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1442. }
  1443. }
  1444. void HttpServer::HandleUpdateWorkspace(const httplib::Request& req, httplib::Response& res) {
  1445. // Authenticate the request
  1446. auto auth_user = AuthenticateRequest(req);
  1447. if (!auth_user) {
  1448. res.status = 401;
  1449. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1450. return;
  1451. }
  1452. // Extract workspace ID from path (needed for IsWorkspaceAdmin check)
  1453. std::string workspace_id = req.matches[1].str();
  1454. // Requires system:workspaces:update permission OR workspace admin
  1455. bool can_update = authorizationService_->HasPermission(*auth_user, permissions::kWorkspacesUpdate) ||
  1456. authorizationService_->IsWorkspaceAdmin(*auth_user, workspace_id);
  1457. if (!can_update) {
  1458. res.status = 403;
  1459. res.set_content(R"({"error":"Forbidden - requires system:workspaces:update permission or workspace admin"})", "application/json");
  1460. return;
  1461. }
  1462. // Check if WorkspaceService is available
  1463. if (!workspaceService_) {
  1464. res.status = 503;
  1465. res.set_content(R"({"error":"Workspace service not available"})", "application/json");
  1466. return;
  1467. }
  1468. try {
  1469. auto body = nlohmann::json::parse(req.body);
  1470. UpdateWorkspaceRequest update_req;
  1471. update_req.actor_id = auth_user->user_id;
  1472. if (body.contains("name")) {
  1473. update_req.name = body["name"].get<std::string>();
  1474. }
  1475. if (body.contains("settings")) {
  1476. update_req.settings = body["settings"];
  1477. }
  1478. auto result = workspaceService_->UpdateWorkspace(workspace_id, update_req);
  1479. if (!result.success) {
  1480. res.status = 400;
  1481. nlohmann::json error_response = {{"error", result.error}};
  1482. res.set_content(error_response.dump(), "application/json");
  1483. return;
  1484. }
  1485. // Return updated workspace
  1486. nlohmann::json workspace_json = {
  1487. {"id", result.workspace->id},
  1488. {"name", result.workspace->name},
  1489. {"settings", result.workspace->settings},
  1490. {"created_at", result.workspace->created_at},
  1491. {"updated_at", result.workspace->updated_at}
  1492. };
  1493. res.set_content(workspace_json.dump(), "application/json");
  1494. } catch (const nlohmann::json::parse_error& e) {
  1495. res.status = 400;
  1496. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  1497. } catch (const std::exception& e) {
  1498. spdlog::error("Update workspace error: {}", e.what());
  1499. res.status = 500;
  1500. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1501. }
  1502. }
  1503. void HttpServer::HandleDeleteWorkspace(const httplib::Request& req, httplib::Response& res) {
  1504. // Authenticate the request
  1505. auto auth_user = AuthenticateRequest(req);
  1506. if (!auth_user) {
  1507. res.status = 401;
  1508. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1509. return;
  1510. }
  1511. // Requires system:workspaces:delete permission
  1512. if (!authorizationService_->HasPermission(*auth_user, permissions::kWorkspacesDelete)) {
  1513. res.status = 403;
  1514. res.set_content(R"({"error":"Forbidden - requires system:workspaces:delete permission"})", "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. // Extract workspace ID from path
  1525. std::string workspace_id = req.matches[1].str();
  1526. auto result = workspaceService_->DeleteWorkspace(workspace_id);
  1527. if (!result.success) {
  1528. res.status = 404;
  1529. nlohmann::json error_response = {{"error", result.error}};
  1530. res.set_content(error_response.dump(), "application/json");
  1531. return;
  1532. }
  1533. res.set_content(R"({"message":"Workspace deleted successfully"})", "application/json");
  1534. } catch (const std::exception& e) {
  1535. spdlog::error("Delete workspace error: {}", e.what());
  1536. res.status = 500;
  1537. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1538. }
  1539. }
  1540. // ============================================================================
  1541. // Group Management Routes Implementation
  1542. // ============================================================================
  1543. void HttpServer::SetupGroupRoutes() {
  1544. // POST /api/workspaces/:wid/groups - Create a new group in workspace
  1545. httpServer_->Post(R"(/api/workspaces/([a-zA-Z0-9\-]+)/groups)", [this](const httplib::Request& req, httplib::Response& res) {
  1546. HandleCreateGroup(req, res);
  1547. });
  1548. // GET /api/workspaces/:wid/groups - List groups in workspace
  1549. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+)/groups)", [this](const httplib::Request& req, httplib::Response& res) {
  1550. HandleListGroups(req, res);
  1551. });
  1552. // GET /api/workspaces/:wid/groups/:id - Get a specific group
  1553. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+)/groups/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1554. HandleGetGroup(req, res);
  1555. });
  1556. // PATCH /api/workspaces/:wid/groups/:id - Update a group
  1557. httpServer_->Patch(R"(/api/workspaces/([a-zA-Z0-9\-]+)/groups/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1558. HandleUpdateGroup(req, res);
  1559. });
  1560. // DELETE /api/workspaces/:wid/groups/:id - Delete a group
  1561. httpServer_->Delete(R"(/api/workspaces/([a-zA-Z0-9\-]+)/groups/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1562. HandleDeleteGroup(req, res);
  1563. });
  1564. spdlog::info("Group management routes registered: /api/workspaces/:wid/groups");
  1565. }
  1566. void HttpServer::HandleCreateGroup(const httplib::Request& req, httplib::Response& res) {
  1567. // Authenticate the request
  1568. auto auth_user = AuthenticateRequest(req);
  1569. if (!auth_user) {
  1570. res.status = 401;
  1571. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1572. return;
  1573. }
  1574. // Extract workspace ID from path
  1575. std::string workspace_id = req.matches[1].str();
  1576. // Requires system:groups:create permission OR workspace group management permission
  1577. bool can_create = authorizationService_->HasPermission(*auth_user, permissions::kGroupsCreate) ||
  1578. authorizationService_->CanManageWorkspaceGroups(*auth_user, workspace_id);
  1579. if (!can_create) {
  1580. res.status = 403;
  1581. res.set_content(R"({"error":"Forbidden - requires system:groups:create permission or workspace group management"})", "application/json");
  1582. return;
  1583. }
  1584. // Check if GroupService is available
  1585. if (!groupService_) {
  1586. res.status = 503;
  1587. res.set_content(R"({"error":"Group service not available"})", "application/json");
  1588. return;
  1589. }
  1590. try {
  1591. auto body = nlohmann::json::parse(req.body);
  1592. CreateGroupRequest create_req;
  1593. create_req.workspace_id = workspace_id;
  1594. create_req.actor_id = auth_user->user_id;
  1595. if (body.contains("name")) {
  1596. create_req.name = body["name"].get<std::string>();
  1597. }
  1598. if (body.contains("permissions") && body["permissions"].is_array()) {
  1599. for (const auto& perm : body["permissions"]) {
  1600. if (perm.is_string()) {
  1601. create_req.permissions.push_back(perm.get<std::string>());
  1602. }
  1603. }
  1604. }
  1605. auto result = groupService_->CreateGroup(create_req);
  1606. if (!result.success) {
  1607. res.status = 400;
  1608. nlohmann::json error_response = {{"error", result.error}};
  1609. res.set_content(error_response.dump(), "application/json");
  1610. return;
  1611. }
  1612. // Return created group
  1613. nlohmann::json group_json = {
  1614. {"id", result.group->id},
  1615. {"workspace_id", result.group->workspace_id},
  1616. {"name", result.group->name},
  1617. {"permissions", result.group->permissions},
  1618. {"created_at", result.group->created_at},
  1619. {"updated_at", result.group->updated_at}
  1620. };
  1621. res.status = 201;
  1622. res.set_content(group_json.dump(), "application/json");
  1623. } catch (const nlohmann::json::parse_error& e) {
  1624. res.status = 400;
  1625. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  1626. } catch (const std::exception& e) {
  1627. spdlog::error("Create group error: {}", e.what());
  1628. res.status = 500;
  1629. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1630. }
  1631. }
  1632. void HttpServer::HandleListGroups(const httplib::Request& req, httplib::Response& res) {
  1633. // Authenticate the request
  1634. auto auth_user = AuthenticateRequest(req);
  1635. if (!auth_user) {
  1636. res.status = 401;
  1637. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1638. return;
  1639. }
  1640. // Extract workspace ID from path
  1641. std::string workspace_id = req.matches[1].str();
  1642. // Check access: must be member OR have system:groups:read permission
  1643. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  1644. auth_user->workspace_ids.end(),
  1645. workspace_id) != auth_user->workspace_ids.end());
  1646. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kGroupsRead);
  1647. if (!is_member && !has_system_access) {
  1648. res.status = 403;
  1649. res.set_content(R"({"error":"Forbidden - not a member of this workspace"})", "application/json");
  1650. return;
  1651. }
  1652. // Check if GroupService is available
  1653. if (!groupService_) {
  1654. res.status = 503;
  1655. res.set_content(R"({"error":"Group service not available"})", "application/json");
  1656. return;
  1657. }
  1658. try {
  1659. // Parse query parameters
  1660. int limit = 100;
  1661. int offset = 0;
  1662. bool include_deleted = false;
  1663. if (req.has_param("limit")) {
  1664. limit = std::stoi(req.get_param_value("limit"));
  1665. if (limit < 1 || limit > 1000) {
  1666. limit = 100;
  1667. }
  1668. }
  1669. if (req.has_param("offset")) {
  1670. offset = std::stoi(req.get_param_value("offset"));
  1671. if (offset < 0) {
  1672. offset = 0;
  1673. }
  1674. }
  1675. if (has_system_access && req.has_param("include_deleted")) {
  1676. include_deleted = req.get_param_value("include_deleted") == "true";
  1677. }
  1678. bool include_system = has_system_access &&
  1679. req.has_param("include_system") &&
  1680. req.get_param_value("include_system") == "true";
  1681. auto result = groupService_->ListGroups(workspace_id, limit, offset, include_deleted);
  1682. if (!result.success) {
  1683. res.status = 500;
  1684. nlohmann::json error_response = {{"error", result.error}};
  1685. res.set_content(error_response.dump(), "application/json");
  1686. return;
  1687. }
  1688. // Build response
  1689. nlohmann::json groups_array = nlohmann::json::array();
  1690. // Add global system groups first if requested
  1691. if (include_system) {
  1692. auto global_result = groupService_->ListSystemGroups();
  1693. if (global_result.success) {
  1694. for (const auto& group : global_result.groups) {
  1695. nlohmann::json grp_json = {
  1696. {"id", group.id},
  1697. {"workspace_id", group.workspace_id},
  1698. {"name", group.name},
  1699. {"permissions", group.permissions},
  1700. {"is_system", group.is_system},
  1701. {"parent_group_id", group.parent_group_id},
  1702. {"created_at", group.created_at},
  1703. {"updated_at", group.updated_at},
  1704. {"deleted_at", group.deleted_at},
  1705. {"created_by", group.created_by},
  1706. {"updated_by", group.updated_by},
  1707. {"created_by_name", ResolveUserName(group.created_by)},
  1708. {"updated_by_name", ResolveUserName(group.updated_by)}
  1709. };
  1710. groups_array.push_back(grp_json);
  1711. }
  1712. }
  1713. }
  1714. for (const auto& group : result.groups) {
  1715. nlohmann::json grp_json = {
  1716. {"id", group.id},
  1717. {"workspace_id", group.workspace_id},
  1718. {"name", group.name},
  1719. {"permissions", group.permissions},
  1720. {"is_system", group.is_system},
  1721. {"parent_group_id", group.parent_group_id},
  1722. {"created_at", group.created_at},
  1723. {"updated_at", group.updated_at},
  1724. {"created_by", group.created_by},
  1725. {"updated_by", group.updated_by},
  1726. {"created_by_name", ResolveUserName(group.created_by)},
  1727. {"updated_by_name", ResolveUserName(group.updated_by)}
  1728. };
  1729. if (has_system_access) {
  1730. grp_json["deleted_at"] = group.deleted_at;
  1731. }
  1732. groups_array.push_back(grp_json);
  1733. }
  1734. nlohmann::json response = {
  1735. {"groups", groups_array},
  1736. {"total_count", result.total_count}
  1737. };
  1738. res.set_content(response.dump(), "application/json");
  1739. } catch (const std::exception& e) {
  1740. spdlog::error("List groups error: {}", e.what());
  1741. res.status = 500;
  1742. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1743. }
  1744. }
  1745. void HttpServer::HandleGetGroup(const httplib::Request& req, httplib::Response& res) {
  1746. // Authenticate the request
  1747. auto auth_user = AuthenticateRequest(req);
  1748. if (!auth_user) {
  1749. res.status = 401;
  1750. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1751. return;
  1752. }
  1753. // Extract workspace ID and group ID from path
  1754. std::string workspace_id = req.matches[1].str();
  1755. std::string group_id = req.matches[2].str();
  1756. // Check access: must be member OR have system:groups:read permission
  1757. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  1758. auth_user->workspace_ids.end(),
  1759. workspace_id) != auth_user->workspace_ids.end());
  1760. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kGroupsRead);
  1761. if (!is_member && !has_system_access) {
  1762. res.status = 403;
  1763. res.set_content(R"({"error":"Forbidden - not a member of this workspace"})", "application/json");
  1764. return;
  1765. }
  1766. // Check if GroupService is available
  1767. if (!groupService_) {
  1768. res.status = 503;
  1769. res.set_content(R"({"error":"Group service not available"})", "application/json");
  1770. return;
  1771. }
  1772. try {
  1773. auto result = groupService_->GetGroup(group_id);
  1774. if (!result.success) {
  1775. res.status = 404;
  1776. nlohmann::json error_response = {{"error", result.error}};
  1777. res.set_content(error_response.dump(), "application/json");
  1778. return;
  1779. }
  1780. // Verify group belongs to the workspace
  1781. if (result.group->workspace_id != workspace_id) {
  1782. res.status = 404;
  1783. res.set_content(R"({"error":"Group not found in this workspace"})", "application/json");
  1784. return;
  1785. }
  1786. // Return group
  1787. nlohmann::json group_json = {
  1788. {"id", result.group->id},
  1789. {"workspace_id", result.group->workspace_id},
  1790. {"name", result.group->name},
  1791. {"permissions", result.group->permissions},
  1792. {"created_at", result.group->created_at},
  1793. {"updated_at", result.group->updated_at}
  1794. };
  1795. res.set_content(group_json.dump(), "application/json");
  1796. } catch (const std::exception& e) {
  1797. spdlog::error("Get group error: {}", e.what());
  1798. res.status = 500;
  1799. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1800. }
  1801. }
  1802. void HttpServer::HandleUpdateGroup(const httplib::Request& req, httplib::Response& res) {
  1803. // Authenticate the request
  1804. auto auth_user = AuthenticateRequest(req);
  1805. if (!auth_user) {
  1806. res.status = 401;
  1807. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1808. return;
  1809. }
  1810. // Extract workspace ID and group ID from path
  1811. std::string workspace_id = req.matches[1].str();
  1812. std::string group_id = req.matches[2].str();
  1813. // Requires system:groups:update permission OR workspace group management permission
  1814. bool can_update = authorizationService_->HasPermission(*auth_user, permissions::kGroupsUpdate) ||
  1815. authorizationService_->CanManageWorkspaceGroups(*auth_user, workspace_id);
  1816. if (!can_update) {
  1817. res.status = 403;
  1818. res.set_content(R"({"error":"Forbidden - requires system:groups:update permission or workspace group management"})", "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. // First verify group belongs to the workspace
  1829. auto existing = groupService_->GetGroup(group_id);
  1830. if (!existing.success) {
  1831. res.status = 404;
  1832. nlohmann::json error_response = {{"error", existing.error}};
  1833. res.set_content(error_response.dump(), "application/json");
  1834. return;
  1835. }
  1836. if (existing.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. auto body = nlohmann::json::parse(req.body);
  1842. UpdateGroupRequest update_req;
  1843. update_req.actor_id = auth_user->user_id;
  1844. if (body.contains("name")) {
  1845. update_req.name = body["name"].get<std::string>();
  1846. }
  1847. if (body.contains("permissions") && body["permissions"].is_array()) {
  1848. std::vector<std::string> perms;
  1849. for (const auto& perm : body["permissions"]) {
  1850. if (perm.is_string()) {
  1851. perms.push_back(perm.get<std::string>());
  1852. }
  1853. }
  1854. update_req.permissions = perms;
  1855. }
  1856. auto result = groupService_->UpdateGroup(group_id, update_req);
  1857. if (!result.success) {
  1858. res.status = 400;
  1859. nlohmann::json error_response = {{"error", result.error}};
  1860. res.set_content(error_response.dump(), "application/json");
  1861. return;
  1862. }
  1863. // Return updated group
  1864. nlohmann::json group_json = {
  1865. {"id", result.group->id},
  1866. {"workspace_id", result.group->workspace_id},
  1867. {"name", result.group->name},
  1868. {"permissions", result.group->permissions},
  1869. {"created_at", result.group->created_at},
  1870. {"updated_at", result.group->updated_at}
  1871. };
  1872. res.set_content(group_json.dump(), "application/json");
  1873. } catch (const nlohmann::json::parse_error& e) {
  1874. res.status = 400;
  1875. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  1876. } catch (const std::exception& e) {
  1877. spdlog::error("Update group error: {}", e.what());
  1878. res.status = 500;
  1879. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1880. }
  1881. }
  1882. void HttpServer::HandleDeleteGroup(const httplib::Request& req, httplib::Response& res) {
  1883. // Authenticate the request
  1884. auto auth_user = AuthenticateRequest(req);
  1885. if (!auth_user) {
  1886. res.status = 401;
  1887. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1888. return;
  1889. }
  1890. // Extract workspace ID and group ID from path
  1891. std::string workspace_id = req.matches[1].str();
  1892. std::string group_id = req.matches[2].str();
  1893. // Requires system:groups:delete permission OR workspace group management permission
  1894. bool can_delete = authorizationService_->HasPermission(*auth_user, permissions::kGroupsDelete) ||
  1895. authorizationService_->CanManageWorkspaceGroups(*auth_user, workspace_id);
  1896. if (!can_delete) {
  1897. res.status = 403;
  1898. res.set_content(R"({"error":"Forbidden - requires system:groups:delete permission or workspace group management"})", "application/json");
  1899. return;
  1900. }
  1901. // Check if GroupService is available
  1902. if (!groupService_) {
  1903. res.status = 503;
  1904. res.set_content(R"({"error":"Group service not available"})", "application/json");
  1905. return;
  1906. }
  1907. try {
  1908. // First verify group belongs to the workspace
  1909. auto existing = groupService_->GetGroup(group_id);
  1910. if (!existing.success) {
  1911. res.status = 404;
  1912. nlohmann::json error_response = {{"error", existing.error}};
  1913. res.set_content(error_response.dump(), "application/json");
  1914. return;
  1915. }
  1916. if (existing.group->workspace_id != workspace_id) {
  1917. res.status = 404;
  1918. res.set_content(R"({"error":"Group not found in this workspace"})", "application/json");
  1919. return;
  1920. }
  1921. auto result = groupService_->DeleteGroup(group_id);
  1922. if (!result.success) {
  1923. res.status = 400;
  1924. nlohmann::json error_response = {{"error", result.error}};
  1925. res.set_content(error_response.dump(), "application/json");
  1926. return;
  1927. }
  1928. res.set_content(R"({"message":"Group deleted successfully"})", "application/json");
  1929. } catch (const std::exception& e) {
  1930. spdlog::error("Delete group error: {}", e.what());
  1931. res.status = 500;
  1932. res.set_content(R"({"error":"Internal server error"})", "application/json");
  1933. }
  1934. }
  1935. // ============================================================================
  1936. // Membership Routes
  1937. // ============================================================================
  1938. void HttpServer::SetupMembershipRoutes() {
  1939. // POST /api/workspaces/:wid/members - Add a user to workspace
  1940. httpServer_->Post(R"(/api/workspaces/([a-zA-Z0-9\-]+)/members)", [this](const httplib::Request& req, httplib::Response& res) {
  1941. HandleAddMember(req, res);
  1942. });
  1943. // GET /api/workspaces/:wid/members - List members in workspace
  1944. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+)/members)", [this](const httplib::Request& req, httplib::Response& res) {
  1945. HandleListMembers(req, res);
  1946. });
  1947. // GET /api/workspaces/:wid/members/:userId - Get a specific member
  1948. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+)/members/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1949. HandleGetMember(req, res);
  1950. });
  1951. // PUT /api/workspaces/:wid/members/:userId - Update user's groups in workspace
  1952. httpServer_->Put(R"(/api/workspaces/([a-zA-Z0-9\-]+)/members/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1953. HandleUpdateMember(req, res);
  1954. });
  1955. // DELETE /api/workspaces/:wid/members/:userId - Remove user from workspace
  1956. httpServer_->Delete(R"(/api/workspaces/([a-zA-Z0-9\-]+)/members/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  1957. HandleRemoveMember(req, res);
  1958. });
  1959. spdlog::info("Membership routes registered: /api/workspaces/:wid/members");
  1960. }
  1961. void HttpServer::HandleAddMember(const httplib::Request& req, httplib::Response& res) {
  1962. // Authenticate the request
  1963. auto auth_user = AuthenticateRequest(req);
  1964. if (!auth_user) {
  1965. res.status = 401;
  1966. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  1967. return;
  1968. }
  1969. // Extract workspace ID from path
  1970. std::string workspace_id = req.matches[1].str();
  1971. // Requires system:memberships:create permission OR workspace member management permission
  1972. bool can_add = authorizationService_->HasPermission(*auth_user, permissions::kMembershipsCreate) ||
  1973. authorizationService_->CanManageWorkspaceMembers(*auth_user, workspace_id);
  1974. if (!can_add) {
  1975. res.status = 403;
  1976. res.set_content(R"({"error":"Forbidden - requires system:memberships:create permission or workspace member management"})", "application/json");
  1977. return;
  1978. }
  1979. // Check if MembershipService is available
  1980. if (!membershipService_) {
  1981. res.status = 503;
  1982. res.set_content(R"({"error":"Membership service not available"})", "application/json");
  1983. return;
  1984. }
  1985. try {
  1986. // Parse request body
  1987. auto json = nlohmann::json::parse(req.body);
  1988. AddMemberRequest add_req;
  1989. add_req.workspace_id = workspace_id;
  1990. if (json.contains("user_id") && json["user_id"].is_string()) {
  1991. add_req.user_id = json["user_id"].get<std::string>();
  1992. } else {
  1993. res.status = 400;
  1994. res.set_content(R"({"error":"user_id is required"})", "application/json");
  1995. return;
  1996. }
  1997. if (json.contains("group_ids") && json["group_ids"].is_array()) {
  1998. for (const auto& item : json["group_ids"]) {
  1999. if (item.is_string()) {
  2000. add_req.group_ids.push_back(item.get<std::string>());
  2001. }
  2002. }
  2003. }
  2004. auto result = membershipService_->AddMember(add_req);
  2005. if (!result.success) {
  2006. res.status = 400;
  2007. nlohmann::json error_response = {{"error", result.error}};
  2008. res.set_content(error_response.dump(), "application/json");
  2009. return;
  2010. }
  2011. // Return created membership
  2012. nlohmann::json member_json = {
  2013. {"id", result.member->id},
  2014. {"workspace_id", result.member->workspace_id},
  2015. {"user_id", result.member->user_id},
  2016. {"group_ids", result.member->group_ids},
  2017. {"created_at", result.member->created_at},
  2018. {"updated_at", result.member->updated_at}
  2019. };
  2020. res.status = 201;
  2021. res.set_content(member_json.dump(), "application/json");
  2022. } catch (const nlohmann::json::exception& e) {
  2023. res.status = 400;
  2024. nlohmann::json error_response = {{"error", "Invalid JSON: " + std::string(e.what())}};
  2025. res.set_content(error_response.dump(), "application/json");
  2026. } catch (const std::exception& e) {
  2027. spdlog::error("Add member error: {}", e.what());
  2028. res.status = 500;
  2029. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2030. }
  2031. }
  2032. void HttpServer::HandleListMembers(const httplib::Request& req, httplib::Response& res) {
  2033. // Authenticate the request
  2034. auto auth_user = AuthenticateRequest(req);
  2035. if (!auth_user) {
  2036. res.status = 401;
  2037. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2038. return;
  2039. }
  2040. // Extract workspace ID from path
  2041. std::string workspace_id = req.matches[1].str();
  2042. // Check access: must be member OR have system:memberships:read permission
  2043. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  2044. auth_user->workspace_ids.end(),
  2045. workspace_id) != auth_user->workspace_ids.end());
  2046. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kMembershipsRead);
  2047. if (!is_member && !has_system_access) {
  2048. res.status = 403;
  2049. res.set_content(R"({"error":"Forbidden - not a member of this workspace"})", "application/json");
  2050. return;
  2051. }
  2052. // Check if MembershipService is available
  2053. if (!membershipService_) {
  2054. res.status = 503;
  2055. res.set_content(R"({"error":"Membership service not available"})", "application/json");
  2056. return;
  2057. }
  2058. try {
  2059. // Get query parameters
  2060. int limit = 100;
  2061. int offset = 0;
  2062. bool include_deleted = false;
  2063. if (req.has_param("limit")) {
  2064. limit = std::stoi(req.get_param_value("limit"));
  2065. if (limit < 1 || limit > 1000) {
  2066. limit = 100;
  2067. }
  2068. }
  2069. if (req.has_param("offset")) {
  2070. offset = std::stoi(req.get_param_value("offset"));
  2071. if (offset < 0) {
  2072. offset = 0;
  2073. }
  2074. }
  2075. if (has_system_access && req.has_param("include_deleted")) {
  2076. include_deleted = req.get_param_value("include_deleted") == "true";
  2077. }
  2078. auto result = membershipService_->ListMembers(workspace_id, limit, offset, include_deleted);
  2079. if (!result.success) {
  2080. res.status = 500;
  2081. nlohmann::json error_response = {{"error", result.error}};
  2082. res.set_content(error_response.dump(), "application/json");
  2083. return;
  2084. }
  2085. // Build response with user details
  2086. nlohmann::json members_array = nlohmann::json::array();
  2087. for (const auto& member : result.members) {
  2088. nlohmann::json member_json = {
  2089. {"id", member.id},
  2090. {"workspace_id", member.workspace_id},
  2091. {"user_id", member.user_id},
  2092. {"group_ids", member.group_ids},
  2093. {"created_at", member.created_at},
  2094. {"updated_at", member.updated_at}
  2095. };
  2096. if (has_system_access) {
  2097. member_json["deleted_at"] = member.deleted_at;
  2098. }
  2099. // Fetch user details if UserService is available
  2100. if (userService_) {
  2101. auto user_result = userService_->GetUser(member.user_id);
  2102. if (user_result.success && user_result.user) {
  2103. member_json["user"] = {
  2104. {"id", user_result.user->id},
  2105. {"email", user_result.user->email},
  2106. {"name", user_result.user->name},
  2107. {"created_at", user_result.user->created_at}
  2108. };
  2109. }
  2110. }
  2111. members_array.push_back(member_json);
  2112. }
  2113. nlohmann::json response = {
  2114. {"members", members_array},
  2115. {"total_count", result.total_count}
  2116. };
  2117. res.set_content(response.dump(), "application/json");
  2118. } catch (const std::exception& e) {
  2119. spdlog::error("List members error: {}", e.what());
  2120. res.status = 500;
  2121. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2122. }
  2123. }
  2124. void HttpServer::HandleGetMember(const httplib::Request& req, httplib::Response& res) {
  2125. // Authenticate the request
  2126. auto auth_user = AuthenticateRequest(req);
  2127. if (!auth_user) {
  2128. res.status = 401;
  2129. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2130. return;
  2131. }
  2132. // Extract workspace ID and user ID from path
  2133. std::string workspace_id = req.matches[1].str();
  2134. std::string user_id = req.matches[2].str();
  2135. // Check access: must be member OR have system:memberships:read permission
  2136. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  2137. auth_user->workspace_ids.end(),
  2138. workspace_id) != auth_user->workspace_ids.end());
  2139. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kMembershipsRead);
  2140. if (!is_member && !has_system_access) {
  2141. res.status = 403;
  2142. res.set_content(R"({"error":"Forbidden - not a member of this workspace"})", "application/json");
  2143. return;
  2144. }
  2145. // Check if MembershipService is available
  2146. if (!membershipService_) {
  2147. res.status = 503;
  2148. res.set_content(R"({"error":"Membership service not available"})", "application/json");
  2149. return;
  2150. }
  2151. try {
  2152. auto result = membershipService_->GetMembershipByUser(workspace_id, user_id);
  2153. if (!result.success) {
  2154. res.status = 404;
  2155. nlohmann::json error_response = {{"error", result.error}};
  2156. res.set_content(error_response.dump(), "application/json");
  2157. return;
  2158. }
  2159. // Return membership
  2160. nlohmann::json member_json = {
  2161. {"id", result.member->id},
  2162. {"workspace_id", result.member->workspace_id},
  2163. {"user_id", result.member->user_id},
  2164. {"group_ids", result.member->group_ids},
  2165. {"created_at", result.member->created_at},
  2166. {"updated_at", result.member->updated_at}
  2167. };
  2168. res.set_content(member_json.dump(), "application/json");
  2169. } catch (const std::exception& e) {
  2170. spdlog::error("Get member error: {}", e.what());
  2171. res.status = 500;
  2172. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2173. }
  2174. }
  2175. void HttpServer::HandleUpdateMember(const httplib::Request& req, httplib::Response& res) {
  2176. // Authenticate the request
  2177. auto auth_user = AuthenticateRequest(req);
  2178. if (!auth_user) {
  2179. res.status = 401;
  2180. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2181. return;
  2182. }
  2183. // Extract workspace ID and user ID from path
  2184. std::string workspace_id = req.matches[1].str();
  2185. std::string user_id = req.matches[2].str();
  2186. // Requires system:memberships:update permission OR workspace member management permission
  2187. bool can_update = authorizationService_->HasPermission(*auth_user, permissions::kMembershipsUpdate) ||
  2188. authorizationService_->CanManageWorkspaceMembers(*auth_user, workspace_id);
  2189. if (!can_update) {
  2190. res.status = 403;
  2191. res.set_content(R"({"error":"Forbidden - requires system:memberships:update permission or workspace member management"})", "application/json");
  2192. return;
  2193. }
  2194. // Check if MembershipService is available
  2195. if (!membershipService_) {
  2196. res.status = 503;
  2197. res.set_content(R"({"error":"Membership service not available"})", "application/json");
  2198. return;
  2199. }
  2200. try {
  2201. // Parse request body
  2202. auto json = nlohmann::json::parse(req.body);
  2203. UpdateMemberRequest update_req;
  2204. if (json.contains("group_ids") && json["group_ids"].is_array()) {
  2205. std::vector<std::string> group_ids;
  2206. for (const auto& item : json["group_ids"]) {
  2207. if (item.is_string()) {
  2208. group_ids.push_back(item.get<std::string>());
  2209. }
  2210. }
  2211. update_req.group_ids = group_ids;
  2212. }
  2213. auto result = membershipService_->UpdateMembership(workspace_id, user_id, update_req);
  2214. if (!result.success) {
  2215. res.status = 400;
  2216. nlohmann::json error_response = {{"error", result.error}};
  2217. res.set_content(error_response.dump(), "application/json");
  2218. return;
  2219. }
  2220. // Return updated membership
  2221. nlohmann::json member_json = {
  2222. {"id", result.member->id},
  2223. {"workspace_id", result.member->workspace_id},
  2224. {"user_id", result.member->user_id},
  2225. {"group_ids", result.member->group_ids},
  2226. {"created_at", result.member->created_at},
  2227. {"updated_at", result.member->updated_at}
  2228. };
  2229. res.set_content(member_json.dump(), "application/json");
  2230. } catch (const nlohmann::json::exception& e) {
  2231. res.status = 400;
  2232. nlohmann::json error_response = {{"error", "Invalid JSON: " + std::string(e.what())}};
  2233. res.set_content(error_response.dump(), "application/json");
  2234. } catch (const std::exception& e) {
  2235. spdlog::error("Update member error: {}", e.what());
  2236. res.status = 500;
  2237. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2238. }
  2239. }
  2240. void HttpServer::HandleRemoveMember(const httplib::Request& req, httplib::Response& res) {
  2241. // Authenticate the request
  2242. auto auth_user = AuthenticateRequest(req);
  2243. if (!auth_user) {
  2244. res.status = 401;
  2245. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2246. return;
  2247. }
  2248. // Extract workspace ID and user ID from path
  2249. std::string workspace_id = req.matches[1].str();
  2250. std::string user_id = req.matches[2].str();
  2251. // Requires system:memberships:delete permission OR workspace member management permission
  2252. bool can_remove = authorizationService_->HasPermission(*auth_user, permissions::kMembershipsDelete) ||
  2253. authorizationService_->CanManageWorkspaceMembers(*auth_user, workspace_id);
  2254. if (!can_remove) {
  2255. res.status = 403;
  2256. res.set_content(R"({"error":"Forbidden - requires system:memberships:delete permission or workspace member management"})", "application/json");
  2257. return;
  2258. }
  2259. // Check if MembershipService is available
  2260. if (!membershipService_) {
  2261. res.status = 503;
  2262. res.set_content(R"({"error":"Membership service not available"})", "application/json");
  2263. return;
  2264. }
  2265. try {
  2266. auto result = membershipService_->RemoveMember(workspace_id, user_id);
  2267. if (!result.success) {
  2268. res.status = 400;
  2269. nlohmann::json error_response = {{"error", result.error}};
  2270. res.set_content(error_response.dump(), "application/json");
  2271. return;
  2272. }
  2273. res.set_content(R"({"message":"Member removed successfully"})", "application/json");
  2274. } catch (const std::exception& e) {
  2275. spdlog::error("Remove member error: {}", e.what());
  2276. res.status = 500;
  2277. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2278. }
  2279. }
  2280. // ============================================================================
  2281. // API Key Routes
  2282. // ============================================================================
  2283. void HttpServer::SetupApiKeyRoutes() {
  2284. // POST /api/users/:id/api-keys - Create an API key for a user
  2285. httpServer_->Post(R"(/api/users/([a-zA-Z0-9\-]+)/api-keys)", [this](const httplib::Request& req, httplib::Response& res) {
  2286. HandleCreateApiKey(req, res);
  2287. });
  2288. // GET /api/users/:id/api-keys - List user's API keys
  2289. httpServer_->Get(R"(/api/users/([a-zA-Z0-9\-]+)/api-keys)", [this](const httplib::Request& req, httplib::Response& res) {
  2290. HandleListApiKeys(req, res);
  2291. });
  2292. // DELETE /api/users/:id/api-keys/:keyId - Revoke an API key
  2293. httpServer_->Delete(R"(/api/users/([a-zA-Z0-9\-]+)/api-keys/([a-zA-Z0-9\-]+))", [this](const httplib::Request& req, httplib::Response& res) {
  2294. HandleRevokeApiKey(req, res);
  2295. });
  2296. spdlog::info("API key routes registered: /api/users/:id/api-keys");
  2297. }
  2298. void HttpServer::HandleCreateApiKey(const httplib::Request& req, httplib::Response& res) {
  2299. // Authenticate the request
  2300. auto auth_user = AuthenticateRequest(req);
  2301. if (!auth_user) {
  2302. res.status = 401;
  2303. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2304. return;
  2305. }
  2306. // Extract user ID from path
  2307. std::string target_user_id = req.matches[1].str();
  2308. // Check permissions: own OR system:api_keys:create permission
  2309. bool is_own = (auth_user->user_id == target_user_id);
  2310. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kApiKeysCreate);
  2311. if (!is_own && !has_system_access) {
  2312. res.status = 403;
  2313. res.set_content(R"({"error":"Forbidden - can only create API keys for yourself or requires system:api_keys:create permission"})", "application/json");
  2314. return;
  2315. }
  2316. // Check if ApiKeyService is available
  2317. if (!apiKeyService_) {
  2318. res.status = 503;
  2319. res.set_content(R"({"error":"API key service not available"})", "application/json");
  2320. return;
  2321. }
  2322. try {
  2323. // Parse request body
  2324. auto json = nlohmann::json::parse(req.body);
  2325. CreateApiKeyRequest create_req;
  2326. create_req.user_id = target_user_id;
  2327. if (json.contains("name") && json["name"].is_string()) {
  2328. create_req.name = json["name"].get<std::string>();
  2329. } else {
  2330. res.status = 400;
  2331. res.set_content(R"({"error":"name is required"})", "application/json");
  2332. return;
  2333. }
  2334. if (json.contains("permissions") && json["permissions"].is_array()) {
  2335. for (const auto& item : json["permissions"]) {
  2336. if (item.is_string()) {
  2337. std::string perm = item.get<std::string>();
  2338. // Users can only grant permissions they have (unless they have system access)
  2339. if (!has_system_access) {
  2340. // For now, allow all permissions - proper permission checking
  2341. // would require looking up user's actual permissions
  2342. }
  2343. create_req.permissions.push_back(perm);
  2344. }
  2345. }
  2346. }
  2347. if (json.contains("expires_at") && json["expires_at"].is_string()) {
  2348. create_req.expires_at = json["expires_at"].get<std::string>();
  2349. }
  2350. auto result = apiKeyService_->CreateApiKey(create_req);
  2351. if (!result.success) {
  2352. res.status = 400;
  2353. nlohmann::json error_response = {{"error", result.error}};
  2354. res.set_content(error_response.dump(), "application/json");
  2355. return;
  2356. }
  2357. // Return created key info INCLUDING the raw key (only time it's returned!)
  2358. nlohmann::json key_json = {
  2359. {"id", result.api_key->id},
  2360. {"user_id", result.api_key->user_id},
  2361. {"name", result.api_key->name},
  2362. {"key_prefix", result.api_key->key_prefix},
  2363. {"key", result.raw_key}, // THE RAW KEY - only returned once!
  2364. {"permissions", result.api_key->permissions},
  2365. {"created_at", result.api_key->created_at},
  2366. {"expires_at", result.api_key->expires_at}
  2367. };
  2368. res.status = 201;
  2369. res.set_content(key_json.dump(), "application/json");
  2370. } catch (const nlohmann::json::exception& e) {
  2371. res.status = 400;
  2372. nlohmann::json error_response = {{"error", "Invalid JSON: " + std::string(e.what())}};
  2373. res.set_content(error_response.dump(), "application/json");
  2374. } catch (const std::exception& e) {
  2375. spdlog::error("Create API key error: {}", e.what());
  2376. res.status = 500;
  2377. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2378. }
  2379. }
  2380. void HttpServer::HandleListApiKeys(const httplib::Request& req, httplib::Response& res) {
  2381. // Authenticate the request
  2382. auto auth_user = AuthenticateRequest(req);
  2383. if (!auth_user) {
  2384. res.status = 401;
  2385. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2386. return;
  2387. }
  2388. // Extract user ID from path
  2389. std::string target_user_id = req.matches[1].str();
  2390. // Check permissions: own OR system:api_keys:read permission
  2391. bool is_own = (auth_user->user_id == target_user_id);
  2392. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kApiKeysRead);
  2393. if (!is_own && !has_system_access) {
  2394. res.status = 403;
  2395. res.set_content(R"({"error":"Forbidden - can only list your own API keys or requires system:api_keys:read permission"})", "application/json");
  2396. return;
  2397. }
  2398. // Check if ApiKeyService is available
  2399. if (!apiKeyService_) {
  2400. res.status = 503;
  2401. res.set_content(R"({"error":"API key service not available"})", "application/json");
  2402. return;
  2403. }
  2404. try {
  2405. // Check for include_revoked parameter (requires system access)
  2406. bool include_revoked = false;
  2407. if (has_system_access && req.has_param("include_revoked")) {
  2408. include_revoked = req.get_param_value("include_revoked") == "true";
  2409. }
  2410. auto result = apiKeyService_->ListApiKeys(target_user_id, include_revoked);
  2411. if (!result.success) {
  2412. res.status = 500;
  2413. nlohmann::json error_response = {{"error", result.error}};
  2414. res.set_content(error_response.dump(), "application/json");
  2415. return;
  2416. }
  2417. // Build response (note: raw keys and hashes are NOT included)
  2418. nlohmann::json keys_array = nlohmann::json::array();
  2419. for (const auto& key : result.api_keys) {
  2420. nlohmann::json key_json = {
  2421. {"id", key.id},
  2422. {"user_id", key.user_id},
  2423. {"name", key.name},
  2424. {"key_prefix", key.key_prefix}, // Only prefix, not full key
  2425. {"permissions", key.permissions},
  2426. {"created_at", key.created_at},
  2427. {"updated_at", key.updated_at},
  2428. {"last_used_at", key.last_used_at},
  2429. {"expires_at", key.expires_at}
  2430. };
  2431. if (has_system_access) {
  2432. key_json["deleted_at"] = key.deleted_at;
  2433. }
  2434. keys_array.push_back(key_json);
  2435. }
  2436. nlohmann::json response = {
  2437. {"api_keys", keys_array},
  2438. {"total_count", result.total_count}
  2439. };
  2440. res.set_content(response.dump(), "application/json");
  2441. } catch (const std::exception& e) {
  2442. spdlog::error("List API keys error: {}", e.what());
  2443. res.status = 500;
  2444. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2445. }
  2446. }
  2447. void HttpServer::HandleRevokeApiKey(const httplib::Request& req, httplib::Response& res) {
  2448. // Authenticate the request
  2449. auto auth_user = AuthenticateRequest(req);
  2450. if (!auth_user) {
  2451. res.status = 401;
  2452. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2453. return;
  2454. }
  2455. // Extract user ID and key ID from path
  2456. std::string target_user_id = req.matches[1].str();
  2457. std::string key_id = req.matches[2].str();
  2458. // Check permissions: own OR system:api_keys:delete permission
  2459. bool is_own = (auth_user->user_id == target_user_id);
  2460. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kApiKeysDelete);
  2461. if (!is_own && !has_system_access) {
  2462. res.status = 403;
  2463. res.set_content(R"({"error":"Forbidden - can only revoke your own API keys or requires system:api_keys:delete permission"})", "application/json");
  2464. return;
  2465. }
  2466. // Check if ApiKeyService is available
  2467. if (!apiKeyService_) {
  2468. res.status = 503;
  2469. res.set_content(R"({"error":"API key service not available"})", "application/json");
  2470. return;
  2471. }
  2472. try {
  2473. auto result = apiKeyService_->RevokeApiKey(key_id, target_user_id);
  2474. if (!result.success) {
  2475. res.status = 400;
  2476. nlohmann::json error_response = {{"error", result.error}};
  2477. res.set_content(error_response.dump(), "application/json");
  2478. return;
  2479. }
  2480. res.set_content(R"({"message":"API key revoked successfully"})", "application/json");
  2481. } catch (const std::exception& e) {
  2482. spdlog::error("Revoke API key error: {}", e.what());
  2483. res.status = 500;
  2484. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2485. }
  2486. }
  2487. // ============================================================================
  2488. // Collection Routes
  2489. // ============================================================================
  2490. void HttpServer::SetupCollectionRoutes() {
  2491. // POST /api/workspaces/:wid/collections - Create a collection
  2492. httpServer_->Post(R"(/api/workspaces/([a-zA-Z0-9\-]+)/collections)", [this](const httplib::Request& req, httplib::Response& res) {
  2493. HandleCreateCollection(req, res);
  2494. });
  2495. // GET /api/workspaces/:wid/collections - List collections
  2496. httpServer_->Get(R"(/api/workspaces/([a-zA-Z0-9\-]+)/collections)", [this](const httplib::Request& req, httplib::Response& res) {
  2497. HandleListCollections(req, res);
  2498. });
  2499. // GET /api/workspaces/:wid/collections/:name - Get a collection
  2500. 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) {
  2501. HandleGetCollection(req, res);
  2502. });
  2503. // PUT /api/workspaces/:wid/collections/:name - Update a collection
  2504. 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) {
  2505. HandleUpdateCollection(req, res);
  2506. });
  2507. // DELETE /api/workspaces/:wid/collections/:name - Drop a collection
  2508. 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) {
  2509. HandleDropCollection(req, res);
  2510. });
  2511. spdlog::info("Collection routes registered: /api/workspaces/:wid/collections");
  2512. }
  2513. void HttpServer::HandleCreateCollection(const httplib::Request& req, httplib::Response& res) {
  2514. // Authenticate the request
  2515. auto auth_user = AuthenticateRequest(req);
  2516. if (!auth_user) {
  2517. res.status = 401;
  2518. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2519. return;
  2520. }
  2521. // Extract workspace ID from path
  2522. std::string workspace_id = req.matches[1].str();
  2523. // Verify workspace exists and user has access
  2524. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  2525. if (!ws_result.success) {
  2526. res.status = 404;
  2527. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  2528. return;
  2529. }
  2530. // Requires system:collections:create permission OR workspace membership with manage_collections
  2531. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  2532. auth_user->workspace_ids.end(),
  2533. workspace_id) != auth_user->workspace_ids.end());
  2534. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kCollectionsCreate);
  2535. if (!is_member && !has_system_access) {
  2536. res.status = 403;
  2537. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  2538. return;
  2539. }
  2540. // Check if CollectionService is available
  2541. if (!collectionService_) {
  2542. res.status = 503;
  2543. res.set_content(R"({"error":"Collection service not available"})", "application/json");
  2544. return;
  2545. }
  2546. try {
  2547. // Parse request body
  2548. auto json = nlohmann::json::parse(req.body);
  2549. CreateCollectionRequest create_req;
  2550. create_req.workspace_id = workspace_id;
  2551. if (json.contains("name") && json["name"].is_string()) {
  2552. create_req.name = json["name"].get<std::string>();
  2553. } else {
  2554. res.status = 400;
  2555. res.set_content(R"({"error":"name is required"})", "application/json");
  2556. return;
  2557. }
  2558. // Parse settings
  2559. if (json.contains("schema") && json["schema"].is_string()) {
  2560. create_req.settings.schema = json["schema"].get<std::string>();
  2561. }
  2562. if (json.contains("encrypted_fields") && json["encrypted_fields"].is_array()) {
  2563. for (const auto& item : json["encrypted_fields"]) {
  2564. if (item.is_string()) {
  2565. create_req.settings.encrypted_fields.push_back(item.get<std::string>());
  2566. }
  2567. }
  2568. }
  2569. if (json.contains("ttl_seconds") && json["ttl_seconds"].is_number_integer()) {
  2570. create_req.settings.ttl_seconds = json["ttl_seconds"].get<int64_t>();
  2571. }
  2572. auto result = collectionService_->CreateCollection(create_req);
  2573. if (!result.success) {
  2574. res.status = 400;
  2575. nlohmann::json error_response = {{"error", result.error}};
  2576. res.set_content(error_response.dump(), "application/json");
  2577. return;
  2578. }
  2579. // Return created collection info
  2580. nlohmann::json coll_json = {
  2581. {"name", result.collection->name},
  2582. {"workspace_id", result.collection->workspace_id},
  2583. {"document_count", result.collection->document_count},
  2584. {"size_bytes", result.collection->size_bytes},
  2585. {"created_at", result.collection->created_at},
  2586. {"settings", {
  2587. {"schema", result.collection->settings.schema},
  2588. {"encrypted_fields", result.collection->settings.encrypted_fields},
  2589. {"ttl_seconds", result.collection->settings.ttl_seconds}
  2590. }}
  2591. };
  2592. res.status = 201;
  2593. res.set_content(coll_json.dump(), "application/json");
  2594. } catch (const nlohmann::json::exception& e) {
  2595. spdlog::warn("Create collection JSON parse error: {}", e.what());
  2596. res.status = 400;
  2597. res.set_content(R"({"error":"Invalid JSON in request body"})", "application/json");
  2598. } catch (const std::exception& e) {
  2599. spdlog::error("Create collection error: {}", e.what());
  2600. res.status = 500;
  2601. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2602. }
  2603. }
  2604. void HttpServer::HandleListCollections(const httplib::Request& req, httplib::Response& res) {
  2605. // Authenticate the request
  2606. auto auth_user = AuthenticateRequest(req);
  2607. if (!auth_user) {
  2608. res.status = 401;
  2609. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2610. return;
  2611. }
  2612. // Extract workspace ID from path
  2613. std::string workspace_id = req.matches[1].str();
  2614. // Verify workspace exists and user has access
  2615. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  2616. if (!ws_result.success) {
  2617. res.status = 404;
  2618. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  2619. return;
  2620. }
  2621. // Check access: must be member OR have system:collections:read permission
  2622. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  2623. auth_user->workspace_ids.end(),
  2624. workspace_id) != auth_user->workspace_ids.end());
  2625. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kCollectionsRead);
  2626. if (!is_member && !has_system_access) {
  2627. res.status = 403;
  2628. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  2629. return;
  2630. }
  2631. // Check if CollectionService is available
  2632. if (!collectionService_) {
  2633. res.status = 503;
  2634. res.set_content(R"({"error":"Collection service not available"})", "application/json");
  2635. return;
  2636. }
  2637. try {
  2638. // Check if user with system access wants to include system collections
  2639. bool include_system = has_system_access &&
  2640. req.has_param("include_system") &&
  2641. req.get_param_value("include_system") == "true";
  2642. auto result = collectionService_->ListCollections(workspace_id);
  2643. if (!result.success) {
  2644. res.status = 500;
  2645. nlohmann::json error_response = {{"error", result.error}};
  2646. res.set_content(error_response.dump(), "application/json");
  2647. return;
  2648. }
  2649. nlohmann::json collections_array = nlohmann::json::array();
  2650. for (const auto& coll : result.collections) {
  2651. // Check if collection name starts with underscore (system collection)
  2652. bool is_system = !coll.name.empty() && coll.name[0] == '_';
  2653. nlohmann::json coll_json = {
  2654. {"name", coll.name},
  2655. {"workspace_id", coll.workspace_id},
  2656. {"document_count", coll.document_count},
  2657. {"size_bytes", coll.size_bytes},
  2658. {"created_at", coll.created_at},
  2659. {"updated_at", coll.updated_at},
  2660. {"is_system", is_system},
  2661. {"created_by", coll.created_by},
  2662. {"updated_by", coll.updated_by},
  2663. {"created_by_name", ResolveUserName(coll.created_by)},
  2664. {"updated_by_name", ResolveUserName(coll.updated_by)},
  2665. {"settings", {
  2666. {"schema", coll.settings.schema},
  2667. {"encrypted_fields", coll.settings.encrypted_fields},
  2668. {"ttl_seconds", coll.settings.ttl_seconds}
  2669. }}
  2670. };
  2671. collections_array.push_back(coll_json);
  2672. }
  2673. // If superadmin requested system collections, add global system collections
  2674. if (include_system) {
  2675. auto system_result = collectionService_->ListSystemCollections();
  2676. if (system_result.success) {
  2677. for (const auto& coll : system_result.collections) {
  2678. nlohmann::json coll_json = {
  2679. {"name", coll.name},
  2680. {"workspace_id", ""},
  2681. {"document_count", coll.document_count},
  2682. {"size_bytes", coll.size_bytes},
  2683. {"created_at", coll.created_at},
  2684. {"updated_at", coll.updated_at},
  2685. {"is_system", true},
  2686. {"created_by", coll.created_by},
  2687. {"updated_by", coll.updated_by},
  2688. {"created_by_name", ResolveUserName(coll.created_by)},
  2689. {"updated_by_name", ResolveUserName(coll.updated_by)},
  2690. {"settings", nlohmann::json::object()}
  2691. };
  2692. collections_array.push_back(coll_json);
  2693. }
  2694. }
  2695. }
  2696. nlohmann::json response = {
  2697. {"collections", collections_array},
  2698. {"total_count", static_cast<int64_t>(collections_array.size())}
  2699. };
  2700. res.set_content(response.dump(), "application/json");
  2701. } catch (const std::exception& e) {
  2702. spdlog::error("List collections error: {}", e.what());
  2703. res.status = 500;
  2704. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2705. }
  2706. }
  2707. void HttpServer::HandleGetCollection(const httplib::Request& req, httplib::Response& res) {
  2708. // Authenticate the request
  2709. auto auth_user = AuthenticateRequest(req);
  2710. if (!auth_user) {
  2711. res.status = 401;
  2712. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2713. return;
  2714. }
  2715. // Extract workspace ID and collection name from path
  2716. std::string workspace_id = req.matches[1].str();
  2717. std::string collection_name = req.matches[2].str();
  2718. // Verify workspace exists and user has access
  2719. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  2720. if (!ws_result.success) {
  2721. res.status = 404;
  2722. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  2723. return;
  2724. }
  2725. // Check access: must be member OR have system:collections:read permission
  2726. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  2727. auth_user->workspace_ids.end(),
  2728. workspace_id) != auth_user->workspace_ids.end());
  2729. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kCollectionsRead);
  2730. if (!is_member && !has_system_access) {
  2731. res.status = 403;
  2732. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  2733. return;
  2734. }
  2735. // Check if CollectionService is available
  2736. if (!collectionService_) {
  2737. res.status = 503;
  2738. res.set_content(R"({"error":"Collection service not available"})", "application/json");
  2739. return;
  2740. }
  2741. try {
  2742. auto result = collectionService_->GetCollection(workspace_id, collection_name);
  2743. if (!result.success) {
  2744. res.status = 404;
  2745. nlohmann::json error_response = {{"error", result.error}};
  2746. res.set_content(error_response.dump(), "application/json");
  2747. return;
  2748. }
  2749. nlohmann::json coll_json = {
  2750. {"name", result.collection->name},
  2751. {"workspace_id", result.collection->workspace_id},
  2752. {"document_count", result.collection->document_count},
  2753. {"size_bytes", result.collection->size_bytes},
  2754. {"created_at", result.collection->created_at},
  2755. {"updated_at", result.collection->updated_at},
  2756. {"settings", {
  2757. {"schema", result.collection->settings.schema},
  2758. {"encrypted_fields", result.collection->settings.encrypted_fields},
  2759. {"ttl_seconds", result.collection->settings.ttl_seconds}
  2760. }}
  2761. };
  2762. res.set_content(coll_json.dump(), "application/json");
  2763. } catch (const std::exception& e) {
  2764. spdlog::error("Get collection error: {}", e.what());
  2765. res.status = 500;
  2766. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2767. }
  2768. }
  2769. void HttpServer::HandleUpdateCollection(const httplib::Request& req, httplib::Response& res) {
  2770. // Authenticate the request
  2771. auto auth_user = AuthenticateRequest(req);
  2772. if (!auth_user) {
  2773. res.status = 401;
  2774. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2775. return;
  2776. }
  2777. // Extract workspace ID and collection name from path
  2778. std::string workspace_id = req.matches[1].str();
  2779. std::string collection_name = req.matches[2].str();
  2780. // Verify workspace exists and user has access
  2781. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  2782. if (!ws_result.success) {
  2783. res.status = 404;
  2784. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  2785. return;
  2786. }
  2787. // Requires system:collections:update permission OR workspace membership
  2788. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  2789. auth_user->workspace_ids.end(),
  2790. workspace_id) != auth_user->workspace_ids.end());
  2791. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kCollectionsUpdate);
  2792. if (!is_member && !has_system_access) {
  2793. res.status = 403;
  2794. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  2795. return;
  2796. }
  2797. // Check if CollectionService is available
  2798. if (!collectionService_) {
  2799. res.status = 503;
  2800. res.set_content(R"({"error":"Collection service not available"})", "application/json");
  2801. return;
  2802. }
  2803. try {
  2804. // Parse request body
  2805. auto json = nlohmann::json::parse(req.body);
  2806. // Get existing settings first
  2807. auto get_result = collectionService_->GetCollection(workspace_id, collection_name);
  2808. if (!get_result.success) {
  2809. res.status = 404;
  2810. res.set_content(R"({"error":"Collection not found"})", "application/json");
  2811. return;
  2812. }
  2813. CollectionSettings settings = get_result.collection->settings;
  2814. // Update only provided fields
  2815. if (json.contains("schema") && json["schema"].is_string()) {
  2816. settings.schema = json["schema"].get<std::string>();
  2817. }
  2818. if (json.contains("encrypted_fields") && json["encrypted_fields"].is_array()) {
  2819. settings.encrypted_fields.clear();
  2820. for (const auto& item : json["encrypted_fields"]) {
  2821. if (item.is_string()) {
  2822. settings.encrypted_fields.push_back(item.get<std::string>());
  2823. }
  2824. }
  2825. }
  2826. if (json.contains("ttl_seconds") && json["ttl_seconds"].is_number_integer()) {
  2827. settings.ttl_seconds = json["ttl_seconds"].get<int64_t>();
  2828. }
  2829. auto result = collectionService_->UpdateCollection(workspace_id, collection_name, settings);
  2830. if (!result.success) {
  2831. res.status = 400;
  2832. nlohmann::json error_response = {{"error", result.error}};
  2833. res.set_content(error_response.dump(), "application/json");
  2834. return;
  2835. }
  2836. nlohmann::json coll_json = {
  2837. {"name", result.collection->name},
  2838. {"workspace_id", result.collection->workspace_id},
  2839. {"document_count", result.collection->document_count},
  2840. {"size_bytes", result.collection->size_bytes},
  2841. {"created_at", result.collection->created_at},
  2842. {"updated_at", result.collection->updated_at},
  2843. {"settings", {
  2844. {"schema", result.collection->settings.schema},
  2845. {"encrypted_fields", result.collection->settings.encrypted_fields},
  2846. {"ttl_seconds", result.collection->settings.ttl_seconds}
  2847. }}
  2848. };
  2849. res.set_content(coll_json.dump(), "application/json");
  2850. } catch (const nlohmann::json::exception& e) {
  2851. spdlog::warn("Update collection JSON parse error: {}", e.what());
  2852. res.status = 400;
  2853. res.set_content(R"({"error":"Invalid JSON in request body"})", "application/json");
  2854. } catch (const std::exception& e) {
  2855. spdlog::error("Update collection error: {}", e.what());
  2856. res.status = 500;
  2857. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2858. }
  2859. }
  2860. // ============================================================================
  2861. // Document Routes
  2862. // ============================================================================
  2863. void HttpServer::SetupDocumentRoutes() {
  2864. // POST /api/workspaces/:wid/collections/:name/documents - Create a document
  2865. 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) {
  2866. HandleCreateDocument(req, res);
  2867. });
  2868. // GET /api/workspaces/:wid/collections/:name/documents - List documents
  2869. 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) {
  2870. HandleListDocuments(req, res);
  2871. });
  2872. // GET /api/workspaces/:wid/collections/:name/documents/:id - Get a document
  2873. 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) {
  2874. HandleGetDocument(req, res);
  2875. });
  2876. // PUT /api/workspaces/:wid/collections/:name/documents/:id - Update a document
  2877. 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) {
  2878. HandleUpdateDocument(req, res);
  2879. });
  2880. // DELETE /api/workspaces/:wid/collections/:name/documents/:id - Delete a document
  2881. 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) {
  2882. HandleDeleteDocument(req, res);
  2883. });
  2884. spdlog::info("Document routes registered: /api/workspaces/:wid/collections/:name/documents");
  2885. }
  2886. void HttpServer::HandleCreateDocument(const httplib::Request& req, httplib::Response& res) {
  2887. // Authenticate the request
  2888. auto auth_user = AuthenticateRequest(req);
  2889. if (!auth_user) {
  2890. res.status = 401;
  2891. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2892. return;
  2893. }
  2894. // Extract workspace ID and collection name from path
  2895. std::string workspace_id = req.matches[1].str();
  2896. std::string collection_name = req.matches[2].str();
  2897. // Verify workspace exists and user has access
  2898. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  2899. if (!ws_result.success) {
  2900. res.status = 404;
  2901. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  2902. return;
  2903. }
  2904. // Check document create permission using AuthorizationService
  2905. if (!authorizationService_->CanCreateDocument(*auth_user, workspace_id, collection_name)) {
  2906. res.status = 403;
  2907. res.set_content(R"({"error":"Forbidden - no permission to create documents in this collection"})", "application/json");
  2908. return;
  2909. }
  2910. // Check if DocumentService is available
  2911. if (!documentService_) {
  2912. res.status = 503;
  2913. res.set_content(R"({"error":"Document service not available"})", "application/json");
  2914. return;
  2915. }
  2916. try {
  2917. // Parse request body
  2918. auto json = nlohmann::json::parse(req.body);
  2919. CreateDocumentRequest create_req;
  2920. create_req.workspace_id = workspace_id;
  2921. create_req.collection = collection_name;
  2922. if (json.contains("id") && json["id"].is_string()) {
  2923. create_req.id = json["id"].get<std::string>();
  2924. }
  2925. if (json.contains("data") && json["data"].is_object()) {
  2926. create_req.data = json["data"];
  2927. } else {
  2928. // Treat entire body as data if no "data" field
  2929. create_req.data = json;
  2930. create_req.data.erase("id"); // Remove id from data
  2931. }
  2932. auto result = documentService_->CreateDocument(create_req);
  2933. if (!result.success) {
  2934. res.status = 400;
  2935. nlohmann::json error_response = {{"error", result.error}};
  2936. res.set_content(error_response.dump(), "application/json");
  2937. return;
  2938. }
  2939. // Return created document info
  2940. nlohmann::json doc_json = {
  2941. {"id", result.document->id},
  2942. {"collection", result.document->collection},
  2943. {"workspace_id", result.document->workspace_id},
  2944. {"data", result.document->data},
  2945. {"created_at", result.document->created_at},
  2946. {"updated_at", result.document->updated_at},
  2947. {"version", result.document->version}
  2948. };
  2949. // Broadcast document create event to WebSocket subscribers
  2950. BroadcastDocumentEvent(workspace_id, collection_name, DocumentAction::Create,
  2951. result.document->id, result.document->data);
  2952. res.status = 201;
  2953. res.set_content(doc_json.dump(), "application/json");
  2954. } catch (const nlohmann::json::exception& e) {
  2955. spdlog::warn("Create document JSON parse error: {}", e.what());
  2956. res.status = 400;
  2957. res.set_content(R"({"error":"Invalid JSON in request body"})", "application/json");
  2958. } catch (const std::exception& e) {
  2959. spdlog::error("Create document error: {}", e.what());
  2960. res.status = 500;
  2961. res.set_content(R"({"error":"Internal server error"})", "application/json");
  2962. }
  2963. }
  2964. void HttpServer::HandleListDocuments(const httplib::Request& req, httplib::Response& res) {
  2965. // Authenticate the request
  2966. auto auth_user = AuthenticateRequest(req);
  2967. if (!auth_user) {
  2968. res.status = 401;
  2969. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  2970. return;
  2971. }
  2972. // Extract workspace ID and collection name from path
  2973. std::string workspace_id = req.matches[1].str();
  2974. std::string collection_name = req.matches[2].str();
  2975. // Verify workspace exists and user has access
  2976. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  2977. if (!ws_result.success) {
  2978. res.status = 404;
  2979. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  2980. return;
  2981. }
  2982. // Check collection read permission using AuthorizationService
  2983. if (!authorizationService_->CanReadCollection(*auth_user, workspace_id, collection_name)) {
  2984. res.status = 403;
  2985. res.set_content(R"({"error":"Forbidden - no permission to read documents in this collection"})", "application/json");
  2986. return;
  2987. }
  2988. // Check if DocumentService is available
  2989. if (!documentService_) {
  2990. res.status = 503;
  2991. res.set_content(R"({"error":"Document service not available"})", "application/json");
  2992. return;
  2993. }
  2994. try {
  2995. DocumentQuery query;
  2996. query.workspace_id = workspace_id;
  2997. query.collection = collection_name;
  2998. // Parse query parameters
  2999. if (req.has_param("limit")) {
  3000. query.limit = std::stoi(req.get_param_value("limit"));
  3001. if (query.limit < 1) query.limit = 1;
  3002. if (query.limit > 1000) query.limit = 1000;
  3003. }
  3004. if (req.has_param("offset")) {
  3005. query.offset = std::stoi(req.get_param_value("offset"));
  3006. if (query.offset < 0) query.offset = 0;
  3007. }
  3008. if (req.has_param("sort")) {
  3009. query.sort_field = req.get_param_value("sort");
  3010. }
  3011. if (req.has_param("order")) {
  3012. query.sort_ascending = (req.get_param_value("order") != "desc");
  3013. }
  3014. if (req.has_param("filter")) {
  3015. try {
  3016. query.filter = nlohmann::json::parse(req.get_param_value("filter"));
  3017. } catch (...) {
  3018. // Invalid filter JSON - ignore
  3019. }
  3020. }
  3021. auto result = documentService_->ListDocuments(query);
  3022. if (!result.success) {
  3023. res.status = 500;
  3024. nlohmann::json error_response = {{"error", result.error}};
  3025. res.set_content(error_response.dump(), "application/json");
  3026. return;
  3027. }
  3028. nlohmann::json docs_array = nlohmann::json::array();
  3029. for (const auto& doc : result.documents) {
  3030. nlohmann::json doc_json = {
  3031. {"id", doc.id},
  3032. {"collection", doc.collection},
  3033. {"workspace_id", doc.workspace_id},
  3034. {"data", doc.data},
  3035. {"created_at", doc.created_at},
  3036. {"updated_at", doc.updated_at},
  3037. {"version", doc.version}
  3038. };
  3039. docs_array.push_back(doc_json);
  3040. }
  3041. nlohmann::json response = {
  3042. {"documents", docs_array},
  3043. {"total_count", result.total_count}
  3044. };
  3045. res.set_content(response.dump(), "application/json");
  3046. } catch (const std::exception& e) {
  3047. spdlog::error("List documents error: {}", e.what());
  3048. res.status = 500;
  3049. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3050. }
  3051. }
  3052. void HttpServer::HandleGetDocument(const httplib::Request& req, httplib::Response& res) {
  3053. // Authenticate the request
  3054. auto auth_user = AuthenticateRequest(req);
  3055. if (!auth_user) {
  3056. res.status = 401;
  3057. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3058. return;
  3059. }
  3060. // Extract workspace ID, collection name, and document ID from path
  3061. std::string workspace_id = req.matches[1].str();
  3062. std::string collection_name = req.matches[2].str();
  3063. std::string document_id = req.matches[3].str();
  3064. // Verify workspace exists and user has access
  3065. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3066. if (!ws_result.success) {
  3067. res.status = 404;
  3068. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3069. return;
  3070. }
  3071. // Check if DocumentService is available
  3072. if (!documentService_) {
  3073. res.status = 503;
  3074. res.set_content(R"({"error":"Document service not available"})", "application/json");
  3075. return;
  3076. }
  3077. try {
  3078. auto result = documentService_->GetDocument(workspace_id, collection_name, document_id);
  3079. if (!result.success) {
  3080. res.status = 404;
  3081. nlohmann::json error_response = {{"error", result.error}};
  3082. res.set_content(error_response.dump(), "application/json");
  3083. return;
  3084. }
  3085. // Check document read permission with ownership
  3086. std::string doc_owner = result.document->data.value("_created_by", "");
  3087. if (!authorizationService_->CanReadDocument(*auth_user, workspace_id, collection_name, doc_owner)) {
  3088. res.status = 403;
  3089. res.set_content(R"({"error":"Forbidden - no permission to read this document"})", "application/json");
  3090. return;
  3091. }
  3092. nlohmann::json doc_json = {
  3093. {"id", result.document->id},
  3094. {"collection", result.document->collection},
  3095. {"workspace_id", result.document->workspace_id},
  3096. {"data", result.document->data},
  3097. {"created_at", result.document->created_at},
  3098. {"updated_at", result.document->updated_at},
  3099. {"version", result.document->version}
  3100. };
  3101. res.set_content(doc_json.dump(), "application/json");
  3102. } catch (const std::exception& e) {
  3103. spdlog::error("Get document error: {}", e.what());
  3104. res.status = 500;
  3105. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3106. }
  3107. }
  3108. void HttpServer::HandleUpdateDocument(const httplib::Request& req, httplib::Response& res) {
  3109. // Authenticate the request
  3110. auto auth_user = AuthenticateRequest(req);
  3111. if (!auth_user) {
  3112. res.status = 401;
  3113. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3114. return;
  3115. }
  3116. // Extract workspace ID, collection name, and document ID from path
  3117. std::string workspace_id = req.matches[1].str();
  3118. std::string collection_name = req.matches[2].str();
  3119. std::string document_id = req.matches[3].str();
  3120. // Verify workspace exists and user has access
  3121. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3122. if (!ws_result.success) {
  3123. res.status = 404;
  3124. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3125. return;
  3126. }
  3127. // Check if DocumentService is available
  3128. if (!documentService_) {
  3129. res.status = 503;
  3130. res.set_content(R"({"error":"Document service not available"})", "application/json");
  3131. return;
  3132. }
  3133. try {
  3134. // First get the document to check ownership
  3135. auto existing = documentService_->GetDocument(workspace_id, collection_name, document_id);
  3136. if (!existing.success) {
  3137. res.status = 404;
  3138. nlohmann::json error_response = {{"error", existing.error}};
  3139. res.set_content(error_response.dump(), "application/json");
  3140. return;
  3141. }
  3142. // Check document write permission with ownership
  3143. std::string doc_owner = existing.document->data.value("_created_by", "");
  3144. if (!authorizationService_->CanWriteDocument(*auth_user, workspace_id, collection_name, doc_owner)) {
  3145. res.status = 403;
  3146. res.set_content(R"({"error":"Forbidden - no permission to update this document"})", "application/json");
  3147. return;
  3148. }
  3149. // Parse request body
  3150. auto json = nlohmann::json::parse(req.body);
  3151. UpdateDocumentRequest update_req;
  3152. update_req.workspace_id = workspace_id;
  3153. update_req.collection = collection_name;
  3154. update_req.id = document_id;
  3155. if (json.contains("data") && json["data"].is_object()) {
  3156. update_req.data = json["data"];
  3157. } else {
  3158. // Treat entire body as data if no "data" field
  3159. update_req.data = json;
  3160. }
  3161. if (json.contains("merge") && json["merge"].is_boolean()) {
  3162. update_req.merge = json["merge"].get<bool>();
  3163. }
  3164. if (json.contains("expected_version") && json["expected_version"].is_number_integer()) {
  3165. update_req.expected_version = json["expected_version"].get<int64_t>();
  3166. }
  3167. auto result = documentService_->UpdateDocument(update_req);
  3168. if (!result.success) {
  3169. res.status = 400;
  3170. nlohmann::json error_response = {{"error", result.error}};
  3171. res.set_content(error_response.dump(), "application/json");
  3172. return;
  3173. }
  3174. nlohmann::json doc_json = {
  3175. {"id", result.document->id},
  3176. {"collection", result.document->collection},
  3177. {"workspace_id", result.document->workspace_id},
  3178. {"data", result.document->data},
  3179. {"created_at", result.document->created_at},
  3180. {"updated_at", result.document->updated_at},
  3181. {"version", result.document->version}
  3182. };
  3183. // Broadcast document update event to WebSocket subscribers
  3184. BroadcastDocumentEvent(workspace_id, collection_name, DocumentAction::Update,
  3185. result.document->id, result.document->data);
  3186. res.set_content(doc_json.dump(), "application/json");
  3187. } catch (const nlohmann::json::exception& e) {
  3188. spdlog::warn("Update document JSON parse error: {}", e.what());
  3189. res.status = 400;
  3190. res.set_content(R"({"error":"Invalid JSON in request body"})", "application/json");
  3191. } catch (const std::exception& e) {
  3192. spdlog::error("Update document error: {}", e.what());
  3193. res.status = 500;
  3194. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3195. }
  3196. }
  3197. void HttpServer::HandleDeleteDocument(const httplib::Request& req, httplib::Response& res) {
  3198. // Authenticate the request
  3199. auto auth_user = AuthenticateRequest(req);
  3200. if (!auth_user) {
  3201. res.status = 401;
  3202. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3203. return;
  3204. }
  3205. // Extract workspace ID, collection name, and document ID from path
  3206. std::string workspace_id = req.matches[1].str();
  3207. std::string collection_name = req.matches[2].str();
  3208. std::string document_id = req.matches[3].str();
  3209. // Verify workspace exists and user has access
  3210. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3211. if (!ws_result.success) {
  3212. res.status = 404;
  3213. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3214. return;
  3215. }
  3216. // Check if DocumentService is available
  3217. if (!documentService_) {
  3218. res.status = 503;
  3219. res.set_content(R"({"error":"Document service not available"})", "application/json");
  3220. return;
  3221. }
  3222. try {
  3223. // First get the document to check ownership
  3224. auto existing = documentService_->GetDocument(workspace_id, collection_name, document_id);
  3225. if (!existing.success) {
  3226. res.status = 404;
  3227. nlohmann::json error_response = {{"error", existing.error}};
  3228. res.set_content(error_response.dump(), "application/json");
  3229. return;
  3230. }
  3231. // Check document delete permission with ownership
  3232. std::string doc_owner = existing.document->data.value("_created_by", "");
  3233. if (!authorizationService_->CanDeleteDocument(*auth_user, workspace_id, collection_name, doc_owner)) {
  3234. res.status = 403;
  3235. res.set_content(R"({"error":"Forbidden - no permission to delete this document"})", "application/json");
  3236. return;
  3237. }
  3238. auto result = documentService_->DeleteDocument(workspace_id, collection_name, document_id);
  3239. if (!result.success) {
  3240. res.status = 404;
  3241. nlohmann::json error_response = {{"error", result.error}};
  3242. res.set_content(error_response.dump(), "application/json");
  3243. return;
  3244. }
  3245. // Broadcast document delete event to WebSocket subscribers
  3246. BroadcastDocumentEvent(workspace_id, collection_name, DocumentAction::Delete,
  3247. document_id, nlohmann::json::object());
  3248. res.set_content(R"({"message":"Document deleted successfully"})", "application/json");
  3249. } catch (const std::exception& e) {
  3250. spdlog::error("Delete document error: {}", e.what());
  3251. res.status = 500;
  3252. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3253. }
  3254. }
  3255. void HttpServer::HandleDropCollection(const httplib::Request& req, httplib::Response& res) {
  3256. // Authenticate the request
  3257. auto auth_user = AuthenticateRequest(req);
  3258. if (!auth_user) {
  3259. res.status = 401;
  3260. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3261. return;
  3262. }
  3263. // Extract workspace ID and collection name from path
  3264. std::string workspace_id = req.matches[1].str();
  3265. std::string collection_name = req.matches[2].str();
  3266. // Verify workspace exists and user has access
  3267. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3268. if (!ws_result.success) {
  3269. res.status = 404;
  3270. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3271. return;
  3272. }
  3273. // Requires system:collections:delete permission OR workspace membership
  3274. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  3275. auth_user->workspace_ids.end(),
  3276. workspace_id) != auth_user->workspace_ids.end());
  3277. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kCollectionsDelete);
  3278. if (!is_member && !has_system_access) {
  3279. res.status = 403;
  3280. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  3281. return;
  3282. }
  3283. // Check if CollectionService is available
  3284. if (!collectionService_) {
  3285. res.status = 503;
  3286. res.set_content(R"({"error":"Collection service not available"})", "application/json");
  3287. return;
  3288. }
  3289. try {
  3290. // Check for force parameter
  3291. bool force = false;
  3292. if (req.has_param("force")) {
  3293. force = req.get_param_value("force") == "true";
  3294. }
  3295. auto result = collectionService_->DropCollection(workspace_id, collection_name, force);
  3296. if (!result.success) {
  3297. res.status = 400;
  3298. nlohmann::json error_response = {{"error", result.error}};
  3299. res.set_content(error_response.dump(), "application/json");
  3300. return;
  3301. }
  3302. res.set_content(R"({"message":"Collection dropped successfully"})", "application/json");
  3303. } catch (const std::exception& e) {
  3304. spdlog::error("Drop collection error: {}", e.what());
  3305. res.status = 500;
  3306. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3307. }
  3308. }
  3309. // ============================================================================
  3310. // View Routes
  3311. // ============================================================================
  3312. void HttpServer::SetupViewRoutes() {
  3313. // POST /api/workspaces/:workspace_id/views - Create a new view
  3314. httpServer_->Post(R"(/api/workspaces/([^/]+)/views)",
  3315. [this](const httplib::Request& req, httplib::Response& res) {
  3316. HandleCreateView(req, res);
  3317. });
  3318. // GET /api/workspaces/:workspace_id/views - List all views
  3319. httpServer_->Get(R"(/api/workspaces/([^/]+)/views)",
  3320. [this](const httplib::Request& req, httplib::Response& res) {
  3321. HandleListViews(req, res);
  3322. });
  3323. // GET /api/workspaces/:workspace_id/views/:view_id - Get a specific view
  3324. httpServer_->Get(R"(/api/workspaces/([^/]+)/views/([^/]+))",
  3325. [this](const httplib::Request& req, httplib::Response& res) {
  3326. HandleGetView(req, res);
  3327. });
  3328. // PATCH /api/workspaces/:workspace_id/views/:view_id - Update a view
  3329. httpServer_->Patch(R"(/api/workspaces/([^/]+)/views/([^/]+))",
  3330. [this](const httplib::Request& req, httplib::Response& res) {
  3331. HandleUpdateView(req, res);
  3332. });
  3333. // DELETE /api/workspaces/:workspace_id/views/:view_id - Delete a view
  3334. httpServer_->Delete(R"(/api/workspaces/([^/]+)/views/([^/]+))",
  3335. [this](const httplib::Request& req, httplib::Response& res) {
  3336. HandleDeleteView(req, res);
  3337. });
  3338. spdlog::info("View routes configured");
  3339. }
  3340. void HttpServer::HandleCreateView(const httplib::Request& req, httplib::Response& res) {
  3341. // Authenticate the request
  3342. auto auth_user = AuthenticateRequest(req);
  3343. if (!auth_user) {
  3344. res.status = 401;
  3345. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3346. return;
  3347. }
  3348. // Extract workspace ID from path
  3349. std::string workspace_id = req.matches[1].str();
  3350. // Verify workspace exists
  3351. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3352. if (!ws_result.success) {
  3353. res.status = 404;
  3354. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3355. return;
  3356. }
  3357. // Requires system:views:create permission OR workspace membership
  3358. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  3359. auth_user->workspace_ids.end(),
  3360. workspace_id) != auth_user->workspace_ids.end());
  3361. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kViewsCreate);
  3362. if (!is_member && !has_system_access) {
  3363. res.status = 403;
  3364. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  3365. return;
  3366. }
  3367. // Check if ViewService is available
  3368. if (!viewService_) {
  3369. res.status = 503;
  3370. res.set_content(R"({"error":"View service not available"})", "application/json");
  3371. return;
  3372. }
  3373. // Parse request body
  3374. nlohmann::json body;
  3375. try {
  3376. body = nlohmann::json::parse(req.body);
  3377. } catch (const nlohmann::json::parse_error& /*e*/) {
  3378. res.status = 400;
  3379. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  3380. return;
  3381. }
  3382. // Validate required fields
  3383. if (!body.contains("name") || !body["name"].is_string()) {
  3384. res.status = 400;
  3385. res.set_content(R"({"error":"name is required"})", "application/json");
  3386. return;
  3387. }
  3388. if (!body.contains("collection_name") || !body["collection_name"].is_string()) {
  3389. res.status = 400;
  3390. res.set_content(R"({"error":"collection_name is required"})", "application/json");
  3391. return;
  3392. }
  3393. try {
  3394. CreateViewRequest request;
  3395. request.workspace_id = workspace_id;
  3396. request.name = body["name"].get<std::string>();
  3397. request.collection_name = body["collection_name"].get<std::string>();
  3398. // Parse schema if provided
  3399. if (body.contains("schema") && body["schema"].is_object()) {
  3400. const auto& schema_json = body["schema"];
  3401. if (schema_json.contains("title")) {
  3402. request.schema.title = schema_json.value("title", "");
  3403. }
  3404. if (schema_json.contains("description")) {
  3405. request.schema.description = schema_json.value("description", "");
  3406. }
  3407. if (schema_json.contains("layout")) {
  3408. request.schema.layout = schema_json["layout"];
  3409. }
  3410. if (schema_json.contains("fields") && schema_json["fields"].is_array()) {
  3411. for (const auto& field_json : schema_json["fields"]) {
  3412. SchemaField field;
  3413. field.name = field_json.value("name", "");
  3414. field.type = StringToFieldType(field_json.value("type", "text"));
  3415. field.label = field_json.value("label", "");
  3416. field.description = field_json.value("description", "");
  3417. field.required = field_json.value("required", false);
  3418. field.display_order = field_json.value("display_order", 0);
  3419. field.widget = field_json.value("widget", "");
  3420. field.group = field_json.value("group", "");
  3421. field.default_value = field_json.value("default_value", nlohmann::json());
  3422. field.options = field_json.value("options", nlohmann::json());
  3423. field.reference_collection = field_json.value("reference_collection", "");
  3424. field.computed_expression = field_json.value("computed_expression", "");
  3425. request.schema.fields.push_back(field);
  3426. }
  3427. }
  3428. }
  3429. // Parse settings if provided
  3430. if (body.contains("settings") && body["settings"].is_object()) {
  3431. const auto& settings_json = body["settings"];
  3432. request.settings.is_default = settings_json.value("is_default", false);
  3433. request.settings.show_in_sidebar = settings_json.value("show_in_sidebar", true);
  3434. request.settings.icon = settings_json.value("icon", "");
  3435. request.settings.filters = settings_json.value("filters", nlohmann::json::object());
  3436. request.settings.sort = settings_json.value("sort", nlohmann::json::object());
  3437. }
  3438. auto result = viewService_->CreateView(request);
  3439. if (!result.success) {
  3440. res.status = 400;
  3441. nlohmann::json error_response = {{"error", result.error}};
  3442. res.set_content(error_response.dump(), "application/json");
  3443. return;
  3444. }
  3445. // Build response with view info
  3446. nlohmann::json view_json = {
  3447. {"id", result.view->id},
  3448. {"workspace_id", result.view->workspace_id},
  3449. {"name", result.view->name},
  3450. {"collection_name", result.view->collection_name},
  3451. {"created_at", result.view->created_at},
  3452. {"updated_at", result.view->updated_at}
  3453. };
  3454. // Add schema
  3455. nlohmann::json schema_json = {
  3456. {"title", result.view->schema.title},
  3457. {"description", result.view->schema.description},
  3458. {"layout", result.view->schema.layout}
  3459. };
  3460. nlohmann::json fields_json = nlohmann::json::array();
  3461. for (const auto& field : result.view->schema.fields) {
  3462. nlohmann::json field_json = {
  3463. {"name", field.name},
  3464. {"type", FieldTypeToString(field.type)},
  3465. {"label", field.label},
  3466. {"description", field.description},
  3467. {"required", field.required},
  3468. {"display_order", field.display_order},
  3469. {"widget", field.widget},
  3470. {"group", field.group}
  3471. };
  3472. if (!field.default_value.is_null()) {
  3473. field_json["default_value"] = field.default_value;
  3474. }
  3475. if (!field.options.is_null()) {
  3476. field_json["options"] = field.options;
  3477. }
  3478. if (!field.reference_collection.empty()) {
  3479. field_json["reference_collection"] = field.reference_collection;
  3480. }
  3481. if (!field.computed_expression.empty()) {
  3482. field_json["computed_expression"] = field.computed_expression;
  3483. }
  3484. fields_json.push_back(field_json);
  3485. }
  3486. schema_json["fields"] = fields_json;
  3487. view_json["schema"] = schema_json;
  3488. // Add settings
  3489. view_json["settings"] = {
  3490. {"is_default", result.view->settings.is_default},
  3491. {"show_in_sidebar", result.view->settings.show_in_sidebar},
  3492. {"icon", result.view->settings.icon},
  3493. {"filters", result.view->settings.filters},
  3494. {"sort", result.view->settings.sort}
  3495. };
  3496. res.status = 201;
  3497. res.set_content(view_json.dump(), "application/json");
  3498. } catch (const std::exception& e) {
  3499. spdlog::error("Create view error: {}", e.what());
  3500. res.status = 500;
  3501. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3502. }
  3503. }
  3504. void HttpServer::HandleListViews(const httplib::Request& req, httplib::Response& res) {
  3505. // Authenticate the request
  3506. auto auth_user = AuthenticateRequest(req);
  3507. if (!auth_user) {
  3508. res.status = 401;
  3509. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3510. return;
  3511. }
  3512. // Extract workspace ID from path
  3513. std::string workspace_id = req.matches[1].str();
  3514. // Verify workspace exists
  3515. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3516. if (!ws_result.success) {
  3517. res.status = 404;
  3518. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3519. return;
  3520. }
  3521. // Check access: must be member OR have system:views:read permission
  3522. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  3523. auth_user->workspace_ids.end(),
  3524. workspace_id) != auth_user->workspace_ids.end());
  3525. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kViewsRead);
  3526. if (!is_member && !has_system_access) {
  3527. res.status = 403;
  3528. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  3529. return;
  3530. }
  3531. // Check if ViewService is available
  3532. if (!viewService_) {
  3533. res.status = 503;
  3534. res.set_content(R"({"error":"View service not available"})", "application/json");
  3535. return;
  3536. }
  3537. try {
  3538. ViewListResult result;
  3539. // Check if filtering by collection
  3540. if (req.has_param("collection")) {
  3541. std::string collection_name = req.get_param_value("collection");
  3542. result = viewService_->ListViewsForCollection(workspace_id, collection_name);
  3543. } else {
  3544. result = viewService_->ListViews(workspace_id);
  3545. }
  3546. if (!result.success) {
  3547. res.status = 500;
  3548. nlohmann::json error_response = {{"error", result.error}};
  3549. res.set_content(error_response.dump(), "application/json");
  3550. return;
  3551. }
  3552. nlohmann::json views_json = nlohmann::json::array();
  3553. for (const auto& view : result.views) {
  3554. nlohmann::json view_json = {
  3555. {"id", view.id},
  3556. {"workspace_id", view.workspace_id},
  3557. {"name", view.name},
  3558. {"collection_name", view.collection_name},
  3559. {"created_at", view.created_at},
  3560. {"updated_at", view.updated_at}
  3561. };
  3562. // Add schema summary (fields count and title)
  3563. view_json["schema"] = {
  3564. {"title", view.schema.title},
  3565. {"field_count", view.schema.fields.size()}
  3566. };
  3567. // Add settings
  3568. view_json["settings"] = {
  3569. {"is_default", view.settings.is_default},
  3570. {"show_in_sidebar", view.settings.show_in_sidebar},
  3571. {"icon", view.settings.icon}
  3572. };
  3573. views_json.push_back(view_json);
  3574. }
  3575. nlohmann::json response = {{"views", views_json}};
  3576. res.set_content(response.dump(), "application/json");
  3577. } catch (const std::exception& e) {
  3578. spdlog::error("List views error: {}", e.what());
  3579. res.status = 500;
  3580. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3581. }
  3582. }
  3583. void HttpServer::HandleGetView(const httplib::Request& req, httplib::Response& res) {
  3584. // Authenticate the request
  3585. auto auth_user = AuthenticateRequest(req);
  3586. if (!auth_user) {
  3587. res.status = 401;
  3588. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3589. return;
  3590. }
  3591. // Extract workspace ID and view ID from path
  3592. std::string workspace_id = req.matches[1].str();
  3593. std::string view_id = req.matches[2].str();
  3594. // Verify workspace exists
  3595. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3596. if (!ws_result.success) {
  3597. res.status = 404;
  3598. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3599. return;
  3600. }
  3601. // Check access: must be member OR have system:views:read permission
  3602. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  3603. auth_user->workspace_ids.end(),
  3604. workspace_id) != auth_user->workspace_ids.end());
  3605. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kViewsRead);
  3606. if (!is_member && !has_system_access) {
  3607. res.status = 403;
  3608. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  3609. return;
  3610. }
  3611. // Check if ViewService is available
  3612. if (!viewService_) {
  3613. res.status = 503;
  3614. res.set_content(R"({"error":"View service not available"})", "application/json");
  3615. return;
  3616. }
  3617. try {
  3618. auto result = viewService_->GetView(workspace_id, view_id);
  3619. if (!result.success || !result.view) {
  3620. res.status = 404;
  3621. nlohmann::json error_response = {{"error", result.error}};
  3622. res.set_content(error_response.dump(), "application/json");
  3623. return;
  3624. }
  3625. // Build full response with view info
  3626. nlohmann::json view_json = {
  3627. {"id", result.view->id},
  3628. {"workspace_id", result.view->workspace_id},
  3629. {"name", result.view->name},
  3630. {"collection_name", result.view->collection_name},
  3631. {"created_at", result.view->created_at},
  3632. {"updated_at", result.view->updated_at}
  3633. };
  3634. // Add schema
  3635. nlohmann::json schema_json = {
  3636. {"title", result.view->schema.title},
  3637. {"description", result.view->schema.description},
  3638. {"layout", result.view->schema.layout}
  3639. };
  3640. nlohmann::json fields_json = nlohmann::json::array();
  3641. for (const auto& field : result.view->schema.fields) {
  3642. nlohmann::json field_json = {
  3643. {"name", field.name},
  3644. {"type", FieldTypeToString(field.type)},
  3645. {"label", field.label},
  3646. {"description", field.description},
  3647. {"required", field.required},
  3648. {"display_order", field.display_order},
  3649. {"widget", field.widget},
  3650. {"group", field.group}
  3651. };
  3652. if (!field.default_value.is_null()) {
  3653. field_json["default_value"] = field.default_value;
  3654. }
  3655. if (!field.options.is_null()) {
  3656. field_json["options"] = field.options;
  3657. }
  3658. if (!field.reference_collection.empty()) {
  3659. field_json["reference_collection"] = field.reference_collection;
  3660. }
  3661. if (!field.computed_expression.empty()) {
  3662. field_json["computed_expression"] = field.computed_expression;
  3663. }
  3664. fields_json.push_back(field_json);
  3665. }
  3666. schema_json["fields"] = fields_json;
  3667. view_json["schema"] = schema_json;
  3668. // Add settings
  3669. view_json["settings"] = {
  3670. {"is_default", result.view->settings.is_default},
  3671. {"show_in_sidebar", result.view->settings.show_in_sidebar},
  3672. {"icon", result.view->settings.icon},
  3673. {"filters", result.view->settings.filters},
  3674. {"sort", result.view->settings.sort}
  3675. };
  3676. res.set_content(view_json.dump(), "application/json");
  3677. } catch (const std::exception& e) {
  3678. spdlog::error("Get view error: {}", e.what());
  3679. res.status = 500;
  3680. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3681. }
  3682. }
  3683. void HttpServer::HandleUpdateView(const httplib::Request& req, httplib::Response& res) {
  3684. // Authenticate the request
  3685. auto auth_user = AuthenticateRequest(req);
  3686. if (!auth_user) {
  3687. res.status = 401;
  3688. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3689. return;
  3690. }
  3691. // Extract workspace ID and view ID from path
  3692. std::string workspace_id = req.matches[1].str();
  3693. std::string view_id = req.matches[2].str();
  3694. // Verify workspace exists
  3695. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3696. if (!ws_result.success) {
  3697. res.status = 404;
  3698. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3699. return;
  3700. }
  3701. // Requires system:views:update permission OR workspace membership
  3702. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  3703. auth_user->workspace_ids.end(),
  3704. workspace_id) != auth_user->workspace_ids.end());
  3705. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kViewsUpdate);
  3706. if (!is_member && !has_system_access) {
  3707. res.status = 403;
  3708. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  3709. return;
  3710. }
  3711. // Check if ViewService is available
  3712. if (!viewService_) {
  3713. res.status = 503;
  3714. res.set_content(R"({"error":"View service not available"})", "application/json");
  3715. return;
  3716. }
  3717. // Parse request body
  3718. nlohmann::json body;
  3719. try {
  3720. body = nlohmann::json::parse(req.body);
  3721. } catch (const nlohmann::json::parse_error& /*e*/) {
  3722. res.status = 400;
  3723. res.set_content(R"({"error":"Invalid JSON body"})", "application/json");
  3724. return;
  3725. }
  3726. try {
  3727. UpdateViewRequest request;
  3728. request.workspace_id = workspace_id;
  3729. request.id = view_id;
  3730. if (body.contains("name") && body["name"].is_string()) {
  3731. request.name = body["name"].get<std::string>();
  3732. }
  3733. if (body.contains("collection_name") && body["collection_name"].is_string()) {
  3734. request.collection_name = body["collection_name"].get<std::string>();
  3735. }
  3736. // Parse schema if provided
  3737. if (body.contains("schema") && body["schema"].is_object()) {
  3738. ViewSchema schema;
  3739. const auto& schema_json = body["schema"];
  3740. schema.title = schema_json.value("title", "");
  3741. schema.description = schema_json.value("description", "");
  3742. schema.layout = schema_json.value("layout", nlohmann::json::object());
  3743. if (schema_json.contains("fields") && schema_json["fields"].is_array()) {
  3744. for (const auto& field_json : schema_json["fields"]) {
  3745. SchemaField field;
  3746. field.name = field_json.value("name", "");
  3747. field.type = StringToFieldType(field_json.value("type", "text"));
  3748. field.label = field_json.value("label", "");
  3749. field.description = field_json.value("description", "");
  3750. field.required = field_json.value("required", false);
  3751. field.display_order = field_json.value("display_order", 0);
  3752. field.widget = field_json.value("widget", "");
  3753. field.group = field_json.value("group", "");
  3754. field.default_value = field_json.value("default_value", nlohmann::json());
  3755. field.options = field_json.value("options", nlohmann::json());
  3756. field.reference_collection = field_json.value("reference_collection", "");
  3757. field.computed_expression = field_json.value("computed_expression", "");
  3758. schema.fields.push_back(field);
  3759. }
  3760. }
  3761. request.schema = schema;
  3762. }
  3763. // Parse settings if provided
  3764. if (body.contains("settings") && body["settings"].is_object()) {
  3765. ViewSettings settings;
  3766. const auto& settings_json = body["settings"];
  3767. settings.is_default = settings_json.value("is_default", false);
  3768. settings.show_in_sidebar = settings_json.value("show_in_sidebar", true);
  3769. settings.icon = settings_json.value("icon", "");
  3770. settings.filters = settings_json.value("filters", nlohmann::json::object());
  3771. settings.sort = settings_json.value("sort", nlohmann::json::object());
  3772. request.settings = settings;
  3773. }
  3774. auto result = viewService_->UpdateView(request);
  3775. if (!result.success || !result.view) {
  3776. res.status = 400;
  3777. nlohmann::json error_response = {{"error", result.error}};
  3778. res.set_content(error_response.dump(), "application/json");
  3779. return;
  3780. }
  3781. // Build response with updated view info
  3782. nlohmann::json view_json = {
  3783. {"id", result.view->id},
  3784. {"workspace_id", result.view->workspace_id},
  3785. {"name", result.view->name},
  3786. {"collection_name", result.view->collection_name},
  3787. {"created_at", result.view->created_at},
  3788. {"updated_at", result.view->updated_at}
  3789. };
  3790. // Add schema
  3791. nlohmann::json schema_json = {
  3792. {"title", result.view->schema.title},
  3793. {"description", result.view->schema.description},
  3794. {"layout", result.view->schema.layout}
  3795. };
  3796. nlohmann::json fields_json = nlohmann::json::array();
  3797. for (const auto& field : result.view->schema.fields) {
  3798. nlohmann::json field_json = {
  3799. {"name", field.name},
  3800. {"type", FieldTypeToString(field.type)},
  3801. {"label", field.label},
  3802. {"description", field.description},
  3803. {"required", field.required},
  3804. {"display_order", field.display_order},
  3805. {"widget", field.widget},
  3806. {"group", field.group}
  3807. };
  3808. if (!field.default_value.is_null()) {
  3809. field_json["default_value"] = field.default_value;
  3810. }
  3811. if (!field.options.is_null()) {
  3812. field_json["options"] = field.options;
  3813. }
  3814. if (!field.reference_collection.empty()) {
  3815. field_json["reference_collection"] = field.reference_collection;
  3816. }
  3817. if (!field.computed_expression.empty()) {
  3818. field_json["computed_expression"] = field.computed_expression;
  3819. }
  3820. fields_json.push_back(field_json);
  3821. }
  3822. schema_json["fields"] = fields_json;
  3823. view_json["schema"] = schema_json;
  3824. // Add settings
  3825. view_json["settings"] = {
  3826. {"is_default", result.view->settings.is_default},
  3827. {"show_in_sidebar", result.view->settings.show_in_sidebar},
  3828. {"icon", result.view->settings.icon},
  3829. {"filters", result.view->settings.filters},
  3830. {"sort", result.view->settings.sort}
  3831. };
  3832. res.set_content(view_json.dump(), "application/json");
  3833. } catch (const std::exception& e) {
  3834. spdlog::error("Update view error: {}", e.what());
  3835. res.status = 500;
  3836. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3837. }
  3838. }
  3839. void HttpServer::HandleDeleteView(const httplib::Request& req, httplib::Response& res) {
  3840. // Authenticate the request
  3841. auto auth_user = AuthenticateRequest(req);
  3842. if (!auth_user) {
  3843. res.status = 401;
  3844. res.set_content(R"({"error":"Unauthorized"})", "application/json");
  3845. return;
  3846. }
  3847. // Extract workspace ID and view ID from path
  3848. std::string workspace_id = req.matches[1].str();
  3849. std::string view_id = req.matches[2].str();
  3850. // Verify workspace exists
  3851. auto ws_result = workspaceService_->GetWorkspace(workspace_id);
  3852. if (!ws_result.success) {
  3853. res.status = 404;
  3854. res.set_content(R"({"error":"Workspace not found"})", "application/json");
  3855. return;
  3856. }
  3857. // Requires system:views:delete permission OR workspace membership
  3858. bool is_member = (std::find(auth_user->workspace_ids.begin(),
  3859. auth_user->workspace_ids.end(),
  3860. workspace_id) != auth_user->workspace_ids.end());
  3861. bool has_system_access = authorizationService_->HasPermission(*auth_user, permissions::kViewsDelete);
  3862. if (!is_member && !has_system_access) {
  3863. res.status = 403;
  3864. res.set_content(R"({"error":"Forbidden - no access to this workspace"})", "application/json");
  3865. return;
  3866. }
  3867. // Check if ViewService is available
  3868. if (!viewService_) {
  3869. res.status = 503;
  3870. res.set_content(R"({"error":"View service not available"})", "application/json");
  3871. return;
  3872. }
  3873. try {
  3874. auto result = viewService_->DeleteView(workspace_id, view_id);
  3875. if (!result.success) {
  3876. res.status = 404;
  3877. nlohmann::json error_response = {{"error", result.error}};
  3878. res.set_content(error_response.dump(), "application/json");
  3879. return;
  3880. }
  3881. res.set_content(R"({"message":"View deleted successfully"})", "application/json");
  3882. } catch (const std::exception& e) {
  3883. spdlog::error("Delete view error: {}", e.what());
  3884. res.status = 500;
  3885. res.set_content(R"({"error":"Internal server error"})", "application/json");
  3886. }
  3887. }
  3888. } // namespace smartbotic::webserver