com.google.android.gms.auth.GoogleAuthUtil Java Examples

The following examples show how to use com.google.android.gms.auth.GoogleAuthUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Install.java    From Saiy-PS with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get the account type associated with the install location of the app
 *
 * @return the account type
 */
public static String getAccountType() {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "getAccountType");
    }

    switch (Global.installLocation) {

        case PLAYSTORE:
            if (DEBUG) {
                MyLog.i(CLS_NAME, "getAccountType PLAYSTORE");
            }
            return GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE;
        case AMAZON:
            if (DEBUG) {
                MyLog.i(CLS_NAME, "getAccountType AMAZON");
            }
            return "";
        default:
            return "";
    }
}
 
Example #2
Source File: TaskSyncAdapter.java    From SyncManagerAndroid-DemoGoogleTasks with MIT License 6 votes vote down vote up
private String getGoogleAuthToken() throws IOException {
	String googleUserName = PrefsUtil.retrieveGoogleTasksUser(mContext);
	
	String token = "";
	try {
		Log.d(TAG, "getGoogleAuthToken... "+googleUserName);
		token = GoogleAuthUtil.getTokenWithNotification(mContext,
				googleUserName, GoogleTaskApiService.SCOPE, null);
	} catch (UserRecoverableNotifiedException userNotifiedException) {
		// Notification has already been pushed.
		// Continue without token or stop background task.
	} catch (GoogleAuthException authEx) {
		// This is likely unrecoverable.
		Log.e(TAG,
				"Unrecoverable authentication exception: "
						+ authEx.getMessage(), authEx);
	}
	return token;
}
 
Example #3
Source File: MainActivity.java    From SyncManagerAndroid-DemoGoogleTasks with MIT License 6 votes vote down vote up
/**
 * Gets an authentication token from Google and handles any
 * GoogleAuthException that may occur.
 */
protected String fetchToken() throws IOException {
    try {
        return GoogleAuthUtil.getToken(MainActivity.this, mEmailText, mScope);
    } catch (UserRecoverableAuthException userRecoverableException) {
        // GooglePlayServices.apk is either old, disabled, or not present
        // so we need to show the user some UI in the activity to recover.
        //mActivity.handleException(userRecoverableException);
    	//Log.e(TAG, userRecoverableException.getMessage(), userRecoverableException);
    	
    	mException = userRecoverableException;
    } catch (GoogleAuthException fatalException) {
        // Some other type of unrecoverable exception has occurred.
        // Report and log the error as appropriate for your app.
    	Log.e(TAG, fatalException.getMessage(), fatalException);
    }
    return null;
}
 
Example #4
Source File: GoogleAccountCredential.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an OAuth 2.0 access token.
 *
 * <p>
 * Must be run from a background thread, not the main UI thread.
 * </p>
 */
public String getToken() throws IOException, GoogleAuthException {
  if (backOff != null) {
    backOff.reset();
  }

  while (true) {
    try {
      return GoogleAuthUtil.getToken(context, accountName, scope);
    } catch (IOException e) {
      // network or server error, so retry using back-off policy
      try {
        if (backOff == null || !BackOffUtils.next(sleeper, backOff)) {
          throw e;
        }
      } catch (InterruptedException e2) {
        // ignore
      }
    }
  }
}
 
Example #5
Source File: AccountUtils.java    From evercam-android with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Retrieves the user profile information in a manner supported by
 * Gingerbread devices.
 *
 * @param context the context from which to retrieve the user's email address
 *                and name
 * @return a list of the possible user's email address and name
 */

private static UserProfile getUserProfileOnGingerbreadDevice(Context context) {
    // Other that using Patterns (API level 8) this works on devices down to
    // API level 5
    final Matcher valid_email_address = Patterns.EMAIL_ADDRESS.matcher("");
    final Account[] accounts = AccountManager.get(context).getAccountsByType(GoogleAuthUtil
            .GOOGLE_ACCOUNT_TYPE);
    UserProfile user_profile = new UserProfile();
    // As far as I can tell, there is no way to get the real name or phone
    // number from the Google account
    for (Account account : accounts) {
        if (valid_email_address.reset(account.name).matches())
            user_profile.addPossibleEmail(account.name);
    }
    // Gets the phone number of the device is the device has one
    if (context.getPackageManager().hasSystemFeature(Context.TELEPHONY_SERVICE)) {
        final TelephonyManager telephony = (TelephonyManager) context.getSystemService
                (Context.TELEPHONY_SERVICE);
        user_profile.addPossiblePhoneNumber(telephony.getLine1Number());
    }

    return user_profile;
}
 
