Using Angular to authenticate users API - javascript

I am building a web application in Angular ( Im new to Angular).
I building a form to pass new user info to the third party software via API end point.
to post data I need to pass name(new user) email(new user) user_key(mine) and api_key (changes evry hour)
To get the new api_key I need to Post
POST: https://pi.pardot.com/api/login/version/3
message body: email=<email>&password=<password>&user_key=<user_key>
and this returns
<rsp stat="ok" version="1.0">
<api_key><api_key here></api_key>
</rsp>
Once I have the new Key I can pass it with the form post to post data.
Question
I think Ill need to have a function that runs before the Posting of data that dose the post to get the new api_keyand changes the api_key variable on my new user post.
so the main question is how do I do this with angular, I have added my current post controller bellow that post the new user data.
My controller
// submit button controller POST
// =============================================================================
FirstModule.controller('formController', function ($scope, $http) {
$scope.formData = {};
$scope.processForm = function (Fname, Lname, email) {
var data = {
Fname: $scope.formData.Fname,
Lname: $scope.formData.Lname,
email: $scope.formData.email,
api_key: 'changes every hr', //needs to be dynamic
user_key: 'my key'
};
//Call the services
$http.post('https://some api.com/api/prospect/version/4/do/create', JSON.stringify(data)).then(function (response) {
if (response.data)
$scope.formData = "Post Data Submitted Successfully!";
}, function (response) {
$scope.formData = "Post Data Submitted Failed";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
};
});
My form
<form name="myForm" id="signup-form" class="col-sm-8 col-sm-offset-2"
ng-submit="processForm()"
ng-click="postdata(formData)">
<!-- our nested state views will be injected here -->
<div id="form-views" ui-view></div>
</form>
So this part is Ok, but how do I run a function before this runs so I get the latest api_key ? and more importantly how can I do it safe ?
The API is Pardot
For security should I place all; API request on a backed script maybe node ?

you can try to use app.run() and write the function in that. app.run() will always run before your controller. Here is one link you can check AngularJS app.run() documentation?

Related

I am updating this in view file by clicking it and want to show in view file without refreshing it

$scope.pause = function(userid){
var id = $scope.userid;
var status = 3;
getClients.status(id,status).then(function(response)
{
console.log('Response',response);
$scope.clients = response.data;
console.log('Data',$scope.clients);
$scope.cancel();
});
};
I am updating this in view file by clicking it and want to show in view file without refreshing it.
Solution,
HTML
<div ng-controller="controllerName" ng-int="getData()">
</div>
JS
app.controller("name",fucntion(){
$scope.getData = function(){
//api call to get data from database
$scope.data = resultData;
}
$scope.yourEditFunction = function(){
//make API call to update data in database
$scope.getData();
}
})
But ideally if you assign your get API result to an $scope variable and later in edit function update it then there is no need to refresh page angular will update the data for you.

http function undefined on angular

I'm new to angular and MEAN stack, and prior to this, I asked a question here:
Angular Routing ngRoute fails to pull my other HTML files
Basically, I didn't properly set my app routing and the solution is I have to modify my link to #! from #, and someone there said that it was caused by breaking change in Angular 1.6, before this I had a working implementation but it wasn't a proper one-page app since it didn't pull only the appropriate HTML of the app. Okay, so now I can view and navigate the app.
Then I ran into another problem when I tried to communicate with the app which supposedly registered me into the app, when I clicked on the button on my HTML page
<form class="form-auth" ng-submit="register()">
<h2>Register</h2>
<p class="text-warning">{{error_message}}</p>
<input type="username" ng-model="user.username" placeholder="Username" class="form-control"><br>
<input type="password" ng-model="user.password" placeholder="Password" class="form-control"><br>
<input type="submit" value="Register" class="btn btn-primary" />
I got an error on the console log, saying
Error: $http.post(...).success is not a function
at b.$scope.register (iotApp.js:73)
at fn (eval at compile (angular.js:15152), <anonymous>:4:144)
at e (angular.js:26673)
at b.$eval (angular.js:17958)
at b.$apply (angular.js:18058)
at HTMLFormElement.<anonymous> (angular.js:26678)
at bg (angular.js:3613)
at HTMLFormElement.d (angular.js:3601)(anonymous function) # angular.js:14324(anonymous function) # angular.js:10834$apply # angular.js:18063(anonymous function) # angular.js:26678bg # angular.js:3613d # angular.js:3601
This is the part of the code indicated by the console where the error is
app.controller('authController', function($scope, $http, $rootScope, $location){
$scope.user = {username: '', password: ''};
$scope.error_message = '';
$scope.login = function(){
$http.post('/auth/login', $scope.user).success(function(data){
if(data.state == 'success'){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
}
else{
$scope.error_message = data.message;
}
});
};
$scope.register = function(){
$http.post('/auth/signup', $scope.user).success(function(data){
if(data.state == 'success'){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
}
else{
$scope.error_message = data.message;
}
});
};
});
I have read some of the other answers but most of them have accidentally put the dependency in the method parameters where the controller is already imported. It works fine when I use the Advanced REST Client, which is a chrome extension to manually send a register request, but not when I use the app. Any help or just general pointers would be appreciated. Thank you!
From the $http.post documentation:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

How to read HTML (for email body) from another file in NodeJS

I am new to NodeJS.
I started working on a contact us page, which, when submitted, sends out an acknowledgement email with following HTML to user.
<p>Hello Sujit,</p>
<p>Thank you for approaching us.</p>
<p>We have received your request and our executive will get in touch with you soon.</p>
<p>Thank you.</p>
Following is the code to send email:
var mailer = require("nodemailer");
var emailBody = "<HTML above>";
// Use Smtp Protocol to send Email
var smtpTransport = mailer.createTransport("SMTP",{
service: "#######",
auth: {
user: "#########",
pass: "#######"
}
});
var mail = {
from: "######################",
to: params.email,
subject: "Welcome user.",
text: "",
html: emailBody
}
smtpTransport.sendMail(mail, function(error, response){
if(error){
console.log("Mail error:>>");
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
smtpTransport.close();
});
Currently, using nodemailer, I am sending this email with the HTML body defined in the same file - app.js. It is working fine so far.
But, is there any way I can separate the HTML with variables/placeholders for "name" and place in some other file, so that the body content can be managed directly? Some way by which I can load the body content into the variable emailBody.
Thanks.
Yes!! Create one folder with name "templates" inside that create text files for particular email. Like welcome.txt. In welcome.txt write code like
<p>Hello #name,</p>
<p>Thank you for approaching us.</p>
Then using fs module you can read that file like fs.readFile([filepath]) and store this value in variable . Like var mailContent = fs.readFile([filepath]). Then using javascript replace function replace #name with actual name .
Like mailContent.replace('#name','abcd')
Yes, you can maintain a JSON structure with key value pair.
template.json
{
"Subject" : "Acknowledgement Mail",
"Body" : Above HTML
}
And then you can read require this JSON or pass this as a parameter to your function.
var template = require('./templates.json);
var mail = {
from: "######################",
to: params.email,
subject:template.Subject,
text: "",
html: template.Body
}

Page redirection not working in angularjs using window.location.href

I am coding a page where after the user has entered the data in input fields, the data will be validated with an ajax request. After the data has been validated the page must be redirected to another page.
The below code is not working :
$scope.validateUser = function() {
username = $scope.username;
password = $scope.password;
if ( username === "nrvarun89") {
console.log(username+" "+password+" path is :"+window.location.href);
window.location.href = "http://localhost/b2c-webadmin/index/";
console.log(username+" "+password+" new path is :"+window.location);
}
};
If you are using anuglarjs make use of the $window service (best practice):
https://docs.angularjs.org/api/ng/service/$window
This should work:
$window.location.href
(See this for reference: https://docs.angularjs.org/guide/$location)

How do I receive and use a JSON object on the client-side from the server (Node JS and Express)?

I am trying to do something seemingly very simple but I'm having trouble working it out. Users can submit some text using a HTML form with POST method. This is then sent off to an API for processing, and returns with a JSON object. I then just want the app.js file to send this JSON object back so I can play around with it using JQuery.
Here is the .post method in my app.js
app.post('/', function(req, res){
console.log("starting app.post");
// See User Modeling API docs. Path to profile analysis is /api/v2/profile
// remove the last / from service_url if exist
var parts = url.parse(service_url.replace(/\/$/,''));
var profile_options = { host: parts.hostname,
port: parts.port,
path: parts.pathname + "/api/v2/profile",
method: 'POST',
headers: {
'Content-Type' :'application/json',
'Authorization' : auth }
};
// create a profile request with the text and the https options and call it
create_profile_request(profile_options,req.body.content)(function(error,profile_string) {
if (error) {res.render('home.html',{'error': error.message});
console.log("errormessage: "+error.message);
}
else {
// parse the profile and format it
var profile_json = JSON.parse(profile_string);
var flat_traits = flatten.flat(profile_json.tree);
// Extend the profile options and change the request path to get the visualization
var fileName="file 1"; //this will eventually be imported automatically
//console.log(flat_traits);
var scoreObject={"title":fileName, "percentage":functions.matchPercentage(flat_traits)}
res.send(scoreObject); //this is what I assume should send this back client-side
});
}
});
});
// creates a request function using the https options and the text in content
// the function that return receives a callback
var create_profile_request = function(options,content) {
return function (/*function*/ callback) {
// create the post data to send to the User Modeling service
var post_data = {
'contentItems' : [{
'userid' : 'dummy',
'id' : 'dummyUuid',
'sourceid' : 'freetext',
'contenttype' : 'text/plain',
'language' : 'en',
'content': content
}]
};
// Create a request to POST to the User Modeling service
var profile_req = https.request(options, function(result) {
result.setEncoding('utf-8');
var response_string = '';
result.on('data', function(chunk) {
response_string += chunk;
});
result.on('end', function() {
if (result.statusCode != 200) {
var error = JSON.parse(response_string);
console.log("status: "+result.statusCode);
callback({'message': error.user_message}, null);
console.log(error.user_message);
} else
callback(null,response_string);
});
});
profile_req.on('error', function(e) {
callback(e,null);
});
profile_req.write(JSON.stringify(post_data));
profile_req.end();
}
};
So I presume res.send is what passes the data across to the client-side, but then how do I receive the data on the client-side? This is my attempt at the JScript:
$.getJSON('/').done(function(data){
$('#resultsList').append('<li data-icon="arrow-r" data-iconpos="right" id="'+
data.title+'"> <a href="#breakdownDialog"> <div id="cvResults"><h3>'+
data.title+'</h3> <span>'+data.percentage+
'%</span></div></a><div id="output"></div></li>');
console.log(data.title+data.percentage);
}
});
I want to take some of the values from the JSON object and put them in a list on the existing HTML page. At the moment this just takes me to a different blank page that says Undefined.
How should I grab the JSON data from the server?
EDIT: Here's the HTML form I am submitting the data with:
<form method="POST" id="submitForm">
<fieldset>
<textarea id="textArea" required="true" rows="5" name="content"></textarea>
<button class="btn btn-block" type="submit">
Analyse
</button>
</fieldset>
</form>
Are you sure that you are sending json with res.send()? Try to set header
res.set('Content-Type', 'application/json') or use this res.json() instead of res.send()

Categories