How to pull data from the Directus database to the site? - javascript

I created a database in Directus. I created a separate project for the site, where I will add data. Installed # directus / sdk.
image
But when importing, I get an error
Uncaught SyntaxError: Cannot use import statement outside a module
this is my code
import { Directus } from '#directus/sdk';
const directus = new Directus('https://api.example.com/');
await directus.auth.login({
email: 'admin#example.com',
password: 'pass',
});
const articles = await directus.items('articles').readMany();
console.log({
items: articles.data,
total: articles.meta.total_count,
});
How do I fix this error?
Is it correct to create a separate project for the site? Or could it be done in the same place as the database?

TLDR; The issue faced is does not appear to be an issue with Directus.
There are three different pieces of software/code that that you should be aware of.
Database.
Directus Install.
Your App.
These are three different things, make sure you're clear on the difference. The database will be stored in your database of choice, MySQL, Postgres etc... Directus only connects to this and it will remain should you decide to stop using Directus for any reason.
You will need to install Directus in one location. You will then need to write your application in another location, where you may use the SDK for easy Directus API usage within your app.
It is correct (as you asked) to have your application as a separate "project".
The reason you are getting the error Cannot use import statement outside a module is not related to Directus. This is a common error when you are building or compiling your application incorrectly (Not ES6) therefore I cannot provide much support to you.
Here are some helpful debugging resources:
https://www.google.com/search?q=cannot+use+import+statement+outside+a+module
"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6
https://exerror.com/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-importing-ecmascript-6/

Related

How can I reference data from MariaDB on web browser JS application?

