admin firebase auth and node js - node.js

I'm working on android app and I use node js back end and Firebase platform for my app, I manage users with firebase-auth, and the problem is when I register a new user to firebase-auth using node js I see this error.
This is the source code.
function registerUser(socket,io){
​// retrieve data from android app
socket.on('userData',(data)=>{
console.log(data.email);
console.log(data.userName);
console.log(data.password);
​
​// register new user using data.
admin.auth().createUser({
email: data.email,
password: data.password,
displayName: data.userName,
})
.then(function(userRecord) {
// See the UserRecord reference doc for the contents of userRecord.
console.log("Successfully created new user:", userRecord.uid);
const db = admin.database();
const ref = db.ref('users/');
const userid = ref.child(encodeEmail(data.email));
userid.set({
username: data.userName,
email: data.email,
password:data.password
}).then((error)=>{
console.log('successfully write in database real time ');
});
})
.catch(function(error) {
console.log("Error creating new user:", error);
});
});
}
and this is the error:
Error creating new user: { Error: www.googleapis.com network timeout. Please try again.
at FirebaseAppError.FirebaseError [as constructor] (/node_modules/firebase-admin/lib/utils/error.js:39:28)
at new FirebaseAppError (/firebase-admin/lib/utils/error.js:84:23)
at TLSSocket.<anonymous> (friend-chat-server/node_modules/firebase-admin/lib/utils/api-request.js:121:51)
at emitNone (events.js:105:13)
at TLSSocket.emit (events.js:207:7)
at TLSSocket.Socket._onTimeout (net.js:398:8)
at ontimeout (timers.js:469:11)
at tryOnTimeout (timers.js:304:5)
at Timer.listOnTimeout (timers.js:264:5)
errorInfo:
{ code: 'app/network-timeout',
message: 'www.googleapis.com network timeout. Please try again.' } }
firebase added to node js successfully everything good but i don't know how to fix this . help please!

Related

Error connecting to Atlas Free Cluster (MongoDB)

TL;DR: Can't connect to Atlas Cluster even after doing exactly what docs said.
Hi, so I read the docs of getting started with Atlas and everything seemed nice & easy. I did follow the steps, created a free cluster, whitelisted my IP, and then tried to connect using their sample app:
const { MongoClient } = require("mongodb");
// Replace the following with your Atlas connection string
const url = "mongodb+srv://<username>:<password>#clustername.mongodb.net/test?retryWrites=true&w=majority&useNewUrlParser=true&useUnifiedTopology=true";
const client = new MongoClient(url);
async function run() {
try {
await client.connect();
console.log("Connected correctly to server");
} catch (err) {
console.log(err.stack);
}
finally {
await client.close();
}
}
run().catch(console.dir);
But the following error occurred when I tried to execute with: node connect.js
PS C:\Users\marjo\Documents\mongoDB Atlas> node connect
(node:11352) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoNetworkError: failed to connect to server [remote-doc-shard-00-02-otc5a.mongodb.net:27017] on first connect [MongoError: bad auth Authentication failed.
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\auth_provider.js:46:25
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\scram.js:240:11
at _callback (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:349:5)
at Connection.messageHandler (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:378:5)
at Connection.emit (events.js:315:20)
at processMessage (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connection.js:384:10)
at TLSSocket.<anonymous> (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connection.js:553:15)
at TLSSocket.emit (events.js:315:20)
at addChunk (_stream_readable.js:297:12)
at readableAddChunk (_stream_readable.js:273:9) {
ok: 0,
code: 8000,
codeName: 'AtlasError'
}]
at Pool.<anonymous> (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\topologies\server.js:438:11)
at Pool.emit (events.js:315:20)
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\pool.js:561:14
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\pool.js:1008:9
at callback (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:97:5)
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:396:21
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\auth_provider.js:66:11
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\scram.js:240:11
at _callback (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:349:5)
at Connection.messageHandler (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:378:5)
I tried changing the connection string with the one from Atlas: (because it was different from the docs by a tiny bit)
const uri = "mongodb+srv://Marjo:<password>#remote-doc-otc5a.mongodb.net/<dbname>?retryWrites=true&w=majority";
But still the same result. My password had a !character so I put %21 instead of it. I also replaced with cluster name (Remote-Doc) and test but it still failed.
I'd appreciate if you could help me!
I think that you are having a problem with the parse of your password, maybe it has special characters.
The best way to handle this is to change the way that you are connecting to pass the user and password as options.
You can follow the doc and change your MongoClient conection for something like this:
const mongoclient = new MongoClient(new Server("remote-doc-otc5a.mongodb.net", 27017));
// Listen for when the mongoclient is connected
mongoclient.open(function (err, mongoclient) {
// Then select a database
const db = mongoclient.db("dbname");
// Then you can authorize your self
db.authenticate('username', 'password', (err, result) => {
// On authorized result=true
// Not authorized result=false
// If authorized you can use the database in the db variable
});
});
And with mongoose you can do something like this:
mongoose.connect('mongodb+srv://#remote-doc-otc5a.mongodb.net/test?retryWrites=true&w=majority', {
user: 'USERNAME',
pass: 'PASSWORD',
useNewUrlParser: true,
useUnifiedTopology: true
})
Also, check if you are not using the account password instead of the cluster/database password.
You can follow this tutorial to check if you are using the correct one: MongoDB Atlas Setup - Digital Ocean.
I just changed the Atlas password to a simple one with no special characters, and the connection worked! I feel ashamed now

