I would like that every user who verifies his email in my app gets a certain role afterwards. I'm using the alanning:roles package. Anyway, after he clicks on the verification link that I have a function that sets a role in in Mongo for him.
so I found this function but its apparently only client side:
// (client-side)
Template.Homepage.created = function() {
if (Accounts._verifyEmailToken) {
Accounts.verifyEmail(Accounts._verifyEmailToken, function(err) {
if (err != null) {
if (err.message = 'Verify email link expired [403]') {
console.log('Sorry this verification link has expired.')
}
} else {
console.log('Thank you! Your email address has been confirmed.')
}
});
}
};
And I have the method for setting roles on the server side
Accounts.onCreateUser(function (options, user) {
Roles.setRolesOnUserObj(user, ['employer']);
if (options.profile) {
// include the user profile
user.profile = options.profile
}
How can I connect those two, or is there a better way for implementing this logic. I know this is now in the function "onCreateUser" but would put it seperatly if there is a better way.
First, install the matb33:collection-hooks package.
Then you can detect changes to the user's collection on the server:
var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
Meteor.users.after.update(function(userId, doc, fieldNames, modifier, options) {
if (indexOf.call(fieldNames, "emails") >= 0 && doc.emails) {
doc.emails.forEach(function(email) {
if (email.verified === true) {
// Verified address - do something....
}
});
}
});
Related
Here I have the code in my Nuxt middleware. The code works fine till I use the redirect function. As soon as I use redirect inside route checker if condition. It says the user is null.
In this image you can see in the console in client.js it shows User with all data but below that immediately it show User null in handle-login-route.js which is my middleware due to which redirect is not working.
Here is my middleware code
export default function ({ store, route, redirect}) {
const user = store.getters["user/user"];
const blockRouteAdmin = /\/admin\/*/g;
const blockRouteManager = /\/manager\/*/g;
const path = ["/signup", "/login"];
let value = path.includes(route.path);
console.log("User", user);
if (user) {
if (user.isAdmin) {
if (!route.path.match(blockRouteAdmin)) {
redirect("/admin");
}
}
if (user.isManager) {
if (!route.path.match(blockRouteManager)) {
redirect("/manager");
}
}
if (user.isUser) {
if (
route.path.match(blockRouteAdmin) ||
route.path.match(blockRouteManager) ||
value
) {
redirect("/");
}
}
}
if (!user) {
console.log("No user");
if (
route.path.match(blockRouteAdmin) ||
route.path.match(blockRouteManager)
) {
redirect("/");
} else {
redirect();
}
}
}
This Meteor app has the insecure and autopublish removed and accounts-password added.
It uses Accounts.createUser({username: someName, password: somePwrd});
It avoids using allow/deny and uses instead Meteor.call to insert documents because reading in the docs, it says that
Server code is trusted and isn't subject to allow and deny restrictions. That includes methods that are called with Meteor.call — they are expected to do their own access checking rather than relying on allow and deny.
But when I fire up the Meteor.logout(), I am still able to insert new documents to Tasks1 collection. How can that be? I though logout will stop inserting any new documents. How can I fix it? Thanks
///////////////////////////
//both/both.js
///////////////////////////
Tasks1 = new Mongo.Collection('tasks1');
///////////////////////////
//server/server.js
///////////////////////////
Meteor.publish('tasks1', function(){
return Tasks1.find({userId: this.userId});
});
Meteor.methods({
addTasks1: function (doc) {
Tasks1.insert(doc);
}
});
///////////////////////////
//client/client.js
///////////////////////////
Template.footer.events({
'click button': function () {
if ( this.text === "SUBMIT" ) {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
var params = {};
params[inputs[i].name] = inputs[i].value;
Meteor.call('addTasks1', params);
}
}
}
});
Template.mainMenu.events({
'click #logout': function () {
Meteor.logout();
}
});
In your server addTasks1 method, you should first check if the user is a user like so:
Meteor.methods({
addTasks1: function(doc) {
if (!Meteor.userId()) {
throw new Meteor.Error("Not Authorized");
} else {
Tasks1.insert(doc);
}
}
})
Logout alone doesn't stop users from being able to insert. You must edit your method code to achieve this.
addTasks1: function (doc) {
if (Meteor.userId()) {
Tasks1.insert(doc);
}
}
I have publish method that depends on user state:
Meteor.publish('myGroup', function () {
if (this.userId != null) {
var user = Meteor.users.findOne(this.userId);
return Group.find(user.profile.groupId);
} else {
return [];
}
});
When user state changes (user.profile.groupId), I don't get new data. I can fix it by refreshing the browser.
I was trying to fix that, by making subscription reactive:
Tracker.autorun(function () {
var user = Meteor.user(); // depend on user
if (user != null) {
Meteor.subscribe('myGroup');
}
});
But it doesn't seem to work. What is the best way to solve this problem?
Passing unused parameters seems to be the best workaround:
Meteor.subscribe("myGroup", user.profile.groupId);
As the title suggests I would like to provide functionality to allow a user to update the email they use to login to my app using Firebase Simple Login. Cannot figure out an elegant way to do this. App uses AngularFire if that is relevant.
Does one exist or do I need to create a new account and delete the old one using the $removeUser() and $createUser() methods?
Update for Firebase 2.1.x
The Firebase SDK now provides a changeEmail method.
var ref = new Firebase('https://<instance>.firebaseio.com');
ref.changeEmail({
oldEmail: 'kato#domain.com',
newEmail: 'kato2#kato.com' ,
password: '******'
}, function(err) {
console.log(err ? 'failed to change email: ' + err : 'changed email successfully!');
});
Historical answer for Firebase 1.x
In Simple Login, this is equivalent to changing the user's ID. So there is no way to do this on the fly. Simply create the new account, remove the old one as you have already suggested.
If you're user profiles in Firebase, you'll want to move those as well. Here's brute force, safe method to migrate an account, including user profiles. You could, naturally, improve upon this with some objectification and futures:
var ref = new Firebase('URL/user_profiles');
var auth = new FirebaseSimpleLogin(ref);
// assume user has logged in, or we obtained their old UID by
// looking up email address in our profiles
var oldUid = 'simplelogin:123';
moveUser( auth, ref, oldUid, '123#abc.com', '456#def.com', 'xxx' );
function moveUser( auth, usersRef, oldUid, oldId, newId, pass ) {
// execute activities in order; first we copy old paths to new
createLogin(function(user) {
copyProfile(user.uid, function() {
// and once they safely exist, then we can delete the old ones
removeOldProfile();
removeOldLogin();
});
});
function copyProfile(newId, next) {
ref.child(oldUid).once('value', function(snap) {
if( snap.val() !== null ) {
ref.child(newId, snap.val(), function(err) {
logError(err);
if( !err ) { next(); }
});
}
});
}
function removeOldProfile() {
ref.child(oldId).remove(logError);
}
function createLogin(next) {
auth.createUser(newId, pass, function(err, user) {
logError(err);
if( !err ) { next(user); }
});
}
function removeOldLogin() {
auth.removeUser(oldId, pass, logError);
}
}
function logError(err) {
if( err ) { console.error(err); }
}
I have made an facebook app. Now i need to take user information using a pop-up permission box. If a user has authenticated the app, facebook should not open dialog box for permission but if a user comes to app first time then it must open a dialog box. What I am trying to do here is...and getting error like...
Cannot call method 'showPermissionDialog' of undefined
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
alert("1");
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
//alert(uid);
var accessToken = response.authResponse.accessToken;
jQuery("#<%= accessToken.ClientID %>").val(accessToken);
// alert(accessToken);
fqlQuerynew();
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
alert('not_authorized');
OnRequestPermission();
} else {
alert("3");
//alert('the user isnt logged in to Facebook');
}
});
};
function OnRequestPermission() {
var myPermissions = "publish_stream, manage_pages"; // permissions your app needs
FB.Connect.showPermissionDialog("email,offline_access", function (perms) {
if (!perms) {
alert("hi");
// document.location.href = 'YouNeedToAuthorize.html';
} else {
alert("buy");
document.location.href = 'homePage.html';
}
});
}
If you have just copied and pasted it from your code then I think you have added one extra closing bracket after FB.getLoginStatus '};'.
After removing that try your code. If it doesn't work then can we know when you want to check login status like after clicking some social button or while loading page.
Here's a modified version of your code, I haven't tested it and it's not complete, but should give you an idea of what to do:
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
jQuery("#<%= accessToken.ClientID %>").val(accessToken);
fqlQuerynew();
} else if (response.status === 'not_authorized') {
OnRequestPermission();
} else {
...
}
});
function OnRequestPermission() {
var myPermissions = "publish_stream, manage_pages"; // permissions your app needs
FB.login(function(response) {
if (response.status === 'connected') {
FB.api("me/permissions", checkPermissions);
}
else {
....
}
}, { scope: "email,offline_access" });
}
function checkPermissions(response) {
if (response.data && response.data.legth == 1) {
var perms = response.data[0];
// iterate over perms and check if the user has all needed permissions
}
}