Swift - How to use FireStore Authentication - swift

I am struggling with a problem for a while now.
I am using FireStore Database in my Swift project.
Here is my sample fragment of code:
db.collection("XXXX").whereField("XXXX", isEqualTo: XXX).getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
// SUCCESFULL
}
The thing is that, in my database, currently I do not have any Rules implemented. So it is not secure. I want to implement to my swift project so that I can modify the rules on my database.
I do not understand how to enable Authentication for my swift project.
In the Nature of my project, there is no user authentication needed by the users who is willing to use the application.
How can I implement authentication just before the database query in the code, so that the rules on my database satisfies.
The authentication must be independent on the users since there is no authentication mechanism exists in my swift projects since I do no need the users to authenticate in the app.
Can you share a simple authentication code or something so that I can use in my project ?
I tried to read the docs on google but they are all related to User Authentication Methods such Facebook, Email/Password, SMS .. etc
Thank you in Advance Guys

Related

Can you validate whether a user has been recently authenticated on Firebase (Swift)?

Is there a way to check if a user has recently authenticated on Firebase to avoid this message when trying to delete a user: "This operation is sensitive and requires recent authentication. Log in again before retrying this request."
I have been playing around trying to compare lastSignInDate (below) to current time but there seems to be a large margin of error on this which can cause problems:
firebase.auth().currentUser.metadata.lastSignInTime
Are there any functions that can return a simple boolean as to whether a user has recently authenticated so the user.delete() function will work properly?
Thanks so much!
The best way to do this is by checking if the response has an error, like so:
let user = Auth.auth().currentUser
user.delete { error in
if let error = error {
if (error.code == "auth/requires-recent-login") {
// The user's credentials are too old. Prompt Login screen.
}
} else {
// ...
}
}
According to Firebase Documentation, There's no other approach to this other than comparing the current date with firebase.auth().currentUser.metadata.lastSignInDate (Only if you have the Admin SDK on your app, but you most probably do not need that for enabling a user to delete themselves).

Realm Sync Facebook Authentication not working

I am trying to enable Facebook authentication in Realm Sync, but keep getting an error on login.
I have been using these guides:
https://docs.realm.io/sync/v/3.x/using-synced-realms/user-authentication/additional-providers#facebook
https://docs.realm.io/sync/v/3.x/self-hosted/customize/authentication/included-third-party-auth-providers/facebook-authentication
I have the Access Token provided by the Facebook API/SDK enabling me to log in/sign up a user.
When I use Realm's libraries to log in a user with the Facebook Access Token, I get an error stating the 'provider' parameter is invalid, but this parameter is defined by Realm's own classes.
I have successfully authenticated a user with an email & password so do I need to set up something else on Facebook/Realm Sync? It seems Facebook authentication just doesn't work in Realm Sync and the above help files are pretty useless.
Authentication code
func authenticateWithFacebook(facebookToken: String, completion: #escaping (RealmAuthenticationResult) -> ()) {
let credentials = SyncCredentials.facebook(token: facebookToken)
print("------FACEBOOK LOGIN-------")
print("Token: \(facebookToken)")
login(credentials) { (result, userId) in
completion(result)
}
}
private func login(_ credentials: SyncCredentials, completion: #escaping (RealmAuthenticationResult, String?) -> ()) {
SyncUser.logIn(with: credentials, server: RealmConnection.AUTH_URL, onCompletion: { (user, err) in
if let _ = user {
print("User has logged in/signed up")
return completion(RealmAuthenticationResult.success(true), user?.identity)
} else if let error = err {
print(error.localizedDescription)
return completion(RealmAuthenticationResult.failure(error), user?.identity)
}
})
}
The error
Error Domain=io.realm.sync.auth Code=601 "Your request parameters did
not validate. provider: Invalid parameter 'provider'!;"
UserInfo={NSLocalizedDescription=Your request parameters did not
validate. provider: Invalid parameter 'provider'!;}
Other things I have tried
I have tried directly instantiating the base provider class 'RLMIdentityProvider' and creating SyncCredentials with that, but no dice.
A workaround is to get the account information from the Facebook API/SDK and use the account's email to login/signup with a username/password setup. However, it seems to make Facebook authentication redundant.
That Realm Documentation link is outdated. See the 3.16.0 Documentation (or later) as a lot was changed.
At the moment Password, JWT & Firebase are the only auth options with Firebase Authentication being a very solid solution. Integrating Firebase is also covered in the Realm Documentation in the Using Sync'd Realms -> Authentication section. I won't link it as the documentation is being frequently updated now days.
As stated by the Realm Team (several times) extensive auth options are not a priority as other companies (like Firebase) handle it very well.
There were a number of posts on the Realm forums speaking to this but Ian's response to this question is very succinct.
we have and will continue to prioritize synchronization features for
mobile
and then
This is why we recommend that a production app should outsource user
management and authentication to a company which specialized in these
features.