how did this forked in the rest api route go wrong?

Update: This problem was solved. I followed the advice of the replies and tried the console.log(req.body) command. Turns out it was calling a different function. Now at the time I was using postman to test the API and I learned that editing an already saved function is not the same as with other text or media editors and you have to make a completely new function to test it. I.E. I used a previous post function to create user and changed some elements, turns out postman doesnt like that and just ran the old function.
Thanks for the help everyone
I made an admin route using an already working user route exactly except using fewer values.
I keep getting an undefined error during validation when ever I try to run a post function. what could have gone wrong here? Or where should I look for the error, I checked the spellings of each of the values Iam using in the create admin function but I see no spelling problems?
Error in Console:
Error: admin validation failed: AdminEMail: Path `AdminEMail` is required., AdminPassword: Path `AdminPassword` is required.
at ValidationError.inspect (D:\Downloads\Compressed\api-master_3\api-master\node_modules\mongoose\lib\error\validation.js:48:26)
at formatValue (internal/util/inspect.js:563:31)
at inspect (internal/util/inspect.js:221:10)
at formatWithOptions (internal/util/inspect.js:1693:40)
at Object.Console.<computed> (internal/console/constructor.js:272:10)
at Object.log (internal/console/constructor.js:282:61)
at D:\Downloads\Compressed\api-master_3\api-master\routes\Admin.js:25:21
at D:\Downloads\Compressed\api-master_3\api-master\node_modules\mongoose\lib\model.js:4876:16
at D:\Downloads\Compressed\api-master_3\api-master\node_modules\mongoose\lib\helpers\promiseOrCallback.js:16:11
at D:\Downloads\Compressed\api-master_3\api-master\node_modules\mongoose\lib\model.js:4899:21
at D:\Downloads\Compressed\api-master_3\api-master\node_modules\mongoose\lib\model.js:493:16
at D:\Downloads\Compressed\api-master_3\api-master\node_modules\kareem\index.js:246:48
at next (D:\Downloads\Compressed\api-master_3\api-master\node_modules\kareem\index.js:167:27)
at next (D:\Downloads\Compressed\api-master_3\api-master\node_modules\kareem\index.js:169:9)
at Kareem.execPost (D:\Downloads\Compressed\api-master_3\api-master\node_modules\kareem\index.js:217:3)
at _handleWrapError (D:\Downloads\Compressed\api-master_3\api-master\node_modules\kareem\index.js:245:21) {
errors: {
AdminEMail: ValidatorError: Path `AdminEMail` is required.
at validate (D:\Downloads\Compressed\api-master_3\api-master\node_modules\mongoose\lib\schematype.js:1178:13)
at D:\Downloads\Compressed\api-master_3\api-master\node_modules\mongoose\lib\schematype.js:1161:7
at Array.forEach (<anonymous>)
at SchemaString.SchemaType.doValidate (D:\Downloads\Compressed\api-master_3\api-master\node_modules\mongoose\lib\schematype.js:1106:14)
at D:\Downloads\Compressed\api-master_3\api-master\node_modules\mongoose\lib\document.js:2379:18
at processTicksAndRejections (internal/process/task_queues.js:76:11) {
properties: [Object],
kind: 'required',
path: 'AdminEMail',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
},
AdminPassword: ValidatorError: Path `AdminPassword` is required.
at validate (D:\Downloads\Compressed\api-master_3\api-master\node_modules\mongoose\lib\schematype.js:1178:13)
at D:\Downloads\Compressed\api-master_3\api-master\node_modules\mongoose\lib\schematype.js:1161:7
at Array.forEach (<anonymous>)
at SchemaString.SchemaType.doValidate (D:\Downloads\Compressed\api-master_3\api-master\node_modules\mongoose\lib\schematype.js:1106:14)
at D:\Downloads\Compressed\api-master_3\api-master\node_modules\mongoose\lib\document.js:2379:18
at processTicksAndRejections (internal/process/task_queues.js:76:11) {
properties: [Object],
kind: 'required',
path: 'AdminPassword',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'admin validation failed'
}
And Here is the route:
//Imported modules
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
//Imported models
const Admin = require('../models/admin');
//const User = require('../models/user');
router.get('/', (req,res) =>{
res.send("We are on Admin");
})
//Admin Functions
//Creation of new Admin
router.post("/signup", (req,res) => {
const admin = new Admin({
_id: new mongoose.Types.ObjectId(),
AdminEMail: req.body.AdminEMail,
AdminPassword: req.body.AdminPassword
});
admin.save(function(err,admin){
if(err){
console.log(err);
res.send(err);
return
}
console.log("New admin created");
res.send(admin);
})
})
//Admin Login and verification
router.post("/login", (req,res) => {
const AdminID = req.body.AdminID;
const Username = req.body.username;
const Password = req.body.password;
Admin.findOne({_id:AdminID}, function(err, foundAdmin){
if(err){
res.send("<h1>got clicked</h1>");
console.log(err);
}else{
if(foundAdmin){
if(foundAdmin.AdminEMail === Username){
if(foundAdmin.AdminPassword === Password){
res.send("logged in");
}
else{
res.send("Username and Password Mismatch");
}
}
else{
res.send("Username and ID Mismatch");
}
}
else{
res.send("No Such admin exists");
}
}
});
});
//
module.exports = router;

Getting "InternalServerError" while using Mongo with Node js

I am new to Node js programming. Trying to write a simple user create using.. code along with the stack track is given below. Appreciate any help as to what is causing this..
users-add.mjs:
'use strict';
const util = require('util');
const restify = require('restify-clients');
console.log("starting...");
var client = restify.createJsonClient({url: 'http://localhost:'+process.env.PORT, version: '*'});
console.log("starting...2 ");
client.basicAuth('them', 'D4ED43C0-8BD6-4FE2-B358-7C0E230D11EF');
client.post('/create-user', { username: "me", password: "w0rd", provider: "local",
familyName: "GUD", givenName: "RG", middleName: "Ud", emails: [], photos: []},
(err, req, res, obj) => {
console.log("starting...4 ");
if(err) {
console.log("starting...5");
console.error(err.stack);
}
else {
console.log("starting...6");
console.log('Created ' + util.inspect(obj));
}
});
console.log("starting...3 ");
Here is the error I'm getting.. Surprisingly the server side code is able to insert the record into MongoDB, and yet I get this error..
InternalServerError: {}
at Object.createHttpErr (/Users/raviguduru/node-web-dev/chapter8/users/node_modules/restify-clients/lib/helpers/errors.js:91:26)
at ClientRequest.onResponse (/Users/raviguduru/node-web-dev/chapter8/users/node_modules/restify-clients/lib/HttpClient.js:309:26)
at Object.onceWrapper (events.js:300:26)
at ClientRequest.emit (events.js:210:5)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:583:27)
at HTTPParser.parserOnHeadersComplete (_http_common.js:115:17)
at Socket.socketOnData (_http_client.js:456:22)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
Pls help.
This problem is solved now.. The internal server error comes when we have MongoDBClient calls not wrapped in try/catch blocks. After I included try/catch blocks, they went away.

node.js is not connecting to SQL Server database using SQL Server authentication

I'm using node.js and the mssql package to connect to a SQL Server database using SQL Server authentication. When I try connecting using SQL Server Management Studio with the same credentials, it is working fine. However, with node.js, I cannot login and get an error code ELOGIN with connection error.
I've tried many examples shown in google and I'm facing the same issue.
Let me know what I'm missing. Here is the code snippet of mine.
Code starts here
var sql = require('mssql');
var config = {
server: 'scaXXXXXXXXXXXX',
database: 'scaXXXXXXXXXX',
user: 'svcXXXXXXX',
password: 'Password',
port: 1433
};
function listProducts() {
var conn = new sql.ConnectionPool(config);
conn.connect().then(function () {
var request = new sql.Request(conn);
request.query("select top 1 * from dbo.Persons").then(function
(recordSet) {
console.log(recordSet);
conn.close();
}).catch(function (err) {
console.log(err);
conn.close();
});
}).catch(function (err) {
console.log(err);
});
}
listProducts();
This is the error while running this code:
ConnectionError: Login failed for user 'svcXXXXXXX'.
at Connection.tedious.once.err (C:\aws\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:189:13)
at Connection.processLogin7Response (C:\aws\node_modules\tedious\lib\connection.js:1397:14)
at Connection.message (C:\aws\node_modules\tedious\lib\connection.js:1932:14)
at Connection.dispatchEvent (C:\aws\node_modules\tedious\lib\connection.js:1084:36)
at MessageIO.messageIo.on (C:\aws\node_modules\tedious\lib\connection.js:984:14)
at MessageIO.emit (events.js:189:13)
at Message.message.on (C:\aws\node_modules\tedious\lib\message-io.js:32:14)
at Message.emit (events.js:194:15)
code: 'ELOGIN',
originalError: { ConnectionError: Login failed for user 'svcXXXXXXX'.
at ConnectionError (C:\aws\node_modules\tedious\lib\errors.js:13:12)
at Parser.tokenStreamParser.on.token (C:\aws\node_modules\tedious\lib\connection.js:735:29)
at Parser.emit (events.js:189:13)
at Parser.parser.on.token (C:\aws\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
at Parser.emit (events.js:189:13)
at addChunk (C:\aws\node_modules\readable-stream\lib_stream_readable.js:297:12)
at readableAddChunk (C:\aws\node_modules\readable-stream\lib_stream_readable.js:279:11)
at Parser.Readable.push (C:\aws\node_modules\readable-stream\lib_stream_readable.js:240:10)
at Parser.Transform.push (C:\aws\node_modules\readable-stream\lib_stream_transform.js:139:32)
at doneParsing (C:\aws\node_modules\tedious\lib\token\stream-parser.js:80:14)
message: 'Login failed for user \'svcXXXXXXX\'.',
code: 'ELOGIN' }, name: 'ConnectionError' }
I expect one record from database should extract and display.
it looks your login information is not correct.
did you write proper user name and password?
if your login info is correct, then check out login info has authority to be connected from the external environment
Try this out. It worked for me. If you are not doing with a localhost Database you need to be in that network. Make sure you can ping the database server.
var sql = require("mssql");
var moment = require("moment");
let port = process.env.PORT;
if (port == null || port == "") {
port = 8000;
}
var config = {
user: "xxxx",
password: "xxxxx",
server: "xxxxxx",
database: "xxxx"
};
const dbconn = sql.connect(config, err => {
if (!err) {
console.log("Connected to the database");
} else {
console.log("Problem in connecting to database");
console.log(err);
console.log("testing ");
}
});
app.get("/getSummaryDetails", (req, res) => {
dbconn.query("exec QCGrid", (err, rows, fields) => {
if (!err) {
res.send(rows.recordsets[0]);
}
});
});

Unable to connect to Microsoft SQL Server using Node.js,mssql and express

I am trying to learn Node.js and created a simple project to query the local database. But I get failed to look up an instance error message.
I have checked that the SQL Server services running in services.msc
I have verified TCP/IP is enabled
I have tried with the username and password and without it as well. I connect to localdb in SQL Server Management Studio as (localdb)\v11.0 and below is the screenshot of the properties
What am I doing incorrectly? What should be actual username and password? What should be the servername?
const sql = require('mssql');
// config for your database
const config = {
user: 'mywindows username',
password: 'my windows password',
server: '(localdb)\\v11.0',
database: 'test',
options: {
encrypt: true
}
};
console.log('starting sql');
var connection = new sql.connect(config, function(err) {
console.log(err);
var request = new sql.Request(connection);
request.query('select * from employees', function(err, recordset) {
if(err) // ... error checks
console.log('Database connection error');
console.dir("User Data: "+recordset);
});
});
sql.close();
console.log('ending sql');
});
app.listen(3002, () => {
console.log('Listening on port 3002');})
Below is the error message
{ ConnectionError: Failed to lookup instance on (localdb) -
getaddrinfo ENOTFOUND (localdb)
at Connection.tedious.once.err (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:285:13)
at Connection.emit (events.js:197:13)
at InstanceLookup.instanceLookup (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\connection.js:945:16)
at sender.execute (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\instance-lookup.js:66:13)
at GetAddrInfoReqWrap.invokeLookupAll [as callback] (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\sender.js:43:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:70:17) code: 'EINSTLOOKUP', originalError: { ConnectionError: Failed to
lookup instance on (localdb) - getaddrinfo ENOTFOUND (localdb)
at ConnectionError (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\errors.js:13:12)
at InstanceLookup.instanceLookup (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\connection.js:945:32)
at sender.execute (C:\Users\vndbsubramaniam\Desktop\React projects\ReactWithSql\node_modules\tedious\lib\instance-lookup.js:66:13)
at GetAddrInfoReqWrap.invokeLookupAll [as callback] (C:\Users\vndbsubramaniam\Desktop\React
projects\ReactWithSql\node_modules\tedious\lib\sender.js:43:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:70:17)
message:
'Failed to lookup instance on (localdb) - getaddrinfo ENOTFOUND (localdb)',
code: 'EINSTLOOKUP' }, name: 'ConnectionError' } Database connection error
After struggling for hours on this one finally found the answer here SQL to Node connection
It seems i have to add msnodesqlv8 package and use add the driver syntax to the config.
app.get('/test', (req, res) => {
const sql = require('mssql/msnodesqlv8');
// config for your database
const config = {
database: 'test',
server: '(localdb)\\v11.0',
driver: 'msnodesqlv8',
options : {
trustedConnection : true
}
};
console.log('starting sql');
const pool = new sql.ConnectionPool(config);
pool.connect().then(() => {
//simple query
pool.request().query('select * from employees', (err, result) => {
if(err) res.send(err)
else{
return res.json({
data : result.recordset
})
}
})
sql.close();
})
console.log('ending sql');
});
you will need msnodesqlv8 driver, which you have to paste it in require as
var sql = require('mssql/msnodesqlv8'),
as well as you will have to include it in driver section in config object.
var config = {
user:"*****",
password:"*****",
database:"*****",
driver: 'msnodesqlv8',
server:"*****",
options: {
trustedConnection : true
}
}

Resources