Get Username of Current Realm SyncUser in Swift - realm

Realm Swift 2.0.2, Swift 3
I'd like to display the username of the current Realm SyncUser in my UI. I know I can get the unique ID of a user like this:
let user = SyncUser.all().first
print(user?.identity) //a7f84g203fd18... etc.
...but is there a way to get the user's username? I don't see anything in the docs about it.

Currently there is no way to get username from SyncUser: SyncUser doesn't have username at all, it's just one of the credentials that could be used for authentication.
There is also a related issue at https://github.com/realm/realm-mobile-platform/issues/12

My current solution is to save to UserDefaults the user's email/username when they sign up:
let defaults = UserDefaults.standard
defaults.set(self.email.text!, forKey: "userEmail")
...and then reference it later where I need it in my app:
//Show username/email
accountStatus.text = defaults.string(forKey: "userEmail")

Related

Firebase + Flutter : get platform user used to sign in

I have an app with 3 sign in methods: Google, Facebook & mail.
I want to show the users that are signed in with mail a different screen.
Is it possible to get the sign in method form the package firebase authentication?
I know I can fix this by using firestore & checking if a statement is true or false. But that will cost me a read every time a user opens the app...
This seems to be what you want: https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseUser.html#getProviderData()
In my app where I use Google logins only, I have firebaseUser.providerData[1].providerId == 'google.com'.
Btw, firebaseUser.providerData[0].providerId == 'firebase'.
I guess you could check them all and look for what providers you get for different kinds of users.
Edit: here's what I get when logging in with e-mail: https://postimg.cc/BXWGGN6h
Firebase has a special property providerId. But, as mentioned #GazihanAlankus it always returns firebase.
And, the property firebaseUser.providerData[1].providerId sometimes not exists (for example when user used anonymous login).
So, we should use appropriate approaches, for example:
FirebaseUser user = await _firebaseAuth.currentUser();
if (user.providerData.length < 2) {
// do something
}
else {
print(res.providerId);
}
The list of values, that are returned by property providerId:
EmailAuthProviderID: password
PhoneAuthProviderID: phone
GoogleAuthProviderID: google.com
FacebookAuthProviderID: facebook.com
TwitterAuthProviderID: twitter.com
GitHubAuthProviderID: github.com
AppleAuthProviderID: apple.com
YahooAuthProviderID: yahoo.com
MicrosoftAuthProviderID: hotmail.com
I got this list from the cool research here What is the full list of provider id's for firebase.UserInfo.providerId?
In my app I used
FirebaseAuth.instance.currentUser.providerData[0].providerId == 'google.com'.,
cause providerData[1] doesn't contain any value
For anyone reading this in 2022, Firebase now has nice new docs for Flutter and in it they have this, which I personally found super useful:
if (user != null) {
for (final providerProfile in user.providerData) {
// ID of the provider (google.com, apple.cpm, etc.)
final provider = providerProfile.providerId;
// UID specific to the provider
final uid = providerProfile.uid;
// Name, email address, and profile photo URL
final name = providerProfile.displayName;
final emailAddress = providerProfile.email;
final profilePhoto = providerProfile.photoURL;
}
}
Source: Firebase documentation
But that will cost me a read every time a user opens the app. THIS IS TRUTH!
Alternatively, you can create your own app DB using SQFLite, and create only one table (user) in that, having a field of signUpMethod having possible values are google, facebook and mail. Whenever you opens the app, first check that in your db, if this is mail, redirect to another screen which you want, else call firebase service
Cheers!

Android Firebase Generating Likes

I am working on an project somewhat it is same like an instagram but ,i am not getting how to mange likes when someone like the post then we can use transaction to count++ the likes but when if a user again see the post how to know that the user has already like the post and make the like button in active state?
You could store the liked posts for the user.
Either by storing them at the user:
users/{userId}/likes/{postId} = true
Or by storing them at a separate location:
likes/{userId}/{postId} = true
You could also store them at the post itself:
posts/{postId}/likedBy/{userId} = true
Thinking about it, I think the last option would probably be best as you could set the value in the same transaction as the count++ one.

Telegram bot: How to mention user by its id (not its username)

