Manage users in firebase for multi tenant app - ios

We have a ordering system which end users can order meals from their iOS app. Each iOS app belongs to a brand, each user also belongs to a brand. We put all brand information in one firebase project. The database structure is:
-brands
-- brand_id_1:
-- information
-- brand_id_2:
-- information
-stores
-- store_id_1:
-- brand_id:brand_id_1
-- more information
-- store_id_2:
-- brand_id:brand_id_1
-- more information
-orders
--brand_id_1:
--order_id_1:
--orderinfo
--brand_id_2:
--order_id_4:
--orderinfo
-users
-- user_id_1:
-- brand_id:brand_id_1
-- userinfo
-- user_id_2:
-- brand_id:brand_id_2
-- userinfo
We use Facebook and twitter authentication for sign in each app. However, one firebase project can only assign one Facebook app id. That means if user downloads brand1 app and sign in by Facebook , when he or she downloads brand2 app, the user account will be already created and our users will be confused. We hope each brand has their own user database, but we can still manage all the brands and stores data in one firebase project.
What we want to do is put all brands and stores in a main firebase project, then for each brand just create a firebase project for each iOS app. These firebase projects are just for user login (when sign up success put the uid to main firebase project), and all user orders will be saved to our main firebase project.
Is it possible? or any other better solutions?

Whenever you need an isolated set of users for an app, you will need a new project for that app. You can use multiple databases per project following the instructions in this article (it is for Android, but it's similar for iOS -
you will have to initialize a new Firebase app in the client for each project you want to use).

After several hours of study, I come up with other approach. The idea is:
Use Facebook iOS sdk to sign in from iOS app and get Facebook token.
iOS app sends this token to cloud functions, fetch user profile using Graph api, then create custom token from Facebook uid.
Send this custom token back to iOS app.
iOS app uses this token to sign in to firebase.
iOS code :
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if let token = result.token {
print(token.userID)
print(token.appID)
signInuser(with: token)
}
}
func signInuser(with token:FBSDKAccessToken) {
Alamofire.request("https://xxx.cloudfunctions.net/verifyFacebookUser", method: .post, parameters: ["token":token.tokenString]).responseJSON(completionHandler: { (response) in
switch response.result {
case .success(let data):
if let json = data as? [String:String] {
FIRAuth.auth()?.signIn(withCustomToken: json["token"]!, completion: { (user, err) in
if let error = err {
print(error)
}else {
print(user!.displayName)
print(user!.email)
}
})
}
case .failure( let error):
print(error)
}
})
}
cloud functions:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const graph = require('fbgraph');
var serviceAccount = require("./serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://xxx.firebaseio.com"
});
exports.verifyFacebookUser = functions.https.onRequest((req,res) => {
if (!req.body.token) {
return res.status(400).send('Access Token not found');
}
graph.setAccessToken(req.body.token);
graph.get("me?fields=id,name,email", function(err, result) {
const firebaseUid = "fb:"+result.id;
admin.auth().createUser({
uid:firebaseUid,
displayName:result.name,
email:result.email
}).then(function(userRecord){
console.log(userRecord)
admin.auth().createCustomToken(userRecord.uid)
.then(function(customToken) {
res.send({token:customToken});
})
.catch(function(error) {
console.log("Error creating custom token:", error);
})
});
});
});
With this method, the iOS app of each brand will ask user to agree sign in from Facebook even if he or she already sign in from different brand app. However that means iOS app needs to implement Facebook native sign in process which Firebase SDK already provide.

Related

AWS Amplify iOS SDK : FederatedSignIn Failed to retrieve authorization token on Amplify.API.post

