dsql-admin/dsql-app/.local_dist/server/pages/api/updateUserDatabase.js
Benjamin Toby e0a030f10d Updates
2025-01-13 09:00:21 +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")},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}}})},53382:(e,t,r)=>{r.r(t),r.d(t,{config:()=>S,default:()=>m,routeModule:()=>g});var n={};r.r(n),r.d(n,{default:()=>_});var s=r(89947),a=r(2706),l=r(96762),i=r(30802),o=r(67619),c=r(69842),u=r(30944);let d=r(29021),p=r(21820);r(33873);let{execSync:f}=r(79646);async function _(e,t){if("POST"!==e.method)return t.json({msg:"Failed!"});let r=await (0,c.A)(e,t,!0);if(!r)return t.json({success:!1,msg:"Unauthorized"});let{id:n,db_name:s,db_slug:a,db_description:l,db_image:_,db_full_name:m,active_clone:S,active_clone_parent_db:g}=e.body;m?.match(/datasquirel_user_.*/)||t.json({success:!1,msg:"Unauthorized"});let y=`datasquirel_user_${r.id}_${a}`;if(await (0,i.A)({dbFullName:"datasquirel",tableName:"user_databases",identifierColumnName:"id",identifierValue:n,data:{db_name:s,db_slug:a,db_description:l,db_image:_,db_full_name:y}}),m&&m!==y){console.log("Renaming Database");let e=p.platform().match(/win/i)?"'C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe'":"mysql",t=p.platform().match(/win/i)?"'C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump.exe'":"mysqldump";try{await (0,u.A)({queryString:`CREATE DATABASE \`${y}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`});let r={cwd:process.cwd()};p.platform().match(/win/i)&&(r.shell="bash.exe");let n=`${t} -u ${process.env.DSQL_DB_USERNAME} -h ${process.env.DSQL_DB_HOST} -p${process.env.DSQL_DB_PASSWORD} ${m} > tmpDbFile.sql`;console.log(`updateUserDatabase.ts exe => ${n}`),f(n,r),f(`${e} -u ${process.env.DSQL_DB_USERNAME} -h ${process.env.DSQL_DB_HOST} -p${process.env.DSQL_DB_PASSWORD} ${y} < tmpDbFile.sql`,r),await (0,u.A)({queryString:`DROP DATABASE \`${m}\``})}catch(e){(0,o.default)({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`,n=JSON.parse(d.readFileSync(e,"utf8")),i=n.filter(e=>e.dbFullName===m);if(i[0].dbName=s,i[0].dbFullName=y,i[0].dbDescription=l,i[0].dbImage=_,i[0].dbSlug=a,S){let e=n.filter(e=>e.dbFullName===i[0].childDatabaseDbFullName)[0],t=e.childrenDatabases?.find(e=>e.dbFullName===m);t&&(t.dbFullName=y)}d.writeFileSync(`${e}`,JSON.stringify(n),"utf8"),t.json({success:!0})}catch(e){(0,o.default)({component:"/api/updateUserDatabase/main-catch-error",message:e.message,user:r}),t.json({success:!1,msg:"Database Files could not be written!"})}}let m=(0,l.M)(n,"default"),S=(0,l.M)(n,"config"),g=new s.PagesAPIRouteModule({definition:{kind:a.A.PAGES_API,page:"/api/updateUserDatabase",pathname:"/api/updateUserDatabase",bundlePath:"",filename:""},userland:n})},69842:(e,t,r)=>{r.d(t,{A:()=>o});var n=r(48786),s=r(95969),a=r(29021),l=r.n(a),i=r(89159);async function o(e,t,r){let{keyCookieName:a,csrfCookieName:o}=(0,i.A)();if(!e.cookies?.[a]?.match(/./))return null;let c=(0,s.A)({encryptedString:e.cookies[a]});if(!c)return null;let u=JSON.parse(c);if(!u.csrf_k||r&&!Object.keys(e.headers).find(e=>e.includes(u.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&&!l().existsSync(`${d}/${u.csrf_k}`))return null;if(0==u.verification_status&&!r){let e=await (0,n.A)(`SELECT verification_status FROM users WHERE id='${u.id}'`);e&&e[0]&&1==e[0].verification_status&&t.setHeader("Set-Cookie",["user_refresh=1"])}return u?.date&&Date.now()-u.date>6048e5?null:u}},89159:(e,t,r)=>{r.d(t,{A:()=>n});function n(e){let t=process.env.DSQL_COOKIES_PREFIX||"dsql_",r=process.env.DSQL_COOKIES_KEY_NAME||"key",n=process.env.DSQL_COOKIES_CSRF_NAME||"csrf",s=process.env.DSQL_COOKIES_ONE_TIME_CODE_NAME||"one-time-code",a=e?.database?.replace(/^datasquirel_user_\d+_/,"")||process.env.DSQL_DB_NAME?.replace(/^datasquirel_user_\d+_/,""),l=t;e?.userId&&(l+=`user_${e.userId}_`),a&&(l+=`${a}_`),l+=r;let i=t;e?.userId&&(i+=`user_${e.userId}_`),a&&(i+=`${a}_`),i+=n;let o=t;return e?.userId&&(o+=`user_${e.userId}_`),a&&(o+=`${a}_`),{keyCookieName:l,csrfCookieName:i,oneTimeCodeName:o+=s}}},30802:(e,t,r)=>{r.d(t,{A:()=>u});var n=r(72583),s=r.n(n),a=r(92652),l=r(48786),i=r(37275),o=r(68829),c=r(7971);async function u({dbContext:e,paradigm:t,dbFullName:r,tableName:n,data:u,tableSchema:d,identifierColumnName:p,identifierValue:f,encryptionKey:_,encryptionSalt:m,useLocal:S}){if(!u||!Object.keys(u).length)return null;let g=!!S||!e?.match(/dsql.user/i)&&(!r||!!r.match(/^datasquirel$/)),y=S?c.A:g?l.A:i.default,D=Object.keys(u),E=[],h=[];for(let e=0;e<D.length;e++)try{let t=D[e],r=u[t],n=d?d?.fields?.filter(e=>e.fieldName===t):null,l=n&&n[0]?n[0]:null;if(null==r||void 0==r)continue;let i=/<[^>]+>/g;(l?.richText||String(r).match(i))&&(r=s()(r,a.A)),l?.encrypted&&(r=(0,o.default)({data:r,encryptionKey:_,encryptionSalt:m})),"object"==typeof r&&(r=JSON.stringify(r)),l?.pattern&&!new RegExp(l.pattern,l.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"}}),E.push(`\`${t}\`=?`),"number"==typeof r?h.push(String(r)):h.push(r)}catch(e){console.log("DSQL: Error in parsing data keys in update function =>",e.message);continue}E.push(`date_updated='${Date()}'`),E.push(`date_updated_code='${Date.now()}'`);let A=`UPDATE \`${r}\`.\`${n}\` SET ${E.join(",")} WHERE \`${p}\`=?`;return h.push(f),g?await y(A,h):await y({paradigm:t,queryString:A,queryValues:h})}},92652:(e,t,r)=>{r.d(t,{A:()=>n});let n={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"]}}},43775:(e,t,r)=>{r.d(t,{A:()=>a});var n=r(95969);let s=/^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;async function a({unparsedResults:e,tableSchema:t}){let r=[];try{for(let a=0;a<e.length;a++){let l=e[a],i=Object.keys(l);for(let e=0;e<i.length;e++){let r=i[e],a=t?.fields[e];if(r?.match(s))continue;let o=l[r];("number"==typeof o||o)&&a?.encrypted&&o?.match(/./)&&(l[r]=(0,n.A)({encryptedString:o}))}r.push(l)}return r}catch(t){return console.log("ERROR in parseDbResults Function =>",t.message),e}}},67619:(e,t,r)=>{r.r(t),r.d(t,{default:()=>a});var n=r(29021),s=r.n(n);async function a({user:e,message:t,component:r,noMail:n,req:a}){let l=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"],n=Array.isArray(e)?e[0]:e?.split(",")[0],s=r||n||t||a.socket.remoteAddress;if(!s)return null;return String(s)}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: ${l.toDateString()}
========================================`,s().existsSync("./.tmp/error.log")||s().writeFileSync("./.tmp/error.log","","utf-8");let o=s().readFileSync("./.tmp/error.log","utf-8");s().writeFileSync("./.tmp/error.log",n),s().appendFileSync("./.tmp/error.log",`
${o}`)}catch(e){console.log("Server Error Reporting Error:",e.message)}}},30944:(e,t,r)=>{r.d(t,{A:()=>o});var n=r(43775),s=r(67619),a=r(48786),l=r(37275),i=r(7971);async function o({queryString:e,queryValuesArray:t,database:r,tableSchema:o,useLocal:c}){let u;let d=!!c||!!r?.match(/^datasquirel$/),p=c?i.A:d?a.A:l.default;try{u=e&&t&&Array.isArray(t)&&t[0]?d?await p(e,t):await p({paradigm:"Full Access",queryString:e,queryValues:t}):d?await p(e):await p({paradigm:"Full Access",queryString:e})}catch(e){console.log(`varDatabaseDbHandler Error: ${e.message}`),(0,s.default)({component:"varDatabaseDbHandler/lines-29-32",message:e.message})}if(u&&o)try{let e=u;return await (0,n.A)({unparsedResults:e,tableSchema:o})}catch(e){return console.log("\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>",r,e),(0,s.default)({component:"varDatabaseDbHandler/lines-52-53",message:e.message}),null}else if(u)return u;else return null}},95969:(e,t,r)=>{r.d(t,{A:()=>a});var n=r(55511),s=r(79428);function a({encryptedString:e,encryptionKey:t,encryptionSalt:r}){if(!e?.match(/./))return console.log("Encrypted string is invalid"),e;let a=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(!a?.match(/.{8,}/))return console.log("Decrption key is invalid"),e;if(!l?.match(/.{8,}/))return console.log("Decrption salt is invalid"),e;let o=(0,n.scryptSync)(a,l,i),c=s.Buffer.alloc(16,0),u=(0,n.createDecipheriv)("aes-192-cbc",o,c);try{let t=u.update(e,"hex","utf8");return t+=u.final("utf8")}catch(t){return console.log("Error in decrypting =>",t.message),e}}},68829:(e,t,r)=>{r.r(t),r.d(t,{default:()=>a});var n=r(55511),s=r(79428);function a({data:e,encryptionKey:t,encryptionSalt:r}){if(!e?.match(/./))return console.log("Encryption string is invalid"),e;let a=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(!a?.match(/.{8,}/))return console.log("Encryption key is invalid"),e;if(!l?.match(/.{8,}/))return console.log("Encryption salt is invalid"),e;let o=(0,n.scryptSync)(a,l,i),c=s.Buffer.alloc(16,0),u=(0,n.createCipheriv)("aes-192-cbc",o,c);try{let t=u.update(e,"utf8","hex");return t+=u.final("hex")}catch(t){return console.log("Error in encrypting =>",t.message),e}}},48786:(e,t,r)=>{r.d(t,{A:()=>n});async function n(...e){let t=global.DSQL_DB_CONN;try{if(!t)throw Error("No Connection provided to DB_HANDLER function!");let r=await t.query(...e);return JSON.parse(JSON.stringify(r))}catch(e){return console.log("DB Error =>",e),{success:!1,error:e.message}}finally{await t?.end()}}},37275:(e,t,r)=>{async function n(e,t,r){try{if("string"==typeof t){let n=await e.query(s(t),r);return JSON.parse(JSON.stringify(n))}if("object"!=typeof t)return null;{let r=[];for(let n=0;n<t.length;n++)try{let a=t[n],l=await e.query(s(a.query),a.values);r.push(JSON.parse(JSON.stringify(l)))}catch(e){r.push(null)}return r}}catch(e){return null}finally{e.end()}}function s(e){return e.replace(/\n/gm,"").replace(/ {2,}/g,"").trim()}async function a({paradigm:e,queryString:t,queryValues:r}){try{switch(e){case"Read Only":return await n(global.DSQL_READ_ONLY_DB_CONN,t,r);case"Full Access":case"FA":return await n(global.DSQL_FULL_ACCESS_DB_CONN,t,r);default:return null}}catch(e){return console.log(`DSQL_USER_DB_HANDLER Error: ${e.message}`),null}}r.r(t),r.d(t,{default:()=>a})},7971:(e,t,r)=>{r.d(t,{A:()=>i});var n=r(9973),s=r.n(n),a=r(29021),l=r.n(a);async function i(...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:function(){let e=process.env.DSQL_SSL_DIR;if(!e?.match(/./))return;let t=`${e}/ca-cert.pem`;if(!l().existsSync(t)){console.log(`${t} does not exist`);return}return{ca:l().readFileSync(`${e}/ca-cert.pem`),rejectUnauthorized:!1}}()},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}}}},2706:(e,t)=>{Object.defineProperty(t,"A",{enumerable:!0,get:function(){return r}});var r=function(e){return e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE",e.IMAGE="IMAGE",e}({})},89947:(e,t,r)=>{e.exports=r(75600)}};var t=require("../../webpack-api-runtime.js");t.C(e);var r=t(t.s=53382);module.exports=r})();