What am I doing wrong in my Accounts.createUser() configuration? - meteor

I cant seem to get beyond the Accounts.createUser() line in my code. What's wrong?
I have:
Router.route('/', {
template: 'info',
waitOn: function(){
return Meteor.subscribe('userData');
}
});
I am able to correctly see the results of Meteor.user().services.google.email in the browser console, which is my own email address since am logged in. Am also able to see the correct results for Meteor.user().services.google.accessToken.
And now for the code in subject:
Accounts.createUser({email: Meteor.user().services.google.email, password: Meteor.user().services.google.accessToken},
function( error ){
if(error){
console.log(error.reason, 'Stranger Danger!');
} else {
var userId = Meteor.userId();
console.log('Welcome!', 'success');
Meteor.call( "initApiKey", userId );
}
});
I cant seem to get beyond the Accounts.createUser() line. This is because, I fail to see any error messages, neither do I see the results of the console.log() which are the following functions/callbacks right in/after Accounts.createUser().

I don't understand exactly what you want to do with that code.
It seams that you are trying to create an user account with an account that already exists.
With the code: "email: Meteor.user().services.google.email, password: Meteor.user().services.google.accessToken" seams like you logged in with a google account and you created the email and password. And as you said, you are already logged in with that account, so why would you want to create another acount based in an already existed one ??
If you could explain just a little bit further what you want to accomplish and post any errors or messages from the server-side console, i think would be esier to get what is going on. But I think that even if you get the code right, the Accounts.createUser() will not allow you to create two accounts with the same email and password.

Related

Trouble returning a valid result while integrating Stripe API into my Meteor app

Here's the rundown:
I'm trying to run Stripe API on my Meteor app asynchronously
Long story short, everything works (i.e. subscription and charge is/are created normally and shows up in my Stripe dashboard)
When errors occur, the errors throw normally and show on client via user friendly alerts
I have a problem when there is a success and customer subscription is created, the result is not present in client and instead always returns as an error, despite it being a successful process
Here's what my method looks like on the server:
createCustomer: function(token, email, plan){
try{
let createCustomer = Meteor.wrapAsync(stripe.customers.create);
let result = createCustomer({
source: token,
email: email,
plan: plan
});
let subscription = {
customer: result.id,
sub: result.subscriptions.data[0].id,
plan: result.subscriptions.data[0].plan.name
};
Meteor.users.update({_id: Meteor.userId()}, {$set: subscription});
} catch(error){
if(error.code === "incorrect_cvc"){
throw new Meteor.Error("incorrect_cvc", error.message);
}
// More of such errors follows
}
}
Here's what it looks like on the client:
Stripe.card.createToken({
number: number,
cvc: cvc,
exp_month: exp,
exp_year: exp_year,
address_zip: zip,
address_country: country
}, function(status, response){
if(response.error){
console.log("Make sure all fields are filled before submitting order.");
} else{
let token = response.id;
Meteor.call("createCustomer", token, email, plan, function(error, result){
if(result){
console.log("Congratulations, everything worked!");
} else{
if(error.error === "incorrect_cvc"){
console.log("oops, the CSV is incorrect");
}
// More of such errors follow..
}
})
}
});
So, everything works in terms of when there is a real error, it throws fine on server + client. When user uses card, the charges are created and subscription is always created. HOWEVER, when there is a success and everything clicking fine, I still receive an error on client via callback and the result is never true or triggered. No idea why.
Not 100% up on Meteor, but it looks to me like your createCustomer method doesn't actually return anything, so the result from your (err, result) might never have anything in it?
As was mentioned in the comments, you might want to separate out the steps and wrap each in its own try-catch set so you can better isolate the issue.
Also, I feel like you could probably generalize your server-side error code to something like:
throw new Meteor.Error(error.error, error.message);
And I might even be tempted to do something like this, at least during testing/development - that way you can actually console.log() the original error in the browser:
throw new Meteor.Error(error.error, error.message, JSON.stringify(error));

User Not Found when trying to reset password

I have a user who forgot their password. Using the Accounts package the user tried to get their password reset with the "Reset password" function. When they enter their email address it states "User Not Found".
What is causing this? More importantly how do I fix it? I've been beating my head into a wall trying to find a solution so any help would be great. I've tried to duplicate but my test accounts don't have the same issue.
My build is Meteor 1.2 with the accounts-password and accounts-base packages. My setup is:
passwordSignupFields: "USERNAME_AND_EMAIL"
When resetting the user's password, Meteor tries to look up the user by the provided e-mail. If it cannot find the user using the e-mail - it throws the "User not found" - link to code here
Meteor.methods({forgotPassword: function (options) {
check(options, {email: String});
var user = Accounts.findUserByEmail(options.email);
if (!user)
throw new Meteor.Error(403, "User not found");
const emails = _.pluck(user.emails || [], 'address');
const caseSensitiveEmail = _.find(emails, email => {
return email.toLowerCase() === options.email.toLowerCase();
});
Accounts.sendResetPasswordEmail(user._id, caseSensitiveEmail);
}});
Is the user providing the correct e-mail? Check that the e-mail being provided actually exists in the DB in the Meteor.users collection

Firebase Authentication : Lookup a user by Email