Example #6
Source File: MainActivity.java    From conference-central-android-app with GNU General Public License v2.0 6 votes vote down vote up
private void selectAccount() {
    Account[] accounts = Utils.getGoogleAccounts(this);
    int numOfAccount = accounts.length;
    switch (numOfAccount) {
        case 0:
            // No accounts registered, nothing to do.
            Toast.makeText(this, R.string.toast_no_google_accounts_registered,
                    Toast.LENGTH_LONG).show();
            break;
        case 1:
            mEmailAccount = accounts[0].name;
            performAuthCheck(mEmailAccount);
            break;
        default:
            // More than one Google Account is present, a chooser is necessary.
            // Invoke an {@code Intent} to allow the user to select a Google account.
            Intent accountSelector = AccountPicker.newChooseAccountIntent(null, null,
                    new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, false,
                    getString(R.string.select_account_for_access), null, null, null);
            startActivityForResult(accountSelector, ACTIVITY_RESULT_FROM_ACCOUNT_SELECTION);
    }
}
 
Example #7
Source File: GoogleAccountsService.java    From narrate-android with Apache License 2.0 6 votes vote down vote up
private static Account getAccount() throws MissingGoogleAccountException, PermissionsException {
    String accountName = Settings.getGoogleAccountName();

    if (ContextCompat.checkSelfPermission(GlobalApplication.getAppContext(), Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
        throw new PermissionsException(Manifest.permission.GET_ACCOUNTS);
    } else {

        AccountManager manager = AccountManager.get(GlobalApplication.getAppContext());
        Account[] accounts = manager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);

        for (Account acc: accounts) {
            if (acc.name.equals(accountName)) {
                return acc;
            }
        }

        throw new MissingGoogleAccountException("GoogleAccountsService");

    }
}
 
Example #8
Source File: MainActivity.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void getAuthToken() {
    // [START fcm_get_token]
    String accountName = getAccount();

    // Initialize the scope using the client ID you got from the Console.
    final String scope = "audience:server:client_id:"
            + "1262xxx48712-9qs6n32447mcj9dirtnkyrejt82saa52.apps.googleusercontent.com";

    String idToken = null;
    try {
        idToken = GoogleAuthUtil.getToken(this, accountName, scope);
    } catch (Exception e) {
        Log.w(TAG, "Exception while getting idToken: " + e);
    }
    // [END fcm_get_token]
}
 
Example #9
Source File: DriveSyncService.java    From narrate-android with Apache License 2.0 5 votes vote down vote up
public DriveSyncService() throws UserRecoverableAuthException {
    super(SyncService.GoogleDrive);

    try {
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        String token = GoogleAuthUtil.getToken(GlobalApplication.getAppContext(), Settings.getEmail(), "oauth2:" + DriveScopes.DRIVE_APPDATA);

        if (SettingsUtil.shouldRefreshGDriveToken()) {
            GoogleAuthUtil.clearToken(GlobalApplication.getAppContext(), token);
            token = GoogleAuthUtil.getToken(GlobalApplication.getAppContext(), Settings.getEmail(), "oauth2:" + DriveScopes.DRIVE_APPDATA);
            SettingsUtil.refreshGDriveToken();
        }

        if (BuildConfig.DEBUG)
            LogUtil.log(getClass().getSimpleName(), "Access Token: " + token);

        GoogleCredential credential = new GoogleCredential().setAccessToken(token);
        service = new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName("Narrate").build();

    } catch (UserRecoverableAuthException ue) {
        throw ue;
    } catch (Exception e) {
        LogUtil.log(getClass().getSimpleName(), "Exception in creation: " + e);
        if (!BuildConfig.DEBUG) Crashlytics.logException(e);
    }

    if (CLEAR_FOLDER_CONTENTS) {
        deleteEverything();
    }
}
 
Example #10
Source File: GoogleAccountCredential.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry)
    throws IOException {
  try {
    if (response.getStatusCode() == 401 && !received401) {
      received401 = true;
      GoogleAuthUtil.clearToken(context, token);
      return true;
    }
  } catch (GoogleAuthException e) {
    throw new GoogleAuthIOException(e);
  }
  return false;
}
 
Example #11
Source File: RNGoogleSigninModule.java    From google-signin with MIT License 5 votes vote down vote up
private void insertAccessTokenIntoUserProperties(RNGoogleSigninModule moduleInstance, WritableMap userProperties) throws IOException, GoogleAuthException {
    String mail = userProperties.getMap("user").getString("email");
    String token = GoogleAuthUtil.getToken(moduleInstance.getReactApplicationContext(),
            new Account(mail, "com.google"),
            scopesToString(userProperties.getArray("scopes")));

    userProperties.putString("accessToken", token);
}
 
