UNPKG

yekonga-server

Version:
344 lines (284 loc) 12 kB
/*global Yekonga, serverLibrary */ // @ts-nocheck const express = serverLibrary.express; // @ts-ignore const cookieSession = serverLibrary.cookieSession; const path = serverLibrary.path; const fs = serverLibrary.fs; const ControllerResolver = require(path.join(__dirname, 'controllers/resolvers')); const ControllerAuthResolver = require(path.join(__dirname, 'controllers/authResolvers')); const TemplateConfig = require(path.join(__dirname, 'frontendTemplate')); const Middleware = require(path.join(__dirname, 'middleware')); const app = express.Router(); const playgroundRoute = express.Router(); const playgroundPath = path.join(__dirname, '../..', 'public/graphql-playground'); function setPlaygroundRoute(isAuth) { playgroundRoute.get(`/${isAuth? 'auth':''}`, function(req, res) { const setting = { baseUrl: Yekonga.Helper.getBaseUrl('', {req, res}), baseApi: ((isAuth) ? Yekonga.Helper.getApiAuthRoute() : Yekonga.Helper.getApiRoute()), }; let content = fs.readFileSync(path.join(playgroundPath, 'template.html'), { encoding: 'utf8' }); content = Yekonga.Helper.textTemplate(content, setting); return res.status(200).send(content); }) } app.use(Middleware.preloadGraphqlRelatedQuery); // @ts-ignore app.all('/authorization', async function(req, res) { const Auth = Yekonga.Auth; // @ts-ignore if (!req.session) req.session = {}; // @ts-ignore req.session.views = (req.session.views || 0) + 1; // @ts-ignore req.session.usedBy = ''; if (req.session.usedBy) { if (!req.session.usedBy.includes(Yekonga.Config.appName)) { req.session.usedBy = `${req.session.usedBy},${Yekonga.Config.appName}`; } } else { req.session.usedBy = Yekonga.Config.appName; } return res.json({ views: req.session.views, usedBy: req.session.usedBy, }); }); // @ts-ignore app.all('/config', async function(req, res) { const Auth = Yekonga.Auth; const client = req.Yekonga.Client || {}; let javascript = ``; let config = { baseUrl: Yekonga.Helper.getBaseUrl('', {res,req}), host: client.host }, languages = [], translations = [], permissions = []; if (Yekonga.Model.TranslatorLanguage) { languages = await Yekonga.Model.TranslatorLanguage.find({}, { select: ['translatorLanguageId', 'locale', 'name', 'flag'] }, true); } if (Yekonga.Model.TranslatorTranslation) { translations = await Yekonga.Model.TranslatorTranslation.find({ locale: 'en' }, { select: [ 'translatorTranslationId', 'translatorLanguageId', 'locale', 'name', 'namespace', 'group', 'item', 'descriptions', 'text', 'unstable', 'locked' ] }, true); } if (Auth) { permissions = Auth.Permissions; } if (Yekonga.Config) { let frontApi = Yekonga.Helper.getApiRoute(); let frontAuth = Yekonga.Helper.getApiAuthRoute(); let cryptojsKey = Yekonga.Config.authentication.cryptojsKey; let cryptojsIv = Yekonga.Config.authentication.cryptojsIv; let appName = Yekonga.Config.appName; let endToEndEncryption = Yekonga.Config.endToEndEncryption; let googleApiKey = Yekonga.Config.googleApiKey; let googleClientId = Yekonga.Config.googleClientId; let googleClientSecret = Yekonga.Config.googleClientSecret; let userIdentifiers = Yekonga.Config.userIdentifiers; config.appName = appName ? appName : "Yekonga"; config.endToEndEncryption = endToEndEncryption ? endToEndEncryption : null; config.apiRoute = frontApi; config.authRoute = frontAuth; config.googleApiKey = googleApiKey ? googleApiKey : null; config.googleClientId = googleClientId ? googleClientId : null; config.googleClientSecret = googleClientSecret ? googleClientSecret : null; config.cryptojsKey = cryptojsKey ? cryptojsKey : null; config.cryptojsIv = cryptojsIv ? cryptojsIv : null; config.userIdentifiers = Array.isArray(userIdentifiers)? userIdentifiers: ['email', 'phone'] } const templateConfig = TemplateConfig(); javascript += `window['systemLanguages'] = ${JSON.stringify(languages)};\n`; javascript += `window['systemDefaultLanguage'] = ${JSON.stringify(translations)}\n`; javascript += `window['systemPermissions'] = ${JSON.stringify(permissions)}\n`; javascript += `window['systemConfig'] = ${JSON.stringify(config)}\n`; javascript += `window['systemTemplateConfig'] = ${JSON.stringify(templateConfig)}\n`; const profileScript = await Yekonga.Cloud.systemScript(req, res); if(profileScript && typeof profileScript == 'string') { javascript += profileScript } res.setHeader('Content-Type', 'application/javascript; charset=UTF-8'); res.setHeader('Cache-Control', `public, max-age=0`); return res.send(javascript); }); app.all('/config/data', async (req, res)=>{ const conf = await Yekonga.Cloud.systemConfig(req, res); if(!conf) conf = { profileId: null } res.setHeader('Cache-Control', `public, max-age=0`); res.json(conf); }); app.all('/config/report', async function(req, res) { const reportConfig = TemplateConfig().reportConfig; res.setHeader('Cache-Control', `public, max-age=0`); res.set('Content-Type', 'application/json; charset=UTF-8'); res.send({ reportConfig, }); }) app.get('/download/:filename', function(req, res) { var filename = req.params.filename; var filepath = null; var DIR = null; var title = req.query.title? `${req.query.title}${path.extname(filename)}`: filename; if (Array.isArray(Yekonga.Config.public)) { for (const _public of Yekonga.Config.public) { DIR = path.join(serverLibrary.__dirname, `${_public}/tmp`); filepath = path.join(DIR, req.params.filename); if (fs.existsSync(filepath)) break; } } else { DIR = path.join(serverLibrary.__dirname, `${Yekonga.Config.public}/tmp`); filepath = path.join(DIR, req.params.filename); } if (filepath && fs.existsSync(filepath)) { res.download(filepath, title); setTimeout(function() { try { fs.unlinkSync(filepath); } catch (error) { console.error(error); } }, 15000); } else { res.status(404).send('File not exists'); } }); app.all('/health', function(req, res) { // console.log(req.Yekonga.Client) return res.json({status:"OK"}) }); app.all('/excel-to-csv', async function(req, res) { var data = ''; try { var uploadedFile = req.body.excel || req.body.file || req.body.base64; data = await Yekonga.Helper.excelToCsv(uploadedFile); } catch (error) { console.log(error); } return res.json({ csv: data, }) }); module.exports = function() { // @ts-ignore // @ts-ignore app.all('/languages', async function(req, res) { var data = []; try { if (Yekonga.Model.TranslatorLanguage) { data = await Yekonga.Model.TranslatorLanguage.find({}, { select: ['translatorLanguageId', 'locale', 'name', 'flag'] }, true); } else { console.warn(`'Yekonga.Model.TranslatorLanguage' not found`) } } catch (error) { console.error(error) } var javascript = `window['systemLangueges'] = ${JSON.stringify(data)}`; return res.send(javascript); }); app.all('/translations/:locale?', async function(req, res) { const { params } = req; try { var data = []; // @ts-ignore if (params.locale) { if (Yekonga.Model.TranslatorTranslation) { // @ts-ignore data = await Yekonga.Model.TranslatorTranslation.find({ locale: params.locale }, {}, true); } else { console.warn(`'Yekonga.Model.TranslatorTranslation' not found`) } return res.json(data); } else { if (Yekonga.Model.TranslatorTranslation) { data = await Yekonga.Model.TranslatorTranslation.find({ locale: 'en' }, {}, true); } else { console.warn(`'Yekonga.Model.TranslatorTranslation' not found`) } var javascript = `window['systemDefaultLanguege'] = ${JSON.stringify(data)}`; return res.send(javascript); } } catch (error) { console.error('Error', error) } return res.json([]); }); // @ts-ignore // @ts-ignore app.all('/permissions', function(req, res) { const Auth = Yekonga.Auth; let data = []; if (Auth) { data = Auth.Permissions; } else { return res.json({ error: 'You must login first' }) } return res.json(data); }); var cacheTime = `${1000*60*60*24*365}`; if (Yekonga.Config.public) { if (Array.isArray(Yekonga.Config.public)) { for (const publicPath of Yekonga.Config.public) { app.use(express.static(path.join(serverLibrary.__dirname, publicPath), { maxAge: cacheTime // uses milliseconds per docs })); } } else { app.use(express.static(path.join(serverLibrary.__dirname, Yekonga.Config.public), { maxAge: cacheTime // uses milliseconds per docs })); } } app.use(express.static(path.join(__dirname, '../..', 'public/frontend/application'), { maxAge: cacheTime // uses milliseconds per docs })); if (Yekonga.Config.apiPlaygroundEnable) { setPlaygroundRoute(false); } if (Yekonga.Config.authPlaygroundEnable) { setPlaygroundRoute(true) } if (Yekonga.Config.apiPlaygroundEnable || Yekonga.Config.authPlaygroundEnable) { playgroundRoute.use(express.static(playgroundPath)); app.use('/playground', playgroundRoute); } if (!(Yekonga.Config.restAuthApi === false)) { var route = Yekonga.Config.restAuthApi || '/api/auth'; app.use(`${route}/:method/:uuid?`, async function(req, res) { var data = await (new ControllerAuthResolver(req, res)).execute(); return res.json(data); }); } if (!(Yekonga.Config.restApi === false)) { var route = Yekonga.Config.restApi || '/api'; app.use(`${route}/:class/:method?/:uuid?`, async function(req, res) { var data = await (new ControllerResolver(req, res)).execute(); return res.json(data); }); } if (!(Yekonga.Config.graphql && Yekonga.Config.graphql.apiAuthRoute === false)) { Yekonga.Graphql.authRoute(app); } // Middleware.authorization(app); if (!(Yekonga.Config.graphql && Yekonga.Config.graphql.apiRoute === false)) { Yekonga.Graphql.apiRoute(app); } if (Yekonga.Config.enableDashboard) { var dashboardRoute = Yekonga.Config.dashboardRoute || '/yekonga'; try { // const DashboardModule = require('yekonga-admin'); // // @ts-ignore // app.use(dashboardRoute, DashboardModule) } catch (error) { console.error(error.message); console.error('yekonga-admin module is not installed'); } } return app; }