I am trying to create a webpage that uses data from a MariaDB. My current idea (which has been giving me a lot of trouble) is to just connect to the database from the app.js file, which is the main script for my index.html.
const dotenv = require("dotenv");
dotenv.config();
const mariadb = require("mariadb");
const pool = mariadb.createPool({
database: process.env.DATABASE,
host: process.env.HOST,
user: process.env.USER_TOKEN,
password: process.env.PASSWORD,
});
// the rest of the code involves selecting from the db, and parsing the data
However, I have been running into many issues. I'm not too knowledgeable on all this, but I found that I need to webpack the file if I want to be able to use the "require" keyword. But I could not figure that out as I kept running into weird issues when using Browserify; I think there may be an incompatibility with MariaDB. I also looked into using JS modules, but I am not sure if that is possible with MariaDB.
I am trying to come up with another solution, potentially using some sort of API to a back end, which would make the GET request to the database, but I feel like it should not have to be that complicated for my sake (I also wouldn't really know where to start with this). All I basically want to do, is make a GET request to a MariaDB when the page loads on the client's browser and display that data on the webpage. Is there a simple way to do this?
I suggest you use nodejs to connect and query database as it will greatly resolve a lot of overhead for you..
The easiest way i can think of is using a prisma starter template here
https://github.com/prisma/prisma-examples/tree/latest/javascript/script
It also gives the added advantage of the ORM function...
Hope it helps.

How to secure API Keys in Environment Variables in a Vue CLI 4 and Electron project

I'm trying to develop a desktop app which would need to make a few private API calls, authenticated using some secret keys.
The keys are created for me by external IT service providers outside of my organisation - they are responsible for the security so there are a few constraints:
They said even though they have already taken steps on their end to secure the API and there are mitigation strategies in place even if a breach happens, but still they would like to make sure that I treat the keys with a security-conscious mindset and take whatever steps possible on my end as well to make sure they remain secured.
I'm not allowed to just create random middleware / gateway on a private server or serverless platform to perform the API calls on my app's behalf as these calls may contain business data.
I have done some research and from what I can find, the general recommendation is to set up a ".env" file in the project folder and use environment variables in that file to store the API keys.
But upon reading the Vue CLI documentation I found the following:
WARNING
Do not store any secrets (such as private API keys) in your app!
Environment variables are embedded into the build, meaning anyone can
view them by inspecting your app's files.
So, given the constraints, is there a way to store these keys securely in a Vue CLI 4 + Electron Desktop app project?
Thanks.
In general, especially if you have a lot of environment variables, it would be better practice to store environment variables in a dot env file (.env), however, it's possible that this file could be leaked when you package your electron app. So, in this case it would be better to store your environment variables from the terminal/command line. To do so follow this guide (https://www.electronjs.org/docs/api/environment-variables).
Keep in mind anything that requires the API key/private information try to keep it on the backend, i.e., the electron process and send the results to the Vue front end.
Here's an example of how you could implement this:
On windows from CMD:
set SOME_SECRET="a cool secret"
On POSIX:
$ export SOME_SECRET="a cool secret"
Main process:
// Other electron logic
const { ipcMain } = require("electron");
// Listen for an event sent from the client to do something with the secret
ipcMain.on("doSomethingOnTheBackend", (event, data) => {
API.post("https://example.com/some/api/endpoint", {token: process.env.SOME_SECRET, data});
});
Client side:
const { ipcRenderer } = require("electron");
ipcRenderer.send("doSomethingOnTheBackend", {username: "test", password: "some password"});
Also note, to use the ipcRenderer on the client side nodeIntegration needs to be enabled.
Here are some more resources to help you get started:
https://www.electronjs.org/docs/api/ipc-renderer
https://www.electronjs.org/docs/api/ipc-main

Firebase deploy: Missing expected firebase config value databaseURL

I'm trying to deploy my first function with firebase cloud functions.
I deployed the standard function "helloWorld" without problem, but then, when I added this:
const admin = require("firebase-admin");
admin.initializeApp();
firebase deploy didn't work anymore and caused this error:
Missing expected firebase config value databaseURL, config is actually{"projectId":"PROJECT-ID","storageBucket":"PROJECT-ID.appspot.com","locationId":"europe-west"}
If you are unit testing, please set process.env.FIREBASE_CONFIG
How can I set config or the value of databaseURL? I don't find anywhere the file where these things are written... I also looked in documentation but I didn't find anything useful
I tried also with
admin.initializeApp(process.env.FIREBASE_CONFIG);
but this give me this error:
Error: Error occurred while parsing your function triggers.
Error: Invalid Firebase app options passed as the first argument to initializeApp() for the app named "[DEFAULT]". Options must be a non-null object.
It looks like you're being affected by a change that was made a few months ago where the databaseURL is no longer auto-created when you create a new project.
If that is the case, you you can force the databaseURL to be generated by going to the Realtime Database panel in the Firebase console. If this indeed fixes the problem, it might be worth filing a bug report with the Firebase support team.
It looks like you don't have a default database created. Visit your firebase console and create at least one real-time database.
You can explicit select a database instance with functions.database.instance() View Docs

How to prevent firebase db access from chrome console or other methods

So I have a single page frontend only app. Right now I have something like this
// db.js
import firebase from "firebase/app"
import "firebase/firestore";
var firebaseConfig = {
...
};
export const db = firebase
.initializeApp(firebaseConfig)
.firestore();
in main.js I was experimenting with putting the db instance in the global window scope just to see if I could go to the chrome web console and access it to submit a doc and indeed I can
// main.js
import { db } from './db'
window.db = db;
and then from chrome console
db.collection("test").add({'somekey': 'Can I add this doc?'})
How do I prevent someone from doing this without having a real backend to check auth? I like the reactivity of vue + firebase. If I don't expose the db variable to global scope is that enough? I was reading this post:
https://forum.vuejs.org/t/how-to-access-vue-from-chrome-console/3606/2
because any variable you create inside your main.js fiel will still not be globally available due to how webpack
One of the great things about Firestore is that you can access it directly from within your web page. That means that within that web page, you must have all configuration data to find the relevant Google servers, and find your Firebase project on those servers. In your example, that data is part of firebaseConfig.
Since you app needs this configuration, any malicious user can also get this data from your app. There is no way to hide this: if you app needs, a sufficiently motivated malicious user will be able to find it. And once someone has the configuration, they can use it to access your database.
The way to control access to the database, is by using Firebase's server-side security rules. Since these are enforced on the server, there is no way to bypass them, neither by your code, nor by the code that a malicious user writes.
You can use these security rules to ensure that all data is valid, for example making sure that all the required fields are there, and that there's no data that your app doesn't use.
But the common approach is to also ensure that all data access is authorized. This requires that your users are authenticated with Firebase Authentication. You can either require your users to sign in with their credentials, or you can anonymously sign them in. In the latter case they don't need to enter any credentials, but you can still ensure for example that each user can only write data to their own area of the data, and that they can only read their own data.

How to parse error with Square Connect API example (Node)

I am trying to learn how to process payments with Square, and am trying to run their examples from GitHub to get a feel regarding how to structure the payments application. I built the node example from here: https://github.com/square/connect-api-examples/tree/master/connect-examples/v2/node_payment using npm install and npm build to get the app up and running.
I am using "4532759734545858" for the card number, "123" for CVV, "0120" for expiration, and "94103" for the zip. I got the card number from here: https://docs.connect.squareup.com/articles/using-sandbox where it states that this is a good number to use for a Visa sandbox.
Also, I have updated the config.json with properties from my developer settings.
When trying to process a payment a get a DOM element that says "Card Declined" without further specifying the error. Is there something I can do to parse the error?
Based on the documentation at: https://docs.connect.squareup.com/articles/using-sandbox#generatingerrorstates it seems the amount_money field of the request is not being populated, but I am having trouble confirming.
Ideally I would like to get to a point where I can add a card as a hash value to my db and use it for recurring billing...
That "card declined" message is actually the error you get back from Square's APIs. You can play around with the error messaging in the app.js file and the `error.jade. Try error.catagory, code, detail.
Keep in mind that this is just a sample app, to show that you can use the APIs with node.js, you probably don't want to use this code in your production system.

Categories

Resources