firebase session for two users [duplicate] - ios

In my main page I have a list of users and i'd like to choose and open a channel to chat with one of them.
I am thinking if use the id is the best way and control an access of a channel like USERID1-USERID2.
But of course, user 2 can open the same channel too, so I'd like to find something more easy to control.
Please, if you want to help me, give me an example in javascript using a firebase url/array.
Thank you!

A common way to handle such 1:1 chat rooms is to generate the room URL based on the user ids. As you already mention, a problem with this is that either user can initiate the chat and in both cases they should end up in the same room.
You can solve this by ordering the user ids lexicographically in the compound key. For example with user names, instead of ids:
var user1 = "Frank"; // UID of user 1
var user2 = "Eusthace"; // UID of user 2
var roomName = 'chat_'+(user1<user2 ? user1+'_'+user2 : user2+'_'+user1);
console.log(user1+', '+user2+' => '+ roomName);
user1 = "Eusthace";
user2 = "Frank";
var roomName = 'chat_'+(user1<user2 ? user1+'_'+user2 : user2+'_'+user1);
console.log(user1+', '+user2+' => '+ roomName);
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
A common follow-up questions seems to be how to show a list of chat rooms for the current user. The above code does not address that. As is common in NoSQL databases, you need to augment your data model to allow this use-case. If you want to show a list of chat rooms for the current user, you should model your data to allow that. The easiest way to do this is to add a list of chat rooms for each user to the data model:
"userChatrooms" : {
"Frank" : {
"Eusthace_Frank": true
},
"Eusthace" : {
"Eusthace_Frank": true
}
}
If you're worried about the length of the keys, you can consider using a hash codes of the combined UIDs instead of the full UIDs.
This last JSON structure above then also helps to secure access to the room, as you can write your security rules to only allow users access for whom the room is listed under their userChatrooms node:
{
"rules": {
"chatrooms": {
"$chatroomid": {
".read": "
root.child('userChatrooms').child(auth.uid).child(chatroomid).exists()
"
}
}
}
}

In a typical database schema each Channel / ChatGroup has its own node with unique $key (created by Firebase). It shouldn't matter which user opened the channel first but once the node (& corresponding $key) is created, you can just use that as channel id.
Hashing / MD5 strategy of course is other way to do it but then you also have to store that "route" info as well as $key on the same node - which is duplication IMO (unless Im missing something).

We decided on hashing users uid's, which means you can look up any existing conversation,if you know the other persons uid.
Each conversation also stores a list of the uids for their security rules, so even if you can guess the hash, you are protected.

Hashing with js-sha256 module worked for me with directions of Frank van Puffelen and Eduard.
import SHA256 from 'crypto-js/sha256'
let agentId = 312
let userId = 567
let chatHash = SHA256('agent:' + agentId + '_user:' + userId)

Related

How can I retrieve all members when querying for appRoleAssignedTo in Microsoft Graph?

