dsql-admin/dsql-app/.local_dist/server/pages/api/updateUserDatabase.js
Benjamin Toby bc037e839f Updates
2024-12-15 12:27:16 +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,r)=>{Object.defineProperty(r,"M",{enumerable:!0,get:function(){return function e(r,t){return t in r?r[t]:"then"in r&&"function"==typeof r.then?r.then(r=>e(r,t)):"function"==typeof r&&"default"===t?r:void 0}}})},29750:(e,r,t)=>{t.r(r),t.d(r,{config:()=>h,default:()=>E,routeModule:()=>y});var s={};t.r(s),t.d(s,{default:()=>g});var n=t(89947),a=t(2706),o=t(96762),l=t(33364),i=t.n(l),c=t(48225),u=t.n(c),p=t(6420),d=t.n(p),_=t(57638),S=t.n(_);let m=t(29021),f=t(21820);t(33873);let{execSync:D}=t(79646);async function g(e,r){if("POST"!==e.method)return r.json({msg:"Failed!"});let t=await d()(e,r,!0);if(!t)return r.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_.*/)||r.json({success:!1,msg:"Unauthorized"});let g=`datasquirel_user_${t.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",r=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 t={cwd:process.cwd()};f.platform().match(/win/i)&&(t.shell="bash.exe");let s=`${r} -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,t),D(`${e} -u ${process.env.DSQL_DB_USERNAME} -h ${process.env.DSQL_DB_HOST} -p${process.env.DSQL_DB_PASSWORD} ${g} < tmpDbFile.sql`,t),await S()({queryString:`DROP DATABASE \`${c}\``,database:c})}catch(e){u()({component:"/api/updateUserDatabase/lines-88-111",message:e.message,user:t})}}try{let e=`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${t.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],r=e.childrenDatabases?.find(e=>e.dbFullName===c);r&&(r.dbFullName=g)}m.writeFileSync(`${e}`,JSON.stringify(s),"utf8"),r.json({success:!0})}catch(e){u()({component:"/api/updateUserDatabase/main-catch-error",message:e.message,user:t}),r.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,r,t)=>{t(81630);let s=t(51348),n=t(72835),a=t(29021),o=t(31341);async function l(e,r,t,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||t&&!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(t&&!a.existsSync(`${d}/${p.csrf_k}`))return null;if(0==p.verification_status&&!t){let e=await s(`SELECT verification_status FROM users WHERE id='${p.id}'`);e&&e[0]&&1==e[0].verification_status&&r.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 r=process.env.DSQL_COOKIES_PREFIX||"dsql_",t=process.env.DSQL_COOKIES_KEY_NAME||"key",s=process.env.DSQL_COOKIES_CSRF_NAME||"csrf",n=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+_/,""),o=r;e?.userId&&(o+=`user_${e.userId}_`),a&&(o+=`${a}_`),o+=t;let l=r;e?.userId&&(l+=`user_${e.userId}_`),a&&(l+=`${a}_`),l+=s;let i=r;return e?.userId&&(i+=`user_${e.userId}_`),a&&(i+=`${a}_`),{keyCookieName:o,csrfCookieName:l,oneTimeCodeName:i+=n}}},33364:(e,r,t)=>{let s=t(72583),n=t(16570),a=t(51348),o=t(21339),l=t(20503),i=t(44900);async function c({dbContext:e,paradigm:r,dbFullName:t,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)&&(!t||!!t.match(/^datasquirel$/)),g=f?i:D?a:o,E=Object.keys(u),h=[],y=[];for(let e=0;e<E.length;e++)try{let r=E[e],t=u[r],a=p?p?.fields?.filter(e=>e.fieldName===r):null,o=a&&a[0]?a[0]:null;if(null==t||void 0==t)continue;let i=/<[^>]+>/g;(o?.richText||String(t).match(i))&&(t=s(t,n)),o?.encrypted&&(t=l({data:t,encryptionKey:S,encryptionSalt:m})),"object"==typeof t&&(t=JSON.stringify(t)),o?.pattern&&!new RegExp(o.pattern,o.patternFlags||"").test(t)&&(console.log("DSQL: Pattern not matched =>",t),t=""),"string"==typeof t&&t.match(/^null$/i)&&(t={toSqlString:function(){return"NULL"}}),"string"!=typeof t||t.match(/./i)||(t={toSqlString:function(){return"NULL"}}),h.push(`\`${r}\`=?`),"number"==typeof t?y.push(String(t)):y.push(t)}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:r,database:t,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,r,t)=>{let s=t(72835),n=t(30003);e.exports=async function({unparsedResults:e,tableSchema:r}){let t=[];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 t=l[e],a=r?.fields[e];if(t?.match(n))continue;let i=o[t];("number"==typeof i||i)&&a?.encrypted&&i?.match(/./)&&(o[t]=s({encryptedString:i}))}t.push(o)}return t}catch(r){return console.log("ERROR in parseDbResults Function =>",r.message),e}}},48225:(e,r,t)=>{let s=t(29021),{IncomingMessage:n}=t(81630);e.exports=async function({user:e,message:r,component:t,noMail:n,req:a}){let o=new Date,l=(()=>{if(!a)return null;try{let e=a.headers["x-forwarded-for"],r=a.headers["x-real-ip"],t=a.headers["cf-connecting-ip"],s=Array.isArray(e)?e[0]:e?.split(",")[0],n=t||s||r||a.socket.remoteAddress;if(!n)return null;return String(n)}catch(e){return null}})();try{let n=`🚀 SERVER ERROR ===========================
Error Message: ${r}
Component: ${t}`;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,r,t)=>{t(29021);let s=t(6061),n=t(48225),a=t(51348),o=t(21339),l=t(44900);e.exports=async function({queryString:e,queryValuesArray:r,database:t,tableSchema:i,useLocal:c}){let u;let p=!!c||!!t?.match(/^datasquirel$/),d=c?l:p?a:o;try{u=e&&r&&Array.isArray(r)&&r[0]?p?await d(e,r):await d({paradigm:"Full Access",database:t,queryString:e,queryValues:r}):p?await d(e):await d({paradigm:"Full Access",database:t,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 =>",t,e),n({component:"varDatabaseDbHandler/lines-52-53",message:e.message}),null}else if(u)return u;else return null}},72835:(e,r,t)=>{let{scryptSync:s,createDecipheriv:n}=t(55511),{Buffer:a}=t(79428);e.exports=({encryptedString:e,encryptionKey:r,encryptionSalt:t})=>{if(!e?.match(/./))return console.log("Encrypted string is invalid"),e;let o=r||process.env.DSQL_ENCRYPTION_PASSWORD,l=t||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 r=c.update(e,"hex","utf8");return r+=c.final("utf8")}catch(r){return console.log("Error in decrypting =>",r.message),e}}},20503:(e,r,t)=>{let{scryptSync:s,createCipheriv:n}=t(55511),{Buffer:a}=t(79428);e.exports=({data:e,encryptionKey:r,encryptionSalt:t})=>{if(!e?.match(/./))return console.log("Encryption string is invalid"),e;let o=r||process.env.DSQL_ENCRYPTION_PASSWORD,l=t||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 r=c.update(e,"utf8","hex");return r+=c.final("hex")}catch(r){return console.log("Error in encrypting =>",r.message),e}}},51348:(e,r,t)=>{let s=t(9973),n=t(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 r=await a.query(...e);return await a.end(),JSON.parse(JSON.stringify(r))}catch(e){return console.log("DB Error =>",e),{success:!1,error:e.message}}}e.exports=o},21339:(e,r,t)=>{let s=t(29021);t(33873);let n=t(9973),a=t(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:r,queryString:t,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:t,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:r,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:r,ssl:a()}}),l&&Array.isArray(l)&&l[0]?o.query(t,l).then(p).catch(d):o.query(t).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,r,t)=>{let s=t(9973),n=t(21580);async function a(...e){let r=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 t=await r.query(...e);return await r.end(),JSON.parse(JSON.stringify(t))}catch(e){return console.log("DB Error =>",e.message),{success:!1,error:e.message}}}e.exports=a},21580:(e,r,t)=>{let s=t(29021);e.exports=function(){let e=process.env.DSQL_SSL_DIR;if(!e?.match(/./))return;let r=`${e}/ca-cert.pem`;if(!s.existsSync(r)){console.log(`${r} does not exist`);return}return{ca:s.readFileSync(`${e}/ca-cert.pem`)}}},2706:(e,r)=>{var t;Object.defineProperty(r,"A",{enumerable:!0,get:function(){return t}}),function(e){e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE",e.IMAGE="IMAGE"}(t||(t={}))},89947:(e,r,t)=>{e.exports=t(75600)}};var r=require("../../webpack-api-runtime.js");r.C(e);var t=r(r.s=29750);module.exports=t})();