How to run firebase on server side? - javascript

I want to use firebase as a database service to my server to which a android app would send requests to. I want the server to retrieve data rather than the android app because I want to do some processing before sending data back to client (app).
My node code (index.js) :
const express = require('express')
const app = express()
var port = process.env.PORT || 10000
firebase = require('./firebase') // I added this cuz I can't use <script> tag here
// Initialize Firebase
var config = {
apiKey: "AIzaSynotgonnatell2Q-kwk85XrCyNnc",
authDomain: "hnotgonnatell.firebaseapp.com",
databaseURL: "https://hnotgonnatell.firebaseio.com",
projectId: "notgonnatell",
storageBucket: "",
messagingSenderId: "699935506077"
};
firebase.initializeApp(config);
var database = firebase.database()
ref = database.ref("some_table")
data = {
name : "my name",
number : "2938019283"
}
app.get('/', function(req, res){
ref.push(data)
res.send("hello")
})
app.listen(port)
I cannot use <script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script> cause I'm not connecting to firebase from client. So I instead copied the code from https://www.gstatic.com/firebasejs/4.12.1/firebase.js and imported it into my index.js using require() . When I run the index.js I get:
firebase.initializeApp(config);
^
TypeError: firebase.initializeApp is not a function
at Object.<anonymous> (E:\workspace_javascript\firebase_try\index.js:24:10)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:422:7)
at startup (bootstrap_node.js:143:9)
at bootstrap_node.js:537:3
It works well when I run it by returning a html with firebase code inside <script>

Install firebase from NPM
npm install --save firebase-admin
Initiallize firebase
var admin = require('firebase-admin');
var serviceAccount = require('path/to/serviceAccountKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});
src: https://firebase.google.com/docs/admin/setup

If you want to access Firebase products on a server, you should be using the Firebase Admin SDK, not the client SDK.

Related

firebase.auth().currentUser and onAuthStateChanged always null inspite of being signed in

The firebase.auth().currentUser is always null, as is the onAuthStateChanged listener in my node.js code. However, the user is signed in at my front end swift application. And it is from there that I call to the above node.js script in firebase. A snippet of my code is below. Please take a look and let me know how I can resolve this issue.
Version info
firebase 3.17.5
npm 5.4.2
firebase SDK 5.0.4
Platform Information
linux mac-book air 17.2.0
CODE:
'use strict';
const firebase = require('firebase');
const fireApp = require('firebase-app');
const functions = require('firebase-functions');
const fireAuth = require('firebase-auth');
const admin = require('firebase-admin');
const gcs = require('#google-cloud/storage');
const exec = require('child_process').exec;
const path = require('path');
const fs = require('fs');
const google = require('googleapis');
const sizeOf = require('image-size');
var config = {
apiKey: "Ahigdhvd_icvisQijbdsivdbbvb_blisdvchsblksdbs",
authDomain: "my_project.firebaseapp.com",
databaseURL: "https://my_project.firebaseio.com",
projectId: "my_project",
storageBucket: "my_project.appspot.com",
messagingSenderId: "2536384943632"
};
firebase.initializeApp(config);
admin.initializeApp(config);
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log("user is signed in")
} else {
console.log("no user is signed in")
}
});
You can't use the Firebase Authentication SDK like this. The SDK only works on the client side. You can detect when the user logs in an out on the device (web, Android, iOS), but code running elsewhere can't set up listeners like this.
If you need to communicate with a backend about the login state of the user, you'll have to write some code to communicate between the frontend and backend.

TypeError: PUBNUB.init is not a function

