UserUtils.java revision 5f9dbc1d2645f20ce883c11f6b2511503cecf8ce
1/*
2 * Copyright (C) 2014 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 */
16package com.android.providers.contacts.util;
17
18import com.android.providers.contacts.ContactsProvider2;
19
20import android.content.Context;
21import android.content.pm.UserInfo;
22import android.os.UserManager;
23import android.util.Log;
24
25public final class UserUtils {
26    public static final String TAG = ContactsProvider2.TAG;
27
28    public static final boolean VERBOSE_LOGGING = Log.isLoggable(TAG, Log.VERBOSE);
29
30    private UserUtils() {
31    }
32
33    private static UserManager getUserManager(Context context) {
34        return (UserManager) context.getSystemService(Context.USER_SERVICE);
35    }
36
37    public static int getCurrentUserHandle(Context context) {
38        return getUserManager(context).getUserHandle();
39    }
40
41    /**
42     * @return the user ID of the corp user that is linked to the current user, if any.
43     * If there's no such user or cross-user contacts access is disallowed by policy, returns -1.
44     *
45     * STOPSHIP: Have amith look at it.
46     */
47    public static int getCorpUserId(Context context) {
48        final UserManager um = getUserManager(context);
49        final int currentUser = um.getUserHandle();
50
51        // STOPSHIP Check the policy and make sure cross-user contacts lookup is allowed.
52
53        if (VERBOSE_LOGGING) {
54            Log.v(TAG, "getCorpUserId: current=" + currentUser);
55        }
56
57        // TODO: Skip if the current is not the primary user?
58
59        // Check each user.
60        for (UserInfo ui : um.getUsers()) {
61            if (!ui.isManagedProfile()) {
62                continue; // Not a managed user.
63            }
64            final UserInfo parent = um.getProfileParent(ui.id);
65            if (parent == null) {
66                continue; // No parent.
67            }
68            // Check if it's linked to the current user.
69            if (um.getProfileParent(ui.id).id == currentUser) {
70                if (VERBOSE_LOGGING) {
71                    Log.v(TAG, "Corp user=" + ui.id);
72                }
73                return ui.id;
74            }
75        }
76        if (VERBOSE_LOGGING) {
77            Log.v(TAG, "Corp user not found.");
78        }
79        return -1;
80    }
81}
82