OAuth2Manager.java 18.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
package com.bitstrips.imoji.monouser.oauth2;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.text.TextUtils;
import android.util.Base64;
import com.bitstrips.imoji.behaviour.BehaviourHelper;
import com.bitstrips.imoji.injection.ForApplication;
import com.bitstrips.imoji.monouser.api.TokenErrorResponse;
import com.bitstrips.imoji.monouser.controllers.UserLogoutController;
import com.bitstrips.imoji.monouser.models.AuthToken;
import com.bitstrips.imoji.monouser.models.AuthorizationRequest;
import com.bitstrips.imoji.monouser.models.OAuth2Constants;
import com.bitstrips.imoji.util.PreferenceUtils;
import com.bitstrips.imoji.util.WebUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Request.Builder;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import dagger.Lazy;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Inject;
import javax.inject.Singleton;

@Singleton
public class OAuth2Manager
{
  public static final String APP_SCHEME = "bitmojiapp";
  public static final Set<String> BITMOJI_AUTHORITIES = new HashSet() {};
  public static final Set<String> BITMOJI_FORCE_LOGOUT_ERRORS = new HashSet() {};
  public static final String HTTPS_SCHEME = "https";
  public static final String HTTP_SCHEME = "http";
  private final Gson a;
  private final BehaviourHelper b;
  private final PreferenceUtils c;
  private final Context d;
  private final OkHttpClient e;
  private final Lazy<UserLogoutController> f;
  private AuthorizationRequest g;
  private AtomicReference<AuthToken> h;
  private final AtomicBoolean i = new AtomicBoolean(false);
  
  @Inject
  public OAuth2Manager(@ForApplication Context paramContext, Gson paramGson, BehaviourHelper paramBehaviourHelper, PreferenceUtils paramPreferenceUtils, Lazy<UserLogoutController> paramLazy)
  {
    this.d = paramContext;
    this.a = paramGson;
    this.b = paramBehaviourHelper;
    this.c = paramPreferenceUtils;
    this.f = paramLazy;
    this.e = new OkHttpClient();
    this.h = new AtomicReference(null);
  }
  
  @Nullable
  private Request a(@NonNull RequestBody paramRequestBody, @NonNull String paramString)
  {
    boolean bool = this.b.isStagingEndpoint();
    String str = String.format("%s:%s", new Object[] { OAuth2Constants.getClientId(bool), OAuth2Constants.getClientSecret(bool) });
    try
    {
      str = Base64.encodeToString(str.getBytes("UTF-8"), 2);
      return new Request.Builder().header("Content-Type", "application/x-www-form-urlencoded").header("Authorization", String.format("Basic %s", new Object[] { str })).header("Bitmoji-User-Agent", WebUtils.getBitmojiUserAgent(this.d)).url(String.format("%s%s", new Object[] { this.b.getAccountsEndpoint(), paramString })).post(paramRequestBody).build();
    }
    catch (UnsupportedEncodingException paramRequestBody) {}
    return null;
  }
  
  @Nullable
  private Request a(boolean paramBoolean, @Nullable AuthToken paramAuthToken)
  {
    if (!b(paramAuthToken)) {}
    while (!b(paramBoolean, paramAuthToken)) {
      return null;
    }
    FormEncodingBuilder localFormEncodingBuilder = new FormEncodingBuilder();
    localFormEncodingBuilder.add("grant_type", "refresh_token");
    localFormEncodingBuilder.add("refresh_token", paramAuthToken.getRefreshToken());
    return a(localFormEncodingBuilder.build(), "/accounts/oauth2/token");
  }
  
