Do I need to put createUser code in a meteor method? - javascript

I'm writing a meteor app and working on my user registration template.
Currently I have the following code, imported on the client:
Template.register.events({
'submit form': function(event){
event.preventDefault();
let username = $('[id=input-username').val();
let email = $('[id=input-email]').val();
let password = $('[id=input-password]').val();
Accounts.createUser({
username: username,
email: email,
password: password
}, function(error){
if(error){
Bert.alert( "That username or email is either taken or invalid. Try again.", 'danger', 'growl-top-right' );
// console.log(error.reason);
}
else {
FlowRouter.go('mainLayout');
}
});
}
});
My question is, is it ok to have the Accounts.createUser code on the client or do I need to call this from a meteor method imported on the server? In my head I'm thinking a user can register as many times as they like with different emails / usernames therefore what's the harm in having the code on the client vs making a call to the server.
Thoughts welcome.

CreateUser is designed to be used from the client. It handles the encryption of the password before it is sent to the server.

You can do validations at client side to save time but ideally you should write the code in meteor method on server side and call it on client side via Meteor.call(). In your case I can simply add users using chrome console and can loop it to million times to add random stuff in your db. Csrf attacks are mostly welcome this way. You should also specify collections.allow() and collections.deny() when you are defining a new Mongo.Collection(). Also you should remove autopublish and insecure package from meteor project.

Related

Is there a way to get ethereal email message ID in node.js through SendGrid?

I'm currently using SendGrid as an email service in a web app, and I want to set up my dev environment to send emails to https://ethereal.email/ so I can make sure they look correct. The way I currently have it set up is I'll use nodemailer.createTestAccount() on startup, then log the credentials, then if I need to see the emails I have to manually go to the ethereal site to log in and view all the emails.
Since I'm using SendGrid to send the messages I can't just use nodemailer.getTestMessageUrl(info), but I would really like to be able to just log the URL every time an email is sent in dev then I could just go directly to the message.
I've already tried printing the SendGrid response, as well as connecting via IMAP and loading the most recent message but neither of those contain the message ID anywhere that I can see.
Is there any way to get the message ID of an email sent to ethereal.email and construct a URL directly to the message?
My environment is node.js and I'm using #sendgrid/mail to send messages.
Thanks!
Twilio SendGrid developer evangelist here.
The Nodemailer documentation here suggests that you use ethereal.email as your SMTP settings in development. Then you can use nodemailer.getTestMessageUrl(info) to get the right URL.
You say you are using #sendgrid/mail to send messages, which won't respond with the URL as it is not sent out through the ethereal.email SMTP server. If you do want that URL, your best bet is to replace SendGrid in your development/test environment with ethereal.email.
You could do this by creating your own email sending objects with the same interface, one for #sendgrid/mail and one for Nodemailer with ethereal.email credentials and load the object you want based on the environment.
For example:
class SendGridEmail {
constructor(sgApiKey) {
// construct SG mail object
}
sendEmail(options) {
// use SG mail object to send email
}
}
class NodemailerEmail {
constructor() {
}
sendEmail(options) {
}
}
function getMailer() {
if (process.env.NODE_ENV === "production") {
return new SendGridEmail(process.env.SG_API_KEY);
} else {
return new NodemailerEmail();
}
}
// later
getMailer().sendEmail(options);

Is it possible to authenticate my credentials through console when the app starts?

