Loopback angular 401 Authorization Required - angularjs

i'm developing app with loopback & angular. I extened "user" modal in loopback into "puser" modal with some addi. fields('reportto'). Login & Register for the extended modal is working fineBut when i tried to use the method "find", its showing 401 Authorization required.
Code:
Puser.find({
filter : {
where : {
"reportto" : '639124805'
}
}
}, function(success) {
console.log(success);
}, function(error) {
console.log(error);
});
Please chk the screenshot for req. header.
Can anyone help on this?

By default, loopback protects find method to be accessed only the owner rule.
In order to change it you have to override the model configuration json. (for more information click here)
For example, to allow public access to all methods add the following acl:
"acls": [
{
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
}
]

Related

POST request to Azure Functions App to be send twice before success in React (Axios, Fetch)

I have a simple upload form which onsbubmit should post data to API. In my previous question I struggled to get it running in general, but now CORS went into play. After spending hours on configuring CORS back an forth on Azure Function I got stuck. Finally I managed to verify the server with Curl (Allow Access Origin is matching). This made me thinking there is a bug/feature in how axios handles the requests. So I used fetch just before axios. When deployed one POST fire was successful. I thought I found the problem - so I commented out the axios part. Deployed again. Nothing. So I am back with the working solution but really dirty - one of the methods is firing Error. The other is working. I think the working one is the second one. Any ideas what is happening here?
Here is my code snippet:
formHandler() {
const { formFields } = this.state;
console.log(formFields);
const response = fetch('https://example.com', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formFields),
})
axios({
url: 'https://example.com',
method: 'post',
headers: { 'Content-Type': 'application/json'},
data: formFields
}).then(function(response){
console.log(response);
//Perform action based on response
})
.catch(function(error){
alert(error);
console.log(error.status);
//Perform action based on error
});
}
}
and this is the function.json content on Azure:
{ "bindings": [ { "authLevel": "function", "type": "httpTrigger", "direction": "in", "name": "req" }, { "type": "http", "direction": "out", "name": "res" } ] }
I have enabled the methods in the platform features of Azure Function. Should this automatically propagate to function.json? Or should I add this manually?
Axios sends an OPTIONS request prior to sending the POST. It's likely that the Azure Function is denying the OPTIONS request, which prevents the POST request from being successful. Read more about the OPTIONS verb here and here. However, it looks like your function.json is missing a methods key that should have a value of [ "options", "get", "post" ]. This will explicitly allow both OPTIONS and POST (as well as GET).
Your Azure Function's function.json should be something like this:
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"options",
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
For all those who struggle with similar issue the workaround is relatively simple. Stick to content-type application/x-www-form-urlencoded and avoid custom headers, this way it will not force preflight with OPTIONS.
There seems to be a bug either in Axios package and/or Azure Functions on handling posting/responding to OPTIONS call. Check out: https://medium.com/#praveen.beatle/avoiding-pre-flight-options-calls-on-cors-requests-baba9692c21a
for some other related hints.
In firefox I noticed that Option call from Localhost has Origin: null. This maybe AXIOS bug and Azure Function does not accept this call as proper Options call. But I stopped further investigation on his.

How to call a function upon http get or post?

I'm sure this is a stupid question but I am very new to the backend so please forgive me.
I am building an angularjs app with express/node also and am trying to integrate PayPal (as a Node.js SDK), what I want is to call the pay method on the SDK from an angular controller and I am doing as follows:
On button click:
// controller
$scope.pay = function(amount) {
PaymentFactory.doPayment(amount);
}
Payment Factory:
// PaymentFactory
return {
doPayment: function(amount) {
$http.get("../../../server/payments/paypal.js")
.then(function(response) {
console.log( response );
})
}
}
Then the server-side file is as below:
require('paypal-adaptive');
var app = require('../../server.js');
var PayPal = require('paypal-adaptive');
var paypalSdk = new PayPal({
userId: 'userid',
password: 'password',
signature: 'signature',
sandbox: true //defaults to false
});
var payload = {
requestEnvelope: {
errorLanguage: 'en_US'
},
actionType: 'PAY_PRIMARY',
currencyCode: 'GBP',
feesPayer: 'EACHRECEIVER',
memo: 'Chained payment example',
cancelUrl: 'returnUrl,
returnUrl: 'cancelUrl',
receiverList: {
receiver: [
{
email: 'email1',
amount: '3.40',
primary:'true'
},
{
email: 'email2',
amount: '1.20',
primary:'false'
}
]
}
};
paypalSdk.pay(payload, function (err, response) {
if (err) {
console.log(err);
} else {
// Response will have the original Paypal API response
// But also a paymentApprovalUrl, so you can redirect the sender to checkout easily
console.log('Redirect to %s', response.paymentApprovalUrl);
return response;
}
});
Of course the get request just returns a string of the server-side file contents, I understand why the above doesn't work but not sure how one would make it work. My aim is to call the PayPal SDK from the angular factory and get back the response so that I can redirect a user to a URL. A direct solution would be helpful but even more so I need pointers to the principles that I am not understanding here as far as how one should call functions upon user actions to get this data from the server side. I have tried searching but I don't really the language to use in my search.
All you need to do is use curl (node-curl npm module). Using curl will help you post data to your paypal url and get back the response. Now you need to handle this response from paypal and accordingly generate your own response to be received by the angular http method.

