Skip to content

Commit

Permalink
feat: add Microsoft login with authenticateUserWithMicrosoft()
Browse files Browse the repository at this point in the history
  • Loading branch information
leyenda authored and dpa99c committed Nov 23, 2022
1 parent ddfe9c2 commit 20a6284
Show file tree
Hide file tree
Showing 6 changed files with 103 additions and 19 deletions.
45 changes: 30 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,26 +55,19 @@ To help ensure this plugin is kept updated, new features are added and bugfixes
- [Android background notifications](#android-background-notifications)
- [Android foreground notifications](#android-foreground-notifications)
- [Android Notification Channels](#android-notification-channels)
- [Android 7 and below](#android-7-and-below)
- [Android Notification Icons](#android-notification-icons)
- [Android Default Notification Icon](#android-default-notification-icon)
- [Android Large Notification Icon](#android-large-notification-icon)
- [Android Custom Notification Icons](#android-custom-notification-icons)
- [Android Notification Color](#android-notification-color)
- [Android Notification Sound](#android-notification-sound)
- [Android 8.0 and above](#android-80-and-above)
- [On Android 7 and below](#on-android-7-and-below)
- [Android cloud message types](#android-cloud-message-types)
- [iOS notifications](#ios-notifications)
- [iOS background notifications](#ios-background-notifications)
- [iOS notification sound](#ios-notification-sound)
- [iOS critical notifications](#ios-critical-notifications)
- [iOS badge number](#ios-badge-number)
- [iOS actionable notifications](#ios-actionable-notifications)
- [iOS notification settings button](#ios-notification-settings-button)
- [Data messages](#data-messages)
- [Data message notifications](#data-message-notifications)
- [Android data message notifications](#android-data-message-notifications)
- [iOS data message notifications](#ios-data-message-notifications)
- [Custom FCM message handling](#custom-fcm-message-handling)
- [Android](#android)
- [iOS](#ios)
Expand All @@ -92,10 +85,12 @@ To help ensure this plugin is kept updated, new features are added and bugfixes
- [onTokenRefresh](#ontokenrefresh)
- [getAPNSToken](#getapnstoken)
- [onApnsTokenReceived](#onapnstokenreceived)
- [onOpenSettings](#onopensettings)
- [onMessageReceived](#onmessagereceived)
- [grantPermission](#grantpermission)
- [grantCriticalPermission](#grantcriticalpermission)
- [hasPermission](#haspermission)
- [hasCriticalPermission](#hascriticalpermission)
- [unregister](#unregister)
- [isAutoInitEnabled](#isautoinitenabled)
- [setAutoInitEnabled](#setautoinitenabled)
Expand Down Expand Up @@ -141,21 +136,17 @@ To help ensure this plugin is kept updated, new features are added and bugfixes
- [signInUserWithCustomToken](#signinuserwithcustomtoken)
- [signInUserAnonymously](#signinuseranonymously)
- [verifyPhoneNumber](#verifyphonenumber)
- [Android](#android-2)
- [iOS](#ios-2)
- [setLanguageCode](#setlanguagecode)
- [authenticateUserWithEmailAndPassword](#authenticateuserwithemailandpassword)
- [authenticateUserWithGoogle](#authenticateuserwithgoogle)
- [Android](#android-3)
- [authenticateUserWithApple](#authenticateuserwithapple)
- [iOS](#ios-3)
- [Android](#android-4)
- [authenticateUserWithMicrosoft](#authenticateuserwithmicrosoft)
- [signInWithCredential](#signinwithcredential)
- [linkUserWithCredential](#linkuserwithcredential)
- [reauthenticateWithCredential](#reauthenticatewithcredential)
- [registerAuthStateChangeListener](#registerauthstatechangelistener)
- [useAuthEmulator](#useAuthEmulator)
- [getClaims](#getClaims)
- [useAuthEmulator](#useauthemulator)
- [getClaims](#getclaims)
- [Remote Config](#remote-config)
- [fetch](#fetch)
- [activateFetched](#activatefetched)
Expand Down Expand Up @@ -2850,6 +2841,30 @@ To use Sign In with Apple in your iOS app you need to do the following:
To use Sign In with Apple in your Android app you need to do the following:
- Configure your app for Sign In with Apple as outlined in the [Firebase documentation's "Before you begin" section](https://firebase.google.com/docs/auth/android/apple#before-you-begin)

### authenticateUserWithMicrosoft
Authenticates the user with a Microsoft account using Sign In with Oauth to obtain a credential that can be used to sign the user in/link to an existing user account/reauthenticate the user.
- Follow [Firebase documentation's "Authenticate Using Microsoft" section](https://firebase.google.com/docs/auth/web/microsoft-oauth)

**Parameters**:
- {function} success - callback function to pass {object} credentials to as an argument. The credential object has the following properties:
- {string} id - the identifier of a native credential object which can be used for signing in the user.
- {function} error - callback function which will be passed a {string} error message as an argument

Example usage:

```javascript

FirebasePlugin.authenticateUserWithMicrosoft(function(credential) {
FirebasePlugin.signInWithCredential(credential, function() {
console.log("Successfully signed in");
}, function(error) {
console.error("Failed to sign in", error);
});
}, function(error) {
console.error("Failed to authenticate with Microsoft: " + error);
});
```

### signInWithCredential
Signs the user into Firebase with credentials obtained via an authentication method such as `verifyPhoneNumber()` or `authenticateUserWithGoogle()`.
See the [Android-](https://firebase.google.com/docs/auth/android/phone-auth#sign-in-the-user) and [iOS](https://firebase.google.com/docs/auth/ios/phone-auth#sign-in-the-user-with-the-verification-code)-specific Firebase documentation for more info.
Expand Down
36 changes: 35 additions & 1 deletion src/android/FirebasePlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
import com.google.firebase.Timestamp;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.OAuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
Expand Down Expand Up @@ -116,6 +117,7 @@
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;


import static android.content.Context.MODE_PRIVATE;

public class FirebasePlugin extends CordovaPlugin {
Expand Down Expand Up @@ -297,7 +299,9 @@ public boolean execute(String action, JSONArray args, CallbackContext callbackCo
this.authenticateUserWithGoogle(callbackContext, args);
} else if (action.equals("authenticateUserWithApple")) {
this.authenticateUserWithApple(callbackContext, args);
} else if (action.equals("createUserWithEmailAndPassword")) {
} else if (action.equals("authenticateUserWithMicrosoft")) {
this.authenticateUserWithMicrosoft(callbackContext, args);
}else if (action.equals("createUserWithEmailAndPassword")) {
this.createUserWithEmailAndPassword(callbackContext, args);
} else if (action.equals("signInUserWithEmailAndPassword")) {
this.signInUserWithEmailAndPassword(callbackContext, args);
Expand Down Expand Up @@ -1760,6 +1764,36 @@ public void run() {
});
}

public void authenticateUserWithMicrosoft(final CallbackContext callbackContext, final JSONArray args){
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String locale = args.getString(0);
OAuthProvider.Builder provider = OAuthProvider.newBuilder("microsoft.com");
if(locale != null){
provider.addCustomParameter("locale", locale);
provider.addCustomParameter("prompt", "consent");
}
Task<AuthResult> pending = FirebaseAuth.getInstance().getPendingAuthResult();
if (pending != null) {
callbackContext.error("Auth result is already pending");
pending
.addOnSuccessListener(new AuthResultOnSuccessListener())
.addOnFailureListener(new AuthResultOnFailureListener());
} else {
String id = FirebasePlugin.instance.saveAuthProvider(provider.build());;
JSONObject returnResults = new JSONObject();
returnResults.put("instantVerification", true);
returnResults.put("id", id);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, returnResults));
}
} catch (Exception e) {
handleExceptionWithContext(e, callbackContext);
}
}
});
}

public void signInUserWithCustomToken(final CallbackContext callbackContext, final JSONArray args){
cordova.getThreadPool().execute(new Runnable() {
public void run() {
Expand Down
1 change: 1 addition & 0 deletions src/ios/FirebasePlugin.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
- (void)signInUserAnonymously:(CDVInvokedUrlCommand*)command;
- (void)authenticateUserWithGoogle:(CDVInvokedUrlCommand*)command;
- (void)authenticateUserWithApple:(CDVInvokedUrlCommand*)command;
- (void)authenticateUserWithMicrosoft:(CDVInvokedUrlCommand*)command;
- (void)signInWithCredential:(CDVInvokedUrlCommand*)command;
- (void)linkUserWithCredential:(CDVInvokedUrlCommand*)command;
- (void)reauthenticateWithCredential:(CDVInvokedUrlCommand*)command;
Expand Down
27 changes: 26 additions & 1 deletion src/ios/FirebasePlugin.m
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
@import FirebaseAnalytics;
@import FirebaseRemoteConfig;
@import FirebasePerformance;
@import FirebaseCore;
@import FirebaseAuth;
@import FirebaseFunctions;
@import UserNotifications;
Expand Down Expand Up @@ -41,6 +42,7 @@ @implementation FirebasePlugin
static NSMutableDictionary* firestoreListeners;
static NSString* currentInstallationId;
static NSMutableDictionary* traces;
static FIROAuthProvider* oauthProvider;


+ (FirebasePlugin*) firebasePlugin {
Expand Down Expand Up @@ -711,7 +713,6 @@ - (void)authenticateUserWithEmailAndPassword:(CDVInvokedUrlCommand*)command {
NSString* password = [command.arguments objectAtIndex:1];
FIRAuthCredential* authCredential = [FIREmailAuthProvider credentialWithEmail:email password:password];
NSNumber* key = [self saveAuthCredential:authCredential];

NSMutableDictionary* result = [[NSMutableDictionary alloc] init];
[result setValue:@"true" forKey:@"instantVerification"];
[result setValue:key forKey:@"id"];
Expand Down Expand Up @@ -811,6 +812,30 @@ - (void)authenticateUserWithApple:(CDVInvokedUrlCommand*)command{
}
}

- (void)authenticateUserWithMicrosoft:(CDVInvokedUrlCommand*)command{
@try {
oauthProvider = [FIROAuthProvider providerWithProviderID:@"microsoft.com"];
[oauthProvider setCustomParameters:@{@"prompt": @"consent"}];
[oauthProvider getCredentialWithUIDelegate:nil
completion:^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) {
if (error) {
NSLog(@"Error: %@ %@", error, [error userInfo]);
@throw([NSException exceptionWithName:@"Error" reason:error.localizedDescription userInfo:nil]);
}
if (credential) {
NSNumber* key = [self saveAuthCredential:credential];
NSMutableDictionary* result = [[NSMutableDictionary alloc] init];
[result setValue:@"true" forKey:@"instantVerification"];
[result setValue:key forKey:@"id"];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
}];
}@catch (NSException *exception) {
[self handlePluginExceptionWithContext:exception :command];
}
}

- (void)signInWithCredential:(CDVInvokedUrlCommand*)command {
@try {
FIRAuthCredential* credential = [self obtainAuthCredential:[command.arguments objectAtIndex:0] command:command];
Expand Down
9 changes: 7 additions & 2 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,11 +198,16 @@ export interface FirebasePlugin {
): void
authenticateUserWithGoogle(
clientId: string,
success?: () => void,
success?: (credential:object) => void,
error?: (err: string) => void
): void
authenticateUserWithApple(
success?: () => void,
success?: (credential:object) => void,
error?: (err: string) => void,
locale?: string,
): void
authenticateUserWithMicrosoft(
success?: (credential:object) => void,
error?: (err: string) => void,
locale?: string,
): void
Expand Down
4 changes: 4 additions & 0 deletions www/firebase.js
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,10 @@ exports.authenticateUserWithApple = function (success, error, locale) {
exec(success, error, "FirebasePlugin", "authenticateUserWithApple", [locale]);
};

exports.authenticateUserWithMicrosoft = function (success, error, locale) {
exec(success, error, "FirebasePlugin", "authenticateUserWithMicrosoft", [locale]);
};

exports.signInWithCredential = function (credential, success, error) {
if(typeof credential !== 'object') return error("'credential' must be an object");
exec(success, error, "FirebasePlugin", "signInWithCredential", [credential]);
Expand Down

0 comments on commit 20a6284

Please sign in to comment.