I've been working with the Amplify SDK to get federatedSignIn working with my iOS app with "Sign in with Apple" and Cognito to eventually make calls to API Gateway / Lambda functions.
TL;DR : My access token does not appear to be "automatically included in outbound requests" to my API as per the last paragraph of this section of the docs : Cognito User pool authorization
I have successfully authenticated using the tutorial found here Authentication Getting Started and other various Youtube videos on the Amazon Web Services channel.
Upon successful sign in through Apple I'm given an ASAuthorizationAppleIDCredential object. This contains the user field (token) which I pass to the Amplify.Auth class using the following Swift code :
func signIn (with userId: String)
{
guard
let plugin = try? Amplify.Auth.getPlugin(for: AWSCognitoAuthPlugin().key),
let authPlugin = plugin as? AWSCognitoAuthPlugin,
case .awsMobileClient (let client) = authPlugin.getEscapeHatch()
else
{
return
}
client.federatedSignIn(providerName: AuthProvider.signInWithApple.rawValue, token: userId) { (state, error) in
if let unwrappedError = error
{
print (unwrappedError)
}
else if let unwrappedState = state
{
print ("Successful federated sign in:", unwrappedState)
}
}
}
All appears to be successful and to double check I use the following bit of code to ensure I'm authorized :
func getCredentialsState (for userId:String)
{
let provider = ASAuthorizationAppleIDProvider()
provider.getCredentialState(forUserID: userId) { (credentialsState, error) in
if let unwrappedError = error
{
print (unwrappedError)
}
switch credentialsState
{
case .authorized:
print ("User Authorized")
case .notFound, .revoked:
print ("User Unauthenticated")
case .transferred:
print ("User Needs Transfer")
#unknown default:
print ("User Handle new use cases")
}
}
}
In the console I see "User Authorized" so everything appears to be working well.
However when I then go to make a call to Amplify.API.post I get the following error:
[Amplify] AWSMobileClient Event listener - signedOutFederatedTokensInvalid
Failed APIError: Failed to retrieve authorization token.
Caused by:
AuthError: Session expired could not fetch cognito tokens
Recovery suggestion: Invoke Auth.signIn to re-authenticate the user
My function for doing the POST is as follows :
func postTest ()
{
let message = #"{'message": "my Test"}"#
let request = RESTRequest (path: "/test", body: message.data(using: .utf8))
Amplify.API.post (request:request)
{
result in switch result
{
case .success(let data):
let str = String (decoding: data, as: UTF8.self)
print ("Success \(str)")
case .failure(let apiError):
print ("Failed", apiError)
}
}
}`
I then went into the API Gateway UI and changed the generated Method Request on my resource from AWS IAM to my Cognito User Pool Authorizer thinking this was the issue. I also changed the awsAPIPlugin authorizationType to "AMAZON_COGNITO_USER_POOLS" in my amplifyconfiguration.json file. This unfortunately did not have any affect.
I've seen posts such as this issue User is not created in Cognito User pool for users logging in with Google federated login #1937 where people discuss the problem of having to to use a web ui to bring up the social sign in. I understand that Apple will reject your app sometimes for this. Therefore this is not a solution.
I then found this post which seems to resolve the issue however this appears to use the old version of the SDK? Get JWT Token using federatedSignIn #1276
I'm not great with Swift (I'm still an Objective C expert, but am slowly learning Swift) so I'm uncertain which path to go here and whether this is actually a solution? It does seem to be quite more complicated than the function I have that does my POST? The RESTRequest does seem to be a simple and easy solution but I'm uncertain how to pass it the Authorization token (or even how to get the token if it is needed here).
However, everything I've read about the SDK is that the authorization should be handled automatically in the background according the docs in my first link above. Specifically pointed out, again, here : Cognito User pool authorization. The last paragraph here states 👍
With this configuration, your access token will automatically be included in outbound requests to your API, as an Authorization header.
Therefore, what am I missing here as this does not appear to automatically include my access token to my outbound requests to my API?

iOS Firebase OTP verification without Sign Up

I need help verifying the OTP with Firebase.
I Managed to receive a SMS with the OTP but when I verify it I get automatically signed up and I only know if the OTP was valid if I signed up - else I get a popup like "invalid otp".
How can I manually validate the otp? My goal is to open another screen where the user puts in more information.
func verifyCode(){
let credential = PhoneAuthProvider.provider().credential(withVerificationID: self.CODE, verificationCode: code)
print(credential)
loading = true
//here i just want to verify my OTP without signing in...
Auth.auth().signIn(with: credential) { (result, err) in //here i am signing in...
self.loading = false
if let error = err{
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.error)
self.code = ""
self.errorMsg = error.localizedDescription
withAnimation{ self.error.toggle()}
return
}
self.gotoRegistration = true
withAnimation{self.status = true}
}
}
There is no way to use Firebase Authentication's phone/OTP provider without automatically signing the user in.
But the fact that the user is signed in to Firebase, does not mean that you have to grant them access to all parts/data in your app. If you want them to provide more information, you can do so before or after signing them in to Firebase, and make it part of the same sign-up flow as far as the user is concerned.
So something like:
// Sign the user in with Firebase
// Check if the user has provider the additional registration information
// If not, send them to the registration information screen
// If so, send them to the next screen of the app
You can also enforce these rules in your back-end code, or (if you use one of Firebase's back-end services) in the server-side security rules.

Firebase Anonymous Login - Why FirebaseID changes when logged to Facebook, but it remains the same when not logged to Facebook?

I have the following logic for allowing guest users to login to my app:
(1) Login as Anonymous.
(2) Check if Facebook is logged.
(3) If it is logged to Facebook, link to Anonymous.
(4) If link fails, Login to firebase passing facebook token to Firebase
If I am not logged in Facebook the Anonymous ID given by firebase after step (1) is always the same. However, the first time I login to Facebook, I link the account to firebase as in step (3). And from that onwards, I get a different Anonymous ID every time I go through the login process.
Question 1. Will the Anonymous ID in step (1) ALWAYS be the same until I login to Facebook for the first time?
Question 2. What is the best login flow to allow users to save data in the backend as guests, and link to facebook later when the user decides to do so?
Here is my swift code that implements my pseudo code:
func login() -> Promise<AuthCredential?> {
// Login as Anonymous. Check if FB is logged. If it is, link to Anonymous. If fails, pass FB token to Firebase
print("........................")
print("Starting Login")
return Promise { seal in
Auth.auth().signInAnonymously() { (authResult, error) in
print("-Done Login Anonymously", authResult?.credential, Auth.auth().currentUser?.uid)
if let error = error {
print("-DID NOT SIGNED UP WITH FIREBASE:", error)
seal.reject(error)
} else {
if AccessToken.isCurrentAccessTokenActive { // If Facebook token is active exchange for Firebase
let credential = FacebookAuthProvider.credential(withAccessToken: AccessToken.current!.tokenString)
print("-Loggged with FACEBOOK!!!!", credential)
Auth.auth().currentUser!.link(with: credential) { (result, error) in
print("-Linked Account!!!!??????????", result as Any, error as Any)
if error != nil {
Auth.auth().signIn(with: credential) { (authResult, error) in
print("-Signed UP in Firebase USIG FB. No Linking")
if let error = error {
print("-DID NOT SIGNED UP WITH FIREBASE:", error)
seal.reject(error)
} else {
print("-DID SIGNED UP WITH FIREBASE using FB:", Auth.auth().currentUser?.uid)
seal.fulfill(authResult?.credential)
}
}
}
}
}
// print("-Done Login", Auth.auth().currentUser?.uid)
// seal.fulfill(authResult?.credential)
}
}
}
}
The API documentation for signInAnonymously (javascript) reads:
If there is already an anonymous user signed in, that user will be
returned; otherwise, a new anonymous user identity will be created and
returned.
You probably only want to call signInAnonymously if there is no user signed into the app. It's best to wait to see if a user is already signed in using an auth state listener, as the sign-in process is not immediate.
Once you link the anonymous account with a full account, you should probably not call signInAnonymously again, since you probably want the user to stay signed in with their full account and no create another new anon account.

How can I devide users into different groups(Identity pools) automatically?

I'm using AWS Cognito in my iOS app to implement the user signup & signin functions. I used the official Amplify SDK DOCs(https://aws-amplify.github.io/docs/ios/authentication) as a reference, and the app works well. But, actually I want to give my users different access authority which can achieve different contents(like files in S3).
While the user signing up the app, they must choose a group. Based on the group, they are given different access authority.
I've read the SDK DOCs and developer guide but I haven't found a good way to implement this function.
Is there any function in cognito I can use to separate users into different Identity pools? Or can anybody show me some samples which allow users having different access authority.
AWSMobileClient.sharedInstance().signUp(username: "your_username",
password: "Abc#123!",
userAttributes: ["email":"john#doe.com", "phone_number": "+1973123456"]) { (signUpResult, error) in
if let signUpResult = signUpResult {
switch(signUpResult.signUpConfirmationState) {
case .confirmed:
print("User is signed up and confirmed.")
case .unconfirmed:
print("User is not confirmed and needs verification via \(signUpResult.codeDeliveryDetails!.deliveryMedium) sent at \(signUpResult.codeDeliveryDetails!.destination!)")
case .unknown:
print("Unexpected case")
}
} else if let error = error {
if let error = error as? AWSMobileClientError {
switch(error) {
case .usernameExists(let message):
print(message)
default:
break
}
}
print("\(error.localizedDescription)")
}
}
You don't have to put users in different identity pools. Cognito already has user groups that you can use to assign different roles.
I am not familiar with IOS but there should be an admin add user to group method that you can use.

Error adding Firebase users Swift

By following the information on this link, I am currently working on trying to create a user using Firebase, as shown in the code below. However, it appears no user is created when the app is run. Any input is greatly appreciated. The Firebase URL was taken from my test database.
let ref = Firebase(url: "https://test-96df2.firebaseio.com")
ref.createUser("bobtony#example.com", password: "correcthorsebatterystaple",
withValueCompletionBlock: { error, result in
if error != nil {
// There was an error creating the account
print("error creating account")
} else {
let uid = result["uid"] as? String
print("Successfully created user account with uid: \(uid)")
}
})
Edit:
The propagated error is:
Error Code: AUTHENTICATION_DISABLED) Projects created at
console.firebase.google.com must use the new Firebase Authentication
SDKs available from firebase.google.com/docs/auth/
However, as shown below, the email/password authentication is enabled in the Firebase console.
You have already authorized the email registration as I can see in your screenshot. So the problem doesnt realies on AUTHENTICATION_DISABLED.
From your error message and the snippet code I can see that you have created a new project but you are trying to use the legacy firebase SDK and so you will have compatibility issues. Also, you are looking into the old firebase documentation.
First of all you will need to make sure you have configured your project as documented in new firebase start guide.
After, you can take a look at the documentation for creating a new user with the new sdk. You can find the 3.x create user call bellow.
FIRAuth.auth()?.createUserWithEmail(email, password: password) { (user, error) in
// ...
}

Resources