I am attempting to programmatically retrieve a list of users (principalType = "User") and their associated appRoleId values for an enterprise app using itsresourceId value from Azure AD. There is a total of ten Users with a combined total of twenty appRoleId values associated with the app. However, when I run my query I receive data for just two users and a combined total of four appRoleId values.
Here's my C# code:
GraphServiceClient myGraphClient = GetGraphServiceClient([scopes]);
// Retrieve the [Id] value for the app. Note [Id] is a pseudonym for the [resourceId] required to retrieve users and app roles assigned.
var servPrinPage = await myGraphClient.ServicePrincipals.Request()
.Select("id,appRoles")
.Filter($"startswith(displayName, 'Display Name')")
.GetAsync()
.ConfigureAwait(false);
// Using the first [Id] value from the [ServicePrincipals] page, retrieve the list of users and their assigned roles for the app.
var appRoleAssignedTo = await myGraphClient.ServicePrincipals[servPrinPage[0].Id].AppRoleAssignedTo.Request().GetAsync().ConfigureAwait(false);
The query returns a ServicePrincipalAppRoleAssignedToCollectionPage (as expected) but the collection only contains four pages (one per User/appRoleId combination).
As an aside, the following query in Microsoft Graph Explorer produces an equivalent result:
https://graph.microsoft.com/v1.0/servicePrincipals/[resourceId]/appRoleAssignedTo
What am I missing here? I need to be able to retrieve the complete list of users and assigned app roles. Any assistance is greatly appreciated.
The issue I was confronting has to do with the pagination feature employed by Azure AD and MS Graph. In a nutshell, I was forced to submit two queries in order to retrieve all twenty records I was expecting.
If you have a larger set of records to be retrieved you may be faced with submitting a much larger number of successive queries. The successive queries are managed using a "skiptoken" passed as a request header each time your query is resubmitted.
Here is my revised code with notation....
// Step #1: Create a class in order to strongly type the <List> which will hold your results.
// Not absolutely necessary but always a good idea when working with <Lists> in C#.
private class AppRoleByUser
{
public string AzureDisplayName;
public string PrincipalDisplayName;
}
// Step #2: Submit a query to acquire the [id] for the Service Principal (i.e. your app).
// Note the [ServicePrincipals].[id] property is synonymous with the [resourceId] needed to
// retrieve [AppRoleAssignedTo] values from Microsoft Graph in the next step.
// Initialize the Microsoft Graph Client.
GraphServiceClient myGraphClient = GetGraphServiceClient("Directory.Read.All");
// Retrieve the Service Principals page containing the app [Id].
var servPrinPage = await myGraphClient.ServicePrincipals.Request().Select("id,appRoles").Filter($"startswith(displayName, 'Your App Name')").GetAsync().ConfigureAwait(false);
// Store the app [Id] in a local variable (for readability).
string resourceId = servPrinPage[0].Id;
// Step #3: Using the [Id]/[ResourceId] value from the previous step, retrieve a list of AppRoleId/DisplayName pairs for your app.
// Results of the successive queries are typed against the class created earlier and are appended to the <List>.
List<AppRoleByUser> appRoleByUser = new List<AppRoleByUser>();
// Note, unlike "Filter" or "Search" parameters, it is not possible to
// add a "Skiptoken" parameter directly to your query in C#.
// Instead, it is necessary to insert the "skiptoken" as request header using the Graph QueryOption class.
// Note the QueryOption List is passed as an empty object on the first pass of the while loop.
var queryOptions = new List<QueryOption>();
// Initialize the variable to hold the anticipated query result.
ServicePrincipalAppRoleAssignedToCollectionPage appRoleAssignedTo = new ServicePrincipalAppRoleAssignedToCollectionPage();
// Note the number of user/role combinations associated with an app is not always known.
// Consequently, you may be faced with the need to acquire multiple pages
// (and submit multiple consecutive queries) in order to obtain a complete
// listing of user/role combinations.
// The "while" loop construct will be utilized to manage query iteration.
// Execution of the "while" loop will be stopped when the "bRepeat" variable is set to false.
bool bRepeat = true;
while (bRepeat == true)
{
appRoleAssignedTo = (ServicePrincipalAppRoleAssignedToCollectionPage) await myGraphClient.ServicePrincipals[resourceId].AppRoleAssignedTo.Request(queryOptions).GetAsync().ConfigureAwait(false);
foreach (AppRoleAssignment myPage in appRoleAssignedTo)
{
// I was not able to find a definitive answer in any of the documents I
// found but it appears the final record in the recordset carries a
// [PrincipalType] = "Group" (all others carry a [PrincipalType] = "User").
if (myPage.PrincipalType != "Group")
{
// Insert "User" data into the List<AppRoleByUser> collection.
appRoleByUser.Add(new AppRoleByUser{ AzureDisplayName = myPage.PrincipalDisplayName, AzureUserRole = myPage.AppRoleId.ToString() });
}
else
{
// The "bRepeat" variable is initially set to true and is set to
// false when the "Group" record is detected thus signaling
// task completion and closing execution of the "while" loop.
bRepeat = false;
}
}
// Acquire the "nextLink" string from the response header.
// The "nextLink" string contains the "skiptoken" string required for the next
// iteration of the query.
string nextLinkValue = appRoleAssignedTo.AdditionalData["#odata.nextLink"].ToString();
// Parse the "skiptoken" value from the response header.
string skipToken = nextLinkValue.Substring(nextLinkValue.IndexOf("=") + 1);
// Include the "skiptoken" as a request header in the next iteration of the query.
queryOptions = new List<QueryOption>()
{
new QueryOption("$skiptoken", skipToken)
};
}
That's a long answer to what should have been a simple question. I am relatively new to Microsoft Graph but it appears to me Microsoft has a long way to go in making this API developer-friendly. All I needed was to know the combination of AppRoles and Users associated with a single, given Azure AD app. One query and one response should have been more than sufficient.
At any rate, I hope my toil might help save time for someone else going forward.
Could you please remove "Filter" from the code and retry the operation. Let us know if that worked.