Example #12
Source File: RNGoogleSigninModule.java    From google-signin with MIT License 5 votes vote down vote up
@Override
protected Void doInBackground(String... tokenToClear) {
    RNGoogleSigninModule moduleInstance = weakModuleRef.get();
    if (moduleInstance == null) {
        return null;
    }
    try {
        GoogleAuthUtil.clearToken(moduleInstance.getReactApplicationContext(), tokenToClear[0]);
        moduleInstance.getPromiseWrapper().resolve(null);
    } catch (Exception e) {
        moduleInstance.promiseWrapper.reject(MODULE_NAME, e);
    }
    return null;
}
 
Example #13
Source File: GoogleAuthHelper.java    From ribot-app-android with Apache License 2.0 5 votes vote down vote up
public String retrieveAuthToken(Account account)
        throws GoogleAuthException, IOException {

    String token = GoogleAuthUtil.getToken(mContext, account, SCOPE);
    // Token needs to be clear so we make sure next time we get a brand new one. Otherwise this
    // may return a token that has already been used by the API and because it's a one time
    // token it won't work.
    GoogleAuthUtil.clearToken(mContext, token);
    return token;
}
 
Example #14
Source File: GoogleOauth2.java    From edx-app-android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets an authentication token from Google and handles any
 * GoogleAuthException that may occur.
 */
protected String fetchToken() throws IOException {
    if ( activity == null )
        return null;
    try {
        logger.debug("Fetching google oauth2 token ...");
        return GoogleAuthUtil.getToken(activity, mEmail, mScope);
    } catch (UserRecoverableAuthException userRecoverableException) {
        // GooglePlayServices.apk is either old, disabled, or not present
        // so we need to show the user some UI in the activity to recover.
        logger.debug("User recoverable error occurred");
        logger.error(userRecoverableException);
        
        // Requesting an authorization code will always throw
          // UserRecoverableAuthException on the first call to GoogleAuthUtil.getToken
          // because the user must consent to offline access to their data.  After
          // consent is granted control is returned to your activity in onActivityResult
          // and the second call to GoogleAuthUtil.getToken will succeed.
        if (activity != null && userRecoverableException.getIntent() != null) {
            activity.startActivityForResult(userRecoverableException.getIntent(), REQUEST_AUTHORIZATION);
        }
    } catch (GoogleAuthException fatalException) {
        logger.warn("google auth error occurred");
        // Some other type of unrecoverable exception has occurred.
        // Report and log the error as appropriate for your app.
        logger.error(fatalException);
    }
    return null;
}
 
Example #15
Source File: LoginActivity.java    From platform-friends-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private String[] getAccountNames() {
    mAccountManager = AccountManager.get(this);
    Account[] accounts = mAccountManager.getAccountsByType(
            GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
    String[] names = new String[accounts.length];
    for (int i = 0; i < names.length; i++) {
        names[i] = accounts[i].name;
    }
    return names;
}
 
Example #16
Source File: GoogleSignUpActivity.java    From socialmediasignup with MIT License 4 votes vote down vote up
private void handleSignInResult(GoogleSignInResult result) {
    if (result == null) {
        handCancel(SocialMediaSignUp.SocialMediaType.GOOGLE_PLUS);
        return;
    }
    if (result.isSuccess() && result.getSignInAccount() != null) {
        final GoogleSignInAccount acct = result.getSignInAccount();
        final SocialMediaUser user = new SocialMediaUser();
        user.setUserId(acct.getId());
        user.setAccessToken(acct.getIdToken());
        user.setProfilePictureUrl(acct.getPhotoUrl() != null ? acct.getPhotoUrl().toString() : "");
        user.setEmail(acct.getEmail());
        user.setFullName(acct.getDisplayName());
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    if (acct.getAccount() == null) {
                        handleError(new RuntimeException("Account is null"));
                    } else {
                        String accessToken = GoogleAuthUtil.getToken(getApplicationContext(), acct.getAccount(), getAccessTokenScope());
                        user.setAccessToken(accessToken);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                handleSuccess(SocialMediaSignUp.SocialMediaType.GOOGLE_PLUS, user);
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    handleError(e);
                }
            }
        });
    } else {
        String errorMsg = result.getStatus().getStatusMessage();
        if (errorMsg == null) {
            handCancel(SocialMediaSignUp.SocialMediaType.GOOGLE_PLUS);
        } else {
            handleError(new Throwable(result.getStatus().getStatusMessage()));
        }
    }
}
 
