quickblox - how can I get content by owner? - quickblox

I'm working on a CMS and I'd like to know if I can get the content by owner, in other to show the pictures from the app's users.
I know that i can get the content list of the current user with:
QB.content.list(function(error, response){
if(error) {
console.log(error);
} else {
// Success
}
});
but can I access to other user's content?
thank you very much

Unfortunately, this functionality isn't in the API right now. If it's profile pictures you want, you can just use the blob parameter on a user.
If you can provide us some good use cases for - send me an email at alex.bass#quickblox.com and we'll consider adding it.
Hopefully this hasn't inconvenienced you too much.
EDIT:
I've just been informed by my colleague that there is a way around this - it's not perfect, but it does get the job done.
You can create a custom objects class with just 2 fields: blob_id and user_id. Then when content is uploaded, just add a record in the callback.
Here's the complete code - I haven't tested it though. Let me know if you have any troubles.
When uploading:
QB.init(app_id, auth_key, auth_secret);
var user_id;
QB.createSession({login: <username>, password: <password>}, function(error, response){
if(error) {
console.log(error);
} else {
// Just making a record of the user_id for use later
user_id = response.id;
}
});
//
// later...
//
var files = $("input[type=file]")[0].files;
// This function will create "content" record in QB, then when QB returns AWS URL to
// post to, it will automatically upload it, then on completion, mark uploaded.
QB.content.createAndUpload({'file': files, 'public': true}, function(err, response){
if (err) {
console.log(err);
} else {
// Response will contain blob ID.
var data = {
blob_id: response.id,
blob_owner: user_id
}
QB.data.create("BlobsToUsers", data, function(err, response){
if (err) {
console.log(err);
} else {
// Done
}
});
}
});
Then, later on when you're listing content:
QB.data.list("BlobsToUsers", { blob_owner: user_id } function(err, response){
if (err) {
console.log(err);
} else {
// response.items will be array of all records with the specified blob_owner.
// You could also filter by date, timestamp or whatever you want.
}
});
To break it down into steps:
Use "QB.content.createAndUpload()" to upload data
Create custom objects record matching blob ID to owner
Later, when listing, get records from Custom Objects.
Do whatever you want from there. There is a function named "QB.content.getFileUrl()" that will return an AWS URL that you use for an <img> tag.
Hope this helps

Related

React-native : how to check if it's the user's first connection?

I 'm new to react-native and I would like to set up my first page of the app with
1- The user never logged in the app, I 'll present the app with some slides + go to signup page
2 -The user is already in => directly go to the user page
3 -The user is already in but the id is not correct
Can you guide me through it ?
For the first point I really don't know how to check if the user exist in my db
For the second and third points I thought I'd try :
onPressLogin(){
fetch('linktomyAPI',{
method: 'POST',
headers:{
'Content-Type' : 'application/json',
'Accept':'application/json'
},
body: JSON.stringify({
username:this.state.username,
password: this.state.password,
})
})
.then(response => response.json())
.then((responseData) =>{
if(responseData.error !== 1){ // verify the success case, as you didn't provide the success case i am using the error code
this.setState({ // its recommended you verify the json before setting it to state.
userdetail: responseData,
})
setTimeout(() => {
Actions.Authentication();
}, 2300);
AsyncStorage.setItem('username', this.state.username); // its setItem not saveitem.
} else {
console.log(responseData);
Alert.alert(JSON.stringify(responseData)); // Alerts doesn't allow arrays or JSONs, so stringify them to view in Alerts
}
}).catch((error) => {
// handle catch
console.log("error:"+JSON.stringify(error));
});
}
Do you think I can do this way, is that relevant?
Thanks for taking the time to answer me. I'm really new so I need help and explanations. Thanks !!! :)
you can use the UserInfo to do. firstly, you have saved the user info in memory use Session js and in the device local file use AsyncStore. you already do it use the AsyncStore.
firstly save the user info into Session,the Session structure is:{id:"dd333",name:"john"},
...
setTimeout(() => {
Actions.Authentication();
}, 2300);
Session.id = res.id;
Session.name = res.name;
AsyncStorage.setItem('userinfo', Json.stringfy(res));
then you can show diffent page and condition.
// in the component which you want compoentDidMount
componentDidMount() {
// here you can try to get it from AsyncStore if the Session is null.
// then hanle it as the followng
if(Session.id == ""){
//default it is "", it means the user does not login
} else if(Session.id != "222"){
// the user id is not correct
} else {
// here is the user login and id is correct
}
}

Create users under an alias

I'm trying to create an user under an alias. for eg. Say I've a company and my AWS account is My-Org-007 and under this I can create users. But I want to do this using API. when I went through the documentation, it is given as below.
https://iam.amazonaws.com/?Action=CreateUser
&Path=/division_abc/subdivision_xyz/
&UserName=Bob
&Version=2010-05-08
&AUTHPARAMS
Here I'm confused about the Path(where can I get the path) and AUTHPARAMS(I have Access key ID and Secret access key, are these that I need and how d I access it in API Call).
please let me know on how I can do it using the API.
Thanks
Unless you have a very compelling reason to use AWS APIs directly, you would want to use the AWS SDKs. SDKs make your life a lot easy in achieving what you want. Check CreateUser documentation here for NodeJS SDK(SDKs for other programming languages like Go, Java, Python, .Net, C++ ... are also available for you to use): http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html
/* The following create-user command creates an IAM user named Bob in the current account. */
var params = {
UserName: "Bob"
};
iam.createUser(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
/*
data = {
User: {
Arn: "arn:aws:iam::123456789012:user/Bob",
CreateDate: <Date Representation>,
Path: "/",
UserId: "AKIAIOSFODNN7EXAMPLE",
UserName: "Bob"
}
}
*/
});
Calling the createUser operation
var params = {
UserName: 'STRING_VALUE', /* required */
Path: 'STRING_VALUE'
};
iam.createUser(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});