I am using Node.js and I'm trying to get PubNub integrated to get my chatroom up and running. I have been following numerous tutorials and they all seem to have PubNub executing from their client-side. However, to ensure the security of my publish-key and subscribe-key I want to have PubNub execute from my server-side (Nodejs). However the problem is occurs exactly when I try to do just that. Here is my server:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var request = require('request');
var pubnub = require('pubnub');
pubnub = pubnub.init({
subscribe_key: 'sub-c-demo',
publish_key: 'pub-c-demo',
ssl: true
});
//Defining routes
var routes = require('./routes/index');
//Init express
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
//View Engine
app.set('view engine', 'ejs');
//Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
//Get route
app.use('/', routes);
//Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('3000 is the magic port!!');
});
Why do I get a TypeError: pubnub.init is not a function when I try to initialize pubnub?
$ node server
/Users/macbookpro/Desktop/project007/server.js:8
var pubnub = pubnub.init({
^
TypeError: pubnub.init is not a function
at Object.<anonymous> (/Users/macbookpro/Desktop/project007/server.js:8:21)
at Module._compile (module.js:573:32)
at Object.Module._extensions..js (module.js:582:10)
at Module.load (module.js:490:32)
at tryModuleLoad (module.js:449:12)
at Function.Module._load (module.js:441:3)
at Module.runMain (module.js:607:10)
at run (bootstrap_node.js:382:7)
at startup (bootstrap_node.js:137:9)
at bootstrap_node.js:497:3
I followed what seemed to be all the necessary steps:
npm i pubnub --save
var pubnub = require('pubnub');
https://cdn.pubnub.com/sdk/javascript/pubnub.4.4.2.min.js
(Included the latest sdk in my header)
But there seems to be an error somewhere which has lead to me to be confused about the error as well as a few other things.
1). I have been piecing things together from all three but which of these tutorials should i really be following?
https://vimeo.com/35557579
https://www.pubnub.com/docs/nodejs/pubnub-javascript-sdk-v4
https://www.pubnub.com/docs/javascript/pubnub-javascript-sdk-v4
2). Does my publish-key and subscribe-key need be secured or can I simply run PubNub from my client-side like shown in most tutorials?
3). Forget about the server-side and client, should I be executing PubNub as a javascript file and linking the script? <script src="js/pubnubchatroom.js"></script>
I am new to this stuff and im just trying to wrap my head around it all. Thanks in advance!
PubNub V4 SDK NodeJS new Init
There is a new way to initialize your PubNub SDK. See the following example. v4 SDKs are not drop-in compatible. You can mix v4 and v3 SDKs between environments successfully.
const PubNub = require('pubnub');
const pubnub = new PubNub({
publishKey : 'demo',
subscribeKey : 'demo'
})
Follow https://www.pubnub.com/docs/nodejs/pubnub-javascript-sdk-v4
pub/sub keys can be exposed. never expose your secret key.
PubNub is compatible with any strategy in this regard.

Getting failed to load c++ bson extension error using Mongodb and Node.js