  /* Error */
  @VisibleForTesting
  private void a()
  {
    // Byte code:
    //   0: aload_0
    //   1: monitorenter
    //   2: aload_0
    //   3: getfield 107	com/bitstrips/imoji/monouser/oauth2/OAuth2Manager:h	Ljava/util/concurrent/atomic/AtomicReference;
    //   6: invokevirtual 230	java/util/concurrent/atomic/AtomicReference:get	()Ljava/lang/Object;
    //   9: ifnonnull +17 -> 26
    //   12: aload_0
    //   13: invokespecial 232	com/bitstrips/imoji/monouser/oauth2/OAuth2Manager:b	()Ljava/lang/String;
    //   16: astore_2
    //   17: aload_2
    //   18: invokestatic 238	android/text/TextUtils:isEmpty	(Ljava/lang/CharSequence;)Z
    //   21: istore_1
    //   22: iload_1
    //   23: ifeq +6 -> 29
    //   26: aload_0
    //   27: monitorexit
    //   28: return
    //   29: aload_0
    //   30: getfield 89	com/bitstrips/imoji/monouser/oauth2/OAuth2Manager:a	Lcom/google/gson/Gson;
    //   33: aload_2
    //   34: ldc -41
    //   36: invokevirtual 244	com/google/gson/Gson:fromJson	(Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Object;
    //   39: checkcast 215	com/bitstrips/imoji/monouser/models/AuthToken
    //   42: astore_2
    //   43: aload_2
    //   44: ifnull -18 -> 26
    //   47: aload_0
    //   48: getfield 107	com/bitstrips/imoji/monouser/oauth2/OAuth2Manager:h	Ljava/util/concurrent/atomic/AtomicReference;
    //   51: aload_2
    //   52: invokevirtual 247	java/util/concurrent/atomic/AtomicReference:set	(Ljava/lang/Object;)V
    //   55: goto -29 -> 26
    //   58: astore_2
    //   59: aload_0
    //   60: monitorexit
    //   61: aload_2
    //   62: athrow
    // Local variable table:
    //   start	length	slot	name	signature
    //   0	63	0	this	OAuth2Manager
    //   21	2	1	bool	boolean
    //   16	36	2	localObject1	Object
    //   58	4	2	localObject2	Object
    // Exception table:
    //   from	to	target	type
    //   2	22	58	finally
    //   29	43	58	finally
    //   47	55	58	finally
  }
  
  private void a(@Nullable AuthorizationRequest paramAuthorizationRequest)
  {
    this.g = paramAuthorizationRequest;
    this.c.putString(2131231282, this.a.toJson(this.g));
  }
  
  @VisibleForTesting
  private String b()
  {
    return this.c.getString(2131231283, null);
  }
  
  private static void b(Runnable paramRunnable)
  {
    new Handler(Looper.getMainLooper()).post(paramRunnable);
  }
  
  @VisibleForTesting
  static boolean b(@Nullable AuthToken paramAuthToken)
  {
    return (paramAuthToken != null) && (!TextUtils.isEmpty(paramAuthToken.getAccessToken())) && (!TextUtils.isEmpty(paramAuthToken.getRefreshToken())) && (TextUtils.equals(paramAuthToken.getTokenType(), "Bearer")) && (paramAuthToken.getExpiresIn() > 0L);
  }
  
  private static boolean b(boolean paramBoolean, @NonNull AuthToken paramAuthToken)
  {
    boolean bool = false;
    int j;
    if (System.currentTimeMillis() - paramAuthToken.getLastUpdated() >= Math.min(3600000.0D, paramAuthToken.getExpiresInMillis() / 2.0D))
    {
      j = 1;
      if (System.currentTimeMillis() < paramAuthToken.getLastUpdated() + paramAuthToken.getExpiresInMillis()) {
        break label75;
      }
    }
    label75:
    for (int k = 1;; k = 0)
    {
      if ((!paramBoolean) && (j == 0))
      {
        paramBoolean = bool;
        if (k == 0) {}
      }
      else
      {
        paramBoolean = true;
      }
      return paramBoolean;
      j = 0;
      break;
    }
  }
  
  private AuthorizationRequest c()
  {
    if (this.g == null) {}
    try
    {
      this.g = ((AuthorizationRequest)this.a.fromJson(this.c.getString(2131231282, null), AuthorizationRequest.class));
      return this.g;
    }
    catch (JsonSyntaxException localJsonSyntaxException)
    {
      for (;;) {}
    }
  }
  
