Search in sources :

Example 1 with AccessToken

use of com.codename1.io.AccessToken in project CodenameOne by codenameone.

the class GoogleImpl method nativeLoginImpl.

private void nativeLoginImpl(final GoogleApiClient client) {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(client);
    AndroidNativeUtil.startActivityForResult(signInIntent, RC_SIGN_IN, new IntentResultListener() {

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
            if (requestCode == RC_SIGN_IN) {
                final GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                if (result.isSuccess()) {
                    // Signed in successfully, show authenticated UI.
                    GoogleSignInAccount acct = result.getSignInAccount();
                    String displayName = acct.getDisplayName();
                    String acctId = acct.getId();
                    String email = acct.getEmail();
                    String requestIdToken = acct.getIdToken();
                    Set<Scope> grantedScopes = acct.getGrantedScopes();
                    String code = acct.getServerAuthCode();
                    String scopeStr = scope;
                    System.out.println("Token is " + acct.getIdToken());
                    if (acct.getIdToken() == null && clientId != null && clientSecret != null) {
                        Log.p("Received null ID token even though clientId and clientSecret are set.");
                    }
                    // otherwise we'll set the token to null.
                    if (clientId != null && clientSecret != null && requestIdToken != null && code != null) {
                        ConnectionRequest req = new ConnectionRequest() {

                            @Override
                            protected void readResponse(InputStream input) throws IOException {
                                Map<String, Object> json = new JSONParser().parseJSON(new InputStreamReader(input, "UTF-8"));
                                if (json.containsKey("access_token")) {
                                    setAccessToken(new AccessToken((String) json.get("access_token"), null));
                                    Display.getInstance().callSerially(new Runnable() {

                                        @Override
                                        public void run() {
                                            callback.loginSuccessful();
                                        }
                                    });
                                } else {
                                    setAccessToken(new AccessToken(null, null));
                                    Log.p("Failed to retrieve the access token from the google auth server.  Login succeeded, but access token is null, so you won't be able to use it to retrieve additional information.");
                                    Log.p("Response was " + json);
                                    Display.getInstance().callSerially(new Runnable() {

                                        @Override
                                        public void run() {
                                            callback.loginSuccessful();
                                        }
                                    });
                                }
                            }
                        };
                        req.setUrl("https://www.googleapis.com/oauth2/v4/token");
                        req.addArgument("grant_type", "authorization_code");
                        // req.addArgument("client_id", "555462747934-iujpd5saj4pjpibo7c6r9tbjfef22rh1.apps.googleusercontent.com");
                        req.addArgument("client_id", clientId);
                        // req.addArgument("client_secret", "650YqplrnAI0KXb9LMUnVNnx");
                        req.addArgument("client_secret", clientSecret);
                        req.addArgument("redirect_uri", "");
                        req.addArgument("code", code);
                        req.addArgument("id_token", requestIdToken);
                        req.setPost(true);
                        req.setReadResponseForErrors(true);
                        NetworkManager.getInstance().addToQueue(req);
                    } else {
                        setAccessToken(new AccessToken(null, null));
                        Log.p("The access token was set to null because one of clientId, clientSecret, requestIdToken, or auth were null");
                        Log.p("The login succeeded, but you won't be able to make any requests to Google's REST apis using the login token.");
                        Log.p("In order to obtain a token that can be used with Google's REST APIs, you need to set the clientId, and clientSecret of" + "the GoogleConnect instance to valid OAuth2.0 Client IDs for Web Clients.");
                        Log.p("See https://console.developers.google.com/apis/credentials");
                        Log.p("You can get the OAuth2.0 client ID for this project in your google-services.json file in the oauth_client section");
                        Display.getInstance().callSerially(new Runnable() {

                            @Override
                            public void run() {
                                callback.loginSuccessful();
                            }
                        });
                    }
                } else {
                    if (callback != null) {
                        if (callback != null) {
                            Display.getInstance().callSerially(new Runnable() {

                                @Override
                                public void run() {
                                    callback.loginFailed(GooglePlayServicesUtil.getErrorString(result.getStatus().getStatusCode()));
                                }
                            });
                        }
                    }
                }
            }
        }
    });
}
Also used : Set(java.util.Set) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Intent(android.content.Intent) IOException(java.io.IOException) GoogleSignInResult(com.google.android.gms.auth.api.signin.GoogleSignInResult) ConnectionRequest(com.codename1.io.ConnectionRequest) GoogleSignInAccount(com.google.android.gms.auth.api.signin.GoogleSignInAccount) IntentResultListener(com.codename1.impl.android.IntentResultListener) AccessToken(com.codename1.io.AccessToken) JSONParser(com.codename1.io.JSONParser) Map(java.util.Map)

