login using angular js and $http request not working - javascript

I want to login using $http and GET of REST web services. What I am doing is:
Taking data on the basis of username and password using $http.get
Storing the result: $scope.getResult=res;
Storing it in some variable:
var result=$scope.getResult;
var username=result.userName;
var password=result.password;
var user=this.user;
var pass=this.pass;
After that I will compare with the ng-model of username and password. If it is successful then it will redirect to another page like below:
if (username == user && password == pass)
{
window.location="/next.html";
}
Below is my complete code and please suggest the changes required in my case.
$scope.login = function () {
var user = this.user ; // ng-model of username in html page
var pass = this.pass; //ng-model of password in html page
$http.get("http://localhost:17681/api/userRegisters"+user+pass).success(function (res) {
$scope.getResult = res;
var result = $scope.getResult;
var username = result.userName;
var password = result.password;
if (username == user && password == pass) {
window.location="/next.html";
}
}
}
Please tell me how should I change my code in order to do that.
Thanks in advance :)

Replace the raw window.location method with the AngularJS $location service. Calling window.location from inside a $q service fulfillment handler will generally result in an AngularJS internal error.
$http.get("http://localhost:17681/api/userRegisters"+user+pass)
.then(function onFulfilled(response) {
$scope.getResult = response.data;
var result = $scope.getResult;
var username = result.userName;
var password = result.password;
if (username == user && password == pass) {
//Use this
$location.path("/next.html");
//Not this
//window.location="/next.html";
}
}).catch ( function onRejected(response) {
console.log(response.status);
});
For more information, see AngularJS $location Service API Reference.
Deprecation Notice
The $http legacy promise methods .success and .error have been deprecated. Use the standard .then method instead.1
Debugging the Response
Its gives record via response.data but doesnt give column records. what should be done in order to fetch data ?
What is the specification for the server side API?
What is the server side code that generates the response data?
These are things readers will need to know in order to help you. Otherwise any answer is just a guess.
Industry best practice is to avoid sending passwords as a parameter of a URL as that has security issues.
Two resources recommended by the AngularJS team:2
Deal with users authentication in an AngularJS web app
Authentication in Single Page Applications With Angular.js
Additional Resources
GitHub AngularJS Authentication
Bit of Tech: AngularJS Token Authentication
AngularJS User Registration and Login Example & Tutorial

"http://localhost:17681/api/userRegisters?username= " + username + "&password=" + password
and read the username and password from http://localhost:17681/api/userRegisters this location by using GET HTTP METHOD

Related

Integrate Salesforce registration page with VanillaJS oidc-client-js, getting the error - No matching state found in storage

