1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.car; 17 18 import android.annotation.NonNull; 19 import android.content.Context; 20 import android.content.pm.PackageManager; 21 22 import java.util.Arrays; 23 24 /** 25 * Helper for permissions checks. 26 */ 27 public final class PermissionHelper { 28 29 /** 30 * Checks if caller has the {@code android.Manifest.permission.DUMP} permission. 31 * 32 * @throws SecurityException if it doesn't. 33 */ checkHasDumpPermissionGranted(@onNull Context context, @NonNull String message)34 public static void checkHasDumpPermissionGranted(@NonNull Context context, 35 @NonNull String message) { 36 checkHasAtLeastOnePermissionGranted(context, message, android.Manifest.permission.DUMP); 37 } 38 39 /** 40 * Checks if caller has at least one of the give permissions. 41 * 42 * @throws SecurityException if it doesn't. 43 */ checkHasAtLeastOnePermissionGranted(@onNull Context context, @NonNull String message, @NonNull String...permissions)44 public static void checkHasAtLeastOnePermissionGranted(@NonNull Context context, 45 @NonNull String message, @NonNull String...permissions) { 46 if (!hasAtLeastOnePermissionGranted(context, permissions)) { 47 if (permissions.length == 1) { 48 throw new SecurityException("You need " + permissions[0] + " to: " + message); 49 } 50 throw new SecurityException("You need one of " + Arrays.toString(permissions) 51 + " to: " + message); 52 } 53 } 54 55 /** 56 * Returns whether the given {@code uids} has at least one of the give permissions. 57 */ hasAtLeastOnePermissionGranted(@onNull Context context, @NonNull String... permissions)58 public static boolean hasAtLeastOnePermissionGranted(@NonNull Context context, 59 @NonNull String... permissions) { 60 for (String permission : permissions) { 61 if (context.checkCallingOrSelfPermission(permission) 62 == PackageManager.PERMISSION_GRANTED) { 63 return true; 64 } 65 } 66 return false; 67 } 68 PermissionHelper()69 private PermissionHelper() { 70 throw new UnsupportedOperationException("provides only static methods"); 71 } 72 } 73