Example 2 with AccessToken

use of com.codename1.io.AccessToken in project CodenameOne by codenameone.

the class GoogleImpl method nativelogin.

@Override
public void nativelogin() {
    loginCompleted = false;
    nativeInterface.googleLogin(this);
    Display.getInstance().invokeAndBlock(new Runnable() {

        public void run() {
            while (!loginCompleted) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException ie) {
                }
            }
        }
    });
    if (callback != null) {
        if (nativeIsLoggedIn()) {
            this.setAccessToken(new AccessToken(nativeInterface.getGoogleToken(), null));
            callback.loginSuccessful();
        } else {
            callback.loginFailed(loginMessage);
        }
    }
}
Also used : AccessToken(com.codename1.io.AccessToken)

Example 3 with AccessToken

use of com.codename1.io.AccessToken in project CodenameOne by codenameone.

the class Oauth2 method handleURL.

private void handleURL(String url, WebBrowser web, final ActionListener al, final Form frm, final Form backToForm, final Dialog progress) {
    if ((url.startsWith(redirectURI))) {
        if (Display.getInstance().getCurrent() == progress) {
            progress.dispose();
        }
        web.stop();
        // remove the browser component.
        if (login != null) {
            login.removeAll();
            login.revalidate();
        }
        if (url.indexOf("code=") > -1) {
            Hashtable params = getParamsFromURL(url);
            ConnectionRequest req = new ConnectionRequest() {

                protected void readResponse(InputStream input) throws IOException {
                    byte[] tok = Util.readInputStream(input);
                    String t = new String(tok);
                    if (t.startsWith("{")) {
                        JSONParser p = new JSONParser();
                        Map map = p.parseJSON(new StringReader(t));
                        token = (String) map.get("access_token");
                        Object ex = map.get("expires_in");
                        if (ex == null) {
                            ex = map.get("expires");
                        }
                        if (ex != null) {
                            expires = ex.toString();
                        }
                    } else {
                        token = t.substring(t.indexOf("=") + 1, t.indexOf("&"));
                        int off = t.indexOf("expires=");
                        int start = 8;
                        if (off == -1) {
                            off = t.indexOf("expires_in=");
                            start = 11;
                        }
                        if (off > -1) {
                            int end = t.indexOf('&', off);
                            if (end < 0 || end < off) {
                                end = t.length();
                            }
                            expires = t.substring(off + start, end);
                        }
                    }
                    if (login != null) {
                        login.dispose();
                    }
                }

                protected void handleException(Exception err) {
                    if (backToForm != null) {
                        backToForm.showBack();
                    }
                    if (al != null) {
                        al.actionPerformed(new ActionEvent(err, ActionEvent.Type.Exception));
                    }
                }

                protected void postResponse() {
                    if (backToParent && backToForm != null) {
                        backToForm.showBack();
                    }
                    if (al != null) {
                        al.actionPerformed(new ActionEvent(new AccessToken(token, expires), ActionEvent.Type.Response));
                    }
                }
            };
            req.setUrl(tokenRequestURL);
            req.setPost(true);
            req.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            req.addArgument("client_id", clientId);
            req.addArgument("redirect_uri", redirectURI);
            req.addArgument("client_secret", clientSecret);
            req.addArgument("code", (String) params.get("code"));
            req.addArgument("grant_type", "authorization_code");
            NetworkManager.getInstance().addToQueue(req);
        } else if (url.indexOf("error_reason=") > -1) {
            Hashtable table = getParamsFromURL(url);
            String error = (String) table.get("error_reason");
            if (login != null) {
                login.dispose();
            }
            if (backToForm != null) {
                backToForm.showBack();
            }
            if (al != null) {
                al.actionPerformed(new ActionEvent(new IOException(error), ActionEvent.Type.Exception));
            }
        } else {
            boolean success = url.indexOf("#") > -1;
            if (success) {
                String accessToken = url.substring(url.indexOf("#") + 1);
                if (accessToken.indexOf("&") > 0) {
                    token = accessToken.substring(accessToken.indexOf("=") + 1, accessToken.indexOf("&"));
                } else {
                    token = accessToken.substring(accessToken.indexOf("=") + 1);
                }
                if (login != null) {
                    login.dispose();
                }
                if (backToParent && backToForm != null) {
                    backToForm.showBack();
                }
                if (al != null) {
                    al.actionPerformed(new ActionEvent(new AccessToken(token, expires), ActionEvent.Type.Response));
                }
            }
        }
    } else {
        if (frm != null && Display.getInstance().getCurrent() != frm) {
            progress.dispose();
            frm.show();
        }
    }
}
Also used : Hashtable(java.util.Hashtable) InputStream(java.io.InputStream) ActionEvent(com.codename1.ui.events.ActionEvent) IOException(java.io.IOException) IOException(java.io.IOException) StringReader(com.codename1.util.regex.StringReader) Map(java.util.Map)