Invalid Credentials error message with google custom search api

I am using google custom search api to search for images in angular.js project.
Here is my Code:
var photosPublic = $resource('https://www.googleapis.com/customsearch/v1',
{ key: '..........ZDtw95C0V98ne4S39SPFi68', cx: '..........75325342:1ttvll7gahc' },
{ searchType:'image' });
return {
search: function(query) {
var q = $q.defer();
photosPublic.get({
q: query
}, function(resp) {
q.resolve(resp);
}, function(err) {
console.log(err);
q.reject(err);
})
return q.promise;
}
}
If i enter url plus all credentials directly in browser it works perfectly fine. But when i include this in my project i receive following response:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
What am i doing wrong?
i had the same issue and wanted to share my solution here because i stumbled here from google search.
the problem appears when you set some default authorization headers in request libraries like $resource or axios etc...
When you provide an Authorization header in the request you're sending to google custom search api the google server is trying to authorize you with this header and isn't even trying to authorize you with the given key and cx.
I don't know much about $resource (maybe someone else could add some code?) but i have a solution for axios:
import axios from 'axios'
export default {
url: 'https://www.googleapis.com/customsearch/v1',
http: axios.create(),
search(text) {
this.http.defaults.headers.common = {};
const key = process.env.GOOGLE_SEARCH_API_KEY
const cx = process.env.GOOGLE_SEARCH_SCOPE_ID
return this.http.get(this.url, {
params: {
q: text,
cx,
key
}
})
}
}
This creates an own axios instance for the search api and resets the headers. Plus: your global axios instance is not affected (perhaps your Auth headers is needed for the communication with your backend).

Parse push notification with ionic

I am trying to set up a push notification with parse to handle received notifications.
I used phonegap-parse-plugin plugin and was able to set it up correctly.
My problem with it is that I cannot handle the received notifications. I would like to redirect a user to a the page for the notification based on the notification json params.
So, I decided to switch to parse-push-plugin, but my problem with it is that I cannot even get it to show the alert registered box; it cannot even find the ParsePushPlugin method.
I followed the tutorial which is simple enough and added this to my app.js file
ParsePushPlugin.register(
{ appId:"xxx", clientKey:"xxx", eventKey:"myEventKey" }, //will trigger receivePN[pnObj.myEventKey]
function() {
alert('successfully registered device!');
},
function(e) {
alert('error registering device: ' + e);
});
ParsePushPlugin.on('receivePN', function(pn){
alert('yo i got this push notification:' + JSON.stringify(pn));
});
The alert success just failed to show so I guess it is not working or I am not doing the right thing.
Use phonegap-plugin-push. It is easy to implement and use.
Config :
var push = PushNotification.init({
"android": {
"senderID": "Your-sender-ID",
"forceShow": true, // To show notifications on screen as well
"iconColor": "#403782",
"badge": "true",
"clearBadge": "true" // To clear app badge
},
"ios": {
"alert": "true",
"badge": "true",
"clearBadge": "true",
"sound": "true",
"forceShow": "true"
},
"windows": {}
});
Device Registration :
push.on('registration', function(data) {
localStorage.setItem('pushToken', data.registrationId); // Save registration ID
});
Handle Notifications
push.on('notification', function(data) {
console.log(data);
// Handle all requests here
if (data.additionalData.$state == "mystate") {
$state.go('app.conversations');
}
})

AngularJS Chaining $http calls

I am still quite new to AngularJS and struggling to figure the following out.
I have quite a few web-services that I need to use, quite a few of them relies on the data from another to successfully make the next call.
For example, the first web-service will retrieve a list of Profiles.
ip.controller("ProfilesCtrl", function($scope, $http) {
$http.post("Profile_List.asp").success(function(data) {
$scope.profiles = data;
}).error(function() {
alert("An unexpoected error ocurred while loading profiles!");
});
});
Profiles returns a JSON object.
Data returned:
{
"Success": true,
"ErrorMessage": "",
"Objects": [{
"GUID": "208FF69D-A4EB-4760-B2ED-414C900F4AAC",
"Name": "John Doe",
"Status": false
}, {
"GUID": "BC5C53FD-5CA7-4DBE-8594-D26AD88B758B",
"Name": "Jane Doe",
"Status": true
}, {
"GUID": "2FCD677B-DA36-4014-823A-9BDD1A72AD66",
"Name": "Anonymous",
"Status": true
}]
}
Ok, so after I have made the initial call, I need to send the GUID of each Profile Object to another web-service. This service will use the GUID to determine the ID of that specific Profile.
The data from the second web-service will only return the ID for the GUID of the first call.
How can I chain these $http calls? Would it be better to create a new json object and use data from there?
I have done this before using ajax.
*Another question regarding my controller code, is this fine like this or would it be better to maybe do the $http calls as a Service, Provider or Factory? How can I go about doing this?
Any help/links with getting the above to AngularJS code would be appreciated.
Please ask if anything is unclear.
Simply call execute the next call in your "success" handler.
$http.post("Profile_List.asp").success(function(data) {
$scope.profiles = data;
//first call succeeded, and we have the data. call method 2
executeStep2($scope.profiles);
})
function executeStep2(profiles)
{
$http.post("second_method") // etc. (you can just send profiles as post data here)
}

Resources