I want to to create a vpn configuration with ionic. I tried this code but it returns unknown-error. What could be the cause? What can I do?
const options = {
vpnHost: 'tt.monkeyvpn.com',
vpnUsername: 'tester',
vpnPassword: 'test',
userCertificate: 'MIINmAIBAzCCDV4GCSqGSIb3DQEHAaCCDU8Egg1LMIINRzCCB78GCSqGSIb3DQEHBqCCB7AwggesAgEAMIIHpQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQIQSYYmUBCA3kCAggAgIIHeFtesvIQYBMRaFk',
caCertificate: '',
userCertificatePassword: 'testit',
};
window['plugins'].VPNManager.enable(
function(result) {
console.log('result ', result);
alert('connected');
},
function(error) {
console.log('error ', error);
alert(error);
},
options
);
Related
Everyone
I am going to get birthday and location from Facebook using react-native-fbsdk.
Here's part of my code:
LoginManager.logInWithReadPermissions(['public_profile', 'user_birthday', 'user_location'])
.then((result) => {
if (result.isCancelled) {
return;
}
AccessToken.getCurrentAccessToken().then((data) => {
console.log(data); // output 1:
const responseInfoCallback = (error, profile) => {
if (error) {
console.log(error);
} else {
console.log(profile); // output 2:
}
};
const accessToken = data.accessToken;
const infoRequest = new GraphRequest(
'/me',
{
accessToken,
parameters: {
fields: {
string: 'name,gender,birthday,location{location}',
},
},
},
responseInfoCallback,
);
new GraphRequestManager().addRequest(infoRequest).start();
});
});
})
.catch(error => console.log(error));
Here's result of output 1 and 2
--------- output 1 -------
{ accessToken: .......,
permissions: [ 'email', 'public_profile' ],
declinedPermissions: [],
applicationID: '968214779983507',
accessTokenSource: undefined,
userID: '161823674419561',
expirationTime: 1515417067593.333,
lastRefreshTime: 1510242607593.949 }
-------output 2--------
{ id: '161823674419561', gender: 'male', name: '....' }
Please help me.
Thanks.
Those permissions only work for users with a role in the App. If you want to make them work for everyone else, you need to go through a review process: https://developers.facebook.com/docs/facebook-login/review
I'm trying to figure out how to stub mongoDB in hapi js to allow testing but I have no idea how to do it. I've tried checking out Sinonjs but I have no idea how to apply it in this particular case.
Here's some of the code:
// index.js
'use strict';
const Hapi = require('hapi');
const MongoJS = require('mongojs');
const server = new Hapi.Server();
server.connection({ host: 'localhost', port: 11001 });
server.app.db = MongoJS('crunchbase', ['companies']);
server.register([
{
register: require('./lib/plugins')
},
{
register: require('./lib/modules/companies'),
options: {
baseUrl: '/v1/companies'
}
}
], (err) => {
if (err) {
throw err;
}
server.start((err) => {
if (err) {
throw err;
}
server.log('info', `Server listening on ${server.info.uri}`);
});
});
module.exports = server;
Here's are the routes:
// companies.js
'use strict';
const Boom = require('boom');
const Joi = require('joi');
const error = Joi.object().keys({
statusCode: Joi.number(),
error: Joi.string(),
message: Joi.string()
});
const schema = Joi.object().keys({
_id: Joi.object(),
permalink: Joi.string(),
name: Joi.string(),
homepage_url: Joi.string(),
category_list: Joi.string(),
funding_total_usd: Joi.alternatives().try(Joi.number(), Joi.string()),
status: Joi.string(),
country_code: Joi.string().allow(''),
state_code: Joi.alternatives().try(Joi.string(), Joi.number()).allow(''),
region: Joi.string().allow(''),
city: Joi.string().allow(''),
funding_rounds: Joi.number(),
founded_at: Joi.string().allow(''),
first_funding_at: Joi.string(),
last_funding_at: Joi.string()
});
exports.register = (server, options, next) => {
const db = server.app.db;
const { baseUrl } = options;
server.route([
{
method: 'GET',
path: baseUrl,
config: {
description: 'companies',
notes: 'Get a list of companies from the database',
tags: ['api'],
validate: {
query: {
limit: Joi.number().min(1).max(20).default(5)
}
},
response: {
status: {
200: Joi.array().items(schema),
400: error,
500: error
}
}
},
handler: (request, reply) => {
db.companies.find().limit(request.query.limit, (err, docs) => {
if (err) {
return reply(Boom.wrap(err, 'Internal MongoDB error.'));
}
reply(docs);
});
}
}
]);
return next();
};
exports.register.attributes = {
pkg: require('./package.json')
};
And here's the test suite:
// companies.test.js
'use strict';
const Code = require('code');
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const { describe, it } = lab;
const expect = Code.expect;
const Server = require('../../');
describe('Companies module test suite', () => {
const baseUrl = '/v1/companies';
it('should return array of 5 companies by default', (done) => {
Server.inject({
method: 'GET',
url: baseUrl
}, (response) => {
expect(response.statusCode).to.equal(200);
expect(response.result).to.be.an.array().and.have.length(5);
done();
});
});
it('should return array of 3 companies', (done) => {
Server.inject({
method: 'GET',
url: baseUrl + '?limit=3'
}, (response) => {
expect(response.statusCode).to.equal(200);
expect(response.result).to.be.an.array().and.have.length(3);
done();
});
});
it('should throw an error', (done) => {
Server.inject({
method: 'GET',
url: baseUrl + '?limit=me'
}, (response) => {
expect(response.statusCode).to.equal(400);
expect(response.result.error).to.equal('Bad Request');
done();
});
});
});
It works but only if there's a connection to the db which I want to decouple. Any help would be appreciated.
Here's a solution courtesy of devinivy
One approach I've taken is to place queries in server methods, then
stub out the server methods (server.methods.x = stubX) in my tests.
You could also check out proxyquire as suggested by timcosta
Here's the brief github discussion
If I want to configure the binaryMediaTypes [ 'image/jpg', 'text/html' ] for an API through nodejs. What is the right API to use? It looks like the below is not working.
const config = JSON.stringify({
"swagger": "2.0",
"info": {
"title": this.apiName
},
"x-amazon-apigateway-binary-media-types": [ 'image/jpg', 'text/html' ]
});
return new Promise((resolve, reject) => {
var params = {
restApiId: apiId, /* required */
mode: 'merge',
body: config
};
this.apiGatewaySDK.putRestApi(params, (err, data) => {
if (err) {
reject(err);
}
else {
resolve('binary set successfully');
}
});
});
we end up using updateRestApi(). Pls note the patchOpertions part, it is very unintuitive (sth aws sdk could improve? )
let patchOperationsArray = [];
patchOperationsArray.push(
{
op: 'add',
path: '/binaryMediaTypes/'+ e.replace("/", "~1")
}
);
const params = {
restApiId: apiId, /* required */
patchOperations:patchOperationsArray
};
this.apiGatewaySDK.updateRestApi(params, (err, data) => {
if (err) {
reject(err);
}
else {
this.serverless.cli.log('API Gateway Configuring: Binary support are set correctly');
resolve('binary set successfully');
}
});
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed last month.
Improve this question
Every tutorial or unfinished documentation out there doensn't work. This is why I ask here: Is there a simple tutorial, which really works, for passport and sails?
follow this steps two integrate passport with sails js
first :-
List these dependencies inside application_directory/package.json under dependencies
//application_directory/package.json
{
...
"dependencies": {
...
"passport": "~0.1.16",
"passport-local": "~0.1.6",
"bcrypt": "~0.7.6"
}
...
}
2-
To create user model run the following command:
sails generate model user
3- model user.js will look like the following
var bcrypt = require('bcrypt');
module.exports = {
attributes: {
username: {
type: 'string',
required: true,
unique: true
},
password: {
type: 'string',
required: true
},
toJSON: function() {
var obj = this.toObject();
delete obj.password;
return obj;
}
},
beforeCreate: function(user, cb) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) {
console.log(err);
cb(err);
}else{
user.password = hash;
cb(null, user);
}
});
});
}
};
4- To create a controller in sails type the command
sails generate controller
AuthController will look like the following:
var passport = require('passport');
module.exports = {
login: function (req, res) {
res.view();
},
process: function(req, res){
passport.authenticate('local', function(err, user, info) {
if ((err) || (!user)) {
return res.send({
message: 'login failed'
});
res.send(err);
}
req.logIn(user, function(err) {
if (err) res.send(err);
return res.send({
message: 'login successful'
});
});
})(req, res);
},
logout: function (req,res){
req.logout();
res.send('logout successful');
}
};
module.exports.blueprints = {
actions: true,
rest: true,
shortcuts: true
};
5- add the following code to application_directory/config/routes.js
module.exports.routes = {
// (This would also work if you had a file at: `/views/home.ejs`)
'/': {
view: 'home/index'
},
'/login': {
controller: 'AuthController',
action: 'login'
},
'/logout': {
controller: 'AuthController',
action: 'logout'
}
......
}
6- Inside application_directory/config create a file passport.js and add the following code to that
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
module.exports = {
express: {
customMiddleware: function(app){
console.log('Express midleware for passport');
app.use(passport.initialize());
app.use(passport.session());
}
}
};
7- Inside /api/services/ create a file passport.js and add the following code to that
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
bcrypt = require('bcrypt'); < /code>
//helper functions
function findById(id, fn) {
User.findOne(id).done(function (err, user) {
if (err) {
return fn(null, null);
} else {
return fn(null, user);
}
});
}
function findByUsername(u, fn) {
User.findOne({
username: u
}).done(function (err, user) {
// Error handling
if (err) {
return fn(null, null);
// The User was found successfully!
} else {
return fn(null, user);
}
});
}
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
findById(id, function (err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(
function (username, password, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
findByUsername(username, function (err, user) {
if (err)
return done(null, err);
if (!user) {
return done(null, false, {
message: 'Unknown user ' + username
});
}
bcrypt.compare(password, user.password, function (err, res) {
if (!res)
return done(null, false, {
message: 'Invalid Password'
});
var returnUser = {
username: user.username,
createdAt: user.createdAt,
id: user.id
};
return done(null, returnUser, {
message: 'Logged In Successfully'
});
});
})
});
}
));
8- Modify the authenticated.js file present inside /api/policies/
/**
* Allow any authenticated user.
*/
module.exports = function (req, res, ok) {
// User is allowed, proceed to controller
var is_auth = req.isAuthenticated()
if (is_auth) return next();
// User is not allowed
else return res.redirect("/login");
};
I'm trying to share an image to Facebook in React Native through the react-native-fbsdk package.
I have the following, copied almost completely from the docs, but I can't figure out how to format the imageUrl, I keep getting errors saying the SharingContent is invalid.
What am I doing wrong here?
const sharePhotoContent = {
contentType: 'photo',
photos: [
{
imageUrl: "./local/image/path.png",
userGenerated: false,
caption: "Hello World"
}
]
};
ShareDialog.canShow(sharePhotoContent).then(
function(canShow) {
if (canShow) {
return ShareDialog.show(sharePhotoContent);
}
}
).then(
function(result) {
if (result.isCancelled) {
AlertIOS.alert('Share cancelled');
} else {
AlertIOS.alert('Share success with postId: ' + result.postId);
}
},
function(error) {
AlertIOS.alert('Share fail with error: ' + error);
}
);
You can use the react-native-image-picker https://github.com/marcshilling/react-native-image-picker to get the uri of the image and use it create a SharePhotoContent.
Also note that you need to have the facebook app installed in order to share an image.
This is working fine for me
shareLinkWithShareDialog() {
let shareLinkContent = {
contentType: 'link',
contentUrl: 'https://www.facebook.com/images/fb_icon_325x325.png',
contentDescription: 'Facebook sharing is easy!'
}
ShareDialog.canShow(shareLinkContent).then((canShow) => {
if (canShow) return ShareDialog.show(shareLinkContent);
}
).then((result) => {
if (result.isCancelled) {
alert('Share cancelled');
} else {
alert('Share success with postId: ' + result.postId);
}
},
function(error) {
alert('Share fail with error: ' + error);
}
);
}