How to retrieve other users from a Firebase app? - javascript

I'm learning JavaScript and I'm trying to built a social app in a specific domain. Nothing big as usual social network because it's for a small community.
So I'm using Firebase, JavaScript ES6 and only one HTML file with an <app>. I already have and auth system, profile page for the current user. But my problem is that I don't know, understand the way to have pages from other's profile.
So as far as I succeed to go it's to get the other's users information from by Firebase database. But I'm stuck in my mind. Should I create an HTML file for each user? I don't think so?
This project is for a certification.
And my other problem is and can't make a verification from data. Well I succeed to check if data exist but it doesn't block the process so it updates anyway and get 2 users with the same name (see code below).
firebase
Atom
savePrenom(event){
let database = firebase.database();
event.preventDefault();
let uid = firebase.auth().currentUser.uid;
database.ref('users').once('value', (snapshot)=>{
snapshot.forEach( el=>{
if(prenom.value === el.val().prenom){
console.log('existe déjà');
}
if (prenom.value != el.val().prenom){
savePrenom.style.display= 'none';
editPrenom.style.display= 'block';
prenom.disabled = true;
database.ref('users/'+uid).update({
prenom: prenom.value
})
}
})
});
}

To solve your first problem: Do not create a html file for each user, that's terrible!
You should rather fetch the data and then use DOM manipulation to insert your data into the page. I do not know which database you are using so I can not give you a code sample for the fetching but only one for DOM manipulations.
Let's say you have the following html:
<p id='description'></p>
You can get the element by id and change it's properties, this is known as DOM manipulation.
document.getElementById('description').textValue = 'Very important'
This assigns Very important to the paragraph (the text will appear when executed by a browser).
Since you said you use plain ES6 only, I'm not going into backend technologies like NodeJS.
I can not help you with the second one since I lack information, please submit some code and tell us more about the technologies you are using.

