How to connect to Realm from aws lambda node - node.js

I am trying to connect to a Realm instance from an aws lambda (node) with the following code:
await Realm.Sync.User.login('https://server.realm.io', 'username', 'password')
.then((user) => {
let config = user.createConfiguration();
config.schema = [Schema];
Realm.open(config).then((realm) => {
//Do some cool stuff });
The problem is it tries to create a directory realm-object-server when it logins. As we know the lambdas file system is read-only except for the tmp folder. Is there a way to tell realm to write this realm-object-server to the tmp folder or is there a way to login that doenst create a direcotry at all?
Thanks in advance for the help

I ran into the same issue using Realm from a Google Cloud Function. None of the Realm configuration options like path or inMemory seemed to have any effect. After much digging, the solution I found was to call process.chdir('/tmp') prior to opening the Realm. This changes the current NodeJS process's working directory as explained in the NodeJS documentation. This allowed me to open the realm successfully.

Related

GCloud Vision API Permission Denied on Second Request

I've gone through all the setup steps to make calls to the Google Vision API from a Node.js App. Link to the guide: https://cloud.google.com/vision/docs/libraries#setting_up_authentication
I'm using the ImageAnnotatorClient from the #google-cloud/vision package to make some text detections.
At first, it looked like everything was set up correctly but I don't know why it only allows me to do one request.
Further requests will give me the following error:
Error: 7 PERMISSION_DENIED: Your application has authenticated using end user credentials from the Google Cloud SDK or Google Cloud Shell which are not supported by the vision.googleapis.com. We recommend configuring the billing/quota_project setting in gcloud or using a service account through the auth/impersonate_service_account setting. For more information about service accounts and how to use them in your application, see https://cloud.google.com/docs/authentication/
If I restart the Node app it again allows me to do one request to the Vision API but then the subsequent requests keep failing.
Here's my code which is almost the same as in the examples:
const vision = require('#google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
const detectText = async (imgPath) => {
// console.log(imgPath);
const [result] = await client.textDetection(imgPath);
const detections = result.textAnnotations;
return detections;
}
It is worth to mention that this works every time when I run the Node app in my local machine. The problem is happening on my Ubuntu Droplet from Digital Ocean.
Again, I set everything up as it is in the guides. Created a Service Account, downloaded the Service Account Key JSON file, set up the environment variable like this:
export GOOGLE_APPLICATION_CREDENTIALS="PATH-TO-JSON-FILE"
I'm also setting the environment variable in the .bashrc file.
What could I be missing? Before setting up everything from scratch and go through the whole process again I thought it would be good to ask for some help.
So I found the problem. In my case, it was a problem with PM2 not passing the system env variables to the Node app.
So I had everything set up correctly auth-wise but the Node app wasn't seeing the GOOGLE_APPLICATION_CREDENTIALS env var.
I deleted the PM2 process, created a new one and now it works.

Does NodeJs needs public file permissons to access file?

I tried accessing data with FileZilla and additionally downloading it. This worked. However, now I tried accessing the same file with the same user with nodeJS with "GET". Here I get the Error "Access Denied".
I looked into the permissions, and the owner and group of the file are able to read and write the file, but no public permissions. My user is part of the "Group". However, I am now wondering, if the file needs to have public permissions to read and write in order to access the file via nodeJs?
Quick Info: I access the file both with FileZilla and NodeJS via SFTP. All configs / user etc. are the same.
Code:
let Client = require('ssh2-sftp-client');
let sftp = new Client();
sftp.connect({
host: config.development.host,
port: config.development.port,
username: config.development.username,
password: config.development.password
}).then(() => {
return sftp.get(`${config.development.pathToFile}/${filename}`);
}).then(async (data) => {
console.log('data', data);
csv({
noheader: true,
output: "csv"
})
Thanks!
Does NodeJs needs public file permissons to access file?
As long as the user that spawned the Node.js process has read permissions for the specific file, you shouldn't encounter any problems.
I would suggest learning how multi-user environments & permissions management works.
Recommended reading :
Learning the shell - Lesson 9: Permissions
Linux Tutorial - 8. Understand Permissions
Recommended further reading :
The default Linux security model is a bit inflexible. To give special
access (such as modification privileges) to a group of people, you
have to get your system administrator to create a group with those
people in it. Furthermore, if you would like to give a different set
of access privileges (such as read access) to another group of people,
you can’t do it because you can only assign one group owner per file
or directory. To solve this problem, you can use ACLs (Access Control
Lists). You can learn more about them from this link: ACLs
(Quote extracted from here)
After all, it will come in handy and it wont take you much effort to understand.

How do you locate and delete the auth information that google saves to your disk file to connect to the api with a different email? NODE.JS on MAC OS

I ran a test run to learn how to connect to google calendar api via node.google auth with node js
I re-walked through the steps to attempt to connect my actual project to google calendar api, but when i run node quickstart.js i get this error:
The API returned an error: Error: unauthorized_client
after hours of deliberating I figured out that the Google client library was saving my auth info on my disk. So, when i ran node quickstart.js, I received an error because my new client_secret.json that I created for my actual project, did not match the info in my client_secret.json that was created in my test run.
A doc suggestion that I found that i think is relevant:
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-nodejs-quickstart.json
but when I navigate to my user folder I do not have a .credentials directory, thus I'm unable to locate and delete my old auth info.
I tried searching for oauth via global search and found a few oauth.js files that I thought were the issue. I naively deleted all of them and then re ran the command only to find the terminal yell at me for not having an oauth node module.
After more hours of replacing the oauth files I deleted I'm still unable to locate or delete the troublesome auth info.
Has anyone encountered a similar problem while programming on a mac and connecting to Google API thru node?
Assuming your code is following the quick start. You can find the credeitlals for the user
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/';
If you change it to (or the equivalent to a mac directory structure not mac person sorry)
var TOKEN_DIR = c:\currentdir\credentials;
It should request access again and store the new credentials file there
Note:
It looks like the way the code works they are expecting you to have the .json file in that directory. So remember to put it in what ever directory you have TOKEN_DIR set to.
var TOKEN_PATH = TOKEN_DIR + 'calendar-nodejs-quickstart.json';
The problem I had was finding that credentials directory. I learned that it was a hidden folder and learned how to show / hide hidden folders. For any future problem havers the answer is to navigate to /Users/YOURUSERPROFILE in finder and pressing: CMD + SHIFT + . to show the hidden credential folder

Electron Node.js node localstorage osx mkdir permission denied

I am working with Electron and Node.js. We have developed an application that works fine on windows and as a requirement had to package it for mac os. I packaged the application using electron-packager, the packaging process completes and package is generated. Double clicking it throws an error that permission denied for mkdir, as i am using node localstorage to maintain some settings on the user's local machine. somehow mac doesn't local storage to create folder in the root of the application. Any help in this matter will be great. Thanks
First off, is the code in question in the main process or in a renderer process? If it is the latter, you don't need to use 'node-localstorage', because you can use the renderer's native LocalStorage. If you are in the main process, then you need to provide your own storage strategy so using 'node-localstorage' is a viable option.
In any case, you need to carefully consider where to store the data; for starters, let's look at where Electron's renderer processes would store its LocalStorage data: this differs based on the OS, but you can get and set the paths using the app module -- the path in question is userData, which on OS X would default to ~/Library/Application Support/<App Name>. Electron uses that folder to persist cookies, caches, LocalStorage etc. so I would suggest using that folder as well. (Otherwise, refer to XDG defaults for good defaults)
What your example above was trying to do is store your 'errorLogDb' in the current working directory, which might depend on your OS, where your App is installed, how you executed it, etc.
Finally, it's a good idea to differentiate between your 'production' app and your app during development and testing, because you might not want to use the same storage folders for every environment. In any case, just writing to './errorLogDb' is likely to cause lots of headaches so I'd be thankful for the permission denied error.
this strategy worked for me:
const { LocalStorage } = require('node-localstorage');
let ls;
mb.on('ready', () => {
let prefsPath = mb.app.getPath('userData') + '/prefs';
ls = new LocalStorage(prefsPath);
loadPrefs();
});
mb.on('after-create-window', () => { /* ls... */ }
exports.togglePref = () => { /* ls... */ }

ldap nodejs active directory authentication

I am currently working on a web application in node.js in which a user needs to log in to access the information. I want to check the user login and password with an external active directory server. I have tried using node-ldapauth, but I can't get it work (I don't know if it works for active directories, maybe just openLdap). Any suggestions?
I used an rubyldap library to solve the problem thanks!
Update: As requested this is the library I used to solve the problem https://github.com/ruby-ldap/ruby-net-ldap/
After installing the ruby library on your server, using gem install (look it up it's not too hard)
require 'rubygems'
require 'net/ldap'
ldap = Net::LDAP.new :host => server_ip_address,
:port => 389,
:auth => {
:method => :simple,
:username => "cn=manager, dc=example, dc=com",
:password => "opensesame"
}
filter = Net::LDAP::Filter.eq("cn", "George*")
treebase = "dc=example, dc=com"
ldap.search(:base => treebase, :filter => filter) do |entry|
puts "DN: #{entry.dn}"
entry.each do |attribute, values|
puts " #{attribute}:"
values.each do |value|
puts " --->#{value}"
end
end
end
p ldap.get_operation_result
Set up a ruby file as shown above.
You can run the ruby library by using
var ldap = 'ruby '+process.cwd()+'/src/ruby/ruby_file_name '+ user+' '+password;
To grab the user and password in ruby use ARGV[0] and ARGV1.
You can grab the ruby returned result in node.js by using a call back function
var result = exec(ldap, theCallBack);
in the theCallBack function you can grab the returned ruby library results by passing in stdout
ex:
function theCallBack(err,stdout) {
----your code here, stdout is what you PUT in the ruby library.
Hope this helps!
Could you post the snipet of your code and the error you get?
I am trying to do the similar and came across the ldapjs library. It allows you to implement a client ldap connection to an LDAP server and you can, in doing the connection validate the users username and password.
I tried setting it up on windows with 0.8.2 and ran in to some issues, which it sounds like the developer is looking in to. The nice aspect of this library is it doesn't rely on the OpenLDAP binding that the one you referenced does.
For having ldapjs installation working on Windows, I wrote the steps I followed here http://tochedev.blogspot.be/2012/07/i-wanted-to-add-ldapjs-to-my-windows.html
Hope this helps.

Resources