Skip to content

Commit

Permalink
fix: implement base of each provider
Browse files Browse the repository at this point in the history
  • Loading branch information
riderx committed Sep 12, 2024
1 parent 7e7ba95 commit 0e51109
Show file tree
Hide file tree
Showing 12 changed files with 979 additions and 34 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
package ee.forgr.capacitor.social.login;

import android.content.Intent;
import androidx.activity.result.ActivityResult;
import com.getcapacitor.JSObject;
import com.getcapacitor.PluginCall;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import net.openid.appauth.*;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class AppleProvider {
private static final String APPLE_AUTHORIZATION_ENDPOINT = "https://appleid.apple.com/auth/authorize";
private static final String APPLE_TOKEN_ENDPOINT = "https://appleid.apple.com/auth/token";

private AuthorizationService authService;
private String clientId;
private String redirectUri;

public void initialize(String clientId) {
this.clientId = clientId;
this.authService = new AuthorizationService(getActivity());
}

public void login(PluginCall call, JSObject payload) {
String[] scopes = payload.getArrayString("scopes");
String redirectUri = payload.getString("redirectURI");
String nonce = payload.getString("nonce");
String state = payload.getString("state");

this.redirectUri = redirectUri;

AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder(
new AuthorizationServiceConfiguration(
Uri.parse(APPLE_AUTHORIZATION_ENDPOINT),
Uri.parse(APPLE_TOKEN_ENDPOINT)
),
clientId,
ResponseTypeValues.CODE,
Uri.parse(redirectUri)
).setScopes(scopes);

if (nonce != null) {
authRequestBuilder.setNonce(nonce);
}

if (state != null) {
authRequestBuilder.setState(state);
}

AuthorizationRequest authRequest = authRequestBuilder.build();
Intent authIntent = authService.getAuthorizationRequestIntent(authRequest);
startActivityForResult(call, authIntent, 0);
}

@Override
protected void handleOnActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
AuthorizationResponse authResponse = AuthorizationResponse.fromIntent(data);
AuthorizationException authException = AuthorizationException.fromIntent(data);

if (authResponse != null) {
// Exchange authorization code for access token
TokenRequest tokenRequest = new TokenRequest.Builder(
new AuthorizationServiceConfiguration(
Uri.parse(APPLE_AUTHORIZATION_ENDPOINT),
Uri.parse(APPLE_TOKEN_ENDPOINT)
),
clientId
).setGrantType(GrantTypeValues.AUTHORIZATION_CODE)
.setRedirectUri(Uri.parse(redirectUri))
.setAuthorizationCode(authResponse.authorizationCode)
.build();

authService.performTokenRequest(tokenRequest, new AuthorizationService.TokenResponseCallback() {
@Override
public void onTokenRequestCompleted(TokenResponse tokenResponse, AuthorizationException ex) {
if (tokenResponse != null) {
// Handle successful token response
String accessToken = tokenResponse.accessToken;
String idToken = tokenResponse.idToken;

// Parse ID token to get user information
JsonObject idTokenObject = JsonParser.parseString(new String(Base64.decode(idToken.split("\\.")[1], Base64.DEFAULT))).getAsJsonObject();
String userId = idTokenObject.get("sub").getAsString();
String email = idTokenObject.has("email") ? idTokenObject.get("email").getAsString() : null;
String givenName = idTokenObject.has("given_name") ? idTokenObject.get("given_name").getAsString() : null;
String familyName = idTokenObject.has("family_name") ? idTokenObject.get("family_name").getAsString() : null;

// Resolve the plugin call with the token and user information
JSObject response = new JSObject();
response.put("user", userId);
response.put("email", email);
response.put("givenName", givenName);
response.put("familyName", familyName);
response.put("identityToken", idToken);
response.put("authorizationCode", authResponse.authorizationCode);
savedCall.resolve(response);
} else {
// Handle token request failure
savedCall.reject("Error exchanging authorization code for access token: " + ex.getMessage());
}
}
});
} else if (authException != null) {
// Handle authorization failure
savedCall.reject("Error during authorization: " + authException.getMessage());
} else {
// Handle unknown error
savedCall.reject("Unknown error occurred.");
}
}
}

public void logout(PluginCall call) {
// Perform logout logic for Apple Sign-In
// Clear any stored user data or tokens
// ...

call.resolve();
}

