Using passport-google-oauth with react-native - node.js

I'm trying to use passport-google-oauth in my react-native application. When I run the app it throws the error: requiring unknown module util . I've installed the package using npm install .. and I've also tried npm install ... --save
App/Components/Login.js
'use strict';
var React = require('react-native');
var GoogleStrategy = require('passport-google-oauth').OAuthStrategy;
...
package.json
{
"name": "NativeApp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node_modules/react-native/packager/packager.sh"
},
"dependencies": {
"passport": ">= 0.0.0",
"passport-google-oauth": "^0.2.0",
"react-native": "^0.4.4"
},
"devDependencies": {}
}
index.ios.js
'use strict';
var React = require('react-native');
var Login = require('./App/Components/login');
var {
AppRegistry,
StyleSheet,
Text,
View,
NavigatorIOS,
} = React;
class AppStoreIOS extends React.Component{
render() {
return (
<NavigatorIOS
titleTextColor = '#0073A0'
// barTintColor = '#183E63'
initialRoute={{
component: Login,
title: 'AppStore v2.0',
passProps: { myProp: 'foo' },
}}
/>
);
}
};

Don't think this going to work for you. Passport expects to be run in an node.js (express based) environment, and will at least require some work to port it to using a webview for the Oauth flow, realistically it will be a lot of work.
Have a look at https://medium.com/#jtremback/oauth-2-with-react-native-c3c7c64cbb6d for an example of how to support oauth in react-native. I haven't tried this, but it looks pretty straight forward.

Related

Shopify node api context initalize errors out

I'm trying to make an app following these directions:
https://github.com/Shopify/shopify-node-api/blob/main/docs/getting_started.md
I have all the code configred and it looks like this:
// src/index.ts
import http from 'http';
import url from 'url';
import querystring from 'querystring';
import Shopify, { ApiVersion } from '#shopify/shopify-api';
require('dotenv').config();
const { API_KEY, API_SECRET_KEY, SCOPES, SHOP, HOST } = process.env
Shopify.Context.initialize({
API_KEY,
API_SECRET_KEY,
SCOPES: [SCOPES],
HOST_NAME: HOST.replace(/https?:\/\//, ""),
HOST_SCHEME: HOST.split("://")[0],
IS_EMBEDDED_APP: {boolean},
API_VERSION: ApiVersion.{version} // all supported versions are available, as well as "unstable" and "unversioned"
});
// Storing the currently active shops in memory will force them to re-login when your server restarts. You should
// persist this object in your app.
const ACTIVE_SHOPIFY_SHOPS: { [key: string]: string | undefined } = {};
async function onRequest(
request: http.IncomingMessage,
response: http.ServerResponse,
): Promise<void> {
const {headers, url: req_url} = request;
const pathName: string | null = url.parse(req_url).pathname;
const queryString: string = String(url.parse(req_url).query);
const query: Record<string, any> = querystring.parse(queryString);
switch (pathName) {
default:
// This shop hasn't been seen yet, go through OAuth to create a session
if (ACTIVE_SHOPIFY_SHOPS[SHOP] === undefined) {
// not logged in, redirect to login
response.writeHead(302, {Location: `/login`});
response.end();
} else {
response.write('Hello world!');
// Load your app skeleton page with App Bridge, and do something amazing!
}
return;
} // end of default path
} // end of onRequest()
http.createServer(onRequest).listen(3000);
Package JSON looks like this:
{
"name": "shopify-checkout-apit",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"#shopify/shopify-api": "^3.1.0"
},
"devDependencies": {
"#types/node": "^17.0.40",
"dotenv": "^16.0.1",
"typescript": "^4.7.3"
},
"scripts": {
"build": "npx tsc",
"prestart": "yarn run build",
"start": "node dist/index.js"
}
}
When I go to run the app with yarn start I get a ton of errors
PS C:\Users\kawnah\shopify-checkout-apit> yarn start yarn run v1.22.18
$ yarn run build $ npx tsc src/index.ts:17:27 - error TS1003:
Identifier expected.
17 API_VERSION: ApiVersion.{version} // all supported versions are
available, as well as "unstable" and "unversioned"
~
src/index.ts:18:1 - error TS1005: ',' expected.
18 }); ~
Found 2 errors in the same file, starting at: src/index.ts:17
error Command failed with exit code 2. info Visit
https://yarnpkg.com/en/docs/cli/run for documentation about this
command. error Command failed with exit code 2. info Visit
https://yarnpkg.com/en/docs/cli/run for documentation about this
command. PS C:\Users\kawnah\shopify-checkout-apit>
I have no idea what any of this means.
Typescript Error TS1003 when attempting to access object properties using bracket notation
Why does this trigger an Identifier Expected error in Typescript?
I tried deleting node modules and reinstalling but it didn't work.
How do you fix this?
the config needs to look like this
Shopify.Context.initialize({
API_KEY,
API_SECRET_KEY,
SCOPES: [SCOPES],
HOST_NAME: HOST.replace(/https?:\/\//, ""),
HOST_SCHEME: HOST.split("://")[0],
IS_EMBEDDED_APP: true,
API_VERSION: ApiVersion.October21 // all supported versions are available, as well as "unstable" and "unversioned"
});

TypeError: Cannot read property 'address' of undefined supertest

I need some help to resolve my problem with testing on nodejs codes. I'm using mocha and supertest. I'm confused with the implementation in supertest. I don't know to resolved it. I'm trying to automate downloading a file.
describe('GET /entry/:entryId/file/:id/download', function(){
it('should pass download function', function(done){
this.timeout(15000);
request(app.webServer)
.get('/entry/543CGsdadtrE/file/wDRDasdDASAS/download')
.set('Authorization', 'Bearer eyJ0eXAiOiJKV1QiLCJhbGco')
.expect(200)
.end(function(err, res) {
if (err) return done(err);
console.log(err, res);
done();
});
});
});
I received a similar error from mocha when testing an express app. Full text of error:
0 passing (185ms)
2 failing
1) loading express responds to /:
TypeError: app.address is not a function
at Test.serverAddress (test.js:55:18)
at new Test (test.js:36:12)
at Object.obj.(anonymous function) [as get] (index.js:25:14)
at Context.testSlash (test.js:12:14)
2) loading express 404 everything else:
TypeError: app.address is not a function
at Test.serverAddress (test.js:55:18)
at new Test (test.js:36:12)
at Object.obj.(anonymous function) [as get] (index.js:25:14)
at Context.testPath (test.js:17:14)
I fixed it by adding this to my express server.js, i.e. export the server object
module.exports = app
Typescript users, who are facing this error, check two things:
The express server should have module.exports = app (thanks to #Collin D)
Use import * as app from "./app"
instead of wrong import app from "./app"
I was facing same problem, above solution didn't work for me, some one in my shoes
kindly follow this guy's
exports in server.js should be
module.exports.app = app;
If you have multiple modules than use es6 feature
module.exports = {
app,
something-else,
and-so-on
}
my package.json for version cross ref..
{
"name": "expressjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha **/*.test.js",
"start": "node app.js",
"test-watch": "nodemon --exec npm test"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.4",
"hbs": "^4.0.1"
},
"devDependencies": {
"mocha": "^5.2.0",
"supertest": "^3.3.0"
}
}