Ok guys sorry for not responding for all question/answers but i got both solutions.
On the first one. As i could get the informations from a user a simply add some data-classes to passe the data that i could get from firebase. But their was a easier solution. From the moment i can get any information inside a user, i could get the key of each user using snapshot.key (which i forgot). So then it's easy, using a forEach element, each link to each profil use the right information on an other page.
Second question to check if a username already existe when changed for exemple. Well, i started to make a once reference value on my database users. Then if my pseudo.value === el.val().pseudo that means it existe to error message. If not, the user can change his username if wanted with .update for firebase.
database.ref('users').once('value', (snapshot)=>{
let find = false;
snapshot.forEach(el =>{
if(pseudo.value === el.val().pseudo){
//console.log('YEAH');
find = true
}
})
if (find === false) {
savePseudo.style.display= 'none';
editPseudo.style.display= 'block';
pseudo.disabled = true;
database.ref('users/'+uid).update({
pseudo: pseudo.value
})
}
Thanks all.

Related

How to isolate a Gunjs database?

I've been trying out GunJs for a couple of days now and I'm really enjoying it. As a starter project I've followed the Fireship chat dapp video aimed at building your own chat.
Here's the issue, now that I've finished the tutorial I would like to create my own chat. However, for some reason if I get a 'chat' node within my own app it seems to pick up on the same 'chat' node as the tutorial one that is online.
onMount(() => {
// Get Messages in large chat
db.get('chat')
.map()
.once(async (data, id) => {
if (data) {
// key for E2E - to do: change for web3
const key = '#foo';
var message = {
//transform the data
who: await db.user(data).get('alias'),
what: (await SEA.decrypt(data.what, key)) + '',
when: GUN.state.is(data, 'what'),
};
if (message.what) {
messages = [...messages.slice(-100), message]
}
}
})
})
This is also the case if I change the encryption key (then the messages just become undefined). Multiple questions arise from this:
Are graph node names unique within the whole of GunDb?
How do you handle conflicts where two gun-based apps call on the same node name?
Is this problem generally solved through filtering using 'header' props?
How do I make it pick up on only my data?
Even if I've read most of the docs, there seems to be something I'm missing in my comprehension of how the graph is generally seperated between apps. Any insight on how this works would be much appreciated.
Are graph node names unique within the whole of GunDb?
Yes.
How do you handle conflicts where two gun-based apps call on the same node name?
You don't. The expected result will be, they will overwrite each other.
Is this problem generally solved through filtering using 'header' props?
I don't think it's the right way to do it.
How do I make it pick up on only my data?
Use your own relay server.
Conclusion :
gunDB doesn't really care about the who fetch / put the data. If you want to protect your data, use your own relay server (not a public one), and put data in your user space. user space is readonly to the public, but read/write for the owner.

Custom Tab in the Field Service Schedule Board

I found this blog: http://www.powerobjects.com/2016/08/01/advanced-customizations-for-the-custom-tab-in-the-field-service-schedule-board/#collapse2
In it the author describes using configuration to create a new tab in the Field Services Schedule Board by pointing it to a CRM web resource.
The blog includes the following javascript:
function updateBooking()
{
var entityRecordGuid = "10B8A40B-D499-E611-80E6-A45D36FC5A4C";
// GUID is hardcoded to make the sample code easier to understand.
// We can extend this customization to be able to extract the selected booking IDs
// from the SChedule Board's DOM, but that is out of scope for now
var bookableResourceBooking = new XrmServiceToolkit.Soap.BusinessEntity("bookableresourcebooking", entityRecordGuid);
bookableResourceBooking.attributes["cus_urgency"] = document.getElementById('UrgencyInput').value;
bookableResourceBooking.attributes["cus_notes"] = document.getElementById('NoteInput').value;
var updateResponse = XrmServiceToolkit.Soap.Update(bookableResourceBooking);
if (updateResponse == "") { // clear fields if synced to crm
document.getElementById('UrgencyInput').value = "";
document.getElementById('NoteInput').value = "";
} else {
alert('Data didn't sync to CRM');
}
}
The problem that I've got is that I'm not sure how to get the entityRecordGuid value dynamically.
There doesn't seem to be a way of configuring the web resource to
have the selected Item as part of the querystring
There seem to be undocumented JavaScript libraries for Field
Services; however, I can't access them from the web resource IFrame
and of course, they're undocumented.
Has anyone else tried to do this? I'm using CRM Online
I ended up doing this by scraping the HTML directly rather than trying to use any of the API methods from Field One.
This wasn't really a satisfactory answer for me. It depends on the Unscheduled Orders board being in a certain order and since this is changeable by the end-user my solution is very fragile.
For anyone else looking, I did manage to find these API methods; however, I couldn't find any documentation for them so assume that they are unsupported. I also couldn't tie them together to achieve what I wanted
// get the id of the sub grid
F1SDK.SchedulerPage.UnscheduledOrdersGrid.id
// -> "UnscheduledGrid"
F1SDK.SchedulerPage.UnscheduledOrdersGrid.getItemId()
// -> "UnscheduledGrid"
F1SDK.SchedulerPage.UnscheduledOrdersGrid.getStore().storeId
// -> "UnscheduledWorkOrders"
F1SDK.SchedulerPage.UnscheduledOrdersGrid.getStore().data.items[0].internalId
F1SDK.SchedulerPage.UnscheduledOrdersGrid.selModel.selected.items[0].internalId
// Get a subgrid
FieldOneSkyUtils.Subgrid.GetSubgrid('id')
F1SDK.data.models.WorkOrder.getFields()
F1SDK.data.models.WorkOrder.getIdByWONumber('00106')
// -> {55caa97d-429a-e611-80e6-c4346bc4bef0}

get foreignId Data from the feed of a user [Stream Js]

hi i'm trying to implement getstream.io in my project.
i'm using https://github.com/GetStream/stream-js
as my server side script is in nodeJS.
i'm able to create a user in feed using
user1 = client.feed('user', 'dpz');
i'm creating activity for this user using using
activity ={
"actor":"user:1",
"message": "#flat_4_bfcaffca-c35f-11e5-8080-8001002e75f6",
"verb":"tweet",
"object":"tweet:4",
"foreign_id": "flat:4"
};
user1.addActivity(activity);
if i want to get all records of that user,
i use
user1.get()
.then(function(body) { console.log(JSON.stringify(body)); })
.catch(function(reason) { console.log(JSON.stringify(reason.error));});
i get result as :
{"duration":"19ms",
"next":"",
"results":[{
"actor":"user:1",
"foreign_id":"flat:4",
"id":"41231d40-ca5a-11e5-8080-800047dac62a",
"message":"#flat_4_bfcaffca-c35f-11e5-8080-8001002e75f6",
"object":"tweet:4",
"origin":null,
"target":null,
"time":"2016-02-03T09:41:09.335584",
"to":[],
"verb":"tweet"
}]
}
in your rest_ documentation
https://getstream.io/docs_rest/#feed_detail
you have specified
feed/(feed_slug)/(user_id)/(activity_id|foreign_id)/
to delete an activity for if the foreign key matches criteria.
in your nodejs code
user1.removeActivity({foreignId: 'flat:4'})
line works to remove the feed for that user where foreign key is flat:4
user1.get({foreignId: 'flat:4'})
does not work
can you please help if i want to get feeds with the foreignId as 'flat:4'
is there any way for such ?
please help as i'm stuck on this point only.
The feed/(feed_slug)/(user_id)/(activity_id|foreign_id)/ endpoint is only for DELETE requests. At this present is not possible to retrieve activities by its foreign_id. That field can only be used to perform cascaded deletion and/or to define the uniqueness of your data.
Looking at the code that you added, it seems like to use references to feeds as the value for foreign_ids, if that's the case then you are probably using this field in a weird/wrong way and you should create a new question on SO to ask help with the integration of your data.

Change URL data on page load

Hello I have a small website where data is passed between pages over URL.
My question is can someone break into it and make it pass the same data always?
For example let say, when you click button one, page below is loaded.
example.com?clicked=5
Then at that page I take value 5 and get some more data from user through a form. Then pass all the data to a third page. In this page data is entered to a database. While I observe collected data I saw some unusual combinations of records. How can I verify this?
yes. as javascript is open on the website, everyone can hack it.
you will need to write some code on you backend to validade it.
always think that you user/costumer will try to hack you sytem.
so take precautions like, check if user is the user of the session, if he is logged, if he can do what he is trying to do. check if the record that he is trying get exists.
if u are using a stand alone site, that u made the entire code from the ashes, you will need to implement this things by yourself.
like using the standard php session, making the data validation etc.
or you can find some classes that other people have made, you can find a lot o this on google. as it is a common problem of web programing.
if u are using a backed framework that isnt from another world, probably already has one. sp, go check its documentation.
html:
<a id = 'button-one' name = '5'> Button One </a>
javascript:
window.onload = function() {
document.getElementById('button-one').onclick = function() {
changeURL(this.attributes.name.value);
};
};
function changeURL(data) {
location.hash = data;
}

Meteor - Allow multiple users to edit a post

I'm not able to use the node server debugger so I'm posting here to see if I can get a nudge in the right direction.
I am trying to allow multiple users to edit documents created by any of the users within their specific company. My code is below. Any help would be appreciated.
(Server)
ComponentsCollection.allow({
// Passing in the user object (has profile object {company: "1234"}
// Passing in document (has companyId field that is equal to "1234"
update: function(userObject, components) {
return ownsDocument(userObject, components);
}
});
(Server)
// check to ensure user editing document created/owned by the company
ownsDocument = function(userObject, doc) {
return userObject.profile.company === doc.companyId;
}
The error I'm getting is: Exception while invoking method '/components/update' TypeError: Cannot read property 'company' of undefined
I'm trying to be as secure as possible, though am doing some checks before presenting any data to the user, so I'm not sure if this additional check is necessary. Any advice on security for allowing multiple users to edit documents created by the company would be awesome. Thanks in advance. -Chris
Update (solution):
// check that the userId specified owns the documents
ownsDocument = function(userId, doc) {
// Gets the user form the userId being passed in
var userObject = Meteor.users.findOne(userId);
// Checking if the user is associated with the company that created the document being modified
// Returns true/false respectively
return doc.companyId === userObject.profile.companyId;
}
Looking at the docs, it looks like the first argument to the allow/deny functions is a user ID, not a user document. So you'll have to do Meteor.users.findOne(userId) to get to the document first.
Do keep in mind that users can write to their own profile subdocument, so if you don't disable that, users will be able to change their own company, allowing them to edit any post. You should move company outside of profile.
(If you can't use a proper debugger, old-fashioned console.log still works. Adding console.log(userObject) to ownsDocument probably would have revealed the solution.)

Categories

Resources