Loopback3 - Find current user by access token

I have read in Loopback3 docs that getCurrentContext() has been deprecated. What I'd like to do is grab the access token and use that to find the associated user in the db, so I can get a company_id that the user belongs to and alter the query to include that in the where clause. I am using MySQL and a custom UserAccount model which extends from User.
I am new to Loopback so struggling to figure this out especially as most of the online help seems to point to getCurrentContext();.
I've set up some middleware to run on the parse phase:
middleware.json
"parse": {
"./modifyrequest": {
"enabled": true
}
}
modifyrequest.js
var loopback = require('loopback');
module.exports = function(app) {
return function tracker(req, res, next) {
console.log('Middleware triggered on %s', req.url);
console.log('-------------------------------------------------------------------');
console.log(req.accessToken);
}
};
However req.accessToken is always undefined. I have added to server.js:
app.use(loopback.token());
Any ideas? Is this the wrong approach ?
SOLUTION
As per Kamal's comment below...
Try setting "loopback#token": {} in middleware.json under "initial:before"
This populates req.accessToken
First, try setting "loopback#token": {} in middleware.json under "initial:before".
Then, if you are accessing accessToken from request object, you can find the userId within that accessToken object. Try to log req.accessToken, you will find the userId therein.
You can use that user id to search for corresponding user in the database.
User.findById(req.accessToken.userId, function(err, user){
if(err) {
//handle error
}
else {
//access user object here
}
});

firebase once() gives permission error, though ref() succeeds

The goal: scan firebase data and delete items older than a given time.
The problem: the query generates a permissions error, though other read operations are allowed. Yet the problem seems to be the .read rule, since when it's taken out, everything works.
I authenticate using a token with "username" and "dataClass" embedded. Authentication normally works fine, and subscribed clients are receiving updates. Debugging log and examining the auth() payload show that the "username" and "dataClass" are correctly embedded in the token and correctly extracted by Firebase.
However, trying to use once() to get a subset of data older than a certain age generates a permission error. I can see the data location using ref(), however, with no error. Why does ref() work and a query doesn't? Possible basic misunderstanding: does a query return a copy of data, as it would in a SQL database, or does it return pointers to the data?
Here's the code, followed by the rules being used. Thanks mucho.
var Firebase = require('firebase');
Firebase.enableLogging(true, true);
// auth token is passed in as an argument
var token;
process.argv.forEach(function(val, index, array) {if (index==2) {token=val;} });
var oneHourAgo=(new Date).getTime() - (minutes*60000);
var fb=new Firebase("https://<mysite>.firebaseio.com/changeMessages");
connect2Firebase(fb,token);
function connect2Firebase(firebase,authToken) {
firebase.auth(authToken, function(error,payload) {
if(error) {
console.log("Login Failed!", error);
} else {
console.log("Login Succeeded!");
console.log(payload);
doSomething();
}
});
}
function doSomething() {
// THIS GIVES PERMISSION ERROR
fb.endAt(oneHourAgo).once('value', function(ss) { console.log(ss.val()); });
// THIS WORKS
//console.log(fb.endAt(oneHourAgo).ref().toString());
}
// THE RULES. Changing to ".read":true makes it work.
{
"rules": {
"changeMessages": {
"$dataClass": {
".read": "auth.dataClass == $dataClass && auth.username == 'admin'",
".write": "auth.username == 'admin'"
}
}
}
}

quickblox web how to upload profile picture

I'm trying to upload a profile picture (blob_id) from a javascript document and I can't find a way, I donĀ“t know if I should use this snippets or even how to use it :(
I'll be so thankfull if you could help me
Thanks
QB.users.update({ id: user_creds.user_id, website: "http://quickblox.com"}, function(error, response){
if(error) {
console.log(error);
} else {
// Success
}
});
sorry about this. We'll be beefing up the documentation soon.
Here's how to upload a profile picture
We'll have a file input:
<input type="file" id="picture" />
Then assuming you have jQuery in your environment, we'll reference it like this:
var profile_picture = $("#picture")[0].files;
Then you upload the file to Quickblox AWS like so:
QB.content.createAndUpload({file: profile_picture, public: true}, function(error, response) {
if (error) {
console.log("upload didn't work");
} else {
var blob_id = response.id;
}
});
As you can see, the ID of the blob is the id field of the response.
You then add this blob ID as the blob_id field of a new user when you create him/her:
QB.users.create({login: "username_here", password: "password_here", blob_id: blob_id_here}, function(error, response){
if(error) {
console.log(error);
} else {
}
});
I made a page which demos the uploading functionality of the Javascript SDK - you can check it out here: http://www.quickblox.com/alex/websdk/upload.html