Example #17
Source File: GoogleDriveTransport.java    From CameraV with GNU General Public License v3.0 4 votes vote down vote up
public void doAuth () throws OperationCanceledException, AuthenticatorException, IOException, UserRecoverableNotifiedException, GoogleAuthException
{
	
	Bundle bund = new Bundle();
	token = GoogleAuthUtil.getTokenWithNotification(InformaService.getInstance().getApplicationContext(), account.name, Models.ITransportStub.GoogleDrive.SCOPE,bund);
	
	if (bund.containsKey(AccountManager.KEY_AUTHTOKEN))	
		token = bund.getString(AccountManager.KEY_AUTHTOKEN);

	/**
	if (token != null)
		am.invalidateAuthToken(Models.ITransportStub.GoogleDrive.SCOPE, token);

	
	AccountManagerFuture<Bundle> response = am.getAuthToken(account, Models.ITransportStub.GoogleDrive.SCOPE, true, new AccountManagerCallback<Bundle> () {

		@Override
		public void run(AccountManagerFuture<Bundle> result) {
            try {
				token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN);
            	
			} catch (OperationCanceledException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (AuthenticatorException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
	}, null);
	
	Bundle b;
	b = response.getResult();
	token = b.getString(AccountManager.KEY_AUTHTOKEN);
		
				*/
	
}
 
Example #18
Source File: GoogleAccountsService.java    From narrate-android with Apache License 2.0 4 votes vote down vote up
public static boolean invalidateToken(String token) throws IOException, GoogleAuthException {
    GoogleAuthUtil.clearToken(GlobalApplication.getAppContext(), token);
    return true;
}
 
Example #19
Source File: AccountIdProvider.java    From 365browser with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a stable id for the account associated with the given email address.
 * If an account with the given email address is not installed on the device
 * then null is returned.
 *
 * This method will throw IllegalStateException if called on the main thread.
 *
 * @param accountName The email address of a Google account.
 */
public String getAccountId(String accountName) {
    try {
        return GoogleAuthUtil.getAccountId(ContextUtils.getApplicationContext(), accountName);
    } catch (IOException | GoogleAuthException ex) {
        Log.e("cr.AccountIdProvider", "AccountIdProvider.getAccountId", ex);
        return null;
    }
}
 
Example #20
Source File: AccountIdProvider.java    From AndroidChromium with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a stable id for the account associated with the given email address.
 * If an account with the given email address is not installed on the device
 * then null is returned.
 *
 * This method will throw IllegalStateException if called on the main thread.
 *
 * @param accountName The email address of a Google account.
 */
public String getAccountId(Context ctx, String accountName) {
    try {
        return GoogleAuthUtil.getAccountId(ctx, accountName);
    } catch (IOException | GoogleAuthException ex) {
        Log.e("cr.AccountIdProvider", "AccountIdProvider.getAccountId", ex);
        return null;
    }
}
 
Example #21
Source File: AccountIdProvider.java    From delion with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a stable id for the account associated with the given email address.
 * If an account with the given email address is not installed on the device
 * then null is returned.
 *
 * This method will throw IllegalStateException if called on the main thread.
 *
 * @param accountName The email address of a Google account.
 */
public String getAccountId(Context ctx, String accountName) {
    try {
        return GoogleAuthUtil.getAccountId(ctx, accountName);
    } catch (IOException | GoogleAuthException ex) {
        Log.e("cr.AccountIdProvider", "AccountIdProvider.getAccountId", ex);
        return null;
    }
}
 
Example #22
Source File: Utils.java    From conference-central-android-app with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns the {@code Array} of Google Accounts, if any. Return value can be an empty array
 * (if no such account exists) but never <code>null</code>.
 *
 * @param context
 * @return
 */
public static Account[] getGoogleAccounts(Context context) {
    AccountManager am = AccountManager.get(context);
    return am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
}
 
Example #23
Source File: GoogleAccountsService.java    From narrate-android with Apache License 2.0 2 votes vote down vote up
/**
 * This method is used to retrieve an Oauth2 token to authenticate with Google's REST APIs.
 * For some reason, using Google Play Service's
 *
 * @param scope This is the Authorization scope that defines the permissions for the Oauth token.
 *              For more info on the scopes for Google Drive, see:
 *              https://developers.google.com/drive/v3/web/about-auth
 *
 * @return Oauth2 token that can be used as a Bearer to authenticate with Google's REST APIs
 */
public static String getAuthToken(String scope) throws MissingGoogleAccountException, PermissionsException, IOException, GoogleAuthException {
    Account acc = getAccount();
    String token = GoogleAuthUtil.getToken(GlobalApplication.getAppContext(), acc, "oauth2:" + scope);
    return token;
}