Get a value of item in the array - mongodb

I have a structure and I want to find a value of token which is a sub-item of access_tokens for a comparing value of tokens. How can I find a token?
{
"_id" : ObjectId("5aa28846de35244ec439a563"),
"user" : ObjectId("5a9d53e52d989d2accda2ee5"),
"refresh_token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJyZWZyZXNoX3Rva2VuIiwianRpIjoiNWE1NDZmOGQtNjBjMy00YmYzLTk0OGQtYjJiM2E5MDU5MWMwIiwib2JqZWN0aWQiOiI1YTlkNTNlNTJkOTg5ZDJhY2NkYTJlZTUiLCJleHAiOjE1MjA2MDQ3MjMsImlzcyI6IlByb25ldCBBUyIsImF1ZCI6IkF1dGhBcGkifQ.sxfUJgFnfMKKtSOLzksfPB-FqQN4ydaKi9YAVZqobK4",
"expTime" : "9.03.2018 14:12:03",
"access_tokens" : [{
"token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhY2Nlc3NfdG9rZW4iLCJqdGkiOiIxMzM1Nzg0My0xNzRhLTQwOWYtOTgyMS0yY2ZhN2U1NmE5NDYiLCJvYmplY3RpZCI6IjVhOWQ1M2U1MmQ5ODlkMmFjY2RhMmVlNSIsImV4cCI6MTUyMDYwNDcyMywiaXNzIjoiUHJvbmV0IEFTIiwiYXVkIjoiQXV0aEFwaSJ9.KgYWj8w89W4DsyX5pkg7OPuCyT2DFUSAktkMmlb1kOk",
"exp_date" : "9.03.2018 14:12:03"
}]
}

I have class for my access token which is called SubToken and there is a structure for a collection which stored in mongodb and it is called TokenCollection. I reached subtoken (access token) which is sub item of a refresh token it is called Token.
SubToken res = TokenCollection.Find(new BsonDocument { { "access_tokens.token", access_token } }).FirstAsync().Result.access_tokens.Find(x => x.token == access_token);

Related

Flutter : can't get all response body from get request

I have get request in Flutter app, when I test the request in postman I get all data, something like this :
{
"result":{
"name" : "somename",
"images":[
"test.jpg",
"test2.jpg"
],
"sizes":[
{
"id": 1,
"value" : 5
},
{
"id": 2,
"value" : 15
}
]
}
}
I call data and print them like this without using models:
var data = json.decode(response.body);
print(data['result']['name']);
print(data['result']['images']);
print(data['result']['sizes']);
it is print all things expect last one.
where must be the mistake?
Solved, by adding "?sizesView = true" to the link
final response = await http.get(path +'?sizesView = true'):
you should get the index of the last one because it is in a dictionary not a list do this:
print(data['result']['sizes'][0]['id']) // it will get the first index of the sizes list and then get the id key
or you can creat a model of list to get the indexes of your list

How MongoClient::save(...) might change the _id field of document parameter

I have a class User that embeds a JsonObject to represent the user's fields. This class looks like that:
class User {
private JsonObject data;
public User(...) {
data = new JsonObject();
data.put("...", ...).put(..., ...);
}
public String getID() { return data.getString("_id"); }
// more getters, setters
// DB access methods
public static userSave(MongoClient mc, User user){
// some house keeping
mc.save("users", user.jsonObject(), ar -> {
if(ar.succeeded()) { ... } else { ... }
});
}
}
I've just spent more than half a day trying to figure out why a call to user.getID() sometimes produced the following error: ClassCastException: class io.vertx.core.json.JsonObject cannot be cast to class java.lang.CharSequence. I narrowed down to the userSave() method and more specifically to MongoClient::save() which actually produces a side effect which transforms the data._id from something like
"_id" : "5ceb8ebb9790855fad9be2fc"
into something like
"_id" : {
"$oid" : "5ceb8ebb9790855fad9be2fc"
}
This is confirmed by the vertx documentation which states that "This operation might change _id field of document parameter". This actually is also true for other write methods like inserts.
I came with two solutions and few questions about doing the save() properly while keeping the _id field up to date.
S1 One way to achieve that is to save a copy of the Json Object rather than the object itself, in other words : mc.save("users", user.jsonObject().copy(), ar -> {...});. This might be expensive on the long run.
S2 An other way is to "remember" _id and then to reinsert it into the data object in the if(ar.succeeded()) {data.put("_id", oidValue); ...} section. But as we are asynchronous, I don't think that the interval between save() and the data.put(...) is atomic ?
Q1: Solution S1 make the assumption that the ID doesn't change, i.e., the string 5ceb8ebb9790855fad9be2fc will not change. Do we have a warranty about this ?
Q2: What is the right way to implement the saveUser() properly ?
EDIT: The configuration JSON object user for the creation of the MongoClient is as follows (in case there is something wrong) :
"main_pool" : {
"pool_name" : "mongodb",
"host" : "localhost",
"port" : 27017,
"db_name" : "appdb",
"username" : "xxxxxxxxx",
"password" : "xxxxxxxxx",
"authSource" : "admin",
"maxPoolSize" : 5,
"minPoolSize" : 1,
"useObjectId" : true,
"connectTimeoutMS" : 5000,
"socketTimeoutMS" : 5000,
"serverSelectionTimeoutMS" : 5000
}

Creating JWT custom claims in DataPower

