Sending a welcome email parse cloudcode with mailgun - javascript

I have a working mailgun server in my parse cloudcode for an iOS app. I have set up a series of emails to be triggered by status changes in the database. I have now set up a welcome email that was formerly hard coded into the app. I have it set up as an afterSave however during the app the user is saved more than once, causing the welcome to be triggered. Is there a way I can only send this out once, or do I have to make it specific to a new user registering in the function if that is possible. Thanks.
Parse.Cloud.afterSave(Parse.User, function(request) {
console.log("aftersave fired");
if(!request.user.existed()){
var email = "Hello and welcome";
var subject = "Welcome to W!";
var recipient = request.user.get("email");
console.log(recipient);
Mailgun.sendEmail({
to: "#gmail.com",
from: "#gmail.com",
subject: subject,
text: email
}, {
success: function(httpResponse) {
response.success();
},
error: function(httpResponse) {
response.success();
}
});
}
});

You can do something as simple as set a flag in a new column on the User class which indicates that they have been welcomed. When the user is saved, check that flag and decide wether to send or not (and update the flag).

Related

Sending email to user upon registration in react

I am working on an app with React as the base. I have created a registration page and want to send a verification code via email to the user once he registers. I have done the UI part, but have no idea on how to proceed and make it work. I have seen how emails are sent to the user upon registration in PHP, and want to implement the same in React.
Since you are using node, you'll be able to make use of the node mailer package. This allows you to send emails easily straight from node.
https://nodemailer.com/
Have a look at there site for all the details on how to get it setup!
Here is some psuedo code:
User.register(userDetails).then( (createdUser) => {
// Your user is created
// Now lets send them an email
var mailOptions = {
from: '"Info ?" <yoursite#yoursite.com>', // sender address
to: userDetails.email, // This can also contain an array of emails
subject: 'Thanks for registering with <your site name>',
// text: 'Hello world ?', // plaintext body
html: '<b>Some HTML here....</b>' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
})

Node.js xmpp client gets "BAD_REGISTRATION" error as message response

What could possibly be wrong with this code? I'm trying to send push notification to my mobile device. No luck so far.. Made a little test with php and using GCM HTTP protocol to understand if my API's and passwords are correct - everything worked like a charm.. Here's my code snippet which is not working.
var xmpp = require('node-xmpp-client');
var ltx = require('ltx');
var options = {
jid: 'xxxxxxxxxxx#gcm.googleapis.com',
password: 'AIzaxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
port: 5235,
host: 'gcm.googleapis.com',
legacySSL: true,
preferredSaslMechanism: true
};
var xmppClient = new xmpp.Client(options);
xmppClient.connection.socket.setTimeout(0);
xmppClient.connection.socket.setKeepAlive(true, 10000);
xmppClient.on('online', function() {
var receiver = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxx-GnbkL2e5UlsS4utMw9rLTFrcsrhqxeH8xvzzzzzzzzzzzzzzzzzzzzzzz";
/*var rawmsg = '<message id=""><gcm xmlns="google:mobile:data">{"to":"' + receiver + '", "message_id":"m-xxxx123", "data": {"hello":"world"}, "time_to_live":600, "delay_while_idle": true, "delivery_receipt_requested": true }</gcm></message>';
var msg = ltx.parse(rawmsg);*/
var msg = new xmpp.Element('message', {id: ''}).c('gcm', {xmlns: 'google:mobile:data'}).t(JSON.stringify({
to: receiver,
message_id: 'm-xxxx123',
time_to_live: 600,
delay_while_idle: true,
delivery_receipt_requested: true
}));
xmppClient.send(msg);
............
............
}
And this is what comes back on 'stanza's event as a response.
........","message_id":"m-xxxx123","error":"BAD_REGISTRATION","error_description":""}' ],
Here are the possible causes of your error according to the documentation.
Invalid Registration Token
Check the format of the registration token you pass to the server. Make sure it matches the registration token the client app receives from registering with GCM. Do not truncate or add additional characters.
Mismatched Sender
A registration token is tied to a certain group of senders. When a client app registers for GCM, it must specify which senders are allowed to send messages. You should use one of those sender IDs when sending messages to the client app. If you switch to a different sender, the existing registration tokens won't work.

Parse Cloud: Send a notifications to a specific user

I'm currently implementing push notifications to follow user. Apparently, I managed to get push notifications done and responsive well.Hence, The notifications were sent to everyone.I would like to create push notifications and received the notification only by one respective user each time when other users have followed their user account.
I haven't create a pointer that should associate with User. Even If I create, is there any amendments that I should amends on my Cloudcode?
I would like to send push notifications to a specific user whenever other user has followed that user.
eg: Test 1 followed you.
Parse.Cloud.define("FollowersAndFollowing", function(request,result){
var query = new Parse.Query(Parse.User);
var message = request.params.message;
var pushQuery = new Parse.Query(Parse.Installation);
query.equalTo('userLink',request.params.User);
Parse.Push.send({
where: pushQuery,
data : {
alert: message,
badge: "Increment",
sound: "",
}
}, {
success: function(result) {
console.log(JSON.stringify(result));
response.success(result);
},
error: function(error) {
console.error(JSON.stringify(error));
response.error(error)
}
});
});
Above this ^ is my cloud code in .JS
if (status == false) {
// Create the push notification message.s
let pushMessage = "\(PFUser.currentUser()!.username!) has followed you."
// Submit the push notification.
PFCloud.callFunctionInBackground("FollowersAndFollowing", withParameters: ["message" : pushMessage, "User" : "\(userData.username!)"])
}
and above this is in swift code for frontend.
enter image description here
and the second the url is my class and subclasses of how I setting up
enter image description here
Use a cloud code beforeSave trigger on the Installation class to keep User pointers up to date.
// Make sure all installations point to the current user
Parse.Cloud.beforeSave(Parse.Installation, function(request, response) {
Parse.Cloud.useMasterKey();
if (request.user) {
request.object.set("user", request.user);
} else {
request.object.unset("user");
}
response.success();
});
You may also want to use an afterSave trigger on your Follow class to send out the push notification instead of calling a cloud function. Without knowing the structure of that class or how you have implemented a follower/following scheme it's hard to give any further information.

Parse main.js Mandrill HTML mail sending issue

I have a cloud function on Parse in main.js where I send mail as HTML encoded with Mandrill API. I call this function through my iOS app posting some parameters and its perfectly ok, sends the email. However I want to localize the HTML body depending on the language of user. Since I checked the iOS in-line HTML options which are very tricky, I'm trying to do it in my sendMail function on main.js:
Parse.Cloud.define("sendMail", function(request, response) {
var Mandrill = require('mandrill');
Mandrill.initialize('APP_ID');
var locale = request.params.locale;
var userName = request.params.user;
var password = request.params.pass;
var HTMLBodyEn = '<p>text</p>';
var HTMLBody = HTMLBodyEn;
if (locale == 'tr') {
HTMLBody = '<p>yazı</p>';
}
Mandrill.sendEmail({
message: {
html: HTMLBody,
subject: request.params.subject,
from_email: request.params.fromEmail,
from_name: request.params.fromName,
to: [
{
email: request.params.toEmail,
name: request.params.toName
}
]
},
async: true
},{
success: function(httpResponse) {
console.log(httpResponse);
response.success("Email sent!");
},
error: function(httpResponse) {
console.error(httpResponse);
response.error("Uh oh, something went wrong");
}
});
});
Well it's simple as that. If condition you see there causes all the problem... As you can see there I'm receiving a locale key to change the body but it doesn't and Parse returns 141 error code which means after some digging is a time-out exception.
I can't seem to understand that a simple if statement as that causes a timeout.
Can anyone help me on this? Encountered anything similar?
You might be experiencing side effects from a text encoding issue. The Mandrill SDK on parse doesn't appear to handle the charset you're using. Take a look at this post from their forums that offers a workaround for that problem.
https://www.parse.com/questions/sometimes-getting-mandrill-you-must-specify-a-key-value-error-when-sending-email

backbone.js - handling if a user is logged in or not

Firstly, should the static page that is served for the app be the login page?
Secondly, my server side code is fine (it won't give any data that the user shouldn't be able to see). But how do I make my app know that if the user is not logged in, to go back to a login form?
I use the session concept to control user login state.
I have a SessionModel and SessionCollection like this:
SessionModel = Backbone.Model.extend({
defaults: {
sessionId: "",
userName: "",
password: "",
userId: ""
},
isAuthorized: function(){
return Boolean(this.get("sessionId"));
}
});
On app start, I initialize a globally available variable, activeSession. At start this session is unauthorized and any views binding to this model instance can render accordingly. On login attempt, I first logout by invalidating the session.
logout = function(){
window.activeSession.id = "";
window.activeSession.clear();
}
This will trigger any views that listen to the activeSession and will put my mainView into login mode where it will put up a login prompt. I then get the userName and password from the user and set them on the activeSession like this:
login = function(userName, password){
window.activeSession.set(
{
userName: userName,
password: password
},{
silent:true
}
);
window.activeSession.save();
}
This will trigger an update to the server through backbone.sync. On the server, I have the session resource POST action setup so that it checks the userName and password. If valid, it fills out the user details on the session, sets a unique session id and removes the password and then sends back the result.
My backbone.sync is then setup to add the sessionId of window.activeSession to any outgoing request to the server. If the session Id is invalid on the server, it sends back an HTTP 401, which triggers a logout(), leading to the showing of the login prompt.
We're not quite done implementing this yet, so there may be errors in the logic, but basically, this is how we approach it. Also, the above code is not our actual code, as it contains a little more handling logic, but it's the gist of it.
I have a backend call that my client-side code that my static page (index.php) makes to check whether the current user is logged in. Let's say you have a backend call at api/auth/logged_in which returns HTTP status code 200 if the user is logged in or 400 otherwise (using cookie-based sessions):
appController.checkUser(function(isLoggedIn){
if(!isLoggedIn) {
window.location.hash = "login";
}
Backbone.history.start();
});
...
window.AppController = Backbone.Controller.extend({
checkUser: function(callback) {
var that = this;
$.ajax("api/auth/logged_in", {
type: "GET",
dataType: "json",
success: function() {
return callback(true);
},
error: function() {
return callback(false);
}
});
}
});
Here is a very good tutorial for it http://clintberry.com/2012/backbone-js-apps-authentication-tutorial/
I think you should not only control the html display but also control the display data. Because user can use firefox to change your javascript code.
For detail, you should give user a token after he log in and every time he or she visit your component in page such as data grid or tree or something like that, the page must fetch these data (maybe in json) from your webservice, and the webservice will check this token, if the token is incorrect or past due you shouldn't give user data instead you should give a error message. So that user can't crack your security even if he or she use firebug to change js code.
That might be help to you.
I think you should do this server sided only... There are many chances of getting it hacked unit and unless you have some sort of amazing api responding to it

Categories

Resources