Using the Browse option

I'm writing an application for Twinfield. I login to an account with 4 administrations in it. I would like to retrieve all information belonging to not payed invoices.
With the search opttion I get al open invoices for a certain office.
string[][] finderOptions = new string[2][];
switch (office)
{
case 0:
finderOptions[0] = new string[] { "office", "xxxx01-01" };
break;
case 1:
finderOptions[0] = new string[] { "office", "xxxx03-01" };
break;
}
finderOptions[1] = new string[] { "dim1", "1300" };
TwinfieldFinder.MessageOfErrorCodes[] errorCodes = xmlFinder.Search(hdrXml, "IVT", "*", 0, 1, 0, finderOptions, out findResult);
This works. But it retuns the invoicenumber and I also need the transaction number. Therefore I perform a Browse to find the traansaction number.
Maybe there is another way to find the complete transaction using the invoicenumber iso the transactionnumber?
The Browse call looks like this:
TwinfieldProcessXml.ProcessXmlSoapClient xmlClient = new
TwinfieldProcessXml.ProcessXmlSoapClient("ProcessXmlSoap", cluster + "/webservices/processxml.asmx?wsdl");
TwinfieldProcessXml.Header hdrXml2 = new TwinfieldProcessXml.Header();
hdrXml2.CompanyCode = finderOptions[0][1];
hdrXml2.AnyAttr = hdr.AnyAttr;
hdrXml2.SessionID = hdr.SessionID;
It doens't matter if I user the CompanyCode in the headers It alwasy return the informatie belonging to the first office: xxxx01-01.
When using the browse codes in Twinfield, make sure to do the SoapCall to select the right company, as documented there:
https://c3.twinfield.com/webservices/documentation/#/FAQ
Otherwise you will get the data back for the default company:
Q. When using the Browse Data functionality, in the response I get data from a different company. What is wrong?
A. In the browse data request there is no option to set the current company. Before sending the request, make sure the correct company is set by using the SelectCompany function. See also Web Services Authentication.
To get the open invoices the best way is to use the browse codes. Select code 100 and add a filter on the column matchstatus, here is an example:
https://gist.github.com/alexjeen/d4ef3295820dc98c7f0171e47294dbfe

In firebase, how to set user details on the basis of their e-mail id's instead of UID or other credentials?

