Why Roles not checking if userIsInRole? - javascript

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.

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.

Realm.objects() in react-native app return empty objects

I'm creating a db in realm, but when i want to consult the data with Realm.objects() return empty objects, like this: {"0":{},"1":{},"2":{}...etc}, my code is the next:
import Realm from "realm";
const nombreEsquema = 'Imagen12';
class Imagen {}
let esquema = Imagen.schema = {
name: nombreEsquema,
properties: {
nombre: {
type: 'string'
},
uri: {
type: 'string'
},
url: {
type: 'string'
},
}
};
let dbRealm = Realm.open({
schema: [esquema]
});
functionRealm() {
dbRealm.then(realm => {
realm.write(() => {
realm.create(nombreEsquema, {
nombre: 'David',
url: 'My URL',
uri: 'My URI'
});
});
let images = realm.objects(nombreEsquema);
console.log("------------------------------");
for (let i of images) {
console.log(i);
}
});
}
i read the realm's documentation but i don't see anything with that problem, my realm version is 5.0.2, and i don't know what i'm doing bad, i hope you can help me with my problem.
So I had the same issue as well. I was able to resolve it by following these steps:
Upgrade the realm package to 5.0.3 yarn upgrade realm
Run npx react-native link realm (Realm does not fully support auto-linking yet)
Verify that the linking happened properly by following the instructions at the top of: https://realm.io/docs/javascript/latest/
Make sure to add this line --> import io.realm.react.RealmReactPackage; to the top of your MainApplication.java in android/app/src/main/java/com/<your-app-name>/MainApplication.java
<------------------------------------- || **Optional ** || ------------------------------------->
**You shouldn't have to do this, but just incase...
Check your package list in android/app/src/main/java/com/<your-app-name>/MainApplication.java to ensure it is configured as followed:
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
+ packages.add(new RealmReactPackage()); // <-- This line adds in the realm package.
packages.add(new RNSensitiveInfoPackage());
return packages;
}
cd into /android directory and clean by running ./gradlew clean
Re-compile and run again from your project's root directory npx react-native run-android
** If you get an error that looks something like this:
Native module realm tried to override realm for module name realm. If this was your intention, set canOverrideExistingModule=true
Open <your-app-name>/node_modules/realm/android/src/main/java/io/realm/react/RealmReactModule.java
Add the following lines inside the RealmReactModule class:
#Override
public boolean canOverrideExistingModule() {
return true;
}
Hope this helps! 🙂
Indeed you can just upgrade realm to 5.0.3 because there is a bug on 5.0.2
See on the release log: https://github.com/realm/realm-js/releases/tag/v5.0.3

Blazor Client Side and Okta Widget

