How can i prevent User from directly accessing the HTML page - rest

I have got a set 3 HTML Pages
I am using Apache Tomcat 7 server . I have got the following HTML pages (All are HTML pages only)
login.html
sales.html
index.html
The code for the login.html is when clicked on submit is
<input type="email" name="email" id="email" >
<input type="pin" name="email" id="pin" >
<button class="primary login-btn">Submit</button>
Once clicked on Submit button , i am calling a Jersey REST Webservce this way and will response either true OR false based on the values present in our Database
function submitLoginForm() {
var email_input = $.trim($("#email").val());
var pin_input = $.trim($("#pin").val());
var logininfo = {
'email': email_input,
'pin': pin_input
};
var login_information = JSON.stringify(logininfo);
$.ajax({
type: 'POST',
dataType: 'json',
data: login_information,
url: url + '/HEGS/orn/webchecklogin',
success: function(response) {
// if true , redirect to sales.html page
window.location = "index.html"
},
});
}
All this is working fine , my issue is , how can i stop the prevent the user from accessing the page directly
For example if he types the follwing URL
http:localhost:8080/HEGS/dealer/sales.html

You would want to redirect the url to one file, which would then load the correct file based on the criteria you set. I don't know much about Tomcat, but this article seems to explain it well under the "URL Rewriting" section.

Related

phonegap submit form, how to send to my email

