Is there a way to update api key value using sdk? - aws-sdk

I need to update the api key value using my lambda function.
I looked through API Gateway SDK Documentation and I thought updateApiKey was the best option, but when I send the request, I get an error as return:
BadRequestException: Invalid patch path 'value' specified for op 'replace'. Must be one of: [/description, /enabled, /name, /customerId]
at Object.extractError (/var/task/node_modules/aws-sdk/lib/protocol/json.js:51:27)
at Request.extractError (/var/task/node_modules/aws-sdk/lib/protocol/rest_json.js:55:8)
at Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
at Request.emit (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
at Request.emit (/var/task/node_modules/aws-sdk/lib/request.js:683:14)
at Request.transition (/var/task/node_modules/aws-sdk/lib/request.js:22:10)
at AcceptorStateMachine.runTo (/var/task/node_modules/aws-sdk/lib/state_machine.js:14:12)
at /var/task/node_modules/aws-sdk/lib/state_machine.js:26:10
at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:38:9)
at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:685:12)
Basically, it is saying that I can't update "value", so I couldn't do what I need
For now, my code is that:
let sendPromise = null;
let params = {
"apiKey": "xxxxxxxxx",
patchOperations: [
{
op: "replace",
path: "value",
value: "teste123"
}
]
};
sendPromise = new AWS.APIGateway().updateApiKey( params ).promise();
try {
const data = await sendPromise;
return criarResposta( 200, `{
"message": "OK"
}` );
} catch (err) {
console.error(err, err.stack);
return criarResposta( 500, err.stack );
}
Is there any other function to update the api key value?

There is no other function to update the api key value. I think this is by design.
I do not know this for sure but there is evidence that AWS designed the apikey resource's value attribute immutable:
The AWS REST api for ApiGateway is the service's endpoint which supports the largest subset of operations available. The attributes which support modification are listed in the REST api documentation: /customerId, /description, /enabled, /labels, /name, /stages. [1]
The AWS Management Console does not support modification of the apikey value either. There is only the option to 'show' the apikey's value.
So if you want to change the value, you have to delete the existing apikey and create a new one. This includes recreating all the usageplankey resources which associate apikey resources with usageplan resources.
References
[1] https://docs.aws.amazon.com/apigateway/api-reference/link-relation/apikey-update/#remarks

Related

GoogleJsonResponseException: Field name is required

I'm working with the Google Analytics API for the first time and I'm trying to create a new property. I wrote a JS function in Google App Script:
function insertProperty() {
var resource =
{
// "accountId": "177832616",
"resource":{
"name": "Test Property 7",
// "dataRetentionResetOnNewActivity": false,
"websiteUrl": "https://www.test.com"
}
}
var accountID = '177832616';
var request = Analytics.Management.Webproperties.insert(resource, accountID);
// request.execute(function (response) { console.log(property.id) });
}
This is the error the API throws:
GoogleJsonResponseException: API call to analytics.management.webproperties.insert failed with error: Field name is required. (line 56, file "Code")
The insert() method seems to take two parameters: insert(Webproperty resource, string accountId);
Since it's not recognizing the name key/value I added to resource, my guess is I haven't declared the variable as a Webproperty type and I'm not sure how to do this. I assumed Webproperty was a { } variable type, but at this point I'm not sure what to try next. Doing research online, I'm not able to find anything regarding the API's Webproperty so any context/info is helpful.
From your question, I could understand that Google Analytics API is used with Advanced Google services of Google Apps Script. In this case, resource of Analytics.Management.Webproperties.insert(resource, accountId) can directly use the request body of the method of "Web Properties: insert". I think that the reason of your error is due to this. So please modify as follows and test it again.
From:
var resource =
{
// "accountId": "177832616",
"resource":{
"name": "Test Property 7",
// "dataRetentionResetOnNewActivity": false,
"websiteUrl": "https://www.test.com"
}
}
To:
var resource = {
"name": "Test Property 7",
"websiteUrl": "https://www.test.com"
}
Note:
When accountId is not correct, an error occurs. Please be careful this.
From iansedano's comment, in this case, request of var request = Analytics.Management.Webproperties.insert(resource, accountID); directly returns the values. So you can see the value like console.log(request) and console.log(request.toString()).
Reference:
Web Properties: insert

Custom permissions using HATEOS in REST JSON

I have an API with Search (GET), Create (POST) and Update method (PUT) on a resource.
The Update (PUT) operation supports update of parameters such as 'name', 'value' and 'status'. The permission for updating 'status' is different from updating other parameters.
When UI reads the GET (search) response it enable update of fields(name, value and status) based on the permissions returned. Planning to return permissions using HATEOS as below.
"self": {
"href": "https://mobile-services.test.com/api/V1/area/resorce/{resourceId}",
"methods": [ "GET", "POST" ]
},
Is it allowed return custom values (such as "POST-Status") for 'methods" key? If no, please suggest a way of handling the permissions in this scenario.