Trying to use JavaScript Interop using Blazor client side.
The widget doesn't render.
I was hoping to setup an employee portal in Blazor, but wanted to use the Okta widget of course. Initially I just couldn't get the widget to render and now more problems. Will have to back track a little, but has anyone a clue how to render a javascript UI component within Blazor?
Also, I replaced the Okta config info with my own Okta developer instance info - not shown below...
#inject IJSRuntime JSRuntime
<h3>Employee Login</h3>
<div id="okta-signin-widget"></div>
#code {
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
JSRuntime.InvokeAsync<object>("RenderLogin", "OnAfterRender was Triggered");
}
}
}
RenderLogin is a tag in a JavaScript file OktaLogin.js
Inside an OktaLogin.js file (everything in the file is client side):
signInWidgetConfig = {
// Enable or disable widget functionality with the following options. Some of these features require additional configuration in your Okta admin settings. Detailed information can be found here: https://github.com/okta/okta-signin-widget#okta-sign-in-widget
// Look and feel changes:
logo: '//logo.clearbit.com/okta.com', // Try changing "okta.com" to other domains, like: "workday.com", "splunk.com", or "delmonte.com"
language: 'en', // Try: [fr, de, es, ja, zh-CN] Full list: https://github.com/okta/okta-signin-widget#language-and-text
i18n: {
//Overrides default text when using English. Override other languages by adding additional sections.
'en': {
'primaryauth.title': 'Sign In', // Changes the sign in text
'primaryauth.submit': 'Sign In' // Changes the sign in button
// More e.g. [primaryauth.username.placeholder, primaryauth.password.placeholder, needhelp, etc.].
// Full list here: https://github.com/okta/okta-signin-widget/blob/master/packages/#okta/i18n/dist/properties/login.properties
}
},
// Changes to widget functionality
features: {
registration: true, // Enable self-service registration flow
rememberMe: true, // Setting to false will remove the checkbox to save username
//multiOptionalFactorEnroll: true, // Allow users to enroll in multiple optional factors before finishing the authentication flow.
//selfServiceUnlock: true, // Will enable unlock in addition to forgotten password
//smsRecovery: true, // Enable SMS-based account recovery
//callRecovery: true, // Enable voice call-based account recovery
router: true // Leave this set to true for the API demo
},
baseUrl: 'https://live-widget.oktapreview.com',
clientId: '0oaexo9c530ZUVuOj0h7',
redirectUri: 'https://developer.okta.com/live-widget',
authParams: {
issuer: 'https://live-widget.oktapreview.com/oauth2/ausexqn31sz3HMxdf0h7',
responseType: ['id_token', 'token'],
scopes: ['openid', 'email', 'profile']
}
};
signInWidget = new OktaSignIn(signInWidgetConfig);
function widgetSuccessCallback(res) {
var key = '';
if (res[0]) {
key = Object.keys(res[0])[0];
signInWidget.tokenManager.add(key, res[0]);
}
if (res[1]) {
key = Object.keys(res[1])[0];
signInWidget.tokenManager.add(key, res[1]);
}
if (res.status === 'SUCCESS') {
var token = signInWidget.tokenManager.get(key);
console.log("Logged in to Okta and issued token:");
console.log(token);
console.log("Reload this page to start over.");
alert("Logged in! Check your developer console for details");
}
}
function widgetErrorCallback(err) {
}
RenderLogin:** signInWidget.renderEl({ el: '#widget-container' }, widgetSuccessCallback, widgetErrorCallback);

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

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');
}
});
}
},

Stripe javascript API Stripe.Recipients undefined

so I'm using Parse to handle a Stripe enabled app. We want our users to be able to cash out their in app credits, and we're planning on using Stripe to handle that. I've been able to create Customers in Stripe successfully, and link a bank account to these. Now I'm trying to initiate a transfer to one of these bank accounts, following
https://stripe.com/docs/tutorials/sending-transfers
But I'm running into an issue where Stripe.recipients is undefined.
Relevant code:
Initialization of Stripe:
var Stripe = require('stripe');
Stripe.initialize('sk_test_ukk7e8B46I39nxoUd6XILpPZ');
Parse Cloud Function for transferring:
Parse.Cloud.define("startTransfer", function(request, response) {
var userObjectId = request.params.userObjectId;
var credits = request.params.credits;
var StripeCustomer = Parse.Object.extend("StripeCustomer");
var stripeCustomerQuery = new Parse.Query(StripeCustomer);
stripeCustomerQuery.equalTo("userObj", userObjectId);
stripeCustomerQuery.find({
success: function(results) {
if(results.length == 0) {
} else if(results.length == 1) {
var customer = results[0];
// handle returning customer adding a new card
Stripe.Recipients.create({
name: customer.description,
type: "individual",
bank_account: customer.source,
email: customer.email
}, function(err, recipient) {
// recipient;
console.log("have a recipient");
if(err == nil) {
Stripe.transfers.create({
amount: credits,
currency: "usd",
recipient: recipient,
bank_account: customer.source,
statement_descriptor: "Cash Out"
}, function(err1, transfer) {
// asynchronously called
if(err == nil) {
response.success("Successfully transferred funds");
} else {
response.error(err1);
}
});
} else {
response.error(err);
}
});
}
}, error: function(error) {
reponse.error(error);
}
});
});
I'm calling this from iOS, using the PFCloud.callFunction API call. It seems to be hitting this code properly, but Recipients is said to be undefined in the error message, but the Stripe documentation requires it. How can I solve this?
Turns out, the Stripe cloud code module is indeed using an older version of Stripe. Therefore, according to this bug report, the solution is to download the newer SDK and manually add it to cloud code modules.
Source:
https://developers.facebook.com/bugs/523104684492016/
Actual post from the bug report (from Facebook employee):
Parse modules are using an old version of the API and there is no plan to update it in the near future.
As a workaround please download the newer SDKs directly off the third party site, place it in "cloud/" folder and import it using require();
We're going to close this by design.

Categories