Node registry path with electron-updater and Sinopia

I am currently working on an application running on Electron (former atom-shell), and trying to design a way to alert the user when a new update is available. To do this, I am using electron-updater in the way described in electron-updater-sample. I also configured Sinopia to be listening on http://localhost:4873/ (default behavior) and ran this commande line:
npm config set registry "http://localhost:4873"
I checked in the .npmrc file, the registry is properly set with the new value.
The problem I have is when I try to check for the update, I get this error message in console:
{ [HTTPError: Response code 404 (Not Found)]
message: 'Response code 404 (Not Found)',
code: undefined,
host: 'registry.npmjs.org',
hostname: 'registry.npmjs.org',
method: 'GET',
path: '/hacker-keyboard-electron',
statusCode: 404,
statusMessage: 'Not Found' }
So I believe I forgot something in the configuration of npm that makes the application listen to the regular path for npm rather than the Sinopia server. The question is what?
Please find below the code I am using:
foobar-generator
├── app
├── bower components
├── bower.json
├── index.html
├── index. js
├── main. js
├── nbproject
├── node modules
├── npm-debug.log
├── package.json
├── readme. md
└── sinopia
package.json
{
"name": "foobar-generator",
"version": "0.0.1",
"description": "A generator for foobar",
"main": "main.js",
"dependencies": {
"angular": "^1.4.7",
"bootstrap": "^3.3.5",
"chokidar": "^1.2.0",
"electron-debug": "^0.2.1",
"electron-packager": "^5.1.0",
"electron-plugins": "^0.0.4",
"electron-prebuilt": "^0.33.6",
"electron-rebuild": "^1.0.2",
"electron-updater": "^0.2.0",
"grunt": "^0.4.5",
"jquery": "^2.1.4"
},
"devDependencies": {},
"publishConfig": {
"registry": "http://localhost:4873/"
},
"registry": "http://localhost:4873/"
}
main.js
var appli = require('app');
var BrowserWindow = require('browser-window');
var updater = require('electron-updater');
var util = require('util');
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;
var loaded = false;
// Quit when all windows are closed.
appli.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
appli.quit();
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
appli.on('ready', function () {
updater.on('ready', function () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
mainWindow.openDevTools({detach: true});
mainWindow.on('closed', function () {
mainWindow = null;
});
});
updater.on('updateRequired', function () {
appli.quit();
});
updater.on('updateAvailable', function () {
if (mainWindow) {
mainWindow.webContents.send('update-available');
}
});
updater.start();
updater.check(function (err, results) {
if (err) {
return console.error(util.inspect(err));
}
console.log(results);
});
});
Do you guys see anything I could have forgotten/done wrong?
By reading the manual for npmrc (npm help npmrc), I have discovered the the .npmrc file is not unique. By configuring the registry the way I did, I only changed the per-user .npmrc. But there also should be such a file in your project root directory! It is in this one that you should configure the registry you want to use. Adding this file in project root directory solved the problem I was facing.
You should listen to error event.
Try this
updater.on('error', function (err) {
console.log(err);
});