  public static boolean hasSnapchatInstalled(@NonNull Context paramContext)
  {
    Intent localIntent = new Intent("android.intent.action.VIEW");
    localIntent.setData(Uri.parse("snapchat://"));
    paramContext = paramContext.getPackageManager();
    if (paramContext == null) {}
    do
    {
      return false;
      paramContext = paramContext.queryIntentActivities(localIntent, 0);
    } while ((paramContext == null) || (paramContext.size() <= 0));
    return true;
  }
  
  @VisibleForTesting
  final void a(@NonNull AuthToken paramAuthToken)
  {
    try
    {
      Object localObject = b();
      localObject = (AuthToken)this.a.fromJson((String)localObject, AuthToken.class);
      if ((b(paramAuthToken)) && ((localObject == null) || (((AuthToken)localObject).getLastUpdated() <= paramAuthToken.getLastUpdated())))
      {
        localObject = this.a.toJson(paramAuthToken);
        this.c.putString(2131231283, (String)localObject);
        this.h.set(paramAuthToken);
      }
      return;
    }
    finally {}
  }
  
  @VisibleForTesting
  final void a(@Nullable final OnOAuth2TokenRefreshCallback paramOnOAuth2TokenRefreshCallback, final boolean paramBoolean1, final boolean paramBoolean2, final boolean paramBoolean3)
  {
    if (paramOnOAuth2TokenRefreshCallback == null) {
      return;
    }
    this.i.set(false);
    b(new Runnable()
    {
      public final void run()
      {
        if (paramBoolean1)
        {
          paramOnOAuth2TokenRefreshCallback.onTokenRefreshSucceeded(paramBoolean2);
          return;
        }
        paramOnOAuth2TokenRefreshCallback.onTokenRefreshFailed(paramBoolean3);
      }
    });
  }
  
  @VisibleForTesting
  final void a(@Nullable Response paramResponse, @Nullable OnOAuth2TokenRefreshCallback paramOnOAuth2TokenRefreshCallback)
    throws IOException
  {
    if ((paramResponse != null) && (paramResponse.isSuccessful()) && (paramResponse.body() != null) && (paramResponse.body().charStream() != null)) {}
    for (AuthToken localAuthToken = (AuthToken)this.a.fromJson(paramResponse.body().charStream(), AuthToken.class); localAuthToken != null; localAuthToken = null)
    {
      if (TextUtils.isEmpty(localAuthToken.getRefreshToken())) {
        localAuthToken.setRefreshToken(getRefreshToken());
      }
      if (!b(localAuthToken)) {
        break;
      }
      localAuthToken.setLastUpdated(System.currentTimeMillis());
      a(localAuthToken);
      a(paramOnOAuth2TokenRefreshCallback, true, true, false);
      return;
    }
    if ((paramResponse != null) && (!paramResponse.isSuccessful()) && (paramResponse.code() == 400)) {}
    for (paramResponse = (TokenErrorResponse)this.a.fromJson(paramResponse.body().charStream(), TokenErrorResponse.class); (paramResponse != null) && (!TextUtils.isEmpty(paramResponse.getError())) && (BITMOJI_FORCE_LOGOUT_ERRORS.contains(paramResponse.getError().toLowerCase())); paramResponse = null)
    {
      ((UserLogoutController)this.f.get()).logout();
      a(paramOnOAuth2TokenRefreshCallback, false, false, true);
      return;
    }
    a(paramOnOAuth2TokenRefreshCallback, false, false, false);
  }
  
  public void asyncRefreshToken(boolean paramBoolean, @NonNull final OnOAuth2TokenRefreshCallback paramOnOAuth2TokenRefreshCallback)
  {
    if (this.i.getAndSet(true)) {
      return;
    }
    a();
    AuthToken localAuthToken = (AuthToken)this.h.get();
    Request localRequest = a(paramBoolean, localAuthToken);
    if (localRequest == null)
    {
      if ((localAuthToken != null) && (!b(paramBoolean, localAuthToken))) {}
      for (paramBoolean = true;; paramBoolean = false)
      {
        a(paramOnOAuth2TokenRefreshCallback, paramBoolean, false, false);
        return;
      }
    }
    this.e.newCall(localRequest).enqueue(new Callback()
    {
      public final void onFailure(Request paramAnonymousRequest, IOException paramAnonymousIOException)
      {
        OAuth2Manager.this.a(paramOnOAuth2TokenRefreshCallback, false, false, false);
      }
      
      public final void onResponse(Response paramAnonymousResponse)
        throws IOException
      {
        OAuth2Manager.this.a(paramAnonymousResponse, paramOnOAuth2TokenRefreshCallback);
      }
    });
  }
  
