I am working on developing a custom extension for MIT App Inventor that integrates OAuth authentication. I wants to implement OAuth to allow users to easily log in using external providers (like Google) within their App Inventor project. However, I'm facing challenges in managing the OAuth callback within the context of MIT App Inventor's component activities.
My code
import com.google.appinventor.components.annotations.*;
import com.google.appinventor.components.runtime.*;
import com.google.appinventor.components.common.ComponentCategory;
import android.content.Context;
import android.util.Log;
import android.app.Activity;
import androidx.activity.ComponentActivity;
public class Newkotjav extends AndroidNonvisibleComponent {
private final Context context;
private final KotlinHelper kotlinHelper;
private ComponentContainer container;
public Newkotjav(ComponentContainer container) {
super(container.$form());
this.container = container;
this.context = container.$context();
this.kotlinHelper = new KotlinHelper(context);
}
@SimpleFunction(description = "Create a Google OAuth session.")
public void CreateGoogleOAuthSession(String successUrl, String failureUrl) {
ComponentActivity activity = (ComponentActivity) container.$context(); // Is its ok?
kotlinHelper.createGoogleOAuthSession(activity, successUrl, failureUrl, new ResponseHandler() {
@Override
public void onSuccess(String result) {
OAuthSessionCreated(result);
}
@Override
public void onFailure(String error) {
OAuthSessionFailed(error);
}
});
}
@SimpleEvent(description = "Fired when the Google OAuth session is successfully created.")
public void OAuthSessionCreated(String sessionDetails) {
EventDispatcher.dispatchEvent(this, "OAuthSessionCreated", sessionDetails);
}
@SimpleEvent(description = "Fired when the Google OAuth session creation fails.")
public void OAuthSessionFailed(String error) {
EventDispatcher.dispatchEvent(this, "OAuthSessionFailed", error);
}
}
Kotlin Helper
fun createGoogleOAuthSession(activity: ComponentActivity, successUrl: String, failureUrl: String, handler: ResponseHandler) {
CoroutineScope(Dispatchers.IO).launch {
try {
val result = account.createOAuth2Session(
activity = activity, // Using avtivity
provider = OAuthProvider.GOOGLE,
success = successUrl,
failure = failureUrl,
scopes = listOf("profile", "email")
)
withContext(Dispatchers.Main) {
handler.onSuccess(result.toString())
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
handler.onFailure(e.message ?: "Failed to create OAuth session")
}
}
}
}