Integrate Salesforce registration page with VanillaJS, getting the error - No matching state found in storage
We are redirecting the user to Salesforce registration page when Create Account button is created.
Once the User registers in Salesforce, the user is redirected to our site but we are getting this error. ('No matching state found in storage').
We tried the below solution but still getting the same error.
As I stated in my answer, the oidc client maintains state information
in the local storage so that it can verify that it got the response
back from the intended server. You can mimic this by generating a
secure random string and saving it in localStorage. Do this before
sending a request to your auth server to register a new user.
Reference- Integrate third party login in from my registration page with IdentityServer4 and Angular 6 - 'No matching state found in storage'
Is there a function related to creating registration? How to fix this issue?
Thanks.
Appreciate your help.
After spending days on this issue. Finally found the workaround as registration is not a feature of OIDC.
To overcome this issue, need to follow the Sign In process same as for Sign Up process, created the startSignupMainWindow method same as startSigninMainWindow and passing the signUpFlag:true as shown below in code.
/* This function is written to mimic the oidc library sign in process flow */
function startSignupMainWindow() {
var someState = {
message: window.location.href,
signUpFlag: true
};
mgr.signinRedirect({
state: someState,
useReplaceToNavigate: true
}).then(function() {
log("signinRedirect done");
}).catch(function(err) {
log(err);
});
}
Reading the signUpFlag:true in UserManager.js and swapping the Salesforce Sign In page Url with Sign Up page url and calling the Register function in Code.
UserManager.js(oidc - client - dev - js / src / UserManager.js)
//UserManager Customised Code :
return this.createSigninRequest(args).then(signinRequest => {
Log.debug("UserManager._signinStart: got signin request");
navigatorParams.url = signinRequest.url;
navigatorParams.id = signinRequest.state.id;
if (signinRequest.state._data.signUpFlag) {
register(signinRequest.state._id, signinRequest.state._code_challenge);
} else {
return handle.navigate(navigatorParams);
}
})
The below code is Register function written in code.
/* This function is written to send the code_challenge to salesforce server so that
salesforce server holds the code challenge and used to verify the further requests(token-request)
against the code_challenge it received initially.*/
//Customised register function written outside the library (Inside our App):
function register(_id, code_challenge) {
var date = new Date();
var baseUrl = "SALESFORCE_URL/login/SelfRegister?expid=id";
var expId = "id";
var userPage = encodeURIComponent(window.location.href);
var appDetails = "response_type=code&" +
"client_id=CLIENT_ID" +
"client_secret=CLIENT_SECRET&" +
"redirect_uri=CALLBACK_URL&" +
"state=" + _id + "&code_challenge=" + code_challenge + "&code_challenge_method=S256&response_mode=query";
var encodedapp = encodeURIComponent(appDetails);
var startUrl = "/services/oauth2/authorize/expid?" + encodedapp;
var signUpUrl = baseUrl + "&startURL=" + startUrl;
window.open(signUpUrl, "_self");
};

Payment GateWay integration in nodejs and mongodb

Hi I am Integration Payment GateWay to my app but i am stuck. for cod(Cash On Delivery) mode of payment it is working fine.but while in integration online payment gateway it is giving bit pain like i am creating payment link using instamojo when link is created successful; i return that payment link to client and redirect user to that link
1 if user fills card details successfully and instamojo hits my provided webhook(post url) with payment details
2 what if user cancels tab or doesn't pays
question here is where shall in create order in database. if it is to be created on placeorder url of my app then i need to set order status incomplete and run a cron job for second condition (because order is already created and webhook is not hit by intamojo). is it right way to do or there is other better ways to handle all this
Promise.all([getUpdatedCart(userId), findUser(userId), getDiscount(userId,couponCode)])
.then(function(resultArray) {
var cart = resultArray[0];
var user = resultArray[1];
var discountAmount = resultArray[2];
var offerId=null;
if (!cart)
return sendResponse(response,400,"error","Cart Not Found");
if (discountAmount>0)
var offerId=getOfferId(couponCode);
var order = {
user: user._id,
cart: cart._id,
shippingAddress:shippingAddressId,
billingAddress:billingAddressId,
paymenMethod: paymentMethod,
offer:offerId,
deliveryNote:deliveryNote,
amount:cart.amount
};
var newOrder = Order(order);
if (paymentMethod==='cod')
newOrder.save(function(error,order){
if (!error)
if (order){
Cart.expireCart(cart._id);
return sendResponse(response,201,"success",order);
}
});
else if(paymentMethod==='intamojo'){
var purpose='Order Number-'+ newOrder.id;
Instamojo.setHeaders(InstaConfig.test.API_KEY, InstaConfig.test.API_AUTH_TOKEN);
var amountPayable = cart.amount - discountAmount;
var data = generatePayload(user, purpose, amountPayable);
Instamojo.createPaymentLink(data, function(error, resultResponse, body) {
if (resultResponse && body && resultResponse.statusCode===201)
return sendResponse(response,200,"success",body.longUrl+"?embed=form");
});
}
else if(paymentMethod==='payumoney'){
}
else
return sendResponse(response,400,"error","Invalid Mode of Payment");
})
.catch(function(error) {
return sendResponse(response,400,"error",error);
});
Can anyone Please help if i need to write cron job kindly suggest library for that
You need not create a cron job.
You can create Order in your database first, and then create a request passing the orderID in purpose parameter to uniquely Identify the Payment Request.
Provide redirect_url and webhook at the time of create a request.
After any Payment payment_request_id and payment_id is send to the redirect_url provided.
Use payment_request_id and payment_id to get the status of the payment, the response will have payment: { ... ,status, ... } use this to update the status in your database.
You can use webhook as a fallback if the user accidentally closes the browser window/tab before it reaches the redirect_url.
For more details, read the documentation

