hello.js: Is it possible to set the provider's settings dynamically? - javascript

I have implemented a new module for hello.js.
I need the auth, grant and base to be dynamic.
Is there a way to set/override these values from the hello.init() call?
My module looks like this:
(function(hello) {
hello.init({
my_service_name: {
name: 'My-Service-Name',
oauth: {
version: 2,
auth: 'http://mydomain/oauth/authorize',
grant: 'http://mydomain/oauth/token'
},
scope: {
basic: ['basic_scope']
},
base: 'http://mydomain/',
xhr: function(p) {
if (p.method !== 'get' && p.data) {
// Serialize payload as JSON
p.headers = p.headers || {};
p.headers['Content-Type'] = 'application/json';
if (typeof (p.data) === 'object') {
p.data = JSON.stringify(p.data);
}
}
return true;
}
}
});
})(hello);
and my hello.init() call:
hello.init({
my_service_name: server.consumerKey
}, {
redirect_uri : server.callbackUrl,
});
The use-case is that the application I am developing will communicate with several servers, so I cannot hardcode the URLs in the module's file.

I figured out that I can override the default settings by passing the whole oauth object in the hello.init() call:
hello.init({
my_service_name: {
id: server.consumerKey,
oauth: {
version: 2,
auth: server.auth_url,
grant: server.token_url
},
base: server.baseUrl
}
}, {
redirect_uri : server.callbackUrl
});

Related

SOCKS5 Proxy Authentication in Google Chrome Extension

I'm trying to create a extension which would use my SOCKS5 proxy with authentication.
Code in my background script is like this:
var config = {
mode: "fixed_servers",
rules: {
fallbackProxy: {
scheme: "socks5",
host: "myhostaddress"
}
}
};
chrome.proxy.settings.set(
{ value: config, scope: 'regular' },
function () { });
chrome.webRequest.onAuthRequired.addListener(
function (details) {
console.log("onAuthRequired!", details);
return ({
authCredentials: {
'username': "uname",
'password': "pass"
}
});
},
{ urls: ["<all_urls>"] },
['blocking']
);
But I always get ERR_SOCKS_CONNECTION_FAILED error on each page...
What am I doing wrong?
As stated in thread, Chrome doesn't support SOCKS5 proxy with authentication. The only browser that might be supported is Maxthon browser.

hapi-swagger disables my routes

Below is the glue manifest I use to fire up the server:
var Config = require('../config.json');
var internals = {
manifest: {
connections: [
{
host : Config.host || process.env.IP,
port : Config.apiPort || process.env.PORT,
labels : ['api']
}],
plugins: {
'./decorate': [{ 'select': ['api']}],
'hapi-auth-jwt': [{ 'select': ['api']}],
'./authentication': [{ 'select': ['api']}],
'./controllers': [{ 'select': ['api']}],
'./models': [{ 'select': ['api']}],
'./api': [{ 'select': ['api']}],
good: {
opsInterval: 5000,
reporters: [
{ 'reporter': 'good-console', 'events': { 'log': '*' } }
]
}
}
}
};
if (!process.env.PRODUCTION) {
internals.manifest.plugins['blipp'] = [{}];
internals.manifest.plugins['good'].reporters[0].events['ops'] = '*';
}
module.exports = internals.manifest;
As soon as I add 'hapi-swagger' to the list of plugins the server stops responding to the routes defined in the ./api file. None of the routes work. Is the the right way to add hapi-swagger to the glue manifest or am I doing something absurd?
EDIT: Below is the api.js
exports.register = function (plugin, options, next) {
plugin.dependency('controllers');
plugin.dependency('models');
var Controllers = plugin.plugins.controllers.handlers;
var Models = plugin.plugins.models.models;
plugin.bind({
models: Models
});
plugin.route([
{ method: 'GET', path: '/token', config: Controllers.Membership.token },
{ method: 'GET', path: '/', config: Controllers.Home.status },
{ method: 'GET', path: '/nodes', config: Controllers.Node.search },
{ method: 'GET', path: '/services', config: Controllers.Node.services },
{ method: 'GET', path: '/createnodetree', config: Controllers.Loader.createNodeTree }
]);
next();
};
exports.register.attributes = {
name: 'api',
version: require('../package.json').version
};
This happens if you try to use hapi-swagger without either including the documentation view dependencies or properly disabling documentation support. From the docs:
If you want to view the documentation from your API you will also need to install the inert and vision plugs-ins which support templates and static content serving. If you wish just to used swagger.json without the documentation for example with swagger-codegen simply set options.enableDocumentation to false.
You didn't show how you are adding the hapi-swagger plugin but you simply need to add 'enableDocumentation': false to options wherever you define that. You can find examples at the link above.

pass common data in every ajax call

I need to pass rest=1 in every ajax call. How do i do that. Can i add it at a global level something like Transform Request
This is how my service looks like. I have several such service where only the endpoint or apipath changes
return $resource(apiPath, {
rest: 1,
}, {
query: {
method: 'GET',
isArray: true,
}
}
);
Also It would be good if i could only add to calls if the ajaxurl/apiurl is not in a exclude list
Try adding this in your main app config block.
$httpProvider.interceptors.push(function() {
return {
'request': function(config) {
if (config.method === 'POST')
angular.extend(config.data, {rest: 1});
return config;
}
};
});

