dsql-admin/dsql-app/.local_dist/server/pages/api/createUserDatabase.js
Benjamin Toby 3ffd2d6777 Updates
2024-12-05 08:03:33 +01:00

16 lines
6.5 KiB
JavaScript

"use strict";(()=>{var e={};e.id=8893,e.ids=[8893],e.modules={27825:e=>{e.exports=require("lodash")},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")},33873:e=>{e.exports=require("path")},34932:(e,r,t)=>{t.r(r),t.d(r,{config:()=>R,default:()=>g,routeModule:()=>N});var a={};t.r(a),t.d(a,{default:()=>h});var s=t(89947),l=t(2706),n=t(96762),i=t(51348),o=t.n(i),u=t(77538),c=t.n(u),d=t(6420),p=t.n(d),m=t(47670),_=t.n(m),S=t(51926),b=t.n(S);let f=t(29021),E=t(33873),{execSync:D}=t(79646);async function h(e,r){if("POST"!==e.method)return r.json({msg:"Failed!"});let t=await p()(e,r,!0);if(!t)return r.json({success:!1,msg:"Unauthorized"});let a=await o()("SELECT * FROM users WHERE id = ?",[t.id]),s=a?.[0],{db_name:l,db_slug:n,db_description:i,db_image:u,duplicate:d,keepUpdated:m,keepDataUpdated:S}=e.body;if(n.match(/[^a-zA-Z0-9-_]/))return r.json({success:!1,msg:"Input Error"});let h=`datasquirel_user_${t.id}_${n}`,g=await b()(`CREATE DATABASE IF NOT EXISTS \`${h}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);if(!g?.affectedRows)return r.json({success:!1,msg:"Database Could Not be created!"});let R={user_id:t.id,db_name:l,db_slug:n,db_full_name:h,db_description:i,db_image:u};d&&m&&(R.active_clone="1",R.active_clone_parent_db=d),d&&S&&(R.active_data="1");let N=await _()({dbFullName:"datasquirel",tableName:"user_databases",data:R});if(N.insertId)try{let e=`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${t.id}/main.json`,a=JSON.parse(f.readFileSync(e,"utf8")),o={dbName:l,dbSlug:n,dbFullName:h,dbDescription:i,dbImage:u,tables:[]};if(d)try{let e=a.filter(e=>e.dbFullName===d)[0];o.tables=e.tables,m&&(o.childDatabase=!0,o.childDatabaseDbFullName=d,S&&(o.updateData=!0),e.childrenDatabases?e.childrenDatabases.push({dbFullName:h}):e.childrenDatabases=[{dbFullName:h}]);for(let e=0;e<o.tables.length;e++){let r=o.tables[e];await _()({dbFullName:"datasquirel",tableName:"user_database_tables",data:{user_id:t.id,db_id:N.insertId,db_slug:n,table_name:r.tableFullName,table_slug:r.tableName}})}}catch(e){c()({component:"/api/createUserDatabase/lines-117-159",message:e.message,user:t})}if(a.push(o),f.writeFileSync(`${e}`,JSON.stringify(a),"utf8"),d){let e=E.join(process.cwd(),"/shell");D(`node createDbFromSchema.js --user ${t.id} --database ${h}`,{cwd:e})}let p=await b()(`GRANT ALL PRIVILEGES ON ${h}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'${process.env.DSQL_DB_TARGET_IP_ADDRESS||"%"}' WITH GRANT OPTION`);if(p.error)throw Error(p.error);let g=await b()(`GRANT SELECT ON ${h}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'${process.env.DSQL_DB_TARGET_IP_ADDRESS||"%"}'`);if(g.error)throw Error(g.error);s?.mariadb_user&&s?.mariadb_pass&&await b()(`GRANT ALL PRIVILEGES ON ${h}.* TO '${s.mariadb_user}'@'${s.mariadb_host}'`),await b()("FLUSH PRIVILEGES"),r.json({success:!0})}catch(e){c()({component:"/api/createUserDatabase/main-catch-error",message:e.message,user:t}),r.json({success:!1,msg:"Database Files could not be written!"})}else r.json({success:!1,msg:"Database Could Not Be Recorded!"})}let g=(0,n.M)(a,"default"),R=(0,n.M)(a,"config"),N=new s.PagesAPIRouteModule({definition:{kind:l.A.PAGES_API,page:"/api/createUserDatabase",pathname:"/api/createUserDatabase",bundlePath:"",filename:""},userland:a})},77538:(e,r,t)=>{let a=t(29021),{IncomingMessage:s}=t(81630);e.exports=async function({user:e,message:r,component:t,noMail:s,req:l}){let n=new Date,i=(()=>{if(!l)return null;try{let e=l.headers["x-forwarded-for"],r=l.headers["x-real-ip"],t=l.headers["cf-connecting-ip"],a=Array.isArray(e)?e[0]:e?.split(",")[0],s=t||a||r||l.socket.remoteAddress;if(!s)return null;return String(s)}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}`),l?.url&&(s+=`
URL: ${l.url}`),l?.body&&(s+=`
Request Body: ${JSON.stringify(l.body,null,4)}`),i&&(s+=`
IP: ${i}`),s+=`
Date: ${n.toDateString()}
========================================`,a.existsSync("./.tmp/error.log")||a.writeFileSync("./.tmp/error.log","","utf-8");let o=a.readFileSync("./.tmp/error.log","utf-8");a.writeFileSync("./.tmp/error.log",s),a.appendFileSync("./.tmp/error.log",`
${o}`)}catch(e){console.log("Server Error Reporting Error:",e.message)}}},6420:(e,r,t)=>{t(81630);let a=t(51348),s=t(72907),l=t(29021);async function n(e,r,t,n){if(!e.cookies?.datasquirelAuthKey?.match(/./))return null;let i=s(e.cookies.datasquirelAuthKey);if(!i)return null;let o=JSON.parse(i);if(!o.csrf_k||t&&!e.headers["x-csrf-auth"]?.match(RegExp(`${o.csrf_k}`)))return null;let u=process.env.DSQL_USER_LOGIN_KEYS_PATH;if(!u)return console.log("DSQL_USER_LOGIN_KEYS_PATH env variable not found. Please set this variable."),null;if(t&&!l.existsSync(`${u}/${o.csrf_k}`))return null;if(0==o.verification_status&&!t){let e=await a(`SELECT verification_status FROM users WHERE id='${o.id}'`);e&&e[0]&&1==e[0].verification_status&&r.setHeader("Set-Cookie",["user_refresh=1"])}return o?.date&&Date.now()-o.date>6048e5?null:o}e.exports=n},72907:(e,r,t)=>{let{scryptSync:a,createDecipheriv:s}=t(55511),{Buffer:l}=t(79428);e.exports=e=>{let r=s("aes-192-cbc",a(process.env.DSQL_ENCRYPTION_PASSWORD||"",process.env.DSQL_ENCRYPTION_SALT||"",24),l.alloc(16,0));try{let t=r.update(e,"hex","utf8");return t+=r.final("utf8")}catch(e){return null}}},51926:(e,r,t)=>{let a=t(29021),s=t(48225),l=t(45356);e.exports=async function(e){let r;"production".match(/dev/)&&a.appendFileSync("./.tmp/sqlQuery.sql",e+"\n"+Date()+"\n\n\n","utf8");try{r=await l(e)}catch(e){s({component:"noDatabaseDbHandler",message:e.message}),console.log("ERROR in noDatabaseDbHandler =>",e.message)}return r||null}},45356:(e,r,t)=>{let a=t(9973),s=t(21580),l=a({config:{host:process.env.DSQL_DB_HOST,user:process.env.DSQL_DB_USERNAME,password:process.env.DSQL_DB_PASSWORD,charset:"utf8mb4",ssl:s()}});e.exports=function(...e){try{return new Promise((r,t)=>{l.query(...e).then(e=>{l.end(),r(JSON.parse(JSON.stringify(e)))}).catch(e=>{l.end(),r({error:e.message,sql:e.sql})})})}catch(e){return{success:!1,error:e.message}}}}};var r=require("../../webpack-api-runtime.js");r.C(e);var t=e=>r(r.s=e),a=r.X(0,[4050],()=>t(34932));module.exports=a})();