Email verify in sail.js - angularjs

I am trying to make a portal for filling up a form for which an applicant needs to create an account before filling out the form. The only issue is how can I stop from spamming the applicant creating account with fake mail. Is it possible to verify email in sail. I have done this in express using node mailer.
var express = require('express');
var nodemailer= require('nodemailer');
var app = express();
var smtpTransport = nodemailer.createTransport("SMTP", {
service: "Gmail",
auth: {
user: "email",
pass: "pass"
}
});
var rand, mailOptions, host, link;
/*---SMTP OVER---*/
/*--Routing Started--*/
app.get('/', function(req , res) {
res.sendfile('index.html');
});
app.get('/send', function(req , res) {
rand=Math.floor((Math.random() * 100) + 54);
host= req.get(host);
link="http://"+req.get('host')+"/verify?id="+rand;
mailOptions={
to : req.query.to,
subject : "Please confirm your Email account",
html : "Hello,<br> Please Click on the link to verify your email.<br>Click here to verify"
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
});
app.get('/verify',function(req,res){
console.log(req.protocol+":/"+req.get('host'));
if((req.protocol+"://"+req.get('host'))==("http://"+host))
{
console.log("Domain is matched. Information is from Authentic email");
if(req.query.id==rand)
{
console.log("email is verified");
res.end("<h1>Email "+mailOptions.to+" is been Successfully verified");
}
else
{
console.log("email is not verified");
res.end("<h1>Bad Request</h1>");
}
}
else
{
res.end("<h1>Request is from unknown source");
}
});
/*--------------------Routing Over----------------------------*/
app.listen(9999,function(){
console.log("Express Started on Port 3000");
});
Any help will be appreciated Thanks

You should be able to use nodemailer in sails pretty much the same, just change the app.gets into corresponding controller actions.
MailController.js:
module.exports = {
sendVerificationMail: function(req, res) {
// your app.get('/send') code
},
verifyEmail: function(req, res) {
// your app.get('/verify') code
}
}
As a side note, your verifying logic kinda breaks when another user tries to register before the first one has completed his registration:
First user requests for email verification, rand = 34 for example
Second user requests for email verification, rand = 58
First user tries to verify his email with id=34, verification fails since 34 !== 58

Related

Integrating Stripe JS with MEAN Stack Application

I'm trying to integrate stripe in my MEAN stack application. It's not communicating with Stripe to receive the token. I'm not sure why.
I have stripe source code sourced in my index.html page for my angular application.
It is not communicating with Stripe to receive the token, that console.log never fills, So I know it's not communicating with Stripe for some reason, but the same source code communicates with Stripe in a standalone application. I also believe it is failing when sending server side. I'm trying to send this request from port 3000 to port 8082.
Then I have the below script in another HTML page in my app for stripe:
Stripe.setPublishableKey('pk_test_******************');
var $btn = $('#submit');
$btn.on('click', function() {
$btn.prop('disabled', true);
$btn.button('progress');
var cardNum = $('#card-num').val();
var cardExp = $('#card-exp').val().split('/');
var cardCVC = $('#card-cvc').val();
// First submit the card information to Stripe to get back a token
console.log("starting stripe token");
Stripe.card.createToken({
number: cardNum,
exp_month: cardExp[0],
exp_year: cardExp[1],
cvc: cardCVC
}, function(status, response) {
var $form = $('#form');
var token = response.id;
console.log(response.id);
// Save the token into a hidden input field
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// Now submit the form to our server so it can make the charge against the token
$.post("http://localhost:8082/charge", $form.get(0), function(res) {
console.log("response from charge: " + res);
});
// All done!
$btn.addClass('btn-success').removeClass('btn-primary');
$btn.button('success');
setTimeout(function() {
$('#checkout').modal('hide');
}, 250);
});
return false;
});
I see the console.log response of starting stripe token but it doesn't actually communicate with stripe.
Then here is my server side code:
app.post('/charge', function(req, res) {
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/meanAuth", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
var stripeToken = req.body.stripeToken;
var amount = 1000;
stripe.charges.create({
card: stripeToken,
currency: 'usd',
amount: amount
},
function(err, charge) {
if (err) {
res.send(500, err);
} else {
res.send(204);
}
});
});
My reason for doing this is I'm trying to send user information in my request to the server side code so the server can update a value in my Mongo database.
I need help! Thanks in advance

Node / Angular Authentication

I'm trying to figure out how to authenticate a user using node.js and angular.js. I have a node server which has a route pointing to api/login. Users can register and log in everything works. But when I get to the client side, I have no idea where to go. I have set up a http interceptor which send the user back to the login page if a session doesn't exist. I am currently using session express. Below are snippets of my code:
Login Route:
router.post('/login', function(req, res, next) {
var username = req.body.username;
var password = req.body.password;
User.findOne({username: username, password: password}, function(err, user) {
if(err) {
console.log(err);
res.status(500).send();
}
if(!user) {
res.status(404).send();
} else {
console.log('Set' + user);
req.session.user = user;
res.status(200).send();
}
});
Protecting this endpoint:
app.get('/api/endpoint', function(req, res) {
if(!req.session.user) {
console.log('Unauthorized');
res.status(401).send();
} else {
console.log('Logged in');
res.status(200).send();
}
});
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', require('./routes/login'));
app.use('/api', require('./routes/register'));
app.listen(port);
I'm not sure if this is detailed enough but I know there's something really simple going wrong here I just cannot see it haha! Any help would be greatly appreciated!

How do I process responses from express with angular?

This is for a project for college. I am having difficulty understanding how to handle express responses with angular. My partner handled most of the back end and I took care of most of the front end, as to how to get information from express and use it on the front end. Our routing is below, if it will help.
// set variables for environment
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
//tell express to use the bodyParser middleware
app.use(bodyParser());
//start the mysql interface
var mysql = require('mysql');
var mysql = require('mysql');
var connectionPool = mysql.createPool({
host : 'localhost',
user : '<user>',
password : '<password>',
database : '<table>'
});
// connection.connect();
// connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
// if (err) throw err;
// console.log('The solution is: ', rows[0].solution);
// });
// connection.end();
// Set server port
app.listen(80);
console.log('server is running at 127.0.0.1:80');
// views as directory for all template files
app.set('views', path.join(__dirname, 'views'));
// instruct express to server up static assets
app.use(express.static('public'));
// set routes
app.get('/', function(req, res) {
res.sendFile(__dirname + '/views/index.html');
});
app.get('/:file', function(req, res) {
res.sendFile(__dirname + '/views/' + req.params.file);
});
app.get('/req/:itemname', function(req,res)
{
connectionPool.getConnection(function(err, connection)
{
if(err)
{
console.log('connection error: \n\n\n');
console.log(err);
res.statusCode = 503;
res.send({
result: 'error',
err: err.code
});
}
else
{
var query = 'SELECT * FROM Product WHERE name LIKE \'%' + req.params.itemname +'%\' ORDER BY ProductID asc';
console.log(query);
connection.query(query, req.params.id, function(err, rows, fields)
{
if(err)
{
console.log(err);
res.statusCode = 500;
res.send({
result: 'error',
err: err.code
});
}
else
{
res.send({
result: 'success',
err: '',
fields: fields,
json: rows,
length: rows.length
});
}
});
connection.release();
}
});
// connection.destroy();
});
app.post('/login/', function(req,res)
{
//debug for routes to make sure everything is working properly
console.log('I am in the login post route');
//connect to SQL pool
connectionPool.getConnection(function(err, connection)
{
if(err)
{
console.log('connection error: \n\n\n');
console.log(err);
res.statusCode = 503;
res.send({
result: 'error, having issue connecting to MYSQL DB instance',
err: err.code
});
}
else
{
var user = req.body.email;
user = user.toUpperCase();
var password = req.body.password;
console.log('user: ' + user);
console.log('password: ' + password);
var query = 'select COUNT(*) AS recordCount, isStaff from userTable where email = \''+user+'\' AND password = \''+password+'\'';
console.log(query);
connection.query(query, req.params.id, function(err, rows, fields)
{
if(err)
{
//another connection issue
console.log('in 500 error box')
console.log(err);
res.statusCode = 500;
res.send({
result: 'error',
err: err.code
});
}
else
{
//if the query was successful, we check to see if their exists a record of this query
//debug print count of records that match parameters
// console.log(rows[0].recordCount)
//if the return query has a user that has admin privileges, redirect them to the admin page
console.log(rows[0].isStaff);
if(rows[0].recordCount >=1 && rows[0].isStaff == 1)
{
console.log('at least one staff record')
res.sendFile(__dirname + '/views/admin.html')
// next();
}
else if(rows[0].recordCount >=1 && rows[0].isStaff == 0)
{
console.log('at least one nonstaff record')
res.sendFile(__dirname + '/views/customer.html')
// next();
}
else
{
console.log('invalid login')
console.log('in 503 error box, invalid user')
res.statusCode = 503;
res.send({
statuscode: '503',
result: 'E-mail or Password is incorrect',
});
}
}
});
connection.release();
}
});
});
Near the bottom of the code we specifically would like to handle the case when we have a login error. Right now it just sends back {{ statuscode: 503, result: 'E-mail or Password is incorrect'}} on a blank page.
On the front end a modal is displayed requesting sign in information. On success it redirects to a different page. On failure we would like to tell the front end to leave the modal on the page open and post an alert message in the body of the modal.
Please help.
Edit: The purpose of the project is working with the database. The project requires a web based app as the interface and since our next course requires using the MEAN stack we decided to go ahead and start learning a bit on our own.
In your $http call on the frontend, simply pass in a second argument as you error handling callback. The $http service will run that function any time the server sends back an error status.
https://docs.angularjs.org/api/ng/service/$http
$http.get('api/route')
.then(function successCallback(response) {
loginSuccessRedirect();
}, function errorCallback(response) {
handleLoginError();
});

posting scope variable through $http.post in angularjs

$http.post('/#/college', $scope.userb)
.success(function(data, status) {
console.log("Sent ok");
})
.error(function(data, status) {
console.log("Error");
})
[1]: http://i.stack.imgur.com/NlHyy.jpg
Is this the correct format/way to post my form data using http.post.?
The above code always returns "error" in the console.
please guide me to use http.post to post my form datathrough my controller.
var nodemailer = require("nodemailer");
var bodyparser = require("body-parser");
var app = express();
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "abc#gmail.com",
pass: "abc202"
}
});
var rand, mailOptions, host, link;
app.get('/#/college',function(req,res){
rand=Math.floor((Math.random() * 100) + 54);
host=req.get('host');
link="http://"+req.get('host')+"/verify?id="+rand;
mailOptions={
to : req.userb.counselloremail,
subject : "Please confirm your Email account",
html : "Hello,<br> Please Click on the link to verify your email.<br>Click here to verify"
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
app.use(morgan('dev'));
app.use(gzippo.staticGzip("" + __dirname + "/dist"));
app.listen(process.env.PORT || 5000);
I am trying to access the email address from the scope variable and post it so that i may send a confirmation mail that he is successfully registered now. Also I am sending the code of my web.js file that receives the posted data and sends the mail.
That URL you are posting to is not going to be valid.
If you are posting to another route in your app, the URL would just be #/college.
I'm also a little worried that you don't have anything setup to receive a post request, like on a server or anything. Could you give some more detail about what you are trying to do and your setup?
var dataObject = {
userid : LoginUserID
};
var responsePromise = $http.post(ApiAccessUrl+"/store/userstoreslist/", dataObject, {});
responsePromise.success(function(dataFromServer, status, headers, config)
{
var outputDate=angular.fromJson(dataFromServer);
});
responsePromise.error(function(data, status, headers, config) {
console.log("Error in fetching user store call!");
});
This is the correct way of sending data using http.post

how to restrict only admin to add user?

Iam new to express.js. I got strucked with problem of adding user only by admin. and also user should not bee add if admin logged out. Here is my code please can any one help me. Iam using express.js, mongodb.
it is server side code
route.js
app.route('/auth/signin').post(users.signin);
app.route('/auth/adduser').post(users.in,users.adduser);
express.js
This is my signin code
exports.signin = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err || !user) {
res.status(400).send(info);
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
req.session.value = user;
res.jsonp(user);
}
});
}
})(req, res, next);
};
This is adduser code
exports.in=function(req,res,next){
var user=req.session.value;
console.log('user details get from signin page'+JSON.stringify(user));
if(user.username===config.admin.username){
next(); //it goes to add user page
}
else{
res.send('your not a Admin');
}
};
exports.adduser = function(req, res) {
delete req.body.roles;
var user = new User(req.body);
var message = null;
// Add missing user fields
user.provider = 'local';
user.displayName = user.firstName + ' ' + user.lastName;
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(user);
console.log('user added');
}
});
};
But, while exceuting the code it gets error that req.session.value is undefined
i.e..,the data is not getting from signin page.
The main aim of posting this code is admin only has to add the user when he login .otherwise should send a message like you are not an admin or please login....
Actually passport sets the user on req object with logIn() method so you dont need this line
req.session.value = user; // remove this
and you can just get user on
console.log(req.user);
To verify this
Add this middleware in server.js or you app.js
app.use(function(req, res, next) {
console.log(req.user);
next();
});
here after the login occurs and authenticate plus logIn() methods are called , refreshing the page will console.log your user
Adding custom object/varaibles to session
to add user object or any thing else on session of passport you can do this as follow
req.session.passport.hi = "hello";
to verify this after adding this to session on subsequent page refresh see console when using following middleware
app.use(function(req, res, next) {
console.log(req.session.passport.hi);
next();
});

Resources