  public void clearToken()
  {
    this.h.set(null);
  }
  
  public void finishOAuthGrant(@Nullable Uri paramUri, @NonNull final OnOAuth2LoginCallback paramOnOAuth2LoginCallback)
  {
    AuthorizationRequest localAuthorizationRequest = c();
    if ((paramUri == null) || (TextUtils.isEmpty(paramUri.getQueryParameter("code"))) || (TextUtils.isEmpty(paramUri.getQueryParameter("state"))) || (localAuthorizationRequest == null) || (!TextUtils.equals(paramUri.getQueryParameter("state"), localAuthorizationRequest.getState())) || (TextUtils.isEmpty(localAuthorizationRequest.getRedirectUri())) || (TextUtils.isEmpty(localAuthorizationRequest.getCodeVerifier())))
    {
      paramOnOAuth2LoginCallback.onLoginFailed();
      return;
    }
    FormEncodingBuilder localFormEncodingBuilder = new FormEncodingBuilder();
    localFormEncodingBuilder.add("grant_type", "authorization_code");
    localFormEncodingBuilder.add("code", paramUri.getQueryParameter("code"));
    localFormEncodingBuilder.add("redirect_uri", localAuthorizationRequest.getRedirectUri());
    localFormEncodingBuilder.add("client_id", OAuth2Constants.getClientId(this.b.isStagingEndpoint()));
    localFormEncodingBuilder.add("code_verifier", localAuthorizationRequest.getCodeVerifier());
    paramUri = a(localFormEncodingBuilder.build(), "/accounts/oauth2/token");
    if (paramUri == null)
    {
      paramOnOAuth2LoginCallback.onLoginFailed();
      return;
    }
    this.e.newCall(paramUri).enqueue(new Callback()
    {
      public final void onFailure(Request paramAnonymousRequest, IOException paramAnonymousIOException)
      {
        OAuth2Manager.a(new Runnable()
        {
          public final void run()
          {
            OAuth2Manager.5.this.a.onLoginFailed();
          }
        });
      }
      
      public final void onResponse(Response paramAnonymousResponse)
        throws IOException
      {
        if ((paramAnonymousResponse != null) && (paramAnonymousResponse.isSuccessful()) && (paramAnonymousResponse.body() != null) && (paramAnonymousResponse.body().charStream() != null))
        {
          paramAnonymousResponse = (AuthToken)OAuth2Manager.a(OAuth2Manager.this).fromJson(paramAnonymousResponse.body().charStream(), AuthToken.class);
          if (OAuth2Manager.b(paramAnonymousResponse))
          {
            paramAnonymousResponse.setLastUpdated(System.currentTimeMillis());
            OAuth2Manager.this.a(paramAnonymousResponse);
            OAuth2Manager.b(OAuth2Manager.this);
            OAuth2Manager.a(new Runnable()
            {
              public final void run()
              {
                OAuth2Manager.5.this.a.onLoginSucceeded();
              }
            });
            return;
          }
        }
        OAuth2Manager.a(new Runnable()
        {
          public final void run()
          {
            OAuth2Manager.5.this.a.onLoginFailed();
          }
        });
      }
    });
  }
  
  public void forceRefreshToken(@NonNull OnOAuth2TokenRefreshCallback paramOnOAuth2TokenRefreshCallback)
  {
    asyncRefreshToken(true, paramOnOAuth2TokenRefreshCallback);
  }
  
  @Nullable
  public String getAccessToken()
  {
    a();
    AuthToken localAuthToken = (AuthToken)this.h.get();
    if (localAuthToken == null) {
      return null;
    }
    return localAuthToken.getAccessToken();
  }
  
  @Nullable
  public String getRefreshToken()
  {
    a();
    AuthToken localAuthToken = (AuthToken)this.h.get();
    if (localAuthToken == null) {
      return null;
    }
    return localAuthToken.getRefreshToken();
  }
  