I'm setting up a simple "fire and forget" kind of back-end app running on a DigitalOcean droplet. I want to start the app, enter a username and password into the console, and reuse that username and password later without entering data. Essentially, the app simply monitors various GitHub repositories for pull requests, reads comments and checks for "yes" or "no" votes from contributors, and then merges or closes that pull request based on majority vote.
The issue I have right now is that because the app has no UI, I can't figure out how to request a username and password from the user.
Ideally, I'd like to open the console, run the app, and then the first thing the app does is ask for a username and password in the console. It would then simply use the entered data as a variable for authentication later on down the line.
This is my very first time dealing with authentication (I'm about 3 months into JS programming). Any help is appreciated.
const loginUsername = ()=> {
//ask for username in this function
return username;
};
const loginPassword = ()=> {
//ask for password in this function
return password;
};
Later on in the app:
if(votesYes >= majorityVotes){
console.log('The request has been accepted.')
axios({
method: 'put',
url: `${pullRequestUrl}/${pull.number}/merge`,
auth: {
username: loginUsername,
password: loginPassword
}
})
As it stands right now, if I manually type in my username and password into the code, it all works swimmingly. But, given that the repo is public, I'd like to not include that data in the code.

Auth0 email confirmation, how to handle registration gracefuly

I am using auth0.
My app requires users to confirm their email.
When a user registers, he receives this alert:
Error: unauthorized. Check the console for further details.
This is because the user has not yet verified his email.
How do I "catch" this event / alert in order to redirect the user to a view of my choice?
Thank you for your help
There is a couple of different parts to this.
1). have you enabled the email verified rule? (it is a template available from Auth0 dashboard -
function forceEmailVerification(user, context, callback) {
console.log("force-email-verification");
if(context.connection !== "MyDB") {
return callback(null, user, context);
}
if (!user.email_verified) {
return callback(new UnauthorizedError('Please verify your email before logging in.'));
} else {
return callback(null, user, context);
}
}
That effectively raises an exception in the Rules pipeline if email not verified. It will return the error to your application on the callbackUrl you provide as two query params - error and error_description. It is then up to you how you handle this - Here is a sample Node.js application I wrote specifically to illustrate how this works - In the sample, i am using some express middleware to check for the error and error_description and forward to a Custom controller / view if detected.
2). Only if needed, you can also explicitly trigger an email verification email. It is a POST request to https://{{tenant}}.auth0.com/api/users/{{user_id}}/send_verification_email
endpoint, passing an Authorization Bearer header with an Auth0 APIv1 token (and empty body). The token can be obtained by making a POST request to https://{{tenant}}.auth0.com/oauth/token endpoint passing body of the form:
{
"client_id": "{GLOBAL CLIENT ID}",
"client_secret": "{GLOBAL CLIENT SECRET}",
"grant_type": "client_credentials"
}
You can get the global client id and client secret under account settings -> advanced from Auth0 dashboard. Please do NOT store any secrets on SPA apps etc - using this endpoint should only be done from Client Confidential / Trusted applications (e.g traditional MVC webapp you own).
Hope this helps. Please leave comments if anything unclear.

Can an access token returned by Facebook to the Javascript SDK work server-side with the PHP SDK?

I'm building a website that makes use of Facebook connect. I'm authenticating users client-side with the javascript SDK and calling an AJAX method on my server every time a user logs in to check if the user is known to my app, and if the user is new to store their FBID in my database to register them as a new user.
My question is: Can the access token returned by Facebook to the Javascript SDK be used server-side (with the PHP SDK for example)? Can I send the access token string to the server via an AJAX call, store it in my database (along with a timestamp so I know how long it's valid for) and then use it to make calls to the graph API server-side? Is this even a logical thing to do?
Yes, this should work. Look at this question: How to properly handle session and access token with Facebook PHP SDK 3.0?
This is a workaround for the old JS and new PHP SDK. In my app I send the access token generated by the JS SDK via a form to my PHP. I have no doubts that this also works by sending the access token via ajax!
Using Jquery:
//Set an error message
var oops = ("Put your something went wrong message here.");
//Function to post the data to the server
function save(uid, accessToken){
$.post("../foo/bar", { uid: uid, access_token: accessToken, etc, etc }, function(data){
alert("Successfully connected to Facebook.");
location.reload();
}, "text");
}
function handler(x){
if (x.authResponse){
var token = x.authResponse.accessToken;
var uid = x.authResponse.id;
FB.api("/me/accounts", {access_token: token},
function(response){
if(response.data.length == 0) {
//Regular facebook user with one account (profile)
save(uid, token);
}else{
//Handle multiple accounts (if you want access to pages, groups, etc)
}
});
}else{
alert(oops);
}
}
FB.login(handler, {scope: 'The list of permissions you are requesting goes here'});
Any improvement suggestions are always appreciated.

node_mailer doesn't return err but email not sent

I can't quite figure this out one... I have a SMTP server that's hosted on the same network as me, I can ping it and attempt to send emails, but the actual email never comes through. I'm using node_mailer... During the callback no error is returned... There is no authentication on the server as it's only used internally, and I'm not sure if that's maybe part of the problem. It works via ASP, but I'd like to get it working with Node.js
My script is basically just this:
email.send({
host : "theaddressoftheserver(can ping)",
port : "25",
domain : "theaddressoftheserver(can ping)",
to : "Some#internalEmail.com",
from : "Some#internalEmail.com",
subject : "Test",
body: "Test"
},
function(err, result){
if(err) console.log(err);
else console.log("Appears to have sent...");
});
I would recommend you to use Postmark.
Postmark helps small and large web applications deliver and track transactional email. Stop worrying about setup, delivery, and server maintenance. We already excel at this.
There are already two Postmark libraries for Node.js.
Postmark.js by Chris Williams
node-postmark by David Pitman
Example
var postmark = require("postmark")("YOURAPIKEY");
postmark.send({
"From": "donotreply#example.com",
"To": "target#example.us",
"Subject": "Test",
"TextBody": "Test Message"
});
I recently answered a similar question, it might help you:
https://stackoverflow.com/a/12623787/340736
Unfortunately, it's kind of hard to know exactly where your problem lies. Is the ASP-script on the same server? Have you tried running telnet against the server and sending it manually? Do the Node process have firewall restrictions?
One thing that comes to mind is that if you say that your ASP-script works, and that your SMTP-server uses no authentication. But could it be that is is, and that it is impersonating your user (the user in which the ASP-process is running under) and authenticating with that (AD authentication)..
Just a wild guess.
I figured node_mailer to send emails from a gmail account. I used code,
const transporter = createTransport({
service: gmail,
auth: {
user: process.env.MAILADDRESS,
pass: process.env.MAILPASSWORD
}
});
let mailOptions = {
from: process.env.MAILADDRESS,
to: recipient#email.com,
subject: 'verification code for verify email',
text: 'verification code
}
transporter.sendMail(mailOptions, function(err, info){
if (err) {
// something
} else {
// something
}
})
This is simple. In order to make this work I had to make sure Gmail account's Less secure app access on before using that email. I'm talking about the email that I user to send email. (Sender's email).
So my point is if there is any security option in your SMTP server that's hosted on your same network, you need to turn it off in order to node_mailer to use email address.

Categories