dsql-admin/dsql-app/.local_dist/server/pages/api/updateUserDatabase.js
Benjamin Toby d9d32a4643 Updates
2024-12-09 13:27:08 +01:00

16 lines
13 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),l=r(33364),i=r.n(l),c=r(48225),u=r.n(c),p=r(6420),d=r.n(p),_=r(57638),S=r.n(_);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:l,db_full_name:c,active_clone:p,active_clone_parent_db:_}=e.body;c?.match(/datasquirel_user_.*/)||t.json({success:!1,msg:"Unauthorized"});let g=`datasquirel_user_${r.id}_${a}`;if(await i()({dbFullName:"datasquirel",tableName:"user_databases",identifierColumnName:"id",identifierValue:s,data:{db_name:n,db_slug:a,db_description:o,db_image:l,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 S()({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 S()({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")),i=s.filter(e=>e.dbFullName===c);if(i[0].dbName=n,i[0].dbFullName=g,i[0].dbDescription=o,i[0].dbImage=l,i[0].dbSlug=a,p){let e=s.filter(e=>e.dbFullName===i[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 l(e,t,r,l){let{keyCookieName:i,csrfCookieName:c}=o();if(!e.cookies?.[i]?.match(/./))return null;let u=n({encryptedString:e.cookies[i]});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=l},31341:e=>{e.exports=function(e){let t=process.env.DSQL_COOKIES_PREFIX||"dsql_",r=process.env.DSQL_COOKIES_KEY_NAME||"key",s=process.env.DSQL_COOKIES_CSRF_NAME||"csrf",n=e?.database||process.env.DSQL_DB_NAME?.replace(/^datasquirel_user_\d+_/,""),a=t;e?.userId&&(a+=`user_${e.userId}_`),n&&(a+=`${n}_`),a+=r;let o=t;return e?.userId&&(o+=`user_${e.userId}_`),n&&(o+=`${n}_`),{keyCookieName:a,csrfCookieName:o+=s}}},33364:(e,t,r)=>{let s=r(72583),n=r(16570),a=r(51348),o=r(21339),l=r(20503),i=r(44900);async function c({dbContext:e,paradigm:t,dbFullName:r,tableName:c,data:u,tableSchema:p,identifierColumnName:d,identifierValue:_,encryptionKey:S,encryptionSalt:m,useLocal:f}){if(!u||!Object.keys(u).length)return null;let D=!!f||!e?.match(/dsql.user/i)&&(!r||!!r.match(/^datasquirel$/)),g=f?i: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=l({data:r,encryptionKey:S,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(_),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],l=Object.keys(o);for(let e=0;e<l.length;e++){let r=l[e],a=t?.fields[e];if(r?.match(n))continue;let i=o[r];("number"==typeof i||i)&&a?.encrypted&&i?.match(/./)&&(o[r]=s({encryptedString:i}))}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,l=(()=>{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)}`),l&&(n+=`
IP: ${l}`),n+=`
Date: ${o.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",n),s.appendFileSync("./.tmp/error.log",`
${i}`)}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),l=r(44900);e.exports=async function({queryString:e,queryValuesArray:t,database:r,tableSchema:i,useLocal:c}){let u;let p=!!c||!!r?.match(/^datasquirel$/),d=c?l:p?a:o;try{u=e&&t&&Array.isArray(t)&&t[0]?p?await d(e,t):await d({paradigm:"Full Access",database:r,queryString:e,queryValues:t}):p?await d(e):await d({paradigm:"Full Access",database:r,queryString:e})}catch(e){n({component:"varDatabaseDbHandler/lines-29-32",message:e.message})}if(u&&i)try{let e=u;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(u)return u;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,l=r||process.env.DSQL_ENCRYPTION_SALT,i=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(!l?.match(/.{8,}/))return console.log("Decrption salt is invalid"),e;let c=n("aes-192-cbc",s(o,l,i),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,l=r||process.env.DSQL_ENCRYPTION_SALT,i=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(!l?.match(/.{8,}/))return console.log("Encryption salt is invalid"),e;let c=n("aes-192-cbc",s(o,l,i),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:l}){try{return new Promise((i,c)=>{let u=!!e?.match(/full.access|^fa$/i);try{function p(e){o.end(),i(JSON.parse(JSON.stringify(e)))}function d(e){o.end(),i({error:e.message,queryStringGenerated:r,queryValuesGenerated:l,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()}}),l&&Array.isArray(l)&&l[0]?o.query(r,l).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"),i({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})();