grunt-contrib-connect - undefined is not a function for connect.static

I am trying to configure the grunt connect such a way that
For static pages it serves pages from src directory
web service calls are intercepted by middle-ware and static json is served.
While the web service calls are being mocked correctly the connect.static call ends up giving an error
TypeError: undefined is not a function
While I realize that the connect.static was provided in later versions of this module, I have already upgraded to a version later than that
Here is my package.json file
{
"name": "my-angular-seed-project",
"version": "1.0.0",
"description": "angular seed with only bower and grunt",
"main": "index.js",
"dependencies": {
},
"devDependencies": {
"bower": "^1.4.1",
"grunt": "^0.4.5",
"grunt-cli": "^0.1.13",
"grunt-contrib-connect": ">=0.10.0",
"grunt-contrib-jshint": "latest",
"grunt-contrib-uglify": "latest",
"grunt-contrib-watch": "latest",
"jshint-stylish": "^2.0.1"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Here is the gruntfile.js
// Gruntfile.js
// our wrapper function (required by grunt and its plugins)
// all configuration goes inside this function
module.exports = function(grunt) {
var restEndPoints = {
"/restapi/users": {"GET":"json-files/users.get.json"},
"/restapi/users/login": {"GET":"json-files/users.get.json"},
"/restapi/users/john#gmail.com": {"GET":"json-files/users.get.john.json"},
"/restapi/nodes": {"GET":"json-files/nodes.get.json","PUT":"json-files/nodes.put.json","POST":"json-files/nodes.put.json"},
"/restapi/nodes/Node1": {"GET":"json-files/nodes.get.node1.json","DELETE":"json-files/nodes.delete.node1.json"},
"/restapi/services": {"GET":"json-files/services.get.json","PUT":"json-files/services.put.json","POST":"json-files/services.put.json"},
"/restapi/services/nginx": {"GET":"json-files/services.get.nginx.json","DELETE":"json-files/services.delete.nginx.json"},
"/restapi/commands": {"GET":"json-files/commands.get.json","PUT":"json-files/commands.put.json","POST":"json-files/commands.put.json"},
"/restapi/commands/pwd": {"GET":"json-files/commands.get.pwd.json","DELETE":"json-files/commands.delete.pwd.json"}
};
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;};
// ===========================================================================
// CONFIGURE GRUNT ===========================================================
// ===========================================================================
grunt.initConfig({
// get the configuration info from package.json ----------------------------
// this way we can use things like name and version (pkg.name)
pkg: grunt.file.readJSON('package.json'),
// all of our configuration will go here
watch: {
},
// configure jshint to validate js files -----------------------------------
jshint: {
options: {
reporter: require('jshint-stylish') // use jshint-stylish to make our errors look and read good
},
// when this task is run, lint the Gruntfile and all js files in src
build: ['Gruntfile.js', 'src/**/*.js']
},
// configure connect to run server (on test/serve or example)
connect: {
server: {
options: {
port : 8000,
hostname : 'localhost',
base : 'src',
middleware: function (connect,options){return [
//Middleware #1 - for rest api calls
function restapiMiddleware(req, res, next) {
if (req.url.indexOf('restapi') > 0){
console.log(req.method+' request received for webservice api ['+req.url+']');
var match = false;
var json_file_to_serve = "";
var keys = Object.keys(restEndPoints);
keys.forEach(function(urlAsKey) {
if (req.url.endsWith(urlAsKey)) {
Object.keys(restEndPoints[urlAsKey]).forEach(function(httpMethodsAsKey) {
if (req.method == httpMethodsAsKey){
match = true;
json_file_to_serve = restEndPoints[urlAsKey][httpMethodsAsKey];
}
}); //forEach ends
}
}); //forEach ends
//no match with the url, move along
if (match == false) {
return next();
}
if (req.url.endsWith('/login')){
res.writeHead(200, { 'user-auth-token':'56f7997504b352cbf6ba6210409e423f5fdac49a','user-enc-email':'lJUXityStsKko/lPr9eJUc5fLFCV5kFm' });
}
//Finalize this response with json file
res.end(grunt.file.read(json_file_to_serve));
// if not restapi call then goto next middleware
// can we serve static right here ?
}else{
return next();
}
} // element/middleware one ends so comma just json objects this is awesome
,
//Middleware #2 for static page calls
function staticMiddleware(connect,options) {
connect.static(options.base);
//connect.static('src');
}
] // array ends
}
}
}
}
});
// ===========================================================================
// LOAD GRUNT PLUGINS ========================================================
// ===========================================================================
// we can only load these if they are in our package.json
// make sure you have run npm install so our app can find these
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-watch');
//register the task
grunt.registerTask('serve', ['connect', 'watch']);
};
Am I missing something trivial here ?
Thanks #R4c00n & #Christian Fritz, I was going through the gruntfile of the grunt-contrib-connect and it uses the serveStatic call instead of connect.static and yes the module serve-static is part of grunt contrib connect's node_modules. So now a serveStatic(base.options) does wire the static files as well.
Here is the updated grunt file section (the serve static call has to be first though)
middleware: function (connect,options){return [
//statically serve pages from src directory
serveStatic('src'),
//Middleware #1 - for rest api calls
function restapiMiddleware(req, res, next) {
// middleware code
}];}

cloud9 crypto is not working at all been trying for days

I am trying to get a setup work with utils, the problem is it can not find the crypto module.
I have install utils and crypto using npm install then when I run my script
node server.js casper.js
I get this error
Error: Cannot find module 'crypto'
phantomjs://bootstrap.js:289
phantomjs://bootstrap.js:254 in require
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:7
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:117
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/utils/utils.js:118
TypeError: 'undefined' is not a function (evaluating 'utils.inherits(Nightmare, Casper)')
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/nightmarejs/lib/nightmareClient.js:21
/var/lib/stickshift/53452520e0b8cd1d870002e1/app-root/data/828422/node_modules/nightmarejs/lib/nightmareTest.js:16
why can it not find crypto. I have tried all different ways to get this working, but no luck
does any one have any ideas?
package.json file
{
"name": "chat-example",
"version": "0.0.0",
"description": "A chat example to showcase how to use `socket.io` with a static `express` server",
"main": "server.js",
"repository": "",
"author": "Mostafa Eweda <mostafa#c9.io>",
"dependencies": {
"async": "~0.2.8",
"express": "~3.2.4",
"socket.io": "~0.9.14",
"phantomjs": "*",
"casperjs": "*",
"nightmarejs": "*",
"utils": "*",
"casper": "*"
}
}
server.js
var nightmareJS = require('./node_modules/nightmarejs/lib/nightmare').nightmare('test');
nightmareJS.notifyCasperMessage = function(msg) {
if(msg.type == 'statement') {
console.log(msg.msg);
console.log("Nightmare Server says hello.");
}
else if(msg.type == 'dateQuestion') {
console.log(msg.msg);
var d = new Date();
nightmareJS.sendCasperMessage({ time: d.toString(), timeNow: d.getTime()});
}
}
casper.js
casper.start('http://www.google.com', function() {
this.test.assertTitle('Google', 'Google has the correct title');
this.sendMessageToParent({ type: 'statement', msg: 'Hello Nightmare.'})
})
casper.then(function() {
this.waitForMessageResponse({ type: 'dateQuestion', msg: 'What time is it?'}, 'time', function() {
var d = new Date();
this.echo('Nightmare thinks the time is: ' + this.lastDataReceived.time);
this.log('Nightmare thinks the time is: ' + this.lastDataReceived.time, 'debug');
this.test.assert(Math.abs(this.lastDataReceived.timeNow - d.getTime()) < 1000, "Nightmare and Casper's times are within 1000 seconds of each other");
})
});
casper.run(function() {
this.test.done();
});
and then i run the files using
node server.js casper.js
i am trying to get nightmarejs to work but utils cannot find crypto
please someone help i so need this to work

Resources