I am getting the following error while trying to run server using Node.ja with Mongodb.
Error:
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
C:\xampp\htdocs\odiya_chat\server.js:15
db = mongo.connect("127.0.0.1:27017/"+db, collections);
^
TypeError: Object function (connString, cols) {
var dbname = getDbName(connString);
var onserver = thunky(function(cb) {
getTopology(connString, function(err, topology) {
if (err) return cb(err);
cb(null, topology);
});
});
if (!dbname) {
dbname = connString._dbname;
onserver = thunky(function(cb) {
toMongodbCore(connString, function(err, server) {
if (err) cb(new Error('You must pass a connection string or a mongojs in
stance.'));
cb(null, server);
});
});
}
var that = new Database({name: dbname, cols: cols}, onserver);
if (typeof Proxy !== 'undefined') {
var p = Proxy.create({
get: function(obj, prop) {
if (that[prop]) return that[prop];
that[prop] = that.collection(prop);
return that[prop];
}
});
return p;
};
return that;
} has no method 'connect'
at Object.<anonymous> (C:\xampp\htdocs\odiya_chat\server.js:15:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3
Error-2
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
My server side code is given below.
Server.js
var port=8888;
var express=require('express');
var http=require('http');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
var mongo = require('mongojs');
var app=express();
var server=http.createServer(app);
db = 'doctor',
collections = ['oditek'],
db = mongo.connect("127.0.0.1:27017/"+db, collections);
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) // parse application/json
app.use(methodOverride());
app.use(cookieParser());
//app.use(expressSession({secret:'somesecrettokenhere'})); // simulate DELETE and PUT
app.get('/',function(req,res){
res.sendfile('view/index.html');
})
app.get('/login',function(req,res){
res.sendfile('view/login.html');
});
app.get('/chatroom',function(req,res){
if(req.session){
res.sendfile('view/chatroom.html');
}
});
server.listen(port);
console.log('server is running on the port'+port);
Here My requirement is If user is already logged in client side he will get the chatroom.html page and if not in client side it will ask you for login.I am implementing here connect-mongodb-session for store the session.I have read some posts regarding this and tried the answer but still error was there.Please help me to resolve this error.
Since you're using the mongojs module, you're going to have to connect to the database using the following method
db = mongo("127.0.0.1:27017/"+db, collections);

Object #<MongoClient> has no method 'open'

I've been trying to make a simple site with Node.js, Express.js, and MongoDB. I'm new to these technologies and have been having problem set up the database
Here is snippet of code in my index.js file:
var http = require('http'),
express = require('express'),
path = require('path'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
CollectionDriver = require('./collectionDriver').CollectionDriver;
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var mongoHost = 'localHost';
var mongoPort = 27017;
var collectionDriver;
var mongoClient = new MongoClient(new Server(mongoHost, mongoPort));
mongoClient.open(function(err, mongoClient) {
if (!mongoClient) {
console.error("Error! Exiting... Must start MongoDB first");
process.exit(1);
}
var db = mongoClient.db("MyDatabase");
collectionDriver = new CollectionDriver(db);
});
After I try to run node index.js in terminal, it says the following:
js-bson: Failed to load c++ bson extension, using pure JS version
/Users/username/dev/ga-final/index.js:31
mongoClient.open(function(err, mongoClient) { //C
^
TypeError: Object #<MongoClient> has no method 'open'
at Object.<anonymous> (/Users/username/dev/ga-final/index.js:31:13)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
What is wrong? Why can't I call open? Can you help me fix this? thanks!
This is happening may be because you are using new version of mongodb it is working fine after I use mongodb driver version 1.4.
npm install mongodb#1.4.x
Take a look at the mongodb docs. Your mongoClient object is not what you think it is, and that why there isn't an open() method available.
Make your example code look more like theirs:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
db.close();
});

Express has no method configure error

I'm trying to get started with the MEAN stack. And I'm following this tutorial: link
I have made it until the Test Our Server section. Here
// modules =================================================
var express = require('express');
var app = express();
var mongoose= require('mongoose');
// configuration ===========================================
// config files
var db = require('./config/db');
var port = process.env.PORT || 8080; // set our port
mongoose.connect(db.url); // connect to our mongoDB database (uncomment after you enter in your own credentials in config/db.js)
app.configure(function() {
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(express.logger('dev')); // log every request to the console
app.use(express.bodyParser()); // have the ability to pull information from html in POST
app.use(express.methodOverride()); // have the ability to simulate DELETE and PUT
});
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
app.listen(port); // startup our app at http://localhost:8080
console.log('Magic happens on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app
When I run
nodemon server.js
I get this error
app.configure(function() {
^
TypeError: Object function (req, res, next) {
app.handle(req, res, next);
} has no method 'configure'
at Object.<anonymous> (C:\Users\Yuksel\Desktop\node\test\server.js:14:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
5 Mar 17:27:20 - [nodemon] app crashed - waiting for file changes before startin
g...
It simply says app has no method configure(I guess). But when I delete the configure part and run it again, it works.(This mean app has .listen method, so it is an express object.)
I have tried with both node and nodemon. And I couldn't figure it out. Thank you for your time.
Tom in his blog post new-features-node-express-4 provides examples of how to convert from using app.configure in express version 3.x to removing it in express version 4.0.
For convenience I added the code example below.
Version 3.x
// all environments
app.configure(function(){
app.set('title', 'Application Title');
})
// development only
app.configure('development', function(){
app.set('mongodb_uri', 'mongo://localhost/dev');
})
// production only
app.configure('production', function(){
app.set('mongodb_uri', 'mongo://localhost/prod');
})
Version 4.0
// all environments
app.set('title', 'Application Title');
// development only
if ('development' == app.get('env')) {
app.set('mongodb_uri', 'mongo://localhost/dev');
}
// production only
if ('production' == app.get('env')) {
app.set('mongodb_uri', 'mongo://localhost/prod');
}
The configure method has been removed from express as of version 4.0.0 (including 4.0.0-rc2). See the changelog at https://github.com/strongloop/express/blob/master/History.md#400--2014-04-09

Categories

Resources