Firebase Auth + Own Api

is it possible to use only the firebase auth and then create an own api with own database?
So I write an REST API which uses the firebase token to authentificate.
Thanks!
It depends on the technology that you will be using for the backend API. There is a Firebase Admin SDK, that is aimed at Java, Python and Node developers, but I think the functionality that you are looking for is only available in the Node SDK (although I believe that there are workarounds for this).
The way this works is that after your user signs in on the client side, they can request a token using firebase.auth().currentUser.getIdToken() which can then be passed to your backend which can then be verified, see the below example for how it could be done using Node and Restify.
const server = restify.createServer({});
server.use(validateJwt);
function validateJwt(req, res, next) {
if(!req.headers.token){
//reject
}
admin.auth().verifyIdToken(req.headers.token).then(decodedToken=>{
console.log(`token for user ${decodedToken.sub} valid`);
admin.auth().getUser(decodedToken.sub).then(user=>{
console.log(`fetched user ${user.email}`);
next();
}).catch(err=>{
res.send(500, 'the user with the ID does not exist in firebase');
})
}).catch(err=>{
console.log(`token validation failed: ${err}`);
res.send(401, 'authentication failed')});
}
I believe you should be able to do this, by using Firebase to authorise the user and then allow read access to a link securely stored for authenticated users only. This could then link to the database, if this is what you mean. I'd assume you may have already started here, but this is where to start Understand Firebase Realtime Database Rules

Realm Object Server - Error: Your request parameters did not validate

I built a small iOS application which uses Realm instead of CoreData. The app does not require a login as it only stores data entered by the user. I'm currently trying to save users data so that if a user deleted the app for example, the data will be there by default the next the app is re-installed.
Here's where I am getting confused. Can I still use Realm Mobile Platform even though the app will not require a login screen. (i.e. data will automatically be saved for users who are logged-in to their iCloud accounts).
Here's what I've done so far:
I configured Realm Object Server on an AWS EC2 instance, and I can login to the realm dashboard through the browser just fine.
I configured the cloudKit stanza in the configuration.yml file as per the authentication instructions.
In my setupRealm() func, I tried the following code but I keep getting a parameters validation error:
SyncUser.logIn(with: cloudKitCredentials,
server: serverURL) { user, error in
if let user = user {
print("in")
}
else if let error = error {
fatalError(String(describing: error))
// Error: "Your request parameters did not validate."
}
This is the error message:
Error Domain=io.realm.sync Code=3
"Your request parameters did not validate."
UserInfo={statusCode=400,
NSLocalizedDescription=Your request parameters did not validate.}:
I suspect that the my iCloud user is not being tied with the object server, but I can't seem to put the pieces together. I'd appreciate any pointers.
The server requires a restart after editing the authentication lines in the configuration.yml.

Firebase do not create user in Unity SDK

It is strange that Firebase can't create user in Unity SDK out of the box.
Firebase Console was tuned (anonymous access and email/password access are enabled) and google-service.json was placed in Assets folder of Unity.
However, Firebase still won't create a user. This is the code where it always fails:
auth.SignInAnonymouslyAsync().ContinueWith(task => {
if (task.IsCompleted && !task.IsCanceled && !task.IsFaulted) {
Debug.Log("User is now signed in.");
FirebaseUser newUser = task.Result;
}
else if (task.IsFaulted || task.IsCanceled)
{
Debug.Log("User signup failed");
}
});
Why?
There are possible several reasons:
The app was run in the Editor, rather than on the device
The configuration file is not updated after you add Firebase Auth feature
The password is shorter than 6 chacters
The email address is in invalid form, e.g. abcdef#aaa
The first one is highly likely the reason why.
I have created a tutorial here, which covers the steps to create/login using firebase in Unity, hope this is helpful.