|
| 1 | +package com.travelaudience.nexus.proxy; |
| 2 | + |
| 3 | +import com.github.benmanes.caffeine.cache.Caffeine; |
| 4 | +import com.github.benmanes.caffeine.cache.LoadingCache; |
| 5 | +import com.google.api.client.auth.oauth2.Credential; |
| 6 | +import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; |
| 7 | +import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; |
| 8 | +import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; |
| 9 | +import com.google.api.client.http.HttpTransport; |
| 10 | +import com.google.api.client.http.javanet.NetHttpTransport; |
| 11 | +import com.google.api.client.json.JsonFactory; |
| 12 | +import com.google.api.client.json.jackson2.JacksonFactory; |
| 13 | +import com.google.api.client.util.store.DataStoreFactory; |
| 14 | +import com.google.api.client.util.store.MemoryDataStoreFactory; |
| 15 | +import com.google.api.services.cloudresourcemanager.CloudResourceManager; |
| 16 | +import com.google.api.services.cloudresourcemanager.model.Organization; |
| 17 | +import com.google.common.collect.ImmutableSet; |
| 18 | + |
| 19 | +import java.io.IOException; |
| 20 | +import java.io.UncheckedIOException; |
| 21 | +import java.util.List; |
| 22 | +import java.util.Set; |
| 23 | + |
| 24 | +import static com.google.api.services.cloudresourcemanager.CloudResourceManagerScopes.CLOUD_PLATFORM_READ_ONLY; |
| 25 | +import static com.google.api.services.oauth2.Oauth2Scopes.USERINFO_EMAIL; |
| 26 | +import static java.util.concurrent.TimeUnit.MILLISECONDS; |
| 27 | + |
| 28 | +/** |
| 29 | + * Wraps {@link GoogleAuthorizationCodeFlow} caching authorization results and providing unchecked methods. |
| 30 | + */ |
| 31 | +public class CachingGoogleAuthCodeFlow { |
| 32 | + private static final DataStoreFactory DATA_STORE_FACTORY = new MemoryDataStoreFactory(); |
| 33 | + private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); |
| 34 | + private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); |
| 35 | + private static final Set<String> SCOPES = ImmutableSet.of(CLOUD_PLATFORM_READ_ONLY, USERINFO_EMAIL); |
| 36 | + |
| 37 | + private final LoadingCache<String, Boolean> authCache; |
| 38 | + private final GoogleAuthorizationCodeFlow authFlow; |
| 39 | + private final String organizationId; |
| 40 | + private final String redirectUri; |
| 41 | + |
| 42 | + private CachingGoogleAuthCodeFlow(final int authCacheTtl, |
| 43 | + final String clientId, |
| 44 | + final String clientSecret, |
| 45 | + final String organizationId, |
| 46 | + final String redirectUri) throws IOException { |
| 47 | + this.authCache = Caffeine.newBuilder() |
| 48 | + .maximumSize(4096) |
| 49 | + .expireAfterWrite(authCacheTtl, MILLISECONDS) |
| 50 | + .build(k -> this.isOrganizationMember(k, true)); |
| 51 | + this.authFlow = new GoogleAuthorizationCodeFlow.Builder( |
| 52 | + HTTP_TRANSPORT, |
| 53 | + JSON_FACTORY, |
| 54 | + clientId, |
| 55 | + clientSecret, |
| 56 | + SCOPES |
| 57 | + ).setDataStoreFactory( |
| 58 | + DATA_STORE_FACTORY |
| 59 | + ).setAccessType( |
| 60 | + "offline" |
| 61 | + ).setApprovalPrompt( |
| 62 | + "force" |
| 63 | + ).build(); |
| 64 | + this.organizationId = organizationId; |
| 65 | + this.redirectUri = redirectUri; |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Creates a new instance of {@link CachingGoogleAuthCodeFlow}. |
| 70 | + * |
| 71 | + * @param authCacheTtl the amount of time (in ms) during which to cache the fact that a user is authorized. |
| 72 | + * @param clientId the application's client ID. |
| 73 | + * @param clientSecret the application's client secret. |
| 74 | + * @param organizationId the organization ID. |
| 75 | + * @param redirectUri the URL which to redirect users to in the end of the authentication flow. |
| 76 | + * @return a new instance of {@link CachingGoogleAuthCodeFlow}. |
| 77 | + */ |
| 78 | + public static final CachingGoogleAuthCodeFlow create(final int authCacheTtl, |
| 79 | + final String clientId, |
| 80 | + final String clientSecret, |
| 81 | + final String organizationId, |
| 82 | + final String redirectUri) { |
| 83 | + try { |
| 84 | + return new CachingGoogleAuthCodeFlow(authCacheTtl, clientId, clientSecret, organizationId, redirectUri); |
| 85 | + } catch (final IOException ex) { |
| 86 | + throw new UncheckedIOException(ex); |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + /** |
| 91 | + * Returns the full authorization code request URL (complete with the redirect URL). |
| 92 | + * |
| 93 | + * @return the full authorization code request URL (complete with the redirect URL). |
| 94 | + */ |
| 95 | + public final String buildAuthorizationUri() { |
| 96 | + return this.authFlow.newAuthorizationUrl().setRedirectUri(redirectUri).build(); |
| 97 | + } |
| 98 | + |
| 99 | + /** |
| 100 | + * Returns the principal authenticated by {@code token}. |
| 101 | + * |
| 102 | + * @param token an instance of {@link GoogleTokenResponse}. |
| 103 | + * @return the principal authenticated by {@code token}. |
| 104 | + */ |
| 105 | + public final String getPrincipal(final GoogleTokenResponse token) { |
| 106 | + try { |
| 107 | + return token.parseIdToken().getPayload().getEmail(); |
| 108 | + } catch (final IOException ex) { |
| 109 | + throw new UncheckedIOException(ex); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + /** |
| 114 | + * Returns whether a given user is a member of the organization. |
| 115 | + * |
| 116 | + * @param userId the user's ID (typically his organization email address). |
| 117 | + * @return whether a given user is a member of the organization. |
| 118 | + */ |
| 119 | + public final boolean isOrganizationMember(final String userId) { |
| 120 | + return isOrganizationMember(userId, false); |
| 121 | + } |
| 122 | + |
| 123 | + private final boolean isOrganizationMember(final String userId, |
| 124 | + final boolean forceCheck) { |
| 125 | + if (!forceCheck) { |
| 126 | + return this.authCache.get(userId); |
| 127 | + } |
| 128 | + |
| 129 | + final Credential credential = this.loadCredential(userId); |
| 130 | + |
| 131 | + if (credential == null) { |
| 132 | + return false; |
| 133 | + } |
| 134 | + |
| 135 | + final GoogleCredential googleCredential = new GoogleCredential().setAccessToken(credential.getAccessToken()); |
| 136 | + |
| 137 | + final CloudResourceManager crm = new CloudResourceManager.Builder( |
| 138 | + HTTP_TRANSPORT, |
| 139 | + JSON_FACTORY, |
| 140 | + googleCredential).setApplicationName(this.authFlow.getClientId()).build(); |
| 141 | + |
| 142 | + final List<Organization> organizations; |
| 143 | + |
| 144 | + try { |
| 145 | + organizations = crm.organizations().list().execute().getOrganizations(); |
| 146 | + } catch (final IOException ex) { |
| 147 | + throw new UncheckedIOException(ex); |
| 148 | + } |
| 149 | + |
| 150 | + return organizations != null |
| 151 | + && organizations.stream().anyMatch(org -> this.organizationId.equals(org.getOrganizationId())); |
| 152 | + } |
| 153 | + |
| 154 | + /** |
| 155 | + * Loads the credential for the given user ID from the credential store. |
| 156 | + * |
| 157 | + * @param userId the user's ID. |
| 158 | + * @return the credential found in the credential store for the given user ID or {@code null} if none is found. |
| 159 | + */ |
| 160 | + public final Credential loadCredential(final String userId) { |
| 161 | + try { |
| 162 | + return this.authFlow.loadCredential(userId); |
| 163 | + } catch (final IOException ex) { |
| 164 | + throw new UncheckedIOException(ex); |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + /** |
| 169 | + * Returns a {@link GoogleTokenResponse} corresponding to an authorization code token request based on the given |
| 170 | + * authorization code. |
| 171 | + * |
| 172 | + * @param authorizationCode the authorization code to use. |
| 173 | + * @return a {@link GoogleTokenResponse} corresponding to an authorization code token request based on the given |
| 174 | + * authorization code. |
| 175 | + */ |
| 176 | + public final GoogleTokenResponse requestToken(final String authorizationCode) { |
| 177 | + try { |
| 178 | + return this.authFlow.newTokenRequest(authorizationCode).setRedirectUri(this.redirectUri).execute(); |
| 179 | + } catch (final IOException ex) { |
| 180 | + throw new UncheckedIOException(ex); |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + /** |
| 185 | + * Stores the credential corresponding to the specified {@link GoogleTokenResponse}. |
| 186 | + * |
| 187 | + * @param token an instance of {@link GoogleTokenResponse}. |
| 188 | + * @return the {@link Credential} corresponding to the specified {@link GoogleTokenResponse}. |
| 189 | + */ |
| 190 | + public final Credential storeCredential(final GoogleTokenResponse token) { |
| 191 | + try { |
| 192 | + return this.authFlow.createAndStoreCredential(token, this.getPrincipal(token)); |
| 193 | + } catch (final IOException ex) { |
| 194 | + throw new UncheckedIOException(ex); |
| 195 | + } |
| 196 | + } |
| 197 | +} |
0 commit comments