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