dsql-admin/dsql-app/.local_dist/server/pages/api/updateUserDatabase.js
Benjamin Toby 8b7ea057d0 Updates
2024-12-06 14:24:26 +01:00

16 lines
12 KiB
JavaScript

"use strict";(()=>{var e={};e.id=7214,e.ids=[7214],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")},21820:e=>{e.exports=require("os")},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}}})},29750:(e,t,r)=>{r.r(t),r.d(t,{config:()=>h,default:()=>E,routeModule:()=>y});var s={};r.r(s),r.d(s,{default:()=>g});var n=r(89947),a=r(2706),o=r(96762),i=r(33364),l=r.n(i),c=r(48225),u=r.n(c),p=r(6420),d=r.n(p),S=r(57638),_=r.n(S);let m=r(29021),f=r(21820);r(33873);let{execSync:D}=r(79646);async function g(e,t){if("POST"!==e.method)return t.json({msg:"Failed!"});let r=await d()(e,t,!0);if(!r)return t.json({success:!1,msg:"Unauthorized"});let{id:s,db_name:n,db_slug:a,db_description:o,db_image:i,db_full_name:c,active_clone:p,active_clone_parent_db:S}=e.body;c?.match(/datasquirel_user_.*/)||t.json({success:!1,msg:"Unauthorized"});let g=`datasquirel_user_${r.id}_${a}`;if(await l()({dbFullName:"datasquirel",tableName:"user_databases",identifierColumnName:"id",identifierValue:s,data:{db_name:n,db_slug:a,db_description:o,db_image:i,db_full_name:g}}),c&&c!==g){console.log("Renaming Database");let e=f.platform().match(/win/i)?"'C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe'":"mysql",t=f.platform().match(/win/i)?"'C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump.exe'":"mysqldump";try{await _()({queryString:`CREATE DATABASE \`${g}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`,database:c});let r={cwd:process.cwd()};f.platform().match(/win/i)&&(r.shell="bash.exe");let s=`${t} -u ${process.env.DSQL_DB_USERNAME} -h ${process.env.DSQL_DB_HOST} -p${process.env.DSQL_DB_PASSWORD} ${c} > tmpDbFile.sql`;console.log(`updateUserDatabase.js exe => ${s}`),D(s,r),D(`${e} -u ${process.env.DSQL_DB_USERNAME} -h ${process.env.DSQL_DB_HOST} -p${process.env.DSQL_DB_PASSWORD} ${g} < tmpDbFile.sql`,r),await _()({queryString:`DROP DATABASE \`${c}\``,database:c})}catch(e){u()({component:"/api/updateUserDatabase/lines-88-111",message:e.message,user:r})}}try{let e=`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${r.id}/main.json`,s=JSON.parse(m.readFileSync(e,"utf8")),l=s.filter(e=>e.dbFullName===c);if(l[0].dbName=n,l[0].dbFullName=g,l[0].dbDescription=o,l[0].dbImage=i,l[0].dbSlug=a,p){let e=s.filter(e=>e.dbFullName===l[0].childDatabaseDbFullName)[0],t=e.childrenDatabases?.find(e=>e.dbFullName===c);t&&(t.dbFullName=g)}m.writeFileSync(`${e}`,JSON.stringify(s),"utf8"),t.json({success:!0})}catch(e){u()({component:"/api/updateUserDatabase/main-catch-error",message:e.message,user:r}),t.json({success:!1,msg:"Database Files could not be written!"})}}let E=(0,o.M)(s,"default"),h=(0,o.M)(s,"config"),y=new n.PagesAPIRouteModule({definition:{kind:a.A.PAGES_API,page:"/api/updateUserDatabase",pathname:"/api/updateUserDatabase",bundlePath:"",filename:""},userland:s})},6420:(e,t,r)=>{r(81630);let s=r(51348),n=r(72835),a=r(29021),o=r(31341);async function i(e,t,r,i){let{keyCookieName:l,csrfCookieName:c}=o();if(!e.cookies?.[l]?.match(/./))return null;let u=n({encryptedString:e.cookies[l]});if(!u)return null;let p=JSON.parse(u);if(!p.csrf_k||r&&!e.headers["x-csrf-auth"]?.match(RegExp(`${p.csrf_k}`)))return null;let d=process.env.DSQL_USER_LOGIN_KEYS_PATH;if(!d)return console.log("DSQL_USER_LOGIN_KEYS_PATH env variable not found. Please set this variable."),null;if(r&&!a.existsSync(`${d}/${p.csrf_k}`))return null;if(0==p.verification_status&&!r){let e=await s(`SELECT verification_status FROM users WHERE id='${p.id}'`);e&&e[0]&&1==e[0].verification_status&&t.setHeader("Set-Cookie",["user_refresh=1"])}return p?.date&&Date.now()-p.date>6048e5?null:p}e.exports=i},31341:e=>{e.exports=function(){let e=process.env.DSQL_COOKIES_PREFIX||"dsql_";return{keyCookieName:e+(process.env.DSQL_COOKIES_KEY_NAME||"key"),csrfCookieName:e+(process.env.DSQL_COOKIES_CSRF_NAME||"csrf")}}},33364:(e,t,r)=>{let s=r(72583),n=r(16570),a=r(51348),o=r(21339),i=r(20503),l=r(44900);async function c({dbContext:e,paradigm:t,dbFullName:r,tableName:c,data:u,tableSchema:p,identifierColumnName:d,identifierValue:S,encryptionKey:_,encryptionSalt:m,useLocal:f}){if(!u||!Object.keys(u).length)return null;let D=!e?.match(/dsql.user/i)&&(!r||!!r.match(/^datasquirel$/)),g=f?l:D?a:o,E=Object.keys(u),h=[],y=[];for(let e=0;e<E.length;e++)try{let t=E[e],r=u[t],a=p?p?.fields?.filter(e=>e.fieldName===t):null,o=a&&a[0]?a[0]:null;if(null==r||void 0==r)continue;o?.richText&&(r=s(r,n)),o?.encrypted&&(r=i({data:r,encryptionKey:_,encryptionSalt:m})),"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?y.push(String(r)):y.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 b=`UPDATE ${c} SET ${h.join(",")} WHERE \`${d}\`=?`;return y.push(S),D?await g(b,y):await g({paradigm:t,database:r,queryString:b,queryValues:y})}e.exports=c},30003:e=>{e.exports=/^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/},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"]}}},6061:(e,t,r)=>{let s=r(72835),n=r(30003);e.exports=async function({unparsedResults:e,tableSchema:t}){let r=[];try{for(let a=0;a<e.length;a++){let o=e[a],i=Object.keys(o);for(let e=0;e<i.length;e++){let r=i[e],a=t?.fields[e];if(r?.match(n))continue;let l=o[r];("number"==typeof l||l)&&a?.encrypted&&l?.match(/./)&&(o[r]=s({encryptedString:l}))}r.push(o)}return r}catch(t){return console.log("ERROR in parseDbResults Function =>",t.message),e}}},48225:(e,t,r)=>{let s=r(29021),{IncomingMessage:n}=r(81630);e.exports=async function({user:e,message:t,component:r,noMail:n,req:a}){let o=new Date,i=(()=>{if(!a)return null;try{let e=a.headers["x-forwarded-for"],t=a.headers["x-real-ip"],r=a.headers["cf-connecting-ip"],s=Array.isArray(e)?e[0]:e?.split(",")[0],n=r||s||t||a.socket.remoteAddress;if(!n)return null;return String(n)}catch(e){return null}})();try{let n=`🚀 SERVER ERROR ===========================
Error Message: ${t}
Component: ${r}`;e?.id&&e?.first_name&&e?.last_name&&e?.email&&(n+=`
User Id: ${e?.id}
User Name: ${e?.first_name} ${e?.last_name}
User Email: ${e?.email}`),a?.url&&(n+=`
URL: ${a.url}`),a?.body&&(n+=`
Request Body: ${JSON.stringify(a.body,null,4)}`),i&&(n+=`
IP: ${i}`),n+=`
Date: ${o.toDateString()}
========================================`,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}`)}catch(e){console.log("Server Error Reporting Error:",e.message)}}},57638:(e,t,r)=>{r(29021);let s=r(6061),n=r(48225),a=r(51348),o=r(21339);e.exports=async function({queryString:e,queryValuesArray:t,database:r,tableSchema:i}){let l;let c=!!r?.match(/^datasquirel$/),u=c?a:o;try{l=e&&t&&Array.isArray(t)&&t[0]?c?await u(e,t):await u({paradigm:"Full Access",database:r,queryString:e,queryValues:t}):c?await u(e):await u({paradigm:"Full Access",database:r,queryString:e})}catch(e){n({component:"varDatabaseDbHandler/lines-29-32",message:e.message})}if(l&&i)try{let e=l;return await s({unparsedResults:e,tableSchema:i})}catch(e){return console.log("\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>",r,e),n({component:"varDatabaseDbHandler/lines-52-53",message:e.message}),null}else if(l)return l;else return null}},72835:(e,t,r)=>{let{scryptSync:s,createDecipheriv:n}=r(55511),{Buffer:a}=r(79428);e.exports=({encryptedString:e,encryptionKey:t,encryptionSalt:r})=>{if(!e?.match(/./))return console.log("Encrypted string is invalid"),e;let o=t||process.env.DSQL_ENCRYPTION_PASSWORD,i=r||process.env.DSQL_ENCRYPTION_SALT,l=process.env.DSQL_ENCRYPTION_KEY_LENGTH?Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH):24;if(!o?.match(/.{8,}/))return console.log("Decrption key is invalid"),e;if(!i?.match(/.{8,}/))return console.log("Decrption salt is invalid"),e;let c=n("aes-192-cbc",s(o,i,l),a.alloc(16,0));try{let t=c.update(e,"hex","utf8");return t+=c.final("utf8")}catch(t){return console.log("Error in decrypting =>",t.message),e}}},20503:(e,t,r)=>{let{scryptSync:s,createCipheriv:n}=r(55511),{Buffer:a}=r(79428);e.exports=({data:e,encryptionKey:t,encryptionSalt:r})=>{if(!e?.match(/./))return console.log("Encryption string is invalid"),e;let o=t||process.env.DSQL_ENCRYPTION_PASSWORD,i=r||process.env.DSQL_ENCRYPTION_SALT,l=process.env.DSQL_ENCRYPTION_KEY_LENGTH?Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH):24;if(!o?.match(/.{8,}/))return console.log("Encryption key is invalid"),e;if(!i?.match(/.{8,}/))return console.log("Encryption salt is invalid"),e;let c=n("aes-192-cbc",s(o,i,l),a.alloc(16,0));try{let t=c.update(e,"utf8","hex");return t+=c.final("hex")}catch(t){return console.log("Error in encrypting =>",t.message),e}}},51348:(e,t,r)=>{let s=r(9973),n=r(21580),a=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:n()}});async function o(...e){try{let t=await a.query(...e);return await a.end(),JSON.parse(JSON.stringify(t))}catch(e){return console.log("DB Error =>",e),{success:!1,error:e.message}}}e.exports=o},21339:(e,t,r)=>{let s=r(29021);r(33873);let n=r(9973),a=r(21580),o=n({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:a()}});e.exports=function({paradigm:e,database:t,queryString:r,queryValues:i}){try{return new Promise((l,c)=>{let u=!!e?.match(/full.access|^fa$/i);try{function p(e){o.end(),l(JSON.parse(JSON.stringify(e)))}function d(e){o.end(),l({error:e.message,queryStringGenerated:r,queryValuesGenerated:i,sql:e.sql})}o=u?n({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:a()}}):n({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:a()}}),i&&Array.isArray(i)&&i[0]?o.query(r,i).then(p).catch(d):o.query(r).then(p).catch(d)}catch(e){s.appendFileSync("./.tmp/dbErrorLogs.txt",e.message+"\n"+Date()+"\n\n\n","utf8"),l({error:e.message})}})}catch(e){return{success:!1,error:e.message}}}},44900:(e,t,r)=>{let s=r(9973),n=r(21580);async function a(...e){let t=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:n()},onConnect:()=>{console.log("Connection Successful!")},onConnectError:e=>{console.log("Connection Error",e.message)},onError:e=>{console.log("Client Error",e.message)}});console.log("Querying ...");try{let r=await t.query(...e);return await t.end(),JSON.parse(JSON.stringify(r))}catch(e){return console.log("DB Error =>",e.message),{success:!1,error:e.message}}}e.exports=a},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=29750);module.exports=r})();