I want to change some fields in user details that correspond to a certain e-mail id manually.
Currently I have to look in authentication console for the e-mail id corresponding to UID(which is basis of storing user details now) but I don't want to do that.
Another option I thought was storing user details on the basis of their mobile numbers(as it is equally easily recognisible as email-id), but this will make login system on the basis of phone number instead of email-id.
Main problem is dot in email-id's that don't let email-id's to store as keys.
It's true, Firebase does not allow in it's key symbols like . (dot). There are also other symbols like $ (dollar sign), [ (left square bracket), ] (right square bracket), # (hash or pound sign) and / (forward slash) that are also forbidden.
So in order to solve your problem, you need to encode the email address like this:
name#email.com -> name#email,com
To achieve this, i recomand you to use the following method:
static String encodeUserEmail(String userEmail) {
return userEmail.replace(".", ",");
}
And to decode the email, you can use the following method:
static String decodeUserEmail(String userEmail) {
return userEmail.replace(",", ".");
}

Get Data from Odata service with Logged in User

I have one Odata service , which is providing me the data and I am able to display this data on table. We are going to deploy this application to Launchpad. Now we have this requirement in which logged in user must get the data according to his/her login ID. So If my user ID is XXXXX , I should get the records only for XXXXX. I am unable to understand the process flow. Shall we implement the logic in Odata itself or should I get all the data and filter the model on UI, before displaying it.
Regards,
MS
In oData itself you can access login user by sy-uname. using that user you can filter your data.
OR
In front end you can access login user by below code
var vUrl = "proxy/sap/bc/ui2/start_up";
var oxmlHttp = null;
oxmlHttp = new XMLHttpRequest();
oxmlHttp.onreadystatechange = function() {
if (oxmlHttp.readyState == 4 && oxmlHttp.status == 200) {
var oUserData = JSON.parse(oxmlHttp.responseText);
vUser = oUserData.id;
}
};
oxmlHttp.open( "GET", vUrl, false );
oxmlHttp.send(null);
You have to handle this in Odata only. Get User id from UI using
var storename = sap.ushell.Container.getService("UserInfo").getId();
and set it to Odata to filter and send back the results.
You should handle such requirements in the Service level (OData level), not in the UI.
In DPC_EXT class variable SY-UNAME gives you the logged in user. So you should filter your records by deriving more information from that.

When to use uid and when to use $id in angularfire

$id The key where this record is stored. The same as obj.$ref().key
To get the id of an item in a $firebaseArray within ng-repeat, call $id on that item.
These two are from the angular fire reference:
https://github.com/firebase/angularfire/blob/master/docs/reference.md
What I understand is if there is firebase object created with :
var object = $firebaseObject(objectRef);
then I can use uid always.
uid : object.uid
But I saw examples where the firebase auth user is used with $id.
return Auth.$requireSignIn().then(function (firebaseUser) {
return Users.getProfile(firebaseUser.uid).$loaded().then(function (profile) {
**profile.uid or profile.$id here**
Also is it possible the object to have uid but not to have $id (obj.$ref().key). Aren't they the same thing? Does the object have to be loaded first with $loaded() to use $id or uid?
Regards
You seem to be confusing two concepts:
the object.$id of an AngularFire object contains the key of that object in the Firebase Database.
a firebaseUser.uid in Firebase terms is the identification of a Firebase Authentication user.
It is common to store your Firebase Authentication users in the database under their uid, in which case user.$id would be their uid. But they are still inherently different things.
Users
uid1
displayName: "makkasi"
uid2
displayName: "Frank van Puffelen"
So if you we look at the code snippet you shared:
return Auth.$requireSignIn().then(function (firebaseUser) {
return Users.getProfile(firebaseUser.uid).$loaded().then(function (profile) {
The first line requires that the user is signed-in; only then will it execute the next line with the firebaseUser that was signed in. This is a regular JavaScript object (firebase.User), not an AngularFire $firebaseObject.
The second line then uses the firebaseUser.uid property (the identification of that user) to load the user's profile from the database into an AngularFire $firebaseObject. Once that profile is loaded, it executes the third line.
If the users are stored in the database under their uid, at this stage profile.$id and firebaseUser.uid will be the same value.

Resources