Running on DataPower 7.5.2.0
I created a JWT Generator as part of a AAA Policy and it is working fine, I am able to generate, sign and then externally verify the JWT with no issues.
Now I want to add a custom claim to the JWT, so I ticked the box for Custom and then uploaded this Gateway script file:
var claim = {
"result" : {
"user" : "hardcode"
}
};
session.output.write(claim);
and it generates the correct JWT with the user attribute. However when I try to add a second value to it like so:
var claim = {
"result" : {
"user" : "hardcode",
"name" : "myname"
}
};
session.output.write(claim);
I now get this error:
[Error: Required CustomClaim Name or Value field missing] errorMessage: 'Required CustomClaim Name or Value field missing', errorCode: '0x8580005c', errorDescription: 'GatewayScript console log message.', errorSuggestion: 'GatewayScript console log message. Refer to the message for more information.'
Which is the same message I got before I realized I had to set the output to result from the InfoCenter's vague documentation.
How do I add multiple custom claims in the JWT Generator Gateway script??
It would appear that DataPower only allows you to add a single custom claim, so you just need to make that a complex object like so:
var claim = {
"result" : {
"claim" : {
"user" : "hardcode",
"one" : true,
"clientId" : "asdf-asdf-asdf",
"endpoint" : "http://192.168.142:8080/member/ws"
}
}
};
session.output.write(claim);
This then generates the correct JWT with a nest claim.
eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhcGljIiwic3ViIjoiYWRtaW4iLCJleHAiOjE0ODIyNjU5ODQsImlhdCI6MTQ4MjI2MjM4NCwianRpIjoiZDhjNTE1ZDEtZmVjMS00ZGVmLThiNDctZmYzY2E2OWVjOWRiIiwibm9uY2UiOiJtN2lVZlBqTCIsImF1ZCI6ImlkMSIsImNsYWltIjp7InVzZXIiOiJmcmVkIiwib25lIjp0cnVlLCJjbGllbnRJZCI6ImFzZGYtYXNkZi1hc2RmIiwiZW5kcG9pbnQiOiJodHRwOi8vMTkyLjE2OC4xNDI6ODA4MC9tZW1iZXIvd3MifX0.viakwnM5bhhmGIn0QmDJTmsWCuIciO2BOdUVyxYpsFA

What am I doing wrong when manipulating data in Meteor/MongoDB?

I have this helper
myClub: function(){
var currentUserId = Meteor.userId();
var user = Meteor.users.findOne({_id: currentUserId});
return user;
}
I want it to return user.role
Here is my user in MongoDB
{
"_id" : "RdirmrLG3t8qBk4js",
"createdAt" : ISODate("2016-04-17T19:40:56.877Z"),
"services" : {
"password" : {
"bcrypt" : "$2a$10$cPe92XR9DT238bH/RanYEu.J6K2ImvAEbWOcVq6j9luI0BH08Qdly"
},
"resume" : {
"loginTokens" : [
{
"when" : ISODate("2016-04-17T19:51:49.474Z"),
"hashedToken" : "uVKUj/7JEkkOuizXhjl212Z38E47HXCex+D4zRikQ1k="
}
]
}
},
"username" : "worker",
"role" : "worker",
"club" : "hzSKAJfPXo7hSpTYS"
}
The code above works just fine. So it finds the current user and outputs info about it. But when I change user to user.role I get the following errormessage.
TypeError: Cannot read property 'role' of undefined
at Object.myClub
How can it be undefined? Is my syntax incorrect?
Template helpers are reactive, which means they update themselves as the app state changes or new data appears. In your case, the helper is called immediately when the template is rendered and before the Meteor.users collection is filled. Therefore, the .findOne() method returns undefined. It will be corrected in the second pass after new data arrives.
The simple fix here is to check whether the data is present inside the helper:
myClub: function(){
var currenUserId = Meteor.userId();
var user = Meteor.users.findOne({_id: currenUserId});
if(!user) return 'NO DATA';
return user.role;
},
In real life you'll probably want to wait for the basic data to be loaded before you render the template. That is usually done on the controller level.
Try:
myClub: function(){
return Meteor.user() && Meteor.user().role;
}
This is shorthand for return the role if there's a user.
As far as the role field not showing up, make sure that you are publishing that key from the server and subscribing to it. For example:
Meteor.publish('me',function(){
return Meteor.users.find(this.userId,{fields: {role: 1, username: 1, profile: 1, emails: 1}});
});
And on the client:
var me = Meteor.subscribe('me');
if ( me.ready() ) console.log("Ta-da! The role is: "+Meteor.user().role);
make sure that you subscribed to all data you need.
By the way, you can try following:
role: function(){ return (Meteor.user() || {}).role; }
Cheers

How to find payment collection using response id?

I am developing angularjs nodejs application
Following has Payment Collection find function and result
var collectionId = "5673d6c7da28e94f51277894"
Payment.find({id: collectionId}).exec(function(err,payment)
console.log(payment);
);
Console result :
{
"_id" : ObjectId("5673d6c7da28e94f51277894"),
"response" : {
"status" : "approved",
"id" : "PAY-9N740711P28316116KZX5U4I"
}
}
I need to find payment collection using response id
My code here
var paymentId = "PAY-9N740711P28316116KZX5U4I"
Payment.find({ response : {id: paymentId}}).exec(function(err,payment)
console.log(payment);
);
Console result :
undefined
If you are not clear question, please comment
Hope answer, thanks
It should be:
Payment.find({ 'response.id': paymentId }).exec(function(err,payment) {
console.log(payment);
});