I am creating a telegram bot and using sendMessage method to send the messages.
it is easy to mention user using #username, But how to mention user when they don't have username?
If using the telegram app/web, we can mentioned the user by #integer_id (name), and telegram app/web will convert it into clickable text. integer_id will be generated automatically when we select the user, after typing #.
another background:
I am trying to use forceReply and I want to target user, if they have username, I can easily target them, by mentioning them on the text on sendMessage method.
the bot I am creating is a "quiz" like bot. where each player need to take turn, and the bot is sending them the question, each msg from bot will target different player.
NOTE: I am not disabling the Privacy Mode, I don't want telegram bombing my server with msg I don't need. it was overloading my cheap nasty server. so, disabling it not an option.
I am open for other solution, where the bot can listen to selected player.
thanks.
UPDATE 21/10:
I've spoke to BotSupport for telegram, they said, for now Bots can't mention user without username.
so in my case, I still keep using forceReply, and also, gave a short msg to user which doesn't have username to set it up, so they can get the benefit from forceReply function.
According to official documentation it is possible to mention user by its numerical id with markup:
[inline mention of a user](tg://user?id=123456789)
According to this link :
it is possible to mention user by its numerical id with markup:
Markdown style
To use this mode, pass Markdown in the parse_mode field
when using sendMessage. Use the following syntax in your message:
[inline mention of a user](tg://user?id=123456789)
and you can also use HTML style :
HTML style
To use this mode, pass HTML in the parse_mode field when using sendMessage. The following tags are currently supported:
inline mention of a user
Try this:
#bot.message_handler(func=lambda message: True)
def echo_message(message):
cid = message.chat.id
message_text = message.text
user_id = message.from_user.id
user_name = message.from_user.first_name
mention = "["+user_name+"](tg://user?id="+str(user_id)+")"
bot_msg = f"Hi, {mention}"
if message_text.lower() == "hi":
bot.send_message(cid, bot_msg, parse_mode="Markdown")
For python-telegram-bot you can do the following:
user_id = update.message.from_user['id']
user_name = update.message.from_user['username']
mention = "["+user_name+"](tg://user?id="+str(user_id)+")"
response = f"Hi, {mention}"
context.bot.sendMessage(chat_id=update.message.chat_id,text=response,parse_mode="Markdown")
No, this restriction is related to Telegram's privacy policy and prevention of abuse.
It is possible to mention a user when sending messages (BOT API), but that is not what you need:
[inline mention of a user](tg://user?id=<user_id>)
Links tg://user?id= can be used to mention a user by their id without using a username. Please note:
These links will work only if they are used inside an inline link. For example, they will not work, when used in an inline keyboard button or in a message text.
These mentions are only guaranteed to work if the user has contacted the bot in the past, has sent a callback query to the bot via inline button or is a member in the group where he was mentioned.
https://core.telegram.org/bots/api#markdown-style
you need to link to the text: "tg://user?id=" and id
user_id = 123456XX # id of the user to mention
chat_id = 123456XXX # chat id where to mention
user_name = name of user
await bot.send_message(chat_id, f"<a href='tg://user?id={user_id}'>{user_name}</a>", "HTML")
here is an example:
#dp.message_handler()
async def mention(msg: types.Message):
await msg.answer(f"<a href='tg://user?id={msg.from_user.id}'>{msg.from_user.full_name}</a>", "HTML")
Bots are able to tag users by their ID, they just can't do this using the official HTTP Bot API.
Update: Not necessairy anymore, since Telegram added native Support for this.
If you log into your bots account with MadelineProto (PHP) you can use this 'link' to mention someone by it's ID with parse_mode set to markdown
[Daniil Gentili](mention:#danogentili)

Meteor.users maintaining users

I have a Meteor app where I need to:
Create / update app users including their name, username and password. So I was wondering if first is it possible to do so while login to the app as a Meteor user? In other words is it possible to create / update other app users while logging in as an app user? I've tried to search for an example / how to but couldn't find any so any help will be highly appreciated.
Add custom fields to Meteor.users document (ex. User type(accountant / sales...etc), Phone...etc)? After research couldn't find any example except on how to update Meteor.users profile in update only, but couldn't find how to do so when creating the new user, so any help will be highly appreciated.
Thanks
To add fields to user simply use onCreateUser function
Accounts.onCreateUser(function(user) {
user.type = "customer";
user.phone = "123456789";
//etc
return user;
});
And I didn't understand first question, but you can update user data by making query, such as:
Meteor.users.update({_id:this._id},{$addToSet~});

Registering new users via OAuth2 : what to set as user identifier for future log ins?

I have managed to successfully configure this. The problem is, when I change the lines below :
//I have set all requested data with the user's username
//modify here with relevant data
$user->setUsername($username);
$user->setEmail($username);
$user->setPassword($username);
into the information I want to retrive, such as real name, email, my generated password etc, when I click the Login button for Facebook per say, I am asked again if I want to connect with my local testing site.
From what I understand, in the documentation I linked above, this :
$user = $this->userManager->findUserBy(array($this->getProperty($response) => $username));
is the line that checks if the user exists or not, and the initial code by itself, sets either facebook_id or twitter_id (this is how I save them) as a new User *username*. If I change the line
$user->setUsername($username); //same as facebook/twitter _id
into
$user->setUsername(setProperUsername()); //sets a proper unique username
Then everytime I try to login I get the "Register" message. So, I have a general idea of how it works but I am having a hard time understanding some things:
1. When I have registered with Facebook and I login with twitter, I register again, no knew row is created, but missing twitter_id fields are updated/populated, username stays intact. How come HWI/FOSUB knows I am the same person when my previous data were from Facebook not Twitter?
2. If there is a global way of knowing I am the same person, what data from the $response object should I use as a key to identify already registered users?
After testing a lot with this, I have the answer if anyone runs into this type of situation
Check your default_target path, make it so it is /profile, /account etc, don't default to login again. Also, if a user is already logged in, do not make him access your login page. This was why my data was being updated. I was basically logged in with my Facebook account and registering with my Twitter account too.
No, there is no global way of knowing I am the same person. The $response object sent me a unique ID for that specific user according to the provider policy. You might use this to identify already registered users and log them in.

Resources