How to add array values in Claims of IdToken in Cognito using claimsToAddOrOverride

I am using Pre Token Generation to update the claims of IdToken.
I am successfully able to update claim using single key:value pair.
Below is the sample example of that.
event["response"] = {"claimsOverrideDetails":{"claimsToAddOrOverride":{"scope": "test.debug"}}}
But when i am trying to add array of string inside that, it giving me internal server error (Response from AWS Cognito)
Ex:
event["response"] = {"claimsOverrideDetails":{"claimsToAddOrOverride":{"scope": ["test1","test2]}}}
It is working fine using 'Test' option of lambda function.
If i am using groupsToOverride then it is overriding the cognito:groups claim.
Any help?
I think this must be a bug with Cognito and unfortunately will require a workaround until it's resolved.
It's not ideal I know, but I've worked around this issue by using a delimited string which I then parse to an array when I receive the token.
Lambda:
exports.handler = (event, context, callback) => {
event.response = {
"claimsOverrideDetails": {
"claimsToAddOrOverride": {
"scope": "test1|test2"
}
}
};
// Return to Amazon Cognito
callback(null, event);
};
Client:
const token = jwt.decode(id_token);
const scopes = token.scope.split('|');
The name scope have special meaning in a JWT, libraries expect this to be a list in string form separated by space. So the scopes test1 and test2 would become "test1 test2".
I would recommend using space as separator and not any other format. If you prefer another format just give your field a different name - like group.
{
"iss": "https://authorization-server.example.com/",
"sub": " 5ba552d67",
"aud": "https://rs.example.com/",
"exp": 1544645174,
"client_id": "s6BhdRkqt3_",
"scope": "openid profile reademail"
}

Angular resource 404 Not Found

I've read other posts that have similar 404 errors, my problem is that I can correctly query the JSON data, but can't save without getting this error.
I'm using Angular's $resource to interact with a JSON endpoint. I have the resource object returning from a factory as follows:
app.factory('Product', function($resource) {
return $resource('api/products.json', { id: '#id' });
});
My JSON is valid and I can successfully use resource's query() method to return the objects inside of my directive, like this:
var item = Product.query().$promise.then(function(promise) {
console.log(promise) // successfully returns JSON objects
});
However, when I try to save an item that I've updated, using the save() method, I get a 404 Not Found error.
This is the error that I get:
http://localhost:3000/api/products.json/12-34 404 (Not Found)
I know that my file path is correct, because I can return the items to update the view. Why am I getting this error and how can I save an item?
Here is my data structure:
[
{
"id": "12-34",
"name": "Greece",
"path": "/images/athens.png",
"description": ""
},
...
]
By default the $save method use the POST verb, you will need to figure out which HTTP verbs are accepted by your server en order to make an update, most modern api servers accept PATCH or PUT requests for updating data rather than POST.
Then configure your $resource instance to use the proper verb like this :
app.factory('Product', function($resource) {
return $resource('api/products.json', { id: '#id' }, {'update': { method:'PUT' }});
});
check $resource docs for more info.
NOTE: $resource is meant to connect a frontend with a backend server supporting RESTful protocol, unless you are using one to receive data & save it into a file rather than a db.
Otherwise if you are only working with frontend solution where you need to implement $resource and have no server for the moment, then use a fake one, there is many great solutions out there like deployd.
You probably don't implement POST method for urls like /api/products.json/12-34. POST method is requested from angular for saving a new resource. So you need to update your server side application to support it and do the actual saving.
app.factory('Product', function($resource) {
return $resource('api/products.json/:id', { id: '#id' });
});
Try adding "/:id" at the end of the URL string.

Ember error when json response root key is singular

I am getting an Ember error when the response json root is singular.
json response:
{"subscription": {"id": "1"}}
error:
Assertion failed: Your server returned a hash with the key subscription but you have no mapping for it
model:
App.Subscription
If I pass a plural root key subscriptions in the json response, it works fine. I don't think I should have to do this though since the singular version is default behavior for active
_model_serializers if there is only one resource to send.
Is this a bug in Ember or should I be doing something for this to be supported?
What might help is to define plurals on your adapter. So in the case of a model called App.Subscription this could look like this:
App.Adapter = DS.RESTAdapter.extend();
App.Adapter.configure('plurals', { "subscription": "subscription" });
Edit
As for the .json one possible solution might be to hook into the buildURL function of your RESTAdapter and adding the .json suffix yourself. This could look something like this:
App.Adapter = DS.RESTAdapter.extend({
buildURL: function(record, suffix) {
var url = this._super(record, suffix);
return url + ".json";
}
})
This would make a request to http://localhost:4000//subscription.json
Hope it helps.