secret key visible in javascript code (JavaScript, Firebase)?

I have a function that checks wether the password and user match before authenticating using a custom token.
function getUser(user, password) {
var usersRef = new Firebase("mydatabase/users");
var userRef = usersRef.child(user);
userRef.once("value",
function getHandler(snapshot) {
if (snapshot.val().password == password) {
var token = createToken(user);
ref.authWithCustomToken(token, authHandler);
} else {
alert("Gebruikersnaam en code komen niet overeen");
}
},
function errorHandler(errorObject) {
alert("Ophalen van gebruikersgegevens is mislukt: " + errorObject.code);
}
);
}
To create e token I instantiate the firebase class FirebaseTokenGenerator with the secret key. Like
function createToken(user) {
var tokenGenerator = new FirebaseTokenGenerator("<secret key...>");
var updatedObj = {
"uid": "custom:"+user,
"level": "docent"
}
return tokenGenerator.createToken(updatedObj);
However in that way the secret key would be visible for anyone looking into the .js source code. I'm pretty sure that is not how it should be done but what is the right way to do this then, the Firebase-way?
EDIT:
I tried to figure out the javascript way for this but got stuck there so switched back to php. Used the firebase-token-generator code from github (here), installed it including dependencies in my project with composer and that all seems to work fine (token is generated).
<?php
include_once "FirebaseToken.php";
$uid = $_POST['uid'];
$level = $_POST['level'];
$tokenGen = new Services_FirebaseTokenGenerator("<secret key>");
$token = $tokenGen->createToken(array("uid" => "custom:BAAJ"), array("admin" => False));
echo $token;
?>
Reading this SO post I found that following would be the way to embed it in my javascript code:
function createToken(user) {
$.post('php/createtoken.php', {uid: user, level: 'docent'}, function(data){
//successful ajax request
return data;
}).error(function(error){
alert("Create token mislukt: "+error);
});
};
But for som reason the token is not generated then. When called from getUser at first both the success and error part of the javascript createToken function are not executed at all (resulting in an undefined value for variable token. Then createToken is called a second time (??) and then the success part is executed however the data now does not contain the token but the complete php script...?
What is the problem and how to solve?
You should avoid to do anything 'secret' in the client browser. There, the secret will be visible, password will be hackable via XSS and sniffable and you could connect to any user with some XSS.
You should rather move this part onto the server side to be more secure, it could be NodeJS, PHP or anything else. (HTTPS connections, obviously)
You have to do this in your server side application and send the generated token to your client app. The token should be sent over HTTPS as well. Default token expiry is 24 hours. This can be changed.

Calling the app config method inside ajax response - AngularJS

I am developing an app using angularjs and this is my first hands on using angular. Although, I have started understanding it and have developed some part of the app but I am stuck at one particular point.
I am trying to implement login functionality, so as the page loads, I am authenticating user and redirecting him to login page. On successful login, I am storing some values of user in one of the config provider.
Now I am using an API which has their own method of authentication and they have expose the ajax method which I can use to authenticate a user.
I have provided a snippet below. What I am primarily doing is using the external API, authenticating the user and once authenticated, I am getting roles associated to that user using another ajax method of the API, called "GetUserDetails".
And inside the response of the "GetUserDetails", I am injecting a provider and setting some values, so I can use this across my app.
The problem here is the app.config method is never called/executded. I mean the ajax request is returning response, and the alert is displayed on my page, but app.config is never executed.
But the same app.config if I call inside the done() of GetUser method, the app.config gets executed and stores values in my provider. But I want the GetuserDetails values also to be stored before I do anything in my app as I want to execute certain functionality based on user.
Below is my function in main.js file
function(angular,angularRoute,app,routes,configService){
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
$.c.authentication.getUser()
.done(function(response){
if(response.userName!="anonymous"){
$.c.ajax({
method: "GetUserDetails",
parameters: {
User: response.user
}
})
.done(function(res) {
alert("I have reached the destination").
app.config(['configServiceProvider', function(configServiceProvider){
configServiceProvider.setLoginStatus(true);
configServiceProvider.setUserName(response.userName);
configServiceProvider.setUserObject(response);
configServiceProvider.setUserRoleDetails(res);
}]);
})
.fail(function(res) {
alert("Error while getting user roles ."+res);
});
angular.resumeBootstrap([app['name']]);
}
else
{
app.config(['configServiceProvider', function(configServiceProvider){
configServiceProvider.setLoginStatus(false);
configServiceProvider.setUserName(response.userName);
}]);
//Show Login Screen
var url = window.location.href.split("#")[0];
window.location.href = url + "#/Login";
angular.resumeBootstrap([app['name']]);
}
})
.fail(function(response){
$rootScope.isLoggedIn=false;
});
});
Here is my configServiceProvider
define(['../app'],function(app){
return app.provider('configService', function(){
var options={};
this.setLoginStatus = function(status){
//$rootScope.isLoggedIn = status;
options.isLoggedIn=status;
};
this.setPreLoginInfo=function(info){
options.preLoginInfo=info;
};
this.setUserName=function(name){
options.username=name;
}
this.setUserObject = function(userObject) {
options.userObject = userObject;
}
this.setUserRoleDetails = function(userRoleDetails) {
options.userRoleDetails = userRoleDetails;
}
this.$get=[function(){
if(!options){
}
return options;
}];
});
})
Can anyone please explain me what's going wrong here or what I am missing ?
Also, is there any alternative to achieve the same functionality ?
No luck in figuring out why the above scenario was not working. Since I had already spent lot of time behind this, I have found a workaround to achieve the same with the use of services.

AngularJS and REST resources naming wondering

So in my angular js app in service called 'authService' I have the following resources:
var userAreaLogin = $resource('/api/user_area/login');
var userAreaSignup = $resource('/api/user_area/signup');
var session = $resource('/api/user_area/getSession');
var userAreaLogout = $resource('/api/user_area/logout');
but this doesn't feel quite right, I'm using only the get methods, for example:
this.login = function(credentials) {
var user = userAreaLogin.get(credentials, function() {
...
});
};
this.signup = function(userInfo) {
var signup = userAreaSignup.get(userInfo, function() {
...
});
};
I'm confused about what resources to use, should I have something like this?
var session = $resource('/api/user/session');
var userArea = $resource('/api/user');
userArea.get(credentials); //should login the user?
userArea.post(credentials); //should signup the user?
session.delete(); //should logout the user?
session.get(); //should get the sessions of the logged user if any?
By REST sessions are maintained by the client and not by the service. You should use HTTPS and send the username and password with every request (for example with HTTP basic auth headers) instead of using session cookies... (stateless constraint)
Ofc. on the client side you can have login and logout which will change the content of the auth headers sent via AJAX.
You are going to the right direction.
In a well designed REST API you should have something like this.
POST /users/sign_in # Create a user session (signs in)
DELETE /users/sign_out # Delete a user session (signs out)
POST /users # Create a new user resource
GET /users/:id # Get the user resource
Based on these API you can then define your services. I also suggest to use $http which is cleaner, although you'll write few lines of code more.
# Session related methods
Session.create
Session.delete
# User related methods
User.create
User.get
Hope this makes things clearer.

Categories