public void getCurrentUser(PluginCall call) {
// Retrieve the currently logged-in user information
// ...

if (currentUser != null) {
JSObject response = new JSObject();
response.put("user", currentUser.userId);
response.put("email", currentUser.email);
response.put("givenName", currentUser.givenName);
response.put("familyName", currentUser.familyName);
response.put("identityToken", currentUser.identityToken);
call.resolve(response);
} else {
call.reject("No user currently logged in.");
}
}

public void refresh(PluginCall call) {
// Perform token refresh logic for Apple Sign-In
// ...

if (refreshedToken != null) {
JSObject response = new JSObject();
response.put("accessToken", refreshedToken);
call.resolve(response);
} else {
call.reject("Failed to refresh token.");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package ee.forgr.capacitor.social.login;

import android.content.Intent;
import androidx.activity.result.ActivityResult;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.getcapacitor.JSObject;
import com.getcapacitor.PluginCall;

import org.json.JSONException;

import java.util.Arrays;
import java.util.List;

public class FacebookProvider {
private CallbackManager callbackManager;
private PluginCall savedCall;

public void initialize(String facebookAppId) {
callbackManager = CallbackManager.Factory.create();

LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// Handle successful login
AccessToken accessToken = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest(accessToken, (object, response) -> {
try {
JSObject result = new JSObject();
result.put("accessToken", accessToken.getToken());
result.put("userId", object.getString("id"));
result.put("expires", accessToken.getExpires().getTime());
result.put("lastRefresh", accessToken.getLastRefresh().getTime());
result.put("applicationId", accessToken.getApplicationId());
result.put("declinedPermissions", accessToken.getDeclinedPermissions());
result.put("permissions", accessToken.getPermissions());

JSObject profile = new JSObject();
profile.put("fields", object.names());

JSObject response = new JSObject();
response.put("accessToken", result);
response.put("profile", profile);

savedCall.resolve(response);
} catch (JSONException e) {
savedCall.reject("Error parsing Facebook response: " + e.getMessage());
}
});

Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,picture.width(720).height(720)");
request.setParameters(parameters);
request.executeAsync();
}

@Override
public void onCancel() {
// Handle login cancellation
savedCall.reject("Facebook login cancelled.");
}

@Override
public void onError(FacebookException exception) {
// Handle login error
savedCall.reject("Error during Facebook login: " + exception.getMessage());
}
});
}

public void login(PluginCall call, JSObject payload) {
savedCall = call;
List<String> permissions = Arrays.asList(payload.getArrayString("permissions"));
LoginManager.getInstance().logInWithReadPermissions(getActivity(), permissions);
}

public void logout(PluginCall call) {
LoginManager.getInstance().logOut();
call.resolve();
}

public void getCurrentUser(PluginCall call) {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null && !accessToken.isExpired()) {
JSObject result = new JSObject();
result.put("accessToken", accessToken.getToken());
result.put("userId", accessToken.getUserId());
result.put("expires", accessToken.getExpires().getTime());
result.put("lastRefresh", accessToken.getLastRefresh().getTime());
result.put("applicationId", accessToken.getApplicationId());
result.put("declinedPermissions", accessToken.getDeclinedPermissions());
result.put("permissions", accessToken.getPermissions());

JSObject response = new JSObject();
response.put("accessToken", result);
response.put("profile", new JSObject());

call.resolve(response);
} else {
call.reject("No current Facebook user.");
}
}

public void refresh(PluginCall call) {
AccessToken.refreshCurrentAccessTokenAsync(new AccessToken.AccessTokenRefreshCallback() {
@Override
public void OnTokenRefreshed(AccessToken accessToken) {
if (accessToken != null) {
JSObject result = new JSObject();
result.put("accessToken", accessToken.getToken());
result.put("userId", accessToken.getUserId());
result.put("expires", accessToken.getExpires().getTime());
result.put("lastRefresh", accessToken.getLastRefresh().getTime());
result.put("applicationId", accessToken.getApplicationId());
result.put("declinedPermissions", accessToken.getDeclinedPermissions());
result.put("permissions", accessToken.getPermissions());

call.resolve(result);
} else {
call.reject("Failed to refresh Facebook access token.");
}
}

@Override
public void OnTokenRefreshFailed(FacebookException exception) {
call.reject("Error refreshing Facebook access token: " + exception.getMessage());
}
});
}

@Override
protected void handleOnActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
Loading

0 comments on commit 0e51109

Please sign in to comment.