Backand user object not associated with custom user object if created through API - backand

I have created a custom "users" object that I know is associated with backand's user object. However when I created them from my app using Backand's SDK, I can see the user being created in the Backand's registered users but not in my custom object "users"

It appears to be a permissions issue. Not documented well either. If your Anonymous Access is set to (read only) and you remove the try catch statement from the "Create My App User" server side javascript you will get a 401 error in your client. Set Anonymous Access to public and it works first try. There is probably a better way to do this but I am still looking into it I dont want to give the Anonymous Users that much access. But it definitely proved it is permissions issue.

Make sure you have the following security actions in Security & Auth and that their conditions is set to true:
Event - During create,
Name - Create My App User
Code:
/* globals
$http - Service for AJAX calls
CONSTS - CONSTS.apiUrl for Backands API URL
Config - Global Configuration
*/
'use strict';
function backandCallback(userInput, dbRow, parameters, userProfile) {
// When a new user registers, add her to the users object.
// If you are using a different object for your users then change this action accordingly.
if (parameters.sync)
return {};
if (!parameters)
parameters = {};
parameters.email = userInput.Username;
parameters.firstName = userInput.FirstName;
parameters.lastName = userInput.LastName;
try{
var response = $http({
method: "POST",
url:CONSTS.apiUrl + "/1/objects/users",
params: {parameters: {"sync": true}},
data: parameters,
headers: {"Authorization": userProfile.token}
});
}
catch(err) {
// register user even if there is an error or no users object
}
return {};
}
Event - During update,
Name - Update My App User
Code:
/* globals
$http - Service for AJAX calls
CONSTS - CONSTS.apiUrl for Backands API URL
Config - Global Configuration
*/
'use strict';
function backandCallback(userInput, dbRow, parameters, userProfile) {
// When a registered user is changed, change your users object as well.
// If you are using a different object for your users then change this action accordingly.
// Get the user id by the user's email
var currentUser = $http({
method: "GET",
url:CONSTS.apiUrl + "/1/objects/users",
params: {filter:[{"fieldName":"email", "operator":"equals", "value": userInput.Username }]},
headers: {"Authorization": userProfile.token}
});
if (currentUser.data.length == 1) {
var currentUserId = currentUser.data[0].__metadata.id;
var response = $http({
method: "PUT",
url:CONSTS.apiUrl + "/1/objects/users/" + currentUserId + "",
params: {},
data: {"firstName": userInput.FirstName, "lastName": userInput.LastName },
headers: {"Authorization": userProfile.token}
});
}
return {};
}
Event - During delete,
Name - Delete My App User
Code:
/* globals
$http - Service for AJAX calls
CONSTS - CONSTS.apiUrl for Backands API URL
Config - Global Configuration
*/
'use strict';
function backandCallback(userInput, dbRow, parameters, userProfile) {
// When a registered user name is deleted, delete her from your users object as well.
// If you are using a different object for your users then change this action accordingly.
// Get the user id by the user's email
var currentUser = $http({
method: "GET",
url:CONSTS.apiUrl + "/1/objects/users",
params: {filter:[{"fieldName":"email", "operator":"equals", "value": dbRow.Username }]},
headers: {"Authorization": userProfile.token}
});
if (currentUser.data.length == 1) {
var currentUserId = currentUser.data[0].__metadata.id;
var response = $http({
method: "DELETE",
url:CONSTS.apiUrl + "/1/objects/users/" + currentUserId + "",
params: {},
headers: {"Authorization": userProfile.token}
});
}
return {};
}

Related

Authorize to a 3rd party service within Postman request