Example 4 with AccessToken

use of com.codename1.io.AccessToken in project CodenameOne by codenameone.

the class Login method doLogin.

/**
 * Logs in the user.
 * If the service has a native login it will try to use that, otherwise an
 * Oauth2 web login will be used.
 */
public void doLogin() {
    if (isNativeLoginSupported()) {
        nativelogin();
    } else {
        if (oauth2URL == null) {
            System.out.println("No oauth2URL found Use setOauth2URL");
            return;
        }
        if (clientId == null) {
            System.out.println("No ClientId found Use setClientId");
            return;
        }
        if (redirectURI == null) {
            System.out.println("No redirectURI found Use setRedirectURI");
            return;
        }
        if (clientSecret == null) {
            System.out.println("No clientSecret found Use setClientSecret");
            return;
        }
        Oauth2 auth = createOauth2();
        auth.showAuthentication(new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                // success
                if (evt.getSource() instanceof AccessToken) {
                    AccessToken t = (AccessToken) evt.getSource();
                    setAccessToken(t);
                    if (callback != null) {
                        callback.loginSuccessful();
                    }
                    return;
                }
                if (evt.getSource() instanceof String) {
                    String t = (String) evt.getSource();
                    setAccessToken(new AccessToken(t, null));
                    if (callback != null) {
                        callback.loginSuccessful();
                    }
                    return;
                }
                if (evt.getSource() instanceof Exception) {
                    if (callback != null) {
                        Exception e = (Exception) evt.getSource();
                        Log.e(e);
                        callback.loginFailed(e.getMessage());
                    }
                }
            }
        });
    }
}
Also used : ActionListener(com.codename1.ui.events.ActionListener) ActionEvent(com.codename1.ui.events.ActionEvent) AccessToken(com.codename1.io.AccessToken) Oauth2(com.codename1.io.Oauth2) IOException(java.io.IOException)

Aggregations

AccessToken (com.codename1.io.AccessToken)3 IOException (java.io.IOException)3 ActionEvent (com.codename1.ui.events.ActionEvent)2 InputStream (java.io.InputStream)2 Map (java.util.Map)2 Intent (android.content.Intent)1 IntentResultListener (com.codename1.impl.android.IntentResultListener)1 ConnectionRequest (com.codename1.io.ConnectionRequest)1 JSONParser (com.codename1.io.JSONParser)1 Oauth2 (com.codename1.io.Oauth2)1 ActionListener (com.codename1.ui.events.ActionListener)1 StringReader (com.codename1.util.regex.StringReader)1 GoogleSignInAccount (com.google.android.gms.auth.api.signin.GoogleSignInAccount)1 GoogleSignInResult (com.google.android.gms.auth.api.signin.GoogleSignInResult)1 InputStreamReader (java.io.InputStreamReader)1 Hashtable (java.util.Hashtable)1 Set (java.util.Set)1