Using adapter headers outside of ActiveModelAdapter

I've got my authorization system working nicely with Ember Data. All my ember-data calls are signed with the correct tokens by using adapater.ajax() instead of $.ajax. However, I've got a case where I am using a 3rd party upload library which uses its own XHR request (jquery.fileapi). This library exposes a "headers" property for the requests it makes, but I'm not sure what the best way is to get the headers out of my adapter and pass it the file upload component I'm building.
ApplicationAdapter:
export default DS.ActiveModelAdapter.extend({
namespace: 'api/v1',
headers: function() {
var authToken = this.get('session.authToken') || 'None';
return {
'Authorization': Ember.String.fmt('Bearer %#', authToken)
};
}.property('session.authToken')
});
ImageUploadComponent:
didInsertElement: function() {
this.$('.js-uploader').fileapi({
url: '/api/v1/users/avatar',
accept: 'image/*',
headers: {'?????????????'}
});
}
I'd rather not define a global in "headers" when the 'session.authToken' changes.
Here's what I'm doing for now. Would love other solutions.
DS.Store.reopen({
apiPathFor: function() {
var url = arguments.length ? Array.prototype.slice.call(arguments).join('/') : ''
, adapter = this.adapterFor('application');
return [adapter.urlPrefix(), url].join('/');
}
});
export default Ember.Component.extend({
endpoint: null,
store: Ember.computed.readOnly('targetObject.store'),
didInsertElement: function() {
var store = this.get('store')
, adapter = store.adapterFor('application')
, headers = adapter.get('headers')
, url = store.apiPathFor(this.get('endpoint'));
var args = {
url: url,
headers: headers,
accept: 'image/*'
};
this.$('.js-fileapi').fileapi(args);
},
});

Emberjs authentication session not working

I have followed Authentication Tutorial, but running into some issues.
I have a php backend api which resides in another domain, http://rest.api {local development}
The ember js application uses ember-app-kit and connects to the rest api.
When the user submits the login form it sends the username/email with password to one of the route defined in the rest api Session Controller
import AuthManager from 'lms/config/auth_manager';
var SessionNewController = Ember.ObjectController.extend({
attemptedTransition : null,
loginText : 'Log In',
actions: {
loginUser : function() {
var self = this;
var router = this.get('target');
var data = this.getProperties('identity', 'password');
var attemptedTrans = this.get('attemptedTransition');
$.post('http://rest.api/login',
data,
function(results) {
console.log(results.session);
console.log(results.user_id);
AuthManager.authenticate(results.session, results.user_id);
if(attemptedTrans) {
attemptedTrans.retry();
self.set('attemptedTransition', null);
} else {
router.transitionTo('index');
}
}
)
}
}
});
export default SessionNewController;
After receiving the api result in the results variable which looks like this :
Object {success: "user login success", session: "2OmwKLPclC.YhYAT3745467my7t0m2uo", user_id: "1"}
But as soon as I capture the data and send it to the AuthManager which resides in Auth Manager Code
import User from 'lms/models/user';
import Application from 'lms/adapters/application';
var AuthManager = Ember.Object.extend({
init: function() {
this._super();
var accessToken = $.cookie('access_token');
var authUserId = $.cookie('auth_user');
if(!Ember.isEmpty(accessToken) || !Ember.isEmpty(authUserId)) {
this.authenticate(accessToken, authUserId);
}
},
isAuthenticated: function() {
return !Ember.isEmpty(this.get('ApiKey.accessToken')) && !Ember.isEmpty(this.get('ApiKey.user'));
},
authenticate: function(accessToken, userId) {
$.ajaxSetup({
headers: { 'Authorization': 'Bearer ' + accessToken }
});
var user = User.store.find(userId);
console.log(user);
this.set('ApiKey', ApiKey.create({
accessToken: accessToken,
user: user
}));
},
reset: function() {
this.set('ApiKey', null);
$.ajaxSetup({
headers: { 'Authorization': 'Bearer None' }
});
},
apiKeyObserver: function() {
Application.accessToken = this.get('apikey.accessToken');
if (Ember.isEmpty(this.get('ApiKey'))) {
$.removeCookie('access_token');
$.removeCookie('auth_user');
} else {
$.cookie('access_token', this.get('ApiKey.accessToken'));
$.cookie('auth_user', this.get('ApiKey.user.id'));
}
}.observes('ApiKey')
});
export default AuthManager;
I got an error in the console saying
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = met...<omitted>...e' new.js:23
(anonymous function) new.js:23
jQuery.Callbacks.fire jquery.js:1037
jQuery.Callbacks.self.fireWith jquery.js:1148
done jquery.js:8074
jQuery.ajaxTransport.send.callback jquery.js:8598
It is not able to pass the variables to the imported function.
Finally got this working. The error that was I doing is after extending the Ember.Object.extend() on auth_manager.js, I didn't create the object anywhere. Thats why it couldnt set create a cookie and throwing that error message.
All I had to do was, .create() after extending the object.
Don't know whether it is the right method or not. But it certainly works.

Categories

Resources