Want to create request in Postman to cover authorization to a 3rd party within request. In application it works this way:
Client clicks the button
Application checks whether there is a token, if not it returns link to the 3rd party service to authorize there
Client follows the link, inputs credentials, submits form
Service redirects client back to the application with authorization code as a query parameter.
Client pushes another button to receive token by the authorization code.
So, is there a way to proceed this scenario within the Postman, not to copy link from response and pasting it to browser in order to complete authorization?
Tried to make request from Test script tab like:
var jsonData = JSON.parse(responseBody);
console.log(jsonData.data)
if (jsonData.data) {
pm.sendRequest(jsonData.data, function (err, response) {
console.log(response);
return response;
});
}
But that was not actually useful
There is a way to get token before request.
You can use Pre-request Script bookmark.
Write JS code to get token and save it to variable (collection / environment).
In specific request open Authorization bookmark and call your variable.
For Bearer:
My Pre-Request Script for example:
let collUsername = pm.variables.get("username");
let collPassword = pm.variables.get("password");
let collClient_id = pm.variables.get("client_id");
let collClient_secret = pm.variables.get("client_secret");
const postRequest = {
url: pm.variables.get("url"),
method: 'POST',
header: {
'Accept': '*/*',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {
mode: 'urlencoded',
urlencoded : [
{ key: 'username', value: collUsername},
{ key: 'password', value: collPassword},
{ key: 'grant_type', value: 'password'},
{ key: 'client_id', value: collClient_id},
{ key: 'client_secret', value: collClient_secret},
{ key: 'user_type', value: 'System'}
]
}
};
pm.sendRequest(postRequest, (error, response) => {
console.log(error ? error : response.json());
let jsonRes = response.json();
pm.collectionVariables.set("token", jsonRes.access_token);
});
I don't know your authentication method so your script can be different.
If you want to refresh only expired token you can add variable with date and check if appropriate time has passed to get new token.
Edit: Scripts written in Tests are executed after getting response so not proper place for your case.

Shopify app with proxy extension PUT requests not working

I have managed to created an app proxy using this guide:
https://shopify.dev/tutorials/display-data-on-an-online-store-with-an-application-proxy-app-extension#handling-proxy-requests
I wanted to update the customer record using a form. On submission of form the below func would be invoked.
jQuery(function($) {
$('#enrollFormID').submit(function() {
var fname = $(FirstName).val();
var lname = $(LastName).val();
var emailID = $(email).val();
var pass = $(password).val();
event.preventDefault();
var data = jQuery(this).serialize();
console.log(data);
data = "form_type="+data;
$.ajax({
url: '/apps/subpath',
type: 'PUT',
data: data,
dataType: 'json',
success: function (data) {
console.info(data);
}
});
return true;
});
});
In the backend app, the below url is getting hit when the form gets submitted, but am not able to retrieve the form data values.
router.put('/test', async (ctx) => {
.....
}
Get request works fine, but with Put request am not able to retrieve the form data from the ajax call.
Can someone help me on this?

Call Request From Collection Within Pre-Request Script

I am fully aware that there is a way to make an ajax call from within a request's Pre-request script, a la,
const getBooks = {
url: "http://" + pm.environment.get("host") + "/books",
method: "GET",
header: "G-TOKEN:ROM831ESV"
};
pm.sendRequest(getBooks, function(err, books) {
const ids = _.map(books.json(), function(book) {
return book.id;
});
pm.globals.set("bookIds", ids);
});
pane but is there a way to call a saved request from a collection by name like you can do with postman.setNextRequest('') something akin to...
pm.sendRequest('Get Books', function(err, books) {
const ids = _.map(books.json(), function(book) {
return book.id;
});
});
Apparently this is not possible in the current version of Postman. There is a request out there on github about this exact issue.
https://github.com/postmanlabs/postman-app-support/issues/4845

Unable to Authorize users using Implicit / Authorization flow in google actions

I am trying to link to the account :
Here is my google cloud function
var AuthHandler = function() {
this.googleSignIn = googleSignIn;
this.googleSignInCallback = googleSignInCallback;
}
function googleSignIn(req, res, next) {
passport = req._passport.instance;
passport.authenticate('google',{scope: 'https://www.googleapis.com/auth/userinfo.email',
state:"google",response_type:"token"},
function(err, user, info) {
console.log(user);
})(req,res,next);
};
function googleSignInCallback(req, res, next) {
passport = req._passport.instance;
passport.authenticate('google',function(err, user, info) {
if(err) {
return next(err);
}
if(!user) {
return res.redirect('http://localhost:8000');
}
console.log(user._json.token);
// /res.redirect('/');
res.redirect('https://oauth-redirect.googleusercontent.com/r/xxxxxx#access_token=' + user._json.token + '&token_type=bearer&state=google')
})(req,res,next);
};
module.exports = AuthHandler;
In google Action Console :
I have created the implicit flow and gave my authorisation url as follows:
https://[region]-[projectid].cloudfunctions.net/[functionname]/auth/google
Error :
this is the browser Url
https://assistant.google.com/services/auth/handoffs/auth/complete?state=xxxx&code=xxxxxx
on which the following error is displayed
The parameter "state" must be set in the query string.
Update 1
Before starting this implementation , i have followed this Solution to create the Authentication.
Problems in this Approach :
1.As stated in the Documentation it is not redirecting to google.com and i'm unable to access the token using the APIAI SDK in javascript. but still i can see the Access token in emulator . for better understanding adding images
Here is my simulator O/P
{
"response": {
"debug": {
"agentToAssistantDebug": {
"assistantToAgentDebug": {
"assistantToAgentJson": "{"accessToken\":\"xxxxxx\""
}
},
"errors": []
}
Update 2 :
So i have started creating with implicit flow and here is my complete repo
After battling with it i have achieved it , as there is no proper articles about creation of own Oauth Server that implements the Google Action , this might helpful for future users.
Authorization Endpoint
app.get('/authorise', function(req, res) {
req.headers.Authorization = 'Bearer xxxxxxxxxxx';
// with your own mechanism after successful
//login you need to create a access token for the generation of
//authorization code and append it to this header;
var request = new Request(req);
var response = new Response(res);
oauth.authorize(request, response).then(function(success) {
// https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID?
//code=AUTHORIZATION_CODE&state=STATE_STRING
var toredirect = success.redirectUri +"?code="+success.code
+"&state="+request.query.state ;
return res.redirect(toredirect);
}).catch(function(err){
res.status(err.code || 500).json(err)
}) });
Token Endpoint :
app.all('/oauth/token', function(req,res,next){
var request = new Request(req);
var response = new Response(res);
oauth
.token(request,response)
.then(function(token) {
// Todo: remove unnecessary values in response
return res.json(token)
}).catch(function(err){
return res.status(500).json(err)
})
});
After creation of this endpoints publish to the Google Cloud functions . I have used MYSQL as the DB using SEQUELIZE and Oauth-Server , if anyone need those models , will share it through repo .
With this you can able to link account using your own Server which implements
Auth tokens and Access Tokens
I think the problem is that the URL on this line isn't sending the parameters as query parameters, they're sending them as part of the anchor:
res.redirect('https://oauth-redirect.googleusercontent.com/r/xxxxxx#access_token=' + user._json.token + '&token_type=bearer&state=google')
You should replace the # with a ?, as illustrated here:
res.redirect('https://oauth-redirect.googleusercontent.com/r/xxxxxx?access_token=' + user._json.token + '&token_type=bearer&state=google')

Calling POST as URL ASP.NET web api

I want to know how to test POST by typing in the url.
Here's my route Config
config.Routes.MapHttpRoute(
name: "myWebApi",
routeTemplate: "api/mywebapi/{action}/{ID}/{DeptID}",
defaults: new { Controller = "mywebapi", ID = #"\d+", DeptID = #"\d+" }
);
programmatically this is how I call POST
I have 3 text boxes and a button. When user clicks on the button the below program gets called
function parseform(button) {
var id = $("#ID").val();
var deptid = $("#DeptID").val();
var name = $("#Name").val();
var inputdata = {
id: id,
deptid: deptid,
name: name
}
if (button.attr('value') === "POST") {
postdata(inputdata);
} else {
console.log("ERROR");
}
}
function postdata(inputdata) {
$("#response").text("Posted");
$.ajax({
type: "POST",
dataType: "json",
url: "api/mywebapi/Post/",
contentType: "application/json",
data: JSON.stringify(inputdata),
xhrFields: {
withCredentials: true
},
success: function (data, status, xhr) {
$("#response").text(status+" - "+data)
},
error: function (xhr, status, error) {
var json = jQuery.parseJSON(xhr.responseText);
$("#response").text(status)
}
});
}
In the controller
[System.Web.Http.AcceptVerbs("POST")]
public void Post([FromBody]mywebapi value)
{
saves to database
}
Here's what I tested
http://localhost:222/api/mywebapi/Post/new newwebapi ({"id":"1","deptid":"2","name":"testing"})
I get error. How to test this?
thanks
R
Since it's a POST request, you can't test it in your browser by typing in an address (those are GET requests, which contain no body).
To test these types of things you can use something like Postman
or Rest Console (if you're using chrome), there's tons of these types of things in whatever your browsers extension store is called.
Some tools you can use are something like Fiddler
this will let you see what the requests and responses look like, and you can change/modify them as well, though it's probably a bit harder to use than something like PostMan or Rest Console (also more powerful)