I am building simple phonegap android app.
i make simple html form with few input fields (Name, Last name, Question).
I want that when user fill input fields (Name, Last name, Question) and click Submit to send to my email address. Just that.
Do you have any idea how to do that with phonegap?
Thank you
You could do it easily by using php or .net (as your selection) with AJAX Call
Just Create One HTML page which display form to User for filling up data and send it.
Here I saw you how I done with PHP (Use phpmailer. for more, visit : http://phpmailer.worxware.com/index.php?pg=examplebmail)
HTML Form
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form action="#!" method="post">
<input type = "text" name="cname" />
<input type = "number" name="cnumber" />
<input type = "email" name="cemail" />
<input type = "submit" value="Submit" onclick="UpdateRecord()" />
</form>
<script>
function UpdateRecord()
{
// Social Links
GolbalURL = "http://www.yourserverpathtophpfile.com";
var cname = $("[name='cname']").val();
var cnumber = $("[name='cnumber']").val();
var cemail = $("[name='cemail']").val();
jQuery.ajax({
type: "POST",
url: GolbalURL+"sendemail.php",
data: "cname="+ cname+"& cnumber="+ cnumber+"& cemail="+ cemail,
dataType: "html",
cache: false,
success: function(response)
{
alert("Email Sent");
}
});
}
</script>
</body>
</html>
Sendmail.php
<?php
$cname = $_REQUEST['cname'];
$cnumber = $_REQUEST['cnumber'];
$cemail = $_REQUEST['cemail'];
require_once('class.phpmailer.php');
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = "Name : ".$cname."Number : ".$cnumber."Email : ".$cemail;
$mail->SetFrom($cemail, $cname);
$address = "youremail#id.com";
$mail->AddAddress($address, "Your Name");
$mail->Subject = "Your Subject";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
Do not forgot to upload your dynamic files to server and give it permissions. Or You can also call device's default mail application from code, check PHONEGAP EMAIL COMPOSER
GIT Link Of Email Compo.
https://github.com/katzer/cordova-plugin-email-composer/blob/172605ee12e58d5e5809e4e031b3b96cead143ac/README.md
You can do using Cordova EmailComposer Plugin for Android . Add this function on your submit button click. For installation follow these steps .
https://github.com/katzer/cordova-plugin-email-composer
function emailComposer(){
window.plugin.email.isServiceAvailable(
function (isAvailable) {
if(isAvailable){
window.plugin.email.open({
to: [''],
cc: [''],
bcc: [''],
subject: '',
body: ''
});
}else{
alert('Service is not available');
}
}
);
}
**JQUERY - CALL PHP SCRIPT TO POST DATA**
var ajax_call = serviceURL;
var form_data = $('#form').serialize();
$.ajax({
type: "POST",
url: ajax_call,
data: form_data,
dataType: "json",
success: function(response) {
//called when successful
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
Examples
There are plugins to compose emails, but it won't send it automatically. You really need to use a back end service to handle this for you. You can setup your own using any app language (PHP, ColdFusion, etc), or consider a service like WuFoo perhaps.

How to fix TypeError: Cannot read property 'name' from Express Nodemailer

So I do want to say that I've been searching for the answer for this and I've also tried to console.log my req.body post form and I keep getting undefined. So I feel that I'm losing the data from the form I send, I'm not sure what I"m doing wrong. So time to show some code.
As a note: I am using Handlebars for my Express Setup.
app.js
var express = require('express'),
exphbr = require('express3-handlebars'), // "express3-handlebars"
nodemailer = require('nodemailer'),
helpers = require('./lib/helpers'),
app = express(), handlebars;
// Create `ExpressHandlebars` instance with a default layout.
handlebars = exphbr.create({
defaultLayout: 'main',
helpers : helpers,
extname : '.html',
// Uses multiple partials dirs, templates in "shared/templates/" are shared
// with the client-side of the app (see below).
partialsDir: [
'views/shared/',
'views/partials/'
]
});
// Register `hbs` as our view engine using its bound `engine()` function.
app.engine('html', handlebars.engine);
app.set('view engine', 'html');
require("./routes")(app, express, nodemailer);
app.listen(3000);
routes.js
module.exports = function (app, express, nodemailer) {
// set up the routes themselves
app.get('/', function (req, res) {
res.render('home', {
title: 'Larry King Orchestra'
});
});
// I cut out a majority of my routes to make this easier to read.
// SEND EMAIL FROM FORM
app.post('/', function (req, res) {
console.log("WTF");
console.log(req.body.name);
console.log(req.body.email);
var mailOpts, smtpTrans;
//Setup nodemailer transport, I chose gmail. Create an application-specific password to avoid problems.
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "email#gmail.com",
pass: "password"
}
});
//Mail options
mailOpts = {
from: req.body.email, //grab form data from the request body object
to: 'anotheremail#gmail.com',
subject: 'LKO Contact Form',
html: 'From: ' + req.body.name + ' <' + req.body.email + '> <br>Phone: ' + req.body.tel + '<br>Date of Event: ' + req.body.date + '<br>Location: ' + req.body.location + '<br>Details & Comments:<br>' + req.body.message + '<br><br><p>Email form provided by WavaMedia.'
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.render('home', {
title: 'Larry King Orchestra',
msg: 'Error occured, message not sent.',
err: true,
page: 'home'
});
}
//Yay!! Email sent
else {
res.render('home', {
title: 'Larry King Orchestra',
msg: 'Message sent! Thank you.',
err: false,
page: 'home'
});
}
});
});
// STATIC ROUTE FOR ASSESTS
app.use(express.static('assests/'));
};
I renamed the handlebars extension to be .html and I have the main layout using partials. SO app.get('/') will show this next file as a partial, and render it on the page.
contact.html
<form class="contact" action="/" method="post">
<label for="name">Name</label>
<input type="name" name="name" id="name">
<label for="email">Your Email (required)</label>
<input type="email" name="email" id="email">
<label for="tel">Phone Number</label>
<input type="tel" name="tel" id="tel">
<label for="date">Date of Your Event</label>
<input type="date" name="date" id="date">
<label for="location">Venue/Location</label>
<input type="location" name="location" id="location">
<label for-"message">Details & Comments</label>
<textarea name="message" id="message" rows="3"></textarea>
<input type="submit" name="submit" id="submit" value="Send" class="btn btn-default">
</form>
My Error:
TypeError: Cannot read property 'name' of undefined at c:\xampp\htdocs\lko\routes.js:129:26 at callbacks (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:164:37) at param (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:138:11) at pass (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:145:5) at Router._dispatch (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:173:5) at Object.router (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:33:10) at next (c:\xampp\htdocs\lko\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.expressInit [as handle] (c:\xampp\htdocs\lko\node_modules\express\lib\middleware.js:30:5) at next (c:\xampp\htdocs\lko\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.query [as handle] (c:\xampp\htdocs\lko\node_modules\express\node_modules\connect\lib\middleware\query.js:45:5)
So I'm not sure where I'm going wrong with the code. I believe the form is sending data to my node app, but where it's going, I'm not sure. I've setup the post method and so far no luck :( I have been trying for a couple days now. I have nodemailer installed as well. I've restarted the server, updated node and npm.
JavaScript Node Guru Masters, only you can show me the light! And thanks for reading though all of this, totally awesome!
app.use(express.bodyParser());
add that to your app.js
that's what grabs information from the post data form.
You have to require body parser package for this.
At first you have to install it with npm.
$ npm install --save body-parser
Then require that in your js file.
var bodyParser = require('body-parser');
Then add the parser. As you are using html post method it uses urlencoded as encoding type. For that add this line.
var urlencodedParser = bodyParser.urlencoded({ extended: false });
(If you use json you must use bodyParser.json() instead of this)
Now add the parser with the encoding type to app.post method as follows.
app.post('/',urlencodedParser, function (req, res) {
//your code here
});
You don't have to be explicitly mention any bodyParser or bodyParer.json
Instead You can make it simple to use this because this is a built-in middleware function in Express.
app.use(express.json());
app.use(bodyparser.urlencoded({extended : true }));

When clicking on login with facebook/persona button with angularFire v0.5.0 ($firebaseAuth) user gets redirected immediately to '/'.Why?

My problem is simple, everything in this code works as expected except that everytime, I click on login button, I get redirected to '/'. I do not want that. I want the user to stay on login page until they finish authenticating via facebook/persona/twitter and then get redirected to '/content'.
Here is my router/app/controllers:
var app = angular.module("myapp", ["ngRoute","firebase"]);
app.config(['$routeProvider',function($routeProvider){
$routeProvider.when('/',{
templateUrl: 'landing.html',
});
$routeProvider.when('/login',{
templateUrl: 'login.html',
controller: 'controller'
});
$routeProvider.when('/content',{
authRequired: true,
templateUrl: 'content.html',
controller: 'MyController'
});
$routeProvider.otherwise({redirectTo: '/'});
}]);
app.controller('MyController',['$scope', '$firebase','$firebaseAuth',function($scope,$firebase,$firebaseAuth) {
var ref = new Firebase("https://mybase.firebaseio.com/");
$scope.auth = $firebaseAuth(ref,{path: '/'});
$scope.messages = $firebase(ref);
$scope.addMessage = function(e) {
if (e.keyCode != 13) return;
$scope.messages.$add({from: $scope.name, body: $scope.msg});
$scope.msg = "";
};
}]);
app.controller('controller',['$scope','$firebaseAuth',function($scope, $firebaseAuth) {
var ref = new Firebase('https://mybase.firebaseio.com/');
$scope.auth = $firebaseAuth(ref);
}]);
This (my preferred solution) didnt work either:
.controller('LoginCtrl',['$scope','$firebase','$firebaseAuth','$location',function($scope,$firebase,$firebaseAuth,$location, waitForAuth){
var ref = new Firebase('https://myfirebase.firebaseio.com/');
$scope.auth = $firebaseAuth(ref,{path: '/'});
waitForAuth.then(function(user){
$location.path('/content');
})
}])
My div/button looks as follows (I also have similar one but with 'persona'.):
<div ng-controller="controller">
<div class="facebook-login">
<span><i class="fa fa-facebook-square fa-lg"></i> LogIn with Facebook</span>
</div>
<div class="facebook-login">
<span><i class="fa fa-facebook-square fa-lg"></i> LogIn with Persona</span>
</div>
</div>
I have included the following in my html:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<script src="//cdn.firebase.com/v0/firebase.js"></script>
<script src="//cdn.firebase.com/v0/firebase-simple-login.js"></script>
<script src="//cdn.firebase.com/libs/angularfire/0.5.0/angularfire.min.js"></script>
<script src="//code.angularjs.org/1.2.6/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/module.waitForAuth.js"></script>
<script src="//login.persona.org/include.js"></script>
<script src="app.js"></script>
I have enabled facebook login and persona login in my firebase forge. Also I have added my facebook app id and secret too. Everytime I click on the login button I get redirected to '/'. waitforAuth I use is here: https://gist.github.com/katowulf/7328023, but if I use it in my controllers, login with facebook/persona buttons do not work at all. If I use waitForAuth, everytime I click on one of the login buttons I get redirected to '/' immediately instead of login popup.
Anyone? :)
I finally found the solution to my problem. Adding the following stops automatic redirect to '/' before login even takes place:
I just needed to add this:
$scope.$on('$locationChangeStart', function(event) {
event.preventDefault();
});
In here like this:
app.controller('controller',['$scope','$firebaseAuth','$location','$rootScope',function($scope, $firebaseAuth,$location,$rootScope) {
$scope.$on('$locationChangeStart', function(event) {
event.preventDefault();
});
var ref = new Firebase('https://mybase.firebaseio.com/');
$scope.auth = $firebaseAuth(ref);
$rootScope.$on('$firebaseAuth:login', function(){
$location.path('/content');
});
}]);
However, I ran into another problem, because this now doesnt work:
$rootScope.$on('$firebaseAuth:login', function(){
$location.path('/content');
Because after user is finished authenticating they should be redirected to /content (instead of being stuck at login page with login buttons disappearing due to ng-hide (See above)), but it does not matter what I try $location.path('/content') doesnt work.
I tried this:
waitForAuth.then(function(){
console.log('test');
$location.path('/content');
})
But console.log prints out "test" in the console way before user is authenticated, so waitForAuth doesnt seem to work either :/. Somehow waitForAuth fires console.log but it doesnt fire $location.path... Odd.
I even tried doing this (both with waitForAuth and $rootScope.$on:
waitForAuth.then(function(){
console.log('test');
$location.path('/content');
$scope.$apply();
})
But I just get an error that angular $digest is already in progress.
Adding this: ng-click="auth.$login('facebook'); return false;" like that, angular throws me this error :
Error: [$parse:syntax] Syntax Error: Token 'false' is an unexpected token at column 33 of the expression [auth.$login('facebook'); return false;] starting at [false;].
And login buttons become un-clickable... :(
Ohh dear... me :)
I had the same problem where the URL was always reverting back to the homepage. The problem was caused by a simple mistake in the html syntax:
Log out
After I removed # in the href attribute the problem was resolved. Hope this helps others who may experience a similar problem.

Tipsy tooltip script does not work with Ajax

I use Tipsy tooltip script on my website:
Script homepage and examples
See the script
It displays some information on mouseover. For example, I have a page with users photos (thumbnails) and onmouseover Tipsy displays user name and age.
<div id="up_gus" style="display:inline-block;">
<a href="/profile.php"><img class="west" title="username showed by Tipsy" src="/foto.jpg"/>
</a></div
It works fine, but now I added Ajax/Jquery to load more photos without page refresh.
<div id="more"><a class="l_more" id="<?php echo $pid;?>" href="#!" >Show more</a></div>
$('.l_more').live("click",function() {
var last_msg_id = $(this).attr("id");
if(last_msg_id!='end'){
$.ajax({
type: "POST",
url: "/mas.php",
data: "vid="+ last_msg_id,
beforeSend: function() {
$('a.l_more').append('<img src="../load.gif" />');
},
success: function(html){
$("div#more").remove();
$("div#up_gus").append(html);
}
});
}
return false;
});
If I load more results (photos) Tipsy onmouseover does not display anything. Any ideas whi it does not work with Ajax?

JSON object parsing error using jQuery Form Plugin

Environment: JQuery Form Plugin, jQuery 1.7.1, Zend Framework 1.11.11.
Cannot figure out why jQuery won't parse my json object if I specify an url other than a php file.
The form is as follows:
<form id="imageform" enctype="multipart/form-data">
Upload your image <input type="file" name="photoimg" id="photoimg" />
<input type="submit" id ="button" value="Send" />
</form>
The javascript triggering the ajax request is:
<script type="text/javascript" >
$(document).ready(function() {
var options = {
type: "POST",
url: "<?php $this->baseURL();?>/contact/upload",
dataType: 'json',
success: function(result) {
console.log(result);
},
error: function(ob,errStr) {
console.log(ob);
alert('There was an error processing your request. Please try again. '+errStr);
}
};
$("#imageform").ajaxForm(options);
});
</script>
The code in my zend controller is:
class ContactController extends BaseController {
public function init() {
/* Initialize action controller here */
}
public function indexAction() {
}
public function uploadAction() {
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$image = $_FILES['photoimg']['tmp_name'];
$im = new imagick($image);
$im->pingImage($image);
$im->readImage($image);
$im->thumbnailImage(75, null);
$im->writeImage('userImages/test/test_thumb.jpg');
$im->destroy();
echo json_encode(array("status" => "success", "message" => "posted successfully"));
}
else
echo json_encode(array("status" => "fail", "message" => "not posted successfully"));
}
}
When I create an upload.php file with the above code, and modify the url from the ajax request to
url: "upload.php",
i don't run into that parsing error, and the json object is properly returned. Any help to figure out what I'm doing wrong would be greatly appreciated! Thanks.
You need either to disable layouts, or using an action helper such as ContextSwitch or AjaxContext (even better).
First option:
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();
And for the second option, using AjaxContext, you should add in your _init() method:
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('upload', 'json')
->initContext();
This will disable automatically disable layouts and send a json header response.
So, instead of your two json_encode lines, you should write:
$this->status = "success";
$this->message = "posted successfully";
and
$this->status = "fail";
$this->message = "not posted successfully";
In order to set what to send back to the client, you simply have to assign whatever content you want into view variables, and these variables will be automatically convert to json (through Zend_Json).
Also, in order to tell your controller which action should be triggered, you need to add /format/json at the end of your URL in your jQuery script as follow:
url: "<?php $this->baseURL();?>/contact/upload/format/json",
More information about AjaxContext in the manual.
Is the Content-type header being properly set as "application/json" when returning your JSON?