I am using Firebase Authentication with Email and Password
I would like to know if i can 'lookup' a user by email only while also not being signed in as a user
The reason I'd like to do this is, is to simply identify if I am already a user of the system, using an email address only
I looked at this older thread but it appears to be the previous version of Firebase
Is it possible to do this in the current Firebase, or my alternative would be to keep this information available (and open to all?) to find out if a given email is part of my system?
I use fetchProvidersForEmail(email)
and if the result return as empty array then, this email hasn't been use to sign up.
firebase.auth().fetchProvidersForEmail(email)
.then(providers => {
if (providers.length === 0) {
// this email hasn't signed up yet
} else {
// has signed up
}
});
You can look up user information by email:
firebase.auth().getUserByEmail(email)
.then(function(userRecord) {
// See the UserRecord reference doc for the contents of userRecord.
console.log('Successfully fetched user data:', userRecord.toJSON());
})
.catch(function(error) {
console.log('Error fetching user data:', error);
});
I'd like to make things more clear that this method does not exist — one could be looking for it in the firebase client library, in which it has never been available in the first place and it wouldn't be a good idea to have anyway. This method is part of the admin SDK, so in order to call the method, you need to run it on the server, and invoke it from the client. OP didn't scope the question to firebase client library, so my answer is still correct.
Retrieve user data
The new method of creating users with email password returns a value whether the given email address is already in use. See here
import { fetchSignInMethodsForEmail } from 'firebase/auth'
fetchSignInMethodsForEmail(auth, registerEamil).then((result) =>{
console.log("result", result);
if (result.length === 0) {
Navigate("/authentication/select_role/" +
registerEamil)
} else {
Navigate('/')
}
Server side option:
https://cloud.google.com/identity-platform/docs/reference/rest/v1/projects.accounts/lookup
POST https://identitytoolkit.googleapis.com/v1/projects/{targetProjectId}/accounts:lookup
{ "email": ["rodneydangerfield#stackoverflow.kom"] }
As for today 2021 Nov. 18th, there is no way provided by the Firebase SDK to fetch a user by email.

Meteor: Resend email verification link

I want to be able to resend an email verification link to users of my Meteor application in case they accidentally delete their email verification email.
I have a link with the id "resentEmailVerificationLink"
I have the following code in my client for when the link is click (alerts are just there to show myself how far the function gets before an error):
Template.dashboard.events({
'click #resentEmailVerificationLink' : function(event) {
event.preventDefault();
var id = Meteor.userId();
alert('clicked: ' + id);
Accounts.sendVerificationEmail(id);
alert('Verification Email resent');
return false; // Stops page from reloading
}
)};
I know the sendVerificationEmail is a server function but I have no idea how to call this function in the server upon clicking the verify email link (I'm a bit of a Meteor newbie).
Any idea of how to accomplish this, because currently it doesn't work with the following error: Uncaught TypeError: Accounts.sendVerificationEmail is not a function
Note: Meteor.Accounts.sendVerificationEmail(id); doesn't work either (it does however produce a different error.
You can try with server side method just create one pass the attrs and call http://docs.meteor.com/#/full/accounts_sendverificationemail on the server. More about meteor methods: http://docs.meteor.com/#/full/meteor_methods

Meteor: Using iron router and custom authentication issue

I might have this pretty close but I'm lacking the knowledge to fix this last issue.
I wanted to use a custom authentication system instead of using accounts-ui so I could track some additional details about each user.
Everything worked great until I get to the resetPassword part. If a user submits their email address in the forgotPassword form, the email is received. But when you click the reset password link in the email it does not display the resetPassword template.
This is on SO here:
Meteor account email verify fails two ways
And the iron-router github issue tracker here (which has the most fixes though is more focused on the enrollmentemail than resetPassword which I'm assuming should be very similar):
Iron-router swallows Accounts.sendEnrollmentEmail
If I understand correctly from the iron-router issue tracker above, iron-router doesn't (or didn't and maybe still doesn't) support hashbang urls like that being sent in the reset password email. A URL like:
http://localhost:3000/#/reset-password/T4rPxcVNWKwBONHSRajSk7dNZvM_YRxTLyzxZVv5SuU
Meteor was then updated so that meteor accounts-base strips out everything after the # and stores them in variables in the Accounts namespace.
While I think I understand all of that, now the question is why I can't get the suggestions in the issue tracker to work for my reset password code. I'm using everything that is in the custom auth system by Julien Le Coupanec and then I've done the following from the issue tracker:
router.js
Router.map(function() {
this.route('invList', {path: '/'});
this.route('resetPassword', {
controller: 'AccountController',
path: '/reset-password/:token',
action: 'resetPassword'
});
});
AccountController = RouteController.extend({
resetPassword: function () {
Accounts.resetPassword(this.params.token, function () {
Router.go('/reset-password');
});
}
});
overrideaccounts.js in /server
(function () {
"use strict";
Accounts.urls.resetPassword = function (token) {
return Meteor.absoluteUrl('reset-password/' + token);
};
Accounts.urls.verifyEmail = function (token) {
return Meteor.absoluteUrl('verify-email/' + token);
};
Accounts.urls.enrollAccount = function (token) {
return Meteor.absoluteUrl('enroll-account/' + token);
};
})();
I'm wondering if the issues isn't related to either bad routing on my part (likely since I don't have my head wrapped around it well yet), if I put "server code" as is listed in the issue track in the right place, or if the session related code below is what is causing the resetPassword template to not display. Or something else that I'm missing of course.
main.js
//forgotPassword helper and event handler
Template.main.helpers({
showForgotPassword: function() {
return Session.get('showForgotPassword');
},
resetPassword: function(){
return Session.get('resetPassword');
}
});
After spending many hours on what I thought would be a really simple authentication system, I'm still at a loss. Appreciate any advice!
Don't struggle with hacking the hash and iron router, just back to Meteor original design flow.
When user click the verify link in email, it lead back to "/" (home), so just did this:
Template.home.created = function() {
if (Accounts._verifyEmailToken) {
Accounts.verifyEmail(Accounts._verifyEmailToken, function(err){
if (err != null) {
// handle the error
} else {
// do what you want, maybe redirec to some route show verify successful message
}
});
}
};
I did this and verify email right, same way worked for enroll, reset password...

Resources