Firebase - setting currentUser - javascript

Assuming that I have a whole user object as a JSON (with its access and refresh tokens) - how can I force firebase/auth to accept it as its currentUser so it triggers e.g. onTokenIdChange?
EDIT:
I want to authenticate the user on a website (my app #1), and inform the browser extension (my app #2) if successful. Right now I'm passing the JSON representation of a user returned from the website's onTokenIdChange to the extension.
EDIT2:
This is the user's JSON I'm referring to:
{
"uid": "some-uid-here",
"email": "john#example.com",
"emailVerified": false,
"isAnonymous": false,
"providerData": [
{
"providerId": "password",
"uid": "john#example.com",
"displayName": null,
"email": "john#example.com",
"phoneNumber": null,
"photoURL": null
}
],
"stsTokenManager": {
"refreshToken": "my-refresh-token",
"accessToken": "my-access-token",
"expirationTime": 1664750677967
},
"createdAt": "1664712317951",
"lastLoginAt": "1664740255685",
"apiKey": "my-api-key",
"appName": "[DEFAULT]"
}

Passing the user profile around is not enough to authenticate a user with. If you want to authenticate the user in a different context, you'll have to pass their credentials around or mint a custom token for them and sign them in with that.

Not sure if I understood the question, but as far as I know, you have to either
Use one of the default signIn methods (like signInWithEmailAndPassword), which requires user input; I think you are chasing something different
Use the custom token approach mentioned by Frank. In that case, your backend application will use the firebase-admin-sdk to generate custom tokens for a given user, acording to the business logic you desire. Only after that your frontend application will use the firebase/auth lib to run the signInWithCustomToken, which will log you in.
Example: your app #2 must have a way to communicate with your backend in order to retrieve a custom token for the given user

Related

Correct format of JSON key for Qualtrics Web Service Query

I'm trying to use the Web Service component of a Qualtrics survey to get data from a mailing list based on an answer provided by the person completing. So they would select "Bob Jones" and then the Web Service would look at the mailing list to then populate the email address for Bob Jones.
I'm able to call the mailing list and see results successfully with the API token, however, any time I try to add a query, I get a return of "Unexpected json key provided"
How can I access a specific entry? The format of the returned list follows:
{
"result": {
"elements": [
{
"id": "abcdefghijk",
"firstName": "Bob",
"lastName": "Jones",
"email": "bobjones#stackoverflow.com",
"externalDataReference": "Jones, Bob",
"embeddedData": {
"PrimaryEmail": "bobjones#stackoverflow.com",
"DisplayName": "Jones, Bob"
},
"language": "null",
"unsubscribed": false,
"responseHistory": [],
"emailHistory": []
},
I'm attempting to add the query where it says Parameter to Web Service...:
I greatly apologize if this has been discussed already. I searched through as many questions as I could, and didn't find an answer to this. Hope someone will help!
The API you are trying to use doesn't accept query parameters and you can't use it to get data for a specific contact.
Whether you can do it at all depends on whether your account has XM Directory or Research Core Contacts. If you have Research Core Contacts, the only way to get data for a specific contact is by contact id. If you have XM Directory you can use the search API. See: https://api.qualtrics.com/api-reference/reference/contacts.json/paths/~1directories~1{directoryId}~1contacts~1search/post

How would I filter the data returned from Slack to find active users?

Question
How would I filter the user data returned from Slack to find Active Slack Users (e.g., users in our workgroup that we pay for)?
If a user is inactive for some time, they no longer cost us (thanks slack!). Also, we can remove people from our workgroup.
How do I filter down the users.list to a list of users we will be charged for? OR What elements from user.list will reveal active membership.
Issue
I was filtering for users not deleted:
const slackActiveAccounts = slackMembers
.filter(member => member.deleted == false);
But users that have stayed inactive and no longer count against our billing will be found as member.deleted: false. So inactive and deleted are different.
user.list json example
From the Slack API documentation
{
"ok": true,
"user": {
"id": "W012A3CDE",
"team_id": "T012AB3C4",
"name": "spengler",
"deleted": false,
"color": "9f69e7",
"real_name": "Egon Spengler",
"tz": "America/Los_Angeles",
"tz_label": "Pacific Daylight Time",
"tz_offset": -25200,
"profile": {
"avatar_hash": "ge3b51ca72de",
"status_text": "Print is dead",
"status_emoji": ":books:",
"status_expiration": 1502138999,
"real_name": "Egon Spengler",
"display_name": "spengler",
"real_name_normalized": "Egon Spengler",
"display_name_normalized": "spengler",
"email": "spengler#ghostbusters.example.com",
"image_24": "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"image_32": "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"image_48": "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"image_72": "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"image_192": "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"image_512": "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg",
"team": "T012AB3C4"
},
"is_admin": true,
"is_owner": false,
"is_primary_owner": false,
"is_restricted": false,
"is_ultra_restricted": false,
"is_bot": false,
"is_stranger": false,
"updated": 1502138686,
"is_app_user": false,
"has_2fa": false,
"locale": "en-US"
}
}
I think the API method team.billableInfo might be more helpful for your case.
This method lists billable information for each user on the team.
Currently this consists solely of whether the user is subject to
billing per Slack's Fair Billing policy.
Or if you want to get the list of currently "active" users I would suggest checking out the API method team.accessLogs. (payed tier only)
This method is used to retrieve the "access logs" for users on a
workspace.
Each access log entry represents a user accessing Slack from a
specific user, IP address, and user agent combination.
The method users.list does not contain any information about user activity. deleted means that a user has been manually deactivated by an admin and can no longer log-in. In general an admin can not delete a user in Slack, only deactivate them.

restricting access to firebase database to users within a set

I wrote a simple chat application a while back to help me learn node and socket.io, I have recently been looking into firebase as a platform for an app/website, and I am running into an interesting problem I can't solve. Within the app there will be a chat app, there will be channels and all that good stuff, the hard part is there will be private chat, where 2 users can talk privately. The plan is to store the chat in a firebase database. Now I can easily restrict access to firebase databases based on if a user is authenticated, and even restrict user profile access to authenticated users and the user that owns that profile, but I am trying to figure out how to restrict access to the "private chat" children of the "chat" database, to only the 2 users that are in that conversation.
I am thinking the database would look something like this...
{
"chat": {
"channels": ['topics', 'current', 'blah', 'blah', 'blah'],
"{PRIVATE_CHAT_UID_GOES_HERE}": {
"users": ["{USER_ID_1}", "{USER_ID_2}"],
"messages": [{"from": "{USER_ID}", "message": "Hi there"},{...}]
"createdOn": "DATE GOES HERE"
},
"{PRIVATE_CHAT_UID_GOES_HERE}": {
"users": ["{USER_ID}", "{USER_ID}"],
"messages": [{...}, {...}],
"createdOn": "DATE GOES HERE"
}
}
}
Then I would restrict access to the child(private chat id) to only the users that are in the "users" array. That way no one can read or write to that particular chat, unless they are in that particular chat. I just have no idea how to go about it.
I know you can do things like
".read": "auth !== null && auth.uid = $uid"
But I don't think that would be applicable since it limits usage to the owner of the uid, and the uid would be automatically generated when I add a child to "chat" to start a private chat between users.
Is something like this even possible, or is there some better way to structure the data that would allow an easy restriction of access to only the 2 users that are part of the conversation?
I am trying to avoid having a node.js server sitting around just verifying if a user is in a chat, it seems like a pointless overhead, when you can list the database and handle auth directly from the database. I am more than happy to provide code samples of what I have, though I don't know that they are relevant. Thank you in advance for any help.
Your first problem is that you're storing the users in an array. An array is an ordered collection that can have duplicate values. In your scenario you don't want duplicate values, and most likely the order doesn't matter. In such cases you should use a set data structure, which in Firebase is modeled as:
"users": {
"{USER_ID_1}": true,
"{USER_ID_2}": true
}
Now you can restrict read access to the chat room to its members by:
{
"rules": {
"chat": {
"$roomid": {
".read": "data.child('members').child(auth.uid).exists()
}
}
}
}
Be careful mixing different data types in the same node. It's often best to keep each entity in its own top-level node, relating the different types by their key. For example, I'd separate the room's messages, members, and other metadata:
chat
rooms
<roomid1>
createdOn: ....
.... other metadata for the room
roomUsers
<roomid1>
user_id1: true
user_id2: true
roomMessages
<roomid1>
<message1>: { ... }
<message2>: { ... }
<message3>: { ... }

How do I properly use MongoDB for Strongloop scaffolded user model storage?

I'm new to Strongloop and newish to MongoDB. So many learning curves going on right now.
My basic issue is I switched the user model (models.json) datasource from the memory connector to the loopback-connector-mongodb connector and I no longer get a userId when I call /login. I get back an accesstoken, but the userID is null. If I switch back to the memory connector, I'll get a userId of 1 or whatever.
It seems like I remember reading somewhere if I do not supply an ID Strongloop would add one for me. Is this only for the in-memory datastore? Do I need to do something special since it's mongo?
Do I need to switch the accessToken model to mongo as well (I just thought of this)?
thanks.
You hit an edge case here: user and accessToken are backed by two different types of DBs. MongoDB uses ObjectID as the default key while memory DB uses number.
accessToken extends from base AccessToken. It inherits the belongsTo relation to base User model. The userId type is set to number. To fix the problem, you can either make sure accessToken model is connected to mongodb or add the following relation in models.json.
"accessToken": {
"dataSource": "db",
"public": true,
"options": {
"base": "AccessToken",
"relations": {
"user": {
"model": "user",
"type": "belongsTo",
"foreignKey": "userId"
}
}
}
},

Get SoundCloud Artist Page? (Round 2)

I'm still trying to write a function in JavaScript where the user can type in an artist, and it will return a link to that artist's SoundCloud page.
For example,
/artist beyonce --> https://soundcloud.com/beyoncemusic
But the SoundCloud URLS don't all act the same. For example,
/artist dave matthews band --> https://soundcloud.com/dave-matthews-band.
For this reason, I can't simply just output scLink/artistName because they all have different URLs. I'm using Node.js, so I looked through a lot of npm packages, but couldn't figure out how to use any for this purpose. Perhaps Soundclouder will work somehow (though I couldn't figure it out myself). Does anyone know how I could write a command like this?
You are using the SoundCloud API, right?
A simple HTTP request to the right API should return the data you want. For example:
http://api.soundcloud.com/users.json?q=beyonce
[
{
"id": 4293843,
"kind": "user",
"permalink": "beyoncemusic",
"username": "Beyoncé",
"uri": "http://api.soundcloud.com/users/4293843",
"permalink_url": "http://soundcloud.com/beyoncemusic",
"avatar_url": "http://i1.sndcdn.com/avatars-000036935308-a2acxy-large.jpg?435a760",
"country": "United States",
"full_name": "Beyoncé",
"description": "",
"city": "New York",
"discogs_name": null,
"myspace_name": "beyonce",
"website": "http://www.beyonceonline.com",
"website_title": "",
"online": false,
"track_count": 33,
"playlist_count": 2,
"plan": "Pro Plus",
"public_favorites_count": 0,
"followers_count": 478783,
"followings_count": 0,
"subscriptions": [
{
"product": {
"id": "creator-pro-unlimited",
"name": "Pro Unlimited"
}
}
]
},
...
]
...so you could just do results[0].permalink_url.
You can use the request module to make the HTTP request manually, or use soundclouder to handle SoundCloud API's authentication details.
Most of the above does not apply if you want to make the actual requests from a browser. (The question is tagged node.js, but it sounds like you want to do this from a web page.)
If you're doing this from a webpage, use the SoundCloud JS SDK. The data you get back will look like the example above.
I don't think you'd be able to get an exact match reliably. Your best bet would be to search for users with the string you are looking for - example: "beyonce" and then to show the results and let them pick the correct link. You may be able to filter out likely results with follower count (high follower count) or something after you've pulled the initial list from soundcloud.
Search code:
users = SC.get('/users', { q: 'beyonce' });
Then iterate over users and display the permalink url. Hope this helps.

Categories