  public boolean isOAuthResponse(Intent paramIntent)
  {
    if (paramIntent == null) {}
    Uri localUri;
    do
    {
      do
      {
        return false;
        localUri = paramIntent.getData();
        if (localUri == null) {
          return TextUtils.equals(paramIntent.getStringExtra("snapchat_action"), "oauth");
        }
        if ((!TextUtils.equals(localUri.getScheme(), "https")) && (!TextUtils.equals(localUri.getScheme(), "http"))) {
          break;
        }
      } while ((TextUtils.isEmpty(localUri.getAuthority())) || (!BITMOJI_AUTHORITIES.contains(localUri.getAuthority().toLowerCase())) || (!TextUtils.equals(localUri.getPath(), OAuth2Constants.OAUTH2_REDIRECT_URI_PATH)));
      return true;
    } while ((!TextUtils.equals(localUri.getScheme(), "bitmojiapp")) || (TextUtils.isEmpty(localUri.toString())) || (!localUri.toString().startsWith(OAuth2Constants.OAUTH2_REDIRECT_APP_SCHEME_URI)));
    return true;
  }
  
  public boolean isUserLoggedIn()
  {
    return !TextUtils.isEmpty(getAccessToken());
  }
  
  public void revokeToken()
  {
    a();
    Object localObject = (AuthToken)this.h.get();
    if (localObject == null) {}
    do
    {
      return;
      FormEncodingBuilder localFormEncodingBuilder = new FormEncodingBuilder();
      localFormEncodingBuilder.add("token", ((AuthToken)localObject).getRefreshToken());
      localObject = a(localFormEncodingBuilder.build(), "/accounts/oauth2/revoke");
    } while (localObject == null);
    this.e.newCall((Request)localObject).enqueue(new Callback()
    {
      public final void onFailure(Request paramAnonymousRequest, IOException paramAnonymousIOException) {}
      
      public final void onResponse(Response paramAnonymousResponse)
        throws IOException
      {}
    });
    clearToken();
  }
  
  public void startOAuthGrant(@NonNull Context paramContext)
  {
    if (c() != null) {}
    for (int j = 1;; j = 0)
    {
      Object localObject = AuthorizationRequestFactory.generateRequest(this.b.isStagingEndpoint());
      a((AuthorizationRequest)localObject);
      if ((!hasSnapchatInstalled(paramContext)) || (this.b.isWebLoginForced()) || (j != 0)) {
        break;
      }
      localObject = ((AuthorizationRequest)localObject).toUri("snapchat://bitmoji");
      try
      {
        Intent localIntent = new Intent("android.intent.action.VIEW");
        localIntent.addFlags(268435456);
        localIntent.setData((Uri)localObject);
        paramContext.startActivity(localIntent);
        return;
      }
      catch (Exception paramContext) {}
    }
    localObject = ((AuthorizationRequest)localObject).toUri(this.b.getAccountsEndpoint() + "/accounts");
    try
    {
      paramContext.startActivity(new Intent("android.intent.action.VIEW", (Uri)localObject));
      return;
    }
    catch (Exception paramContext) {}
  }
  
  public void syncRefreshToken(boolean paramBoolean)
  {
    a();
    Request localRequest = a(paramBoolean, (AuthToken)this.h.get());
    if (localRequest == null) {
      return;
    }
    try
    {
      a(this.e.newCall(localRequest).execute(), null);
      return;
    }
    catch (Exception localException) {}
  }
  
  public static abstract interface OnOAuth2LoginCallback
  {
    public abstract void onLoginFailed();
    
    public abstract void onLoginSucceeded();
  }
  
  public static abstract interface OnOAuth2TokenRefreshCallback
  {
    public abstract void onTokenRefreshFailed(boolean paramBoolean);
    
    public abstract void onTokenRefreshSucceeded(boolean paramBoolean);
  }
}


/* Location:              /home/merong/decompile/hackery-dex2jar.jar!/com/bitstrips/imoji/monouser/oauth2/OAuth2Manager.class
 * Java compiler version: 6 (50.0)
 * JD-Core Version:       0.7.1
 */