dsql-admin/dsql-app/.local_dist/server/pages/api/updateUserTable.js
Benjamin Toby 3ffd2d6777 Updates
2024-12-05 08:03:33 +01:00

28 lines
11 KiB
JavaScript

"use strict";(()=>{var e={};e.id=4371,e.ids=[4371],e.modules={75600:e=>{e.exports=require("next/dist/compiled/next-server/pages-api.runtime.prod.js")},72583:e=>{e.exports=require("sanitize-html")},9973:e=>{e.exports=require("serverless-mysql")},79428:e=>{e.exports=require("buffer")},79646:e=>{e.exports=require("child_process")},55511:e=>{e.exports=require("crypto")},29021:e=>{e.exports=require("fs")},81630:e=>{e.exports=require("http")},33873:e=>{e.exports=require("path")},96762:(e,t)=>{Object.defineProperty(t,"M",{enumerable:!0,get:function(){return function e(t,r){return r in t?t[r]:"then"in t&&"function"==typeof t.then?t.then(t=>e(t,r)):"function"==typeof t&&"default"===r?t:void 0}}})},56363:(e,t,r)=>{r.r(t),r.d(t,{config:()=>N,default:()=>A,routeModule:()=>R});var s={};r.r(s),r.d(s,{default:()=>y});var a=r(89947),n=r(2706),l=r(96762),o=r(51348),i=r.n(o),u=r(73677),c=r.n(u),d=r(39831),p=r.n(d),_=r(77538),S=r.n(_),f=r(6420),m=r.n(f),g=r(33364),h=r.n(g);let b=r(29021),E=r(33873),{execSync:D}=r(79646);async function y(e,t){if("POST"!==e.method)return t.json({msg:"Failed!"});let r=await m()(e,t,!0);if(!r)return t.json({success:!1,msg:"Unauthorized"});let{dbFullName:s,dbSlug:a,dbId:n,tableNameOld:l,payload:o,delegated:u}=e.body,{tableName:d,tableFullName:_,tableDescription:f}=o;if(!d?.match(/./)||d.match(/[^a-zA-Z0-9-_]/))return t.json({success:!1,msg:"Bad Input"});try{let o=await p()({databaseSlug:a,request:e,user:r,query:e.query});if(!await c()({user:r,confirmedDelegetedUser:o,database:a,table:l,dbId:n,priviledgeRegex:/Edit Table/i}))return console.log("User Unauthorized"),t.json({success:!1,msg:"Unauthorized"});let m=o?.rootUserId?o.rootUserId:r.id,g=`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${m}/main.json`,y=JSON.parse(b.readFileSync(g,"utf8")),A=y.filter(e=>e.dbFullName===s)[0].tables.filter((e,t)=>{if(e.tableName===l)return!0});if(A&&A[0])A[0].tableName=d,A[0].tableNameOld=l,A[0].tableFullName=_,f&&(A[0].tableDescription=f),A[0].childrenTables&&A[0].childrenTables.forEach(e=>{try{y.filter(t=>t.dbFullName===e.dbNameFull)[0].tables.filter(t=>{if(t.tableName===e.tableName)return!0})[0].childTableName=d}catch(e){S()({component:"/api/updateUserTable/lines-131-138",message:e.message,user:r})}});else throw Error("Table Does not exist");b.writeFileSync(`${g}`,JSON.stringify(y),"utf8"),await h()({dbFullName:"datasquirel",tableName:"user_database_tables",identifierColumnName:"table_slug",identifierValue:l,data:{table_name:_,table_slug:d,table_description:f}}),u&&o&&await i()("UPDATE delegated_user_tables SET `table`=? WHERE delegated_user_id=? AND root_user_id=? AND `table`=? AND `database`=?",[d,r.id,o.rootUserId,l,a]);let N=E.join(process.cwd(),"/shell"),R=s.replace(/[^a-z\_0-9]/g,""),L=D(`node createDbFromSchema.js --user ${m} --database ${R}`,{cwd:N});console.log(L.toString()),t.json({success:!0})}catch(e){S()({component:"/api/updateUserTable/main-catch-error",message:e.message,user:r}),t.json({success:!1,msg:"Database Files could not be written!"})}}let A=(0,l.M)(s,"default"),N=(0,l.M)(s,"config"),R=new a.PagesAPIRouteModule({definition:{kind:n.A.PAGES_API,page:"/api/updateUserTable",pathname:"/api/updateUserTable",bundlePath:"",filename:""},userland:s})},73677:(e,t,r)=>{let s=r(51348),a=r(77538);e.exports=async function({user:e,confirmedDelegetedUser:t,database:r,table:n,priviledgeRegex:l,dbId:o}){let i,u;try{t?.delegated?(i=await s("SELECT priviledge FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=? AND `database`=? AND `table`=?",[t.rootUserId,e.id,r,n]),u=i[0]?.priviledge?.match(l)):(i=await s("SELECT table_slug FROM user_database_tables WHERE user_id=? AND table_slug=? AND db_id=?",[e.id,n,o]),u=!0)}catch(t){a({component:"checkUserRights",message:t.message,user:e})}return!!i&&!!i[0]&&!!u}},39831:(e,t,r)=>{r(81630);let s=r(72907);e.exports=async function({request:e,databaseSlug:t,user:r,query:a}){try{let n=r.id,l=null;if(!a?.delegated)return{dbUserId:n};let o=a.dbUserId,i=`${process.env.DSQL_USER_DB_PREFIX}${o}_${t}`,u=`${process.env.DSQL_USER_DELEGATED_DB_COOKIE_PREFIX}${i}`;try{if(!e.cookies?.[u])throw Error("Cookie not present");let r=s(e.cookies[u]);if(!r)throw Error("Invalid Token");if((l=JSON.parse(r)).databaseSlug===t)return{dbUserId:n=l.rootUserId,rootUserId:l.rootUserId,rootUserName:l.rootUserName,rootUserEmail:l.rootUserEmail,rootUserImage:l.rootUserImage,databaseFullName:l.databaseFullName,databaseSlug:l.databaseSlug,allowedTables:l.allowedTables,priviledges:l.priviledges,database:l.databaseSlug,delegated:!0}}catch(e){}return{dbUserId:n}}catch(e){return null}}},77538:(e,t,r)=>{let s=r(29021),{IncomingMessage:a}=r(81630);e.exports=async function({user:e,message:t,component:r,noMail:a,req:n}){let l=new Date,o=(()=>{if(!n)return null;try{let e=n.headers["x-forwarded-for"],t=n.headers["x-real-ip"],r=n.headers["cf-connecting-ip"],s=Array.isArray(e)?e[0]:e?.split(",")[0],a=r||s||t||n.socket.remoteAddress;if(!a)return null;return String(a)}catch(e){return null}})();try{let a=`🚀 SERVER ERROR ===========================
Error Message: ${t}
Component: ${r}`;e?.id&&e?.first_name&&e?.last_name&&e?.email&&(a+=`
User Id: ${e?.id}
User Name: ${e?.first_name} ${e?.last_name}
User Email: ${e?.email}`),n?.url&&(a+=`
URL: ${n.url}`),n?.body&&(a+=`
Request Body: ${JSON.stringify(n.body,null,4)}`),o&&(a+=`
IP: ${o}`),a+=`
Date: ${l.toDateString()}
========================================`,s.existsSync("./.tmp/error.log")||s.writeFileSync("./.tmp/error.log","","utf-8");let i=s.readFileSync("./.tmp/error.log","utf-8");s.writeFileSync("./.tmp/error.log",a),s.appendFileSync("./.tmp/error.log",`
${i}`)}catch(e){console.log("Server Error Reporting Error:",e.message)}}},6420:(e,t,r)=>{r(81630);let s=r(51348),a=r(72907),n=r(29021);async function l(e,t,r,l){if(!e.cookies?.datasquirelAuthKey?.match(/./))return null;let o=a(e.cookies.datasquirelAuthKey);if(!o)return null;let i=JSON.parse(o);if(!i.csrf_k||r&&!e.headers["x-csrf-auth"]?.match(RegExp(`${i.csrf_k}`)))return null;let u=process.env.DSQL_USER_LOGIN_KEYS_PATH;if(!u)return console.log("DSQL_USER_LOGIN_KEYS_PATH env variable not found. Please set this variable."),null;if(r&&!n.existsSync(`${u}/${i.csrf_k}`))return null;if(0==i.verification_status&&!r){let e=await s(`SELECT verification_status FROM users WHERE id='${i.id}'`);e&&e[0]&&1==e[0].verification_status&&t.setHeader("Set-Cookie",["user_refresh=1"])}return i?.date&&Date.now()-i.date>6048e5?null:i}e.exports=l},33364:(e,t,r)=>{let s=r(82703),a=r(72583),n=r(16570),l=r(51348),o=r(21339);async function i({dbContext:e,paradigm:t,dbFullName:r,tableName:i,data:u,tableSchema:c,identifierColumnName:d,identifierValue:p,encryptionKey:_,encryptionSalt:S}){if(!u||!Object.keys(u).length)return null;let f=!e?.match(/dsql.user/i)&&(!r||!!r.match(/^datasquirel$/)),m=f?l:o,g=Object.keys(u),h=[],b=[];for(let e=0;e<g.length;e++)try{let t=g[e],r=u[t],l=c?c?.fields?.filter(e=>e.fieldName===t):null,o=l&&l[0]?l[0]:null;if(null==r||void 0==r)continue;o?.richText&&(r=a(r,n)),o?.encrypted&&(r=s(r,_,S)),"object"==typeof r&&(r=JSON.stringify(r)),o?.pattern&&!new RegExp(o.pattern,o.patternFlags||"").test(r)&&(console.log("DSQL: Pattern not matched =>",r),r=""),"string"==typeof r&&r.match(/^null$/i)&&(r={toSqlString:function(){return"NULL"}}),"string"!=typeof r||r.match(/./i)||(r={toSqlString:function(){return"NULL"}}),h.push(`\`${t}\`=?`),"number"==typeof r?b.push(String(r)):b.push(r)}catch(e){console.log("DSQL: Error in parsing data keys in update function =>",e.message);continue}h.push(`date_updated='${Date()}'`),h.push(`date_updated_code='${Date.now()}'`);let E=`UPDATE ${i} SET ${h.join(",")} WHERE \`${d}\`=?`;return b.push(p),f?await m(E,b):await m({paradigm:t,database:r,queryString:E,queryValues:b})}e.exports=i},72907:(e,t,r)=>{let{scryptSync:s,createDecipheriv:a}=r(55511),{Buffer:n}=r(79428);e.exports=e=>{let t=a("aes-192-cbc",s(process.env.DSQL_ENCRYPTION_PASSWORD||"",process.env.DSQL_ENCRYPTION_SALT||"",24),n.alloc(16,0));try{let r=t.update(e,"hex","utf8");return r+=t.final("utf8")}catch(e){return null}}},82703:(e,t,r)=>{let{scryptSync:s,createCipheriv:a}=r(55511),{Buffer:n}=r(79428),l=r(48225);e.exports=(e,t,r)=>{let o=a("aes-192-cbc",s(t||process.env.DSQL_ENCRYPTION_PASSWORD||"",r||process.env.DSQL_ENCRYPTION_SALT||"",24),n.alloc(16,0));try{let t=o.update(e,"utf8","hex");return t+=o.final("hex")}catch(e){return l({component:"encrypt",message:e.message}),null}}},16570:e=>{e.exports={allowedTags:["b","i","em","strong","a","p","span","ul","ol","li","h1","h2","h3","h4","h5","h6","img","div","button","pre","code","br"],allowedAttributes:{a:["href"],img:["src","alt","width","height","class","style"],"*":["style","class"]}}},48225:(e,t,r)=>{let s=r(29021);e.exports=async function({user:e,message:t,component:r,noMail:a}){let n=`🚀 SERVER ERROR ===========================
User Id: ${e?.id}
User Name: ${e?.first_name} ${e?.last_name}
User Email: ${e?.email}
Error Message: ${t}
Component: ${r}
Date: ${Date()}
========================================`;s.existsSync("./.tmp/error.log")||s.writeFileSync("./.tmp/error.log","","utf-8");let l=s.readFileSync("./.tmp/error.log","utf-8");s.writeFileSync("./.tmp/error.log",n),s.appendFileSync("./.tmp/error.log",`
${l}`)}},51348:(e,t,r)=>{let s=r(9973),a=r(21580),n=s({config:{host:process.env.DSQL_DB_HOST,user:process.env.DSQL_DB_USERNAME,password:process.env.DSQL_DB_PASSWORD,database:process.env.DSQL_DB_NAME,port:process.env.DSQL_DB_PORT?Number(process.env.DSQL_DB_PORT):void 0,charset:"utf8mb4",ssl:a()}});async function l(...e){try{let t=await n.query(...e);return await n.end(),JSON.parse(JSON.stringify(t))}catch(e){return console.log("DB Error =>",e),{success:!1,error:e.message}}}e.exports=l},21339:(e,t,r)=>{let s=r(29021);r(33873);let a=r(9973),n=r(21580),l=a({config:{host:process.env.DSQL_DB_HOST,user:process.env.DSQL_DB_READ_ONLY_USERNAME,password:process.env.DSQL_DB_READ_ONLY_PASSWORD,charset:"utf8mb4",ssl:n()}});e.exports=function({paradigm:e,database:t,queryString:r,queryValues:o}){try{return new Promise((i,u)=>{let c=!!e?.match(/full.access|^fa$/i);try{function d(e){l.end(),i(JSON.parse(JSON.stringify(e)))}function p(e){l.end(),i({error:e.message,queryStringGenerated:r,queryValuesGenerated:o,sql:e.sql})}l=c?a({config:{host:process.env.DSQL_DB_HOST,user:process.env.DSQL_DB_FULL_ACCESS_USERNAME,password:process.env.DSQL_DB_FULL_ACCESS_PASSWORD,database:t,ssl:n()}}):a({config:{host:process.env.DSQL_DB_HOST,user:process.env.DSQL_DB_READ_ONLY_USERNAME,password:process.env.DSQL_DB_READ_ONLY_PASSWORD,database:t,ssl:n()}}),o&&Array.isArray(o)&&o[0]?l.query(r,o).then(d).catch(p):l.query(r).then(d).catch(p)}catch(e){s.appendFileSync("./.tmp/dbErrorLogs.txt",e.message+"\n"+Date()+"\n\n\n","utf8"),i({error:e.message})}})}catch(e){return{success:!1,error:e.message}}}},21580:(e,t,r)=>{let s=r(29021);e.exports=function(){let e=process.env.DSQL_SSL_DIR;if(!e?.match(/./))return;let t=`${e}/ca-cert.pem`;if(!s.existsSync(t)){console.log(`${t} does not exist`);return}return{ca:s.readFileSync(`${e}/ca-cert.pem`)}}},2706:(e,t)=>{var r;Object.defineProperty(t,"A",{enumerable:!0,get:function(){return r}}),function(e){e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE",e.IMAGE="IMAGE"}(r||(r={}))},89947:(e,t,r)=>{e.exports=r(75600)}};var t=require("../../webpack-api-runtime.js");t.C(e);var r=t(t.s=56363);module.exports=r})();