Sequelize Authentication cannot complete - javascript

I'm starting out with node.js and sequelize and I get the following error:
/home/cbaket/test/test.js:9
.complete(function(err) {
^
TypeError: undefined is not a function
at Object.<anonymous> (/home/cbaket/test/test.js:9:6)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
My file: test.js is:
var Sequelize = require('sequelize');
var sequelize = new Sequelize('apidb', 'apidb', 'apidb', {
dialect: "mysql", // or 'sqlite', mysql', 'mariadb'
port: 3306 // or 5432 (for postgres)
});
sequelize
.authenticate()
.complete(function(err) {
if (!!err) {
console.log('Unable to connect to the database:', err)
} else {
console.log('Connection has been established successfully.')
}
});
I'm following one of the early tutorials on the Sequelieze website.
I installed the latest sequelize and mysql with the following command.
$ npm install mysql
$ npm install sequelize
I have tried a lot of similar examples and always get the same error.
The libraries are working because other examples work fine, i could create tables in the database and get data from it but the authenticate function always fails.
Thanks! ;)

Authenticate returns a Promise in the later versions of sequelize:
https://github.com/sequelize/sequelize/blob/2.0/lib/sequelize.js#L939
Read the bluebird documentation here as it is quite useful:
https://github.com/petkaantonov/bluebird/blob/master/API.md
Something like this should work (make sure you check for connection errors...this is just a simple example):
var Sequelize = require('sequelize');
var sql = new Sequelize('DB', 'UNAME', 'PASS', {
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
var test = sql.authenticate()
.then(function () {
console.log("CONNECTED! ");
})
.catch(function (err) {
console.log("SOMETHING DONE GOOFED");
})
.done();

Hi sequelize changed their auth scheme in latest release.. Please revert back to older version and try it

you were right!! ;)
I just remove sequelize and then reinstall an old veriosn:
npm install sequelize#1.7.0
and it works!!
I didn't found any info about that... Shouldn't they warn users from deprecated or modified functions ?¿?...
THANKS!! ;)

I suspect you're looking for
Sequelize.authenticate().complete(...)
instead of
Sequelize.authenticate.complete(...)
Sequelize.authenticate is a function that returns a promise. It's not an object with a .complete() method. If you don't execute it, no promise will be returned. If no promise is returned, you can't run .complete() on the promise.
Hope this helps you out.
Here is some documentation on Promises from the Mozilla Development Network.

Uninstall the sequelize module which is installed in your system and install this version using
npm install sequelize#1.7.0
Check the models folder and make sure it contains proper files

Related

Firebase-Functions error after update. What can I do?

I updated my firebase-functions and now I get this error in the Firebase console. The code is still the same, but I get an error now:
/srv/node_modules/#google-cloud/firestore/build/src/collection-group.js:54
async *getPartitions(desiredPartitionCount) {
^
SyntaxError: Unexpected token *
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:617:28)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/srv/node_modules/#google-cloud/firestore/build/src/index.js:39:28)
This is my cloud function TypeScript source:
import * as functions from 'firebase-functions';
import admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
/********************************************************************/
exports.newChatMessage = functions.firestore
.document('/games/{gameId}/chat/{chatId}')
.onCreate((snap, context) => {
const createData = snap.data();
if(!createData) {
return false;
}
const chatMessage = createData.message;
if(!chatMessage) {
return false;
}
console.log('New Chat message in game: ', context.params.gameId);
const payload = {
notification: {
title: 'New chat message',
body: chatMessage,
icon: 'ic_notification'
}
}
return admin.firestore().collection(`/games/${context.params.gameId}/members`).where( 'notificationChat', '==', true ).get().then( members => {
members.forEach( member => {
if(member.id !== createData.user) {
return admin.firestore().doc(`/users/${member.id}`).get().then( memberdata => {
if( memberdata.get('firebaseToken') === '' ) {
return memberdata.data();
} else {
return admin.messaging().sendToDevice(memberdata.get('firebaseToken'), payload).catch( error => { console.log(error) });
}
}).catch( error => { console.log(error) });
} else {
return false;
}
})
}).catch( error => { console.log(error) });
});
What is this? In my functions there isn't any method named *getPartitions.
Downgrade firebase-admin and firebase-functions to version: "firebase-admin": "^8.10.0", "firebase-functions": "^3.6.1" and it will work.
Thanks to Marcel Hoekstra for posting this in the comments.
As Uzbekjon stated, you can get this error if running node v8 instead of v10. Some comments mentioned this was not the desired solution, because they didn't want to upgrade to Firebase's Blaze plan. Unfortunately, there's not going to be much of a choice in the matter soon.
If you go to your Firebase Functions in the console, you'll notice a warning that "Node V8 has been deprecated". As of Feb 15 2021 you will no longer be able to make changes to or deploy any functions using Node.js V8. As of March 15, 2021 you will no longer be able to use the functions at all. They will be completely blocked from execution.
Blog post Migrate your Firebase Cloud Functions to Node.js 10 was really good for explaining how to upgrade to v10. I follow the author's steps and redeployed - no error and no deprecation warning.
Required Updates
Check to make sure you have at least Node.js V10 installed globally on your machine node --version.
npm install -g firebase-tools#latest (you need at least version 8.1.0)
In your package.json file, make sure Node.js V10 is targeted like this:
"engines": {
"node": "10"
}
Check your Firebase environment variables. The source I linked to goes into further detail and links other explanation sources, but basically upgrading might mean default environment variable names have changed (I didn't have to change anything here).
Recommended
Make sure firebase-functions is at least version 3.7.0. I had to update this anyway to solve another error.
Optional, but still recommended
Update your compiler options in tsconfig.json. This will make it so unnecessary language versions are not transpiled.
"compilerOptions": {
"target": "es2018",
"lib": ["es2018"],
}
Test your code :)
Like I mentioned earlier, making this upgrade removed the error for me. Once I made a new deployment, all deprecation warnings were also removed from the Firebase Functions console.
You can also get this error if you are running Node.js v8. Upgrading to Node.js v10 resolves this error.
If you are managing your Node.js version using nvm, then run:
nvm install v10 --lts
I think it is a better solution than downgrading the firebase-admin library.

Unable to use express-unless to exempt a few routes from authentication

I am fairly new to js & nodejs. So, I tried to use express-jwt to authenticate most of my apis.
However, I want to exempt routes like /login and /register from authentication
Having gone through the documentation of express-jwt, I learnt that there is such a lib called express-unless
So, I mimicked the example to see if I can get it working. Here's code
const unless = require('express-unless');
app
.use(authenticateWithExpressJWT)
.unless({ path: ['/login'] });
authenticateWithExpressJWT is my middleware function which works fine
const jwt = require('express-jwt');
const verifyJwt = jwt({ secret: 'secreyKey', algorithms: ['HS256'] });
module.exports.authenticateWithExpressJWT = verifyJwt;
When I searched for examples on Google or Stackoverflow, it seems others don't seem to have any problem using similar code. However, when I do this, it doesn't even compile. I get this error
app.use(authenticateWithExpressJWT).unless({ path: ['/login'] });
^
TypeError: app.use(...).unless is not a function
at Object.<anonymous> (/home/xyz/programming/node/firstApp/index.js:27:37)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
Can somebody help me figure out what am I doing wrong ?
I have another question : How is that people are able to use unless() method without require('express-unless');?
I get the above mentioned compilation error irrespective of whether I add const unless = require('express-unless'); or not
Note: I understand that I can achieve the same without using express-unless. I am only keen to understand how I can use it.
I personally haven't worked with express-unless, but according to the docs, you should be able to do this, since express-jwt itself supports unless:
const jwt = require('express-jwt');
const verifyJwt = jwt({ secret: 'secreyKey', algorithms: ['HS256'] })
.unless({path: ['/login'] });
module.exports.authenticateWithExpressJWT = verifyJwt;
In your app then just use your middleware:
app.use(authenticateWithExpressJWT)
I normally exempt routes from auth by creating a function like as shown below.
function authJwt() {
return expressjwt({
'secret',
algorithms: ['HS256'],
isRevoked: isRevoked,
}).unless({
path: ['/login'],
});
}
async isRevoked(req, payload, done){
// your code goes here for revoking
}
and then in your entry point (index.js/app.js), import the authJwt and use it in your entire app.
app.use(authJwt())
I am also facing the same issue in think there is a issue with the latest version
so I use the "express-unless": "^1.0.0" .
it works well for me .
use this version of the package i think its quick fix for this issue
"express-unless":"^1.0.0"

Plain text SASL authentication in gremlin-javascript

I'm trying to connect to a Gremlin server with the JavaScript driver variant.
Up to package version 2.7.0, this is done easily by passing options to Gremlin.createClient() as in this example for Azure Cosmos DB:
const client = Gremlin.createClient(
config.port,
config.endpoint,
{
"session": false,
"ssl": true,
"user": `/dbs/${config.database}/colls/${config.collection}`,
"password": config.primaryKey
}
);
In newer versions of the package I can't get it done. The official docs suggest using gremlin.driver.auth.PlainTextSaslAuthenticator. However, that method seems to be not implemented in the package and returns TypeError: Cannot read property 'PlainTextSaslAuthenticator' of undefined
My test code (same config.js as in the working example):
const gremlin = require("gremlin");
const config = require("./config");
const Graph = gremlin.structure.Graph;
const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection;
const graph = new Graph();
const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator(
`/dbs/${config.database}/colls/${config.collection}`,
config.primaryKey
);
const g = graph.traversal().withRemote(new DriverRemoteConnection(`ws://${config.endpoint}:${config.port}`, { authenticator });
Return:
C:\repos\gremlin-test\index.js:9
const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator(
^
TypeError: Cannot read property 'PlainTextSaslAuthenticator' of undefined
at Object.<anonymous> (C:\repos\gremlin-test\index.js:9:47)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:612:3
Anyone know a solution to this?
I've not got too much experience with Gremlin.js, but I just downloaded it and have manually searched through all of its files - I can't find any trace of a PlainTextSaslAuthenticator function or its declaration.
This could mean one of two three -
Its function has been (accidentally) removed
It uses a third party package that has been (accidentally) removed
It has not been added to the package yet
Upon a swift Google search, I found this link which seems to show it being added to /lib/driver/auth, but that directory doesn't seem to exist in the package I got through npm install gremlin. Perhaps it is yet to be released?
I would therefore suggest you raise an issue on Github, but it seems that repository you linked doesn't allow for issues to be raised. So perhaps email/contact the author?
EDIT:
Thanks to Stephen for the link - the code hasn't been merged to the package yet. Keep track of it here.

cannot find module at function_module 469:15

I am learning nodejs from Courseera and wanted to run a code from command prompt in windows 10.But this error Cannot find module always occurs.Iam completely at aloss what this means.
I have tried all the methods given in the other stack overflow threads but couldn't solve the issue.
node and npm are correctly installed with versions v6.9.2 and 3.10.9 respectively.
D:\shaury\node-http\public>node -v
v6.9.2
D:\shaury\node-http\public>npm -v
3.10.9
This is the problem which is occcuring:
D:\shaury\node-http\public>node serve
module.js:471
throw err;
^
Error: Cannot find module 'D:\shaury\node-http\public\serve'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
There's a typo in your code.
var http = require('http');
var hostname = 'localhost';
var port = 3000;
var server = http.createServer(function(req, res){
console.log(req.headers);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<html><body><h1>Hello World</h1></body></html>');
});
//here you should surround your string in 'quotation marks' but make sure to use `backticks`
server.listen(port, hostname, function(){
console.log(`Server running at http://${hostname}:${port}/`);
});
Edit: actually you might need to check that you are in the correct directory. When you launch your app it should be from the directory that your .js file is or else supply the path.

'TypeError: undefined is not a function' error when using 'flickrnode' API

I'm new to Node.js and I'm trying to get a Flickr API working on my local machine:
https://github.com/ciaranj/flickrnode
I have installed the flickr module with npm install flickr.
The simplest call is:
var FlickrAPI= require('flickr').FlickrAPI;
var sys= require('sys');
var flickr= new FlickrAPI(your_api_key_here);
// Search for photos with a tag of 'badgers'
flickr.photos.search({tags:'badgers'}, function(error, results) {
sys.puts(sys.inspect(results));
});
I've changed 'sys' to 'util' as node prompted me to and added my api key so I'm calling:
var FlickrAPI= require('flickr').FlickrAPI;
var sys= require('util');
var flickr= new FlickrAPI('...');
// Search for photos with a tag of 'badgers'
flickr.photos.search({tags:'badgers'}, function(error, results) {
sys.puts(sys.inspect(results));
});
Running node myfile.js, I get:
var flickr= new FlickrAPI('a513719086ba8c3a28d2c7726939b58e');
^
TypeError: undefined is not a function
at Object.<anonymous> (/home/charm/ciaranj-flickrnode-8a9d85f/lib/simple.js:3:13)
at Module._compile (module.js:446:26)
at Object..js (module.js:464:10)
at Module.load (module.js:353:31)
at Function._load (module.js:311:12)
at Array.0 (module.js:484:10)
at EventEmitter._tickCallback (node.js:190:38)
Does anyone know how I overcome this problem?
Thanks!
npm install flickr installs https://github.com/sujal/node-flickr, not the one you're looking for. How to install a node.js module without using npm? explains how to install node packages manually

Categories