Iron-Router: onBeforeAction() -> .next() is not a function - javascript

i got a problem with my meteor app and i don't know why.
My meteor version is 1.1.0.3 and here is a list of my packages:
accounts-password 1.1.1 Password support for accounts
alanning:roles 1.2.13 Role-based authorization
chrismbeckett:toastr 2.1.2_1 Gnome / Growl type non-blocking notifications
coffeescript 1.0.6 Javascript dialect with fewer braces and semi...
email 1.0.6 Send email messages
fortawesome:fontawesome 4.4.0 Font Awesome (official): 500+ scalable vector...
fourseven:scss 3.2.0 Style with attitude. Sass and SCSS support fo...
insecure 1.0.3 Allow all database writes by default
iron:router 1.0.9 Routing specifically designed for Meteor
jquery 1.11.3_2 Manipulate the DOM using CSS selectors
meteor-platform 1.2.2 Include a standard set of Meteor packages in ...
Alright... now we talk about my problem. i would like to protect some routes for users who don't have the "admin" role, that works find. The System checks my role right, but they don't render the view.
Error msg in console
Exception in delivering result of invoking 'accounts/hasAdminRole': TypeError: me.next is not a function
at http://localhost:3000/lib/controllers/admin_controller.js?843e8c9edbf0891b773aa63a9ad004d1afcbfb19:28:9
at Meteor.bindEnvironment [as _callback] (http://localhost:3000/packages/meteor.js?43b7958c1598803e94014f27f5f622b0bddc0aaf:983:22)
at _.extend._maybeInvokeCallback (http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:3860:12)
at _.extend.receiveResult (http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:3880:10)
at _.extend._livedata_result (http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:4970:9)
at onMessage (http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:3725:12)
at http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:2717:11
at Array.forEach (native)
at Function._.each._.forEach (http://localhost:3000/packages/underscore.js?0a80a8623e1b40b5df5a05582f288ddd586eaa18:156:11)
at _.extend._launchConnection.self.socket.onmessage (http://localhost:3000/packages/ddp.js?d1840d3ba04c65ffade261f362e26699b7509706:2716:11)
app/lib/controllers/admin_controller.js
onBeforeAction: function () {
var me = this;
if(!Meteor.userId()) {
Router.go('signin');
} else {
Meteor.call('accounts/hasAdminRole', function(err, r) {
if(!err && r) {
console.log('success');
console.log(me);
me.next()
} else {
toastr.error('Not Authorized.', 'Error!');
Router.go('home');
}
});
}
},
app/server/methods.js
'accounts/hasAdminRole': function() {
return Roles.userIsInRole( Meteor.user() , ['admin'] );
}
thanks for your answers!

You can directly store the this.next function in your me variable and call it as such:
onBeforeAction: function () {
var me = this.next;
if(!Meteor.userId()) {
Router.go('signin');
} else {
Meteor.call('accounts/hasAdminRole', function(err, r) {
if(!err && r) {
console.log('success');
me();
} else {
toastr.error('Not Authorized.', 'Error!');
Router.go('home');
}
});
}
},

Related

Keycloak Javascript failed to inicialize

I'm trying to use Keycloak with JavaScript and these are the steps that I followed.
I create a client inside KeyCloak admin panel.
Link to image
I copy the .json file to my apache folder.
{
"realm": "master",
"auth-server-url": "http://localhost:8080/auth",
"ssl-required": "external",
"resource": "test",
"public-client": true,
"confidential-port": 0
}
I go to my index.html and I add these two lines for calling the script.
<script src="keycloak.js"></script>
<script>
function initKeycloak() {
const keycloak = new Keycloak();
keycloak.init().then(function(authenticated) {
alert(authenticated ? 'authenticated' : 'not authenticated');
}).catch(function() {
alert('failed to initialize');
});
}
</script>
this is what i have in myLogical.js
var keycloak = new Keycloak();
function initKeycloak() {
keycloak.init({onLoad: 'login-required'}).then(function() {
constructTableRows(keycloak.idTokenParsed);
pasteToken(keycloak.token);
}).catch(function() {
alert('failed to initialize');
});
}
function constructTableRows(keycloakToken) {
document.getElementById('row-username').innerHTML = keycloakToken.preferred_username;
document.getElementById('row-firstName').innerHTML = keycloakToken.given_name;
document.getElementById('row-lastName').innerHTML = keycloakToken.family_name;
document.getElementById('row-name').innerHTML = keycloakToken.name;
document.getElementById('row-email').innerHTML = keycloakToken.email;
}
function pasteToken(token){
document.getElementById('ta-token').value = token;
document.getElementById('ta-refreshToken').value = keycloak.refreshToken;
}
var refreshToken = function() {
keycloak.updateToken(-1)
I tried to download the file keycloak.js and put it directly on my root folder but it happen the same problem.
These is the message I got when I try to open the page
I'm confused about point 1, does keycloak automatically load configuration from json file in Apache folder? Let's assume that no, and I think that where your problem lies, you're not passing config param to keycloak constructor.
How to initialize keycloak:
const initKeycloak = async () => {
//you can hardcode these values for now just to see if everything works
const config = { url: 'http://localhost:8080/auth', realm: 'master', clientId: 'test'};
const keycloak = new Keycloak(config);
await keycloak
.init({ onLoad: 'login-required' })
.then(isAuthenticated => {
//user is authenticated
})
.catch(error => { console.log('keycloak error', error); });
}
Another important thing is that keycloak-js library version (in package.json) must match keycloak server version. Sometimes different versions work with each other but it's always best practice that keycloak-js version matches keycloak server version.
You can also look here: https://github.com/m-s7/react-core/blob/devel/src/services/keycloak-service.ts this is my repo with working keycloak-js implementation.

Why Roles not checking if userIsInRole?

I'm using Meteor and alanning:roles for user roles in my project. I'm trying to check if logged user has an admin permission.
I've tried all the ways.
That check returns false.I've made what is in README of alanning:roles, like this:
//server/init.js
var users = [
{name:"Normal User",email:"normal#ehnormal.com.br",roles:[]},
{name:"Usuario Secreto",email:"mauriciord#me.com",roles:['view-secrets']},
{name:"Usuario Gerenciador",email:"mauricioreattoduarte#gmail.com",roles:['manage-users']},
{name:"Mauricio",email:"mauricio#thcm.com.br",roles:['admin']}
];
_.each(users, function (user) {
var id;
id = Accounts.createUser({
email: user.email,
password: "apple1",
profile: { name: user.name }
});
if (user.roles.length > 0) {
// Need _id of existing user record so this call must come
// after `Accounts.createUser` or `Accounts.onCreate`
// Roles.addUsersToRoles(id, user.roles, 'default-group');
Meteor.users.update({_id: id}, {$set:{'emails.0.verified': true}});
console.log("usuario criado");
Roles.addUsersToRoles(id, user.roles, 'default-group');
//Roles.addUsersToRoles(id, user.roles);
}
});
Like said in README, too:
//server/publish.js
Meteor.publish(null, function (){
return Meteor.roles.find({})
});
But when i try to check User's permission in routes.js: see here on my repository.
// lib/routes.js
var logado = FlowRouter.group({
name: 'logadoRoutes',
// se não estiver logado vai para /login
triggersEnter: [function(context, redirect) {
console.log('logado grupo');
if(!Meteor.userId()) {
FlowRouter.go('login');
} else {
return true;
}
}]
});
var admin = logado.group({
prefix: '/admin',
name: 'adminRoutes',
triggersEnter: [function(context, redirect) {
var loggedInUser = Meteor.userId();
console.log('verificando admin ...');
if (Roles.userIsInRole(loggedInUser, ['view-secrets', 'admin'], "default-group")) {
return true;
console.log('é admin - rotas');
}
console.log('não é admin - rotas');
throw new Meteor.Error(403, "Acesso Negado");
}]
});
Here is my repository: https://github.com/mauriciord/thomasicamargo
Packages: https://github.com/mauriciord/thomasicamargo/blob/master/.meteor/packages
meteor-base # Packages every Meteor app needs to have
mobile-experience # Packages for a great mobile UX
mongo # The database Meteor supports right now
blaze-html-templates # Compile .html files into Meteor Blaze views
session # Client-side reactive dictionary for your app
jquery # Helpful client-side library
tracker # Meteor's client-side reactive programming library
standard-minifiers # JS/CSS minifiers run for production mode
es5-shim # ECMAScript 5 compatibility for older browsers.
ecmascript # Enable ECMAScript2015+ syntax in app code
kadira:flow-router
kadira:blaze-layout
erasaur:meteor-lodash
stolinski:stylus-multi
fortawesome:fontawesome
spiderable
fastclick
raix:handlebar-helpers
aldeed:collection2
aldeed:autoform
accounts-ui
accounts-password
matb33:bootstrap-glyphicons
zimme:active-route
gwendall:auth-client-callbacks
meteortoys:allthings
datariot:ganalytics
check
twbs:bootstrap
less
arillo:flow-router-helpers
alanning:roles
UPDATE: I changed in layout with isInRole (it was ifInRole), and now it's working.
I was trying to verify the condition on routes.js just pressing 'Enter' on the URL of Navigation Bar. localhost:3000/admin, but when i go this route via anchor link, the condition work 100% haha. In condition i've made this:
if (Roles.subscription.ready() && Roles.userIsInRole(loggedInUser, ['admin'], 'default-group')) {
return true;
console.log('é admin - rotas');
}
I don't know why, i'm new on MeteorJS.

PhoneGap/Cordova with client-side routing?

I've inherited a Cordova/PhoneGap app running Cordova 3.4. My first task was to implement a Client-Side Routing framework to make it easier to navigate between pages. I chose Flatiron Director as my client-side router, but when I went to implement it I started to get weird functionality out of the app.
My first router setup:
var routing = {
testHandler: function(){
console.log('Route ran');
},
routes: function(){
return {
"/testhandler": testHandler
}
}
};
console.log('Routes added');
The routes are added (at least based on the console output). When I attempt to hit the /testhandler hash, I receive a "Failed to load resource: file:///testhandler" error when I set window.location.hash to "/testhandler". I noticed the "Route ran" statement was never printed.
My next attempt was just using the hashchange event with jQuery.
$(window).on('hashchange', function(){ console.log('Ran'); });
On this attempt, regardless of what I change the hash to, I see the 'Ran' output, but I still receive the "Failed to load resource: " error.
Is this a problem with PhoneGap/Cordova? Or our implementation? Is it just not possible to use client-side routing with Cordova? What am I doing wrong?
I know that this doesn't answer your question directly but you may consider making your own provisional router. This may help you to debug your app and to figure out what's the problem.
Something like this for example:
var router = (function (routes) {
var onRouteChange = function () {
// removes hash from the route
var route = location.hash.slice(1);
if (route in routes) {
routes[route]();
} else {
console.log('Route not defined');
}
};
window.addEventListener('hashchange', onRouteChange, false);
return {
addRoute: function (hashRoute, callback) {
routes[hashRoute] = callback;
},
removeRoute: function (hashRoute) {
delete routes[hashRoute];
}
};
})({
route1: function () {
console.log('Route 1');
document.getElementById('view').innerHTML = '<div><h1>Route 1</h1><p>Para 1</p><p>Para 2</p></div>';
},
route2: function () {
console.log('Route 2');
document.getElementById('view').innerHTML = '<div><h1>Route 1</h1><p>Para 1</p><p>Para 2</p></div>';
}
});

XMPP: AngularJs + Strophe.js

I have a basic XMPP client working on strophe.js.
On login I create handlers such as
connect = new Strophe.Connection('http://localhost/http-bind');
...
...
connect.addHandler(on_message, null, "message", "chat");
connect.addHandler(on_presence, null, "presence");
...
...
and then I "listen" to those
function on_presence(presence) {
// handling presence
}
function on_message(presence) {
// handling presence
}
So I am trying to "convert" it into AngularJS. The first part is pretty straight forward. I have a controller which handles the login part just fine:
angular.module('app').controller('loginCtrl', function($scope) {
connect = new Strophe.Connection('http://website.com/http-bind');
connect.connect(data.jid, data.password, function (status) {
if (status === Strophe.Status.CONNECTED) {
connect.addHandler(on_message, null, "message", "chat");
connect.addHandler(on_presence, null, "presence");
}
}
})
But how do I actually begin listening to those events (on_message, on_presence) in the context of angular across all the controllers I have.
Wrap Strophe in an Angular Service. Angular Services are meant to be use as singletons, so you will be able to instantiate the Strophe Service once, and use it everywhere (using Dependency Injection).
As suggested above (or bellow) I wrapped strophe in a service so my login "mechanism" looks like this:
.controller('loginCtrl', function(xmppAuth) {
xmppAuth.auth(login, password);
})
any my service:
.service('xmppAuth', function() {
return {
auth: function(login, password) {
connect = new Strophe.Connection('http://mydomain.net/http-bind');
connect.connect(login, password, function (status) {
if (status === Strophe.Status.CONNECTED) {
// we are in, addHandlers and stuff
}
}
}
}
})
Or may be you can create a module for Strophe and then include the module in your app, and then include strophe as a variable where ever you want to use it.

JsTestDriver assert when using requirejs in intellij

I was trying to write some javascript unit tests, using requirejs and jsTestDriver intellij plugin. When I run them in the IDE I have no error even when there are some. I only see them when opening my browser console.
Did someone manage to make IDE plugin displays failures into a require function ?
My code below and some screen shots illustrating my problem.
TestCase("Collections", {
"test User Collection": function () {
require(['lib/underscore', 'lib/backbone', 'app/user', 'app/collections'],
function (_, Backbone, user, appCollections) {
assertNotUndefined('Users must be defined', appCollections.users);
assertTypeOf('Users must be backbone collection', typeof Backbone.Collection, appCollections.users);
assertTypeOf("Users' model must be a user", typeof Backbone.Model, appCollections.users.model);
});
}
});
I haven't tested this, but it might get you started:
var CollectionsTest = AsyncTestCase('Collections');
CollectionsTest.prototype.testIt = function(queue) {
queue.call('Step 1', function(callbacks) {
function test1(_, Backbone, user, appCollections) {
assertNotUndefined('Users must be defined', appCollections.users);
assertTypeOf('Users must be backbone collection', typeof Backbone.Collection, appCollections.users);
assertTypeOf("Users' model must be a user", typeof Backbone.Model, appCollections.users.model);
}
var onModulesLoaded = callbacks.add(test1);
require(['lib/underscore', 'lib/backbone', 'app/user', 'app/collections'], onModulesLoaded);
});
};

Categories